text_a,text_b,Score the code computes cartesian product itertoolsproduct zip suggested for example inputs result for comparison result zip as see zip itertoolsizip discards additional items longer argument its variant itertoolsiziplongest replaces missing elements arbitrary value for example iterttoolsiziplongest returns,i found nice statement tutorial xy xy x lista listb now i understood statment traverse lista listb x value list a value listb but example two lists length will statement also give pairs one list longer i use different statement thanks advance,3 the example produce combinations items lista listb think writing x lista listb …,i found nice statement tutorial xy xy x lista listb now i understood statment traverse lista listb x value list a value listb but example two lists length will statement also give pairs one list longer i use different statement thanks advance,3 remember written string write spaces first sysstdoutwrite r lenoldstring sysstdoutwrite rprocessing newstring,running loop given set filesand monitoring purpose writes output files currently processed sysstdoutwriterprocessing j sysstdoutflush j filenames output script processing etcsysconfigrhnsourcesexamplewnslepcsbalsipvf problem carriage return r clear previous filename clearly previous filenames idea fix thisand make clear,3 did use encoding option pygmentize use actual encoding source file if defaults latin contain characters quoted,i use pygmentize save python script rtf file propoer colors depends keywords syntax unfortunatelly program substitute special characters ä ä™åºä‡ã³ strange symbols is option set proper code page alternatively tool proceed operation properly if answer question i automatically remove special characters python script,1 i would add generation counter class feedentrydbmodel name dbstringpropertyrequiredtrue generation dbintegerpropertyrequiredtrue def updatefeedoffset generation number response fetchfeedoffset number feeditems parsefeedresponse feedentriestoadd item feeditems feedentriestoaddappend feedentrykeynameitemid nameitemnamegenerationgeneration dbputfeedentriestoadd def deleteoldgeneration q dbgqlqueryselect from feedentry where generation generation dbdeletegeneration,i updating adding items feedwhich items datastore items time problem feed change items might deleted feed i code class feedentrydbmodel name dbstringpropertyrequiredtrue def updatefeedoffset number response fetchfeedoffset number feeditems parsefeedresponse feedentriestoadd item feeditems feedentriestoaddappend feedentrykeynameitemid nameitemname dbputfeedentriestoadd how i find items feed delete datastore i thought creating list itemsin datastore remove items i updated ones left ones delete seems rather slow ps all itemid unique feed item consistent,1 you tell read instruction get three chars time true v oread print v lenv break,i file containing sequence atgaagctaggcatattc i want simple python code divide sequence atg aag gct divide indices the final print output look like atg aag cta ggc ata ttc this i done far usrbinpython import string import sys filenamesysargv oopenfilename ioreadlines imapstringstripi i joini rangeleni print iii i getting output atg aag cta ggc ata ttc the first column correct second column i want,1 you proceeding without checking errors shock code fails way from description sounds like mymod null would consistent failed import one possible cause failed import reversepy posted syntax error,i problems using embedded python c per documentation whenever i try using imported modules i get unhandled exception xee pythoninclexe xc access violation reading location x the error occurs pyobjectgetattrstring method documentation much help i also tried using tutorials example ibm always get access violation the following example code one tutorials i seem get work wrong ccode one main file include pythonh int main pyobject strret mymod strfunc strargs char cstrret pyinitialize mymod pyimportimportmodulereverse strfunc pyobjectgetattrstringmymod rstring strargs pybuildvalues hello world strret pyevalcallobjectstrfunc strargs pyargparsestrret ampcstrret printfreversed string sn cstrret pyfinalize return python code file called reversepy folder def rstrings lens whilei si return i running xp machine using msvs python a bit context i trying embed small python script uses openopc fairly large cprogram would like transfer data two however i already fail proofofconcept test basic examples,1 check result pyimportimportmodule call it fails returns null that default current directory search path add pysyssetpath mymod pyimportimportmodulereverse add current directory module search path make example work,i problems using embedded python c per documentation whenever i try using imported modules i get unhandled exception xee pythoninclexe xc access violation reading location x the error occurs pyobjectgetattrstring method documentation much help i also tried using tutorials example ibm always get access violation the following example code one tutorials i seem get work wrong ccode one main file include pythonh int main pyobject strret mymod strfunc strargs char cstrret pyinitialize mymod pyimportimportmodulereverse strfunc pyobjectgetattrstringmymod rstring strargs pybuildvalues hello world strret pyevalcallobjectstrfunc strargs pyargparsestrret ampcstrret printfreversed string sn cstrret pyfinalize return python code file called reversepy folder def rstrings lens whilei si return i running xp machine using msvs python a bit context i trying embed small python script uses openopc fairly large cprogram would like transfer data two however i already fail proofofconcept test basic examples,3 apparently issue pythonsupport plain broken comes twisted plugins this message ubuntu matthias klose explains issue offers solution packaging twisted plugins pythonsupport broken design even python policy mentions explicitly use packaging helper packages sharing python namespace you use dhpython deprecated build dhpycentral using includelinks matthias klose,as followup how i write setuppy twistdtwisted plugin works setuptools distribute etc one make debian package twisted plugin assuming setuppy properly written using cdbspythoncentraldhpython work i much luck far the trick tools basically run python setuppy install root package whatever ends perhaps previous question properly answered question becomes moot anyone successfully packaged twisted plugin debian,2 k inputinput integers separated spaces try thelist inti ksplit sumthelist raise valueerrorthe user numbers summation large except valueerror printinput integers separated spaces sum greater,is possible also check sum digits list comprehension make another except sum exceeds k inputinput digits separated spaces try inti ksplit except valueerror printinput digits the main thing structure two except blocks keep simple possible make sure sum list,2 on unix import os collections import namedtuple ntuplediskusage namedtuple usage total used free def diskusagepath return disk usage statistics given path returned valus named tuple attributes total used free amount total used free space bytes st osstatvfspath free stfbavail stffrsize total stfblocks stffrsize used stfblocks stfbfree stffrsize return ntuplediskusagetotal used free usage diskusage usagetotal used free for windows might use psutil,i looking number free bytes hd trouble python i tried following import os stat osstatvfspath print statfbsize statfbavail but osx gives bytes tb would nice unfortunately really true what best way get figure,3 unix import os collections import namedtuple ntuplediskusage namedtuple usage total used free def diskusagepath return disk usage statistics given path returned valus named tuple attributes total used free amount total used free space bytes st osstatvfspath free stfbavail stffrsize total stfblocks stffrsize used stfblocks stfbfree stffrsize return ntuplediskusagetotal used free usage diskusage usagetotal used free edit also windows httpscodeactivestatecomrecipesdiskusageinuser edit also available python httpsdocspythonorglibraryshutilhtmlshutildiskusage,how i get actual filesize disk python actual size takes harddrive thanks,3 what pattern otherwise osstat gives date file here sample last mod date stats osstatfile lastmoddate timelocaltimestats,i using remove files disk def matchfilesdir pattern dirname subdirs files oswalkdir f files fendswithpattern yield ospathjoindirname f remove files current dir matching txt f matchfilesdn txt osremovef what i would remove files disk updated today list files today check update list,1 besides osstat could use ospathgetmtime ospathgetctime pro con discussed question you use datetimedatetimefromtimestamp convert timestamp returned datetime object whatever want in example i remove files modified today create list remaining files datetime import datetime timedelta today datetimenowdate remaining f matchfilesdn txt mtime datetimefromtimestampospathgetmtimefdate mtime today osremovef else remainingappendf,i using remove files disk def matchfilesdir pattern dirname subdirs files oswalkdir f files fendswithpattern yield ospathjoindirname f remove files current dir matching txt f matchfilesdn txt osremovef what i would remove files disk updated today list files today check update list,2 if add datetimeproperty autonowtrue record last modified time entity since update every item feed time finished times moment started anything date feed xavier generation counter good need something guaranteed increase refreshes never decrease refresh not sure docs i expect datetimeproperty bigger integerproperty the latter bit integer might size may datetimeproperty stores several integers a group post suggests maybe bytes opposed but remember adding extra property queries adding another index anyway difference size field diluted proportion overhead further k times bytes much even gmonth with either generation datetime necessarily delete data immediately your queries could filter dategeneration recent refresh meaning delete data immediately if feed parsing goes funny fails produce items produces might useful last refresh lying around backup depends entirely app whether worth,i updating adding items feedwhich items datastore items time problem feed change items might deleted feed i code class feedentrydbmodel name dbstringpropertyrequiredtrue def updatefeedoffset number response fetchfeedoffset number feeditems parsefeedresponse feedentriestoadd item feeditems feedentriestoaddappend feedentrykeynameitemid nameitemname dbputfeedentriestoadd how i find items feed delete datastore i thought creating list itemsin datastore remove items i updated ones left ones delete seems rather slow ps all itemid unique feed item consistent,1 could avoid recompiling regexp every file precompiled phrase phrases b b strphrasestripsplit precompiledappendbb recompilers tnsbb reignorecase input output openoutputw openinput data iread pattern regex precompiled data regexsubpattern data owritedata one file repeating many files reusing regexes disclaimer untested may contain typos update also simplify regexp little replacing various space characters suspect bug would want match currently,i large set large files set phrases need replaced file the business logic imposes several restrictions matching must caseinsensitive the whitespace tabs new lines regex cannot ignored my solution see bit slow side how could optimised terms io string replacement data openinputfileread openoutputfilew phrase phrases set words i talking b b strphrasestripsplit regex recompilers tnsbb reignorecase data regexsubbbdata owritedata update x speedup converting text lower case dropping reignorecase,3 btw i noticed forgot parserclose parserfeed it might buffering something close force finish,i extract information following web page python httpwwwhomefinancenlenglishinternationalinterestratesliborliborinterestratesgbpasp the download using urllibrequest seems ok surprisingly i parse html file htmlparser class parsing seems stop middle meta tags without giving rationales this code import urllibrequest htmlparser import htmlparser def downloadlibor htmlfile urllibrequesturlopenhttpwwwhomefinancenlenglishinternationalinterestratesliborliborinterestratesgbpasp return htmlfile class tmphtmlparserhtmlparser def initself selflibor selfstack selfproperstack superinit def handlestarttagself tag attrs printstarttag strtag printselfgetstarttagtext selfstackappendtag def handlestartendtagself tag attrs printstartendtag def unknowndeclself data printunknowndecl def handleendtagself tag printendtag strtag selfstackpop def buildproperstackwebpage dev tool return stack leading libor rate libor webpage webpage parser tmphtmlparser parserfeedwebpage name main webpage downloadlibor printdownload done html strwebpageread buildproperstackhtml exit,1 in python associative arrays called dictionaries a good way iterate dict use iteritems key value itemiteritems print key value if need values use itervalues value itemitervalues print value as learn python dictionaries take note difference iteritems itervalues returns iterator items values returns list array,i really new python i find information i associative array item item id item title python i want validate contents item i dont want use index name like title loop iterate entries item regardless meaning something like range lenitem print itema any ideas suggestions,3 you pass using btree data structure store phrases this fastest way timecomplexity n olog h n number characters input file h length longest word however python offer box implementation btree you also use hashtable dictionary replacement function speed things this easy implement words wish replace alphanumeric single words replacedata â populate replace data phrase phrases key value phrasestripsplit replacedatakeylower value def replacefuncmatchobj function replaces words key matchobjgrouplower replacedatahaskeykey return replacedatakey else return key original code flow data openinputfileread output resubazaz replacefunc data open outputfile w owriteoutput oclose,i large set large files set phrases need replaced file the business logic imposes several restrictions matching must caseinsensitive the whitespace tabs new lines regex cannot ignored my solution see bit slow side how could optimised terms io string replacement data openinputfileread openoutputfilew phrase phrases set words i talking b b strphrasestripsplit regex recompilers tnsbb reignorecase data regexsubbbdata owritedata update x speedup converting text lower case dropping reignorecase,1 this want see comprehensions details sii xrange lens,this similar i want breaking bit number individual fields this typical string i need break four equal parts i need append list new text file original string header i know split string separators spaces string continuous these could thought bit bit binary numbers text text file i brand new programing python please i need patient details generalizations do assume i know anything thank ralph,3 strings lists touples broken using indexing operator using operator inside indexing operator achieve fields try something like x part part part part x x x x,this similar i want breaking bit number individual fields this typical string i need break four equal parts i need append list new text file original string header i know split string separators spaces string continuous these could thought bit bit binary numbers text text file i brand new programing python please i need patient details generalizations do assume i know anything thank ralph,1 there three ways iterate dictionary item key item alternatively itemiterkeys itemkeys python print key itemkey item value itemitervalues itemvalues python print value item key value itemiteritems itemitems python print key value,i really new python i find information i associative array item item id item title python i want validate contents item i dont want use index name like title loop iterate entries item regardless meaning something like range lenitem print itema any ideas suggestions,3 use range builtin function the signature rangestart stop step this produces sequence yields numbers starting start ending stop reached excluding stop range range in python produces nonlist range object functions effectively like readonly list uses way less memory particularly large ranges,how produce following list range python,3 robert answer as i need append list new text file original string header n n joinsii xrange lens give nnnn thus putting byte separate line i understood question edit notes help understand a list see contains data case strings brackets the first item list retrieved mylist python string also object specific methods call so n representing carriage return object type string call method join list argument n joinmylist the elements list joined together string n element the result longer list string two strings added together thus n n joinmylist adds already string right part sum strings i hope clears things,this similar i want breaking bit number individual fields this typical string i need break four equal parts i need append list new text file original string header i know split string separators spaces string continuous these could thought bit bit binary numbers text text file i brand new programing python please i need patient details generalizations do assume i know anything thank ralph,2 use reversed function reversedrange it much meaningful update if want list btk pointed listreversedrange,how produce following list range python,3 if look documentation redirect several things pass function a model a view name a url in general i think better redirect view name rather url in case assuming urlspy entry looks something like urlr homeviewsindex i would instead use redirect like redirect homeviewsindex,i creating django project however i come across small hiccup my urlspy looks like urlr loginpnextloc homeviewslogin urlr logout homeviewslogout my viewspy home app follows def loginrequestnextloc requestmethod post form authenticationformrequestpost userauthauthenticateusernamerequestpost username passwordrequestpost password user none userisactive authloginrequest user return redirectnextloc else error this account disabled administrator contact administrator enabling said account else error the usernamepassword pair incorrect check credentials try else requestuserisauthenticated return redirectprofile form authenticationform error return rendertoresponse loginhtml form form error errorcontextinstancerequestcontextrequest def logoutrequest authlogoutrequest return redirect now i going login page opening expected after i submit form i get error says find module urls after digging around bit i noticed redirect actually translates httplocalhostlogin instead httplocalhost the happens logout ie tries opening url httplocalhostlogout instead httplocalhost basically page opened httplocalhostlogin redirect adds end current url voila i get url i expect httplocalhostlogin i cannot get redirect root site using redirect please help possible also explain cause irrational behavior django,1 for reference alternatives splitting strings equal length parts import refindallr res map join zipiters the zip method splitting sequence nlength groups documented work strings whose length evenly divisible n issue particular question if string length evenly divisible n could use itertoolsiziplongestiters fillvalue,this similar i want breaking bit number individual fields this typical string i need break four equal parts i need append list new text file original string header i know split string separators spaces string continuous these could thought bit bit binary numbers text text file i brand new programing python please i need patient details generalizations do assume i know anything thank ralph,1 i think python tornado great team following reasons tornado really ioloop happens come http implementation runs helpers this means comes everything need web development it also means find road need back end services help scale application tornado likely good use area i actually written back end services front end ones tornado coworker exact opposite experience frontend oriented finds nice work a bit offtopic also used template module outside tornado great success the code modular almost interdependence reusing components breeze you learn know well quickly it would take day figure it code clean unbelievably wellcommented decent documentation besides i able produce production service tornado ca week never seen the tornado source code antimagic it fast stable under load i know absolute blazing fast thing existence projects i used taking heavy load terms number concurrent users terms data transfer highvolume image uploads example completely rock solid terms stability b fast enough i consider scaling horizontally getting bigger hardware python extremely flexible adaptable i use python regularly web development using tornado things including django occasion however i also use things completely unrelated web services like sysadminautomation tasks reporting amp data munging example i write hadoop jobs python things standard library modules os sys shutil itertools collections etc make things blindingly fast build i use python anything environment whether output goes stream browser fat gui console it also fantastic community around really smart people also friendly i compare scala community comparison lots communities python easily favorite lot i became attached hip i polyglot i question i would like pose question python community member,i looking start google maps based web application my initial thoughts first phase focus frontend backend easy write prototype aid much possible development frontend there classic pages meebocom style interface javascript jquery meaning none static pages my eye caught cometstyle server push paradigm i really interested proof concepts do recommendations advantages disadvantages experiences working python tornado vs scala lift what advantages disadvantages areas web application might choice bring note this max developers big distributed changing team thanks,3 you actually getting stuff expect unicode case you think weird escaping due fact looking reprs strings printing unescaped values this lists displayed words u uuu u uuu u uuu w words print w this uses terminal encoding utilize interactively ñ€ð°ð· ð´ð²ð° ñ‚ñ€ð¸ u ñ€ð°ð· u uuu true don miss remark printing unicode strings normally going send screen file wire etc need manually encode correct encoding when use print python tries leverage terminal encoding terminal because generally know one rely interactive interpreter always encode right encoding explicitly otherwise in simple splittingonwhitespace approach might want use regex simply use unicodesplit method uñ€ð°ð· ð´ð²ð° ñ‚ñ€ð¸split u uuu u uuu u uuu your top bytestring example work basically assumes bytestrings ascii semantics using unicode strings allows get right semantics alphabet locale as much possible textual data always represented using unicode rather str,i trying split unicode string words simplistic like print refindallr uw ñ€ð°ð· ð´ð²ð° ñ‚ñ€ð¸ what i expect see ñ€ð°ð· ð´ð²ð° ñ‚ñ€ð¸ but i really get xd xd xd xd xdxbxd xd xd xd what i wrong edit if i use u front string print refindallr uw uñ€ð°ð· ð´ð²ð° ñ‚ñ€ð¸ i get u uuu u uuu u uuu edit aaaaand seems like i read docs first print refindallr uw uñ€ð°ð· ð´ð²ð° ñ‚ñ€ð¸encode utf will give ñ€ð°ð· just make sure though sound like proper way approaching,3 the error see terminal use latin encoding side note check encoding terminal assuming stdout shell python c import sys print sysstdoutencoding and printing utf encode string utf manually like uuudcueuueuc uduafubufcueuucudueu uecubuudfucueduuuffeuffe print sencode utf output å ‰æ›œæ—¥ã§ãƒ©ãƒ† ピクシー乱獲行きます å¸Œæœ›è€ å‹Ÿé›†ä¸­ã§ã™ï¼¾ï¼¾,i getting error file runpy line module print str unicodeencodeerror latin codec encode characters position ordinal range when trying simply print japanese text actually seems string looks like uudcueuueuc uduafubufcueuucudueu uecubuudfucueduuuffeuffe which comes json file how i print code url httpwwwblahcomjson try result simplejsonloadurlliburlopenurl except ioerror print cannot open url data error msg resultmsg str msgcharacter msgmessage print str reprstr u anys uudcueuueuc uduafubufcueuucudueu uecubuudfucueduuuffeuffe printsysstdoutencoding iso,2 you looking randomrandom import random helprandom randomrandom it use generator drand the drand family uses bit linear congruential generator whereas python random module uses superior mersenne twister algorithm if want exact output drand implement python uncomment next line using python x future import division class randobject def initself seed selfn seed def seedself seed selfn seed def srandself seed selfn seed xe def nextself selfn selfn amp return selfn def drandself return selfnext def lrandself return selfnext def mrandself n selfnext n amp n return n however output significantly inferior python standard random number generator the rand family functions declared obsolete svid,i converting c code python i wondering drand equivalent pythonexactly wrapper thanks lot,3 by default specified multiversion mode easyinstalling egg add entry easyinstallpth file sitepackages check see reference suds egg you also check python import path list places python search modules like import sys print syspath did try import suds python shell started easyinstalled suds that would explain behaviour saw the pth files read python startup egg directory zip file appeared syspath copying suds dir inside egg directory worked sitepackages already syspath so make sure restart python installing egg python import zip archives unzip archive sitepackages that leave unzipped directory import i think reads zip file inplace without extracting anywhere file system i seen problems packages work zipped eggs tried read data location filesystem i recommend always using alwaysunzip flag you given command lines used did specify option easyinstall that cause egg installed multiversion mode it syspath default need use pkgresourcesrequire function trying import,i impression python import supposed automatically unzip egg files sitepackages my installation seem want autounzip egg what i tried i used easyinstall install suds module copied egg file sitepackages python import import suds then i used alwaysunzip option easyinstall this time gave directory instead zip file python still import suds module i renamed directory suds still find finally i copied suds directory unzipped egg directory sitepackags python found surprise easyinstall what missing rufus,1 the universal installer build ssl default acctually stop find development libraries headers needs build ssl support unless explicitly use withoutssl libraries is,i existing plone installation created using unified installer the python packaged unified installer include ssl support how would i go adding ssl support existing installation do need rebuild python run bootstrap buildout get enabled or something simply added buildout egg i able create seperate python build ssl support trouble using python version run bootstrappy file bootstrappy line pythonpath assertionerror it looks like getting pythonpath setuptools changes need make am going wrong way any help appreciated thanks dr,1 what true alternate then exchange get desired effect,sometimes i need temporarily comment block headings testing purpose eg b c spop prints since indentation part python syntax i run code i got spop indentationerror unexpected indent i know dedenting code inside commented would make work i like preserve visual structure code instead dedenting indenting time are trick accomplish,3 i something similar problem today i wanted handled server trhough cron libs cron helpers end so created scheduling module attached init it best approach helps code single place execution related main app,i working web app using django i curious way schedule job run periodically basically i want run database make calculationsupdates automatic regular basis i seem find documentation does anyone know set to clarify i know i set cron job i curious feature django provides functionality i like people able deploy app without much config preferably zero i considered triggering actions retroactively simply checking job run since last time request sent site i hoping something bit cleaner,1 i think i got import tkinter import threading import matplotlibbackendsbackendtkagg root tkintertk class plotter def initselffig threadingthreadtargetselfplottingthreadargsfig tstart def plottingthreadselffig canvas matplotlibbackendsbackendtkaggfigurecanvastkaggfig masterroot canvasshow canvasgettkwidgetpacksidetkintertop filltkinterboth expand toolbar matplotlibbackendsbackendtkaggnavigationtoolbartkaggcanvas root toolbarupdate canvastkcanvaspacksidetkintertop filltkinterboth expand tkintermainloop name main import time fig matplotlibfigurefigurefigsize dpi figgcaplot fig matplotlibfigurefigurefigsize dpi figgcaplot shows fig fig like supposed plotterfig timesleep i still plot fig main thread figgcaclear figgcaplot figcanvasdraw the thing try create two instances plotter whole thing crashes that important application probably means i using tkinter wrong suggestionscorrections welcome,i writing program fits curves large sets xy coordinate data it often helpful watch progress algorithm plotting displaying iteration fitting progresses i using matplotlib plotting what i like create figure main thread pass child thread displays that way i access figure methods attributes main thread i plot calling figgcaplot draw calling figcanvasdraw i figure create interactive plotting window shows figure i pass right i using matplotlibpyplotshow display figure also displays figures may defined program is object oriented way create interactive window specific figure i looking solution rely unsupported interfaces matplotlib here post similar still answer question interactive figure oo matplotlib i never understood matplotlib always seems use current objects current figure current axes etc rather specific objects example matplotlibpyplotshowfig rather show i think i missing something if anyone could shed light matplotlib designed way i misunderstanding andor misusing would also appreciated here code import matplotlibpyplot import threading import time class plotter def initselffig threadingthreadtargetselfplottingthreadargsfig tstart def plottingthreadselffig this line shows fig and fig i want show fig only matplotlibpyplotshow name main fig matplotlibpyplotfigure fig matplotlibpyplotfigure plotterfig figgcaclear figgcaplot figcanvasdraw,1 unfortunately python useful html parsing standard library reasonable way parse html using third party module like lxmlhtml beautifulsoup this mean separate dependencythese modules free software want external dependency welcome bundle code make dependency code write,i made script beautifulsoup works fine readable i want redistribute day beautifulsoup external dependency i would like avoid specially considering windows use here code gets every usermap link given google maps user the marked lines ones using beautifulsoup coding utf import urllib beautifulsoup import beautifulsoup bs uid start shown true url httpmapsgooglecommapsuseruid uid ampptabampstart strstart source urlliburlopenurlread soup bssource maptables soupfindallidrecompile map table maptables line tablefindall maptitle mapid researchuid strlinegroup mapname research strlinegroupstrip print shown mapid mapname shown urlliburlretrieve httpmapsgooglecombrmapsmsmsid uid strmapid ampmsaampoutputkml mapname kml spannextspan strsource start else break as see three lines code using bsoup i programmer i lot difficulty trying use standard html xml parsing tools probably i tried wrong way i guess edit this question replacing three lines code script find way solve generic html parsing problems might any help much appreciated thanks reading,2 you could use codeinteractiveconsole socketserver attach python interactive shell socket development a simple example looks like import sys import socketserver code import interactiveconsole class interactiveserversocketserverbaserequesthandler def handleself file selfrequestmakefile shell shellfile try shellinteract except systemexit pass class shellinteractiveconsole def initself file selffile sysstdout file interactiveconsoleinitself return def writeself data selffilewritedata selffileflush def rawinputself prompt selfwriteprompt return selffilereadline name main host port server socketservertcpserverhost port interactiveserver serverserveforever once got running connect port another terminal thing you see working screenshot png the basics using interactiveconsole taken post i modified work socketserver another project i working,is way create second terminal calls curses functions operate rather existing terminal i work much faster i try things interactively i like able run interactive python interpreter one terminal see curses output another as calling initscr interactive window either fails pydev permanently takes away window refresh host spyder causes weird behavior console ipython is possible take different terminal using setupterm if i get different term string call,2 ospathcommonprefix ospathrelpath friends print ospathcommonprefix usrvarlog usrvarsecurity usrvar print ospathcommonprefix tmp usrvar no common prefix root common prefix you thus test whether common prefix one paths ie one paths common ancestor paths … … … commonprefix ospathcommonprefixlistofpaths commonprefix paths … you find relative paths relativepaths ospathrelpathpath commonprefix path paths you even handle two paths method test whether paths one ps depending paths look like might want perform normalization first useful situations one know whether always end paths relative relevant functions include ospathabspath ospathnormpath pps peter briggs mentioned comments simple approach described fail ospathcommonprefix usrvar usrvarlog usrvar even though usrvar common prefix paths forcing paths end calling commonprefix solves specific problem ppps bluenote mentioned adding slash solve general problem here followup question how circumvent fallacy pythons ospathcommonprefix pppps starting pythonâ pathlib module provides saner path manipulation environment i guess common prefix set paths obtained getting prefixes path purepathparents taking intersection parent sets selecting longest common prefix ppppps pythonâ introduced proper solution question ospathcommonpath returns valid path,say i two absolute paths i need check location referring one paths descendant if true i need find relative path descendant ancestor what good way implement python any library i benefit,3 ospathrelpath return relative filepath path either current directory optional start point ospath import relpath relpath usrvarlog usrvar log relpath usrvarlog usrvarsad log so relative path starts means second path descendant first path in python use purepathrelativeto python default jan pathlib import path path usrvarlog relativeto usrvarlog posixpath path usrvarlog relativeto usrvar posixpath log path usrvarlog relativeto etc traceback recent call last file stdin line module file usrlocalcellarpythonframeworkspythonframeworkversionslibpythonpathlibpy line relativeto formatstrself strformatted valueerror usrvarlog start etc,say i two absolute paths i need check location referring one paths descendant if true i need find relative path descendant ancestor what good way implement python any library i benefit,3 another option print ospathrelpath usrvarlog usrvar log,say i two absolute paths i need check location referring one paths descendant if true i need find relative path descendant ancestor what good way implement python any library i benefit,3 using superchildclass selfmethodargs allows walk method resolution order everyone last parent uses super call every class hierarchy exactly not super works newstyle classes using parentclassmethodself args calls one specific class it work involved multiple inheritance this article provides description issue clarifies lot issues people i agree conclusions provides good examples discussion,quick question pythonic inheritence difference idiom posted superchildclassselfmethodargs vs one python docs site parentclassmethodselfargs is one pythonic,2 if know nodes directly underneath p tag check equality nodes nodeagetparent nodebgetparent generally search recursively upwards hit p tag do separately node compare results equality getcontainingparanodea getcontainingparanodeb let ignore cornercase nested p tags else iterate p tags using text search regexes search matches pat recompileregex pat recompileregex para soupfindall p mat patsearchpara mat patsearchpara mat mat continue found match,how check elements beautifulsoup parse tree p tag,1 you if code downright needs something wrong design probably using explicitly passed dictionaries objects proper attributes but answer question directly use sysgetframe just aware might portable across python implementations ie work cpython def getobjectname return sysgetframeflocalsname x foo bar print getobject x def foo baz baf print getobject foo,i experienced tcl developer write procedures help along ie proc call putsvar prints value variable definitave format i know variable value set foo putsvar foo result foo i like kind thing python finding answer in tcl i use upvar command since i pass name variable i upvar see value i understand python upvar type mechanism introspection capaility i would think somewhat trivial i finding answer anywhere here think work def printvarvar valvar mechanism look level get value var print strvar strvalvar x hello printvarx xhello extended def foo hello world printvary foo yhello world,1 this could old shiboken running new pyside version could confirm using latest version shiboken if using ubuntu pythonpyside package ensure modules properly updated see httpbugspysideorgshowbugcgiid,i get importerror usrlibpymodulespythonpysideqtcoreso undefined symbol znshibokenenumcreateglobalenumepobjectpkcssptypeobject i import pyside after installing new version pyside version isolino is work around,1 calculation linear regression based sum various values could write efficient routine modifies sum window moves adding one point subtracting earlier one much efficient repeating process every time window shifts open rounding errors would need restart occasionally probably better equally spaced points precalculating x dependencies understand example detail unsure whether relevant guess assume slope nî£xy î£xî£y nî£x î£x squared httpeasycalculationcomstatisticslearnregressionphp evenly spaced data denominator fixed since shift x axis start window without changing gradient î£x numerator also fixed reason need concerned î£xy î£y latter trivial add subtract value former decreases î£y x weighting decreases increases ny assuming x xn n step suspect clear saying formula slope need completely recalculated step particularly step rename x values n without changing slope almost everything formula changes two terms depend y y drops window yn moves,i d array data wish extract spatial variation the standard way i wish pythonize perform moving linear regression data save gradient def nsslkdpphidp distance fitlen kdpzerosphidpshape dtypefloat myshapekdpshape swn rangemyshape print sweep swn rayn rangemyshape print ray rayn smallpolyfitdistanceaafitlen phidpswn rayn aafitlen xrangemyshapefitlen kdpswn rayn arraylistitertoolschainfitlensmall small fitlensmall return kdp this works well slow i need times i imagine overhead iterator arange line is implimentation moving fit numpyscipy,2 you change using style sheet this customizing qtreeview example style sheet reference qtreeviewbranchhassiblingsadjoinsitem borderimage urlvlinepng qtreeviewbranchhassiblingsadjoinsitem borderimage urlbranchmorepng qtreeviewbranchhaschildrenhassiblingsadjoinsitem borderimage urlbranchendpng qtreeviewbranchhaschildrenhassiblingsclosed qtreeviewbranchclosedhaschildrenhassiblings borderimage none image urlbranchclosedpng qtreeviewbranchopenhaschildrenhassiblings qtreeviewbranchopenhaschildrenhassiblings borderimage none image urlbranchopenpng png filenames images want use,i using qtreeview qitemdelegate reimplement paint routine however expandcollapse buttons siblingchild lines drawn automatically paint routine what drawing i control edit right qt draws qtreeview item order expand button checkbox rest treeitem stuff i want draw order checkbox expand button rest treeitem stuff the problem painting qitemdelegate right expand button,1 i good luck macports install macports already httpwwwmacportsorg install python via macports sudo port install python i typed command said end set default python installation if step run app different way install pygame sudo port install pygame run pygame app python mainpy,i tried install pygame via pip fails based google searches sounds like easyinstall also fails i also checked httpwwwpygameorgwikimaclioncompile solution incomplete i running python bundled lion suggestions appreciate help,3 this python cannot put ifelse inside something else like however pass arguments envcommand using dictionary valueparams jsonkey true kw target outtxt source intxt action function source target else kw envcommandkw,i single sconscript file top level directory i many subdirectories json files containing different keyvalue pair i one envcommand sconscript file i want called based value particular key what best way scons i thinking something like envcommand test valueparams jsonkey test true target outtxt source intxt action function source target else pass,1 short answer bit tautological urlparseurlparsehttpwwwexamplecomgeturl httpwwwexamplecom in example code hostname parsed path network location urlparseurlparsewwwexamplecomgo parseresultscheme netloc path wwwexamplecomgo params query fragment urlparseurlparsehttpwwwexamplecomgo parseresultscheme http netloc wwwexamplecom path go params query fragment,i like add http scheme name front given url string missing otherwise leave url alone i thought urlparse right way but whenever scheme i use get url i get instead scheme domain urlparseurlparse wwwexamplecom http tgeturl httpwwwexamplecom three how i convert url actually looks like httpwwwexamplecom two,2 osgetcwd get anywhere close returns current working directory usually one lauched main script would wrong using file if looking higher level function would probably use similar technique import os ospathdirnamefilefilerindexosextsep egg gives directory navigate osstartfiled,i built python package installs number external files i need able read files script gets installed package i see i use file inside script returns something like librarypythonsitepackagesmpyeggegginfoscripts i navigate files installed top level egg directory i looking standard way determine package installed,1 i used moving window functions somewhat old scikitstimeseries module success they implemented c i managed use situation moving window varies size sure need functionality httppytseriessourceforgenetlibmovingfuncshtml head downloads using python probably need compile extension i works fine httpsourceforgenetprojectspytseriesfilesscikitstimeseries iwe might able help clean example code bit i consider defining argumentsobjects lines defining small variables end row many hardtofollow parentheses,i d array data wish extract spatial variation the standard way i wish pythonize perform moving linear regression data save gradient def nsslkdpphidp distance fitlen kdpzerosphidpshape dtypefloat myshapekdpshape swn rangemyshape print sweep swn rayn rangemyshape print ray rayn smallpolyfitdistanceaafitlen phidpswn rayn aafitlen xrangemyshapefitlen kdpswn rayn arraylistitertoolschainfitlensmall small fitlensmall return kdp this works well slow i need times i imagine overhead iterator arange line is implimentation moving fit numpyscipy,1 i sure one hundred percent efficient try import sqlite db sqliteconnect sampledb c dbcursor newset cexecute select main tempvalue row c item row tempvalueappenditem newsetappendtempvalue tempvalue place back database hope enough guideline,i following sqlite database name sampledb table main fields id name description gender sample elements john fathead m i around rows want remove quotes field values db elements look like john fathead m what would efficient way thanks,1 you might want something like pkgutilgetdata function it read resources relative file package lives standard python package directory structure disk i think read resources zipped egg well though i used,i built python package installs number external files i need able read files script gets installed package i see i use file inside script returns something like librarypythonsitepackagesmpyeggegginfoscripts i navigate files installed top level egg directory i looking standard way determine package installed,1 starting python s flag suppresses automatic importing site module others signal readline actually built so use s flag main script import need make sure least call syssetdefaultencodingascii utf early,basically i cramming python embedded environment i compileconfigure system i surprised site module refuses load okay i need how i control modules python automatically imports notes static build things i copied working environment host static executable contents usrlibpython directory py files aka config files,1 use pyramidbeaker sessionauthenticationpolicy use pyramidauthenticationauthenticateduserid check logged if returns none,i creating webapp using pyramid beaker sessions i would like store user id requestsession userid info successful signing use checking user already signed userid requestsession user signed else user signed session expired the question safe rely sessions better andor safer use pyramid authenticateduserid remember forget pyramidsecurity,3 easiest path rerun unified installer specifying different target if finds libssl time set if try use withpython pick python ssl support and might well update alternatively install distribute new python try bootstrapping distribute give setuptools fewer bugs,i existing plone installation created using unified installer the python packaged unified installer include ssl support how would i go adding ssl support existing installation do need rebuild python run bootstrap buildout get enabled or something simply added buildout egg i able create seperate python build ssl support trouble using python version run bootstrappy file bootstrappy line pythonpath assertionerror it looks like getting pythonpath setuptools changes need make am going wrong way any help appreciated thanks dr,2 parse config usin php script save config vars file using json execute parser pytson using ossystem read json file python,lets say want make python config reader php configphp arr array config b config c config values arr array config b config c config values readconfigpy f open configphp r somehow get array turns pythons arr arr print arr arr config b config c config values print arr arr config b config c config values possible python,1 afaik way something along lines provide help user enters something like python controllerpy h take look argparse module hints incorporate script,my python script accepts number options following python controllerpy create python controllerpy destroy is anyways i get intellisense work commandline for instance typing following python controllerpy tabtab give following create description destroy description is good way portable way,1 for bash feature known bash completion other shells may similar functionality here official reference programmable completion it important keep mind feature shell python script invoking,my python script accepts number options following python controllerpy create python controllerpy destroy is anyways i get intellisense work commandline for instance typing following python controllerpy tabtab give following create description destroy description is good way portable way,1 you probably looking query string request authentication alternative you authenticate certain types requests passing required information querystring parameters instead using authorization http header this useful enabling direct thirdparty browser access private amazon s data without proxying request the idea construct presigned request encode url enduser browser retrieve additionally limit presigned request specifying expiration time,i post form calls amazon s service i direct browser upload amazon thus pass additional information amazon i know file uploaded filetype name signature references httpawsamazoncomarticles it large video file i want upload server first best knowledge rules using urllibopen pass additional variables amazon post request i working couple days success what would best way note i probably using uploadify plugin upload file thank,1 the method looking winfochildren,is possible get children tkinter widget get children children etc basically i want widgets within one entire window edit i found solution utilizing bryan line def allchildren wid list widwinfochildren item list itemwinfochildren listextenditemwinfochildren return list,2 if look matrix multiplication works x determine method calculate eg multiplying element j output matrix need multiply everything row lhs matrix everything column j rhs matrix single loop number elements row equal column j you also need cover every combination j dimensions output matrix loop columns nested inside loop rows the actual code course exercise implement,i idea even begin it needs loop multiply mtrixes example need help much appreciated i know dont want code ok it needs two square matrixes pretty sure pattern looking list thing abab abab abab abab,1 break before try write function multiplies matrices write one multiplies vectors if multiplying two matrices matter multiplying row column j every element ij resultant matrix,i idea even begin it needs loop multiply mtrixes example need help much appreciated i know dont want code ok it needs two square matrixes pretty sure pattern looking list thing abab abab abab abab,1 a b n ansn rangen ans rangen j rangen ansijsumaivbvj v rangen ans i think need simplify formula matrix multiplication we abc cij value ith row jth column answer for example c c note th position array often start instead cij dotproductrowiofacolumnjofbsumrowiofavcolumnjofbv v rangen because want whole answer c need work possible cij this means need try possible pairs ij loop rangen j rangen possible pair,i idea even begin it needs loop multiply mtrixes example need help much appreciated i know dont want code ok it needs two square matrixes pretty sure pattern looking list thing abab abab abab abab,1 in python use int builtin function convert string number int then use chr builtin convert bit integer inclusive range character chr the result chr simply written file opened binary mode filewrite method,i want take string convert actual binary filesimply writing string file would make either ascii file containing i would prefer python directly bash shell java c fine probably one time use thanks,3 there really straightforward way getting html source code webelement you use js i sure python bindings easily like java i sure must something similar javascriptexecutor class python webelement element driverfindelementbyidfoo string contents stringjavascriptexecutordriverexecutescriptreturn argumentsinnerhtml element,i using python bindings run selenium webdriver selenium import webdriver wd webdriverfirefox i know i grab webelement like elem wdfindelementbycssselector myid and i know i get full page source wdpagesource but anyway get element source elemsource returns html string the selenium webdriver docs python basically nonexistent i see anything code seems enable functionality any thoughts best way access html element children,3 the wx demo image example using imagesimage it shows convert display jpg types well if already demo get main wx download page,all examples i seen seem complicated thanks,2 if want use urlparse intending closest correct equivalent use wwwexamplecom urlstring such urlstring unambiguously absolute path without scheme could supply http default scheme i suppose could detecting whether url includes string prepending front,i like add http scheme name front given url string missing otherwise leave url alone i thought urlparse right way but whenever scheme i use get url i get instead scheme domain urlparseurlparse wwwexamplecom http tgeturl httpwwwexamplecom three how i convert url actually looks like httpwwwexamplecom two,1 orduä‡ ucafã© u f ucafã© u xe c ucafã© print reprc ordc u c u u f u xe,in python api way extract unicode code point single character edit in case matters i using python,3 if i understand question correctly ㈲ sencodeunicodeescape b u shows unicode escape code source string,in python api way extract unicode code point single character edit in case matters i using python,3 usually ordcharacter find code point character for completeness though wide characters unicode supplementary multilingual plane represented surrogate pairs ie two code units narrow python builds case i often needed small workaround def getwideordinalchar lenchar return ordchar return x ordchar xd x ordchar xdc this rare applications though normally use ord,in python api way extract unicode code point single character edit in case matters i using python,3 i problem fixed adding blank initpy file appnametemplatetags directory,i small django project i received friend the code works perfectly system however system i get following error message running server templatesyntaxerror currenttags valid tag library template library currenttags found tried djangotemplatetagscurrenttags the problem line html file load currenttags this exact code works system errors what could,3 i recommend reading post general approach interface threads pyqt gui the post discusses thread socket io really applicable thread specifically hardwareinterface threads usually also use io may good fit the approach discussed generic using queuequeue may seem like overkill simple tasks i want call function thread however application grows nontrivial appreciate avoids thread synchronization problems whatsoever scalable i personally used implement complex pyqt guis sidethreads kinds stuff,i using pyside manage hardware perform relatively simple operations depending eg button clicks interface the code running pieces hardware resides another thread for convenience hardware drivers i added generic invokemethod signal ui component use mydriverinvokemethodemit methodname arg kwarg obviously accesses signal attribute thread directly i sure necessarily okay gil world if indeed lazy solution great alternatives invoking arbitrary methods arbitrary threads without operationspecific signal ui connected another signal driver i could imagine instead using signal bit ui code accessed different piece hardware something like doinvocationdriver doinvocationdriver connect invokemethod signal corresponding driver,2 yes possible think would need use popen instead checkcall send process stdout stderr properly configured logger such logger would use logginghandlerssysloghandler send messages syslog server here short example logger could created import logging handler logginghandlerssysloghandler logger logginggetlogger myapplication loggersetlevelloggingdebug loggeraddhandlerhandler and example could replace checkcall popen send data logger process popenshlexsplitcmd stdoutpipe stderrpipe popenwait waits command complete returns command return code processwait print an error occured loggererrorprocessstderr loggerinfoprocessstdout,i want make stdout stderr output checkcall sent syslog is possible code def commandcmd errnone ifexitfalse try checkcallshlexsplitcmd stdoutnull stderrnull except calledprocesserror err none print err ifexit true exit,1 this practical one way could done shell script note uses bc binbash name output file ofileoutputtxt a goofy wrapper convert sequence bit number expressed hex function bstrtobyte echo obaseibase bc build input string stdin this done using pipes echo binstrsh or interactively long enter q line done entering binary string istr read data data q istristrdata else break fi done bytebybyte conversion expr length istr ge copy first characters bstristr drop input string istristr convert bytestring byte bytebstrtobyte bstr debug print echo bstr byte write character file echo en xbyte ofile check empty istr cause error iteration z istr echo string parsed evenly break fi done echo remaining unparsed characters istr which name binstrsh run piping stdin eg echo binstrsh you check something like hexdump eg hexdump outputtxt i point assumes string entered msb first it also simply discard number bits form complete byte you could change make sure pad input sufficiently lastly debugging lines i left commented double signs,i want take string convert actual binary filesimply writing string file would make either ascii file containing i would prefer python directly bash shell java c fine probably one time use thanks,1 in java u builtin function integerparseintstring strbinarynumberint radix method which work string strbinarynumber systemoutprintlnintegerparseintstrbinarynumber output will an exception type numberformatexception thrown following situations occurs the first argument null string length zero the radix either smaller characterminradix larger charactermaxradix any character string digit specified radix except first character may minus sign ud provided string longer length the value represented string value type int,i want take string convert actual binary filesimply writing string file would make either ascii file containing i would prefer python directly bash shell java c fine probably one time use thanks,1 if got characters convert i presuming need something like using python b bytearrayintbxx x range lenb bytearrayb uxa this splits bit string character chunks string multiple long pad first converts chunk integer converts list integers bytearray written directly binary file need convert string open somefile wb f fwritethebytearray if tasks like libraries help example conversion using bitstring module bitstring import bitarray open somefile wb f bitarraybinbtofilef,i want take string convert actual binary filesimply writing string file would make either ascii file containing i would prefer python directly bash shell java c fine probably one time use thanks,3 any language shifting combine numbers radix while i fan different waysmanipulations different languages access kind stuff ease never forget behind basic maths in case binary simple power taking binary string easily convert byte follows assuming gone converted number format first this start getting bit tedious dealing numbers bits larger since byte time simple byte array chosen language suffice allowing push byte turn it worth mentioning also process used bases shift facility simple multiplication generally work well if label columns across top binary easily see i taking example remember powers not part question related taking one step hexadecimal values f values fit bits binary using powers bits decimal a hexadecimal,i want take string convert actual binary filesimply writing string file would make either ascii file containing i would prefer python directly bash shell java c fine probably one time use thanks,2 have tried removing interpreter adding way pydev would update pythonpath it seems like problem mathso compatible latest changes lion maybe update lion got still pythonpath configure eclipse for better choice would using interpreter downloaded pythonorg control need rely mac gives configure python pythonorg see httppydevorgmanualinterpreterhtml,after installing lion aptana stopped working i longer run python code despite failing find problems python system i tried restoring defaults aptana reinstalling looking missing references aptana python components running simple hello world py script generates console message traceback recent call last file applicationsaptana studio pluginsorgpythonpydevdebugpysrcrunfilespy line module main file applicationsaptana studio pluginsorgpythonpydevdebugpysrcrunfilespy line main import pydevrunfiles file applicationsaptana studio pluginsorgpythonpydevdebugpysrcpydevrunfilespy line module import pydevrunfilesunittest file applicationsaptana studio pluginsorgpythonpydevdebugpysrcpydevrunfilesunittestpy line module import pydevrunfilesxmlrpc file applicationsaptana studio pluginsorgpythonpydevdebugpysrcpydevrunfilesxmlrpcpy line module pydevimports import xmlrpclib file applicationsaptana studio pluginsorgpythonpydevdebugpysrcpydevimportspy line module pydevsimplexmlrpcserver import simplexmlrpcserver file applicationsaptana studio pluginsorgpythonpydevdebugpysrcpydevsimplexmlrpcserverpy line module import basehttpserver file systemlibraryframeworkspythonframeworkversionslibpythonbasehttpserverpy line module import mimetools file systemlibraryframeworkspythonframeworkversionslibpythonmimetoolspy line module import tempfile file systemlibraryframeworkspythonframeworkversionslibpythontempfilepy line module random import random random file systemlibraryframeworkspythonframeworkversionslibpythonrandompy line module math import log log exp exp pi pi e e ceil ceil importerror dlopensystemlibraryframeworkspythonframeworkversionslibpythonlibdynloadmathso symbol found pylongasscaleddouble referenced systemlibraryframeworkspythonframeworkversionslibpythonlibdynloadmathso expected flat namespace systemlibraryframeworkspythonframeworkversionslibpythonlibdynloadmathso,1 tree lxmlhtmldocumentfromstringhtmltext element treeiter elementtag h subelement element stuff that find elements h tags iterate subelements you could also take text inside element string stuff way well whatever want httplxmlde lxml awesome i would recommend i update code already using kept website open reference whenever i question,i html document containing multiple chapters text h tag chapter separator how i split document html snippets snippet starts h tag corresponding chapter i though prettifying html iterating content line linebut kind hack is better solution using lxml,3 based described seems like want support browserbased uploads using post there section aws documentation talks as overview keep mind either make bucket publically writeable include policy document i assume including policy document check docs want a policy document fragment json used authenticate request gives bunch conditions must met data uploaded eg expiration tz conditions acl publicread bucket testbucket eq key filename this says action upload allowed given bucket publically readable bucket name testbucket key exactly equal filename now construct signature take json doc utf encode base sign whole thing using secret access key using hmac sha finally base whole thing policydata stuff encpolicy basebencodepolicydataencode utf signed basebencodehmacnewawssecret encpolicy hashlibsha then finally form would look something like form actionhttptestbucketsamazonawscom methodpost enctypemultipartformdata key upload input typeinput namekey valuefilename br input typehidden nameacl valuepublicread input typehidden namesuccessactionredirect valuehttptestbucketsamazonawscomsuccessfuluploadhtml contenttype input typeinput namecontenttype valueimagejpeg br input typehidden nameawsaccesskeyid valueyouraccesskeyid input typehidden namepolicy valueencpolicy input typehidden namesignature valuesigned file input typefile namefile br the elements ignored input typesubmit namesubmit valueupload amazon s form,i reading documentation passing querystring amazon s authentication seem grok exactly stringtosign created used i looking concrete example illustrate construct stringtosign i signature call form for example sake let say following information contenttype imagejpeg bucket testbucket key filename acl publicread expiration never expires access key secret password abc file file user uploads how would i get stringtosign value and i would i create following form form action methodpost enctype multipartformdata classuploadform input namefile typefile form and reference httpdocsamazonwebservicescomamazonslatestdevindexhtmlrestauthenticationhtmlrestauthenticationquerystringauth thank,1 this caused global cursor try creating closing cursor within method raw query needed cursor connectioncursor cursorexecutequery cursorclose,i built site using django i receiving annoying error i trying execute query if i restart apache server error go away short time traceback file usrlocallibpythonsitepackagesdjangocorehandlersbasepy getresponse response callbackrequest callbackargs callbackkwargs file homefrancronviewssetcachespy setcaches cursorexecutequery category id file usrlocallibpythonsitepackagesdjangodbbackendsutilpy execute return selfcursorexecutesql params file usrlocallibpythonsitepackagesdjangodbbackendsmysqlbasepy execute return selfcursorexecutequery args file buildbdistlinuxieggmysqldbcursorspy execute charset dbcharactersetname exception type interfaceerror blablabla exception value,3 ospathrealpath give result ospathdirnameospathrealpathfile,i looking solution found i need script path dirtoscriptscriptpy cdirscriptpy excepted result scriptpy output dirtoscript cd ampamp scriptscriptpy output dirtoscript is function os module something i mixed solutions write print ospathabspathospathdirnamefile but ugly is better way,3 i encountered exactly problem trying install tkinterpypy ubuntu the error message shows looking tclh file usrincludetcl i install dev version tcl library i installed tcldev sudo aptget install tcldev this installs header files usrincludetcl i created symlink usrincludetcl pointing i also installed dev version tk library eg tkdev installed tkh header needed tkinterpypy usrincludetcl directory after steps tkinterpypy installed successfully,i ton trouble installing modules at first i thought i messed python installation mac os x i installed virtual machine ubuntu similar troubles why os x ubuntu failing error for example i install tkinter failing installing collected packages tkinterpypy running setuppy install tkinterpypy building tkinter extension gcc pthread fnostrictaliasing dndebug g fwrapv o wall wstrictprototypes fpic dwithappinit iusrincludetcl iusrincludetk iusrincludepython c srctkinterc buildtemplinuxisrctkintero srctkinterc fatal error tclh no file directory compilation terminated error command gcc failed exit status complete output command usrbinpython c import setuptoolsfile homepfmbuildtkinterpypysetuppy execfilefile install singleversionexternallymanaged record tmppipsmbwirecordinstallrecordtxt running install running build running buildext building tkinter extension gcc pthread fnostrictaliasing dndebug g fwrapv o wall wstrictprototypes fpic dwithappinit iusrincludetcl iusrincludetk iusrincludepython c srctkinterc buildtemplinuxisrctkintero srctkinterc fatal error tclh no file directory compilation terminated error command gcc failed exit status command usrbinpython c import setuptoolsfile homepfmbuildtkinterpypysetuppy execfilefile install singleversionexternallymanaged record tmppipsmbwirecordinstallrecordtxt failed error code storing complete log homepfmpippiplog,3 in case need regex sreplaceblahsv replace produces use format operator,suppose i string blah blah blah using python regex i replace instance blah different value eg i list values v,1 i think really need regex x v sreplace blah x however really wanted regex import x v resub blah x count,suppose i string blah blah blah using python regex i replace instance blah different value eg i list values v,2 you could use resub callback import def callbackmatch return nextcallbackv callbackviter blah blah blah printresubr blah callbacks yields,suppose i string blah blah blah using python regex i replace instance blah different value eg i list values v,3 you could use resub takes string function applies match resub blah lambda iiter nexti blah blah blah,suppose i string blah blah blah using python regex i replace instance blah different value eg i list values v,3 i stumbled upon sj brown tutorial making games past it great page one best i read however like i like calls isinstance fact listeners receive events first isinstance slower checking two strings equals i ended storing name events test name rather class but still notify function battery itching felt like waste time we two optimizations most listeners interested types events for performance reasons quitevent posted listeners interested notified the event manager keeps track listener wants listen event then avoid going tons statements single notify method one method per type event example class gameloopcontroller def onquiteventself event directly called event manager quitevent posted i call event handler selfrunning false because i want developer type little possible i made following thing when listener registered event manager event manager scans methods listener when one method starts prefix like looks rest quitevent binds name method later event manager pumps event list looks event class name quitevent it knows name therefore directly call corresponding event handlers directly the developer nothing adding onwhateverevent methods working it drawbacks if i make typo name handler onrunphysicsevent instead onphysicsranevent example handler never called i wonder but i know trick i wonder long i cannot add event handler listener registered i must unregister reregister indeed events handlers scanned registration then i never anyway i miss despite drawbacks i like much constructor listener explicitly explain event manager wants stay tuned event and execution speed anyway second point when designing event manager want careful very often listener respond event creatingregistering unregisteringdestroying listeners this happens time if think game may break runtimeerror dictionary changed size iteration the code propose iterates copy dictionary protected explosions consequences aware listeners registered event receive event listeners unregistered event still receive event i never found problem though i implemented game i developing i link two articles half i wrote subject httpnirielwordpresscomwhocontrolsthecontrollers httpnirielwordpresscomtheeventmanagementisinplace httpnirielwordpresscomthefirstscreenshotofinfiniworld the links github account bring directly source code relevant parts if cannot wait thing httpsgithubcomnirielinfiniworldblobvsrcevtmanpy in see code event class bit big every inherited event declared lines base event class making life easy so works using python introspection mechanism using fact methods objects like put dictionaries i think quite pythony,a friend i playing around pygame came across tutorial building games using pygame we really liked broke game modelviewcontroller system events gobetween code makes heavy use isinstance checks event system example class cpuspinnercontroller def notifyself event isinstance event quitevent selfkeepgoing this results extremely unpythonic code does anyone suggestions could improved or alternative methodology implementing mvc this bit code i wrote based markhildreth answer i link users does anyone else good suggestions i going leave open another day picking solution class eventmanager def initself weakref import weakkeydictionary selflisteners weakkeydictionary def addself listener selflisteners listener def removeself listener del selflisteners listener def postself event print post event eventname listener selflistenerskeys listenernotifyevent class listener def initself eventmgrnone eventmgr none eventmgraddself def notifyself event eventself class event def initself namegeneric event selfname name def callself controller pass class quiteventevent def initself eventinitself quit def callself listener listenerexitself class runcontrollerlistener def initself eventmgr listenerinitself eventmgr selfrunning true selfeventmgr eventmgr def exitself event print exit called selfrunning false def runself print run called selfrunning event quitevent selfeventmgrpostevent em eventmanager run runcontrollerem runrun this another build using examples paul impressively simple class weakboundmethod def initself meth import weakref selfself weakrefrefmethself selffunc methfunc def callself args kwargs selffuncselfself args kwargs class eventmanager def initself actually anything selflisteners none none def addself eventclass listener print add eventclassname key eventclassname hasattrlistener self hasattrlistener func listener weakboundmethodlistener try selflistenerskeyappendlistener except keyerror need code selflistenerskey listener print add count lenselflistenerskey def removeself eventclass listener key eventclassname selflistenerskeyremovelistener def postself event eventclass eventclass key eventclassname print post event keys key lenselflistenerskey listener selflistenerskey listenerevent class event pass class quiteventevent pass class runcontroller def initself eventmgr eventmgraddquitevent selfexit selfrunning true selfeventmgr eventmgr def exitself event print exit called selfrunning false def runself print run called selfrunning event quitevent selfeventmgrpostevent em eventmanager run runcontrollerem runrun,1 if python code make much use c based libraries could run code jython python run java vm otherwise could write small javajython executable gets information writes stdout read cpython program calling,i looking simple way python get information java classes name class extends implements methods returns types parameters attributes type information basically information need generate javadoc is existing python library get information either java class file matter i probably even okay something gets information javadoc i know javaclass library overkill i looking just want make sure something already exist like i implement,1 do like eachid listofids successful false successful response makerequesteachid response market closed timesleep sleep one day else successful true the title question clue repeating achieved iteration case simply nested,reason want repeat iteration python eachid listofids assume eachid conatins response makerequesteachid assume makerequest function request url using id response market closed timesleep sleep one day function wake sleep one day market currency trade market open want resume loop eachid eachid eachid yet processed market closed help highly appreciated thanks,3 use loop counter counter lenlistofids processing counter counter and increment get market closed,reason want repeat iteration python eachid listofids assume eachid conatins response makerequesteachid assume makerequest function request url using id response market closed timesleep sleep one day function wake sleep one day market currency trade market open want resume loop eachid eachid eachid yet processed market closed help highly appreciated thanks,1 the handler streamhandler setup imports so logging commands imported modules produce output some handlers print files others communicate network print console there way logging statements inside imported modules could know without handlers added logger if logging statements modules reside inside class function example linked output seen time module class function called handler added logger,i googled looked default documentation i figure produce three lines logging mainpy import logging import apple import banana log logginggetlogger main logsetlevelloggingdebug ch loggingstreamhandler chsetlevelloggingdebug formatter loggingformatter asctimes names levelnames messages chsetformatterformatter logaddhandlerch loginfoi main applepy import logging log logginggetlogger mainapple loginfoi apple bananapy import logging log logginggetlogger mainbanana loginfoi banana output main info i main but example logging documentation works fine any ideas,3 a cleaner way handling events also lot faster possibly consumes bit memory multiple event handler functions code something along lines the desired interface class keyboardevent pass class mouseevent pass class notifythisclass def initself eventdispatcher selfed eventdispatcher selfedaddkeyboardevent selfonkeyboardevent selfedaddmouseevent selfonmouseevent def delself selfedremovekeyboardevent selfonkeyboardevent selfedremovemouseevent selfonmouseevent def onkeyboardeventself event pass def onmouseeventself event pass here init method receives eventdispatcher argument the eventdispatcheradd function takes type event interested listener this benefits efficiency since listener ever gets called events interested it also results generic code inside eventdispatcher eventdispatcher implementation class eventdispatcher def initself dict maps event types lists listeners selflisteners dict def addself eventcls listener selflistenerssetdefaulteventcls listappendlistener def postself event try listener selflistenerseventclass listenerevent except keyerror pass no listener interested event but problem implementation inside notifythisclass selfedaddkeyboardevent selfonkeyboardevent the problem selfonkeyboardevent bound method passed eventdispatcher bound methods hold reference self means long eventdispatcher bound method self deleted weakboundmethod you need create weakboundmethod class holds weak reference self i see already know weak references eventdispatcher prevent deletion self an alternative would notifythisclassremovelisteners function call deleting object really cleanest solution i find error prone easy forget the implementation weakboundmethod would look something like class weakboundmethod def initself meth selfself weakrefrefmethself selffunc methfunc def callself args kwargs selffuncselfself args kwargs here robust implementation i posted codereview example use class weakboundmethod import weakboundmethod wbm class notifythisclass def initself eventdispatcher selfed eventdispatcher selfedaddkeyboardevent wbmselfonkeyboardevent selfedaddmouseevent wbmselfonmouseevent connection objects optional when removing listeners manager dispatcher instead making eventdispatcher needlessly search listeners finds right event type search list finds right listener could something like class notifythisclass def initself eventdispatcher selfed eventdispatcher selfconnections selfedaddkeyboardevent wbmselfonkeyboardevent selfedaddmouseevent wbmselfonmouseevent here eventdispatcheradd returns connection object knows eventdispatcher dict lists resides when notifythisclass object deleted selfconnections call connectiondel remove listener eventdispatcher this could make code faster easier use explicitly add functions removed automatically decide want if note eventdispatcherremove exist anymore,a friend i playing around pygame came across tutorial building games using pygame we really liked broke game modelviewcontroller system events gobetween code makes heavy use isinstance checks event system example class cpuspinnercontroller def notifyself event isinstance event quitevent selfkeepgoing this results extremely unpythonic code does anyone suggestions could improved or alternative methodology implementing mvc this bit code i wrote based markhildreth answer i link users does anyone else good suggestions i going leave open another day picking solution class eventmanager def initself weakref import weakkeydictionary selflisteners weakkeydictionary def addself listener selflisteners listener def removeself listener del selflisteners listener def postself event print post event eventname listener selflistenerskeys listenernotifyevent class listener def initself eventmgrnone eventmgr none eventmgraddself def notifyself event eventself class event def initself namegeneric event selfname name def callself controller pass class quiteventevent def initself eventinitself quit def callself listener listenerexitself class runcontrollerlistener def initself eventmgr listenerinitself eventmgr selfrunning true selfeventmgr eventmgr def exitself event print exit called selfrunning false def runself print run called selfrunning event quitevent selfeventmgrpostevent em eventmanager run runcontrollerem runrun this another build using examples paul impressively simple class weakboundmethod def initself meth import weakref selfself weakrefrefmethself selffunc methfunc def callself args kwargs selffuncselfself args kwargs class eventmanager def initself actually anything selflisteners none none def addself eventclass listener print add eventclassname key eventclassname hasattrlistener self hasattrlistener func listener weakboundmethodlistener try selflistenerskeyappendlistener except keyerror need code selflistenerskey listener print add count lenselflistenerskey def removeself eventclass listener key eventclassname selflistenerskeyremovelistener def postself event eventclass eventclass key eventclassname print post event keys key lenselflistenerskey listener selflistenerskey listenerevent class event pass class quiteventevent pass class runcontroller def initself eventmgr eventmgraddquitevent selfexit selfrunning true selfeventmgr eventmgr def exitself event print exit called selfrunning false def runself print run called selfrunning event quitevent selfeventmgrpostevent em eventmanager run runcontrollerem runrun,3 the openstack compute nova project uses sqlalchemy eventlet might interested approach,i using eventlet build simple website crawler starting example i would like use sqlalchemy store web pages content metadata processing it possible use sqlalchemy along eventlet could anyone provide simple example,3 you hard wiring serverprefix settings the mount prefix site available scriptname wsgi environ dictionary thus memory available requestmetaget scriptname,good morning everyone introduction i got question localeurl usage everything works great url like httpwwwmysitecom if i type httpwwwmysitecom adress bar turns correctly httpwwwmysitecom en example if i use view changelocale also right ie change wwwmysitecom en wwwmysitecom fr problem but application use apache server modwsgi the httpdconf script contains line wsgiscriptalias myprefix pathtodjangoappapachedjangowsgi gives url like httpwwwmysitecommyprefix if i type httpwwwmysitecommyprefix adress bar adress turns httpwwwmysitecomen expected result httpwwwmysitecommyprefixen the problem occured changelocale view i modified code order manage prefix store settingsserverprefix def changelocalerequest redirect given url changing locale path the url locale code need specified request parameters o rochaix taken localeurl view tuned manage serverprefix settingspy next requestrequestget next none next next requestmetaget httpreferer none next next settingsserverprefix next urlsplitnextpath prefix false settingsserverprefix nextstartswithsettingsserverprefix prefix true next nextlstripsettingsserverprefix path utilsstrippath next requestmethod post locale requestpostget locale none locale checkforlanguagelocale path utilslocalepathpath locale prefix path settingsserverprefix path response httphttpresponseredirectpath return response customized view able correctly change language sure right way stuff question httpdconf use wsgiscriptalias prefix ie blog need python side use variable settingsserverprefix match wsgiscriptalias use mediaurl stuff maybe configuration order make work automatically without manage python side do think customized view changelocale right way manage issue or kind automagic stuff it solve problem i type adress httpwwwmysitecommyprefix adress bar if customization way go change well i think better solution thanks advance,2 the proper solution move dict outside class class a pass amydict a b result exactly values would get could ask,if i classes a b i basically want something like class a mydict a b since reference function class fully loaded time i try use how i get around,3 i know since question asked i notice response previous answer needed able customize tabs using stylesheets this also possible using qtabwidget since qwidgets setstylesheet qtabwidget uses qtabbar hood pretty much use stylesheet box for instance stylesheet i using change look tabs pyqtpysidebased web browser uses qtabwidget qtabwidgettabbar left px move right px style tab using tab subcontrol note reads qtabbar qtabwidget qtabbartab minwidth px maxwidth px padding px px fontsize em qtabbartabselected margintop px make nonselected tabs look smaller make use negative margins overlapping tabs qtabbartabselected expandoverlap left right px marginleft px marginright px qtabbartabfirstselected first selected tab nothing overlap left marginleft qtabbartablastselected last selected tab nothing overlap right marginright qtabbartabonlyone one tab want overlapping margins marginleft marginright the stylesheet definitely needs tweaking demonstrate possible applying styles qtabwidget you also check qtabbar qtabwidget section official qt style sheets examples page,i started learning pyqt when experimenting tabbar encountered as minimal example want show button tab label tab here pyqt import qtgui class uitabwidgetqtguiqtabwidget def initselfparentnone qtguiqtabwidgetinitselfparent selfsetobjectnametabwidget selfresize selfsetwindowtitleqtguiqapplicationtranslatetabwidget tabwidget none qtguiqapplicationunicodeutf creating tabbar selftabbarqtguiqtabbarself adding first tab selftabbaraddtabtab selftabbarsettabtexttab the widget intended tab selfwidgetfortabqtguiqwidget selfaddtabselfwidgetfortab selfbuttonfortabqtguiqpushbuttonselfwidgetfortab selfbuttonfortabsettextbutton tab adding second tab selftabbaraddtabtab selftabbarsettabtexttab the widget intended tab selfwidgetfortabqtguiqwidget selfaddtabselfwidgetfortab selflabelfortabqtguiqlabelselfwidgetfortab selflabelfortabsettextlabel tab adding tabbar tabwidget selfsettabbarselftabbar selftabbarsetmovabletrue selfsetcurrentindex name main import sys app qtguiqapplicationsysargv ui uitabwidget uishow sysexitappexec in program widget intended tab tab functioned well anyhow see connection widget tabbar the tabbar tab created independently tabwidget tab both tab titles one given tabbar alone shown but set index first tab shown along widgetfortab in second program lack coupling widget tabbar cause problem pyqt import qtgui class uitabwidgetqtguiqtabwidget def initselfparentnone qtguiqtabwidgetinitselfparent selfsetobjectnametabwidget selfresize selfsetwindowtitleqtguiqapplicationtranslatetabwidget tabwidget none qtguiqapplicationunicodeutf creating tabbar selftabbarqtguiqtabbarself adding first tab selftabbaraddtabtab selftabbarsettabtexttab adding second tab selftabbaraddtabtab selftabbarsettabtexttab selftabbarsetmovabletrue adding tabbar tabwidget selfsettabbarselftabbar the widget intended tab selfwidgetfortabqtguiqwidget selfaddtabselfwidgetfortab selfbuttonfortabqtguiqpushbuttonselfwidgetfortab selfbuttonfortabsettextbutton tab the widget intended tab selfwidgetfortabqtguiqwidget selfaddtabselfwidgetfortab selflabelfortabqtguiqlabelselfwidgetfortab selflabelfortabsettextlabel tab selfsetcurrentindex name main import sys app qtguiqapplicationsysargv ui uitabwidget uishow sysexitappexec the output second program horrible i got four first two tabs tab text tabs button tablabel tablabel tab label tab respectively can tell happening what solve problem,1 in case started yet give frameworks try i started django moved webpy webpy hard one might think in fact i find easier work django just cents edit also might help httpwwwaaronswcomweblogrewritingreddit,i like use python build website pv day now i concern choose web framework i know lots people use django people use webpy django seems powerful i also like simplicity webpy which framework i use please introduce performance maintenance complexity thanks can webpy build complicated applications are frameworks better two,3 how intopic urlliburlopen httpstackoverflowcomquestionshowdoiinsertanattributeusingbeautifulsoup content beautifulsoupbeautifulsoupintopic tlist contentfindall table tbl tlist tblattrsappend border do forget try lxmlhtml fast parse well,how i insert attribute using beautifulsoup for example insert border tag attribute edit i answered question particular class table even intopic urlliburlopenfilectesttesthtml content beautifulsoupintopic tlist contentfindall table mytableclass tbl tlist tbl border print tblattrs,1 colon special character python string output special email headers try inserting blank line output output nprint customer,really odd experience took hour figure i cgi script written python takes form data forwards email problem colon string would cause python output nothing email does anyone know for example output print customer works though output print customer prints output my email function works essentially serversendmailfromaddr toaddrs msg msg output just wondering colon special character python string output,3 allow make guesses the mail actually sent body appears empty you question say you using builtin python mailing library if open mail mail reader look headers print line present if problem ending mail headers rn pair mail reader thinks print mail header print part body malformed email if add rn headers everything fine,really odd experience took hour figure i cgi script written python takes form data forwards email problem colon string would cause python output nothing email does anyone know for example output print customer works though output print customer prints output my email function works essentially serversendmailfromaddr toaddrs msg msg output just wondering colon special character python string output,1 go read following official modwsgi documentation httpcodegooglecompmodwsgiwikiprocessesandthreading it explains various modes things run gives general guidelines data scope sharing,in regular application like windows objectsvariables created global level available entire program entire duration program running in web application written php instance variablesobjects destroyed end script everything written database so python running apachemodwsgi how work regards memory b how create objects persist web page requests ensure threading issues apachemodwsgi,1 macports terrible pythondjango development everything seems data i team following postgres download install postgresql read readme installing download psycopg source httpinitdorgpubsoftwarepsycopg edit setupcfg set pgconfig librarypostgresqlbinpgconfig then install python setuppy install i recommend using virtualenv well want stay away base mac os x python install much possible,i recently installed django psycop however python refusing use error can someone please help import psycopg traceback recent call last file stdin line module file libraryframeworkspythonframeworkversionslibpythonsitepackagespsycopginitpy line module psycopgpsycopg import binary number string datetime rowid importerror dlopenlibraryframeworkspythonframeworkversionslibpythonsitepackagespsycopgpsycopgso symbol found pqbackendpid referenced libraryframeworkspythonframeworkversionslibpythonsitepackagespsycopgpsycopgso expected flat namespace libraryframeworkspythonframeworkversionslibpythonsitepackagespsycopgpsycopgso,1 look foreignkey docs it says when object referenced foreignkey deleted django default emulates behavior sql constraint on delete cascade also deletes object containing foreignkey this behavior overridden specifying ondelete argument so default behavior cascade delete change specifying something like class foobarmodelsmodel user modelsforeignkeyuser ondeletemodelssetuserobjectsgetorcreateusernamefoooobarrrr,i cannot find option cascade update delete model api am wondering manual help pass db option sycning db idea,1 here example one might format coordinate record description using strformat crd rafbfcfalphafbetafgammaf spz datadictr cryst abcalphabetagammasp p z printcrdformatdata cryst p the format specifier crd interpreted way r tells format stringinterpolate value strr left justified width af tells format stringinterpolate float value right justified total width digits decimal point the complete description format specified works given,i would like format text protein data bank file format basically i need start text specific columns right i formatting using ljust rjust i feel like magic function i could use give word column start any help would greatly appreciated thanks if statckoverflow searching failed please point direction,1 just guess exclusion list meta class set false boolean fields like use checkbox show post data unchecked the form tell difference boolean form field set false one page first place need explicitly exclude,i custom changeuserform modelform user allows user update account information however i save form userisactive userisstaff userissuperuser get set false any thoughts going formspy class userchangeformformsmodelform username formsregexfieldlabelusername maxlength regexr w helptext required characters fewer letters digits errormessages invalid this value may contain letters numbers characters firstname formscharfieldlabelfirst name maxlength lastname formscharfieldlabellast name maxlength email formsemailfieldlabelemail address newpassword formscharfieldlabelnew password widgetformspasswordinput requiredfalse newpassword formscharfieldlabelconfirm new password widgetformspasswordinput requiredfalse class metaauthformsuserchangeform model user exclude password lastlogin datejoined def cleannewpasswordself password selfcleaneddataget newpassword password selfcleaneddataget newpassword password password raise formsvalidationerrorthe two password fields match else lenpassword lenpassword raise formsvalidationerroryour password must minimum characters return password def saveself committrue user superuserchangeform selfsavecommitfalse lenselfcleaneddata newpassword usersetpasswordselfcleaneddata newpassword commit usersave return user class userprofileformformsmodelform class meta model userprofile exclude user viewspy loginrequired def profilerequest context requestmethod post userform userchangeformrequestpost instance requestuser userprofileform userprofileformrequestpost instance requestuserprofile userformisvalid userprofileformisvalid userformsave userprofileformsave return rendertoresponse accountsprofilecompletehtml contextinstancerequestcontextrequest else userform userchangeforminstance requestuser userprofileform userprofileforminstance requestuserprofile contextupdatecsrfrequest context userform userform context userprofileform userprofileform return rendertoresponse accountsprofilehtml context contextinstancerequestcontextrequest,1 django not provide automatic purging there however handy command available help manually httpsdocsdjangoprojectcomendevtopicshttpsessionsclearingthesessionstore,does table need purged taken care automatically django,3 you serialize python object like there section django documentation httpsdocsdjangoprojectcomendevtopicsserializationid here key part look jsonserializerserializequeryset ensureasciifalse streamresponse,i bit newbie python go easy i writing ajax handler django everything pretty straightforward i banging head bit better part day i like return json string contains dict contains queryset modelspy class projectmodelsmodel uniquename modelscharfieldmaxlength uniquetrue title modelscharfieldmaxlength blanktrue description modelstextfield project description blanktrue projectdate modelsdatefield project completion date published modelsbooleanfield class projectimagemodelsmodel project modelsforeignkey project relatedname images image modelsimagefielduploadtogetimagepath title modelscharfieldmaxlength sortmetric modelsintegerfield viewspy projects projectprojectobjectsfilterpublishedtrue responsedict success true maxgroups result analysis projects queryset projects projects this one works i remove projects dict response jsondumps responsedict this one works projects response serializersserialize json responsedict relations images return httpresponse response mimetype applicationjavascript i commented two serialization lines the first one seems work simple dicts since projects included dict fails project project object json serializable the second one seems work querysetsmodels since outer part dict nonmodel complains str object attribute meta note i using wadofstuff serializer understanding would resolve onetomany relationship defined model but even i get working serializing projects i projectimages output question what best way serialize whole responsedict surely i first person want right question why i unable get manytoone relationship work many thanks help update just found one django json serialization mixed django models dictionary looked promising i get queryset object attribute meta,1 you quite relationship you need arrange link looked way the obvious look directly submissionlink sessionquerylinks filterlinkslink u httpfacebookcom first submissionlink none submissionlink linkslinku httpfacebookcom sessionaddsubmissionlink submission submissionstitleu facebook homepage linksubmissionlink sessionaddsubmission sessioncommit you also use hybrid attributes get something looks bit like example substantially convoluted also relationship relation deprecated,i learning use sqlalchemy i trying following storing title link two separate tables temp submissionstitleu facebook homepage linku httpfacebookcom sessionaddtemp sessionflush transactioncommit via class linksbase tablename links id columninteger primarykeytrue link columntext created columntimestamp defaultdatetimenow def initself link selflink link class submissionsbase tablename submissions id columninteger primarykeytrue created columntimestamp defaultdatetimenow title columntext linkid columninteger foreignkey linksid link relationlinks def initself title link selftitle title selflink link however i always get error attributeerror unicode object attribute sainstancestate what going is better way code,3 have look httpcodeactivestatecomrecipes edit modified use userdefined password arbitrary length requires pycrypto thrown together minutes without test sight edit updated version httpsgistgithubcom,i want encrypt arbitrarylength string password python i would prefer deal padding key generation ivs i honestly know much cryptography yet i like avoid messing i also prefer using wellknown cypher aes my ideal library let call magiccrypt would work like magiccrypt import aes p plaintext k password crypt aesk c cryptencryptp p cryptdecryptc true i checked pycrypto mcrypto pycryptopp gpgme keyczar neither seem offer really easy use mode keyczar comes closest reason wants use keyset saved filelike object something similar as far i know i resort calling mcrypt popen offer mode works exactly like part reason i guessing really technical reason exist do know easy use secure crypto library python if easiest yet secure way using already mentioned libraries,2 yup need add code comment the problem oslistdir returning base file names rename called expects find files whatever directory python thinks by adding ospathjoin build fully qualified path file rename work correctly in comments op stated files got moved folder lead believe rename needed fully qualified path second argument also learned files renamed footxt instead become txt etc preserving file extension this code import os sys path inputinput path dirs oslistdirpath rangelendirs capture fully qualified path original file originalfile ospathjoinpath dirsi build new file name number file extension file name code goes boom newfile ospathjoinpath stri originalfilesplit print renaming formatoriginalfile newfile osrenameoriginalfile newfile verified python showing relevant bits command line you see empty files bartxt footxt renamed path inputinput path input pathusersbfellowsso dirs oslistdirpath dirs bartxt footxt rangelendirs osrenameospathjoinpath dirsi stri stopped python helcaraxeso bfellows ls al total drwxrxrx bfellows bfellows sep drwxrxrx bfellows bfellows sep rwrr bfellows bfellows sep rwrr bfellows bfellows sep helcaraxeso bfellows python v python,code meant ask directory list al files directory rename position list problem i always get error file found print list apperently find files list blank import os sys path inputinput path dirs oslistdirpath rangelendirs osrenamedirsi stri given input files i want rename base file name number preserving file extension thus input atxt testtxt testtxt output txt txt txt,2 djangodb import models djangocontribauthmodels import user class topicmodelsmodel user modelsforeignkeyuser authuser would worked it python library syntax django orm appmodel syntax but pass model string desperately trying solve circular dependency and circular dependency code eff,consider following django model djangodb import models djangocontrib import auth class topicmodelsmodel user modelsforeignkey authmodelsuser name modelscharfieldmaxlength namemaxlength unique true versionnumber modelsintegerfielddefault createdat modelsdatetimefieldautonowadd true modifiedat modelsdatetimefieldautonow true updatefrequency modelsintegerfield this model validate even installing authuser table in authmodelsuserobjectsall out user admin the statement djangoadmin shell python managepy syncdb error one models validate topic user relation model authmodelsuser either installed abstract i using django v pinax ubuntu sqlite database the following questions help much foreign key user table django how i create foreign key user table django,3 list mcrypto see msecret example httpwwwheikkitoivonennetmsecret seems pretty much exactly want disclaimer used listed pypi alpha quality httppypipythonorgpypimsecret update time answering wrote simplecrypt simple wrapper pycrypto aes encryption python similar rob answer also includes pbkdf generate secure key,i want encrypt arbitrarylength string password python i would prefer deal padding key generation ivs i honestly know much cryptography yet i like avoid messing i also prefer using wellknown cypher aes my ideal library let call magiccrypt would work like magiccrypt import aes p plaintext k password crypt aesk c cryptencryptp p cryptdecryptc true i checked pycrypto mcrypto pycryptopp gpgme keyczar neither seem offer really easy use mode keyczar comes closest reason wants use keyset saved filelike object something similar as far i know i resort calling mcrypt popen offer mode works exactly like part reason i guessing really technical reason exist do know easy use secure crypto library python if easiest yet secure way using already mentioned libraries,3 center keyword argument positional argument you use positional arguments south understand see custom fields keyword arguments you could solve providing center default value centernone would fine following example code link defining keyword name passed init name stored database dictionary options may blank setting default value helps,i using custom django model field widget render googlemap widget admin also want use south project handle database migrations however much effort unable generate custom south rule fits custom model last many instrospection rules tried class googlemapmarkerfieldmodelscharfield metaclass modelssubfieldbase description un marcador de google maps widget googlemapmarkerwidget def initself center args kwargs kwargs maxlength kwargs helptext arrastre el cursor en el mapa para seleccionar el punto selfcenter center supergooglemapmarkerfield selfinitargs kwargs def formfieldself kwargs defaults center selfcenter formclass googlemapmarkerformfield defaultsupdatekwargs return supergooglemapmarkerfield selfformfielddefaults def topythonself value isinstancevalue googlemapmarker return value isinstancevalue list return googlemapmarkermapfloat value elif isinstancevalue basestring try return googlemapmarkermapfloat valuesplit except valueerror pass def getprepvalueself value return ff valuelatitude valuelongitude addintrospectionrules googlemapmarkerfield center center websitefieldsgooglemapmarkerfield and traceback getting traceback recent call last file managepy line module executemanagersettings file homearmongeworkspaceenvlibpythonsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file homearmongeworkspaceenvlibpythonsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file homearmongeworkspaceenvlibpythonsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file homearmongeworkspaceenvlibpythonsitepackagesdjangocoremanagementbasepy line execute output selfhandleargs options file homearmongeworkspaceenvlibpythonsitepackagessouthmanagementcommandsschemamigrationpy line handle oldorm lastmigrationorm file homearmongeworkspaceenvlibpythonsitepackagessouthutilspy line method value functionself file homearmongeworkspaceenvlibpythonsitepackagessouthmigrationbasepy line orm return fakeormselfmigrationclass selfapplabel file homearmongeworkspaceenvlibpythonsitepackagessouthormpy line fakeorm ormcacheargs fakeormargs file homearmongeworkspaceenvlibpythonsitepackagessouthormpy line init selfmodelsname selfmakemodelapplabel modelname data file homearmongeworkspaceenvlibpythonsitepackagessouthormpy line makemodel field selfevalincontextcode app extraimports file homearmongeworkspaceenvlibpythonsitepackagessouthormpy line evalincontext return evalcode globals fakelocals file string line module typeerror init takes least arguments given,1 the what new document one place introduced these views introduced proposed python backported seen serve bestofallworlds pieces dict refer before keys values items methods simply made lists this wastes memory copying dict information iterkeys itervalues iteritems methods waste memory featureful thing could iterate could these new views logical features set operations efficient comparison iterable multiple times,i came across three types i used collectionscounter viewkeysviewitems viewvalues method the value three methods returned type dictkeys dictitems dictvalues they iterable i noticed but question three types exist or usage,3 here suggestion create two version script dump everything one in proper thing laying code separate files smart filenames now run first command time python mygameallinonepy the dollar sign represents command line prompt and run second time python mygamepy the time command tell much time game actually took run real time much cpu time took run commands say ten times take average time this called profiling help decide approach best even makes difference,sorry question incredibly easy answer i sound like idiot i wondering i would execute script one file pygame event loop blits etc switch another file selectworldpy event loop blits etc if i call main function create slowdown i still original file open i fine selectworldtransition sort thing thanks advance,1 the read method returns file contents chunks you call returns empty string httpdocspythonorgtutorialinputoutputhtmlmethodsoffileobjects,i tried different ways result always seems i get python read end file it stops halfway i tried binary ascii modes result i also checked special characters file cuts none additionally i tried specifying much read still cuts place it goes something like fopenarchivesarchivelog r logtextfread print logtext it happens whether i call bash python whether i normal user root however works fine file directory i fopenarchivelog r logtextfread print logtext this works like dream any idea,1 what asking essentially define good players easy problem as mentioned simple average score pickingthehighestscore ideal answer depending game design i like recommend read elo rating system chess modified versions design player rating system one simple possible way set window like recent games use average score window players play less games window would placement state again easy problem heavily depends game good luck update i assumed game player vs player if another story most games keep highest score matter many times play game going entry leaderboard since say anything game i idea fair as i mentioned earlier could set window avg score highest score you even reset leaderboard every month remove players played week it depends game want please remember matter make sure rules crystal clear players otherwise would easily upset frustrated,i need create functionmethod python calculates high score leaderboard each player played number rounds game recieving score round i want know best way sort top ranking players accounting score and number rounds played the possible scores round f d d d c c c b b b a a obviously simple average work take account number rounds played whats best way set fair sorting function edit i reading really great answers i want try clear question bit i want players score and number rounds played count towards ranking way fair meaning player b higher rank player a basically high score reflect general effort skill number rounds played plus score means higher ranking edit after reading answers i think best way simple total sum players points across rounds i sure answer assign green check correct,1 there many ways could try example let fa make however try take difficulty account score one higher previous for every game play receive score create total score add game score every time total score that way person receives a person receives a gets score simply sort accordingly each function drawbacks course this function best consider getting b would exceed a even though a much better score give details want rank much easier get algorithm,i need create functionmethod python calculates high score leaderboard each player played number rounds game recieving score round i want know best way sort top ranking players accounting score and number rounds played the possible scores round f d d d c c c b b b a a obviously simple average work take account number rounds played whats best way set fair sorting function edit i reading really great answers i want try clear question bit i want players score and number rounds played count towards ranking way fair meaning player b higher rank player a basically high score reflect general effort skill number rounds played plus score means higher ranking edit after reading answers i think best way simple total sum players points across rounds i sure answer assign green check correct,1 if you’re trying match ipv address use regex import text regex researchregex textgroup refindallregex text,how prevent parital matches using research using dictionary key pattern python for question i would like avoid iterating nested list dictionary value i tried appending regular expressions search pattern results error partial match server e match researche server match print matchgroup,1 i want database get big unwieldy database scaling big topic still fits realm optimization summed three simple rules don don experts only profile first what means question probably optimizing size data good idea how much data really what queries execute regularly data queries slow what database natively help what might seem first blush lot data often nothing worry a good rule thumb dataset fits memory big dataset even big dataset often case small part relevant non completed rows really affect queries you make work well creating right combination indexes database easily find operate rows actually query and might using database wrong thing what describing data comes hangs around gets processed gets archived sounds suspiciously similar queue persistent distributed queues widely available have look celery python framework built queuing may better fit problem trying solve,i relatively new sqlalchemy done basic database creation insert update delete i found quite simple use far my question i want move records one database another backup database what simplest way sqlalchemy,1 yes works the exact implementation depends webserver case nginx recommended mark location internal prevent external access nginx asynchronously serve files django need one thread per request get problematic higher numbers parallel requests remember send xaccelredirect header nginx instead xsendfile see httpwikinginxorgxsendfile information,i research regarding file downloads access control using django my goal completely block access file except accessed specific user i read using django xsendfile one methods choice achieving based so questions etc my rudimentary understanding using xsendfile django user requests uri get protected file django app decides file return based url checks user permission etc django app returns http response xsendfile header set server file path the web server finds file returns requester i assume webs server also strips xsendfile header along way compared chucking file directly django xsendfile seems likely efficient method achieving protected downloads since i rely nginx serve files vs django leaves questions is explanation xsendfile least abstractly correct is really secure assuming i provide normal frontend http access eg httpwwwexamplecomdownloadssecretfilejpg directory file stored ie keep publichtml directory or could techsavvy user examine headers etc reverse engineer way access file distribute is really big difference performance am i going bog application server providing b chunked downloads mb files directly django sortof nonissue the reason i ask versions near equal django version would preferable due ability things python like log number completed downloads tally bandwidth downloads etc thanks advance,3 i never use appengine i guess requestcookies normal dictionary object like example django you try following userid selfrequestcookies cookie exists,in code i using userid selfrequestcookiesget userid userid usergetbyid int userid look right even though technically worksit looks imprecise is better way i check existence cookie,1 try except clauses handy situations like need clear obvious workflow hair trigger invalidate everything catch to clear approach various nuances involved securely trackingmanaging user session leaving data client try userid selfrequestcookies userid raise keyerror exception set isinstanceuserid basestring assert userid raise valueerror exception userid try userid intuserid except valueerror loggingwarnu userid value cookie type could u coerced integer value typeuserid userid isinstanceuserid int raise assertionerroru userid value cookie invalid u typevalue ss typeuserid userid except keyerror userid key exist cookie object loggingdebug no userid value cookie except assertionerror the cookie value invalid clearthecookieandstartagainprobably except exception e something else went wrong loggingerroru an exception count exception e clearthecookieandstartagainprobably raise e else usergetbyiduserid,in code i using userid selfrequestcookiesget userid userid usergetbyid int userid look right even though technically worksit looks imprecise is better way i check existence cookie,1 um problem exactly tried port test port since blocked isp google mx server listening port if isp allow outgoing connections port able send smtp messages way trying you get sorted isp regarding rejection messages sending email directly like increase likelihood rejected flagged spam particularly set address something match domain associated ip address smtp client sends mismatched domain ehlo message content message looks spammy the actual behavior vary according individual mx server configured,i tried playing around python learn smtp protocol more precisely i trying send mail straight host smtp server little success for example say i want send mail gmailcom address i lookup mx record gmailcom nslookup typemx gmailcom gmailcom mx preference mail exchanger altgmailsmtpinlgooglecom gmailcom mx preference mail exchanger gmailsmtpinlgooglecom gmailcom mx preference mail exchanger altgmailsmtpinlgooglecom then i following python import smtplib tried port test port since blocked isp smtplibsmtpaltgmailsmtpinlgooglecom i tried several everyone one i always got errno a socket operation attempted unreachable network errno a connection attempt failed connected party properly respond period time established connection failed conneted host failed respond exception i read somewhere mail servers reverse lookup ip rejecting connection got domain how i also read somewhere many mail servers reject incoming mails dynamic ip addresses i obviously private customer isp how check ip address dynamic static are reasons servers seem reject connection or something,2 test logic tests never part production production mean use released client etc code so bad idea anywhere within script ideally separate files,when write scripts self sufficient bad idea use name main place write tests,3 serializing really generalized possible sqlalchemy mapped classes classes might properties stored database must inferred across multiple levels indirection relationship properties in short know serialize particular class particular use lets pretend need care column values specific instance specific class consideration res here crude function return dict containing values sqlalchemyormattributes import managerofclass sqlalchemyormproperties import columnproperty def getstatedictinstance cls typeinstance mgr managerofclasscls return dictkey getattrinstance key key attr mgriteritems isinstanceattrproperty columnproperty recreate instance dict def createfromstatedictcls statedict mgr managerofclasscls instance mgrnewinstance key value statedictiteritems setattrinstance key value return instance if need something complex probably handling relationships shown columns manytomany relationships probably add case looking sqlalchemyormpropertiesrelationshipproperty iterating collection serializing intermediate dict class left exercise,ok i bit problem i need able create sort importexport functionality sqlalchemy now objects i defining get columns i attr value resclassdictiteritems isinstancevalue instrumentedattribute data evalres strattr paramdictattr data now correctly gets attributes object however i cant certain parameters init since i one handling objects so could situation like class someclassmodelbase mycolumn columnstring stuff def initself mycolumn selfmycolumn mycolumn so case i correspondance name field name parameter recieved init i currently contraining ones define classes init parametes default value i could obj someclass exec obj attr paramattr however i would like get away even constrain is way i achieve,2 most unices already usrbinpython overwriting one bad idea python version used packages system changing one may break when installing python package executable installed usrbinpython i would claim archlinux broken better use want run python archlinux bit special since use usrbinpython python despite default executable name python usrbinpython this confusing seen bug mean use symlink python archlinux script uses python almost certainly break so unices symlinking usrbinpython python bad idea archlinux terrible idea instead install version need call usrbinpythonxx,so i read httpswikiarchlinuxorgindexphppython and clear wiki i install python via pacman s python is reasonable create symlink python ln python usrbinpython i forsee switching python time soon or better way managing multiple python versions like i usually use debian system updatealternatives config python mac os x system python select clarification what i trying find best practice managing various python versions archlinux system i new archlinux familiar ubuntu debian mac os x,2 best practice put tests separate units use unittest module this separation allows keep main code clean need lots testing helper functions encourages write good comprehensive tests since inhibited cluttering main code,when write scripts self sufficient bad idea use name main place write tests,2 it really depends code purposes script for big complex projects sure put tests separate place but working something small might good solution tests along code main idea doctest great python module allows write tests docstrings in case name main look like name main import doctest doctesttestmod i find nice clean,when write scripts self sufficient bad idea use name main place write tests,3 the python reference manual read says also note nonblocking mode less data requested may returned even size parameter given there also draft pep matter apparently accepted a pep python enhancement proposal so sad state affairs cannot rely read give full file one call if file text file i suggest use readlines instead it give list containing every line file as far i tell readlines reliable,i tried different ways result always seems i get python read end file it stops halfway i tried binary ascii modes result i also checked special characters file cuts none additionally i tried specifying much read still cuts place it goes something like fopenarchivesarchivelog r logtextfread print logtext it happens whether i call bash python whether i normal user root however works fine file directory i fopenarchivelog r logtextfread print logtext this works like dream any idea,2 your pyhelloworldglade incorrect make sure created correct glade application glade glade applications installed used if downloaded file make sure correct the error message says expected gladeinterface got interface so xml file interface tag pygtk library expects gladeinterface tag,i made gui glade i want put python program i adapting instructions tutorial i found online load glade file httpwwwpygtkorgarticlespygtkgladeguicreatingaguiusingpygtkandgladehtm when i problems i tried something basic one button calling thing tutorial copy pasting code still work i also took look httpwwwlinuxjournalcomarticlepage function called slightly differently selfwtreegtkgladexml gladefilewindowname instead without windowname implemented equivalent mine fix i definitely pygtk working i made something without using glade worked fine the error i getting usrsharethemesnoxgtkgtkrc murrine configuration option gradients longer supported ignored helloworldpy libgladewarning expected gladeinterface got interface helloworldpy libgladewarning finish parserfinish state traceback recent call last file helloworldpy line module hwg hellowworldgtk file helloworldpy line init selfwtree gtkgladexmlselfgladefile runtimeerror could create gladexml object i running xubuntu the murrine configuration thing comes gtk application opens i included case relevant here code i took tutorial working usrbinenv python import sys try import pygtk pygtkrequire except pass try import gtk import gtkglade except sysexit class hellowworldgtk this hello world gtk application def initself set glade file selfgladefile pyhelloworldglade selfwtree gtkgladexmlselfgladefile get main window connect destroy event selfwindow selfwtreegetwidgetmainwindow selfwindowshow selfwindow selfwindowconnectdestroy gtkmainquit name main hwg hellowworldgtk gtkmain,2 i know really understand but simply need return first ajax call key entity calculation question when user makes response firstly get entity key update property answer step the ajax call return question json example to fetch empty answered question qry calculationallfilter answer none ref qryget the json response key unicoderefkey question refquestion step you update entity key key answer variable http get post request ref dbgetkey refanswer answer refput,i calculation entity datastore say million objects entity it following properties python runtime class calculationdbmodel question dbstringpropertyrequiredtrue answer dbstringproperty suppose examples question property things like really important all calculation objects start empty answer properties when user connects app ajax call made app supposed fetch calculation object empty answer property send user browser the user browser evaluates question sends back different server handler how i update specific calculation object answer property if someone could provide code would great not really experienced app engine query stuff confusing what best solution i want conserve much servercpu possible thanks,1 javascript files works uimodules javascript files included way appended page end body tag though head tag if really want file included head tag simply output value params corescripts head tag template raw params corescripts,in following code snippet i trying add javascript files tornado server html file head tag debugscripts script srcsrcmainjs typetextjavascriptscript class entriestornadowebuimodule def javascriptfilesself return srcmainjs class mainhandlertornadowebrequesthandler def getself params params corescripts debugscripts path ospathjoinospathdirnamefile indexhtml selfrenderpath paramsparams params corescripts debugscripts i trying add script tag html gets parsed text generates ampltscript typeampquottextjavascriptampquot srcampquotsrcmainjsampquotampgtampltscriptampgt so i came across javascriptfiles method tornado specs i getting examples implementations can anyone help,2 you find solution docs if need create relationship model yet defined use name model rather model object class carmodelsmodel manufacturer modelsforeignkey manufacturer class manufacturermodelsmodel,i defined two models one references like class usermodelsmodel loves modelsmanytomanyfieldarticle relatedname lovedby class articlemodelsmodel author modelsforeignkeyuser you see problem classes references no matter order two classes implemented python always raises nameerror exception complaining either one class defined,3 try usung serialiser optional fields argument serializeditems serializersserializejson itemlist fields auxinfo may also suggest using init method add fields considdered bad form django would much better achieved like class mymodelmodelsmodel title modelscharfield description modelstextfield def auxinfoself return i database,i wrote init method one models adds auxiliary information object dynamically adding attribute object reflect column database class mymodelmodelsmodel title modelscharfield description modelstextfield def initself args kwargs selfauxinfo i database this seemed working fine i found case work i code view i set status variable package list mymodels json like djangocore import serializers djangoutils import simplejson use serializers django models serializeditems serializersserializejson itemlist dataitems serializeditems serializeditems string datastatus status package data dict using simplejson python objects resp simplejsondumpsdata return httpresponseresp mimetypeapplicationjavascript the problem seems django serializers serialize model fields attributes object auxinfo come i also pretty sure using serializers simplejson right way thanks help,1 httpsgithubcomkevinwpyflakesvimissues you recommend users clone pyflakesvim repo git clone recursive suggest fact use git submodule update init recursive pyflakesvim saved git submodule or go pyflakesvim git submodule init ampamp git submodule update the point pyflakesvim needs fresh local copy pyflakes ftpluginpluginpyflakes systemwide installed version old,i playing pyflakes plugin vim i open python file i get error messages screenshot any ideas fix thanks advance,1 have trying appstats help httpcodegooglecomappenginedocspythontoolsappstatshtml with software profiling api call,the new pricing model resources datastore reads datastore writes but i could find detailed information exactly measured hard optimize datastore utilization i profile any clues httpcodegooglecomappenginearticlesmanagingresourceshtml doesnt give details,2 from documentationfilesystemsproctxt these numbers identify amount time cpu spent performing different kinds work time units userhz typically hundredths second so figure utilization terms percentages need find userhz machine find long since system booted the second one easy btime line file use for userhz check how get number mili seconds per jiffy,procstat shows ticks user nice sys idle iowait irq sirq like cpu how i calculate individual utilizations user nice etc values like values shows top vmstat,2 you confused logical for example key image check following image image image link false true true instead want key image key link easier read key image link,i dictionary item it strings keys values lists eg item title u python item image u linktoimage item link u link article i want check value length link image may empty i following key value itemiteritems lenvalue key image key link raise dropitemitem empty item return item so item dropped value image key my problem condition work the item still dropped image link empty any idea whats wrong i new python,3 you key image key link key image key link always true,i dictionary item it strings keys values lists eg item title u python item image u linktoimage item link u link article i want check value length link image may empty i following key value itemiteritems lenvalue key image key link raise dropitemitem empty item return item so item dropped value image key my problem condition work the item still dropped image link empty any idea whats wrong i new python,2 if doubt implement magic methods the defaults reason fine in case completely unnecessary implement hash would implement implement eq well unless expect someone set dictionary methods str useful in case result include the class name avoid confusion anything else whether function alive if alive str result identify function say name,i class called weakboundmethod source codereviewse i like guidelines i implement hash also python automatically provides repr function i guess i bother redefining what str i understand human readable text representation object i define well guidelines about hashing function i like generate hash based self func bound method wrapping how i,1 i ended custom xml stripping like xmlstart htmldatafind xml xmlend htmldatarfind mytag xmlstart loguseractionreqgethost chunked data htmldata htmldata htmldataxmlstart xmlend lenhtmldatalen mytag htmldata htmldataxmlend can find simple solution,i following code open read urls htmldata urlliburlopenreqread i believe standard way read data http however response chunked tranferencoding response starts following characters ebrnrn xml version encodingutf this happens due mentioned chunked encoding thus xml data becomes corrupted so i wonder i get rid metadata related chunked encoding,1 this code calculates user utilization spread cores import os import time import multiprocessing def main jiffy ossysconfossysconfnames scclktck numcpu multiprocessingcpucount statfd open procstat statbuf statfdreadlinessplit user nice sys idle iowait irq sirq floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf statfdclose timesleep statfd open procstat statbuf statfdreadlinessplit usern nicen sysn idlen iowaitn irqn sirqn floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf statfdclose print usern user jiffy numcpu name main main,procstat shows ticks user nice sys idle iowait irq sirq like cpu how i calculate individual utilizations user nice etc values like values shows top vmstat,3 ok gonna write notepad first i press enter early i solved problem i really sure why solution solves problem as turns reason one able read one cut early created python script whereas created earlier even though i closed file file appear fully written disk or i grabbing buffer something like by del f and trying grab file i got whole file and yes i use fclose writing file so problem solved anyone give reason i garbage collect manually instance i think i python,i tried different ways result always seems i get python read end file it stops halfway i tried binary ascii modes result i also checked special characters file cuts none additionally i tried specifying much read still cuts place it goes something like fopenarchivesarchivelog r logtextfread print logtext it happens whether i call bash python whether i normal user root however works fine file directory i fopenarchivelog r logtextfread print logtext this works like dream any idea,1 yes using mvc facilities way go even though using qtreewidget still working class derived qabstractitemview therefore model setmodel calls available take model one widgets creating set widgets whenever change data one widgets widgets follow suit using instance model if need maintain selection state widgets parts tree open close might little bit harder might actually work using selectionmodel selectionmodel setselectionmodel,i new python pyqt what best way keep qttreewidgets synchronized items well attributes items these widgets appear different dialog boxes different times session for number reasons i need keep much existing code signals layout intact possible the modelview division would obvious first place go i want touch methods used access update tree i planning refactor whole thing months i need something quickly carry since qtreewidget convenience class data the ui maintained qt designer i want keep way when dialog initialized tree appears the application singleton class dialogs use reference variablesattributes in initialization parent dialog i check see locationtree attribute exists singleton if i would need populate initial state tree dialog use copy any time state dialog tree altered ways i trap i like update singleton locationtree mirror change although clone method qtreewidgetitem i see corresponding method entire qtreewidget how i accomplish least amount change existing code base gui layout john,2 save selfshop getqueryset first method called see code baselistview get method so one solution would get variable code also save selfshop baselistview selfobjectlist def getquerysetself selfshop shopobjectsgetnameselfkwargs shopname offer selfshopgetoffersmodel return offerobjectsall then methods use selfshop def gettemplatenamesself return shopsofferlist selfshopgettype,my url keyword shopname variable there also shop model name field in listview class i need make repeating queries shop model get unicode variable shopgettype method depending result proper template directory selected queryset using subclassed django models here code class offerlistlistview def gettemplatenamesself shop shopobjectsgetnameselfkwargs shopname return shopsofferlist shopgettype def getquerysetself shop shopobjectsgetnameselfkwargs shopname offer shopgetoffersmodel return offerobjectsall def getcontextdataself kwargs getting shop instance shop shopobjectsgetnameselfkwargs shopname context superofferlist selfgetcontextdatakwargs context shop shop return context question best way i get var shop case available methods i python guru may basic problem i tried init overriding i get exchangename specified urlspy get right shop instance i would like avoid repeating thanks,1 numpy scipy contain routines let fit expressions data points expression plot range time like answer nonlinear ex regression using scipy python numpy contains example nonlinear regression exponential like question one negative exponent general fitting extrapolating exponentials positive exponents bad idea extrapolation sensitive noise uncertainty quickly becomes meaningless,i need able extrapolate using n data points curved trend line queried in head would look bit like blue line this calories calculator i data points regarding amount calories burned activity based certain weight eg kg burn around calories kg burn calories kg burn calories etc etc one axis would calories weight obviously i wanted find amount calories burned weight i data point i would need trend line query brings second part question would i go in summary how i extrapolate trend line python how i query trend line get estimates based point trend line,2 yes use python threading module cooperative microthreading module like gevent note python threading mechanism carries disclaimer cpython default python implementation boxes due global interpreter lock cpython one thread execute python code even though certain performanceoriented libraries might overcome limitation if want application make better use computational resources multicore machines advised use multiprocessing however threading still appropriate model want run multiple iobound tasks simultaneously depending underlying modules calling operate may find using threading one thread give control often in case using cooperative microthreading might option,i trying run method infinite loop create video display this method called within another loop handles hardware input cannot loop fast video causing lag i use outer loop run video is way start video loop start hardware loop run separately currently i call video loop sits loop returns,1 you use datetimedatetimestrptime converts string date format datetimedatetime object the format fields eg y denotes fourdigit year specified python documentation import datetime format ymd hmsf datedatetimedatetimestrptimes format date datetimedatetime,i string field like i need convert datetime object python i calculate difference two datetime objects,3 yes use python multiprocessing module note multiprocessing fight gil work simultaneously everything give on hand warning multiprocessing module spawn process completely separate python interpreter so os controlled thread it entirely different process this add overhead programs advantage completely dodging gil makes mild issue,i trying run method infinite loop create video display this method called within another loop handles hardware input cannot loop fast video causing lag i use outer loop run video is way start video loop start hardware loop run separately currently i call video loop sits loop returns,1 just enable developer mode get access shell,i would like use samsung chromebook develop app engine using python unfortunately possible i browser there online ide like codule good enough yet so regards i questions is way hack chrome os pull native linux is way install second os chromebook i new samsung chromebook first one is chrome os extension help programming python app engine,3 if list key value key value turn dict thatdict dictthatlist then unpack setdefaults ie parsersetdefaultthatdict,i trying use argumentparsersetdefaults argparse i want keyworded tuple like parsersetdefaultsbar baz badger i item output configparseritems baz badger how i convert keyworded tuple setdefaults expecting,1 after hours researching exact problem i found solution it nothing pythoncom wincom fact apache running service the solution found httpsocialmsdnmicrosoftcomforumseninnovateonofficethreadbacedbbafef the solution consists simply making one folder giving write permissions relevant apache user bit windows create folder cwindowssyswowconfigsystemprofiledesktop bit windows create folder cwindowssystemconfigsystemprofiledesktop,i problem opening excel document web application running apachemodwsgiwindows server problem application running django developer server one thread my code def myviewrequest import pythoncom wincomclient import dispatchex pythoncomcoinitializeexpythoncomcoinitmultithreaded xl wincomclientdynamicdispatch excelapplication xldisplayalerts false xlvisible doc xlworkbooksopencpathtofilexlsx docsaved true wbclosesavechanges xlquit pythoncomcouninitialize error message exception occurred u microsoft office excel umicrosoft office excel cannot access file cpathto filexlsx there several possible reasons the file name path exist the file used another program the workbook trying save name currently open workbook u cprogram files xmicrosoft officeoffice xlmainchm none i know problem localized somewhere threading i using pythoncomcoinitializeexpythoncomcoinitmultithreaded maybe changing server solve problem libs django apache modwsgi wincom latest i hope somebody help thank you regards,2 i problem have looked sentry codebase found place throws line webviewspy it happens else clause checks header httpauthorization to get passed i add wsgipassauthorization on apache conf i think else clause i mention must bug handled,i get following error sentry client tries logging error unable reach sentry log server http error bad request url httplocalhostsentrystore body missing data traceback recent call last file homedeployenvlibpythonsitepackagessentryclientbasepy line send return selfsendremoteurlurl datamessage headersheaders file homedeployenvlibpythonsitepackagessentryclientbasepy line sendremote response urlliburlopenreq dataread file usrlibpythonurllibpy line urlopen return openeropenurl data timeout file usrlibpythonurllibpy line open response methreq response file usrlibpythonurllibpy line httpresponse http request response code msg hdrs file usrlibpythonurllibpy line error return selfcallchainargs file usrlibpythonurllibpy line callchain result funcargs file usrlibpythonurllibpy line httperrordefault raise httperrorreqgetfullurl code msg hdrs fp httperror http error bad request http the error trying log get saved server thank,1 this valid yaml superset json use pyyaml parse orange apple lemon import yaml yamlloads orange lemon apple more since tab space inside string better remove parsing yaml ssreplace otherwise string cannot parsed,i received output likes orange apple lemon i know standard json format still possible parse python dictionary type is must orange apple lemon must quoted thanks,3 you need typecast cleaneddataget quantity int django topython method form base class all forms try convert values python values part validation process i see anything cleanquantity method would make think work although showing stock class see type field stockquantity my advice would write unit test form view method ensure getting correct values httpsdocsdjangoprojectcomentopicstesting if habit writing unit tests great time start they really save lot time,model modelform django project defined like class consumptionmodelsmodel datemodelsdatetimefielddefaultdatetimenow productnamemodelsforeignkeystocktofield productname quantitymodelsintegerfield customermodelscharfieldmaxlengthnulltrueblanktrue def unicodeself return selfproductname class consumptionformmodelform class meta modelconsumption def cleanquantityself cleaneddataselfcleaneddata productcleaneddatagetproductname quantityintcleaneddataget quantity stockstockobjectsgetproductnameproduct quantity stockquantity raise formsvalidationerrornot enough stock return cleaneddata stock class contains product name serves foreign key consumption whose quantity greater consumption quantity now problem i enter submit consumptionform it gives error quantity field field must integer even i providing integer what reason,1 from i understand virtualenv enables separate library installation paths effectively separate virtual python installations java concept systemwide installed library it always searches classpath libraries loaded since classpath needs defined application application pickandchoose libraries versions wants load if go one level deeper single application somehow needs two different versions library time even classpath trickery it get complicated definitely possible osgi one example supported even tomcat two separate webapplications i seens references security virtualenv description java pretty thorough security system built in server applications often turned easier configure way easily configure exactly java application allowed almost extensions extension libraries used lot even easily loaded arbitrary directories,is anything similar python virtualenv java jvm languages,3 you returning whole cleaneddata dictionary cleanquantity method rather value quantity,model modelform django project defined like class consumptionmodelsmodel datemodelsdatetimefielddefaultdatetimenow productnamemodelsforeignkeystocktofield productname quantitymodelsintegerfield customermodelscharfieldmaxlengthnulltrueblanktrue def unicodeself return selfproductname class consumptionformmodelform class meta modelconsumption def cleanquantityself cleaneddataselfcleaneddata productcleaneddatagetproductname quantityintcleaneddataget quantity stockstockobjectsgetproductnameproduct quantity stockquantity raise formsvalidationerrornot enough stock return cleaneddata stock class contains product name serves foreign key consumption whose quantity greater consumption quantity now problem i enter submit consumptionform it gives error quantity field field must integer even i providing integer what reason,2 i solved problem similarly fabriziom suggested one notable difference since menu item presentation time contain html i want mess around html markup directly present methods so i ended implementing menu definitions python presentation jinja mutual recursion bridging gap different types menu items represented different subclasses class menuitemobject def presentself macromap return macromaptypeselfnameself macromap class textlinkmenuitem def initself url text selfurl selftext url text class sectionmenuitem def initself text items selftext selfitems text items class imagelinkmenuitem the macromap referenced dict mapping type menu item macro implementing represenation it defined jinja macro textlinkl macromap classmenuitem hreflurlescape ltextescape endmacro macro sections macromap div classheadingstextdiv ul classitems item sitems li itempresentmacromap li endfor ul endmacro set defaultmap textlink textlink section section the actual menu definitions cleanly expressed trees menuitem subclasses mainmenu sectionmain menu sectionproduct line textlinkproducts a product section to kick presentation template call top level section present method passing macro map specify present menu eg mainmenupresentdefaultmap as best seen section macro menu items ask children present whose present method call yet another jinja macro recursively having explicitly pass around macro map pretty grants valuable benefit one easily render different representations menu data without touching menu definitions for example macro maps may defined render main website menu variant mobile devices case css suffice xml sitemap even plain text version we actually ended using system website menu sitemap cases,i looking way jinja macro calls different implementations depending type object passed basically standard python method polymorphism right i using ugly workaround similar macro menuitemobj set type objclassname type imagemenuitem imagemenuitemobj elif type foobarmenuitem foobarmenuitemobj else textmenuitemobj endif endmacro in pure python one muck around module environment eg globalsx menuitem pretty works well i tried something similar using jinja context latter seem contain macro definitions what better ways achieve i seeking,1 it means methodattribute returned none tried access nodevalue attribute either algorithm wrong need test none accessing attribute sorry i help i never used library,i using ksoap communicate android app python server containing following files posted i trying retrieve values xml file posted but keep getting attributeerror nonetype object attribute nodevalue can anyone tell wrong code i tried debug error still failed portion xml file macfilterlist map node empty profilelist profile profilenamelabprofilename owneradminowner maplabmap visibletruevisible macfilterlist stringbffdastring stringbffdstring stringbffdstring stringbffdstring macfilterlist profile profilelist soapapipy profilexml refers filename xml file def initself selfprofilefile configprofilexml selfprofile xmlprofiledatastore selfprofileloadxmlfileselfprofilefile def getallprofiledataself selfprofilefile configprofilexml selfprofileloadxmlfileselfprofilefile result selfprofilegetallprofiledata return result profiledatapy class xmlprofiledatastore def getallprofiledataself get node list containing nodes name location profilelist selfxmldocgetelementsbytagname profile numargcheck profiles for location node list profilenode profilelist for child nodes location node compare xy coordinates childnode profilenodechildnodes if child node profile name profilename cmpchildnodenodename profilename numargcheck profiles profiles childnodefirstchilddata childnode childnodenextsibling profiles profiles childnodefirstchildnodevalue childnode childnodenextsibling profiles profiles childnodefirstchildnodevalue childnode childnodenextsibling profiles profiles childnodefirstchildnodevalue childnode childnodenextsibling child childnodechildnodes profiles profiles childfirstchildnodevalue profiles profiles return profiles,1 jumping kelketek answer i remember i read basically python garbage collector runs occasionally guarantees given object collected the flush function httpdocspythonorglibrarystdtypeshtmlfileflush what i gathered flush puts data buffer writing os decide probably one problem were reading file soon writing that could cause race condition httpenwikipediaorgwikiracecondition class generally weird possibly randomhardtoreproduce bugs normally expect highlevel language like python,i tried different ways result always seems i get python read end file it stops halfway i tried binary ascii modes result i also checked special characters file cuts none additionally i tried specifying much read still cuts place it goes something like fopenarchivesarchivelog r logtextfread print logtext it happens whether i call bash python whether i normal user root however works fine file directory i fopenarchivelog r logtextfread print logtext this works like dream any idea,1 i new django attempt in modelspy need override flatpage model provide meta class something like djangocontribflatpagesmodels import flatpage class myflatpageflatpage class meta verbosename static page overridden name this sets name model appear admin you register appear admin myappmodels import myflatpage djangocontribflatpagesmodels import flatpage adminsiteunregisterflatpage adminsiteregistermyflatpage adminmodeladmin you set again someone may able chime better answer i still learning,am pretty new django trying make use flatpage module one site going create i able setup everything admin user create page using flatpage module problem i want change flatpages name thats displayed admin dashboard something sensible end user for example name like manage static pages something like from documents i could understand meta class one need use change label sure use use please help thanks,1 an alternative datetimedatetimestrptime would pythondateutil libray dateutil allow thing without explicit formatting step dateutil import parser dateobj parserparse date datetimedatetime it standard library module handy parsing date time strings especially control format come one caveat install library version python version python easyinstall pip default installing version explicitly indicate pythondateutil using python,i string field like i need convert datetime object python i calculate difference two datetime objects,2 from department dirty hacks this process solved problem hardly elegant remove migrations affected app rm mainappmigrations remove modelspy replace empty file mv mainappmodelspy rm mainapppyc touch mainappmodelspy generate initial migration nothing python managepy schemamigration mainapp initial apply python managepy migrate mainapp restore ones models generate migration recreate everything rm mainappmodelspy mv modelspy mainapp python managepy schemamigration mainapp auto before running new migration edit comment changes really new changes alternatively run fail tables actually exist comment everything apply migration put south something like normal state perform changes followed recommended course step python managepy migrate mainapp better cleaner suggestions welcome indications else approach might break,i using south generate apply migrations rather managing unfortunately south refusing actually anything transcript graffiastestingtustincommercialcomoneclickcos python managepy schemamigration mainapp auto you cannot use auto app migrations try initial graffiastestingtustincommercialcomoneclickcos python managepy schemamigration mainapp initial added model mainappcompanyuk added model mainappcompanyname added model mainappindividual added model mainappdirector added model mainappdirectorsindividual added model mainappdirectorscorporate added model mainappsharecapitalclass added model mainappmember added model mainappmembersindividual added model mainappmembergeneric added model mainappcompanymanager added model mainapppendingregistration added model mainapppendingauthorisation created initialpy you apply migration managepy migrate mainapp graffiastestingtustincommercialcomoneclickcos python managepy migrate mainapp running migrations mainapp nothing migrate loading initial data mainapp no fixtures found graffiastestingtustincommercialcomoneclickcos as see south thinks nothing however last three models completely new table database is anything i short zapping database get south working i intention manually writing migrations rest project would help i would write one migration,1 the downloadcache option want pip install downloadcachepthtodownloadedfiles package however i tested main package downloaded saved installed ok dependencies saved full url path name bit annoying targz files the download option downloads main package dependencies install note prior version download option download dependencies pip install package downloadpthtodownloadedfiles the pip documentation outlines using download fast amp local installs,if i want use pip command download package dependencies keep zipped files get downloaded say djangosocialregistrationtargz way i tried various commandline options always seems unpack delete zipfile gets zipfile original package dependencies,3 something may almost exactly want twistedinternettestreactormixinsreactorbuilder you see used testtcp example,i one python module defines set base classes another python module implements the core python module also test cases test base classes correctly implemented in second module test suite i would like automatically generate testcase subclasses first module adding mixin necessary setup specific implementation i see lots answers parametrizing test cases case i want reuse common classes subclass it ok needs code parent test module instantiate long names tests differently runs automatically if matters code using twisted trial standard unittest,2 this referred database migration sqlalchemy support migration box you look using sqlalchemymigrate help kinds situations alter table chosen database command line utility,i made table using sqlalchemy forgot add column i basically want usersaddcolumn userid foreignkey usersuserid what syntax i find docs,3 just general remark i familiar python i would suggest make sure easily exchange slow parts reference implementation optimized parts eg use something like strategy pattern this allow crossvalidate results sophisticated algorithms ensure mess results keep overall structure simulation algorithm clear separation concerns you place optimized algorithms separate source files folders packages document separately much detail necessary apart try avoid usual traps premature optimization check actually worth eg profiler reinvent wheel look available libraries,i writing scientific program python c complex physical simulation algorithms after implementing algorithm i found lot possible optimizations improve performance common ones precalculating values getting calculations cycle replacing simple matrix algorithms complex but arises problem unoptimized algorithm much slower logic connection theory look much clearer readable also harder extend modify optimized algorithm so question techniques i use keep readability improving performance now i trying keep fast clear branches develop parallel maybe better methods,3 yours good question arises almost every piece code however simple complex written programmer wants call pro i try remember keep mind reader newly come code pretty much crude view problem straightforward maybe brute force approach i originally then i get deeper understanding problem paths solution become clearer i try write comments reflect better understanding i sometimes succeed comments help readers especially help i come back code six weeks later my style write plenty comments anyway i sudden insight gets excited i want see run brain fried i almost always greatly regret later it would great i could maintain two parallel code streams naã¯ve way sophisticated optimized way but i never succeeded to bottom line i write clear complete succinct accurate uptodate comments best i just one thing know already optimization usually mean shoehorning ton code onto one source line perhaps calling function whose argument another function whose argument another function whose argument yet another function i know avoid storing function value temporarily but little usually nothing speed code bitch follow no news i know,i writing scientific program python c complex physical simulation algorithms after implementing algorithm i found lot possible optimizations improve performance common ones precalculating values getting calculations cycle replacing simple matrix algorithms complex but arises problem unoptimized algorithm much slower logic connection theory look much clearer readable also harder extend modify optimized algorithm so question techniques i use keep readability improving performance now i trying keep fast clear branches develop parallel maybe better methods,2 listsort sorts list place ie return new list just write newlistsort return newlist,purpose accept file name print unique words alphabetically problem the file runs i able verify finduniquewords result sorted list however return list main method i seem find any ideas thanks lee def finduniquewordsthelist newlist words read line time item thelist remove punctuation line cleaned cleanupitem split line separate words words cleanedsplit evaluate word word words count unique word word newlist newlistappendword answer newlistsort return answer def cleanupphrase item strphrasereplace item stritemreplace item stritemreplace item stritemreplace item stritemreplacen return item def main filename rawinputenter filename list openfilename r finallist finduniquewordslist print finallist main,3 the problem answer newlistsort sort return sorted list rather sorts list place use answer sortednewlist,purpose accept file name print unique words alphabetically problem the file runs i able verify finduniquewords result sorted list however return list main method i seem find any ideas thanks lee def finduniquewordsthelist newlist words read line time item thelist remove punctuation line cleaned cleanupitem split line separate words words cleanedsplit evaluate word word words count unique word word newlist newlistappendword answer newlistsort return answer def cleanupphrase item strphrasereplace item stritemreplace item stritemreplace item stritemreplace item stritemreplacen return item def main filename rawinputenter filename list openfilename r finallist finduniquewordslist print finallist main,3 favourite rawinput joinanimals this take strings list animals join together end lion tiger fish want add question mark space end favourite rawinput joinanimals also line favourite lion your quotes match make sure use either double single quotes one you also need use compare two things assigning value comparing i would probably like animalstring joinanimals favourite rawinputwhich animals favouriten formatanimalstring which first makes animal string formats choices question new line n puts,hi i starting learn python i using book learn python hard way one exercises build simple game i wanted give options user list for example i would make list called animals would include animals lion tiger fish possible offer selected elements list i pretty sure i know i thinking something like obviously wrong i think helps understand i mean animals lion tiger fish print animals favourite favourite rawinputanimals animals favourite lion print nice choice else print bad choice again i stress enough i know really crap essentially i want offer certain items list option rawinput in case item item thanks advance help,2 how favourite rawinputwhich animals favourite joinstrab ab enumerateanimals fav animalsintfavourite print fav nice choice indeed the big bear kill anyway good bye,hi i starting learn python i using book learn python hard way one exercises build simple game i wanted give options user list for example i would make list called animals would include animals lion tiger fish possible offer selected elements list i pretty sure i know i thinking something like obviously wrong i think helps understand i mean animals lion tiger fish print animals favourite favourite rawinputanimals animals favourite lion print nice choice else print bad choice again i stress enough i know really crap essentially i want offer certain items list option rawinput in case item item thanks advance help,1 when binding tkinter automatically adds argument information event you need account either randfunc definition call here one solution import tkinter tk class sampleapptktk def initself args kwargs tktkinitself args kwargs selfframe tkframeself selfframepack selfbutton tkbuttonselfframe textclick commandlambda b c selfrandfunca b c selfbuttonpack selfframebindreturn lambda event b c selfrandfunca b c make sure frame focus binding work selfframefocusset def randfuncself b c print self self b b c c print abc app sampleapp appmainloop that said rare binding frame right thing typically frame keyboard focus unless focus binding never fire if setting global binding either bind binding tag using bindall method toplevel widget,i tkinter frame button attached tkinter import def randfuncabceffects print abc roottk frameframeroot framebindreturnlambda b c randfuncabc framepack buttonbuttonframe textclick commandlambda abceffnonerandfuncabc buttonpack rootmainloop i want function done user presses enter presses button sadly code gives error frame binding does anyone know solution problem,3 i guess got trouble starting managepy converttosouth mainapp maybe correct make south believe perform first migration go zero managepy migrate fake mainapp zero migrate real first migration managepy migrate mainapp but i make question already models database made without south otherwise use initial if probably complain columns already existing you change situation wiping first schemamigration deleting mainappmigrationsinitialpy you need fiddle south database table directly deleteghostmigrations take care managepy syncdb south expects database sync models managepy converttosouth mainapp actually let south handle database migrations managepy migrate deleteghostmigrations mainapp move first migration deleting old first migration deleted migrations database,i using south generate apply migrations rather managing unfortunately south refusing actually anything transcript graffiastestingtustincommercialcomoneclickcos python managepy schemamigration mainapp auto you cannot use auto app migrations try initial graffiastestingtustincommercialcomoneclickcos python managepy schemamigration mainapp initial added model mainappcompanyuk added model mainappcompanyname added model mainappindividual added model mainappdirector added model mainappdirectorsindividual added model mainappdirectorscorporate added model mainappsharecapitalclass added model mainappmember added model mainappmembersindividual added model mainappmembergeneric added model mainappcompanymanager added model mainapppendingregistration added model mainapppendingauthorisation created initialpy you apply migration managepy migrate mainapp graffiastestingtustincommercialcomoneclickcos python managepy migrate mainapp running migrations mainapp nothing migrate loading initial data mainapp no fixtures found graffiastestingtustincommercialcomoneclickcos as see south thinks nothing however last three models completely new table database is anything i short zapping database get south working i intention manually writing migrations rest project would help i would write one migration,3 i would argue create symlinks like especially going distribute python code assume user python python usrbinpython if script requires python use usrbinenv python if script requires python use usrbinenv python this way scripts work fine even updates python it also much clear version script actually needs,so i read httpswikiarchlinuxorgindexphppython and clear wiki i install python via pacman s python is reasonable create symlink python ln python usrbinpython i forsee switching python time soon or better way managing multiple python versions like i usually use debian system updatealternatives config python mac os x system python select clarification what i trying find best practice managing various python versions archlinux system i new archlinux familiar ubuntu debian mac os x,3 python habitually returns none functions methods mutate data listsort listappend randomshuffle idea hints fact mutating if want take iterable return new sorted list items use sorted builtin function,purpose accept file name print unique words alphabetically problem the file runs i able verify finduniquewords result sorted list however return list main method i seem find any ideas thanks lee def finduniquewordsthelist newlist words read line time item thelist remove punctuation line cleaned cleanupitem split line separate words words cleanedsplit evaluate word word words count unique word word newlist newlistappendword answer newlistsort return answer def cleanupphrase item strphrasereplace item stritemreplace item stritemreplace item stritemreplace item stritemreplacen return item def main filename rawinputenter filename list openfilename r finallist finduniquewordslist print finallist main,3 you forgot sorting requirement edit apparently set sorts elements ascending order probably implementation detail if asked write function test maybe required implement whole thing instead delegating set edit for completeness implementation meet requirements def commonelementsa common x x commonappendx commonsort return tuplecommon,write function commonelementsa takes tuples arguments returns sorted tuple containing elements found tuples my task commonelements commonelements p n p p commonelements p n p p i tried like def commonelementsa return tuplesetaintersection seta anyone know mistake requirement i pass,2 using urllib make everything easier import urllib request urllibrequest httpmapsgooglecommapsfeedsmapsdefaultfull requestaddheader authorization googlelogin auths authorizationtoken urlliburlopenrequestread btw google maps data api deprecated httpgooglegeodevelopersblogspotcommapsdataapideprecationannouncementhtml,i trying get list maps created google maps maps api says following retrieving list maps the maps data api provides feed lists maps created particular user feed known metafeed a typical maps data api metafeed get request following form the default feed requests maps associated authenticated user get httpmapsgooglecommapsfeedsmapsdefaultfull authorization googlelogin authauthorizationtoken the standard metafeed requests maps associated associated userid get httpmapsgooglecommapsfeedsmapsuseridfull authorization googlelogin authauthorizationtoken note get requests require authorization http header passing authsub googlelogin token depending authentication scheme implemented the googlelogin token corresponds clientlogin authentication process i idea create http request authorization http headers i already code get authorizationtoken follows coding utf import urllib getpass httpcodegooglecomintlptbrapismapsdocumentationmapsdatadevelopersguideprotocolhtmlclientlogin username heltonbiker senha getpassgetpass senha usuã¡rio username dic accounttype google email username gmailcom passwd senha service local source heltonmapper url httpswwwgooglecomaccountsclientlogin urlliburlencodedic output urlliburlopenurlread authid outputstripsplit n split i also took look httplib docs understand much i professional programmer any clue,3 set ordered so order result may arbitrary i would come something like def commonelementsa l el el lappendel return tuplel please note way solving problem would get output elements ordered tuple so mentioned comments correct way call ordering sorting also complexity onm n lengths lists respectively onlogm achieved case bisect module used access elements second tuple sorted proceeding if sorting common way required i would stick code bit altered def commonelementsa return tuplesortedsetaintersectionseta on average complexity ominmnlogminnm sorting onm worst case intersection if code needs implemented without using set example purposes study code def commonelementsa l el el lappendel lsort return tuplel complexity onm with using bisect code would look way bisect import bisectleft def commonelementsa l asort sort able use binary search internal loop thus changing complexity on onlogn assuming n rather equal alen lena el bisectlefta el alen ai el lappendx lsort uncomment line list sorted order needed ordered first lits possible sort beginning function would slower average since l smaller average since l intersection return tuplel complexity onlogm,write function commonelementsa takes tuples arguments returns sorted tuple containing elements found tuples my task commonelements commonelements p n p p commonelements p n p p i tried like def commonelementsa return tuplesetaintersection seta anyone know mistake requirement i pass,2 def commonelementsa return tuplesortedsetaintersection seta,write function commonelementsa takes tuples arguments returns sorted tuple containing elements found tuples my task commonelements commonelements p n p p commonelements p n p p i tried like def commonelementsa return tuplesetaintersection seta anyone know mistake requirement i pass,2 ok question open i answer unless i missing something br variants replace br amplt br ampgt in python looks like means text resub br amplt text text resub br ampgt text to explain going negative lookahead successfully matches position following text match subexpression contains note lookaheads consume text matched subexpression verify exists similarly negative look behind thing using preceding text however lookbehinds slight different lookaheads regex implementations subexpressions inside lookbehinds must represent fixedwidth limitedwidth matches python one ones requires fixed width whilst expression works always four characters brs would valid regex python represents variable length match however stack multiple lookbehinds could potentially manually iterate assorted options necessary,i able regex i looking syntax exclude something i parsing amp html code replace amplt etc i need exclude br parsing ie htmlbr headtitletitleheadbr bodybr bodybr html i tried sometihng like ie r bbr others work completely i use resub replace,1 fname argv openfname reader csvreaderi firstrow nextreader currow reader outname currow openoutname wb writer csvwritero writerwriterowfirstrow writerwriterowcurrow hope helps,i trying solve following problem using python i table csv i want extract consecutively row row row etc the extracts saved csv file named according first string nd row extracted now question python right tool example code available thanks lot advance help amp hints claude s clarification thanks feedback actually i trying use csv module open read table using code import csv import sys f opensysargv rt try reader csvreaderf row reader print row now i sure select write required rows sorry beginners kind question claude s,1 your program suggests entrybodyfat variables generated fly want the normal approach store entries labels list map tkinter import root tk names weight bodyfat hydration muscle bones entry label name names e entryroot egridstickye entryname e lb labelroot textname lbgridrowi column labelname lb def printallentries name names print entrynameget b buttonroot textprint commandprintallentries bgridstickys mainloop the value bodyfat entry entrybodyfatget,i want create simple gui i enter values a label button start script i using something like w labelmaster textweight wgridstickye w labelroot textbodyfathydrationmusclebones wgridstickye w labelroot texthydration wgridstickye ok want dynamic also would use w entrys could cast wget need data thinking def createwidgetsself lweightbodyfathydrationmusclebones lv index rangelenl printindex printlindex entrylindex entryroot entrylindexgridstickye labellindexlabelroot textlindex labellindexgridrowindex column to call later varweightentryweightget varbodyfatentrybodyfatget make work,2 then create container class named tuple tuple whatever pickle modify original class parts want pickled pickle serialisation standard python mechanism so unless need eg interoperability different languages stick,i python class contains many objects data structures lists dicts etc handlers classes also contain data structures rather using pickle save entire class amp contents i wondering way serialize data several desired objects save only binary file for example suppose i following python objects mylist mydict b c what best way save contents both python objects binary file ideally i like save objects binary file able load data later,3 you write file system changing fakefileallowedmodes flags googleappenginetools import devappserver allowedmodes devappserverfakefileallowedmodes devappserverfakefileallowedmodes frozenset w f open testtxt w fwrite test fclose devappserverfakefileallowedmodes allowedmodes,what easiest way restore original builtin openfile function appengine devappserver i need get working assets manager development environment compiling multiple jscss files,2 i solution yet something interesting python i realized python used convenient tool notation algorithms basically i wrote program similar started transforming program logically leave results unchanged i came def orderxy xy return xy else return yx n numset n range n rangenn b rangenn ab continue numaddorderanbn orderbnan printn lennum obviously brute force even simple loop feasible maybe algorithm one find closed form expression point if set character num would doable maybe one find duplicate point way this could dead end still pretty cool python used notation work algorithms any progress side,i stuck project euler problem here i done far let denote rectangle width height x respectively xy to form new rectangles consider cutting kind stairway diagonal shown problem description steps but form new rectangle following must hold dx either dy dy the new rectangle becomes either xdd ydd xdd ydd obviously new rectangles area old rectangle that enough confirm g g looping relevant adding new rectangles set careful count xy yx the main issue method possible make new rectangle two different ways for example transform either dividing or another example transforms respectively i lucky enough read blog post it removes need check duplicates searching one sides instead def fw h wamp hamp return wh wh hw r x x wh whx xh x continue wwx xxh r x return r def gn w range n h range w fwh return g would require far long solve regardless fast f though i think necessary either use kind sieving algorithm loop x counting many wh satisfy h w xwh x h wxw xhx i think on algorithm must possible i stuck edit i access forum since i unable solve that i asking help i completed questions want tackle question edit i think considering areas prime factors dead end that different areas rectangles prime areas solutions rectangles semiprime areas solution one primes otherwise solutions but counting semiprime solutions alone would take long since need count primes p p feasible edit i stripped code def gn x range n h range n xh continue w rangemaxh xh n whx xwx xxh x range n h range n xh continue w rangemaxh xh n whx wwx x range n h range n xh continue w rangemaxh xh n whx hxh return i think breaking bruteforce code work though remember enough count solutions x w h three subproblems the last summation would constraints x n h n xh maxh x h w n xwh xhh i think start assumption prime p divides x w h even xh see deduce variables if works well maybe consider p k arbitrary k,1 if use dateutil gae in import dateutilparser parser in parserparse sunday st july pm fuzzytrue out datetimedatetime otherwise rely manipulate date string format strptime parse in datetimedatetimestrptimeresubr w dw ofs r sunday st july pm b y ims p out datetimedatetime,i new python i need migrate project php python running gae environment i need move data one database gae one the chellenge write data strings datetime objects dates stored strings created using php pattern l ds f y a so every date looks like sunday st july pm i looked python documentation i see datetimestrptime job it parameter th rd st endings and may issues well what could advise i use regexp remove unneccessary crap way create datetime object string directly thank advance,2 basically sort string first get ackz use regex like ckz match,for example characters match czk string zack matches string zak does match i tried ckz ckz obviously wrong i feel simple task unable find answer,1 it common assume must give readability get performance that necessarily you need find what exactly spending much time notice i say need measuring here example i mean chances good simple changes avoid waste motion fix anything program told fix,i writing scientific program python c complex physical simulation algorithms after implementing algorithm i found lot possible optimizations improve performance common ones precalculating values getting calculations cycle replacing simple matrix algorithms complex but arises problem unoptimized algorithm much slower logic connection theory look much clearer readable also harder extend modify optimized algorithm so question techniques i use keep readability improving performance now i trying keep fast clear branches develop parallel maybe better methods,2 def whatyoushoulddoservings integrationmethodoven make chicken soup comments they important with syntax highlighting comments first thing new programmer look therefore motivate algorithm outline break stages you make it feel as if you are reading text interspersing code amongst text algorithm overview to make chicken soup acquire chicken broth noodles preprocessing ingredients done optimize cooking time then output soup format via stdout begin algorithm preprocessing thaw chicken broth broth chickenstoredeserialize mix noodles noodles cache begintransactionlocalspoulty cachenoodles tbuynoodles get local store noodles cachenoodles perform thorder rungekutta numerical integration import kitchensink import fixme poor form better kitchensink import pan beginning result boilerplaterkbroth semidirectproduct noodles serve hot logdebug attempting serve return result logdebug server successful also see httpenwikipediaorgwikiliterateprogrammingexample i also heard httpenwikipediaorgwikiaspectorientedprogramming attempts help though i really looked it seems fancy way saying put optimizations debugs junk outside function writing,i writing scientific program python c complex physical simulation algorithms after implementing algorithm i found lot possible optimizations improve performance common ones precalculating values getting calculations cycle replacing simple matrix algorithms complex but arises problem unoptimized algorithm much slower logic connection theory look much clearer readable also harder extend modify optimized algorithm so question techniques i use keep readability improving performance now i trying keep fast clear branches develop parallel maybe better methods,1 to modify existing list use list assignment eg l b c e f l b print l b c e f i would usually prefer create new list using comprehension eg key newvalue x key else x x l but first comment already mentioned sounds like trying make list something really using dict instead,i list tuples l b c e f and two parameters key value new value modify for example key newvalue b means modify b value tuples i two options works f lambda tkv k kv newlist ftkeynewvalue l print newlist newlist rangelenl elem lpop elem key newlistappendkeynewvalue else newlistappendelem print newlist but new python know right can help thank,1 to create new list list comprehension would in key b key else val keyval l out b c e f to modify list place l b c e f ielt enumeratel keyvalelt key likey b printl b c e f,i list tuples l b c e f and two parameters key value new value modify for example key newvalue b means modify b value tuples i two options works f lambda tkv k kv newlist ftkeynewvalue l print newlist newlist rangelenl elem lpop elem key newlistappendkeynewvalue else newlistappendelem print newlist but new python know right can help thank,2 here approach i would use l b c e f key newvalue b pos index index k v enumeratel k key lpos key newvalue break else lappendkey newvalue l b c e f this looks awful lot like ordereddict though keyvalue pairs preserved ordering you might want take look see suits needs edit replaced try except stopiteration break else since might look bit less weird,i list tuples l b c e f and two parameters key value new value modify for example key newvalue b means modify b value tuples i two options works f lambda tkv k kv newlist ftkeynewvalue l print newlist newlist rangelenl elem lpop elem key newlistappendkeynewvalue else newlistappendelem print newlist but new python know right can help thank,1 here one solution involving altering items inplace def replacelist key newvalue currentkey currentvalue enumeratelist currentkey key listi key newvalue or append def replaceorappendlist key newvalue currentkey currentvalue enumeratelist currentkey key listi key newvalue break else listappendkey newvalue usage mylist b c replacemylist b mylist b c if want create new list list comprehension easiest mylist b c findkey newvalue b newlist key newvalue key findkey else value key value mylist newlist b c and wanted append lennewlist lenmylist newlistappendfindkey newvalue note also i changed variable name l l easily confused i best avoided thus saith pep i agree,i list tuples l b c e f and two parameters key value new value modify for example key newvalue b means modify b value tuples i two options works f lambda tkv k kv newlist ftkeynewvalue l print newlist newlist rangelenl elem lpop elem key newlistappendkeynewvalue else newlistappendelem print newlist but new python know right can help thank,2 the natural way would probably use sets rather regex like set czk issubsets code often simpler easier maintain without using regex much,for example characters match czk string zack matches string zak does match i tried ckz ckz obviously wrong i feel simple task unable find answer,2 x xchopped intx x intx,x x xintx ok x want round say use later way dont know x time real place start even possible know change int want store ever took store right id write statments figure say doent strike best way,1 if ntop installed look example files usrsharentoppython ubuntu package version least if epydoc installed run make within usrsharentoppythondocs directory generate documentation once about online documentation python ntop engine python api link work correctly seems like bug requires work part user fix link,can anyone point towards tutorials using python api ntop luca deris paper in web interfaces online documentation python engine i think link error does anyone access document repost online,2 one fell swoop divmod the docs divmod found,x x xintx ok x want round say use later way dont know x time real place start even possible know change int want store ever took store right id write statments figure say doent strike best way,3 you correct height attribute change that attribute tell actual height height configured the actual height depends factors much text wrap length font widget geometry managed tkinter font objects measure method lets determine tall wide string given font you get font widget use method determine much space required string,i label i going put content different sizes i would like know high i need make label i size window stay different content sizes i strategy seems complicated i want set label given width wraplength l labelroot l width l wraplength l text testing now i want query label find many lines used l height stays best i able come use lwinfoheight convert height given pixels number lines used nothing dirl seems give information directly strategy fragile font changes changes any suggestions update using brian oakley suggestion similar i got usenet i following approximation solution needs polishing eg take account label breaks whitespace import tkinter tk import tkfont import random import sys def genstr j rno randomrandint retval strj range rno retval hello stri return retval def gendata lh retval rangelh retvalappend genstr return retval data gendata root tktk font tkfontfontfamily times size class lines def init self selflastct remember cutoff last work def count self text cutoff global font nolines startidx idx selflastct true idx len text idx len text shrink guessed value fontmeasure textstartidxidx cutoff idx startidx print error sysexit else idx selflastct idx startidx adjust since big increase guessed value note first shrunk done idx len text fontmeasure textstartidxidx cutoff idx selflastct idx startidx adjust since small next line determined print textstartidxidx idx lentext fontmeasure textstartidx cutoff return nolines elif idx lentext return nolines else nolines startidx idx idx startidx selflastct lin lines rangelendata lincountdatai rangeminlendata l tklabelroot lpack l text datai print lincount datai print computed lines l width l justify tkleft l anchor w l wraplength l padx l pady l height l font font l background grey else l background grey rootmainloop,1 take number modulus,x x xintx ok x want round say use later way dont know x time real place start even possible know change int want store ever took store right id write statments figure say doent strike best way,1 yes exact way wrote your code fine,for example mymessage dear hello name jj print mymessage name does python feature accomplishing something like code,3 python really concept constant find c so fairly good approach i would actually argue one example consenting adults hold terribly well think language awesome constant every would nice,for example mymessage dear hello name jj print mymessage name does python feature accomplishing something like code,2 your code correct i believe preferred way mymessage dear hello mymessageformat jj dear jj hello preferred possible future replacement operator format method as mentioned mark lutz learning python fourth edition format method features found expression make substitution values explicit trades operator arguably mnemonic method name support different syntax single multiple substitution value cases later book risk python developers may deprecate expression favor format method future in fact note effect python manuals,for example mymessage dear hello name jj print mymessage name does python feature accomplishing something like code,1 yield sucks continuations better actually python yield continuation what continuation a continuation saving present point execution state one continue point later that precisely python yield also precisely implemented it understanding python continuations delimited however i know much i might wrong fact nor i know implications may scala continuation work runtime fact continuations library java work stuff bytecode runtime free constrains scala continuation scala continuation entirely done compile time require quite bit work it also requires code continued prepared compiler and forcomprehensions work a statement like x xs procx if translated xsforeachx procx where foreach method xs class unfortunately xs class long compiled cannot modified supporting continuation as side note also scala continue aside yes duplicate question yes find different way write code,i writing code phd research starting use scala i often text processing i used python whose yield statement extremely useful implementing complex iterators large often irregularly structured text files similar constructs exist languages eg c good reason yes i know previous threads but look like hackedup least badly explained solutions clearly work well often unclear limitations i would like write code something like import generator def yieldvaluesfilestring generate x sourcefromfilefilegetlines scala already using yield keyword givesomething field rsplitx field contains subfield rsplitfield givesubfield else scala continue imo considered bug scala preferred fieldstartswith continue actual need indent following code fieldstartswith val somecalculation stuff somecalculation ampamp fieldstartswithr giver givefieldslice else typically good deal code handle different cases givefield i like see code implements generate give btw give named yield scala taken keyword already i gather reasons i understand scala continuations may work inside statement if generate supply equivalent function works close possible statement iterator code yield almost inevitably sits inside loop please i would prefer get following answers yield sucks continuations better yes general continuations but hella hard understand time iterator want need if scala provides lots powerful tools hard use practice language succeed this duplicate please see comments you rewrite code using streams continuations recursion etc etc please see i also add technically need loops either for matter technically absolutely everything ever need using ski combinators your function long break smaller pieces need yield you production code anyway first need yield doubtful case second production code third text processing like often breaking function smaller pieces especially language forces lacks useful constructs makes code harder understand rewrite code function passed technically yes but result longer iterator chaining iterators much nicer chaining functions in general language force write unnatural style certainly scala creators believe general since provide shitloads syntactic sugar rewrite code way cool awesome way i thought sorry sarcasm previous list typical responses i seen similar scala questions stack overflow thanks help,3 data x data x mathlogy,i looking elegant way something like datai else logdatai xrangelendata so data i want make list fyi output csv file,1 data itertoolschainxlogx x data make list,i looking elegant way something like datai else logdatai xrangelendata so data i want make list fyi output csv file,1 if i understand correctly actually swapping instances class classes instance state kept two possible places slots dict if swap basically swapped instances retaining original name bindings one caveat class cannot immutable must define hash instances already members set keys dictionary would become irretrievable if i think i would swap method class method instead i think would read easier class somebigclass staticmethod def swapdictinstancea instanceb instanceadict instancebdict instancebdict instanceadict classmethod def swapslotcls instancea instanceb values attr clsslots valuesappend attr getattrinstancea attr getattrinstanceb attr attr val val values setattrinstancea attr val setattrinstanceb attr val later somebigclassswapdictthisinstance otherinstance somebigclassswapslotthisinstance otherinstance why if instances bound names consider frubbah somebigclassattrhi mom zikroid somebigclassattr hi dad somebigclassswapdictfrubbah zikroid after swap potentially everything thought knew zikroid changed,i big class lots members quite references instances class lying around unfortunately reasonable reasons references wrong way around instead recreating finding updating everywhere objects referenced adding extra level indirection time i access class individually swapping members i defined method def swapself assertisinstanceother selfclass selfdict otherdict otherdict selfdict i instanceaswapinstanceb references instancea everywhere instancea instanceb the question it seems work fine i use slots feels like might reason i here actual use case i type implements comparison operators necessarily expensive way i various sorted datastructures containing objects type when i something one objects i know comparison order changed order data structures restored swapping modified object next bigger one,3 sumx mathlogx x data,i looking elegant way something like datai else logdatai xrangelendata so data i want make list fyi output csv file,1 the premise question seems want exactly python yield want reasonable suggestions thing different way scala if true important use python it quite nice language unless phd computer science using scala important part dissertation already familiar python really like features design choices use instead anyway actually want learn solve problem scala turns code delimited continuations overkill all need flatmapped iterators here you want write x xs complex yield instead write xsiteratorflatmap produce iterators you want write yielda yieldb instead write iteratorab you want write yielda complex set yields instead write iteratora produce complex iterator that all cases reduced one three in case example would look something like sourcefromfilefilegetlinesflatmapx iteratorsomething rsplitxiteratorflatmapfield field contains rsplitfielditerator else fieldstartswith vals whatever somecalculation ampamp fieldstartswithr iteratorrfieldslice else iteratorfield else iteratorempty ps scala continue done like implemented throwing stackless lightweight exceptions import scalautilcontrolbreaks blah breakable break get want scala yield want,i writing code phd research starting use scala i often text processing i used python whose yield statement extremely useful implementing complex iterators large often irregularly structured text files similar constructs exist languages eg c good reason yes i know previous threads but look like hackedup least badly explained solutions clearly work well often unclear limitations i would like write code something like import generator def yieldvaluesfilestring generate x sourcefromfilefilegetlines scala already using yield keyword givesomething field rsplitx field contains subfield rsplitfield givesubfield else scala continue imo considered bug scala preferred fieldstartswith continue actual need indent following code fieldstartswith val somecalculation stuff somecalculation ampamp fieldstartswithr giver givefieldslice else typically good deal code handle different cases givefield i like see code implements generate give btw give named yield scala taken keyword already i gather reasons i understand scala continuations may work inside statement if generate supply equivalent function works close possible statement iterator code yield almost inevitably sits inside loop please i would prefer get following answers yield sucks continuations better yes general continuations but hella hard understand time iterator want need if scala provides lots powerful tools hard use practice language succeed this duplicate please see comments you rewrite code using streams continuations recursion etc etc please see i also add technically need loops either for matter technically absolutely everything ever need using ski combinators your function long break smaller pieces need yield you production code anyway first need yield doubtful case second production code third text processing like often breaking function smaller pieces especially language forces lacks useful constructs makes code harder understand rewrite code function passed technically yes but result longer iterator chaining iterators much nicer chaining functions in general language force write unnatural style certainly scala creators believe general since provide shitloads syntactic sugar rewrite code way cool awesome way i thought sorry sarcasm previous list typical responses i seen similar scala questions stack overflow thanks help,3 matplotlib python closer may think httpsgithubcommatplotlibmatplotlibpy httpwwwlfduciedugohlkepythonlibsmatplotlib why use pythonstartup instead sitecustomizepy localhost cat startuppy future import printfunction future import division localhost export pythonstartup localhost python python va jun gcc apple inc build dot darwin type help copyright credits license information printfredend file stdin line printfredend syntaxerror invalid syntax d localhost export pythonstartupstartuppy localhost python python va jun gcc apple inc build dot darwin type help copyright credits license information printfredend fred,in python using future import division printfunction i print showing however possible automatically imported python startup i tried use sitecustomizepy special module inport valid inside module shell as i sure people ask i need teaching python teenagers i noticed integer division easy decided switch python however one requirement course able plot function matplotlib pretty good valid python so idea use custom installationnot perfect i better idea matplotlib new natural division any advice maybe matplotlib alternative working python,3 the smtplib prints directly stderr eg line smtplibpy printstderr connect fail host you either monkey patch sysstderr import smtplib smtplibstderr run mail code i might also suggest patching smtplibstderr custom object write method wrap logging code using logging library instance import logging import smtp class stderrloggerobject def initself selflogger logginggetlogger mail def writeself message selfloggerdebugmessage orgstderr smtpstderr smtpstderr stderrlogger smtp stuff smtpstderr orgstderr this question contains useful examples patching stderr context managers,as know python smtplib debug levelwhen i set true param print send information the problem i try get debug info log file they stay cmd console how i log info like connect connect reply esmtp winwebmail ready httpwwwwinwebmailcomrn reply retcode msg esmtp winwebmail ready httpwwwwinw ebmailcom connect esmtp winwebmail ready httpwwwwinwebmailcom send ehlo rn reply sizern reply auth loginrn reply retcode msg size auth login bla bla bla bla,3 no need compile new version python x you start as found sitecustomizepy work this future import identifier import it flags module compiled special rules any module uses features must future import well interactive console the following shell command start interactive console division printfunction active python ic future import division printfunction you could alias python linux set launcher hide extra stuff if using idle pythonstartup script dsm suggests work well note global throughout interpreter affects interactive console modules filesystem must import future explicitly use feature if issue i suggest making template base work needed imports true division future import division modules import matplotlib code def main pass name main main,in python using future import division printfunction i print showing however possible automatically imported python startup i tried use sitecustomizepy special module inport valid inside module shell as i sure people ask i need teaching python teenagers i noticed integer division easy decided switch python however one requirement course able plot function matplotlib pretty good valid python so idea use custom installationnot perfect i better idea matplotlib new natural division any advice maybe matplotlib alternative working python,1 you explicitly say appears using matplotlib i say certain posted i guess happening already bound save figure matplotlib figure and default matplotlib uses tkbased backend thus tk error there need use urwid module matplotlib hooks things like going need disconnect hooks need as simple standalone example reproduce problem import matplotlibpyplot plt import numpy np def saveevent eventkey print saved figure eventcanvasfiguresavefig temppng fig ax pltsubplots aximshownprandomrandom figcanvasmplconnect keypressevent save pltshow notice figure saved also get popup file selection dialogue save figure you avoid either using different key something list b temporarily disabling matplotlib key binding save it pretty easy temporarily disable appropriate matplotlibrc setting import matplotlibpyplot plt import matplotlib mpl import numpy np disable interactive keybinding mplrcparams keymapsave def saveevent eventkey print saved figure eventcanvasfiguresavefig temppng fig ax pltsubplots aximshownprandomrandom figcanvasmplconnect keypressevent save pltshow,i try understand python codes i want select part open image zoom save selected part right trying quickly save open zoom image pressing key for explain better need fire function savefig pressing keyboard key i tried use urwid module import urwid import pil import image imimageopenfigtif imshowim def saveinput input savefigfigpng and i used uinput well try thing import uinput import pil import image def main capabilities uinputevkey uinputkeys device uinputdevicenamepythonuinputkeyboard capabilitiescapabilities deviceemituinputevkey uinputkeys savefigsatpng imimageopenfigtif imshowim and result codes error message appeared exception tkinter callback traceback recent call last file usrlibpythonlibtktkinterpy line call return selffuncargs file usrlibpymodulespythonmatplotlibbackendsbackendtkaggpy line keypress figurecanvasbasekeypresseventself key guieventevent file usrlibpymodulespythonmatplotlibbackendbasespy line keypressevent selfcallbacksprocesss event file usrlibpymodulespythonmatplotlibcbookpy line process funcargs kwargs file usrlibpymodulespythonmatplotlibbackendbasespy line keypress selfcanvastoolbarsavefigureselfcanvastoolbar typeerror savefigure takes exactly argument given it strang never open tkinter please helpâ´me how save zoom image key event i sorry ignorance python new,1 check pyftpdlib giampaolo rodola it one best ftp servers python it used google chromium browser bazaar version control system it complete implementation python rfc aka ftp server implementation spec from commandline python pyftpdlib alternatively myserverpy usrbinenv python pyftpdlib import servers pyftpdlibhandlers import ftphandler address listen every ip machine port server serversftpserveraddress ftphandler serverserveforever there examples website want something complicated to get list command line options python pyftpdlib help note want override use standard ftp port need admin privileges eg sudo,is possible one line command python simple ftp server i like able quick temporary way transfer files linux box without install ftp server preferably way using built python libraries nothing extra install,3 it worked fine fixing two things variable meta metadata nd arg table referred global variable lines createuserstable metadatacreateallengine moved bottom functions called defining as syntax error i guess file got invalid characters last line printed screen my suggestion delete last line retype,i getting maddening syntax error i run following program here error file createthedatabasepy line syntaxerror invalid syntax here code long repetitive easy skim import sqlalchemy sqlalchemy import engine createengine sqliteusersbenscholzdropboxomnicloudomniclouddevdb meta metadata createuserstable createaccountstable createpasswordstable metabind engine metacreateallengine def createuserstable printcreating user table users table users metadata column id integer primarykey true column username string nullable false column emailaddress string nullable false column firstname string column fullname string column joindate datetime def createaccountstable printcreating accounts table accounts table accounts metadata column userid foreignkey usersid column facebookusername string column emailusername string column emailusername string column emailusername string column emailusername string column emailusername string column twitterusername string column twitterusername string column twitterusername string column kloutusername string column dropboxusername string column boxusername string column flickrusername string column flickrusername string column instagramusername string column disqususername string column stackoverflowusername string def createpasswordstable printcreating passwords table passwords table passwords metadata column userid foreignkey usersid column facebookpass string column emailpass string column emailpass string column emailpass string column emailpass string column emailpass string column twitterpass string column twitterpass string column twitterpass string column kloutpass string column dropboxpass string column boxpass string column flickrpass string column flickrpass string column instagrampass string column disquspass string column stackoverflowpass string the program lines long seems get end expect something,1 the string formatting operator also neat things string this foos also foos print string foo bar this bar also bar this really useful repeating one argument sure beats formatstring bar bar you also padding number formatting,for example mymessage dear hello name jj print mymessage name does python feature accomplishing something like code,1 inheriting nothing creates oldstyle class different behaviour newstyle classes i remember specifics see explanation general rule reason favour oldstyle classes always inherit object nothing else,in one past questions answerer suggests better inherit object class want create like scratch need inherit class for example like i always class myclass class inherits nothing def initself pass for suggested class suggestedclassobject class inherits object type def initself pass i confused benefits disadvantage approaches question so idea inherit object type nothing,2 to deal path file names best use builtin module ospath python please look function dirname basename split module,i files i want foo bar left split dn cxdata files f cxdatafootxt f cxdatsbartxt i tried fsplit i thought since dn txt predefined i could subtract nope split work,1 using proper path handling methods os f cxdatafootxt import os ospathbasenamef footxt ospathdirnamef cxdata ospathsplitext f cxdatafoo txt ospathsplitext ospathbasenamef foo txt,i files i want foo bar left split dn cxdata files f cxdatafootxt f cxdatsbartxt i tried fsplit i thought since dn txt predefined i could subtract nope split work,3 being big fan jquery i recommend pyquery offers strong selector like jquery pyquery import pyquery pq dom pqfile yourhtml read print lendom hsectiontitle table h element class name you use id name target class id next adjacent element in case next table element here i added table returns a elements inside table,i would like count urls specific class class h classsectiontitleinsiders at loews corp lh links like hrefresearchstockspeoplerelationshipasppersonidampsymbollus i would like count number kind links class this program i wrote count work headings bsfind h text insiders at loews corp l section headingsfindnext aa sectionfindall href true bbaacount href print bb work would mind giving tip solve issue thank much h classsectiontitleinsiders at loews corp lh table cellpadding cellspacing classtable width stylemarginbottompxtheadtrtdname connectionstdtd colspan stylewidthpxboard relationshipstdtdtitletdtdtype board membertdtd alignrightagetdtrtheadtrtda hrefresearchstockspeoplepersonasppersonidampsymbollus classlinkxsbandrew tisch atdtd stylewidthpx paddingleft pxa hrefresearchstockspeoplerelationshipasppersonidampsymbollusimg srcimagesiconspeoplegif styleverticalalignmiddle atdtd stronga hrefbusinessweekresearchstockspeoplerelationshipasppersonidampsymbollusstrong relationshipsatdtd stylewidthpxcochairman member office president chairman executive committee member finance committee chairman bulovatdtd tdtd alignright stylewidthpxtdtrtrtda hrefresearchstockspeoplepersonasppersonidampsymbollus classlinkxsbjonathan tisch atdtd stylewidthpx paddingleft pxa hrefresearchstockspeoplerelationshipasppersonidampsymbollusimg srcimagesiconspeoplegif styleverticalalignmiddle atdtd stronga hrefbusinessweekresearchstockspeoplerelationshipasppersonidampsymbollusstrong relationshipsatdtd stylewidthpxcochairman member office president member executive committee chairman loews hotels chief executive officer loews hotelstdtd tdtd alignright stylewidthpxtdtrtrtda hrefresearchstockspeoplepersonasppersonidampsymbollus classlinkxsbjames tisch atdtd stylewidthpx paddingleft pxa hrefresearchstockspeoplerelationshipasppersonidampsymbollusimg srcimagesiconspeoplegif styleverticalalignmiddle atdtd stronga hrefbusinessweekresearchstockspeoplerelationshipasppersonidampsymbollusstrong relationshipsatdtd stylewidthpxchief executive officer president member office president director member executive committee member finance committee chairman diamond offshore director cnatdtd tdtd alignright stylewidthpxtdtrtable,1 let try answer questions in dev mode hit ctrl alt t get shell however trimsecure shell let wish you load type os usb install i friends ubuntu everyone moved back chromeos may case different cloud cloud ide give ability develop python you read blog post i wrote past developers chromebook httpgreenidowordpresscomwebdevelopersandthenewchromebook good luck,i would like use samsung chromebook develop app engine using python unfortunately possible i browser there online ide like codule good enough yet so regards i questions is way hack chrome os pull native linux is way install second os chromebook i new samsung chromebook first one is chrome os extension help programming python app engine,3 some time ago i forked smtplib added logfile option among things you try want it also new name smtppy,as know python smtplib debug levelwhen i set true param print send information the problem i try get debug info log file they stay cmd console how i log info like connect connect reply esmtp winwebmail ready httpwwwwinwebmailcomrn reply retcode msg esmtp winwebmail ready httpwwwwinw ebmailcom connect esmtp winwebmail ready httpwwwwinwebmailcom send ehlo rn reply sizern reply auth loginrn reply retcode msg size auth login bla bla bla bla,1 it likely optimisation side browser trying reuse connection see httpenwikipediaorgwikihttppersistentconnection if want make sure sniff traffic using wireshark although localhost based address may require fancy setup,i binding socket localhost order make simple server here simple python script i used create server import os import socket import fcntl tuples socketgetaddrinfo localhost socketafunspec socketsockstream socketaipassive socketaiaddrconfig res tuples af socktype proto canonname sockaddr res sock socketsocketaf socktype proto flags fcntlfcntlsockfileno fcntlfgetfd flags fcntlfdcloexec fcntlfcntlsockfileno fcntlfsetfd flags socksetblocking sockbindsockaddr socklisten now i open script using interactive shell then i go browser visit httplocalhost queue connection server i repeat last step times time inside new tab at point i expect many connections queued server to check i go interactive shell i type sockaccept this works first try subsequent tries i get erno eagain tells connections queued however browser little connecting spinner still going tab i opened i tried chrome firefox i wrote client connects localhost able queue connections problems what going can anyone please check experiment verified browsers for convenience client import os import socket import fcntl socketsocketsocketafinet socketsockstream sconnect localhost srecv,1 you iterate columns table first table sqlalchemyormattributes import managerofclass dummytable managerofclassdummymappermappedtable finally query col dummytablecolumns dummy sessionquerydummyfiltercol first or maybe actually generating specific set columns elaborate function showing in case use getattr no really range n cname cd dummy dbsessionquerydummyfiltergetattrdummy cname first,i table many columns class dummyobject tablename dummies c columninteger c columninteger c columninteger cn columninteger can i query columns individually without specifying column name manually range n cname cd dummy dbsessionquerydummyfilterbyfirst thanks,2 selfassertcontainsresponse invalid message,i like simulate requests views django i writing tests this mainly test forms here snippet simple test request djangotests import testcase class myteststestcase def testformsself response selfclientpostmyform something something selfassertequalresponsestatuscode get page back error the page always returns response whether form error how i check form failed particular field soemthing error,2 to wrap comment tomasz zielinski real answer for several reasons indeed better let apachenginxetc work sending files most servers mechanisms help usecase apache lighttpd xsendfile nginx xaccelredirect the idea use features django like nice urls authentification methods etc let server work serving files what django view return response special header the server replace response actual file example apache def songdownloadrequest path pathtofilemp response httpresponse response xsendfile smartstrpath response contenttype audiompeg response contentlength osstatpathstsize return response install modexsendfile add xsendfileon depending version xsendfileallowabove xsendfilepath thepathtoservefrom apache configuration this way reveale file location keep url management django,so i want serve couple mps folder homeusernamemusic i think would big deal i bit confused using generic views url urlspy urlr songpsongidddownload songdownload name songdownload the example i following found generic view section django documentations httpdocsdjangoprojectcomendevtopicsgenericviews it way bottom i sure tailor needs here viewspy def songdownloadrequest songid song songobjectsgetidsongid response objectdetail request objectid songid mimetype audiompeg response contentdisposition attachment filenames smp songartist songtitle return response i actually loss convey i want spit mp instead output mp current pages html contained should template mp do i need setup apache serve files django able retrieve mp filesystemproper permissions course serve if need configure apache i tell django thanks advance these files hd i need generate anything spot i like prevent revealing location files possible a simple songdownload would fantastic,3 i think want test form test form view form rendered example get idea djangotest import testcase myappforms import myform class myteststestcase def testformsself formdata something something form myformdataformdata selfasserttrueformisvalid tests relating forms example checking form data,i like simulate requests views django i writing tests this mainly test forms here snippet simple test request djangotests import testcase class myteststestcase def testformsself response selfclientpostmyform something something selfassertequalresponsestatuscode get page back error the page always returns response whether form error how i check form failed particular field soemthing error,3 there way get usage statistics api this issue actively discussed aws forum years feedback aws team httpsforumsawsamazoncomthreadjspamessageid the alternatives would turn amazon s server log analyze another option would take advantage amazon devpay service thanks andy edit here official amazon s documentation related amazon s access logs httpdocsamazonwebservicescomamazonslatestdevindexhtmlserverlogshtml,is way programmatically access amazon s account usage data i building application charge endusers use amazon s bucket because i middleman aws end user putdelete operations i able keep track uploads storage usage i allowing users directly access files public access links i able directly monitor downstream usage as plan check download usage regularly is anywhere aws api i access usage statistics,2 i would configure relation onetoone uselistfalse add property would wrap link relationship the sa configuration would look like code work fine creating updating deleting link you might need configure relation deleteorphan option cascade class submissionsbase tablename submissions id columninteger primarykeytrue created columndatetime defaultdatetimenow title columntext linkid columninteger foreignkey linksid linkrel relationlinks backrefbackrefsubmission uselistfalse def initself title linknone selftitle title selflink link property def linkself return selflinkrel selflinkrellink linksetter def linkself value value none selflinkrel none elif selflinkrel none selflinkrel linksvalue else selflinkrellink value,i learning use sqlalchemy i trying following storing title link two separate tables temp submissionstitleu facebook homepage linku httpfacebookcom sessionaddtemp sessionflush transactioncommit via class linksbase tablename links id columninteger primarykeytrue link columntext created columntimestamp defaultdatetimenow def initself link selflink link class submissionsbase tablename submissions id columninteger primarykeytrue created columntimestamp defaultdatetimenow title columntext linkid columninteger foreignkey linksid link relationlinks def initself title link selftitle title selflink link however i always get error attributeerror unicode object attribute sainstancestate what going is better way code,1 you use defaultdict list collections import defaultdict b c dd defaultdictlist k v miteritems ddvappendk dictdd b c if care dict defaultdict omit last step und use defaultdict directly,for example i call function passing dictionary parameter invmap b c b c invmap b c c b invmap b c b c if map b i invert map get invmap b using dictvk k v mapiteritems anyone knows case,3 you probably use defaultdict setdefault def invertdictionaryorigdict result change defaultdictlist k v origdictiteritems resultsetdefaultv appendk,for example i call function passing dictionary parameter invmap b c b c invmap b c c b invmap b c b c if map b i invert map get invmap b using dictvk k v mapiteritems anyone knows case,3 to create custom responses need use bottlebaseresponse object the documentation describes class seems quite easy use so achieve want create baseresponse object status code wish data need include return view,well i working bottle right and i wondering excatly i able build custom response i little script operates data i send i want send responsecode done modification i looking docs bottle find anything thanks advance,1 the argument cursorexecute represents values need inserted database tuple sequence however consider example see happening jason jason jason jason the first example evaluates string instead correct way representing single valued tuple second evaluation anyhow code fix error selfcursorexecuteselect weight from equipment where name item also giving cursorexecute value arguments stringswhich results first evaluation example results error getting,using sqlite python i trying iterate list pull weight item database based item name i tried using parameter substitution suggested prevent sql injections work for example i use item selfinventorynames selfcursorexecuteselect weight from equipment where name item selfcursorclose i get error sqliteprogrammingerror incorrect number bindings supplied the current statement uses supplied i believe somehow caused initial creation database module i made actually creates db bindings cursorexecutecreate table equipment id integer primary key name text price integer weight real info text ammocap integer availabilitywest text availabilityeast text however i use lesssecure substitution item name works fine like item selfinventorynames selfcursorexecuteselect weight from equipment where name item selfcursorclose i figure thinks i bindins i calling one how i fix,3 why temporarily stop patch selfurlopenstop points real urlopen urlliburlopen put patch place selfurlopenstart,is way temporary undo patching using mock within sideeffect in particular i like make something like work mock import patch import urllib import unittest class simpletestunittesttestcase def setupself selfurlpatcher patch urlliburlopen selfurlopen selfurlpatcherstart def sideeffecturl interesting stuff first temporary unpatch urlliburlopen call real one r urlliburlopenurl ought real deal patch return r selfurlopensideeffect sideeffect def testfeatureself almost real urlliburlopen usage goes p urlliburlopenwwwgooglecomread name main unittestmain,1 have look django facebook there examples included link httpsgithubcomtschellenbachdjangofacebook also try list sharing flow fashiolista real life demo httpwwwfashiolistacomstylemodedamourlistultimatesummerwishlist click save photo album,i trying publish photo available server users photo album is job pythondjango done javascript and anyone example code i going round circles week i got users accesstoken permissions publish update basically something like djangopython so i call page upload photo server post users wall upload photo to album facebooks graph api thanks,1 the command works executed terminal except command the code running mv pdf testpdf type runs mv pdf testpdf the difference shell globs wildcard executing mv you simulate using glob module,i trying rename set pdf files desktop using simple python script i somehow successful my current code import ossubprocess path usersarmeddesktop file oslistdirpath command mv pdf testpdf mv command rename files testpdf subprocesscallcommand the output get code files renamed the command works executed terminal i using mac helps way,3 python going expand shell wildcard string default you also without subprocess but code lose pdf files except last one glob import glob import os path usersarmeddesktop oschdirpath filename globpdf osrenamefilename testpdf but i sure really want you need better destination name,i trying rename set pdf files desktop using simple python script i somehow successful my current code import ossubprocess path usersarmeddesktop file oslistdirpath command mv pdf testpdf mv command rename files testpdf subprocesscallcommand the output get code files renamed the command works executed terminal i using mac helps way,1 you looking zipfile stringio create stringio open zipfile add files send,please help problem i sorry sounds noobie coz i really there files jpg docs certain database would i select file database save zip file send browser httpresponse something like response httpresponsemimetype applicationzip response contentdisposition filenamegroupzip the part greatly bothers taking files database coz google seem helpful some relevant codes i temp requestpostgetlist cbox cbox field form tempx modelsfiletableobjectsfilterpkin temp i longer know thanks advance p,1 all multiprocessingpoolmap methods consume iterators fully demo code soon function called to feed map function chunks iterator one chunk time use groupernofill def groupernofilln iterable listgroupernofill abcdefg a b c d e f g ititeriterable def take yield listitertoolsisliceitn return itertakenext chunksize asyncresults finput groupernofillchunksizeitertoolsizipmatrices inds asyncresultsextendpoolmapasyncmyfunc finputget asyncresultsnparrayasyncresults ps poolmapasync chunksize parameter something different it breaks iterable chunks gives chunk worker process calls mapfuncchunk this give worker process data chew funcitem finishes quickly help situation since iterator still gets consumed fully immediately mapasync call issued,i xx numpy array element matrix i need calculations matrices i want use multiprocessing module speed things the results calculations must stored xx array like original one result matrix element ijk original array must put ijk element new array to i want make list could written pseudoish way arrayijk j k pass function multiprocessed assuming matrices list matrices extracted original array myfunc function calculations code would look somewhat like import multiprocessing import numpy np itertools import izip def myfuncfinput do calculations return result index return result finput make indices inds nprollaxisnpindices reshape make function input matrices indices finput izipmatrices inds pool multiprocessingpool asyncresults npasarraypoolmapasyncmyfunc finputget however seems like mapasync actually creating huge finput list first my cpu much memory swap get completely consumed matter seconds obviously i want is way pass huge list multiprocessing function without need explicitly create first or know another way solving problem thanks bunch,3 httpdocspythonorgextendingextendinghtml httpdocspythonorgextending httpenwikibooksorgwikipythonprogrammingextendingwithc httpwikicacrcaltechedudanseindexphpwritingcextensionsforpython,we developing software python two team know cc my question make plugins possible include dll python,1 unless already existing cc libraries want integrate python waste time toss copy tutorial desks tell take days learn,we developing software python two team know cc my question make plugins possible include dll python,3 when working flickrapi python frequently useful print xml returned api calls order see going in example add xmletree import elementtree top add print elementtreetostringfavs see structure returned rsp statok photosets page pages perpage total photoset photoset photoset photoset photosets rsp in real application want check return status check page attributes quickly get want let look photoset elements to iterate change loop elm favsgetchildren print elementtreetostringelm then see structure photoset element navigate for example one would photoset cancomment countcomments countviews datecreate dateupdate farm id needsinterstitial photos primary secretfde server videos visibilitycanseeset titlebirdstitle description photoset title actually stored title subelement from see get information want elm favsgetchildren title elmgetchildrentext print id secret setname elmget id elmget secret title produces output id secret ef setname french creek state park id secret dceddf setname las vegas id secret fde setname birds etc,i wish list sets created user along set id i using flickrapi python here code the setname returning none output the elmget title returning none import flickrapi apikey apikey apisecret apisecret flickr flickrapiflickrapiapikey apisecret token frob flickrgettokenpartoneperms write token rawinputpress enter authorized program flickrgettokenparttwotoken frob try favs flickrphotosetsgetlistuserid n favs flickrfavoritesgetpubliclistuserid n elm favsgetiterator print id secret setname elmget id elmget secret elmget title except raise exceptionsome error encountered,1 edit it seems certain equations definitely possible automate process see original answer left intact based many painful hours fighting latex equation settings failures notice missing elements huge equation blocks almost certainly possible convert latex python vice versa probably painful hand likely need spend time tidying results anyway that said similar questions asked answered how convert math formula python code converting python numeric expression latex maybe get started edit i took look previous questions tested combination comments all credit authors comments import sympy def pythontolatexexpression simplifyfalse symexpr sympysympifyexpression simplify symexpr sympysimplifysymexpr return sympylatexsymexpr name main print pythontolatexrawinputenter python math expression simplifytrue,i writing code long mathematical equations many trigonometric identities is way visualising expression latex making c python expression way around how enter check mathematical expressions see brackets etc right position use latex documents thanks advance,2 it called bit vector bitmap try eg bitvector if want implement need use numeric object list use bitwise operations toggle bits eg bitmap bit bitmap bit enable bit bitmap amp bit disable bit,i big list represented integers default python i think randint range and i want optimize code utilizes much less memory the obvious way use bit represent numbers is possible build list real binary numbers python regards bruno edit thank from answers i found python default i found library installed macports osx saves trouble bit operations pythonbitstring,1 paths specified relative directory containing appyaml try handlers url dailybasic script dailybasicdailybasicpy did want map file indexhtml root url app engine automatically like web servers to mapping try something like url staticfiles indexhtml upload indexhtml,i making project using gae terrible problem i wanted make twitter bot i started first step posting tweets i made tweetstxt folder dailybasicpy here parts codes appyaml application mathgirlna version runtime python apiversion handlers url static staticdir static url dailybasic script dailybasicdailybasicpy url script mainpy mainpy works error usrbinpython coding utf import os import sys googleappengineapi import users googleappengineext import webapp googleappengineext import db googleappengineextwebapp import template googleappengineextwebapputil import runwsgiapp import wsgirefhandlers class mainpagewebapprequesthandler def getself path ospathjoinospathdirnamefile indexhtml selfresponseoutwritetemplaterenderpath none application webappwsgiapplication mainpage debugtrue def main runwsgiappapplication name main main dailybasicpy run every minutes usrbinpython coding utf import os import sys googleappengineext import webapp googleappengineext import db googleappengineextwebapputil import runwsgiapp import tweepy import wsgirefhandlers import time def tweetittweet lentweet apiupdatestatustweet else diaryentriesappendtweet consumerkey consumersecret accesstoken accesstokensecret auth tweepyoauthhandlerconsumerkey consumersecret authsetaccesstokenaccesstoken accesstokensecret api tweepyapiauth class dailybasicwebapprequesthandler def getself timelocaltime path ospathjoinospathdirnamefile tweetstxt fdb openpath r db fdbreadline db todaynow wday nowtmwday dbwday nowtmhour nowtmmin intdb intdb nowtmhour nowtmmin intdb intdb todaynowappenddb iflentodaynow import random tweetittodaynowrandomrandrangelentodaynow application webappwsgiapplication dailybasic dailybasic debugtrue def main runwsgiappapplication name main main cronyaml cron description day process url dailybasic schedule every minutes timezone asiaseoul i googled problem tried everything i put part appyaml workedit able deployed gae warned file referenced handler found dailybasicpy here file tree root dailybasic dailybasicpy tweetstxt mainpy appyaml cronyaml indexyaml indexhtml i want keep indexhtml contains html codes without scripts how i place files write appyaml and sorry poor english added the problem open works tweetstxt uploaded wrong directory,1 this uses bitstring module constructs bitarray object list bitstring import bitarray b bitarrayrandint range internally stored packed bytes take considerably less memory you slice index check set bits etc usual notation additional methods set modify bits to get data back binary string use bbin get byte packed data use btobytes pad zero bits byte boundary,i big list represented integers default python i think randint range and i want optimize code utilizes much less memory the obvious way use bit represent numbers is possible build list real binary numbers python regards bruno edit thank from answers i found python default i found library installed macports osx saves trouble bit operations pythonbitstring,2 as delnan already said comment able use real binary numbers mean bitforbit equivalent memory usage integers longs course real binary numbers meaning address individual bits using bitwise operators easily hidden class also long objects become arbitrarily large ie use simulate arbitrarily large bitsets it going fast python difficult either good start using binary generation scheme following reduce lambda p b b p p randomrandint range of course random supports arbitrarily large upper boundaries r randomrandint this entirely since individual binary digits independent way independent create digit then knowing prngs work really independent case either if concern probably use random module hardware rng,i big list represented integers default python i think randint range and i want optimize code utilizes much less memory the obvious way use bit represent numbers is possible build list real binary numbers python regards bruno edit thank from answers i found python default i found library installed macports osx saves trouble bit operations pythonbitstring,1 you use rollyourown solution function overloading this one copied guido van rossum article multimethods little difference mm overloading python registry class multimethodobject def initself name selfname name selftypemap def callself args types tupleargclass arg args generator expression function selftypemapgettypes function none raise typeerrorno match return functionargs def registerself types function types selftypemap raise typeerrorduplicate registration selftypemaptypes function def multimethodtypes def registerfunction name functionname mm registrygetname mm none mm registryname multimethodname mmregistertypes function return mm return register the usage would multimethods import multimethod import unittest overload makes sense case overload multimethod class spriteobject pass class pointobject pass class curveobject pass overloadsprite point direction int def addbulletsprite start direction speed overloadsprite point point int int def addbulletsprite start headto speed acceleration overloadsprite str def addbulletsprite script overloadsprite curve speed def addbulletsprite curve speed most restrictive limitations moment methods supported functions class members inheritance handled kwargs supported registering new functions done import time thing threadsafe,i know python support method overloading i run problem i seem solve nice pythonic way i making game character needs shoot variety bullets i write different functions creating bullets for example suppose i function creates bullet travelling point a b given speed i would write function like def addbulletsprite start headto speed code but i want write functions creating bullets like def addbulletsprite start direction speed def addbulletsprite start headto spead acceleration def addbulletsprite script for bullets controlled script def addbulletsprite curve speed bullets curved paths and and many variations is better way without using many keyword arguments cause getting kinda ugly fast renaming function pretty bad get either addbullet addbullet addbulletwithreallylongname to address answers no i create bullet class hierarchy thats slow the actual code managing bullets c functions wrappers around c api i know keyword arguments checking sorts combinations parameters getting annoying default arguments help allot like acceleration,3 static files served directly user url specified appyaml they cannot read application deployed servers serve static files infrastructure runs application if need read files script upload nonstatic if need serve files statically directly user browser read scripts need include copies files application although symlink nonstatic directory count second copy get deployed,i making project using gae terrible problem i wanted make twitter bot i started first step posting tweets i made tweetstxt folder dailybasicpy here parts codes appyaml application mathgirlna version runtime python apiversion handlers url static staticdir static url dailybasic script dailybasicdailybasicpy url script mainpy mainpy works error usrbinpython coding utf import os import sys googleappengineapi import users googleappengineext import webapp googleappengineext import db googleappengineextwebapp import template googleappengineextwebapputil import runwsgiapp import wsgirefhandlers class mainpagewebapprequesthandler def getself path ospathjoinospathdirnamefile indexhtml selfresponseoutwritetemplaterenderpath none application webappwsgiapplication mainpage debugtrue def main runwsgiappapplication name main main dailybasicpy run every minutes usrbinpython coding utf import os import sys googleappengineext import webapp googleappengineext import db googleappengineextwebapputil import runwsgiapp import tweepy import wsgirefhandlers import time def tweetittweet lentweet apiupdatestatustweet else diaryentriesappendtweet consumerkey consumersecret accesstoken accesstokensecret auth tweepyoauthhandlerconsumerkey consumersecret authsetaccesstokenaccesstoken accesstokensecret api tweepyapiauth class dailybasicwebapprequesthandler def getself timelocaltime path ospathjoinospathdirnamefile tweetstxt fdb openpath r db fdbreadline db todaynow wday nowtmwday dbwday nowtmhour nowtmmin intdb intdb nowtmhour nowtmmin intdb intdb todaynowappenddb iflentodaynow import random tweetittodaynowrandomrandrangelentodaynow application webappwsgiapplication dailybasic dailybasic debugtrue def main runwsgiappapplication name main main cronyaml cron description day process url dailybasic schedule every minutes timezone asiaseoul i googled problem tried everything i put part appyaml workedit able deployed gae warned file referenced handler found dailybasicpy here file tree root dailybasic dailybasicpy tweetstxt mainpy appyaml cronyaml indexyaml indexhtml i want keep indexhtml contains html codes without scripts how i place files write appyaml and sorry poor english added the problem open works tweetstxt uploaded wrong directory,3 i would use pth file see httpdocspythonorginstallindexhtmlinstsearchpath a pth file file consisting one directory path per line it insert listed directories python path that may better executing shell scripts downsides complex installation break portability etc,ok i following situation i need edit pythonpath dynamically target pc now structure project trunk bin startscript dependencies dependencies from python i could startscript rootpath ospathsplitospathdirnameospathabspathfile dependenciesroot ospathjoinrootpath dependencies sys import path pathextendrootpath dependenciesroot this would trick i need start new python processes processpopen changes syspath gone seems now i thinking sh script would job better unfortunately i total noob idea proceed the sh script basically things python get absolute path directory script located get parent folder say parentpath export pythonpathpythonpathparentpath python startscriptpy so basically first two steps ones i need help also way make changes python syspath persist subprocess opened subprocesspopen please let know,1 have looked sympy it module generating latex python code actually quite bit sympy probably guess name python library symbolic computation the sympy library also includes builtin interpreter cd sympy directory sitepackages type ipython shell prompt with sympy interpeter things like in cosxseriesx out x ⋠x ⋠x ⋠x ── ──── ───── ────── ox in xyexpand out x ⋠x⋠in cosxseriesx out x ⋠x ⋠x ⋠x ── ──── ───── ────── ox quite latexbut sympy easily generate latex python code sympy import integral latex sympyabc import x latexx x latexx mode inline x latexx mode equation beginequationxendequation i also wanted generally recommend sympy libraryunder active development four years improved substantially year excellent mature library symbolic computation excellent docs active helpful community aside submitting couple patches i sympy devcommitter user,i writing code long mathematical equations many trigonometric identities is way visualising expression latex making c python expression way around how enter check mathematical expressions see brackets etc right position use latex documents thanks advance,3 as far i know done the problem ironpython class clr class compatible clr class a clr class static ironpython class dynamic dlr far i know example provide ironpython classes net clr attributes need cmdlet development,i want able write powershell cmdlets using ironpython furthermore i need one cmdlet look environment add cmdlets powershell based contents for example reading directory adding cmdlet remove every filename sees,1 i back jã¶rg w mittag answer the python implementation diioc lightweight completely vanishes to back statement take look famous martin fowler example ported java python pythondesignpatternsinversionofcontrol as see link container python written lines code class container def initself systemdata componentname componentclass componentargs systemdata typecomponentclass typesclasstype args selfdictarg arg componentargs selfdictcomponentname componentclassargs else selfdictcomponentname componentclass,in java ioc di common practice extensively used web applications nearly available frameworks java ee on hand also lots big python web applications beside zope i heard really horrible code ioc seem common python world please name examples think i wrong there course several clones popular java ioc frameworks available python springpython example but none seems get used practically at least i never stumpled upon django sqlalchemy insert favorite wsgi toolkit based web application uses something like in opinion ioc reasonable advantages would make easy replace djangodefaultusermodel example extensive usage interface classes ioc python looks bit odd â»pythonicâ« but maybe someone better explanation ioc widely used python,3 you could update pythonpath environment variable moment update syspath startscript using osenviron dict,ok i following situation i need edit pythonpath dynamically target pc now structure project trunk bin startscript dependencies dependencies from python i could startscript rootpath ospathsplitospathdirnameospathabspathfile dependenciesroot ospathjoinrootpath dependencies sys import path pathextendrootpath dependenciesroot this would trick i need start new python processes processpopen changes syspath gone seems now i thinking sh script would job better unfortunately i total noob idea proceed the sh script basically things python get absolute path directory script located get parent folder say parentpath export pythonpathpythonpathparentpath python startscriptpy so basically first two steps ones i need help also way make changes python syspath persist subprocess opened subprocesspopen please let know,2 splitnum anything numsplit would valid solve problem splits spaces what want convert digit characters num numbers represent list comprehension digits intc c num then sum result expression,i trying make program whatever number entered user digits composing number added sum good done something wrong this simple i suppose though i struggling add together numbers i split do know i this attempt numrawinputinput number numsplit suma print num valid number else print num invalid thank,2 you using rawinput prompt user function returns string composed digits case need make computations convert int here code could look like num rawinput input number suminti num print ok else print failed keep mind python x functions rawinput returns string input returns integers fails something else given python x rawinput function replaced input,i trying make program whatever number entered user digits composing number added sum good done something wrong this simple i suppose though i struggling add together numbers i split do know i this attempt numrawinputinput number numsplit suma print num valid number else print num invalid thank,1 use map function in in mapinta out in summapinta out mapfunction sequence calls functionitem sequence’s items returns list return values see docspythonorg this works rawinput returns string,i trying make program whatever number entered user digits composing number added sum good done something wrong this simple i suppose though i struggling add together numbers i split do know i this attempt numrawinputinput number numsplit suma print num valid number else print num invalid thank,3 your first problem split split string characters splits string whitespace split to go character input string use split use character string i find hard read code variable names like lol rofl i changed your check intdigit excludes i assume accident i using intdigit including instead your current code prints error message time sees invalid character instead i break loop i print first time print success message loop completes without broken if intdigit fails convert digit int raise exception instead i compare character see instead converting code rawinputwhat code digit code digit print the verification code valid please check credit card code break else print thank we process order a compact alternative using loop use generator expression function code rawinputwhat code digit digit code print thank we process order else print the verification code valid please check credit card code,brief i trying write simple program checks given code valid the code valid three characters entered digits if code valid progam displays message thank we process order the output program error message the verification code valid please check credit card code input valid attempt lol rawinputwhat code rofllolsplit int rofl introfl print thank we process order else print the verification code valid please check credit card code purpose to learn i found another way involving checking whole thing worked perfectly but i trying learn request that give explicit direction fix code provide additional relevant advice close thank advance,1 could rawinput aisdigit inta lena print yeah else print nope isdigit cool builtin function checks strings see made entirely digits you wrap inta tryexcept acts shortcircuit operator prevent inta evaluated isdigit returns false edit added lena,brief i trying write simple program checks given code valid the code valid three characters entered digits if code valid progam displays message thank we process order the output program error message the verification code valid please check credit card code input valid attempt lol rawinputwhat code rofllolsplit int rofl introfl print thank we process order else print the verification code valid please check credit card code purpose to learn i found another way involving checking whole thing worked perfectly but i trying learn request that give explicit direction fix code provide additional relevant advice close thank advance,2 what trying check given input matches given pattern three digits case basically regular expressions made using regex code would look like import code rawinputwhat code rematchr code print code ok else print wrong code in regex means beginning string means digit could also means repeated times means end string for informations regular expressions look module documentation,brief i trying write simple program checks given code valid the code valid three characters entered digits if code valid progam displays message thank we process order the output program error message the verification code valid please check credit card code input valid attempt lol rawinputwhat code rofllolsplit int rofl introfl print thank we process order else print the verification code valid please check credit card code purpose to learn i found another way involving checking whole thing worked perfectly but i trying learn request that give explicit direction fix code provide additional relevant advice close thank advance,2 lol rawinputwhat code rofllolsplit split perform think separates parts string according space tab line ends int rofl loop using int variable name good idea int standard type introfl rofl list redefine int use lol instead loop digits intd witll throw exception digit print thank we process order else print the verification code valid please check credit card code you test exactly digits and reply test loop per item loop,brief i trying write simple program checks given code valid the code valid three characters entered digits if code valid progam displays message thank we process order the output program error message the verification code valid please check credit card code input valid attempt lol rawinputwhat code rofllolsplit int rofl introfl print thank we process order else print the verification code valid please check credit card code purpose to learn i found another way involving checking whole thing worked perfectly but i trying learn request that give explicit direction fix code provide additional relevant advice close thank advance,1 i tried addressing problem unfound dynamics library compiling mysqldb module static libraries set static true sitecfg but generated error mysqlo still asking dynamic library to fix i added libraries block static setupposixpy,i downloaded followed install instructions mysql httpdevmysqlcomdownloadsmysql mysqldb python plugin httpsourceforgenetprojectsmysqlpython when i attempt import mysqldb python terminal i get error safira yanigisawa python version python safira yanigisawa python c import mysqldb traceback recent call last file string line module file buildbdistmacosxuniversaleggmysqldbinitpy line module file buildbdistmacosxuniversaleggmysqlpy line module file buildbdistmacosxuniversaleggmysqlpy line bootstrap importerror dlopenusersyanigisawapythoneggsmysqlpythonpymacosxuniversaleggtmpmysqlso library loaded libmysqlclientdylib referenced usersyanigisawapythoneggsmysqlpythonpymacosxuniversaleggtmpmysqlso reason image found safira yanigisawa i found question stack overflow followed instructions safira yanigisawa echo dyldlibrarypath usrlocalmysqllib safira yanigisawa ls l usrlocalmysqllib total rwxrxrx root wheel jan libmysqlclientdylib rwrr root wheel dec libmysqlclienta lrwxrxrx root wheel jan libmysqlclientdylib libmysqlclientdylib lrwxrxrx root wheel jan libmysqlclientrdylib libmysqlclientdylib lrwxrxrx root wheel jan libmysqlclientra libmysqlclienta lrwxrxrx root wheel jan libmysqlclientrdylib libmysqlclientdylib rwrr root wheel dec libmysqlddebuga rwrr root wheel dec libmysqlda rwrr root wheel dec libmysqlservicesa drwxrxrx root wheel dec plugin safira yanigisawa md usrlocalmysqlliblibmysqlclientdylib md usrlocalmysqlliblibmysqlclientdylib baabdbeddad safira yanigisawa and cleaning python egg files rebuilding i still got error then i found bug httpbugsmysqlcombugphpid mysql affecting mac i tried workaround listed cleaned eggs rebuilt i still getting error is another workaround problem specific python am i missing something else edit adding output otool commands safira yanigisawa otool l usersyanigisawapythoneggsmysqlpythonpymacosxuniversaleggtmpmysqlso usersyanigisawapythoneggsmysqlpythonpymacosxuniversaleggtmpmysqlso libmysqlclientdylib compatibility version current version usrliblibsystembdylib compatibility version current version safira yanigisawa otool dx usrlocalmysqlliblibmysqlclientdylib usrlocalmysqlliblibmysqlclientdylib safira yanigisawa,1 the java approach seems either get streaming dom parser python allows mixing two,stax seems pulling parser like sax without inversion control but i find equivalent python expandnode i interested first place i care inversion control for know pulldom stax parser point obtain current subtree dom node,1 in develop branch new option change css hashing method httpsgithubcomjezdezdjangocompressor see line filterscssdefaultpy the settings i using compressenabled true compressoffline false compressstorage compressorstoragegzipcompressorfilestorage compresscsshashingmethod hash using mtime since differs servers there option like js files since hash key never generated using mtime anyway this works perfectly behind loadbalancer when written following latest commit develop branch httpsgithubcomjezdezdjangocompressorcommitdbcfdabfebccfabffcb,i two servers behind load balancer each server running memcached server settings file identical servers defined short shared cache i want paths generated files identical servers client download for get working i need understand django compressor works what actual purpose cache django compressor is file content stored cache filesystem if happens first i hope i asking right questions feel free add a detailed better constructed sequence would helpful edit since servers share memcached server i set compresscachekeyfunction compressorcachesocketcachekey see develop branch using cache key contribute point file names the way i understand mtime collected source jscss files determine may changed new file generated correct this probably happen every load when happen,3 here nice demo using python opencv seems looking video code whether work without modification depends details spot the example uses cvhoughcircles identify circle object circle need replace,i working program python able following a webcam watching movement object moving path the object tracked marked big yellow spot i find yellow spot calculate centerpoint spot make calculations it would awesome centerpoint would draw picture remains whole time how would make happen ive already looked pil pygame opencv find working solution halfsolutions in steps would thanks help d,1 from html specs the html syntax support namespace declarations so i think lxmlhtmlhtmlparser removesignores namespace however beautifulsoup parses html differently i thought might worth shot if also beautifulsoup installed use beautifulsoup parser lxml like import lxmlhtmlsoupparser soupparser import lxmlhtml import io psomeparap opmsofficeparaop htmlsoupparserparseiobytesios beautifulsoup remove namespace neither recognize namespace instead part name tag that say htmlxpath op namespaces foo work but workaroundhack htmlxpath nameop print tag ttag text ttext yields tag op text msofficepara,i processing html files python lxml some edited ms word p tags written opampnbspop instance ie firefox interpret ms tags real p tags display line breaks op tags original editors formatted files eg spaces around nbsp lxml hand tidy processing html files see op tags changed proper p tags unfortunately tidying browsers display line breaks around nbsp breaks original formatting so idea browse op tags either remove add text attribute parent text attribute ie remove op tag markers lxml import etree import lxmlhtml stringio import stringio psomeparap opmsofficeparaop parser lxmlhtmlhtmlparser htmllxmlhtmlparse stringio parser htmlxpath p print tag ttag text ttext the result tag p text somepara tag p text msofficepara so lxlm removes namespace name tag marker is way know p tag namespace i remove ones op thanks,1 since march mathjax cdn use without uploading files gae just make sure page header script typetextjavascript srchttpcdnmathjaxorgmathjaxlatestmathjaxjsconfigtexamsmmlhtmlormml script,i trying add tex support application i would like use mathjax render mathematics formulas client side since i gave server side solution explained the mathjax library pretty fat files easily installed app engine due files number limitation i experience mathjax library i open strategies like available mathjax cdn cutting directoriesfiles reduce package files number do know way use mathjax google app engine,3 in code buttonself text open commandselfonsavepacksideleft first argument button instance tkinter container eg root window frame according httpcodegooglecompchildreneditorsourcebrowsetrunkeditornewpy self instance scrolledtext cannot contain widgets try changing self frm,why error tk attribute error traceback recent call last file editornewpy line module texteditormainloop file editornewpy line init buttonself text open commandselfonsavepacksideleft file cpythonliblibtktkinterpy line init widgetinitself master button cnf kw file cpythonliblibtktkinterpy line init basewidgetsetupself master cnf file cpythonliblibtktkinterpy line setup selftk mastertk attributeerror texteditor instance attribute tk code httpcodegooglecompchildreneditorsourcebrowsetrunkeditornewpy what wrong,1 check permissions classdump command chmod x classdump executable here docs chmod you might also need specify absolute path classdump path also try print joincommand see run pasting results shell,i trying execute following code python import ossubprocess glob import glob path usersarmedprivatesdks oschdirpath file globframework command classdump h file usersarmeddesktopheaders subprocesscallcommand on executing script get following error traceback recent call last file pyshell line module subprocesscallcommand file libraryframeworkspythonframeworkversionslibpythonsubprocesspy line call return popenpopenargs kwargswait file libraryframeworkspythonframeworkversionslibpythonsubprocesspy line init errread errwrite file libraryframeworkspythonframeworkversionslibpythonsubprocesspy line executechild raise childexception oserror errno permission denied any help much appreciated,1 encode turns unicode bytes decode turns bytes unicode you careful mix two your error means either chatter msgtext already bytes trying encode one worst features python lets tries first decode bytes using ascii limited encoding reencode whatever asked this fixed python use app engine app engine expects store unicode so need pass unicode string without encoding in fact data already bytestring would need decode store in short first thing try simply calling encode store data i may pointed please take time read article unicode,i roaming around forums asking questions issues related python utf encodingdecoding this time around i stumbled upon something initially seemed easy problem in previous question httpstackoverflowcomquestionsproblemswithpythoningoogleappengineutfandascii i asked ensure proper addition utf strings variables messagesappendchatmessagechatter msg the solution something along lines messagesappendchatmessagechatterencode utf msgencode utf pretty simple however i faced challenge send data google app engine datastore the code book i using code cloudlooked follows i skipped redundant parts start chatmessage class chatmessagedbmodel user dbstringpropertyrequiredtrue timestamp dbdatetimepropertyautonowaddtrue message dbtextpropertyrequiredtrue def strself return selfuser selftimestamp selfmessage end chatmessage start posthandler class chatroomposterwebapprequesthandler def postself chatter selfrequestgetname msgtext selfrequestgetmessage msg chatmessageuserchatter messagemsgtext msgput callout idcoput selfredirect end posthandler i thought swaping part posthandler following bit msg chatmessageuserchatterencode utf messagemsgtextencode utf would trick unfortunately happen i still keep getting file basedatahomeappssmarkccchatroomoneplpchatpy line post msg chatmessageuserchatterencode utf messagemsgtextencode utf unicodedecodeerror ascii codec decode byte xc position ordinal range naturally i declared coding utf statement put selfresponseheaders contenttype texthtml charsetutf file it nothing alleviate issue as see i wellversed python encodingdecoding problems bit novelty i would appreciate assistance if anyonone could explain i went wrong case practices use avoid similar quandaries future thank advance,2 i would treat different problem if imagine origin centre figure want print manhattan distance cell greater half length edge for example could following import sys r rangerr x rangerr c absx absy r else sysstdoutwritec print produces,you may noticed last query similar task i trying replicate structure if think composed triangles i able produce corners individually put one another i know i would go putting together larger construct though would i attempt would i approach problem tackling single construct work line line i individual triangle parts i assumed triangles bigger thing might shortcut,1 this worked w lines xrangew linesappendjoin w lines reversedlines l lines print l you could shrink wanted well lines join w xrangew print njoinlines lines output w,you may noticed last query similar task i trying replicate structure if think composed triangles i able produce corners individually put one another i know i would go putting together larger construct though would i attempt would i approach problem tackling single construct work line line i individual triangle parts i assumed triangles bigger thing might shortcut,1 print n join range print n join range httpcodepadorgzldeog,you may noticed last query similar task i trying replicate structure if think composed triangles i able produce corners individually put one another i know i would go putting together larger construct though would i attempt would i approach problem tackling single construct work line line i individual triangle parts i assumed triangles bigger thing might shortcut,1 for determinate mode want call start instead simply configure value widget call step method if know advance many bytes going download i assume since using determinate mode simplest thing set maxvalue option number going read then time read chunk configure value total number bytes read the progress bar figure percentage here simulation give rough idea import tkinter tk tkinter import ttk class sampleapptktk def initself args kwargs tktkinitself args kwargs selfbutton ttkbuttontextstart commandselfstart selfbuttonpack selfprogress ttkprogressbarself orienthorizontal length modedeterminate selfprogresspack selfbytes selfmaxbytes def startself selfprogressvalue selfmaxbytes selfprogressmaximum selfreadbytes def readbytesself simulate reading bytes update progress bar selfbytes selfprogressvalue selfbytes selfbytes selfmaxbytes read bytes ms selfafter selfreadbytes app sampleapp appmainloop for work going need make sure block gui thread that means either read chunks like example reading separate thread if use threads able directly call progressbar methods tkinter single threaded you might find progressbar example tkdocscom useful,i want show progress bar downloading file web using urlliburlretrive method how i use ttkprogressbar task here i done far tkinter import ttk tkinter import root tk pb ttkprogressbarroot orienthorizontal length modedeterminate pbpack pbstart rootmainloop but keeps looping,3 if need custom tool specific needs might want develop small django based wep app use celery spawn managed tasks you store log files models this probably require lot effort new web development if want cut programming time would like start generic solution might able start httpcodegooglecomppythonloggingserver some nonpython options cacti munin update see also djangotaskscheduler a web based python console tricky option considered risky non standard addition you consider thoroughly might security stability implications server apps if decide use one check links httpsgithubcomsympysympylive ajax console window ansivt support the probable alternative would probably ssh see also httpwwwpersonalumichedumresslwebshell,i like create web based control center i start processes watch statistics logs outputs also i would like run something like interactive python console webpage i know web development yet i know python something python based would nice could please suggest tools methods i learn implement ideally minimal effort achieve first results,1 encountered problem unmarshalling output p g option marshalloadsstr reads first record marshalloadstringiostr fails marshalload arg must file instead splitting suggested i used temporary file workaround import subprocess marshal tempfile tempf tempfiletemporaryfile subprocesspopencmd stdouttempfcommunicate tempfseek try record marshalloadtempf listdataappend record except eoferror pass tempfclose note python would delete temp file soon close,this really unfortunate situation maya comes code work pipe subprocesspopen p g edit csomefiletxt stdoutsubprocesspipestdout try record marshalload pipe listappend record except eoferror pass various versions work latest also works version ships maya course it throws error error typeerror file maya console line marshalload arg must file what best course action just move life code changed dump file marshalload could load actual file while works lame maya accesses python via zip small test i zipped pythonlib swapped syspath entries pointed zip zip while i tested extensively appears work i tell better worse idea one ideally i think something within i could make work without mixing python versions writing tempfiles disk time any ideas update regarding marshalloads trying marshalloads works error still work way i definitely fumbling around dark stuff the perforce stuff unbearably slow file operations done individually one query must the original code files abcn huge list files p subprocesspopencmd shelltrue stdinsubprocesspipe stdoutsubprocesspipe fi pipe pstdin pstdout fill command files file files fiwritefile n ficlose get results try record marshalload pipe listdataappend record except eoferror pass i know works x listdata ends list file results i figure marshalloads i get back first result this method taken almost verbatim perforce i know way things done it easy imagine i know use subprocess marshal properly update marshalloads totally work after testing piperead supplying data contains null characters something else i fully understand marshalloads would read first entry in particular case i split data collect data listdata results pipereadsplit skip first entry since empty result results listdataappend marshalloads result thanks cristian pointing right direction hopefully anyone upgrading maya using perforce things go little smoother,1 selflogger refer returned property threadawarelogger property,i code like class debugobject property def threadawareloggerself selfloggerinstanceforcurrentthread selfloggerinstanceforcurrentthreadselfclonemainlogger return selfloggerinstanceforcurrentthread def clonemainloggerself return loggerinstanceforcurrentthread class someotherclassobject def initself selfloggerdebugthreadawarelogger def othermethodself selfloggerinfomessage the problematic thing assignment selfloggerdebugthreadawarelogger i sure gonna content selflogger i want whole getter i want getter executed everytime i use selflogger someotherclass but i affraid selflogger stored result getter loggerinstanceforcurrentthread that means logger thread active time assignment this logger right one i call selfloggerinfomessage how get getter threadawarelogger executed everytime i call selfloggerinfomessage sidenote why i actually need shortcut selflogger when i decide replace threadawarelogger advancedthreadawarelogger i change one assignment instead thousand calls selfloggerinfomessage also none business othermethod care logger used edit the assignment getter works described answer unutbu but assigning getter causes issue i think from threadawarelogger i actually call method clonemainlogger now call someotherclasslogger ends exception attributeerror someotherclass object attribute clonemainlogger so far i bypassed issue small hack the someotherclass actually debug instance so i call debugclonemainlogger instead selfclonemainlogger inside threadawarelogger the program works i consider really dirty edit if i add line selfcomptreeloggerdebugthreaawarelogger inside method eg clonemainlogger i getting attributeerror property object attribute debug conclusion i still understand solution,1 a couple things there method order query get first ten entries it would efficient loop the reason template work referring list rather individual entry it entry entrieslist ibnameib entryname br img srcimages entrypicture height widthimgbr ibingredientsib entryingredients br pi entrydescription ip ibcreated byib entryuser brbr endfor once get template working try get entrieslist entrieslist recipesobjectsorderby id here docs sorting slicing queries httpsdocsdjangoprojectcomendevtopicsdbqueries,can seem see i going wrong forgive i new i trying display newest objects within model here loop i used put objects within list put top newest recipe objects list entrieslist allrecipes recipesobjectsannotatecount id newestrecipeindex lenallrecipes index index try x recipesobjectsgetidnewestrecipeindex entrieslistappendx newestrecipeindex newestrecipeindex index index except index index pass i render page like c requestcontextrequest form form entrieslist entrieslist return rendertoresponsemainhtml c and html entries entrieslist ibnameib entrieslistname br img srcimages entrieslistpicture height widthimgbr ibingredientsib entrieslistingredients br pi entrieslistdescription ip ibcreated byib entrieslistuser brbr endfor and modelspy class recipesmodelsmodel name modelscharfieldmaxlength ingredients modelscharfieldmaxlength picture modelsimagefielduploadto recipesymd user modelscharfieldmaxlength date modelsdatetimefieldautonowtrue description modelstextfield comments modelsmanytomanyfieldcomments it seems loop working the correct amount entries it template tags working they blank so seems working fine putting objects inside list retrieve individual fields,3 one way get whole property would make another property class someotherclass property def loggerself return selfdebugthreadawarelogger there might ways,i code like class debugobject property def threadawareloggerself selfloggerinstanceforcurrentthread selfloggerinstanceforcurrentthreadselfclonemainlogger return selfloggerinstanceforcurrentthread def clonemainloggerself return loggerinstanceforcurrentthread class someotherclassobject def initself selfloggerdebugthreadawarelogger def othermethodself selfloggerinfomessage the problematic thing assignment selfloggerdebugthreadawarelogger i sure gonna content selflogger i want whole getter i want getter executed everytime i use selflogger someotherclass but i affraid selflogger stored result getter loggerinstanceforcurrentthread that means logger thread active time assignment this logger right one i call selfloggerinfomessage how get getter threadawarelogger executed everytime i call selfloggerinfomessage sidenote why i actually need shortcut selflogger when i decide replace threadawarelogger advancedthreadawarelogger i change one assignment instead thousand calls selfloggerinfomessage also none business othermethod care logger used edit the assignment getter works described answer unutbu but assigning getter causes issue i think from threadawarelogger i actually call method clonemainlogger now call someotherclasslogger ends exception attributeerror someotherclass object attribute clonemainlogger so far i bypassed issue small hack the someotherclass actually debug instance so i call debugclonemainlogger instead selfclonemainlogger inside threadawarelogger the program works i consider really dirty edit if i add line selfcomptreeloggerdebugthreaawarelogger inside method eg clonemainlogger i getting attributeerror property object attribute debug conclusion i still understand solution,1 the problem col a b c d e f g your list supposed contain strings need quote letter like quoted strings print statements unquoted treated identifiers variables classes functions etc end error additionally mentioned voooza answer need sliceindex input string gets first character letter gets second character number either quote numbers row cast int inta comparison work finally since raw input variable called need format first print statement using input,question write program takes position chess board column col row value row checks whether position valid remember column chess board letter ranging a h inclusive row number inclusive a e valid inputs l if coordinates valid e programs prints the piece moved e otherwise prints the position valid my answer arawinputyou move col a b c d e f g row col row print the piece moved sd input else print the position valid error plugging value like d traceback recent call last file web session line module nameerror name a defined request can direct fix program context the purpose task set answer following question so far program used two separate inputs column row value can modify previous program chess problem version accept position chess board single input in words assume variable position stores column row value chess board b when coordinates input valid example c program prints message the piece moved c if first coordinate range print the first coordinate range ah ah second coordinate range print the second coordinate range close thank assistance,2 col a b c d e f g otherwise looks variables a b c find,question write program takes position chess board column col row value row checks whether position valid remember column chess board letter ranging a h inclusive row number inclusive a e valid inputs l if coordinates valid e programs prints the piece moved e otherwise prints the position valid my answer arawinputyou move col a b c d e f g row col row print the piece moved sd input else print the position valid error plugging value like d traceback recent call last file web session line module nameerror name a defined request can direct fix program context the purpose task set answer following question so far program used two separate inputs column row value can modify previous program chess problem version accept position chess board single input in words assume variable position stores column row value chess board b when coordinates input valid example c program prints message the piece moved c if first coordinate range print the first coordinate range ah ah second coordinate range print the second coordinate range close thank assistance,1 so if know basic c language your problem print element array so go like array int foriii print print array wrong similarly case iterating entrieslist assigning element variable entries now play entries entries entrieslist ibnameib entriesname br img srcimages entriespicture height widthimgbr ibingredientsib entriesingredients br pi entriesdescription ip endfor and ofcourse carl given better solution getting latest recipes case models,can seem see i going wrong forgive i new i trying display newest objects within model here loop i used put objects within list put top newest recipe objects list entrieslist allrecipes recipesobjectsannotatecount id newestrecipeindex lenallrecipes index index try x recipesobjectsgetidnewestrecipeindex entrieslistappendx newestrecipeindex newestrecipeindex index index except index index pass i render page like c requestcontextrequest form form entrieslist entrieslist return rendertoresponsemainhtml c and html entries entrieslist ibnameib entrieslistname br img srcimages entrieslistpicture height widthimgbr ibingredientsib entrieslistingredients br pi entrieslistdescription ip ibcreated byib entrieslistuser brbr endfor and modelspy class recipesmodelsmodel name modelscharfieldmaxlength ingredients modelscharfieldmaxlength picture modelsimagefielduploadto recipesymd user modelscharfieldmaxlength date modelsdatetimefieldautonowtrue description modelstextfield comments modelsmanytomanyfieldcomments it seems loop working the correct amount entries it template tags working they blank so seems working fine putting objects inside list retrieve individual fields,1 what get bytestring you must decode order get unicode string it basically comes bytestring fxevrier bytestringdecode utf u fã©vrier,i trouble get unicode values mysql queries here i mysqldb import connect mysqldbcursors import dictcursor con connect passwd db mydb user dbuser host localhost cursorclass dictcursor useunicodetrue charsetutf cursor concursor cursorexecute u select basicapplet res cursorfetchall printres titlede test title typeres titlede type str as see returning unicode in table structure titlede set unicode idbasicapplet int titlede varchar utfbin i really know i wrong help would really welcome thanks advance simon,1 ospath module using list think looking syspath,running testpy gives traceback recent call last file testpy line module map parsermapospath startwmap typeerror module object subscriptable parserpy import configparser def stringisnumberstring try intstring except return false return true class map parser configparserrawconfigparser mapurl def initself map selfparserreadmap selfmapurl map def tiletypesself all numerical sections assumed tiles return n n selfparsersections stringisnumbern testpy import parser import os map parsermapospath startwmap printmaptiletypes,1 import logging import random class debugobject property def threadawareloggerself loggers logginggetlogger abc logginggetlogger def return selfanotherdebugmethodloggers def anotherdebugmethodselfloggers return randomchoiceloggers class someotherclassobject def initself selfdebugdebug property def loggerself return selfdebugthreadawarelogger def othermethodself selfloggerinfo message name main loggingbasicconfiglevelloggingdebug xsomeotherclass range xothermethod yields output like infodefmessage infoabcmessage infodefmessage infodefmessage infoabcmessage notice changes abc def show debugthreadawarelogger function getting called time,i code like class debugobject property def threadawareloggerself selfloggerinstanceforcurrentthread selfloggerinstanceforcurrentthreadselfclonemainlogger return selfloggerinstanceforcurrentthread def clonemainloggerself return loggerinstanceforcurrentthread class someotherclassobject def initself selfloggerdebugthreadawarelogger def othermethodself selfloggerinfomessage the problematic thing assignment selfloggerdebugthreadawarelogger i sure gonna content selflogger i want whole getter i want getter executed everytime i use selflogger someotherclass but i affraid selflogger stored result getter loggerinstanceforcurrentthread that means logger thread active time assignment this logger right one i call selfloggerinfomessage how get getter threadawarelogger executed everytime i call selfloggerinfomessage sidenote why i actually need shortcut selflogger when i decide replace threadawarelogger advancedthreadawarelogger i change one assignment instead thousand calls selfloggerinfomessage also none business othermethod care logger used edit the assignment getter works described answer unutbu but assigning getter causes issue i think from threadawarelogger i actually call method clonemainlogger now call someotherclasslogger ends exception attributeerror someotherclass object attribute clonemainlogger so far i bypassed issue small hack the someotherclass actually debug instance so i call debugclonemainlogger instead selfclonemainlogger inside threadawarelogger the program works i consider really dirty edit if i add line selfcomptreeloggerdebugthreaawarelogger inside method eg clonemainlogger i getting attributeerror property object attribute debug conclusion i still understand solution,1 you use producerconsumer threads the threads synchronized using queuequeue edit example producerconsumer system threading import thread queue import queue def producequeue nitems rangenitems queueputd print put queueformatd def consumequeue nitems nitems you need sort stop condition queueget print got queueformatd def startproducerandconsumerwait q queue consumerthread threadtarget consume args q producerthread threadtarget produce args q producerthreadstart consumerthreadstart wait producerthreadjoin consumerthreadjoin name main startproducerandconsumertrue as see execute everything consumed correct order,imagine text file mb i reading char char extracting useful information i actually main functions one reading file second extracting info something like def readerpath f openpath r source fread fclose true i read char char call function extractor def extractors i extract useful information now goal continue read extractor working so basicaly question appropriate way accomplish goal,2 available x since using work correctly if upgrade get latest set commands able use command,i trying form fulltext search one mongodb collections la flowdock i create keywords entry document populate lowercased words fields document i search like prefixed search ex searchstring car foundshots connectionshotfind keywords recompile searchstringlowerlimitlimitskipskip the problem i try search multiple words ex searchstring car online regex recompile searchstringslower regex recompile searchstringslower foundshots connectionshotfind keywords regex keywords regexlimitlimitskipskip that work ideas please,1 groups empty since capturing groups httpdocspythonorglibraryrehtmlrematchobjectgroups group always returns whole text matched regardless captured group edited,when i run code print researchr groups i get result however group gives match shouldn groups give something containing match update thanks answers so means i research subgroups i use groups get match,3 creating closure self technically bind function alternative way solving similar underlying problem here trivial example selfmethod lambda self lambda args selfdoargsself,in python way bind unbound method without calling i writing wxpython program certain class i decided nice group data buttons together classlevel list tuples like class mywidgetwxwindow buttons ok onok cancel oncancel def setupself text handler mywidgetbuttons this following line problem line b wxbuttonparent labeltextbindwxevtbutton handler the problem since values handler unbound methods program explodes spectacular blaze i weep i looking around online solution seems like relatively straightforward solvable problem unfortunately i find anything right i using functoolspartial work around anyone know cleanfeeling healthy pythonic way bind unbound method instance continue passing around without calling,3 the reason capturing groups since use pattern httpdocspythonorglibraryrehtmlrematchobjectgroups and group returns entire search result even capturing groups httpdocspythonorglibraryrehtmlrematchobjectgroup,when i run code print researchr groups i get result however group gives match shouldn groups give something containing match update thanks answers so means i research subgroups i use groups get match,2 you groups regex therefore get empty list result try researchr groups with brackets creating capturing group result matches part pattern stored group then get result,when i run code print researchr groups i get result however group gives match shouldn groups give something containing match update thanks answers so means i research subgroups i use groups get match,1 to best knowledge groups returns tuple remembered groups ie groups regular expression enclosed parentheses so write print researchr groups would get response in general groups return tuple groups objects regular expression enclosed within parentheses,when i run code print researchr groups i get result however group gives match shouldn groups give something containing match update thanks answers so means i research subgroups i use groups get match,3 in qt pyqt events called signals bind using slots docs generally speaking define slot decorator class windowimpl qtguiqmainwindow uitremormain uigraphs def init self buffer parent none configuration none initialisation gui setup however qtcorepyqtslotint nameonconfselectorcombocurrentindexchanged def confchanged self newconf stuff handle event the would triggered currentindexchanged event object called confselectorcombo the setup confselectorcombo done gui builder qt creator nokia decided call this really want use get started there tutorials using qt creator obviously want go docs see signals emitted widgets as font stuff i know says docs if set font application default font machine used default font different different machines on windows default windows font used x one qtrc used if default font can’t found font specified qt used the qstylesheet qstyle act proxies changing appearance widgets qstylesheet qstyle as making application wait i found qtime dietime qtimecurrenttimeaddsecs qtimecurrenttime dietime qcoreapplicationprocesseventsqeventloopallevents there also qthreadsleep docs depending kind effect want probably also worth looking threading support nokia docs overall finding information stuff pyqt i found surprisingly useful look qt documentation writing stuff python times works on another note probably also worth looking pyside another python qt library i used works previously i noticed released version update just reiterate luke woodward use qgraphicsscene qgraphicsview render stuff object oriented way the qgraphicsscene actually render anything scene graph qgraphicsview used render contents scene graph for low level drawing thereâ´s also qpainter basic drawing tutorial it also worth looking qgraphicsitem base graphics items includes defining item geometry collision detection painting implementation item interaction event handlers docs the contextd provides html canvas i mistaken use webkit the canvas changed slot objects place canvas willcan slots there fairly complete looking tutorial contextd contextdcanvas for explanation many different ways rendering stuff ask someone else my two cents something fact qt supposed work everywhere trolltech later nokia wanted provide lots choice luckily docs really good,maybe i jumping deep end i give shot here useful features tkinter the tkinter canvas widget object oriented drawing canvas the elements drawing essentially widgets moved modified bound events tkinter uses bindings trigger callbacks the event passed string custom events easily created eventgenerate tkinter method waits specified amount time without freezing gui tkinter predefined fonts like tkdefaultfont colors like systembuttonface dependant system my questions what pyqt equivalents features especially bold ones how i bind elements widget eg label checkbutton event,1 httpsdocsdjangoprojectcomenstabletopicstestingtoolsdjangotestsimpletestcaseassertformerror djangotests import testcase class myteststestcase def testformsself response selfclientpostmyform something something selfassertformerrorresponse form something this field required where form context variable name form something field name this field required exact text expected validation error,i like simulate requests views django i writing tests this mainly test forms here snippet simple test request djangotests import testcase class myteststestcase def testformsself response selfclientpostmyform something something selfassertequalresponsestatuscode get page back error the page always returns response whether form error how i check form failed particular field soemthing error,3 it sounds like mean line profiler something measures time spent ie instrumenting within line i hope mean time wallclock time real goodsize software look cpu time going missing lot another way stacksampling wallclock time zoom ltprof profilers since every line stack sample localized line code using map pdb file way debuggers need parse modify source the percent time taken line code simply percent stack samples containing since working line level need distinguish exclusive self time inclusive time this line percent time active matters whether call another function call blind system function call microcode the advantage looking percents instead absolute times need worry app slowed either sampling competition processes things affect percents much also worry recursion if line code recursive function appears sample ok it still counts one sample containing line the reason ok line code could somehow made take time removing sample would occurred therefore samples containing line would removed sample set program total time would decrease amount fraction samples removed that irrespective recursion you also need count many times line code executed number matters locating code optimize percent time active here explanation issues,i trying determine necessary write line profiler language like available python matlab a naive way interpret line profiler assume one insert time logging around every line definition line dependent parser handles whitespace first problem it seems one needs use parse tree insert timings around individual nodes is conclusion correct does line profiler require parse tree needed beyond time logging update offering bounty question still unresolved update here link well known python line profiler case helpful answering question i yet able make heads tails behavior relative parsing i afraid code matlab profiler accessible also note one could say manually decorating input code would eliminate need parse tree automatic profiler update although question language agnostic arose i thinking creating tool r unless exists i found update regarding use line profiler versus call stack profiler post relating using call stack profiler rprof case exemplifies painful work call stack rather directly analyze things via line profiler,2 i know vpython perusing tutorial i would guess python range,after spending last months learning matlab seems i need switch vpython matlab colon operator comes handy often i found equivalent vpython for reference matlab is easy way thing vpython,1 use beautifulsoup parse returned html search image links you might also need recursively fetch frames iframes,i trying retrieve source webpage including images at moment i import urllib page urlliburlretrieve httpmyurlphp urlgotphp print urlgotphp retrieves source fine i also need download linked images i thinking i could create regular expression searched img src similar downloaded source however i wondering urllib function would retrieve images well similar wget command wget r noparent httpmyurlphp i want use os module run wget i want script run systems for reason i use third party modules either any help much appreciated thanks,2 you want embed python another application use pyrunanyfile run,i python dll already shipped installed end user guaranteed known version number how i use dll execute python scripts without shipping python interpreter,1 its documented fb sdk loginbutton page reason add autologoutlinktrue attribute tag show logout button logged rather making button invisible fbloginbutton autologoutlinktruefbloginbutton warning ignore tag using custom text login button like this always display button whether logged fbloginbutton autologoutlinktruelogin to my servicefbloginbutton,i apologize ahead time clearly documented somewhere fb developer site i find please link appropriate i implemented fb login button website using gae python here html fbloginbuttonfbloginbutton div idfbrootdiv script srchttpconnectfacebooknetenusalljsscript script fbinitappid adafcbefdebe status true cookie true xfbml true fbeventsubscribe authsessionchange functionresponse responsesession a user logged new cookie saved else the user logged cookie cleared script currently behavior i click login button i asked allow application access fb which i choose ok but login button still showing login logout how i implement on server client side,3 use mylist zipmylist original transposed ziporiginal transposed original transposed how works ziporiginal equal ziporiginal original original turn equal zip,i writing code parse tilemap map config file the map format numbers represent tiles i make integer array inttile tile rowsplit row nnlstripnsplitn this produces array format rowcolumn i would prefer columnrow xy i address backwards ie yx but i think concise ways attacking problem i considered reworking format using xml syntax tiled appears difficult beginner thanks advance responses,3 the webtest library helpful test cases httpwebtestpythonpasteorgenlatestindexhtmlformsubmissions,using webapp i create unit tests form checkboxes votes multiple values posted vote field retrieved via requestpostgetall vote input typecheckbox namevote valuebetter input typecheckbox namevote valuefaster input typecheckbox namevote valuestronger in unit test i tried passing list response appgetresponse vote post vote u better u faster u stronger headers contenttype applicationxwwwformurlencoded charsetutf but looks like simply converted string votes selfrequestpostgetall vote uu better u faster u stronger how i pass multiple values vote retrieved list via requestpostgetall,1 this could become heated discussion date logic usually much harder first looks everyone idea make things happen i would probably sacrifice db space models dumb possible eg define anomalies series the repeat condition could either simple terms would parsed depending requirements kiss interval next event occurs from generate next event copy repeat condition generate much events future practically necessary define max time window future generate events generate somebody fact looks time intervall question the events could pointer back parent event whole series identifiable like linked list the model indicator whether single event cancelled the event remains db able copy event future cancelling whole series deletes list events edit answers mentioned dateutil package interval building parsing really looks nice,i building calendar system ground requirement i working special type calendar alongside gregorian i need help logic i writing application django python essentially logical issues i running persist objects possible smartly possible without running tab cpu cycles i feeling polymorphism would solution i exactly sure express i two basic subsets events repeating events oneshot events repeating events subscribers people notified changes if example class canceled moved different address time people subscribed need know some events simply happen every day end time edited happen the problem i one object stores event info repeating policy canceling modifying one event series really screws things i account somehow keeping subscribers aware change keeping series together logical group paradox generating unique event objects normal event series end time repeats indefinitely make sense going store information however change happens single event series i almost create different object database represent cancellation can someone help logic it really twisting mind i really think straight anymore i really like input solve issue repeating events exactly easiest logical thing either repeat every day every mwf st m month every months year date week date month date tuesdays thursdays etc i like help understanding best route logic repeating events well here thought class eventseriesmodelsmodel seriesname modelstextfield seriesdescription modelstextfield seriesrepeatpolicy modelsihavenoideaintheworldonhowtorepresentthisfield seriesdefaulttime modelstimefield seriesstartdate modelsdatefield seriesenddate modelsdatefield location modelsforeignkey location class eventseriesanomalymodelsmodel eventseries modelsforeignkey eventseries relatednameexceptions overridename modelstextfield overridedescription modelstextfield overridetime modelstimefield overridelocation modelsforeignkey location eventdate modelsdatefield class eventseriescancellationmodelsmodel eventseries modelsforeignkey eventseries relatednamecancellations eventdate modelstimefield cancellationexplanation modelstextfield this seems make bit sense stated ruining brain right anything seems like would work another problem question someone wants modify remaining events series heck i i suppose i could change seriesdefaulttime generate anomaly instances past instances set original time ahhhhhh boiling three simple concrete questions how i series repeating events yet allow cancellations modifications individual events modifications rest series whole storing objects database absolutely necessary never generating objects individual events advance how i repeat events highly customizable way without losing mind i allow events repeat number ways making things easy storing objects possible how i allowing switch event series make happen falls holiday,2 don use regex perfectly good parser built python import urllib htmlparser import htmlparser baseurl http class imgparserhtmlparser def initself args kwargs selfdownloads htmlparserinitself args kwargs def handlestarttagself tag attrs tag img attr attrs attr src selfdownloadsappend attr imgp imgparser open testhtml f instead could feed original url obj directly imgpfeedfread path imgpdownloads url baseurl path print url urlliburlretrieveurl path,i trying retrieve source webpage including images at moment i import urllib page urlliburlretrieve httpmyurlphp urlgotphp print urlgotphp retrieves source fine i also need download linked images i thinking i could create regular expression searched img src similar downloaded source however i wondering urllib function would retrieve images well similar wget command wget r noparent httpmyurlphp i want use os module run wget i want script run systems for reason i use third party modules either any help much appreciated thanks,3 try arrayarray phase p array phase p returns boolean numpy array when idx boolean array arrayidx returns array composed rows idx true,i numpy rec array i would like quick queries similar sql select array phase p i would like get record array output row corresponding row original array met query criteria any ideas i pretty sure i done cannot remember function thanks recarray p p lr dtype eventid eventlat f eventlon f eventdepth f eventtime f stationid stationlat f stationlon f stationelv f phase s timeresidual f,3 emit warning instead let code decide handle,i number functions parse data files usually returning list results if i encounter dodgy line file i want soldier process valid lines return but i also want report error calling function the reason i want report calling function notify user file needs looking i want start gui things parse function seems big violation separation concerns the parse function access console i writing error messages anyway this leaves wanting return successful data also raise exception error clearly i consider code try parseresult parsemyfile except myerrorclass e handleerrorssomehowstre def parsefile file list lines actual file err false result lines file processedline processline processedline err true else resultappendprocessedline return result err raise myerrorclasssomething went wrong obviously last three lines make sense i figure nice way i guess i could return err result call like parseerr parseresult parsefile parseerr handleerrorssomehow but returning error codes seems unpythonic enough let alone returning tuples error codes actual result values the fact i feel like i want something strange application really terribly complicated making think i probably something wrong is better solution problem or way i use finally return value raise exception time,2 in principle wsgi intrinsically incompatible asynchronous program design fact pep goes considerable length specify servers applications middleware must behave support kind thing at heart returning iterator container every time asynchronous wsgi appiter invoked would check pending asyncronous tasks database connections etcetera data appiter yields data otherwise yields empty string to support wsgi container would need keep track inflight requests iterate turn get data addition servicing deferred work responsible in principle wsgi apps frameworks actually almost invariably wsgi frameworks block sorts reasons reading files disk loading data database reason most orm make tough problem prevent twisted wsgi container operates assumption since wsgi apps block perhaps wsgi app may block therefore always runs thread there two things either explore twisted web framework fairly solid consider creating wsgi wrapper twisted outside twisted container making sure wsgi app actually asyncronous certainly precondition latter wsgi pretty simple thin wrapper http easy enough,i building web interface twisted application would like use wsgi rather twistedweb directly since rest website wsgi i already substantial wsgi codebase the twisted documentation page i found wsgiresource httptwistedmatrixcomdocumentscurrentwebhowtowebinwsgihtml states like wsgi container anything asynchronous wsgi applications even though twisted wsgi container does true is lessthanhacky way twistedweb style asynchronous web request handling wsgi perhaps part another free software project supposing plan wsgi threads asynchronous work reactor thread block polling data available it pretty if reasonably uncomplicated way asynchronously handling wsgi requests twisted i love hear,3 nobody says valid way treat error throw exception in design caller wants two pieces information valid data whether error occurred probably something went wrong format useful error message that completely valid aboveground case returning pair values an alternative design would pass mutable collection function parameter let fill error messages wants emit that often simplify plumbing caller especially several layers calls parser code knows something error messages afterwards,i number functions parse data files usually returning list results if i encounter dodgy line file i want soldier process valid lines return but i also want report error calling function the reason i want report calling function notify user file needs looking i want start gui things parse function seems big violation separation concerns the parse function access console i writing error messages anyway this leaves wanting return successful data also raise exception error clearly i consider code try parseresult parsemyfile except myerrorclass e handleerrorssomehowstre def parsefile file list lines actual file err false result lines file processedline processline processedline err true else resultappendprocessedline return result err raise myerrorclasssomething went wrong obviously last three lines make sense i figure nice way i guess i could return err result call like parseerr parseresult parsefile parseerr handleerrorssomehow but returning error codes seems unpythonic enough let alone returning tuples error codes actual result values the fact i feel like i want something strange application really terribly complicated making think i probably something wrong is better solution problem or way i use finally return value raise exception time,3 if use numpy use numpyr import numpy np npr array npr array,after spending last months learning matlab seems i need switch vpython matlab colon operator comes handy often i found equivalent vpython for reference matlab is easy way thing vpython,1 try axon kamaelia it compatible pypy get actorflowbased programming significantly accelerated execution speeds pypy jit,is anything python concurrency like erlang particulary transparent actors networks i looked things like greenlet stackless seem network transparency actors i still quite jump hurdle erlangotp i interested something closer home,1 post data encoded using query string encoding multiple items name represented repeating key different values for instance votebetterampvotefasterampvotestronger python library functions though urlliburlencode vote better faster stronger true the second argument true urlencode called doseq instructs urlencode encode sequences lists separate elements,using webapp i create unit tests form checkboxes votes multiple values posted vote field retrieved via requestpostgetall vote input typecheckbox namevote valuebetter input typecheckbox namevote valuefaster input typecheckbox namevote valuestronger in unit test i tried passing list response appgetresponse vote post vote u better u faster u stronger headers contenttype applicationxwwwformurlencoded charsetutf but looks like simply converted string votes selfrequestpostgetall vote uu better u faster u stronger how i pass multiple values vote retrieved list via requestpostgetall,2 yes possible using translate function example translatenodenodename valname accountnumber output you use code line broken readability translate nodenodename straccountnumber valname accountnumber note white space included second argument translate even ampx necessary remove white spaces,okay i got example xml looks like node namedetails node name val nametypeuuval val nameownernval val nameaccountnumberuuval node node name val nametypeuuval val nameownernval val nameaccountnumberu uval node node name val nametypeuuval val nameownernval val nameaccountnumberuuval node node i trying search based accountnumber but many different formats could some spaces dashes mixture etc if i able search removing spaces dashes i able get account number with accountnumber search query ultimate goal get second level node name number search xpath doc libxmlparsedocxml ctxt docxpathnewcontext res ctxtxpathevalnodenodevalname accountnumber straccountnumber name is way use xpath search remove dashes spaces leave numbers thanks,1 i probably recommend download python official site configure aptana find you download latest version python httpwwwpythonorgdownload you specify whether using python x python x for compatibility reasons i probably go python x the latest bit windows version direct link httpwwwpythonorgftppythonpythonamdmsi after downloaded installed place python interpreter assuming use c windows drive cpythonpython you simply need point aptana to go preference left look pydev expand look section interpreter python in theory click auto config automatically detect cpython if simply need click new use file dialog prompt find cpythonpythonexe this also automatically import python libraries sitepackages installed well although fresh install stdlibs let us know issues cheers victor,i impression installing aptana studio also installed python interpreter i try create pydev project says project interpreter specified so let proceed is documentation proceed configuring interpreter studio i using latest build aptana studio standalone build thanks in advance assistance ps i already uninstalled reinstalled studio still issue i running windows bit machine,3 assuming fit whole log file memory i keep dictionary mapping thread ids lines written thread write whole files end threadmap keys thread ids values lists log lines line openfiletoopen sthdid line threadmap threadmapi threadmapiappendline key threadmap f openfolderpathkeylog w line threadmapkey fwriteline fclose if keep whole log file memory try multipass solution write file one time infile openfiletoopen sthdid infileseek reset file read beginning outfile openfolderpathilog w line infile line outfilewriteline outfileclose infileclose,i trying parse log file threadids every like there could number threads configured all threads write log file i parsing log file creating new files specific thread order check later below i capturing threadids list the code job i feel efficient can anything faster sthdid abc cdeefg folderpath newdir ossystemmkdir folderpath line openfiletoopen sthdid line openfolderpathilogawriteline,1 for event series model i created solution ihavenoideaintheworldonhowtorepresentthisfield use pickled object field save recurrence rule rrule dateutil event series model,i building calendar system ground requirement i working special type calendar alongside gregorian i need help logic i writing application django python essentially logical issues i running persist objects possible smartly possible without running tab cpu cycles i feeling polymorphism would solution i exactly sure express i two basic subsets events repeating events oneshot events repeating events subscribers people notified changes if example class canceled moved different address time people subscribed need know some events simply happen every day end time edited happen the problem i one object stores event info repeating policy canceling modifying one event series really screws things i account somehow keeping subscribers aware change keeping series together logical group paradox generating unique event objects normal event series end time repeats indefinitely make sense going store information however change happens single event series i almost create different object database represent cancellation can someone help logic it really twisting mind i really think straight anymore i really like input solve issue repeating events exactly easiest logical thing either repeat every day every mwf st m month every months year date week date month date tuesdays thursdays etc i like help understanding best route logic repeating events well here thought class eventseriesmodelsmodel seriesname modelstextfield seriesdescription modelstextfield seriesrepeatpolicy modelsihavenoideaintheworldonhowtorepresentthisfield seriesdefaulttime modelstimefield seriesstartdate modelsdatefield seriesenddate modelsdatefield location modelsforeignkey location class eventseriesanomalymodelsmodel eventseries modelsforeignkey eventseries relatednameexceptions overridename modelstextfield overridedescription modelstextfield overridetime modelstimefield overridelocation modelsforeignkey location eventdate modelsdatefield class eventseriescancellationmodelsmodel eventseries modelsforeignkey eventseries relatednamecancellations eventdate modelstimefield cancellationexplanation modelstextfield this seems make bit sense stated ruining brain right anything seems like would work another problem question someone wants modify remaining events series heck i i suppose i could change seriesdefaulttime generate anomaly instances past instances set original time ahhhhhh boiling three simple concrete questions how i series repeating events yet allow cancellations modifications individual events modifications rest series whole storing objects database absolutely necessary never generating objects individual events advance how i repeat events highly customizable way without losing mind i allow events repeat number ways making things easy storing objects possible how i allowing switch event series make happen falls holiday,1 you really need regex could use u u replace replace uu,i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks,2 the error message indicates two conflicting metaclasses somewhere hierarchy you need examine classes qt classes figure conflict here simple example code sets situation class metaatype pass class metabtype pass class a metaclass metaa class b metaclass metab we subclass classes directly python know metaclass use class brokena b pass traceback recent call last file stdin line module typeerror error calling metaclass bases metaclass conflict metaclass derived class must nonstrict subclass metaclasses bases what error trying tell us need resolve conflict two metaclasses introducing third metaclass subclass metaclasses base classes i sure clearer error message basically fix class metaabmetaa metab pass class fixeda b metaclass metaab this code compiles runs correctly of course real situation conflictresolving metaclass would decide parent metaclass behaviors adopt figure application requirements bear mind inherited class gets one two metaclass init methods sometimes work lot cases going add init calls way helps get along,looks like i stumbled upon metaclass hell even i wanted anything i writing app qt using pyside i want separate eventdriven part ui definition generated qt designer files hence i create controller classes ease life i multipleinherit anyways an example class basecontrollerqobject def setupeventsself parent selfwindow parent class maincontrollerbasecontroller pass class mainwindowqmainwindow uimainwindow maincontroller def initself parentnone supermainwindow selfinitparent selfsetupuiself selfsetupeventsself this works expected it also inheritance qdialog uidialog basecontroller but i subclass basecontroller try inherit said subclass place basecontroller i receive error typeerror error calling metaclass bases metaclass conflict metaclass derived class must nonstrict subclass metaclasses bases clarification both qmainwindow qdialog inherit qobject basecontroller must also inherit qt event system peculiarities ui classes inherit simple python object class i searched solutions involve cases intentionally using metaclasses so i must something terribly wrong edit my description may clearer adding graphs working example qobject object qmainwindow basecontroller uimainwindow maincontroller mainwindow another working example qobject object qdialog basecontroller uiotherwindow otherwindow not working example qobject object qdialog basecontroller uiotherwindow othercontroller otherwindow,3 there fork djangomaintenancemode allows turn maintenance mode onoff setting value database this way example create simple management command toggle maintenance mode call via fabric i think flexible using modrewrite,i currently using maintenancemodemiddleware put site maintenance mode requires make change settingspy file remote server i would like use fabric remotely put site maintenance mode is way achieve or better method thanks update thanks feedback everyone end i works great httpgarthhumphreyscompainlessdjangomaintenancemodewithfabric i like idea uncomment lines setup i production server would overwritten i pushed new version end putting site maintenance mode server level django level works lot better truly easier flexible least,1 using perl syntax u u start body end body ssg start body end xesg or python equivalent e g u u z sg pre start body end pre definedstart body ssg start body end,i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks,1 usu your pattern tell regex expect numbers usdu that get started python guy i give exact replacement syntax just aware digits repeating capture group edit this edit response comment like i said python guy probably need hold tongue right def replmatchobj matchobjgroup none return else return matchobjgroup source u u u u print resubr sdu repl source results uu uu if offends python deities i promise sacrifice next php developer i come across,i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks,2 i admittedly good regexes way i would doing match uu pair resub bit match using group that looks like examplestr u su vvfv tmp researchuuexamplestrgroup cleanstr resubdtmp,i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks,1 you expose correctly problem i firstly exactly understand having read comment tags u u tags i propose import ss kolu u maa print resub uu lambda mat joinc c matgroup c ss result koluu maa,i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks,1 there many things wrong code i going mark i strongly recommend read python control flow constructs comparison operators builtin data types alistwhatever goes data opencdocuments settingsbhaadesktopblablablatxtread the filename needs string value put c quotes words data data string iterating give one letter per iteration one word words aside syntax remember colons remember means executes body every item collection collection kind print words wrong words say think says operator takes arbitrary value left collection right returns single boolean value right words previous line printwrong spelling properly splled words right,exercise problem given word list text file spell check contents text file print unique words found word list i get solutions problem somebody tell i went correct answer as disclaimer none parses python console my attempt alistwhatever goes data opencdocuments settingsbhaadesktopblablablatxtread i aware something wrong since i get error i use itwhen i write blablablatxt says find thing is function gonna work i working online ivle program files automatically linked console would i things python without logging online ivle words data words print words wrong words right words printwrong spelling properly splled words right oh yehi sure i indented everything correctly i know format question come block like sorry what think,1 for starters httpwwwcsyncorg sort rsync since rsync works ssh ftp httpftp transfers if like option always lftp curlftpfs stackoverflow sistersite provides answer httpserverfaultcomquestionshowtousersyncoverftp that give anything well always ftplib python httpdocspythonorglibraryftplibhtml ftplib import ftp ftpretr ftp getftpcom connect host default port ftpretrlogin user anonymous passwd anonymous ftpretrretrbinary retr readme open readme wb write ftpretrquit ftpsend ftp sendtoftpcom login password ftpsendstorbinary stor todotxt open readme rb ftpsendquit now help tbh without everything guessing want learn use sysargv fetch inputoutput files also sourcehost desition perhaps enjoy,i two ftp server b i need copy files server b server downloading file upload b complicate i want write script python desktop type command job python syncftppy acomsource server folderfolder name source server b comdestination server folderdestination folder name google still find good way sync two ftp server like dropbox is way thanks,1 you mention fact received encoding error motivated write swedify first place found solutions around chcp windows command on nix systems utf terminals swedify necessary rawinput hur lã¥ngt kilometer ã¤r ditt mã¥l hur lã¥ngt kilometer ã¤r ditt mã¥l rawinput hur lã¥ngt kilometer ã¤r ditt mã¥l hur lã¥ngt kilometer ã¤r ditt mã¥l fwiw i use swedify i get error def swedifyinp try return inpdecode utf except return dec strinp swedify hur lã¥ngt kilometer ã¤r ditt mã¥l u hur lxengt kilometer xer ditt mxel rawinputswedify hur lã¥ngt kilometer ã¤r ditt mã¥l traceback recent call last file stdin line module unicodeencodeerror ascii codec encode character u xe position ordinal range your swedify function returns unicode object the builtin rawinput happy unicode objects rawinput㥠ã¥eee eee rawinputu㥠traceback recent call last file stdin line module unicodeencodeerror ascii codec encode character u xe position ordinal range you might want try python see python bug also interest how read unicode input compare unicode strings python update according blog post way set system default encoding this might worth try,i trouble python rawinput command python for reason rawinput get converted string swedify produces giving encoding error aware made swedify begin here trying elif cmd help hjã¤lp info buffert just nu ã¤r programmet relativt begrã¤nsatnde funktioner du har att anvã¤nda ã¤rn buffert historik skriver ut din historikn buffert ã¤ndra nã¥got ã¤ndrar nã¥got databasen fã¶ljande finns att ã¤ndran print swedifybuffert this works fine outputs swedish characters want console but try code x values print piece core goaldistance rawinputswedify hur lã¥ngt kilometer ã¤r ditt mã¥l core goaltime rawinputswedify vad ã¤r ditt mã¥l minuter att springa core goaldistance km p㥠then get cusersanonpython lã¶ppy traceback recent call last file lã·ppy line module core goaldistance rawinputswedify hur l├ã‘ngt kilometer ├ã±r ditt m├ã‘l unicodeencodeerror ascii codec encode character u xe position ordinal range now googled around found solutions none work sad create batch script executes chcp beginning clean solution imo here swedify def swedifyinp try return inpdecode utf except return dec strinp any solutions get rawinput read return value swedify tried encodings import getencoder getdecoder others nothing better,2 since e string add operator for example add r b set word boundary note raw string without r prefix b backspace e pattern r b reescapee r b remember escape e researchpattern researchpattern spam researchpattern group researchpattern spam eggs group string xgroup x refinditerpattern string,e equal i would like add regular expression search prevent match can anyone help i beat head i get syntax error i try append anything slice researche sresrematch object xc,1 found great table httpwikipythonorgmoinmovingtopythonfromotherlanguages python indexes slices sixelement list indexes enumerate elements slices enumerate spaces elements index rear index front lena b c e f slice front slice rear ba b shallow copy,i need good explanation references plus python slice notation to notation needs bit picking it looks extremely powerful i quite got head around,3 another possible design invert control passing error handler parameter also feel like tell python accumulate data list it knows already it hard make list comprehension work def samplehandler print omg i expecting oh well parseresult parsemyfile samplehandler def parsefile handler file list lines actual file result processline line data allresult handler ie falseish values result filternone result remove falseish values return result,i number functions parse data files usually returning list results if i encounter dodgy line file i want soldier process valid lines return but i also want report error calling function the reason i want report calling function notify user file needs looking i want start gui things parse function seems big violation separation concerns the parse function access console i writing error messages anyway this leaves wanting return successful data also raise exception error clearly i consider code try parseresult parsemyfile except myerrorclass e handleerrorssomehowstre def parsefile file list lines actual file err false result lines file processedline processline processedline err true else resultappendprocessedline return result err raise myerrorclasssomething went wrong obviously last three lines make sense i figure nice way i guess i could return err result call like parseerr parseresult parsefile parseerr handleerrorssomehow but returning error codes seems unpythonic enough let alone returning tuples error codes actual result values the fact i feel like i want something strange application really terribly complicated making think i probably something wrong is better solution problem or way i use finally return value raise exception time,1 depending caller design using callbacks might reasonable def gotlineline print got valid line line def goterrorerror print got error error def parsefile line error lines file processedline processline processedline errormyerrorclasssomething went wrong else lineprocessedline parsesomefile gotline goterror,i number functions parse data files usually returning list results if i encounter dodgy line file i want soldier process valid lines return but i also want report error calling function the reason i want report calling function notify user file needs looking i want start gui things parse function seems big violation separation concerns the parse function access console i writing error messages anyway this leaves wanting return successful data also raise exception error clearly i consider code try parseresult parsemyfile except myerrorclass e handleerrorssomehowstre def parsefile file list lines actual file err false result lines file processedline processline processedline err true else resultappendprocessedline return result err raise myerrorclasssomething went wrong obviously last three lines make sense i figure nice way i guess i could return err result call like parseerr parseresult parsefile parseerr handleerrorssomehow but returning error codes seems unpythonic enough let alone returning tuples error codes actual result values the fact i feel like i want something strange application really terribly complicated making think i probably something wrong is better solution problem or way i use finally return value raise exception time,1 you kill python interpreter ctrl this send sigquit instead sigint,usually i interrupt stuff ctrlc sometimes i using threads work example python r apr gcc linux type help copyright credits license information import time timesleep ctraceback recent call last file stdin line module k eyboardinterrupt import queue q queuequeuemaxsize qput qput qput qput cccccccc ccc cc c edit is way get back interpreter solutions far kill python completely existing namespace,2 well i new python seems proccommunicate procstdoutreadlinereadlines waits till process completed as per knowledge implement rotational logging redirect output file using subprocess fire tailf n xx logfile loop program ends print output whenever request user end,i subprocess constantly producing data data i interested however occasionally random times i need grab sample output thing i need read well defined boundaries for example let assume process produces constant bytes per second useful information comes chunks bytes after running seconds i ask see bytes output i would interested bytes inclusive but i ask seconds i want intercept get bytes i need wait see bytes otherwise process happily streaming output devnull i want ever block output stream my friend fred might also ask bytes say seconds i also need tee stuff make data available multiple consumers reading is existing design pattern kind thing how i implement python subprocess ensure communication subprocess nonblocking,1 finally i created login view calls djangocontribauthviewslogin internally,i added djangocontribauthviewslogin everywhere webpage i load templatetag returns authenticationform basehtml this templatetags includes registrationloginhtml template the login working ok i want redirect users page login now redirects whereveriamlogin wich shows registrationloginhtml login ok login fails messages without rest basehtml i followed django documentation so questions like i cannot redirect correctly i modified next variable seem work next requestgetfullpath redirects whereveriamlogin have tried something similar ideas update now question could something like do i declare login view i want include login form everywhere web page thank,1 a quick workaround c failing suspending process threads first z killing this works linux many cases c fails i tested works tested python v python r apr gcc linux type help copyright credits license information import queue q queuequeuemaxsize qput qput qput c keyboardinterrupt kill process z suspends exits shell stopped python mdf kill killed python,usually i interrupt stuff ctrlc sometimes i using threads work example python r apr gcc linux type help copyright credits license information import time timesleep ctraceback recent call last file stdin line module k eyboardinterrupt import queue q queuequeuemaxsize qput qput qput qput cccccccc ccc cc c edit is way get back interpreter solutions far kill python completely existing namespace,1 cselect inbox readonlytrue range typ msgdata cfetchstri rfc responsepart msgdata isinstanceresponsepart tuple msg emailmessagefromstringresponsepart header subject print headerupper msgheader this give idea retrieve subject,i using pythons imaplib connect gmail account i want retrieve top messages unread read matter display subjects sender name address know display contents inbox here code far successful connection import imaplib mail imaplibimapssl imapgmailcom maillogin mygmailgmailcom somecrazypassword maillist mailselect inbox need add stuff maillogout i believe simple enough i familiar enough commands imaplib library any help would must appreciated update thanks julian i iterate message retrieve entire contents typ data mailsearchnone all num datasplit typ data mailfetchnum rfc print message snsn num data mailclose i wanting subject sender is imaplib command items i parse entire contents data text subject sender update ok got subject sender part working iteration done desc order apparently showing oldest messages first how i change i tried range lendata lendata print data gives none iterations ideas i also tried mailsort reverse date utf all gmail doesnt support sort function update figured way code except need import email module mailselect inbox typ data mailsearchnone all ids data idlist idssplit get recent email id latestemailid int idlist iterate messages decending order starting latestemailid dictates reverse looping order range latestemailid latestemailid typ data mailfetch rfc responsepart data isinstanceresponsepart tuple msg emailmessagefromstringresponsepart varsubject msg subject varfrom msg remove brackets around sender email address varfrom varfromreplace varfrom varfromreplace add ellipsis subject length greater characters len varsubject varsubject varsubject print varfromsplit varsubject gives recent message subject sender address decending order requested thanks helped,3 you might want constantly read given stdout chunks bytes then list consumers might implemented functions taking stringsbytestrings depending x x each chunk sent every consumer discarded something like def fas pass def fbs pass consumers fa fb true chunk processstdoutread chunk break something like c consumers cchunk if run thread modify consumers wantneed but take care consumers block otherwise loop blocks that problem last long os gives quite large buffer subprocess but infinite so might need add buffering either per consumer loop,i subprocess constantly producing data data i interested however occasionally random times i need grab sample output thing i need read well defined boundaries for example let assume process produces constant bytes per second useful information comes chunks bytes after running seconds i ask see bytes output i would interested bytes inclusive but i ask seconds i want intercept get bytes i need wait see bytes otherwise process happily streaming output devnull i want ever block output stream my friend fred might also ask bytes say seconds i also need tee stuff make data available multiple consumers reading is existing design pattern kind thing how i implement python subprocess ensure communication subprocess nonblocking,1 since using django builtin developement server try remove following line urlspy urlpatterns staticfilesurlpatterns in production de better serve static files django use collectstatic command edit if settingspy try something like staticroot ospathjoinospathdirnamefile static staticurl static,i configured static settings like staticroot ospathjoinsiteroot static staticurl static staticfilesdirs js ospathjoinstaticroot js css ospathjoinstaticroot css staticfilesfinders djangocontribstaticfilesfindersfilesystemfinder djangocontribstaticfilesfindersappdirectoriesfinder djangocontribstaticfilesfindersdefaultstoragefinder urlspy urlpatterns patterns urlr login login name login urlr logout logoutthenlogin name logout urlr profilepuseridd profilesviewsdetail urlr profileedit profilesviewsedit urlpatterns staticfilesurlpatterns it works well url localhostlogin i get localhostprofileedit site handled profiles app staticurl changes paths static profilestatic javascripts stylesheets found what i wrong edit here would basehtml doctype html html head titleneighr block title endblock title meta httpequivcontenttype contenttexthtml charsetutf script typetextjavascript src staticurl jsjqueryminjsscript block script endblock head body block content endblock body html,1 i dont think something built django many many relation less connection table one possible solution would something like class bookmodelsmodel pass class bookconnectionmodelsmodel book modelsforeignkeybook contenttype modelsforeignkeycontenttype objectid modelspositiveintegerfield contentobject genericgenericforeignkey contenttype objectid class somemodelmodelsmodel pass class someothermodelmodelsmodel pass connect book models book bookobjectscreate somemodelobjectscreate somemodelobjectscreate someothermodelobjectscreate bookconnectionobjectscreatebookbook contentobjectm bookconnectionobjectscreatebookbook contentobjectm bookconnectionobjectscreatebookbook contentobjectm,i want make book model belongs multiple libraries collections references editors together is possible generic relations like contenttype genericgenericmanytomanycontenttype djangoconf import settings djangocontribcontenttypes import generic djangocontribcontenttypesmodels import contenttype djangodb import models djangoutilstranslation import ugettextlazy librarynamemaxlength getattrsettings librarynamemaxlength class librarymodelsmodel name modelstextfieldmaxlengthlibrarynamemaxlength verbosenameu desc modelstextfield class meta verbosename ulibrary verbosenameplural ulibraries class collectionmodelsmodel name modelstextfield description modelstextfield period modelstextfield class meta verbosename ucollection verbosenameplural ucollections class editormodelsmodel blabla class referencemodelsmodel title modelstextfield isbn modelstextfield editor modelsforeignkeyeditor pubdate modelsdatetimefieldautonowaddtrue def unicodeself return us selftitle selfisbn class meta ordering pubdate verbosename ureference verbosenameplural ureferences class bookmodelsmodel contenttype modelsforeignkeycontenttype objectpk modelstextfield contentobject genericgenericforeignkeyctfieldcontenttype fkfieldobjectpk title modelstextfield cover modelstextfield fields class meta verbosename ubook verbosenameplural ubooks,1 i use ironpythontoolsscriptspycpy create exe xcopy deployment instead installer,i using sharpdevelop visual studio ironpython app development i reasons using app development what console based options compiling ironpython exe file packaging manually is possible create executable app ironpython pack using installer,2 you try sqlalchemy the sqlalchemy object relational mapper presents method associating userdefined python classes database tables instances classes objects rows corresponding tables you refer following links httpwwwsqlalchemyorgdocs httpwwwrmunncomsqlalchemytutorialtutorialhtml,is module available connection mssql python i downloaded pymssql python is equivalent module python i aware anyone provide links important note meantime pymssql module available don miss read answer end page httpstackoverflowcoma,2 as jitter points earlier answer syscurrentframes gives need v for lazy following code snippet worked may help print sysstderr n stacktrace start n code threadid stack syscurrentframesitems codeappendn threadid threadid filename lineno name line tracebackextractstackstack codeappend file line filename lineno name line codeappend linestrip line code print sysstderr line print sysstderr n stacktrace end n,i trying dump list active threads including current stack i get list threads using threadingenumerate figure way get stack background a zopeplone app freaks time time consuming cpu needs restarted i feeling loop terminate properly cannot reproduce testenvironemt verification i managed register signal handler triggered outside trigger code soon situation occurs if i could dump stacktrace active threads would give clue goes wrong the hole thing runs python any ideas trace situations like appreciated cheers chriss,3 imho update happen automatically treeview connect treeview correctly dragdataget dragdatareceived methods and allows source destination enablemodeldragdest enablemodeldragsource methods there nothing treeview the model must updated calls dragdatareceiveddata delete specific insertbefore insertafter shown def dragdatareceiveddataself treeview context x selection info etime model treeviewgetmodel data selectiondata dropinfo treeviewgetdestrowatposx dropinfo path position dropinfo iter modelgetiterpath position gtktreeviewdropbefore position gtktreeviewdropintoorbefore modelinsertbeforeiter data else modelinsertafteriter data else modelappenddata contextaction gtkgdkactionmove contextfinishtrue true etime return this snippet comes httpwwwpygtkorgpygtktutorialsectreeviewdraganddrophtmldragdropreordering program treeviewdndpy works perfectly show need hope solves quest,i custom generictreemodel works fine now i want user able rearrange nodes using drag drop i move node new parent data model however treemodel wants notified using methods like rowhaschildtoggled rowdeleted rowinserted so apparently rowmoved calling rowdeleted original path rowinserted new path seems enough so i thought i may recursively issue changes consider following example a b c d now i move c a following things happened rowdelete c rowdelete d rowinserted c rowinserted d childtoggle a childtoggle b childtoggle c however gtk still complains inconsistent state model two things come mind maybe order calling functions relevant idea technically childtoggle also happens however row already deleted b rowhaschildtoggled needs treeiter reference i get exist maybe i following totally wrong approach what’s best way go,1 have look documentation universal feed parser the frontpage nothing examples import feedparser feedparserparsehttpfeedparserorgdocsexamplesatomxml feed title feed data dictionary u sample feed,i trying make atom reader python i familiar php i want equivalent commands python if i using php i would use filegetcontents parse atom maybe use simplexml parser is equivalent commands like filegetcontents also i downloaded universal feed reader python rssatom reader module but i cannot find example i want see least example using universal feed reader,3 you also use pyodbc connect mssql python the recent version available python from getting started guide import pyodbc cnxn pyodbcconnect driversql serverserverlocalhostdatabasetestdbuidmepwdpass cursor cnxncursor cursorexecuteselect userid username users rows cursorfetchall row rows print rowuserid rowusername the sqlalchemy library mentioned another answer uses pyodbc connect mssql databases tries various libraries pyodbc preferred one example code using sqlalchemy sqlalchemy import createengine engine createenginemssqlmepasslocalhosttestdb row engineexecuteselect userid username users print rowuserid rowusername,is module available connection mssql python i downloaded pymssql python is equivalent module python i aware anyone provide links important note meantime pymssql module available don miss read answer end page httpstackoverflowcoma,3 there many ways get up status network interface via polling ranging simply parsing ifconfig output reading status procnet pseudofiles however way notified ie poll events best option ubuntu use netplug package it installed default need sudo aptget install netplug some documentation httpmanpagesubuntucommanpageslucidmannetplugdhtml to set need tweak etcnetplugnetplugdconf etcnetplugnetplug scripts for example config files check section configuring netplug httpnatisbadorgdynnetindexhtml with etcnetplugnetplug python script called network goes downup generate kind event application,i writing python application running linux i want able register notified system network cable plugged i already using pyudev python bindings libudev order get notified usb plug events however network eth module example always remains loaded regardless cable plugged i dont get information i require it works updown events i read lot posts windows wmi providing functionality none linux am i looking right direction a python way python library would ideal i want integrate program,1 this valid equality function since transitive mfloat mfloat mfloat mfloat mfloat also note order used set must override hash following property holds instances b class b ⇒ hasha hashb set finds hashmfloat hashmfloat since set assumes property holds concludes mfloat mfloat without actually calling eq in summary works math import floor class ffloatfloat def eqselfother return floorself floorother def hashself return floorself mapffloat printseta output,a person asked question so get list unique function python alternative equality function i thinking could done inheriting element class overloading equality function import functools functoolstotalordering class ffloatfloat def eqselfother floorself floorother return true else return false def leselfother self return true else return floatself floatother def hashself return floorself mapffloat in out true in seta out set edit replaced abs equality floor equality added hash ps way make class factory class two lambda returns class inherits first one overriding needed equality function,3 el oslistdir cusersmyuser try check open show folder except windowserror pass,i working python javascript i problem specific part program i need show userclient contents specific directory i using python oslistdir this function giving contents directory even inaccessible folders i want show userclient i give example while exploring directory cusersmyuser i get oslistdir in oslistdir cusersmyuser out eclipse gimp hdfview matplotlib pylintd recentlyusedxbel xy appdata application data aptana rubles contacts cookies definixexfes locais desktop documents downloads dropbox favorites installanywhere links menu iniciar modelos music my documents nethood opensignals files os meus documentos pictures printhood recent saved games scitesession searches sendto thumbsdb tracing videos workspace ipython i access given folders for example application data cookies menu iniciar portuguese start menu modelos os meus documentos portuguese my documents nethood printhood sendto if i try access python i get error windowserror traceback recent call last cuserspluxipython console module windowserror error denied access cuserspluxcookies so question i detect inaccessible folders skip show user folders explore,2 your phylip file broken the header says sequences fixing current version biopython seems load file fine maybe use leninfoplex creating header line ps it would good idea include version biopython question,i trying something similar previous question my purpose join sequences equal but time instead letters i numbers alignment file found phylip file problem i try records listseqioparsefilefilename phylip i get error valueerror sequence length expected length i understand second file i creating first one worked perfectly below code used build alignment file flwrite flwritestr flwrite flwritestrsize flwrite n infoplex ref hrv flwritestri num leni flwrite num x flwritestrx flwrite n so interpret number since string any ideas thank,1 how utilizing inlineformsetfactory formfieldcallback param instead providing formset provide callable turns returns field used form form fields callback gets st parameter field kwargs optional params eg widget for example using requestuser filter replace another needed def myviewrequest setup code def getfieldqsfield kwargs formfield fieldformfieldkwargs fieldname client formfieldqueryset formfieldquerysetfilteruserrequestuser return formfield attendanceformset inlineformsetfactory formfieldcallbackgetfieldqs formset attendanceformsetrequestpost instancesession to better understand see usage formfieldcallback django formset code,i using inlineformsetfactory create fields many many relationship clients sessions intermediary attendance model i following views file attendanceformset inlineformsetfactory session attendance formsetbaseattendanceformset exclude user extra maxnum session sessionuserrequestuser formset attendanceformsetrequestpost instancesession and i needed override one form fields i added following formset base class class baseattendanceformsetbaseformset def addfieldsself form index superbaseattendanceformset selfaddfieldsform index formfields client formsmodelchoicefield querysetclientobjectsfilteruser now form works correctly i need pass value formset i filter clients displayed based current user rather using id can anyone help any advice appreciated thanks edit for anyone reading worked def getfieldqsfield kwargs fieldname client return formsmodelchoicefieldquerysetclientobjectsfilteruserrequestuser return fieldformfieldkwargs,3 myfile mylist osaccessmyfile osrok mylistpopmylistindexmyfile list include paths else need modify loop depending attributes,i working python javascript i problem specific part program i need show userclient contents specific directory i using python oslistdir this function giving contents directory even inaccessible folders i want show userclient i give example while exploring directory cusersmyuser i get oslistdir in oslistdir cusersmyuser out eclipse gimp hdfview matplotlib pylintd recentlyusedxbel xy appdata application data aptana rubles contacts cookies definixexfes locais desktop documents downloads dropbox favorites installanywhere links menu iniciar modelos music my documents nethood opensignals files os meus documentos pictures printhood recent saved games scitesession searches sendto thumbsdb tracing videos workspace ipython i access given folders for example application data cookies menu iniciar portuguese start menu modelos os meus documentos portuguese my documents nethood printhood sendto if i try access python i get error windowserror traceback recent call last cuserspluxipython console module windowserror error denied access cuserspluxcookies so question i detect inaccessible folders skip show user folders explore,1 the easiest way i think contents open file f line f linestartswith start pass contentsappendline contents joincontents sections contentssplitstop basically make use pattern behavior store list use pattern get sections,a file programinputtxt content start content stop start content stop how i iterate txt file i take content store different file iteration,1 i found powermock library suitable java resembels mockspy,following cool mocking python anyway also java mockpath ospath mockpathisdir mockreturnvaluefalse myobj myclass myobjinvokesomemethod myobjsomeothermethodassertcalledwithfalse anything like possible java meaning updating return values behavior objects instantiated inside object methods convenient way framework nicely thanks,1 your code work i taken liberty adapt bit imports also know document selfcon make compatible python i use moment works future import withstatement import threading queue urllib contextlib class threaderthreadingthread def initself queue url host threadingthreadinitself selfqueue queue selfurl url selfhost host def runself print selfurl contextlibclosingurlliburlopenselfurl u source uread print hey main name threaderqueuequeue httpwwwstackoverflowcom tstart tjoin edit works also contextlib,i figure problem code class threaderthreadingthread def initself queue url host threadingthreadinitself selfqueue queue selfurl url selfhost host def runself print selfurl httpwwwstackoverflowcom contextlibclosingurlliburlopenselfurl u source uread print hey printing source selfcon doc documentsource selfqueueputdoc selfhost when i run code print selfurl succesfully outputs url print hey working so basically i believe something contextlib blocking code i also tried conventional urlopen method without using contextlib work either furthermore i tried try except program raise error so may problem,1 i sure get buffer changed event however might good idea look connecting signal preeditchanged entry the preeditchanged signal emitted input method used typed text immediately committed buffer so interested text connect signal and get input check valid manipulate fields value accordingly,i want user able type float numbers decimal point show characters how i edit i need get values like nothing like e inconsistent values also rejected,1 port name incorrect correct ports pygtk pygtk pygtk updated recently renamed pypygtk pypygtk pypygtk,my python code uses gtk gui need run osx snow leopard lion unfortunately unofficial pygtk build crashes window gtk windows resize decided test macports version i installed python pygtk via following macports commands sudo port install python sudo port select set python python sudo port install pygtk running python console correctly starts macports version python but trying execute import gtk import pygtk fails error package available i feeling i missed something simple get work something like setting correct sitepackage macports python whatever maybe guru may share bit wisdom update careful examination revealed pygtk installed optlocallibpythonsitepackages leaving pythonsitepackages pythonsitepackages blank running macports version python allows use pygtk but i want python preferred,3 i want address question holidays in several reporting databases i found handy define table let call almanac one row date within certain range if range spans ten years table contain rows that small today standards the primary key date some columns things like whether date holiday normal working day weekend day i know i know could compute weekend stuff using built function but turns convenient include stuff data it makes joins simpler similar then one application program populates almanac it calendar quirks built including enterprise rules figuring days holidays you even include columns fiscal month given date belongs relevant case the rest application entry programs extraction programs treat almanac like plain old data this may seem suboptimal minimal but trust design pattern useful wide variety situations it figure applies case the almanac really subset principles data warehousing star schema design want thing inside cpu could almanac object public features almanacholidaydate,i building calendar system ground requirement i working special type calendar alongside gregorian i need help logic i writing application django python essentially logical issues i running persist objects possible smartly possible without running tab cpu cycles i feeling polymorphism would solution i exactly sure express i two basic subsets events repeating events oneshot events repeating events subscribers people notified changes if example class canceled moved different address time people subscribed need know some events simply happen every day end time edited happen the problem i one object stores event info repeating policy canceling modifying one event series really screws things i account somehow keeping subscribers aware change keeping series together logical group paradox generating unique event objects normal event series end time repeats indefinitely make sense going store information however change happens single event series i almost create different object database represent cancellation can someone help logic it really twisting mind i really think straight anymore i really like input solve issue repeating events exactly easiest logical thing either repeat every day every mwf st m month every months year date week date month date tuesdays thursdays etc i like help understanding best route logic repeating events well here thought class eventseriesmodelsmodel seriesname modelstextfield seriesdescription modelstextfield seriesrepeatpolicy modelsihavenoideaintheworldonhowtorepresentthisfield seriesdefaulttime modelstimefield seriesstartdate modelsdatefield seriesenddate modelsdatefield location modelsforeignkey location class eventseriesanomalymodelsmodel eventseries modelsforeignkey eventseries relatednameexceptions overridename modelstextfield overridedescription modelstextfield overridetime modelstimefield overridelocation modelsforeignkey location eventdate modelsdatefield class eventseriescancellationmodelsmodel eventseries modelsforeignkey eventseries relatednamecancellations eventdate modelstimefield cancellationexplanation modelstextfield this seems make bit sense stated ruining brain right anything seems like would work another problem question someone wants modify remaining events series heck i i suppose i could change seriesdefaulttime generate anomaly instances past instances set original time ahhhhhh boiling three simple concrete questions how i series repeating events yet allow cancellations modifications individual events modifications rest series whole storing objects database absolutely necessary never generating objects individual events advance how i repeat events highly customizable way without losing mind i allow events repeat number ways making things easy storing objects possible how i allowing switch event series make happen falls holiday,1 joblib handles result caching quite transparent way here example documentation joblib import memory mem memorycachedir tmpjoblib import numpy np npvandernparange square memcachenpsquare b squarea memory calling square squarearray square min c squarea the call trigger evaluation result cached the calculation results automatically saved disk joblib might suit needs,i program slow computations i wish debug algorithm now tedious always rerun everything i rather restart middle program can think clever way achieve the first vague idea define checkpoints i make function call i save locals large data pickle andor sqlite sqlite able inspect intermediate data later i could try call program telling restart specific checkpoint however i want split code chunks checkpoints purpose has someone clever idea solve debugging issue,1 the rawinput call blocking use asyncore you need add third player ie like class cmdlineclientasyncorefiledispatcher def initself sender file asyncorefiledispatcherinitself file selfsender sender def handlereadself selfsenderbuffer selfrecv import sys sender sender cmdline cmdlineclientsender sysstdin,i trying learn asyncore module so i decided develop chat program i listen network broadcast udp packages time but problem user typing message user cannot see messages sent another users what i my code usrbinpython coding utf import asyncore import socket class listenerasyncoredispatcher def initself port asyncoredispatcherinitself selfport port selfcreatesocketsocketafinet socketsockdgram selfsetsockoptsocketsolsocket socketsoreuseaddr selfbind selfport def handleconnectself print connected def handlereadself data addr selfrecvfrom print straddr data def handlewriteself pass class senderasyncoredispatcher def initself port asyncoredispatcherinitself selfbuffer selfport port selfcreatesocketsocketafinet socketsockdgram selfsetsockoptsocketsolsocket socketsobroadcast selfbind def handleconnectself print connected def handlereadself pass def handlewriteself selfbuffer sent selfsendtoselfbuffer broadcast selfport selfbuffer selfbuffersent def handlecloseself selfclose def serveforeverself asyncoreloopcount name main listener sender sender true senderserveforever senderbuffer rawinputmessage,3 i finally acceptable answer thanks so question how extract floating number string python numericconstpattern r optional sign etc etc etc etc etc followed optional exponent part desired ee selfrx recompilenumericconstpattern reverbose init part def validatefloatself widget entry entrytext entrygettext newtext selfrxfindallentrytext lennewtext entrysettextnewtext else entrysettext connected changed event entry many thanks helped,i want user able type float numbers decimal point show characters how i edit i need get values like nothing like e inconsistent values also rejected,1 if selecting trailing axes reshape trailing axes apply func axis def ffunc array start shape arrayshape tmp arrayreshapeshapestart indices functmp axis return npunravelindexindices shapestart,i writing code optimize quantities depend variable number parameters for optimization i would like apply index selecting functions numpyargmax numpyargmin across multiple axes below code i using right is builtin efficient approach perform task across arbitrary number axes may may sequential def ndargaxesfunc array start applies index selecting function trailing axes start ntrail lenarrayshapestart number trailing axes apply indices npzerosntrailarrayshapestart dtypenpintp npndindexarrayshapestart indicesellipsisi npunravelindexfuncarrayi arrayshapestart return tupleindices test showing ndargaxes indeed return correct indices array nparangereshape maxjs ndargaxesnpargmax array arraytuplenpindicesarraymaxjs npsqueezenpapplyoveraxesnpamax array axes,1 more work would put xpathlike selector would work valid dictionary key would foo eggs ham handled fooselect would ambiguous,is way define xpath type query nested python dictionaries something like foo spam eggs morefoo bar soap morebar bacon foobar print fooselectmorefoomorebar bacon foobar i also needed select nested lists this done easily jellybean solution def xpathgetmydict path elem mydict try x pathstripsplit try x intx elem elemx except valueerror elem elemgetx except pass return elem foo spam eggs morefoo bar soap morebar bacon bla balbla bla print xpathgetfoo morefoomorebarbacon edit this question accepted answer ancient the newer answers may job better original answer however i test i change accepted answer,1 is reason query way like xpath pattern as commenter question suggested dictionary access elements nest manner also considering data form json use simplejson module load access elements there project jsonpath trying help people opposite intend given xpath make easily accessible via python objects seems useful,is way define xpath type query nested python dictionaries something like foo spam eggs morefoo bar soap morebar bacon foobar print fooselectmorefoomorebar bacon foobar i also needed select nested lists this done easily jellybean solution def xpathgetmydict path elem mydict try x pathstripsplit try x intx elem elemx except valueerror elem elemgetx except pass return elem foo spam eggs morefoo bar soap morebar bacon bla balbla bla print xpathgetfoo morefoomorebarbacon edit this question accepted answer ancient the newer answers may job better original answer however i test i change accepted answer,1 the following function performs required editing operations transpose contents current buffer fut letmnsline ldgpurjs glet mmaxmcol exe norm ma em d silnorms exe norm n gj endf below oneline version letmnsline ldgpurjsexe glet mmaxmcol exe norm ma em d exe silnorms exe norm n gj,i know i use awk i windows box i making function others may awk i also know i write c program i would love create maintain compile something little vim utility i making the original file might the day was long the way was fast would become tt hh ee dw aa yy ww aa ss lf oa ns gt update golf rules apply selecting correct answer update python fans check mr duffy answer,1 not exactly beautiful might use sth like def xpathgetmydict path elem mydict try x pathstripsplit elem elemgetx except pass return elem this support xpath stuff like indices course mention key trap unutbu indicated,is way define xpath type query nested python dictionaries something like foo spam eggs morefoo bar soap morebar bacon foobar print fooselectmorefoomorebar bacon foobar i also needed select nested lists this done easily jellybean solution def xpathgetmydict path elem mydict try x pathstripsplit try x intx elem elemx except valueerror elem elemgetx except pass return elem foo spam eggs morefoo bar soap morebar bacon bla balbla bla print xpathgetfoo morefoomorebarbacon edit this question accepted answer ancient the newer answers may job better original answer however i test i change accepted answer,2 another alternative besides suggested jellybean def querydictd q keys qsplit nd k keys k continue k nd nd ndk else return none return nd foo spam eggs morefoo bar soap morebar bacon foobar print querydictfoo morefoomorebar,is way define xpath type query nested python dictionaries something like foo spam eggs morefoo bar soap morebar bacon foobar print fooselectmorefoomorebar bacon foobar i also needed select nested lists this done easily jellybean solution def xpathgetmydict path elem mydict try x pathstripsplit try x intx elem elemx except valueerror elem elemgetx except pass return elem foo spam eggs morefoo bar soap morebar bacon bla balbla bla print xpathgetfoo morefoomorebarbacon edit this question accepted answer ancient the newer answers may job better original answer however i test i change accepted answer,1 may metaclasses best choice needs lowlevel type but cases use name value module like mymodel type mymodel modelsmodel field modelsbooleanfield module name django uses module value determine django app owns model models myappmodelspy contain myappmodels django knows models filemodule belongs myapp application,i attempting dynamically construct classes subclasses django modelsmodel my code looks like mymodel type mymodel modelsmodel field modelsbooleanfield when django tries load gives following exception traceback recent call last file usrlibpythonsitepackagesdjangocoremanagementcommandsrunserverpy line innerrun selfvalidatedisplaynumerrorstrue file usrlibpythonsitepackagesdjangocoremanagementbasepy line validate numerrors getvalidationerrorss app file usrlibpythonsitepackagesdjangocoremanagementvalidationpy line getvalidationerrors appname error getapperrorsitems file usrlibpythonsitepackagesdjangodbmodelsloadingpy line getapperrors selfpopulate file usrlibpythonsitepackagesdjangodbmodelsloadingpy line populate selfloadappappname true file usrlibpythonsitepackagesdjangodbmodelsloadingpy line loadapp models importmodule models appname file usrlibpythonsitepackagesdjangoutilsimportlibpy line importmodule importname file homeuserprojectappmodelspy line module field modelsbooleanfield file usrlibpythonsitepackagesdjangodbmodelsbasepy line new module attrspop module keyerror module it seems like class constructed using type getting module member present class defined class what going,3 i think best way sort plugin thing using entrypoints api querying,while fairly trivial python import child module another module list attributes becomes slightly difficult want import child modules i building library tools existing d application each tool menu item sub menus i like tool responsible creating menus many change based context templates i like base module able find child modules check createmenu function call finds what easiest way discover child modules,1 you looking ospathwalk globglob enumerating files directory subtree osstat oslstat getting timestamp recent modification,i given task converting c script python script the aim script loop directories start end date mediadb calculate size zipfile going i stuck getting loop go directories different python c experience could anyone offer suggestions c code this loop core files directory sum file size directoryiterator diritmediadbcorefilesdir directoryiterator diritmediadbcorefilesdirdiritdirectoryiteratordirit also anyone ideas get last update timestamp file python would much appreciated the c code get last update timestamp file stdtimet lastwritetimedirit ptime filetimestamp fromtimett edit trying write statement firstly loops directories sums file size i dont need edit delete print directories get file sizes is appropriate use oswalk ospathgetsize secondly need retrieve last updated timestamp files tho dont really understand process getting timestamp,1 pep added support bytes literal python python adopted unicode language’s fundamental string type denoted bit literals either b string using bytes constructor for future compatiblity bytes introduced python but note bytes different serves different purpose x bytes the accurate concise explaination inclusion bytes python given new document,since version bytes function exist python i writing code compatible much versions python possible kind information important is good source find answer questions easily,3 i tell generatetilespy originally modified slightly a memoryerror indicates either requesting abnormally large image rendered found mapnik bug since former likely i figure made mistake modification generatetilespy so i took script overwrote latest version svn got diff differences httpsgistgithubcom on line likely want use otherwise making large x values invalid may cause large image requests wrong given tile,i trying create tiles using generatetilespy every time i run script i get following error exception thread thread traceback recent call last file usrlibpythonthreadingpy line bootstrapinner selfrun file usrlibpythonthreadingpy line run selftargetselfargs selfkwargs file rendertilespy line loop selfrendertiletileuri x z file rendertilespy line rendertile mapnikrenderselfm im memoryerror here script usrbinpython math import picossinlogexpatan subprocess import call import sys os queue import queue import mapnik import threading import random import argparse customfontsdir usrsharefonts mapnikregisterfontscustomfontsdir degtorad pi radtodeg pi default number rendering threads spawn roughly equal number cpu cores available numthreads def minmax abc maxab minac return class googleprojection def initselflevels selfbc selfcc selfzc selfac c rangelevels e c selfbcappendc selfccappendc pi selfzcappendee selfacappendc c def fromlltopixelselfllzoom selfzcintzoom e roundd floatll selfbczoom f minmaxsindegtorad floatll g roundd logffselfcczoom return eg def frompixeltollselfpxzoom e selfzczoom f px eselfbczoom g px eselfcczoom h radtodeg atanexpg pi return fh class renderthread def initself tiledir mapfile q printlock maxzoom selftiledir tiledir selfq q selfm mapnikmap selfprintlock printlock load style xml mapnikloadmapselfm mapfile obtain projection selfprj mapnikprojectionselfmsrs projects tile pixel coordinates latlong epsg selftileproj googleprojectionmaxzoom def rendertileself tileuri x z calculate pixel positions bottomleft topright p x p x convert latlong epsg l selftileprojfrompixeltollp z l selftileprojfrompixeltollp z convert map projection eg mercator coords epsg c selfprjforwardmapnikcoordll c selfprjforwardmapnikcoordll bounding box tile hasattrmapnik mapnikversion mapnikmapnikversion bbox mapnikboxdcxcy cxcy else bbox mapnikenvelopecxcy cxcy rendersize selfmresizerendersize rendersize selfmzoomtoboxbbox selfmbuffersize render image default agg renderer im mapnikimagerendersize rendersize mapnikrenderselfm im imsavetileuri png def loopself true fetch tile queue render r selfqget r none selfqtaskdone break else name tileuri x z r exists ospathisfiletileuri exists exists else selfrendertiletileuri x z bytesosstattileuri empty bytes empty empty tile selfprintlockacquire print name z x exists empty selfprintlockrelease selfqtaskdone def rendertilesbbox mapfile tiledir minzoommaxzoom nameunknown numthreadsnumthreads print rendertilesbbox mapfile tiledir minzoom maxzoom name launch rendering threads queue queue printlock threadinglock renderers rangenumthreads renderer renderthreadtiledir mapfile queue printlock maxzoom renderthread threadingthreadtargetrendererloop renderthreadstart print started render thread renderthreadgetname renderersi renderthread ospathisdirtiledir osmkdirtiledir gprj googleprojectionmaxzoom bboxbbox bboxbbox z rangeminzoommaxzoom px gprjfromlltopixelllz px gprjfromlltopixelllz print fromlattolon check directories place zoom z ospathisdirtiledir zoom osmkdirtiledir zoom x rangeintpxintpx validate x coordinate x z continue check directories place strx x ospathisdirtiledir zoom strx osmkdirtiledir zoom strx rangeintpxintpx validate x coordinate z continue stry tileuri tiledir zoom strx stry png submit tile rendered queue name tileuri x z queueputt signal render threads exit sending empty request queue rangenumthreads queueputnone wait pending rendering jobs complete queuejoin rangenumthreads renderersijoin name main minlon maxlon minlat maxlat bbox minlon minlatmaxlon maxlat stylefilehomemossplixprojectsdevmapitmapstatictilemillugandadistrictsxml tiledirhomemossplixprojectsunicefdevmapitmapstatictiles minzoom maxzoom rendertilesbbox stylefile tiledir minzoom maxzoom here mapnik config file mapnik config shapefile i compiled mapnik source good could problem,2 this swapping implemented sorted data structures class instances,i big class lots members quite references instances class lying around unfortunately reasonable reasons references wrong way around instead recreating finding updating everywhere objects referenced adding extra level indirection time i access class individually swapping members i defined method def swapself assertisinstanceother selfclass selfdict otherdict otherdict selfdict i instanceaswapinstanceb references instancea everywhere instancea instanceb the question it seems work fine i use slots feels like might reason i here actual use case i type implements comparison operators necessarily expensive way i various sorted datastructures containing objects type when i something one objects i know comparison order changed order data structures restored swapping modified object next bigger one,1 personobjectscreatename adam persontype appellant here persontype argument create method expects get persontype instance string so prowide perstype persontypeobjectsgetperstype appelant assuming perstype unique personobjectscreatename adam perstypeperstype taking account case appellant present db try perstype persontypeobjectsgetperstype appelant except persontypedoesnotexists persontype persontypeobjectscreateperstype appellant personobjectscreatename adam perstypeperstype,i new django sqlite i model person foreign key persontype class personmodelsmodel name modelscharfieldmaxlength perstype modelsforeignkeypersontype def unicodeself return selfname class persontypemodelsmodel perstype modelscharfieldmaxlength def unicodeself return selfperstype i trying add entries person using python managepy shell so far i tried import sqlite trialsmodels import conn sqliteconnect privydb print person returns class privytrialsmodelsperson cur conncursor fields name perstype row adam appellant personobjectscreatedictzipfields row but returns error valueerror cannot assign appellant personperstype must persontype instance the string appellant already stored one values persontypeperstype table what i need change get reference perstype field happy provide details needed thanks much time,2 you could use pythongestreamer playing works linux also work windows this requires pythongstreamer pythongobject i would recommend use allinone installer here code import os import sys import tkinter tkinter import gobject import gst def onsyncmessagebus message windowid messagestructure none messagestructuregetname preparexwindowid imagesink messagesrc imagesinksetproperty forceaspectratio true imagesinksetxwindowidwindowid gobjectthreadsinit window tkintertk windowgeometry x video tkinterframewindow bg videopacksidetkinterbottomanchortkintersexpandtkinteryesfilltkinterboth windowid videowinfoid player gstelementfactorymake playbin player playersetproperty videosink none playersetproperty uri files ospathabspathsysargv playersetstategststateplaying bus playergetbus busaddsignalwatch busenablesyncmessageemission busconnect syncmessageelement onsyncmessage windowid windowmainloop,is way play video files like avi mp etc i tried using pymedia apparently works pygame what solution problem,3 this works python x x fix python x try input rawinput except nameerror pass printhi inputsay something,import sys print sysplatform print rawinput i using python get rawinput freeze dos popup the book i reading i using what i fix,3 import joinllower l refindall azaz thisisagoodexample edit actually works first letter uppercase otherwise taken right thing def convertname resub azaz r name return resub azaz r slower,i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve,3 example thisisagoodexample don put underscore first character newexample example character example append underscore character uppercase characterisupper newexample newexample characterlower,i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve,1 when turn cherrypy tool particular url turned child url well so images css js parts config seem redundant so robotstxt section the faviconico would redundant except faviconico special cherrypy sets one typically attribute root object see cptreepy so overriding appropriate toolsstaticdiron true toolsstaticdirroot projectsmysitetrunkroot toolsstaticdirdir toolsstaticfileroot projectsmysitetrunkroot faviconico toolsstaticfileon true toolsstaticfilefilename imagesfaviconico,when i try browse faviconico instance i get error valueerror static tool requires absolute filename got faviconico i get anything images css js folders those serving fine the site looks acts great it darn two files here rootconf file toolsstaticdiron true toolsstaticdirroot projectsmysiteroot toolsstaticdirdir faviconico toolsstaticfileon true toolsstaticfilefilename faviconico toolsstaticdiron true toolsstaticdirdir images robotstxt toolsstaticfileon true toolsstaticfilefilename robotstxt toolsstaticdiron true toolsstaticdirdir images toolsstaticdiron true toolsstaticdirdir images css toolsstaticdiron true toolsstaticdirdir css js toolsstaticdiron true toolsstaticdirdir js here cherrypyconf file global serversocketport serverthreadpool toolssessionson true here startwebpy script import cherrypy rootroothandler import root cherrypyconfigupdatecherrypyconf cherrypytreemountroot rootrootconf hasattrcherrypyengine block syntax cherrypyenginestart cherrypyengineblock else syntax cherrypyserverquickstart cherrypyenginestart,3 here regex way import example thisisagoodexample print resub az example lower this saying find points string preceeded start line followed uppercase character substitute underscore then lowercase whole thing,i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve,3 indeed traditional cross validation fscore vmeasure scoring function would need labeled data ground truth but case could count number classes ground truth dataset use optimal value k hence noneed crossvalidation alternatively could use cluster stability measure unsupervised performance evaluation kind cross validation procedure however yet implemented scikitlearn even though still personal todo list you find additional info approach following answer metaoptimizecomqa in particular read clustering stability an overview ulrike von luxburg,in document clustering process data preprocessing step i first applied singular vector decomposition obtain u s vt choosing suitable number eigen values i truncated vt gives good documentdocument correlation i read now i performing clustering columns matrix vt cluster similar documents together i chose kmeans initial results looked acceptable k clusters i wanted dig bit deeper choosing k value to determine number clusters k kmeans i suggested look crossvalidation before implementing i wanted figure builtin way achieve using numpy scipy currently way i performing kmeans simply use function scipy import numpy scipy preprocess data compute svd u s vt svda a tfidf representation original termdocument matrix obtain documentdocument correlations vt this threshold obtained examining scree plot s docvectors numpytransposeselfvt prepare data run kmeans whitened whitendocvectors res idx kmeanswhitened iter assuming methodology correct far please correct i missing step stage standard way using output perform crossvalidation any referenceimplementationssuggestions would applied kmeans would greatly appreciated,1 if i mistaken would need git client install machine in event git installed try pip install httpsgithubcomfacebookpythonsdkzipballmaster pip install httpsgithubcomfacebookpythonsdktarballmaster you need install gitcore since git protocol associated anything sudo aptget install gitcore,i trying install package github using pip using following syntax pip install e githttpsgithubcomfacebookpythonsdkgiteggfacebooksdk getting error cannot find command git this question unchecked answers saying git needs installed system however answer states git subversion bazaar mercurial supported pip the pip documentation also says native support version control systems git mercurial bazaar so i install package pip i really want install git vps or nonpip tools pulling files repositories without full git install update i bit bullet installed git vps pip still able grab package giving different set errors progress i finally git clone httpgithubcomfacebookpythonsdkgit note http https manage download package installed manually,3 i using formalchemy httpdocsformalchemyorgpyramidformalchemy pyramid author wrote deform httpsdocspylonsprojectorgprojectsdeformdev,since pyramid form dependencies i need recommendations form handling this covers form generation validation etc i know wtforms i dont mind use thing advanced,2 i think looking findprevious could use way import beautifulsoup import content ul classbobby listrongvolume strongli li class hrefcontentbencchts titleissue september issue september li listrongvolume strongli li class hrefcontentbencchts titleissue december issue december li li class hrefcontentbencchts titleissue november issue november li ul lastvolume lastissue soupbeautifulsoupbeautifulsoupcontent results soupfind ul attrs class bobby astring resultsfindall textrecompile issue volumeastringfindprevioustextrecompile volume volumeintresearchr volumegroup issueintresearchr astringgroup hrefastringparent href volumelastvolume volumelastvolume issuelastissue printvolumeissuehref yields u contentbencchts u contentbencchts,i variables one last volume last issue the html i dealing contains list volumes issues recent first i need return href links volumes issues newer i file so using example say last volume last issue i would need return href vol vol i hard time since volume here i far html ul classbobby listrongvolume strongli li class hrefcontentbencchts titleissue september issue september li listrongvolume strongli li class hrefcontentbencchts titleissue december issue december li li class hrefcontentbencchts titleissue november issue november li ul script snipped results soupfind ul attrs class bobby temp i get reading file lastvol find last volume findlastvol resultsfindnext strong text recompile volume lastvol temp i get reading file lastiss find last issue findlastiss findlastvolfindnext text recompile issue lastiss so i get tag last volume issue file i several failed attempts traversing back stopping first issue or starting top traversing volume issue condition met can someone please give assistance thanks,1 pypy source contains purepython implementation sha poking around directory probably also find purepython implementations standard hashes,i looking implementation sha hash function written python i want use get better understanding sha function works i think python ideal language pseudocode limitation i runtest see modifications code output,3 disclaimer easily done explanation solution as slott pointed definitely technically correct behavior streamclose streamwrite called closed socket however i understand motivation question context wsgi app clients terminating connection full partial read exceptional behavior happens time for left unhandled leaves impression unexpected code unprepared fact expected worthy note so nice fix the catch find way distinguish cases situations like client read status closed connection client read bytes closed connection even though requested connection reused ones would appropriate issue sort logging besides logdebug call but situations like client stopped reading middle file connection died isp router stroke worthy error logged something successfully complete transactional state server app builtup rolled back in case ioerror propagating upwards right thing such errors silenceable every place could raised code modified distinguish two cases until wsgi authors seem erred side caution so quick fix i know also i note djangospecific i use pastepylons thing happen,i iphone app using web services implemented python using django piston running apache server wsgi sometimes app closes connection server call finished when causes tue sep error client modwsgi pid exception occurred processing wsgi script myscriptwsgi tue sep error client ioerror failed write data appear server error logs i fix problem app explicitly closing connection leaving finish downloading ignoring result however i like fix serverside possible how i,3 you set blocking signals using qobjectblocksignals httpdocqtnokiacomstableqobjecthtmlblocksignals bool qobjectblocksignals bool block if block true signals emitted object blocked ie emitting signal invoke anything connected if block false blocking occur the return value previous value signalsblocked note destroyed signal emitted even signals object blocked see also signalsblocked,i populating branch qtreewidget setting expanded attribute parent branch true the itemexpanded signal fires response i want is temporary way suppress absorb signals segment code,2 i really sure think need import sqlalchemyextsqlsoup sqlsoup import sqlalchemy engine sqlalchemycreateengine sqlitetestsqlite db sqlsoupengine res dbpeoplefilterbyid first enginedispose return res use queryfirst queryall create engine separately sqlsoup pass engine you dispose engine afterwards do note new pool created dispose engine database perminantly disconnected open connections closed new connections drawn new pool dispose operation,i using sqlsoup perform simple query my question i close engine thanks import sqlalchemyextsqlsoup sqlsoup db sqlsoup sqlitetestsqlite res dbpeoplefilterbyid return res,1 askopenfile returns opened file name need call open if really want name use askopenfilename instead seem necessary,why error appear error exception tkinter callback traceback recent call last file cpythonliblibtktkinterpy line call return selffuncargs file editorpy line onopen fileopened openfno w typeerror coercing unicode need string buffer file found code httpscodegooglecompchildreneditorsourcebrowsetrunkeditornewpy,2 you create cython declaration file pxd it shall contain declarations classes functions want import,i directory structure mymodule init py a initpy apyx b initpy bpyx in bpyx i want cimport functions aa a regular python import works cimport always fails also i compiling a b separately i figure put setuppy top module can anyone help,1 no a generator asynchronous this multiprocessing if want avoid waiting calculation use multiprocessing package independent process expensive calculation you want separate process calculating enqueueing results your generator simply dequeue available results,i generator takes long time iteration run is standard way yield value generate next value waiting called the generator would called time button pressed gui user would expected consider result button press edit workaround might def initialize res nextgen def btncallback displayres res nextgen res return,3 i think backwards print joinset,basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets,1 joinset the join string method set method,basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets,3 netaddr import allmatchingcidrs netaddr import allmatchingcidrs allmatchingcidrs ipnetwork here usage method helpallmatchingcidrs help function allmatchingcidrs module netaddrip allmatchingcidrsip cidrs matches ip address subnet given sequence ip addresses subnets param ip single ip address subnet param cidrs sequence ip addresses andor subnets return matching ipaddress andor ipnetwork objects provided sequence empty list match basically provide ip address first argument list cidrs second argument a list hits returned,given ip address say i check network say python are general tools python ip address manipulation stuff like host lookups ip adddress int network address netmask int hopefully standard python library,1 the join called string print joinset,basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets,2 nor set list method join string joinset b c by way use name list variables give list mylist name list often used python function,basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets,2 you join statement backwards try print joinset,basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets,1 sets join method use strjoin instead joinset the strjoin method work iterable object including lists sets note careful using sets containing integers need convert integers strings call join for example set joinstrs set,basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets,3 see httpcodegooglecompmodwsgiissuesdetailid if processing iterable message logged debug level python exception used thus see client closed connection problems iterable used need loglevel debug apparently would need tweak django response iterable instead string,i iphone app using web services implemented python using django piston running apache server wsgi sometimes app closes connection server call finished when causes tue sep error client modwsgi pid exception occurred processing wsgi script myscriptwsgi tue sep error client ioerror failed write data appear server error logs i fix problem app explicitly closing connection leaving finish downloading ignoring result however i like fix serverside possible how i,1 if use lxml module becomes much easier from lxml tutorial parser etreexmlparserremoveblanktexttrue lxmletree root etreexmlroot b b root parser etreetostringroot b rootab broot,is easy way accomplish thing python xsl accomplishes xslstripspace elements so instance following event elem elementtreeiterparsetmpexamplexml elemtag example print elementtreetostringelem example nodes printed spaces line feeds input file children example node removed,2 you definitely generators create generator next call alternates getting next value returning putting multiple yield statements here example import itertools time def quickgen counter itertoolscountnext def longrunningfunc timesleep return counter true x longrunningfunc yield yield x itr quickgen itrnext setup call takes two seconds itrnext returns immediately itrnext setup call takes two seconds itrnext returns immediately note generator automatically processing get next value caller call next twice value for use case would call next setup time user clicks button would display next value generated call next prefetch,i generator takes long time iteration run is standard way yield value generate next value waiting called the generator would called time button pressed gui user would expected consider result button press edit workaround might def initialize res nextgen def btncallback displayres res nextgen res return,1 strings foo bar applesplit,i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks,3 strings rfoo bar applesplit,i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks,1 you use subprocesspipe also split command use shlexsplit prevent strange behaviours cases subprocess import popen pipe shlex import split p popensplittar c mydir stdoutpipe p popensplitmdsum stdinpstdout but make archive generate checksum use python builtin modules tarfile hashlib instead calling shell commands,i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information,3 ok i sure seems work subprocesscalltar c mydir mdsumshelltrue anyone know original code work,i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information,1 you could place strings text file one string line then strings listopendatafile r,i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks,1 subprocess import popenpipe import hashlib proc popen tar c etchosts stdoutpipe stdout stderr proccommunicate hashlibmdstdouthexdigest acecf,i run normally command line linux tar c mydir mdsum but i try call python i get error subprocesspopen tar c mydir mdsum shelltrue subprocesspopen object xc tar you must specify one acdtrux testlabel options try tar help tar usage information,1 i would say easier way create list strings already as answers pointed ways put strings one big string file split opinion difficult type quotes particularly decent ide automatically closes string quotes also syntax already using anyone else reads code expect using something else adds unnecessary confusion almost zero gain,i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks,1 there two major differences posted the quotes indicate string like would list integers if remove quotes essentially creating list python objects a python object basically foundation python classes eg integers strings python objects basic level you something like foo foo bar bar apple apple strings foobarapple,i new python essentially trying figure syntax replicates functionality strings foo bar apple something similar strings foo bar apple i put quotes around entries thanks,1 runserver developmenttesting it handle high load security etc pythonorg docs set proper webserver serve python code httpdocspythonorghowtowebservershtml,as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see solution usually someone saying i hope using production i assume incorrect way to frustration people seem know command line insecure also desire share rest us excatly one initiate satchmo production server many thanks,1 the code kevin jacobs former question employs biopython uses sequences type seq â« essentially strings letters like agtacactggt seems natural since common way sequences seen biological file formats â» â« there two important differences seq objects standard python strings first different methods secondly seq object important attribute alphabet object describing individual characters making sequence string “mean” interpreted for example agtacactggt dna sequence protein sequence happens rich alanines glycines cysteines threonines the alphabet object perhaps important thing makes seq object string the currently available alphabets biopython defined bioalphabet module â» httpbiopythonorgdistdocstutorialtutorialhtml the reason problem simply seqioparse create seq objects file containing characters alphabet attribute able manage so must use another method not try plate inadapted method different problem here way itertools import groupby operator import itemgetter import regx recompile remultiline open pastierb f records regxfindallfread recordssortkeyitemgetter print lenrecords sn lenrecords n seqequal groupbyrecords itemgetter ids tuplex x equal lenids print ns joinids seq else n print nnumber unique occurences n result lenrecords number unique occurences edit i understood my problem i let fasta instead phylip code phylip valid value attribute alphabet works fine records listseqioparsefile pastierb phylip def seqgetters return strsseq recordssortkeyseqgetter ecr seqequal groupbyrecords seqgetter ids tuplesid equal lenids ecrappend sns joinidsseq print n joinecr produces there incredible amount characters interesting data i wonder but code useless see time import clock itertools import groupby operator import itemgetter import bio import seqio def seqgetters return strsseq clock open pastierb f records listseqioparsef phylip recordssortkeyseqgetter print clockt seconds clock regx recompile remultiline open pastierb f records regxfindallfread recordssortkeyitemgetter print clockt seconds result seconds seconds ratio,i trying something similar previous question my purpose join sequences equal but time instead letters i numbers alignment file found phylip file problem i try records listseqioparsefilefilename phylip i get error valueerror sequence length expected length i understand second file i creating first one worked perfectly below code used build alignment file flwrite flwritestr flwrite flwritestrsize flwrite n infoplex ref hrv flwritestri num leni flwrite num x flwritestrx flwrite n so interpret number since string any ideas thank,1 satchmo seems like django derivative setting django production quite easy deployment environment linux apache use modwsgi well documented windows use pyisapie module follow documentation hope helps,as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see solution usually someone saying i hope using production i assume incorrect way to frustration people seem know command line insecure also desire share rest us excatly one initiate satchmo production server many thanks,1 to deploy django website production server serve either apachemodwsgi nginxgunicorn nginxuwsgi server supporting wsgi the django documentation page deploying django apache modwsgi solutions plenty useful documentation around web,as experienced php programmer i tend avoid things like python however must play cards dealt i work satchmo website i little python django satchmo i need help i ok setting development server i cannot get website work production server i seen use python managepy runserver solution even stack overflow however i see solution usually someone saying i hope using production i assume incorrect way to frustration people seem know command line insecure also desire share rest us excatly one initiate satchmo production server many thanks,1 django automatically creates default permissions every model add delete change you getting integrity error trying create permissions name just remove delete meta description everything ok,i trying purge database mydb repopulate see effects changes django model then happened i rolled back earlier model setup i still get errors i mysql pro i can’t quite figure problem i tried creating new database another name didn’t happen i assume problem created django project here info cuserspython managepy syncdb creating tables creating table authpermission creating table authgrouppermissions creating table authgroup creating table authuseruserpermissions creating table authusergroups creating table authuser creating table authmessage creating table djangocontenttype creating table djangosession creating table djangosite creating table djangoadminlog creating table forumcategory creating table forumthread creating table forumpost you installed django auth system means superusers defined would like create one yesno yes username leave blank use admin email address exampleexamplecom password password superuser created successfully traceback recent call last file managepy line executemanagersettings file cpythonlibsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file cpythonlibsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file cpythonlibsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file cpythonlibsitepackagesdjangocoremanagementbasepy line execute output selfhandleargs options file cpythonlibsitepackagesdjangocoremanagementbasepy line handle return selfhandlenoargsoptions file cpythonlibsitepackagesdjangocoremanagementcommandssyncdbpy line handlenoargs emitpostsyncsignalcreatedmodels verbosity interactive db file cpythonlibsitepackagesdjangocoremanagementsqlpy line emitpostsyncsignal interactiveinteractive dbdb file cpythonlibsitepackagesdjangodispatchdispatcherpy line send response receiversignalself sendersender named file cpythonlibsitepackagesdjangocontribauthmanagementinitp line createpermissions contenttypectype file cpythonlibsitepackagesdjangodbmodelsmanagerpy line create return selfgetquerysetcreatekwargs file cpythonlibsitepackagesdjangodbmodelsquerypy line create objsaveforceinserttrue usingselfdb file cpythonlibsitepackagesdjangodbmodelsbasepy line save selfsavebaseusingusing forceinsertforceinsert forceupdateforceup date file cpythonlibsitepackagesdjangodbmodelsbasepy line savebase result managerinsertvalues returnidupdatepk usingusing file cpythonlibsitepackagesdjangodbmodelsmanagerpy line insert return insertqueryselfmodel values kwargs file cpythonlibsitepackagesdjangodbmodelsquerypy line insertquery return querygetcompilerusingusingexecutesqlreturnid file cpythonlibsitepackagesdjangodbmodelssqlcompilerpy line executesql cursor supersqlinsertcompiler selfexecutesqlnone file cpythonlibsitepackagesdjangodbmodelssqlcompilerpy line executesql cursorexecutesql params file cpythonlibsitepackagesdjangodbbackendsutilpy line execute return selfcursorexecutesql params file cpythonlibsitepackagesdjangodbbackendsmysqlbasepy line execute return selfcursorexecutequery args file cusersmeappdataroamingpythonpythonsitepackagesmysqldbcursorspy line execute selferrorhandlerself exc value file cusersmeappdataroamingpythonpythonsitepackagesmysqldbconnectionspy line defaulterrorhandler raise errorclass errorvalue djangodbutilsintegrityerror duplicate entry deletecategory key contenttypeid modelspy djangodb import models djangocontribauthmodels import user class categorymodelsmodel title modelscharfieldmaxlength class meta verbosenameplural categories permissions createcategory can create new categories editcategory can edit titles categories deletecategory can delete category mergecategory can merge multiple categories together class threadmodelsmodel creationdate modelsdatetimefield author modelsforeignkeyuser title modelscharfieldmaxlength category modelsforeignkeycategory class meta ordering creationdate permissions createthread create new threads editthread edit thread titles deletethread delete threads mergethread merge multiple threads together lockthread lock threads unlockthread open locked threads banuserinthread ban user post thread timeoutuserinthread ban user posting thread temporarily appointthreadmin give user modlike permissions thread class bookmarkmodelsmodel user modelsforeignkeyuser thread modelsforeignkeythread class subscriptionmodelsmodel user modelsforeignkeyuser thread modelsforeignkeythread class postmodelsmodel creationdate modelsdatetimefield author modelsforeignkeyuser thread modelsforeignkeythread content modelstextfield class meta ordering creationdate permissions createpost can create new post editpost can edit users posts deletepost can delete posts tablesinmydb authgroup authgrouppermissions authmessage authpermission authuser authusergroups authuseruserpermissions djangoadminlog djangocontenttype djangosession djangosite forumbookmark forumcategory forumpost forumsubscription forumthread mysql select djangocontenttype id name applabel model permission auth permission group auth group user auth user message auth message content type contenttypes contenttype session sessions session site sites site log entry admin logentry category forum category thread forum thread bookmark forum bookmark subscription forum subscription post forum post,3 i used pyc innosetup create installers you also download run wix command line without using develop visual studio the key make sure include dll need ngen install shorter start times better performance,i using sharpdevelop visual studio ironpython app development i reasons using app development what console based options compiling ironpython exe file packaging manually is possible create executable app ironpython pack using installer,1 do mean maximum filter if look scipyndimagemaximumfilterd as quick example import numpy np import scipyndimage ndimage input npsinnplinspace nppi input input astypenpint makes easier read output ndimagemaximumfilterdinput print in input print out output this yields in out,do happen d nonmaximum suppression algorithm written python i need making canny edge detector python using scipy takes input d intensity vector i looked around web lot information describing behavior canny edge detector examples written java describe edge detection d however scipy support algorithms needed canny edge detection namely gaussian filtering differentiation d thanks advance,1 you basically rand bend int result rand rangeend rangestart rangestart to explain rand generates random number across subset integer values you use modulo lo limit range numbers use start value provide offset also sure seed random number generator note rand apparently pretty lousy random number generator i idea see comments,just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart int rangeend int result rangestart rangeend return result int number randomrange i find equivalent question marks,1 first look how split list evenly sized chunks python using one answers import itertools networktable cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip l networktableii range lennetworktable l cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip now easy do want l joini n l cluster one primary system node one xxxx node ip node two xxxx node ipn cluster two primary system node one xxxx node ip node two xxxx node ipn,i building python script network inventory internal system each system five clusters i looking way adjust list put one line per cluster here way stored system cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip i need adjusted look like cluster oneprimary systemnode onexxxx node ipnode twoxxxx node ip cluster twoprimary systemnode onexxxx node ipnode twoxxxx node ip here really sloppy code i using right i wondering efficient way networktablecount lennetworktable count count networktablecount count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen networktopologywritetemp count count i self taught python may simple adjustment thanks advance,1 you trouble getting good randomness high values n include mathh pow include stdlibh drand long randomrangeint n method needs start size range rather start end long rangestart pown long rangesize pownrangestart expect rand functions offer randomness morewellknown rand function drand gives doubleprecision float scale rangesize start range return rangestart longdrand rangesize here another approach on bit platforms digits int make function return double generate string ascii digits convert include mathh pow include stdlibh atof arbitrary limit const int maxdigits double randomrangeint n char bignumstring maxdigits n maxdigits return first digit bignumstring rand int n subsequent digits zero bignumstringi rand terminate string bignumstringi convert float return atofbignumstring,just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart int rangeend int result rangestart rangeend return result int number randomrange i find equivalent question marks,2 you look facilities boost httpwwwboostorgdoclibsdochtmlboostrandomtutorialhtmlboostrandomtutorialgeneratingintegersinarange,just switch python c i begin rewrite python tools c better understanding solve one this function generate range random numbers example randomrange may return range numbers like python def randomrangen rangestart n rangeend n return randintrangestart rangeend number randomrange c int n int randomrangen int rangestart int rangeend int result rangestart rangeend return result int number randomrange i find equivalent question marks,2 you work around throwing exception catching middleware httpdjangosnippetsorgsnippets,i absolute novice djangocms i gone tutorial configured exactly mentioned documentation now i build application uses form upload products i dont clue move ahead i want start simple forms say username password textbox kind how i use django forms djangocms page i snippet plugin enabled i need guidance any suggestions plsss thanks,1 i think covered options you either subclass monkeypatch typically monkeypatching actually changing rd party class runtime frowned upon depending change need make may way work around bug make sure every time class used new method since tests use method tests monkeypatching unnecessary quite reasonable subclass testcase typically use monkeypatching needed augment method existing class for example wanted calls testcaseassertequal existing test cases augmented logic compare option objects could monkeypatch testcaseassertequal include custom logic plus normal logic something like originalassertequal testcaseassertequal def newassertequalself first second result originalassertequalfirst second isinstancefirst option isinstancesecond option custom comparison return result testcaseassertequal newassertequal however seems least example subclasses monkeypatches unnecessary assuming issue calling selfassertequalfirstoptions secondoptions fails even though option instances equal need write new assertoptionsequal method you probably need option objects define eq properly so assuming got class knowngoodinputstestcase def testgoodoptionsself first second systemundertestgetoptions selfassertoptionsequalfirst second what classes first second for python builtin types assertequal work for custom option class something like class optionobject def init self usefoo false usebar true def eqself selfusefoo otherusefoo selfusebar otherusebar return true return false then assuming first second instances option write test class knowngoodinputstestcase def testgoodoptionsself first second systemundertestgetoptions selfassertequalfirst second,i special cases i need test django i trying extend existing django tests writing test cases here i currently djangotests import testcase define method function def assertoptionsequalself first second logic pass attach method testcase class this feels inelegant testcaseassertoptionsequal assertoptionsequal tests go class knowngoodinputstestcase def testgoodoptionsself selfassertoptionsequal while works defining method function self first parameter attaching testcase feels inelegant is better way augmenting testcase class methods i class mytestcasetestcase def assertoptionsequalself first second use mytestcase tests wondering better alternative thanks,1 if i wanted something like workaround i write class like class prefetchedgeneratorobject def initself generator selfdata generatornext selfgenerator generator selfready true def nextself selfready selfprefetch selfready false return selfdata def prefetchself selfready selfdata selfgeneratornext selfready true it complicated version i made handles calling prefetch calling prefetch many times the basic idea call next want next item you call prefetch time kill your option thread class backgroundgeneratorthreadingthread def initself generator threadingthreadinitself selfqueue queuequeue selfgenerator generator selfdaemon true selfstart def runself item selfgenerator selfqueueputitem selfqueueputnone def nextself nextitem selfqueueget nextitem none raise stopiteration return nextitem this run separately main application your gui remain responsive matter long takes fetch iteration,i generator takes long time iteration run is standard way yield value generate next value waiting called the generator would called time button pressed gui user would expected consider result button press edit workaround might def initialize res nextgen def btncallback displayres res nextgen res return,1 ok i seems solution answer persay way moving multipoint differential i tested result looks similar moving regression i used d sobel filter ramp convolved data def kdpphidp dx fitlen kdpnpzerosphidpshape dtypefloat myshapekdpshape swn rangemyshape print sweep swn rayn rangemyshape print ray rayn kdpswn rayn sobelphidpswn rayn windowlenfitlendx return kdp def sobelxwindowlen sobel differential filter calculating kdp output differential signal unscaled gate spacing example snprxwindowlenxxwindowlen printlens wnparangewindowlenwindowlen print w wwabswsum ynpconvolvewsmode valid return ywindowlenlenxwindowlenwindowlen runs quick,i d array data wish extract spatial variation the standard way i wish pythonize perform moving linear regression data save gradient def nsslkdpphidp distance fitlen kdpzerosphidpshape dtypefloat myshapekdpshape swn rangemyshape print sweep swn rayn rangemyshape print ray rayn smallpolyfitdistanceaafitlen phidpswn rayn aafitlen xrangemyshapefitlen kdpswn rayn arraylistitertoolschainfitlensmall small fitlensmall return kdp this works well slow i need times i imagine overhead iterator arange line is implimentation moving fit numpyscipy,1 here reasons i think would wrong extra code complexity without big need adding one line settings every time bad especially step become explicit apps project using when another developer work project might know app installed step step code versioning system test whole system commit changes deploy i think something wrong point view developdeploy process looking optimization i think much easier better use installedapps if building something public use want make easy possible add modules would nice in case i would recommend package project apps python eggs make use entry points then could deploy app project like pip install myappname without even step step done pip step done setup hooks defined project paste script good example entrypoints utilization install paste script pip install pastescript install django templates pastescript pip install fezdjangoskel paste script knows fezdjangoskel entrypoints start new django project fez templates paste create djangobuildout here portion setuppy fezdjangoskel package entrypoints pastepastercreatetemplate djangobuildoutfezdjangoskelpastertemplatesdjangobuildouttemplate djangoappfezdjangoskelpastertemplatesdjangoapptemplate zcbuildout another great tool might make deployments much easier python eggs plays nice buildout,i written django app i want make easy deploy multiple servers the basic installation copy app folder django project folder add installedapps settingspy run managepy collectstatic this particular app need use db i use south run managepy migrate another story the part i trouble i want manually edit file every time what easiestmost robust way update i thinking i could use inspect module find variable somehow append i luck inspectgetsourcelines find variables,1 why use module directly pointed models singletons if create module like mymodulepy mydb import connection connection connection host port use import mechanism connection instance everywhere mymodule import connection of course define much complex initialization connection possibly via writing class point python initialize module provide objects every subsequent call i believe singleton borg patterns specific applications python part rely direct imports proven otherwise,i wondering implementing singleton class following httpcodeactivestatecomrecipesthesingletonpatternimplementedwithpython wondering blocking issues my code suppose cache sql statements execute cached statements using cursorexecutemanysql listofparams certain number cached elements reached specific executecall done user implementing singleton suppose make possible cache statements applicationwide i afraid i run blocking issues any thoughts,1 python enforced private anything convention letting others know methodfunctionclasswhathaveyou private prefix single leading underscore thirdparty programs use autodocumenting systems help idle ignore names your code would translate like class circleobject python need object member none needed since three initialized member none init others member none would def initself member selfmembermember selfrest def restself lots computing selfmemberresult selfmemberresult given comments code though would well make rest part init class circleobject python need object def initself member selfmembermember lots computing selfmemberresult selfmemberresult,i need following structure python public class circle int member int member int member public circlemember thismember member initializerest private intializerest lot computation get result amp result thismember result thismember result,1 i missing point question there takesnapshot function bit actually takes snapshot commented modify code look like following def takesnapshotselfwidget filename strtimetime jpg pixbuf gtkgdkpixbufgetfromdrawableselfmoviewindowwindow selfmoviewindowwindowgetcolormap pixbufsavefilename jpeg quality take snapshot save image current time,i code monitoring webcam python pygtk the question i take snapshot code usrbinenv python import sys os import pygtk gtk gobject import pygst pygstrequire import gst import time class webcam def initself window gtkwindowgtkwindowtoplevel windowsettitlewebcamviewer windowsetdefaultsize windowconnectdestroy gtkmainquit wm destroy vbox gtkvbox windowaddvbox selfmoviewindow gtkdrawingarea vboxaddselfmoviewindow hbox gtkhbox vboxpackstarthbox false hboxsetborderwidth hboxpackstartgtklabel selfbutton gtkbuttonstart selfbuttonconnectclicked selfstartstop hboxpackstartselfbutton false selfbutton gtkbuttonsnapshot selfbuttonconnectclicked selftakesnapshot hboxpackstartselfbutton false selfbutton gtkbuttonquit selfbuttonconnectclicked selfexit hboxpackstartselfbutton false hboxaddgtklabel set gstreamer pipeline selfplayer gstparselaunch vlsrc autovideosink bus selfplayergetbus busaddsignalwatch busenablesyncmessageemission busconnectmessage selfonmessage busconnectsyncmessageelement selfonsyncmessage windowsetborderwidth windowsetpositiongtkwinposcenteralways windowshowall def takesnapshotselfwidget filename strtimetime jpg selfmoviewindowwindowgetimage print snapshot def startstopself w selfbuttongetlabel start selfbuttonsetlabelstop selfplayersetstategststateplaying else selfplayersetstategststatenull selfbuttonsetlabelstart def exitself widget datanone gtkmainquit def onmessageself bus message messagetype gstmessageeos selfplayersetstategststatenull selfbuttonsetlabelstart elif gstmessageerror err debug messageparseerror print error err debug selfplayersetstategststatenull selfbuttonsetlabelstart def onsyncmessageself bus message messagestructure none return messagename messagestructuregetname messagename preparexwindowid assign viewport imagesink messagesrc imagesinksetpropertyforceaspectratio true imagesinksetxwindowidselfmoviewindowwindowxid name main try webcam gtkgdkthreadsinit gtkmain except keyboardinterrupt pass thanks,1 tar file headers include field modified time file act changing file even change later changed back mean tar file headers different leading different hashes,i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain and let know think workaround def getdirmddirpath build tar file directory return md sum temptarpath teststar tarfiletarfiletemptarpathmode w tadddirpath tclose hashlibmd mupdateopentemptarpath rb read retstr mhexdigest delete tar file osremovetemptarpath return retstr edit as fine folks answered looks like tar includes header information like date modified would using zip work differently another format any ideas work arounds,3 tar files contain metadata beyond actual file contents file access times modification times etc even file contents change tar file fact different,i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain and let know think workaround def getdirmddirpath build tar file directory return md sum temptarpath teststar tarfiletarfiletemptarpathmode w tadddirpath tclose hashlibmd mupdateopentemptarpath rb read retstr mhexdigest delete tar file osremovetemptarpath return retstr edit as fine folks answered looks like tar includes header information like date modified would using zip work differently another format any ideas work arounds,1 you need make tar file propose here workaround algorithm walk directory tree take md signature file sort signatures take md signature text string signatures individual files the single resulting signature looking heck even need python you find pathtodir type f name py exec mdsum awk print sort mdsum,i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain and let know think workaround def getdirmddirpath build tar file directory return md sum temptarpath teststar tarfiletarfiletemptarpathmode w tadddirpath tclose hashlibmd mupdateopentemptarpath rb read retstr mhexdigest delete tar file osremovetemptarpath return retstr edit as fine folks answered looks like tar includes header information like date modified would using zip work differently another format any ideas work arounds,2 as answers mentioned two tar files different even contents either due tar metadata changes file order changes you run checksum file data directly sorting directory lists ensure always order if want include metadata checksum include manually untested example using oswalk import os import ospath def getdirmddirroot build tar file directory return md sum hash hashlibmd dirpath dirnames filenames oswalkdirroot topdowntrue dirnamessortkeyospathnormcase filenamessortkeyospathnormcase filename filenames filepath ospathjoindirpath filename if metadata required add checksum filename good idea hashupdateospathnormcaseospathrelpathfilepath dirroot mtime possibly bad idea st osstatfilepath hashupdatestructpack ststmtime size good idea perhaps hashupdatebytesststsize f openfilepath rb chunk iterlambda fread b hashupdatechunk return hashhexdigest,i trying write python script get mdsum files directory linux which i believe i done code i want able run make sure files within directory changed files added deleted the problem i make change file directory change back i get different result running function even though i changed modified file back can anyone explain and let know think workaround def getdirmddirpath build tar file directory return md sum temptarpath teststar tarfiletarfiletemptarpathmode w tadddirpath tclose hashlibmd mupdateopentemptarpath rb read retstr mhexdigest delete tar file osremovetemptarpath return retstr edit as fine folks answered looks like tar includes header information like date modified would using zip work differently another format any ideas work arounds,3 it possible get email user connected app using graph however connecting signing using facebook users must explicitly give permission use email address since none friends gave permission email addresses limits what means encourage user friends join well make sure sign include request email address,i using djangosocialregistration facebook python sdk this code get friends friends requestfacebookgraphgetconnections friends i get name id i get email address facebookcom email this another attempt also get email friend friends data requestfacebookgraphgetobjectfriend id how i get facebook friends email,1 if want lock either use globals use threadlocal storage webapp fairly sure request cross thread boundary if global state avoided avoided this makes multithreading way easier implement debug i also disagree passing objects around makes application harder maintain — usually way around — global state hides dependencies addition requiring careful synchronisation well also lockfree approaches like stm whatnot probably overkill web application,after reading lot subject discussing irc response seems stay away threads sorry repeating question intention go deeper subject accepting threading evil answer hope find common solution edit just say no combined evils locking deadlocks lock granularity livelocks nondeterminism race conditions guido van rossum i developing python web application i like create global object user accessible current user example requested uri the suggested way pass object around imo makes application harder maintain beautiful code i need value different places might rd party plugins i see many popular frameworks django cherrypy flask use python threading locks solve issue if frameworks go pythonic way feel need create globally accessible object means community needs sort thing and is best way pass objects around is alternative solution use evil threading locks would pythonic store information database memcached thanks advance,3 i would proces lines based name begin seems cluster specifies new set data file open myfile clusters line filereadline linestripstartswithcluster cluster clusterappendlinestrip line filereadline clusterappendlinestrip line filereadline linestripstartswithnode node nodeappendlinestrip line filereadline nodeappendlinestrip clusterappendnode line filereadline clustersappendcluster list clusters nodes list printclusters printclusters,i building python script network inventory internal system each system five clusters i looking way adjust list put one line per cluster here way stored system cluster one primary system node one xxxx node ip node two xxxx node ip cluster two primary system node one xxxx node ip node two xxxx node ip i need adjusted look like cluster oneprimary systemnode onexxxx node ipnode twoxxxx node ip cluster twoprimary systemnode onexxxx node ipnode twoxxxx node ip here really sloppy code i using right i wondering efficient way networktablecount lennetworktable count count networktablecount count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen elif count temp networktablenetworktablenetworktablenetworktablenetworktablenetworktablen networktopologywritetemp count count i self taught python may simple adjustment thanks advance,1 read httpwwwsqlalchemyorgdocscoreschemahtmldefiningsequences key generation part database you simply want database assign unique keys,i created simple db using sqlalchemy python column unique user id user entered i want running counter supplies next id whenever new user added what would best way implement a column value last id number would entirely separate table seems wasteful is way check last userid add one here user base class class userbase tablename users id columninteger primarykey true emailaddress columnstring nullable false username columnstring nullable false password columnstring nullable false firstname columnstring fullname columnstring joindate columndatetime defaultfuncnow enters time upon initialization def initself emailaddress username password selfemailaddress emailaddress selfusername username selfpassword password def reprself return user selfemailaddress selfusername selfpassword selfjoindate,3 some additional details implement keyboardinteractive authentication i thought i working first time server sends two interactive requests the first requests contains prompt password false the second contains empty prompt the code works every server i tested far redhat ubuntu opensuse twistedconchssh import keys userauth class clientuserauthuserauthsshuserauthclient def getpasswordself prompt none normal password authentication print password auth return defersucceed your password def getgenericanswersself name instruction prompts interactive password authentication print interactive auth response lenprompts p enumerateprompts try password plower responsei your password except pass the response always sequence length always identical length prompts return defersucceedresponse enabling logging twisted helpful debugging conch hood well twistedpython import log logmsg started logging a conch program logstartloggingsysstdout,i trying override default authentication scheme twisted conch module something i thought i understood the script answer question i subclassing sshuserauthclient following way class clientuserauthsshuserauthclient def getpasswordself prompt none return defersucceed i obviously replacing sshuserauthclient call call class script for reasons i understand script executing getpassword method class superclass getpassword method does anyone know i wrong the change script i made i added following module import twistedinternet import defer thanks edit strangely subclass method getpublickey called correctly it getpassword method acting weird,2 you also use spynner allows programmatic web browsing,i’m writing little private app automatically log internet banking every day download latest transactions i’m writing django app i’m working python my internet banking doesn’t seem work without javascript — i think uses javascript assign session id sort fetching signin page via httplib gives page telling javascript’s required so i’m looking libraries fetch web pages execute javascript pretty much headless browsers i’m fiddling selenium moment i think it’ll job although designed testing web apps i wondering anything similar capabilities designed general purposes testing any python alternatives selenium sort thing,2 one thing might help use lists list comprehension statements loops eg qcount intrawinput how many questions per quiz quizitems strsamplerx x rangeqcount usersel mydictbookx x quizitems answers rangeqcount nextanswer intrawinput nwhich number sampleri answersappendbooksnextanswer,in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction thanks import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation title formatwelcome bible book quiznn selection rawinput the bible number strlenbooks booksn select next see belown formatnext exitn selection this section displays books bible indexes count indexmap bname enumeratebooks print nd formatcount bname indexmapcount count elif selection print title print n let start quiznnn else print you must select mydictbook genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation newdict dictfromkeysbooks counter print newdict try this section starts random book selection index match usersel print nnn here first books quiz n sampler randomsamplebooks first strsampler second strsampler third strsampler fourth strsampler fifth strsampler usersel mydictbookfirst mydictbooksecond mydictbookthird mydictbookfourth mydictbookfifth numsampler randomsampleusersel print sampler print nmatch correct numeric position print n numsampler samp intrawinput nwhich number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler taking users answer finding resultant book need put statement condition answerbookssamp answerbookssamp answerbookssamp answerbookssamp answerbookssamp taking book finding numeric value associated right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer display answers yield print nyour answers yieldn print stranswer print stranswer print stranswer print stranswer print stranswer takes random books converts strings first strsampler second strsampler third strsampler fourth strsampler fifth strsampler print numeric value string value correct answers print nthe correct answers print sampler mydictbookfirst tstmnt print sampler mydictbooksecond tstmnt print sampler mydictbookthird tstmnt print sampler mydictbookfourth tstmnt print sampler mydictbookfifth tstmnt continue except valueerror break,1 my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction i guess something like right wrong numsamp rawinputenter amount samples xrangenumsamp answer intrawinput nwhich number sampleri bookanswer sampleri rightright else wrongwrong,in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction thanks import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation title formatwelcome bible book quiznn selection rawinput the bible number strlenbooks booksn select next see belown formatnext exitn selection this section displays books bible indexes count indexmap bname enumeratebooks print nd formatcount bname indexmapcount count elif selection print title print n let start quiznnn else print you must select mydictbook genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation newdict dictfromkeysbooks counter print newdict try this section starts random book selection index match usersel print nnn here first books quiz n sampler randomsamplebooks first strsampler second strsampler third strsampler fourth strsampler fifth strsampler usersel mydictbookfirst mydictbooksecond mydictbookthird mydictbookfourth mydictbookfifth numsampler randomsampleusersel print sampler print nmatch correct numeric position print n numsampler samp intrawinput nwhich number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler taking users answer finding resultant book need put statement condition answerbookssamp answerbookssamp answerbookssamp answerbookssamp answerbookssamp taking book finding numeric value associated right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer display answers yield print nyour answers yieldn print stranswer print stranswer print stranswer print stranswer print stranswer takes random books converts strings first strsampler second strsampler third strsampler fourth strsampler fifth strsampler print numeric value string value correct answers print nthe correct answers print sampler mydictbookfirst tstmnt print sampler mydictbooksecond tstmnt print sampler mydictbookthird tstmnt print sampler mydictbookfourth tstmnt print sampler mydictbookfifth tstmnt continue except valueerror break,1 depending want handle edge cases seems work def pointsbetweenp p xs rangep p p ys rangep p p return xy x xs ys print pointsbetween print pointsbetween,this fairly easy i getting headache trying figure i want list coordinates two points like in or in it need work diagonals,1 you appear beginning programmer a general technique i find useful job paper look translate program if see break simpler steps,this fairly easy i getting headache trying figure i want list coordinates two points like in or in it need work diagonals,2 maybe django httpwwwgoogleplsearchqdjangotreemenu js httpwwwgoogleplsearchqjavascripttreemenu better jquery httpwwwgoogleplsearchqjquerytreemenu anyway simple cases hard make impl,i web app three frames banner menu content the menu frame needs dynamic rollup menu example teachers create edit delete schools create edit delete view staff classrooms create edit delete if click schools hideunhide items the menu needs dynamically drawn user login based user group role some users may authorized see classrooms edit users see everything is anything built plugin anyone used would provide framework i need,1 simple implementation using jquery div idmenu ateachersabr div styledisplay none hrefeditabr hrefdeleteabr div aschoolsabr div styledisplay none hrefeditabr hrefdeleteabr div div script typetextjavascript srchttpajaxgoogleapiscomajaxlibsjqueryjqueryminjsscript script typetextjavascript menu clickfunction thisnextnextslidetoggle return false script,i web app three frames banner menu content the menu frame needs dynamic rollup menu example teachers create edit delete schools create edit delete view staff classrooms create edit delete if click schools hideunhide items the menu needs dynamically drawn user login based user group role some users may authorized see classrooms edit users see everything is anything built plugin anyone used would provide framework i need,3 if absolutely know final size array increment size array like myarr numpyzeros range myarrnumpyconcatenate myarr numpyones printmyarr notice first line numpyappend another option it calls numpyconcatenate,i figure use array matrix way i would normally use list i want create empty array matrix add one column row time at moment way i find like mat none col columns mat none mat col else mat hstackmat col whereas list i something like list item data listappenditem is way use kind notation numpy arrays matrices,1 looks like smth windowsspecific did try provide full path python executable command line like ccodepythonbinpythonexe managepy celerydmulti start settingssettings l info also use full paths python file usefull ccodepythonbinpythonexe cpathtoyourprojectmanagepy celerydmulti start settingssettings l info,so far i working python managepy celeryd starting like python managepy celeryd l info settingssettings the code view binaryexectaskdelayrequestpostbinarypath and code settingspy import djcelery djcelerysetuploader brokerbackend djkombutransportdatabasetransport celery brokerhost localhost brokerport brokeruser guest brokerpassword guest brokervhost execute binaries background the thing binaries take pretty short time run others may take half hour working celeryd tasks blocked current one finishes execution i saw examples starting celerydmulti running python managepy celerydmulti start settingssettings l info gives error celerydmulti v starting nodes celeryx traceback recent call last file managepy line module executemanagersettings file ccodepythonlibsitepackagesdjangopyeggdjangocoremanagement line executemanager utilityexecute file ccodepythonlibsitepackagesdjangopyeggdjangocoremanagement line execute selffetchcommandsubcommandrunfromargvselfargv file ccodepythonlibsitepackagesdjangocelerypyeggdjcelerymanage scelerydmultipy line runfromargv argv argv argv file ccodepythonlibsitepackagescelerypyeggcelerybincelerydmul executefromcommandline selfcommandsargvargv cmd file ccodepythonlibsitepackagescelerypyeggcelerybincelerydmul start retcode selfwaitexecargv file ccodepythonlibsitepackagescelerypyeggcelerybincelerydmul waitexec pipe popenargstr envselfenv file ccodepythonlibsubprocesspy line init errread errwrite file ccodepythonlibsubprocesspy line executechild startupinfo windowserror error the system cannot find file specified the celerydmulti start c throws error what i i could succesfully start celery instance allow run tasks parallel also would i need something different view edit debugging led sitepackagescelerypyeggcelerybincelerydmultipywaitexec def waitexecself argv pathsysexecutable args joinpath listargv argstr shlexsplitargsencodeutf pipe popenargstr envselfenv pdb p argstr ccodepythonpythonexe managepy celeryddetach l info pidfilecelerydpid n celeryx logfilecelerydlog pdb p popenargstr envselfenv windowserror windowserror the system cannot find file specified pdb so see path python gets destroyed what i next edit i opened issue,1 two ideas come mind test another robust webserver nginx it run concurrently need see problem persists while paste handle web apps meant handle huge file transfers far i know are using chunked transfer encoding upload,so i rather vexing issue file uploads pylons i hoping someone might able assist originally i posted issue thinking issue pylons i since come conclude issue due server ie paste i tracked exactly issue occurs unsure resolve the behavior follows i pylons web application i serving via paster one piece application allows users upload files systems sometimes rather big mb during uploads server sporadically resets connection ie chrome error reads error neterrconnectionreset the connection reset this always occur time larger files on cases server never hands post application level no exception thrown least i find i narrowed issue cascadepy particular wsgiapplication method invoked httpserverpy from latter result selfserverwsgiapplicationselfwsgienviron selfwsgistartresponse in call function cascadepy file appears written temporary file the relevant loop begins copylen it writes chunks one one open file none writes individually throws exception however server often simply go away writes seemingly random time seem correlated either so i print copylen size decremented i watch decrease point server sudden sends connection reset least client thinks method seems exited copylen ceases printed loop exited though i completely stumped happens sporadically i seem track actual errorexception sort dies if matters i running paste python fedora os does anyone insight might happening i might able resolve thank much help,1 it like says fileopened openfno w that line code problem typeerror coercing unicode need string buffer file found that problem w string clearly fno causes problem the problem string buffer needed actually file you need string buffer filename parameter open the purpose open open files given file name already file so use file,why error appear error exception tkinter callback traceback recent call last file cpythonliblibtktkinterpy line call return selffuncargs file editorpy line onopen fileopened openfno w typeerror coercing unicode need string buffer file found code httpscodegooglecompchildreneditorsourcebrowsetrunkeditornewpy,1 you need set size request textview container scroll example window textview try following import gtk name main window gtkwindowgtkwindowtoplevel scroll gtkscrolledwindow scrollsetpolicygtkpolicynever gtkpolicyalways view gtktextview viewsetwrapmodegtkwrapchar scrollsetsizerequest scrolladdview windowaddscroll windowshowall gtkmain,i textview inside scrolledwindow refuses wrap wordscharswordschars matter i set wrap mode it simply extends size containers pleases here example import gtk window gtkwindowgtkwindowtoplevel windowsetdefaultsize scroll gtkscrolledwindow scrollsetpolicygtkpolicynever gtkpolicyalways view gtktextview viewsetwrapmodegtkwrapchar scrolladdview windowaddscroll windowshowall gtkmain how i make wrap if matters i need parent window resizeable user text,1 you use one following css rule graphicsviewsetstylesheetborderwidth px borderstyle solid graphicsviewsetstylesheetborder px your border disappear import sys pyqtqtgui import class uiqwidget def initself parentnone qwidgetinitself parent graphicsview qgraphicsview graphicsviewsetstylesheetborder px grid qgridlayout gridaddwidgetgraphicsview selfsetlayoutgrid app qapplicationsysargv ui ui uishow sysexitappexec here widget default style httpistackimgurcomgpwawpng and widget style applied httpistackimgurcomakupng,i tried calling selfsetstylesheetbackground transparent border transparent qgraphicsview still leaves pixel border top edge i also tried replacing border transparent borderstyle none work either here screenshot problem what command fully remove border qgraphicsview,2 after posting i discovered nifty little library ftputil httpftputilsschwarzernet presents different ftp interface cribs much os ospath modules possible using final code went roughly like import ftputil host ftputilftphostconstantsftphost constantsftplogin constantsftppass hostmakedirspath hostclose,i ftp ing pile files python directory trees may exist is ftp version makedirs available somewhere i build scratch,1 you actually creating entity key you change counter counterdbkeyfrompath counter defaultcounter counter counterkeydbkeyfrompath counter defaultcounter and since immediately setting amount could initializing entity well counter counterkeydbkeyfrompath counter defaultcounter amount please also note good way create counter app engine you want use technique like sharded counters something using memcached,i first small project pythongae difficulty operating gae database using queries but comes editing single entity i face problem all i need simple counter would increment every site visit so i create entity done create entity code removed project countername defaultcounter def counterkeycounternnone return dbkeyfrompath counter countername class counterdbmodel amount dbintegerproperty class counterclasswebapprequesthandler def getself counter countercounterkeycountername counteramount counterput it ok but i try increment using counter dbgetdbkeyfrompath counter defaultcounter counteramount counterput i get error error webapppy nonetype object attribute amount traceback recent call last file cprogram files xgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlerpostgroups file hgaebincounterpy line post counteramount attributeerror nonetype object attribute amount i checked different variations still cant change entity value what i wrong thanks advance,1 the code use create counter entity likely wrong what creating counter entity whose parent counter keyname equal defaultcounter that seem want evidenced code use update counter you need assign keyname counter entity via one following ways counter counterkeyname defaultcounter counter counterkeydbkeyfrompath counter defaultcounter note general bad idea visit counter like gae entities limti updates per seconds ever scale beyond run problems common technique dealing update limitation use sharding counters described httpcodegooglecomintlplappenginearticlesshardingcountershtml a combination datastore memcache also option mind occasionally losing counter increments,i first small project pythongae difficulty operating gae database using queries but comes editing single entity i face problem all i need simple counter would increment every site visit so i create entity done create entity code removed project countername defaultcounter def counterkeycounternnone return dbkeyfrompath counter countername class counterdbmodel amount dbintegerproperty class counterclasswebapprequesthandler def getself counter countercounterkeycountername counteramount counterput it ok but i try increment using counter dbgetdbkeyfrompath counter defaultcounter counteramount counterput i get error error webapppy nonetype object attribute amount traceback recent call last file cprogram files xgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlerpostgroups file hgaebincounterpy line post counteramount attributeerror nonetype object attribute amount i checked different variations still cant change entity value what i wrong thanks advance,1 import time timesleep this sleep seconds see httpdocspythonorglibrarytimehtmltimesleep,i working integrate api limit number requests per second is way running loop python delay cycle conceptually something like def functionrequest x abcd something wait seconds thank,3 create index tuple first index numpyst xindex,suppose i defined xx numpy array x numpyarangereshape now i get array containing element x subarray x returns array what i tuple mn want retrieve mn element subarray stored tuple for example suppose i i tried x right behaviour returns rows subarray the simplest solution i found xtransposetuplereversedttranspose i sure must better way of course case i could x generalised case i know many dimensions x,3 replace angle angle pi,i created simple polar plot using matplotlib i trying make plot degrees top clock position rather righthand side clock position i see simple way matplotlib documentation i found older question stackoverflow accepted answer seem work year old i thought may better way any ideas,2 perhaps i missing something django objects dict attribute seems want,if came google looking model dict skip question jump first answer my question confuse is good way django entire set model objects single dictionary i mean like class dictmodelmodelsmodel key modelscharfield value modelscharfield dictmodelobjectsalltodict result dictionary keyvalue pairs made records model has anyone else seen useful thanks update i wanted add ultimate goal able simple variable lookup inside template something like dictmodelexamplekey with result dictmodelobjectsgetkeyexactexamplekeyvalue overall though guys really surprised helpful allof responses different ways approach thanks lot update october this question top result google django modeltodict actually pretty awful given solves different problem i asking what i wanted able map instances queryset single dictionary specified model field key modeltodict hand converts single model instance dictionary now needs time pretty darn specific probably extremely rare i even remember project i needed so i would pretty surprised anyone looking information modeltodict going find question actually useful sorry modeltodict seems much common usage case i update dec i changed title hopefully better reflect original intent,2 collections import defaultdict dictb defaultdictlist b listb dictbb id appendb lista things b dictba id things appendb turn algorithm onm omon nlenlista mlenlistb basically avoids looping dict listb dict lista precalculating dicts listb match id,i lists dictionaries list a long list b long i essentially inserting list b dicts list a dicts based key match currently i obvious taking forever seriously like day there must quicker way lista things b listb id b id things appendb,2 here approach may help i leave fill details your code slow on algorithm comparing every a every b if sort lista listb id first onlogn operations iterate easily sorted versions a b linear time this approach common external merges large data sets mihai answer better internal merging simply index everything id memory if memory hold additional structures dictionary lookup constant time approach likely faster mention simpler by way example let say a following ids sorting acfgjp b ids sorting aaaabbbbcccddeeeefffggiikknnnnppppqqqrrr the idea strangely enough keep indexes a b i know sound pythonic at first looking a b so walk b adding things array once exhaust b move one a c but next item b b less c skip b then arrive c b start adding things c continue fashion lists exhausted just one pass,i lists dictionaries list a long list b long i essentially inserting list b dicts list a dicts based key match currently i obvious taking forever seriously like day there must quicker way lista things b listb id b id things appendb,1 there optional saveas parameter sendblob function by default set false setting true cause file treated attachment ie trigger saveopen download dialog user see proper filename example class servehandlerblobstorehandlersblobstoredownloadhandler def getself resource resource strurllibunquoteresource blobinfo blobstoreblobinfogetresource selfsendblobblobinfosaveastrue it also possible overwrite filename passing string selfsendblobblobinfosaveas myfiletxt if want content pdfs open rather save could use contenttype determine behavior blobinfo blobstoreblobinfogetresource type blobinfocontenttype type applicationpdf selfresponseheaders contenttype type selfsendblobblobinfosaveasfalse else selfsendblobblobinfosaveastrue,i using google app engine blobstore store range file types pdf xls etc trying find mechanism original filename uploaded file stored blobinfo used name downloaded file ie user sees somefilepdf save dialogue rather verylongdbkeypdf i see anything docs would allow httpcodegooglecomappenginedocspythonblobstoreoverviewhtml i seen hints posts could use information blobinfo set contentdisposition header is best approach achieving desired end,3 import logging class progressconsolehandlerloggingstreamhandler a handler class allows cursor stay one line selected messages onsameline false def emitself record try msg selfformatrecord stream selfstream sameline hasattrrecord sameline selfonsameline sameline streamwriteselfterminator streamwritemsg sameline streamwrite selfonsameline true else streamwriteselfterminator selfonsameline false selfflush except keyboardinterrupt systemexit raise except selfhandleerrorrecord name main import time progress progressconsolehandler console loggingstreamhandler logger logginggetlogger test loggersetlevelloggingdebug loggeraddhandlerprogress loggerinfo test range loggerinfo remaining seconds extra sameline true timesleep loggerinfo test notice one handler registered extra keyword argument let handler know stay one line there logic emit method handle changes messages stay one line messages need line,how write custom console log function output console window log messages single line append first regular log record progress progressconsolehandler console loggingstreamhandler logger logginggetlogger test loggersetlevelloggingdebug loggeraddhandlerconsole loggeraddhandlerprogress loggerinfo test range loggerprogress remaining seconds timesleep loggerinfo test so console output three lines info test remaining seconds info test any suggestions best way implement,3 you use javascript ajaxstyle post background save whatever information like click then redirect page success,the following html works user clicks word music shows html page ie httpssnuackrmusichtml href onclickparentcontentlocation httpssnuackrmusichtml return falsemusica my question user clicks word web way system server write clicked word music separate file server using python cgi i need store userclicked words separate file perform task server i stuck proceeding part any tips would helpful thanks,1 import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation mydictbook dictbnamei ibname enumeratebooksstart true selection rawinput the bible number booksn lenbooks select next see belown formatprint all books start quizn selection print n join formati bname ibname mydictbookiteritems break elif selection print nlet start quiznnformatwelcome bible book quiznn break else print you must select try numques intrawinput nenter number questions wanna asked sampler randomsamplebooks numques sampler exit numsampler maplambda bname mydictbookbname sampler print numsampler numsampler print nnnhere first books quiz ns nmatch correct numeric positions ns numques strsampler strrandomsamplenumsamplernumques samp intrawinput nwhich number booksi numsampler zipsampsampler yoursort print nyour answers yieldn n join nbk nbk correct zipnumsamplersampler correctsort print nthe correct answers n join nbk nbk correct continue except valueerror break,in code shows neophyteness python i took books kjv bible put logical order via list dictionary i used random method display random books user along position book random list user match something better learn books bible my difficulty figuring go saving results tallying number correctwrong i also would like give user option choose number questions like can someone give direction thanks import random import os name main books genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation title formatwelcome bible book quiznn selection rawinput the bible number strlenbooks booksn select next see belown formatnext exitn selection this section displays books bible indexes count indexmap bname enumeratebooks print nd formatcount bname indexmapcount count elif selection print title print n let start quiznnn else print you must select mydictbook genesis exodus leviticus numbers deuteronomy joshua judges ruth i samuel ii samuel i kings ii kings i chronicles ii chronicles ezra nehemiah esther job psalms proverbs ecclesiastes song solomon isaiah jeremiah lamentations ezekiel daniel hosea joel amos obadiah jonah micah nahum habakkuk zephaniah haggai zechariah malachi matthew mark luke john acts romans i corinthians ii corinthians galatians ephesians philippians colossians i thessalonians ii thessalonians i timothy ii timothy titus philemon hebrews james i peter ii peter i john ii john iii john jude revelation newdict dictfromkeysbooks counter print newdict try this section starts random book selection index match usersel print nnn here first books quiz n sampler randomsamplebooks first strsampler second strsampler third strsampler fourth strsampler fifth strsampler usersel mydictbookfirst mydictbooksecond mydictbookthird mydictbookfourth mydictbookfifth numsampler randomsampleusersel print sampler print nmatch correct numeric position print n numsampler samp intrawinput nwhich number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler samp intrawinput which number sampler taking users answer finding resultant book need put statement condition answerbookssamp answerbookssamp answerbookssamp answerbookssamp answerbookssamp taking book finding numeric value associated right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer right mydictbookanswer display answers yield print nyour answers yieldn print stranswer print stranswer print stranswer print stranswer print stranswer takes random books converts strings first strsampler second strsampler third strsampler fourth strsampler fifth strsampler print numeric value string value correct answers print nthe correct answers print sampler mydictbookfirst tstmnt print sampler mydictbooksecond tstmnt print sampler mydictbookthird tstmnt print sampler mydictbookfourth tstmnt print sampler mydictbookfifth tstmnt continue except valueerror break,1 you could add results another table unless compelling reason calculated column adjacent columns probably easiest there something said separating raw data calculations anyways if must increase size table look using hpy it provides direct interface h file keep mind depending data set created h file may possible simply append column data see section dataspace httpwwwhdfgrouporghdfdocugdatamodelhtml discussion regarding general data format hpy supports resize underlying dataset supports you could also use single buffer store input data like z zerosnrows n moredatainfile read data block zn fromfile yourparams set final column znn fzn append data tableshandleappendz,i trying append large dataset gb existing pytables table the table n columns dataset n columns one column calculated i know n columns i using numpyfromfile read chunks dataset memory appending database ideally i like stick data database calculate final column finish using tablemodifycolumn complete operation i considered appending numpyzeroslennewdata n table using tablemodifycolumns fill new data i hopeful someone knows nice way avoid generating huge array empty data chunk i need append,1 this get started i current time passed function datetime argument est work def findnextcurdt import datetime dt dttime dttime dttime dttime curt curdttime curd curdtdate rangelent ti curt rt tjilent j rangelent rd curd lenti curd dttimedeltadaysi return dtdatetimecombinerdjrtj j rangelenrt everything happens tomorrow return dtdatetimecombinecurd dttimedeltadays the result objects order starting soonest one,i need generate four datetime objects python the next instance am est the next instance am est the next instance pm est the next instance pm est then i need find closest current datetime i wish i could say i starting code i idea start one,1 hyry solution correct i always found numpy r c index tricks bit strange looking so equivalent thing using slice object xslicenone that single argument slice stop position ie none meaning way x equivalent xnonenone,suppose i defined xx numpy array x numpyarangereshape now i get array containing element x subarray x returns array what i tuple mn want retrieve mn element subarray stored tuple for example suppose i i tried x right behaviour returns rows subarray the simplest solution i found xtransposetuplereversedttranspose i sure must better way of course case i could x generalised case i know many dimensions x,2 you create yet another orm layer rather waste lot time reinventing wheel learn existing orm adapt one nosql database engine choice start example sqlalchemy orm want sql because python duck typing invent compatible nosql orm repository orm anything else think important do however reinvent wheel scratch read implementations sqlobject django orm sqlalchemy good places start,i wondering ways accomplish abstracting data storage access away main application small example ioc framework seems overkill maybe passing object via constructor parameter facade pseudocode good way things fill missing pieces python mainpy resp repositoryenginenosql easily switch nosql respsavehello respselecthello repositorypy class repository def initself engine selfengine engine def saveself str enginesavestr def selectself str engineselectstr nosqlpy class nosql def saveself str nosqlsavestr def selectself str nosqlselectstr mysqlpy class mysql def saveself str mysqlsavestr def selectself str mysqlselectstr,1 if columns type use numpylibstridetricksasstrided make array read file shape l n look like shape l n for example in numpyarangereshape in out array in astrides out in b numpylibstridetricksasstrideda shape strides in b out array now use array b fill table the last column row first column next row overwrite compute values this work record array ie complex dtype for try numpylibrecfunctionsappendfields as copy data new array save significant amount memory allow writing,i trying append large dataset gb existing pytables table the table n columns dataset n columns one column calculated i know n columns i using numpyfromfile read chunks dataset memory appending database ideally i like stick data database calculate final column finish using tablemodifycolumn complete operation i considered appending numpyzeroslennewdata n table using tablemodifycolumns fill new data i hopeful someone knows nice way avoid generating huge array empty data chunk i need append,1 here one wxpython httpwxgladesourceforgenet,i hoping find tool similar borland delphi visualbasic python basically i want able program windows apps ease without actually code every single widget does software exist thanks,3 based comment i would simply create book class author class author list chapter class assign chapters book list chapter objects book maintain authorlist dict ids pointing actual author objects use data member book object contain id provide method pull author authorlist dict convenience,following xml file bookxml xml version sample xml document bookstore book ide title sample xml book title author name idau first benjamin first last smith last name affiliation a affiliation author chapter number title first chapter title para b count count para chapter chapter number title third chapter title para b count count para chapter book book idc title xml master title author name idau first john first last doe last name affiliation c affiliation author chapter number title second chapter title para k count count para chapter chapter number title third chapter title para k count count para chapter chapter number title seventh chapter title para k count count para chapter chapter number title ninth chapter title para k count count para chapter book bookstore following python code bookdompy xmldom import minidom node import textwrap class samplescanner def initself doc child docchildnodes childnodetype nodeelementnode childtagname bookstore selfhandlebookstorechild def gettextself nodelist retlist node nodelist nodenodetype nodetextnode retlistappendnodewholetext elif nodehaschildnodes retlistappendselfgettextnodechildnodes return resub joinretlist def handlebookstoreself node child nodechildnodes childnodetype nodeelementnode continue childtagname book selfhandlebookchild def handlebookself node child nodechildnodes childnodetype nodeelementnode continue childtagname title print book title selfgettextchildchildnodes childtagname author selfhandleauthorchild childtagname chapter selfhandlechapterchild def handleauthorself node child nodechildnodes childnodetype nodeelementnode continue childtagname name selfhandleauthornamechild elif childtagname affiliation print author affiliation selfgettextchild def handleauthornameself node surname selfgettextnodegetelementsbytagnamelast givenname selfgettextnodegetelementsbytagnamefirst print author name surname givenname def handlechapterself node print start chapter nodegetattribute number selfgettextnodegetelementsbytagname title child nodechildnodes childnodetype nodeelementnode continue childtagname para selfhandleparachild def handleparaself node partext selfgettextnode partext textwrapfillpartext print partext print doc minidomparse bookxml samplescannerdoc output python bookdompy book id e book title sample xml book name id au author name smith benjamin author affiliation a start chapter first chapter b start chapter third chapter b book id c book title xml master name id au author name doe john author affiliation c start chapter second chapter k start chapter third chapter k start chapter seventh chapter k start chapter ninth chapter k my aim store books books table author info authors table preserving book author relationship mysql db book table id title e sample xml book chapter table bookidchapternumbertitle para e first chapter b e third chapter b author table id bookid name affiliation au e smith benjamin a how i go storing data database i thousand books authors chapters i trouble uniquely identifying dataset bookauthor i use ids pass functions preserve relation i sure best way any pointers highly appreciated ps i working sql part script update i test feel free post thoughts code samples thanks,1 here using qt designer qt httpdiotavellinetpyqtwikicreatingguiapplicationswithpyqtandqtdesigner you might also want look traits it pretty easy simple designs,i hoping find tool similar borland delphi visualbasic python basically i want able program windows apps ease without actually code every single widget does software exist thanks,2 datetimeastimezone basic conversion datetime object if trying get datetime object string pip install pythondateutil simple dateutilparser import parse dateutiltz import tzoffset dt parse datetimedatetime tzinfotzoffsetnone dtastimezonetzoffsetnone datetimedatetime tzinfotzoffsetnone,i timestamp timezone information string format i would like convert display correct datetime using local timezone so eg i timestamp i would like convert say timezone offset dsiplay timestamp i tried using pytz couldnt find many examples showing use offset information one link i found stackoverflow depicts exact problem i hoping better way i could handle using pytz thanks suggestions advance update thanks cixate i found solution similar found links helpful link link posting solution everyones benefit datetime import datetime import sys os import pytz dateutilparser import parse datestr dt parsedatestr print dt localtime dtastimezone pytztimezone australiamelbourne print localtimestrftime ymd hms,3 print u hello ä½ å¥½ bye encode unicodeescape hello ufud bye but consider using json via json,for example i file ajs whose content hello ä½ å¥½ bye which contains two chinese characters whose unicode form ufud i want write python program convert chinese characters ajs unicode form output bjs whose content hello ufud bye my code fp openajs content fpread fpclose fp openbjs w result contentdecodeutf fpwriteresult fpclose seems chinese characters still one character ascii string like i want,3 that actually limit underlying select system call from man page an fdset fixed size buffer executing fdclr fdset value fd negative equal larger fdsetsize result undefined behavior and standard fdsetsize usrincludelinuxposixtypeshdefine fdsetsize so python issue the poll epoll system calls much larger limit what really need use use selectepoll object still select module instead select,the workaround issue supervisord compile python supports file descriptors httpsgithubcomsupervisorsupervisorissues can someone please walk changes necessary accomplish i python source extracted ready go running centos matters thanks update ulimit n already set this full error i getting starting supervisord traceback recent call last file usrlocalbinsupervisord line loadentrypoint supervisora consolescripts supervisord file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line main gooptions file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line go dmain file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line main selfrun file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line run selfrunforever file usrlocallibpythonsitepackagessupervisorapyeggsupervisorsupervisordpy line runforever r w x selfoptionsselectr w x timeout file usrlocallibpythonsitepackagessupervisorapyeggsupervisoroptionspy line select return selectselectr w x timeout valueerror filedescriptor range select,1 you try codecs module codecsopenfilename mode encoding errors buffering codecsopenajs r cpread unicode object codecsopenbjs w utfwritea,for example i file ajs whose content hello ä½ å¥½ bye which contains two chinese characters whose unicode form ufud i want write python program convert chinese characters ajs unicode form output bjs whose content hello ufud bye my code fp openajs content fpread fpclose fp openbjs w result contentdecodeutf fpwriteresult fpclose seems chinese characters still one character ascii string like i want,1 the devappserver production environment concept projects libraries need structure app necessary libraries application root the easiest way usually symlink subdirectories worstcase copy using version control make subrepositories how maps operations ide depends ide general probably easiest get app structured need disk work backwards get ide set like,couple months i started development python c java background i currently working different pythonappengine applications often happens cases application share common code i would like refactor move commongeneric code shared place in either java c i create new library project move code new project add reference library main projects i tried python i unable make work i using eclipse pydev plugin i created new pydev project moved code attempted reference library project main projects using project properties project references add library src folder folder main projects case i error i presume possible leave project boundaries adding existing source folder add external library pretty much google libraries defined using properties external libraries import link import file system enabling create links workspace in cases i able reference library code developing i start debugging appengine development server throws exception find i moved separate library project of course i searched solution lot looks like nobody experienced problem maybe nobody need the closest solution i able find add ant script zip library sources copy target project way debugging pain i unable step library code any suggestion needless say proposed solution must take account library code included upload process appengine thanks,2 this called natsort natural sort a quick google gives httpwwwskynetiecaolanpackagespythonnatsorthtml tried though maybe helps oh necessarily ascii sort number order know like real axis,this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david,1 you need give sorted comparison function something like following sortedlist cmplambda x cmpx just write function need want plug you probably want something like reverse radix sort,this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david,1 a design patterns help prototype factory abstract factory use two patterns configuration objects each method take configuration object use needs also consider applying logical grouping config parameters think ways reduce number inputs psuedo code consider run three different kinds simulations sim sim sim configfactory configfactory new configfactorypathtooptionfile simulation sim simulation sim simulation sim simrun configfactoryconfigforsim simrun configfactoryconfigforsim simrun configfactoryconfigforsim inside factory method might create configuration prototype object sane defaults option file becomes things different default this would paired clear documentation defaults person program might want change edit also consider config returned factory subset overall config,lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need constructed depend many configuration options for example object might need several paths data stored options need passed algorithms object call options used directly object this leads objects needing large number arguments constructed additionally codebase active development big pain go call stack pass along new configuration option way needed one way prevent pain global configuration object freely used anywhere code i particularly like approach leads functions classes take one argument obvious reader data functionclass deals it also prevents code reuse code depends giant config object can anyone give advice program like structured here example i mean configuration option passing style class a def initself opta optb optz selfopta opta selfoptb optb selfoptz optz def fooself arg algoarg opta opte here example global config style class a def initself config selfconfig config def fooself arg algoarg config the examples python question stands similar programming langauge,1 pass around either config parsing class write class wraps intelligently pulls requested options python standard library configparser exposes sections options ini style configuration file using mapping protocol retrieve options directly though dictionary myconf configparserconfigparser myconfread myconfini whattodo myconf section option if explicitly want provide options using attribute notation create class overrides getattr class myconf def initself path selfparser configparserconfigparser selfparserread myconfini def getattrself option return selfparser whattodo section optionoption myconf myconf whattodo myconfwhattodo,lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need constructed depend many configuration options for example object might need several paths data stored options need passed algorithms object call options used directly object this leads objects needing large number arguments constructed additionally codebase active development big pain go call stack pass along new configuration option way needed one way prevent pain global configuration object freely used anywhere code i particularly like approach leads functions classes take one argument obvious reader data functionclass deals it also prevents code reuse code depends giant config object can anyone give advice program like structured here example i mean configuration option passing style class a def initself opta optb optz selfopta opta selfoptb optb selfoptz optz def fooself arg algoarg opta opte here example global config style class a def initself config selfconfig config def fooself arg algoarg config the examples python question stands similar programming langauge,1 convert float string first split sorteda keylambda xmapint strfloatxsplit,this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david,2 this kind hack v sorteda keylambda strtsplit intstrtsplit strt print v result disclaimer assumes places decimal point adjust accordingly,this might sound like silly question i tried find answer works without much success i got list lists v sortedlist print v i iterated list using sorted function however brings items ascii order sorted floats human readable order ie do i need create index somekind convert floats ints any help much appreciated david,1 matplotlib large package many configuration options it use rcparams module manage default parameters rcparams save default parameters dict every functions get options keyword argurments example def fxyoptanone optbnone opta none opta rcparams groupopta,lets say i program large number configuration options the user specify config file my program parse config file internally store pass around options in case software used perform scientific simulation there options sane defaults typically user specify dozen the difficulty i face design internal code many objects need constructed depend many configuration options for example object might need several paths data stored options need passed algorithms object call options used directly object this leads objects needing large number arguments constructed additionally codebase active development big pain go call stack pass along new configuration option way needed one way prevent pain global configuration object freely used anywhere code i particularly like approach leads functions classes take one argument obvious reader data functionclass deals it also prevents code reuse code depends giant config object can anyone give advice program like structured here example i mean configuration option passing style class a def initself opta optb optz selfopta opta selfoptb optb selfoptz optz def fooself arg algoarg opta opte here example global config style class a def initself config selfconfig config def fooself arg algoarg config the examples python question stands similar programming langauge,3 particularly given technique knearest neighbors mentioned q would strongly recommend scikitslearn note answer posted lead developer project informed new homepage project a features believe distinguish library others least python ml libraries used extensive diagnostics amp testing library including plotting modules via matplotlibincludes featureselection algorithms confusion matrix roc precisionrecall etc nice selection batteriesincluded data sets including handwriting digits facial images etc particularly suited ml techniques extensive documentation nice surprise given project two years old including tutorials stepbystep example code use supplied data sets without exception least think moment python ml libraries superb see pymvpa homepag e list dozen popular python ml libraries in past months instance used ffnet mlp neurolab also mlp pybrain qlearning neurolab mlp pymvpa svm available python package index vary significantly wrt maturity scope supplied infrastructure found high quality still best might scikitslearn instance aware python ml libraryother scikitslearnthat includes three features mentioned though solid example code andor tutorials none know integrate library researchgrade data sets diagnostic algorithms second given technique intend use knearest neighbor scikitslearn particularly good choice scikitslearn includes knn algorithms regression returns score classification returns class label well detailed sample code using scikitslearn knearest neighbor module literally easier import numpy relevant scikitslearn module import numpy np sklearn import neighbors knn load one sklearnsuppplied data sets sklearn import datasets iris datasetsloadiris call loadiris loaded data class labels bind variable data irisdata classlabels iristarget construct classifierbuilder instantiating knn module primary class knn knnneighborsclassifier construct train classifier passing data class labels classifierbuilder knnfitdata classlabels neighborsclassifiernneighbors leafsize algorithm auto what unlike nearly ml techniques crux knearest neighbors coding working classifier builder rather difficult step building productiongrade knearest neighbor classifierregressor persistence layerie storage fast retrieval data points nearest neighbors selected for knn data storage layer scikitslearn includes algorithm ball tree know almost nothing apparently superior kdtree traditional data structure knn performance degrade higher dimensional features space additionally knearest neighbors requires appropriate similarity metric euclidean distance usual choice though always best one scikitslearn includes standalong module comprised various distance metrics well testing algorithms selection appropriate one finally libraries mentioned either scope pyml bayesian primarily libraries developers rather applications end users eg orange unusual difficulttoinstall dependencies eg mlpy requires gsl turn must built source least os mac os x note developercommitter scikitslearn,i need classify data i hope nearestneighbour algorithm i googled problem found lot libraries including pyml mlpy orange i unsure start how i go implementing knn using python,3 to make mouse look right direction i try pygametransformrotate make degrees rotation depend directionx directiony variables greater less zero,i learning python pygame working simple game play mouse avoid snakes spawn every seconds roam across screen right i trying get mouse sprite face direction moving the image mouse facing i tried couple ideas get face right direction nothing worked hoping someone could help here code collision detection yet basic code mouse still usrbinpython imports import os sys math import pygame random pygamelocals import sets path game images maindir ospathsplitospathabspathfile datadir ospathjoinmaindir data pygameinit main screen background width height screen pygamedisplaysetmodewidth height pygamedisplaysetcaptiondon get eaten background pygameimageloadospathjoindatadir liquidbmp background pygametransformscalebackground width height screenblitbackground game time setup clock pygametimeclock pygametimesettimeruserevent functions assist image loading def loadimagefile file ospathjoindatadir file surface pygameimageloadfile return surfaceconvertalpha def loadimagesfiles imgs file files imgsappendloadimagefile return imgs class player mouse class mousepygamespritesprite speed def initself image loadimage mousepng image pygametransformscaleimage pygamespritespriteinitselfselfgroups selfimage image selfrect selfimagegetrect surface pygamedisplaygetsurface selfrectcenter width height selfarea surfacegetrect def movexself directionx selfrectmoveipdirectionxselfspeed def moveyself directiony selfrectmoveip directionyselfspeed def updateself pass class snake enemy class snakepygamespritesprite def initself pygamespritespriteinitselfselfgroups image loadimagerandomchoice snakepng snakepng snakepng image pygametransformscaleimage selfimage image selfrect selfimagegetrect surface pygamedisplaygetsurface selfarea surfacegetrect selfmovex randomrandint selfmovey randomrandint def updateself selfrect selfrectmoveselfmovexselfmovey selfrectleft selfarealeft selfrectright selfarearight selfmovex selfmovex newpos selfrectmoveselfmovex selfimage pygametransformflipselfimage selfrect newpos selfrecttop selfareatop selfrectbottom selfareabottom selfmovey selfmovey newpos selfrectmove selfmovey selfrect newpos pregame setup allsprites pygamespritegroup snakesprites pygamespritegroup mousesprites pygamespritegroup snakegroups allsprites snakesprites mousegroups allsprites mousesprites mouse mouse snake snake def main main game loop setup blits seconds clocktick screenblitbackground game events event pygameeventget eventtype pygamequit sysexit elif eventtype userevent snake keystate pygamekeygetpressed directionx keystatekright keystatekleft directiony keystatekup keystatekdown mousemovexdirectionx mousemoveydirectiony allspritesupdate allspritesdrawscreen pygamedisplayupdate pygamedisplayflip clocktick name main main,1 have look itertoolsmodule particulary product method example usage itertoolsproductrange repeat stuff listappendruniii note function call shortened listappendruni example see docspythonorg explanation unpacking argument lists as example output productrange repeat looks like,i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks,3 i think use imap itertools import imap result listimaprun range range range imap yields result want iterate results use list,i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks,1 itertools import product mylist runa b c b c productxrange xrange xrange or itertools import product mylist runa b c b c productxrange repeat,i working python currently following code list range b range c range listappendrunabc runabc returns integer example could multiply three numbers together is faster way either loop numbers use map function thanks,1 use sympy sympy import abcde symbolsabcde x bcminde csqrtxe values abcde print x print print xsubsvalues print ysubsvalues print nxsubsvalues print nysubsvalues output bc c ea bc,i looking way store series formulasequations text easily diffable later formulas depend results earlier ones i able evaluate formulas similar live worksheets mathcad numeric results also able programmatically produce string representation original formula put another way i like able treat formulas data well evaluate formulas i would like text editor syntax highlighting editing formulas my first approach python file formulas stored strings call eval strings however allow syntax highlighting formulas my language choice python i would open nonproprietary solutions example b c e x b c mind e c sqrtx e the intent automatically generate code using evaluated results formulas commenting generated code original formulas,2 you use subprocess module python if logs big simply use python result subprocesscheckoutputpathtoprocesstolauch arg python process subprocesspopenpathtoprocesstolauch arg stdoutsubprocesspipe stderrsubprocesspipe strout strerrr processcommunicate strout find standard output process strerr find standard output process but outputs really big let talk mo ko may cause memory overflow in case big output use file handles stdout stderr outfile openoutfilename w errfile openoutfilename w process subprocesspopenpathtoprocesstolauch arg stdoutoutfile stderrerrfile returncode processwait outfileclose errfileclose and outfile find output process errfile error output of course want relaunch process die put code loop,java program runs particular port ubuntu while running program need take output program needs save log file i use nohub run currentlywhen fail i know failthen process restart nohub get overwritten i want process restart update log file i check later date currently i know state running failed i heard pretty easy using python scripts anyone please help thanks advance renjith raj,1 using python certainly possible if reading mysql might check mysqlpython reading text file use file open filename r filereadline get line parse however added overhead using python if text file orderly one reacord per row row number columns consistent delimiter comma tab semicolon etc efficient way load directly in mysql something like load data infile folderinputdat into table destinationtable fields terminated by idfieldfieldfield if need minor modifications file changing commas things beginning end line might use command line sed nix osx install windows update load data infile quickest httpdevmysqlcomdocrefmanenloaddatahtml when say start article text text text maino maino different fields if fields header article might format text document look something like this header articleand article nice story programming my article goes many lines and many this second article headerand article it and etc then could use load data infile like load data infile folderfilenametxt into table destinationtable lines terminated by fields terminated by headerarticle,i trying load text file database my text file gb i need write python script load text file headers database any guidelines i go thanks,1 there multiple ways solve install webserver local machine write fullfledged python web application write simple webserver application python using basehttpserver write htmljavascript application use python parses file note due recently tightened restrictions may still require served webserver write python application writes database javascript file while inflexible need run every time want update database also simple encode data json write javascript file element like htmlfile open databasehtml w htmlfilewrite html htmlfilewrite scriptvar db jsonencodedatabase script either way going write html javascript,i created database python results kept text file i would like create simple html search button looks database my database would accessible computer my database looks something like reference name dimension xxx aaa so example i search specific reference i would like obtain name dimension obviously is even possible python i start i mention i basic skills html python,1 try replacing sysexit finishedloading qapplicationinstanceexit,i trying hand scraping javascript reliant site it pretty basic site simple list entires names cities actually i want copy paste excel the list controlled javascript i figur i need use something like qt emulate browser i trying pyside i started basic code i adapted usrbinenv python import sys import signal import argparse pysideqtcore import pysideqtgui import pysideqtwebkit import qwebpage class crawler qwebpage def initself url file qwebpageinit self selfurl url selffile file def crawl self signalsignal signalsigint signalsigdfl selfconnect self signal loadfinishedbool selffinishedloading selfmainframeload qurl selfurl def finishedloading self result file open selffile w filewrite selfmainframetohtml fileclose sysexit def main app qapplication sysargv args getargs crawler crawler argsurl argsfile crawlercrawl sysexit appexec def getargs command argument parser returns structure argsurl argsfile parser argparseargumentparserdescription basic scraper parseraddargument u url dest url help url fetch data default httpwwwgooglecom parseraddargument f file dest file help local file path save data default datatxt args parserparseargs return args name main main problem i know pysideqt really well i get error error calling slot finishedloading i even sure means is something i get around without engaging long arduous process figuring qt pyside is simple fix thanks input,1 as noone else offered solution using generator one sample thisisagoodexample def uppersplitdata buff item data itemisupper buff yield buff buff buff item yield buff listuppersplitsample this is a good example joinuppersplitsamplelower thisisagoodexample,i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve,1 did set fixturedirs setting value settingspy see documentation,i trying use postrgesql django apps i get following error right starting project i following files initpy managepy settingspyc urlspyc initpyc settingspy urlspy i added models python managepy syncdb creating tables installing custom sql installing indexes no fixtures found i even trying load fixtures psycopg installed this database section settingspy databases default engine djangodbbackendspostgresqlpsycopg add postgresqlpsycopg postgresql mysql sqlite oracle name myappdevelopment or path database file using sqlite user foo not used sqlite password password not used sqlite host set empty string localhost not used sqlite port set empty string default not used sqlite,1 you simple use case already web server installed probably simplest quickest way use cgi script written python check cgi module httpdocspythonorglibrarycgihtml basically handle get request show html form asking query string post request process query show results,i created database python results kept text file i would like create simple html search button looks database my database would accessible computer my database looks something like reference name dimension xxx aaa so example i search specific reference i would like obtain name dimension obviously is even possible python i start i mention i basic skills html python,1 this passes tests including extra i created it uses recursion here rules i used the first letter abbreviation must match first letter text the rest abbreviation abbrev minus first letter must abbreviation remaining words remaining text starting position first word tests fck fc kopenhavn true fco fc kopenhavn false irl real life true irnl real life false ifk ifk gotebork true ifko ifk gotebork false aik allmanna idrottskluben true aid allmanna idrottskluben true manu manchester united true fz faz zoo true fzz faz zoo true fzzz faz zoo false def isabbrevabbrev text abbrevabbrevlower texttextlower wordstextsplit abbrev return true abbrev text return false abbrevtext return false else return isabbrevabbrev joinwords anyisabbrevabbrevtexti rangelenwords abbrevtextanswer tests resultisabbrevabbrevtext printabbrevtextresultanswer assert resultanswer,i trying develop python algorithm check string could abbrevation another word for example fck match fc kopenhavn matches first characters word fhk would match fco match fc kopenhavn one irl would abbrevate fc kopenhavn fco irl match real life ifk match ifk goteborg aik match allmanna idrottskluben aid match allmanna idrottsklubben this real team name abbrevation i guess hard exclude unless apply domain specific knowledge swedish abbrevations formed manu match manchester united it hard describe exact rules algorithm i hope examples show i update i made mistake showing strings matching letters uppercased in real scenario letters lowercase easy checking letters uppercased,3 this type encoding known mime encodedword email module decode emailheader import decodeheader print decodeheaderutfbieryzwltbhdhnmcmlzdcbmwxyifzlcnbmbgvndwnclahjhdwzzwkdw this outputs list tuples containing decoded string encoding used this format supports different encodings single header to merge single string need convert shared encoding concatenate accomplished using python unicode object emailheader import decodeheader dh decodeheader gewstutfbifdlzzhbgwgzgvyifzvcmzdphvmawdrzwl defaultcharset ascii print join unicodet defaultcharset dh update the problem subject line decoding subject elstamutfbifzlcmbdvgdbmcgdmtidix januar is actually senders fault violates requirement encodedwords header separated whitespace specified rfc section paragraph encodedword appears header field defined text must separated adjacent encodedword text linearwhitespace if need work around preprocessing corrupt headers regex inserts whitespace encodedword part unless end like import headervalue resubr r headervalue,python module helps decode various forms encoded mail headers mainly subject simple say utf strings here example subject headers mail files i subject utfbimknidensbbynm ao subject gewstutfbifdlzzhbgwgzgvyifzvcmzdphvmawdrzwl subject utfbieryzwltbhdhnmcmlzdcbmwxyifzlcnbmbgvndwnclahjhdwzzwkdw utfbzvuigvpbmvzifnlzwhbmz text encoded sting text text encoded string text encoded string encoded string encodig could also something else like iso update i forgot mention i tried emailheaderdecodeheader item messageitems item subject sub emailheaderdecodeheaderitem loggingdebug subject sub this outputs debugrootsubject elstamutfbifzlcmbdvgdbmcgdmtidix januar none really help update thanks ingmar hupp comments first example decodes list two tupels print decodeheader gewstutfbifdlzzhbgwgzgvyifzvcmzdphvmawdrzwl gewst none wegfall der vorlxcxaufigkeit utf always string encodingstring encoding i need loop concat items one string get one string subject elstamutfbifzlcmbdvgdbmcgdmtidix januar decode well print decodeheader elstamutfbifzlcmbdvgdbmcgdmtidix januar elstamutfbifzlcmbdvgdbmcgdmtidix januar none,3 setopenfile amp setopenfile equivalent using intersection pythonic way you might able speed setintx x openfile amp setintx x openfile since storing comparing integers rather strings this works ids numeric course if still fast enough turn slightly imperative style heuristic set smallerfile largerfile checking file size setintx x opensmallerfile note storing strings r r setx x openlargerfile intx if files guaranteed contain duplicates also use list speed things setintx x opensmallerfile r x x openlargerfile intx be sure measure various solutions check whether actually waiting disk network input,i two large files their contents looks like the file contains unsorted list ids some ids may appear one time single file now i want find intersection part two files that ids appear files i read two files sets and get intersection sintersections but consumes lot memory seems slow so better pythonic way if file contains many ids read set limited memory i edit i read file sets using generator def idgenpath line openpath tmp linesplit yield inttmp c idgenpath setc all ids numeric and max id may if use bitarray consume memory,2 i happy say fact possible lines code i know easy toolkits tkinter import import os root tk termf frameroot height width termfpackfillboth expandyes wid termfwinfoid ossystem xterm geometry x sb amp wid rootmainloop the problem use wrong function wid,i want embed terminal main tkinter window i would like sub window terminal bash based terminal would run i would like also able let program interact terminal least i would like read current working directory andor set i know really impossible i able past perltk maybe replicated the code i used something like framemwframeborderwidth relief groove label stuff thought labelbackgroundcadrawwincolorbackgroundcadrawwincolor cvframecanvasheightcvheightwidthcvwidthbackgroundcadrawwincolor bg cadrawwincolor relief sunken packexpand fill frame needed including xterm tkcanvas xtermcontainer cvframecontainer xtid xtermcontainerid converting id hex decimal xterm requires decimal id xtid sprintf hex xtid dcontitem cvcreatewindowxtermwidthxtermheight window xtermcontainer width xtermwidth height xtermheight state normal systemxterm xtid fn fontname geometry geometry sb bg black fg white e xtermjobpl aafname amp mw main tk window of course i completely agree bryan though i never programmed gui library program rather large kind wiki running well surprisingly low amount code devoted gui i tried translating perl code i stumbling id problem the place i found reference way extract id tkinter effbot i use i get attributeerror frame instance attribute windowid must something wrong termf frameroot termfpacksidebottom fillx idtermfwindowid ossystemxterm fn miscfixedmediumrnormalciso geometry x sb bg black fg white e rootbashrc amp id,3 this means django found fixtures this standard message fixtures fixture file next format using create real objects database existing model model myappperson pk fields firstname john lastname lennon model myappperson pk fields firstname paul lastname mccartney see details httpdocsdjangoprojectcomendevhowtoinitialdata,i trying use postrgesql django apps i get following error right starting project i following files initpy managepy settingspyc urlspyc initpyc settingspy urlspy i added models python managepy syncdb creating tables installing custom sql installing indexes no fixtures found i even trying load fixtures psycopg installed this database section settingspy databases default engine djangodbbackendspostgresqlpsycopg add postgresqlpsycopg postgresql mysql sqlite oracle name myappdevelopment or path database file using sqlite user foo not used sqlite password password not used sqlite host set empty string localhost not used sqlite port set empty string default not used sqlite,2 you need create first read lines first file convert line integer saves memory put then line second file convert integer check value that way save memory storing strings two sets,i two large files their contents looks like the file contains unsorted list ids some ids may appear one time single file now i want find intersection part two files that ids appear files i read two files sets and get intersection sintersections but consumes lot memory seems slow so better pythonic way if file contains many ids read set limited memory i edit i read file sets using generator def idgenpath line openpath tmp linesplit yield inttmp c idgenpath setc all ids numeric and max id may if use bitarray consume memory,1 so algorithm necessarily tied python rather generic cannot represent ids set memory if range integers limited approach would use large bitarray now read first file set integer bitarray present now read second file output numbers also present bitarray if even sufficient split range using multiple sweeps ie first pass consider integers smaller x gb bitarray then reset bitarray read files considering integers x x substract x handling integer this way handle large amounts data reasonable runtime a sample single sweep would import bitarray r bitarraybitarray line openfile rintline true line openfile rintline print line,i two large files their contents looks like the file contains unsorted list ids some ids may appear one time single file now i want find intersection part two files that ids appear files i read two files sets and get intersection sintersections but consumes lot memory seems slow so better pythonic way if file contains many ids read set limited memory i edit i read file sets using generator def idgenpath line openpath tmp linesplit yield inttmp c idgenpath setc all ids numeric and max id may if use bitarray consume memory,1 here way accomplish seem want import def isabbrevabbrev text pattern joinabbrevlower return rematch pattern textlower none the caret makes sure first character abbreviation matches first character word true abbreviations edit your new update changed rules bit by using instead characters abbreviation match next next character appears start new word this correctly match fck fc kopenhavn fco however matching aik allmanna idrottskluben work requires knowledge swedish language trivial here new code minor modification import def isabbrevabbrev text pattern sjoinabbrevlower return rematch pattern textlower none,i trying develop python algorithm check string could abbrevation another word for example fck match fc kopenhavn matches first characters word fhk would match fco match fc kopenhavn one irl would abbrevate fc kopenhavn fco irl match real life ifk match ifk goteborg aik match allmanna idrottskluben aid match allmanna idrottsklubben this real team name abbrevation i guess hard exclude unless apply domain specific knowledge swedish abbrevations formed manu match manchester united it hard describe exact rules algorithm i hope examples show i update i made mistake showing strings matching letters uppercased in real scenario letters lowercase easy checking letters uppercased,2 afaik efficient way python especially dealing massive amounts data i like rumpel solution but please note bitarray c extension i would use shell commands handle you preprocess files save time amp space sort u file filesorted sort u file filesorted then use diff find similarities diff changedgroupformat unchangedgroupformat filesorted filesorted of course possible combine everything single command without creating intermediary files update according can recommendation comm appropriate command sort u file filesorted sort u file filesorted comm filesorted filesorted,i two large files their contents looks like the file contains unsorted list ids some ids may appear one time single file now i want find intersection part two files that ids appear files i read two files sets and get intersection sintersections but consumes lot memory seems slow so better pythonic way if file contains many ids read set limited memory i edit i read file sets using generator def idgenpath line openpath tmp linesplit yield inttmp c idgenpath setc all ids numeric and max id may if use bitarray consume memory,1 ocaso protal said comment decide aik valid aid valid right the algo came mind work word threshold number words separated space words stringstripsplit lenwords take first letter every word elif lenwords take two letters first word one letter else single word take first three letter like define logic find abbreviation blindly,i trying develop python algorithm check string could abbrevation another word for example fck match fc kopenhavn matches first characters word fhk would match fco match fc kopenhavn one irl would abbrevate fc kopenhavn fco irl match real life ifk match ifk goteborg aik match allmanna idrottskluben aid match allmanna idrottsklubben this real team name abbrevation i guess hard exclude unless apply domain specific knowledge swedish abbrevations formed manu match manchester united it hard describe exact rules algorithm i hope examples show i update i made mistake showing strings matching letters uppercased in real scenario letters lowercase easy checking letters uppercased,2 edit foobar module add following code import pdb pdbsettrace foobar imported program stop pdbsettrace pdb mode debug code for example use w command print full calling stack,my python library changed main module name foobar foobar for backward compat foobar still exists importing raises warnings now seems example program still imports old module directly i like find erroneous import statement is tool allows trace imports find culprit without wading code,1 others shown idiomatic ways python size data really big use system utilities sort eliminate duplicates use fact file iterator returns one line time something like import os ossystem sort u n snum sns ossystem sort u n snum sns open sns r open sns r try inext inext true inext elif inext else print inext inext except stopiteration pass this avoids one line time file memory system sort faster anything python optimized one task,i two large files their contents looks like the file contains unsorted list ids some ids may appear one time single file now i want find intersection part two files that ids appear files i read two files sets and get intersection sintersections but consumes lot memory seems slow so better pythonic way if file contains many ids read set limited memory i edit i read file sets using generator def idgenpath line openpath tmp linesplit yield inttmp c idgenpath setc all ids numeric and max id may if use bitarray consume memory,2 data larger memory split data file files contain lowest digital ids stxt ends saved stxt then use set find intersection stxt stxt stxt stxt,i two large files their contents looks like the file contains unsorted list ids some ids may appear one time single file now i want find intersection part two files that ids appear files i read two files sets and get intersection sintersections but consumes lot memory seems slow so better pythonic way if file contains many ids read set limited memory i edit i read file sets using generator def idgenpath line openpath tmp linesplit yield inttmp c idgenpath setc all ids numeric and max id may if use bitarray consume memory,1 python natively offer flavors references besides hard aka strong amp weak that said softref implementation i whipped year ago i using places i needed one what provides quite actual soft references comes close use cases it little rough around edges fully functional though relies reference counting internally means probably break anything except cpython in particular i wrote precisely cache expensivetocreate longlived objects softvaluedictionary exactly looking,in languages eg java object references strong weak soft phantom httpweblogsjavanetblogenicholasarchiveunderstandingwhtml in python references strong default weakref module allows weak references is possible soft references python in particular case i cache objects timeconsuming create sometimes may references cached object i want throw cached object away i ie memory plentiful,3 try using backslashes instead slashes ie cbenutzermedesktopsynctxt doswindows style paths to avoid backslashes treated escaping character use raw string osremover cbenutzermedesktopsynctxt,i want delete file located desktop osremove cbenutzermedesktopsynctxt but i get error system cannot find path however file exist given location i copy path paste explorer this open file where problem,2 i used something called unescaping xml know helpfull see httpwikipythonorgmoinescapingxml xmlsaxsaxutils import unescape unescapeamplt ampamp ampgt amp unescapeampapos ampquot ampapos ampquot edit just saw may interresting not tested unescape urllib,i fetching result rss feed using following code try desc itemxpath description text date none desc date nndesc except desc none but sometimes description contains unicode html charecters feed the text xml looks like quot amp stuff while displaying content i want displayed is regular expression remove html tags,1 once text want selected run import os var ospopen xsel read print var,i need python script get selected text application xsel store var thanks,2 what probably looking model validation this introduced quite well documented django models instances validating objects whilst may able write tricky sql long database rows created django orm model validation maintainable solution aside i interested database level short level precommit trigger uniqueness one value dependent upon another true something i seen pattern having field unique constraint activepath would allow false true number null active rows given path value assuming active nullable nullbooleanfield would provide,in model class mymodelmodelsmodel active modelsbooleanfield path modelscharfieldmaxlength i would like constrain path attribute unique amongst instances active true it seems like overriding save might work two saves done concurrently might pass test go ahead save is trick custom sql i using mysql i could use conditional uniqness constraint like database level,1 i suppose vista then aware ui quite lot localization probably path really cusers localization benutzer happening ui,i want delete file located desktop osremove cbenutzermedesktopsynctxt but i get error system cannot find path however file exist given location i copy path paste explorer this open file where problem,2 it django serialiser looks columns attributes you look serialisation tools wad stuff serializer springs mind i wound writing uses django form serialise deserialise,how retain extra column added dynamically queryset serialization json string code tenantunit tenantunitobjectsfilterunitbuildingid dynamically add column unitname tu tenantunit tuunitname tuunitunitname point loop thru queryset tenantunit see dynamic column unitname build json string jsondata serializersserializejson tenantunit check inside json string mising unitname print jsondata can find unitname what happening go round gath nb am serializers follow relationships inside model returns current model,1 another cleaner option achieve use task queue stub within testbed to first initialize task queue stub adding following setup method selftestbed inittestbed selftestbedinittaskqueuestub the tasks scheduler accessed using following code taskq selftestbedgetstubtestbedtaskqueueservicename the interface working queue stub follows getqueues returns list dictionaries information available queues returns list dictionaries information tasks given queue gettasksqueuename deletetaskqueuename taskname removes task taskname given queue flushqueuequeuename removes tasks queue returns tasks filtered name amp url pointed task given queues getfilteredtasksurl name queuenames startbackgroundexecution executes queued tasks shutdown requests task scheduler shutdown also uses app engine sdk facilities works fine deferred library,i using testbed unit test google app engine app app uses taskqueue when i submit task taskqueue unit test appears task queue task execute how i get task execute unit test,3 my choice documentation sphinx others epydoc pylit but sphinx quite awesome,im creating front end web service another company back end i need good simple easily understandable way making document api calls collaborate edit together without confusing one another good specsexamples etc project api documentation doesnt get huge mess many rewrites,1 try subprocesspopen optlocalbinpython fullpathtofilenewtestpy stdoutsubprocesspipe does work removed parameters also f open fullpathnewtestpy print f,i get following error subprocess calls process newtestpy the code run daemon when i started daemon process called worked fine run processes started giving error error occurs every call the error optlocallibraryframeworkspythonframeworkversionsresourcespythonappcontentsmacospython open file newtestpy errno no file directory code indexrow enumeratejobs index newjobs dirsrow dirnameospathjoinhomefolderdirs logfileospathjoindirnamedirslog procsubprocesspopenoptlocalbinpythonnewtestpydirsstdoutopenlogfile stderropenlogfile proid procpid i tried using full path newtestpy gives error any suggestions many thanks,1 are sure directory path correct slashes causing problem dont try import os filepath c ospathsep benutzer ospathsep me ospathsep desktop ospathsep synctxt osremovefilepath advantage using ospathsep dont worry whether linux windows whatever,i want delete file located desktop osremove cbenutzermedesktopsynctxt but i get error system cannot find path however file exist given location i copy path paste explorer this open file where problem,1 thomas k thank guidance thanks i able come maybe said little roudabout solution credit answer go the following line code messagesappendchatmessagechatter msg should look like messagesappendchatmessagechatterencode utf msgencode utf basically i encode utf string ascii,so past days i trying learn python app engine however i encountering number problems ascii utf encoding the freshest issue follows i following piece code simplistic chatroom book code cloud googleappengineext import webapp googleappengineextwebapputil import runwsgiapp import datetime start mainpage class chatmessageobject def initself user msg selfuser user selfmessage msg selftime datetimedatetimenow def strself return selfuser selftime selfmessage messages class chatroompagewebapprequesthandler def getself selfresponseheaderscontenttype texthtml selfresponseoutwrite html head titlemarkcc appengine chat roomtitle head body hwelcome markcc appengine chat roomh pcurrent time sp datetimedatetimenow output set chat messages global messages msg messages selfresponseoutwritepsp msg selfresponseoutwrite form action methodpost divbnameb textarea namename rows colstextareadiv pbmessagebp divtextarea namemessage rows colstextareadiv divinput typesubmit valuesend chatmessageinputdiv form body html end mainpage start posthandler def postself chatter selfrequestgetname msg selfrequestgetmessage global messages messagesappendchatmessagechatter msg now added message chat redirect root page make user browser refresh show chat including new message selfredirect end posthandler start frame chatapp webappwsgiapplication chatroompage def main runwsgiappchatapp name main main end frame it works ok english however moment i add nonstandard characters sorts problems start first order thing actually able display characters html i add meta tag charsetutf etc curiously enter nonstandard letters program processes nicely displays issues however fails load i enter nonascii letters web layout iteself withing script i figured adding utf encoding line would work so i added coding utf this enough of course i forgot save file utf format upon program started running that would good end story alas it work long story short code coding utf googleappengineext import webapp googleappengineextwebapputil import runwsgiapp import datetime start mainpage class chatmessageobject def initself user msg selfuser user selfmessage msg selftime datetimedatetimenow def strself return selfuser selftime selfmessage messages class chatroompagewebapprequesthandler def getself selfresponseheaderscontenttype texthtml selfresponseoutwrite html head titlewitaj w pokoju czatu markcc w app enginetitle meta httpequivcontenttype contenttexthtml charsetutf head body hwitaj w pokoju czatu markcc w app engineh pdokladny czas twojego logowania sp datetimedatetimenow output set chat messages global messages msg messages selfresponseoutwritepsp msg selfresponseoutwrite form action methodpost divbtwã³j nickb textarea namename rows colstextareadiv pbtwoja wiadomoå›ä‡bp divtextarea namemessage rows colstextareadiv divinput typesubmit valuesend chatmessageinputdiv form body html end mainpage start posthandler def postself chatter selfrequestgetuname msg selfrequestgetumessage global messages messagesappendchatmessagechatter msg now added message chat redirect root page make user browser refresh show chat including new message selfredirect end posthandler start frame chatapp webappwsgiapplication chatroompage def main runwsgiappchatapp name main main end frame fails process anything i write chat application running it loads moment i enter message even using standard characters i receive file dpythonlibstringiopy line getvalue selfbuf joinselfbuflist unicodedecodeerror ascii codec decode byte xc position ordinal range error message in words i want able use characters within application i cannot put nonenglish ones interface or way round i use nonenglish characters within app i encode file utf how make work together,1 assuming output always looks something like showed use regular expression numpattern r output compinfomapece researchnumpattern output if match found numstring mgroup extracts first group surrounded etc the pattern looks numbers periods anything extracts numbers periods this work long always getting string matches description hth,compinfomapece this string output cpu always specialnonprintable characters number aim obtain number excluding text specialnonprintable i trying split method sure use specialnonprintable characters can anyone please suggest something it would great help thanks,2 i published python tree implementation site httpwwwquesucedecompageshowidpythontreeimplementation hope use ok code import uuid def sanitizeidid return idstripreplace add delete insert range root depth width range class node def initself name identifiernone expandedtrue selfidentifier struuiduuid identifier none else sanitizeidstridentifier selfname name selfexpanded expanded selfbpointer none selffpointer property def identifierself return selfidentifier property def bpointerself return selfbpointer bpointersetter def bpointerself value value none selfbpointer sanitizeidvalue property def fpointerself return selffpointer def updatefpointerself identifier modeadd mode add selffpointerappendsanitizeididentifier elif mode delete selffpointerremovesanitizeididentifier elif mode insert selffpointer sanitizeididentifier class tree def initself selfnodes def getindexself position index node enumerateselfnodes nodeidentifier position break return index def createnodeself name identifiernone parentnone node nodename identifier selfnodesappendnode selfupdatefpointerparent nodeidentifier add nodebpointer parent return node def showself position levelroot queue selfpositionfpointer level root print formatselfpositionname selfpositionidentifier else printtlevel formatselfpositionname selfpositionidentifier selfpositionexpanded level element queue selfshowelement level recursive call def expandtreeself position modedepth python generator loosly based algorithm essential lisp john r anderson albert t corbett brian j reiser page yield position queue selfpositionfpointer queue yield queue expansion selfqueuefpointer mode depth queue expansion queue depthfirst elif mode width queue queue expansion widthfirst def isbranchself position return selfpositionfpointer def updatefpointerself position identifier mode position none return else selfpositionupdatefpointeridentifier mode def updatebpointerself position identifier selfpositionbpointer identifier def getitemself key return selfnodesselfgetindexkey def setitemself key item selfnodesselfgetindexkey item def lenself return lenselfnodes def containsself identifier return nodeidentifier node selfnodes nodeidentifier identifier name main tree tree treecreatenodeharry harry root node treecreatenodejane jane parent harry treecreatenodebill bill parent harry treecreatenodejoe joe parent jane treecreatenodediane diane parent jane treecreatenodegeorge george parent diane treecreatenodemary mary parent diane treecreatenodejill jill parent george treecreatenodecarol carol parent jill treecreatenodegrace grace parent bill treecreatenodemark mark parent jane print treeshowharry print node treeexpandtreeharry modewidth printnode print,i want build general tree whose root node contains n children children may contain children,3 way keep processes running way variables saved restart script stopped yes it called creating checkpoint memento know program good get started each problem unique create save reload mementos would prefer generalised utility could keep things running script completed even trivial errors it generalize well not variables saved only know required restart process meaningful way perhaps need sort processmanagement tool not really trivial errors eg string encoding issues usually find unit testing that saves lot programming work around error an ounce prevention worth pound silly workarounds sometimes process seems get killed server what you better find an ounce prevention worth pound silly workarounds,i need run bunch long running processes centos server if i leave processes pythonphp scripts run sometimes processes stop running trivial errors eg string encoding issues sometimes process seems get killed server i try use nohup fire jobs crontab is way keep processes running way variables saved i restart script stopped i know i program code would prefer generalised utility could keep things running script completed even trivial errors perhaps i need sort processmanagement tool many thanks suggestions,2 start python interpreter v python v usrlibpythontimeitpy installing zipimport hook import zipimport builtin installed zipimport hook usrlibpythonsitepyc matches usrlibpythonsitepy import site precompiled usrlibpythonsitepyc usrlibpythonospyc matches usrlibpythonospy import os precompiled usrlibpythonospyc import errno builtin import posix builtin usrlibpythonposixpathpyc matches usrlibpythonposixpathpy import posixpath precompiled usrlibpythonposixpathpyc usrlibpythonstatpyc matches usrlibpythonstatpy import stat precompiled usrlibpythonstatpyc usrlibpythongenericpathpyc matches usrlibpythongenericpathpy import genericpath precompiled usrlibpythongenericpathpyc usrlibpythonwarningspyc matches usrlibpythonwarningspy import warnings precompiled usrlibpythonwarningspyc usrlibpythonlinecachepyc matches usrlibpythonlinecachepy import linecache precompiled usrlibpythonlinecachepyc usrlibpythontypespyc matches usrlibpythontypespy import types precompiled usrlibpythontypespyc usrlibpythonuserdictpyc matches usrlibpythonuserdictpy then grep old module,my python library changed main module name foobar foobar for backward compat foobar still exists importing raises warnings now seems example program still imports old module directly i like find erroneous import statement is tool allows trace imports find culprit without wading code,3 this equivalent looping kn outputting current index base n which reduces problem base conversion essentially equivalent long division,given list eg two elements l i need create possible element variations repetitions i tried itertoolscombinations give i wanted with given n k i get elements result look like results,1 import itertools joinitem item itertoolsproduct repeat,given list eg two elements l i need create possible element variations repetitions i tried itertoolscombinations give i wanted with given n k i get elements result look like results,3 your csv file invalid if quote occurs inside quoted string must escaped doubling aa b ampamp bac would result a a b ampamp ba c how csv module guess difference quotes delimit item quotes within item,i csv file follwing format aa b ampamp bac following code read csv file openpath rb f reader csvreaderf delimiter quotechar row reader print row the problem breaks row fields a a b ampamp ba c whereas i expecting output a a b ampamp ba c when i remove double quote b csv file i get output a a b ampamp ba c perfectly fine double quote middle field causing problem even though delimiter quotechar defined,3 i suspect doublequote replaced ampquot,i csv file follwing format aa b ampamp bac following code read csv file openpath rb f reader csvreaderf delimiter quotechar row reader print row the problem breaks row fields a a b ampamp ba c whereas i expecting output a a b ampamp ba c when i remove double quote b csv file i get output a a b ampamp ba c perfectly fine double quote middle field causing problem even though delimiter quotechar defined,2 defined delimiter use text ampersand entity semicolon i recommend changing delimiter something show text like pipe character something,i csv file follwing format aa b ampamp bac following code read csv file openpath rb f reader csvreaderf delimiter quotechar row reader print row the problem breaks row fields a a b ampamp ba c whereas i expecting output a a b ampamp ba c when i remove double quote b csv file i get output a a b ampamp ba c perfectly fine double quote middle field causing problem even though delimiter quotechar defined,1 i published python tree implementation site httpwwwquesucedecompageshowidpythontreeimplementation hope use ok code import uuid def sanitizeidid return idstripreplace add delete insert range root depth width range class node def initself name identifiernone expandedtrue selfidentifier struuiduuid identifier none else sanitizeidstridentifier selfname name selfexpanded expanded selfbpointer none selffpointer property def identifierself return selfidentifier property def bpointerself return selfbpointer bpointersetter def bpointerself value value none selfbpointer sanitizeidvalue property def fpointerself return selffpointer def updatefpointerself identifier modeadd mode add selffpointerappendsanitizeididentifier elif mode delete selffpointerremovesanitizeididentifier elif mode insert selffpointer sanitizeididentifier class tree def initself selfnodes def getindexself position index node enumerateselfnodes nodeidentifier position break return index def createnodeself name identifiernone parentnone node nodename identifier selfnodesappendnode selfupdatefpointerparent nodeidentifier add nodebpointer parent return node def showself position levelroot queue selfpositionfpointer level root print formatselfpositionname selfpositionidentifier else printtlevel formatselfpositionname selfpositionidentifier selfpositionexpanded level element queue selfshowelement level recursive call def expandtreeself position modedepth python generator loosly based algorithm essential lisp john r anderson albert t corbett brian j reiser page yield position queue selfpositionfpointer queue yield queue expansion selfqueuefpointer mode depth queue expansion queue depthfirst elif mode width queue queue expansion widthfirst def isbranchself position return selfpositionfpointer def updatefpointerself position identifier mode position none return else selfpositionupdatefpointeridentifier mode def updatebpointerself position identifier selfpositionbpointer identifier def getitemself key return selfnodesselfgetindexkey def setitemself key item selfnodesselfgetindexkey item def lenself return lenselfnodes def containsself identifier return nodeidentifier node selfnodes nodeidentifier identifier name main tree tree treecreatenodeharry harry root node treecreatenodejane jane parent harry treecreatenodebill bill parent harry treecreatenodejoe joe parent jane treecreatenodediane diane parent jane treecreatenodegeorge george parent diane treecreatenodemary mary parent diane treecreatenodejill jill parent george treecreatenodecarol carol parent jill treecreatenodegrace grace parent bill treecreatenodemark mark parent jane print treeshowharry print node treeexpandtreeharry modewidth printnode print,i trying construct general tree are built data structures python implement tree,2 what mean i need define method init else python know class aobject def initself selffoo def fooself print a i usually place init instance methods class methodspropertyattributes,consider following code class aclass def defaultmethodself return def initself methodtouse defaultmethod print methodtouseself name main aclass in case one cannot move defaultmethod init method i causes nameerror name defaultmethod defined this means i need define method init else python know this means i longer init first method leaves wonder whether usual place init method end class beginning,2 init commonly placed beginning class since first thing run class instantiated since situation requires exist class would nice devs leave note comments class,consider following code class aclass def defaultmethodself return def initself methodtouse defaultmethod print methodtouseself name main aclass in case one cannot move defaultmethod init method i causes nameerror name defaultmethod defined this means i need define method init else python know this means i longer init first method leaves wonder whether usual place init method end class beginning,1 i recently discovered the paster create takes config command line argument this file contains variable use for example i create package called bob config called bobsetupcfg the configuration file contain pastescript created t eggpluginseval plus egg bob dot description bob magic code licensename zipsafeeval false keywords python longdescription bob super useful code base author fred sprocket authoremail fredsprocketexamplecom url httpexamplecom version i use follows paster create basicpackage configbobsetupcfg bob selected implied templates pastescriptbasicpackage a basic setuptoolsenabled package variables author fred sprocket authoremail fredsprocketexamplecom created t description bob magic code dot egg bob eggplugins keywords python licensename longdescription bob super useful code base package bob plus project bob url httpexamplecom version zipsafe false creating template basicpackage creating directory bob recursing package creating bobbob copying initpy bobbobinitpy copying setupcfg bobsetupcfg copying setuppytmpl bobsetuppy running usersomulvirtualenvsimanalyticsbinpython setuppy egginfo if i check bobsetuppy see set variables cat setuppy setuptools import setup findpackages import sys os version setupname bob versionversion descriptionbob magic code longdescription bob super useful code base classifiers get strings httppypipythonorgpypiaactionlistclassifiers keywords python author fred sprocket authoremail fredsprocketexamplecom url httpexamplecom license packagesfindpackagesexclude ezsetup examples tests includepackagedatatrue zipsafefalse installrequires extra requirements entrypoints entry points,so i using pastescript paster i trying automate egg creation my first step get template python egg i noticed pastescript paster one built i creating template command line paster create basicpackage however asks questions series prompts project name author version etc is possible use configuration file pass argument directly command line invoking pastescript my goal one command i run generate egg template thanks help,2 for case would settingspy files called settingsapy settingsbpy specify settings import a would site b would siteb set files apache configs setting environment variable virtual host djangosettingsmodulesettingsa djangosettingsmodulesettingsb then set contribsites app domain names bound appropriate site id flatpages able bound either sites lastly settingsapy settingsbpy either specify seperate root urlconfs use use settingssite urlconfs enable disable groups urls site hope helps edit to clarify long use database secretkey sites use user accounts if sites form examplecom privateexamplecom setting sessioncookiedomain examplecom allow session carry sites,i need split current django application two sites site a contain public facing site would contain static pages registration system the site — site b — site registered users they also login application site site b if i mistaken i use djangocontribsites framework accomplish task multiple sites common autheticationregistration backend how i accomplish thanks,1 i hope could help httpseleniumgooglecodecomsvntrunkdocsapijavaorgopenqaseleniumwebelementhtml here described java method javalangstring gettext but unfortunately available python so translate method names python java try another logic using present methods without getting whole page source eg myid elemgetattribute myid,i using python bindings run selenium webdriver selenium import webdriver wd webdriverfirefox i know i grab webelement like elem wdfindelementbycssselector myid and i know i get full page source wdpagesource but anyway get element source elemsource returns html string the selenium webdriver docs python basically nonexistent i see anything code seems enable functionality any thoughts best way access html element children,1 set x verbose flag regex ie x,i attempting create regular expression parse address five parts address street address address apartment number whatever else shows line address city state zip code when i run python django throwing error states unexpected end pattern i run research can anyone tell modify regular expression match correctly i much regular expression noob i make one supposed i could never written i got httpregexlibcomredetailsaspxregexpid recompiler xn address xazaz po box ds city azaz xazaz x state alkszrap caot dec flm gau hi iadl n ksy la madehinopst ncdehjmvy ohkr parw ri scd tnx ut vait waivy azaz xazazx zipcode dd reverbose newlines added readability as followup question regex separated multiple lines like readability need one line work i could concatenate separate lines i suppose ps i know smells like homework actually work edit actual code used requested i left everything actually already perhaps help the function part django view matter much purposes def parseaddressaddress pattern rnaddressd xazaz po box dsiaddressaptapartmentbldgbuildingdeptdepartmentflfloorhngrhangerlotpierrmroomslippcteoptrlrtrailerunitxwbsmtbasementfrntfrontlbbylobbylowrlowerofcofficephrearsideupprupperscityazazxazaz xstatealkszrapcaotdecflmgauhiiadl nksylamadehinopstncdehjmvyohkrparwriscd tnxutvaitwaivyazazxazazxzipcodedd match researchpattern address i using home address input i tried main st austin tx input well result,1 first read question having said i use function like one requries pythondateutil manage dates dateutilparser import parse dateparser def castvalueself value tests int float lambda value dateparservalue test tests try return testvalue except valueerror continue return value dateutil handle different kind date formats,i csv file contain datetime number number number number i use code read change types code import csv import datetime myarray filename contractcsv fcsvreaderopenfilename rb delimiter row f myarrayarrayrow row f print myarray i get array looks like i idea change first column datetime others float please help thanks,1 you elementtree works loading xml parsing storing abstract representation it writes string walking abstract representation remember things like characters escaped entities whether element stored foo foofoo html foo foofoo now since elementtree works xml html i guessing working lxmlhtml case fact automatically corrects certain forms erroneous html otherwise able store correctly the right way handle html whose data want completely preserved except alter grab tokens remember original representation i done using sgmllib imperfect eg getstarttagtext method getting exact content start tag corresponding method end tags it might good enough anyway for example write html paragraphs removed one might write function like cstringio import stringio class sgmlmodifiersgmllibsgmlparser def initself args kwargs sgmllibsgmlparserinitself args kwargs selffile stringio def getvalueself return selffilegetvalue def startbself attributes skip pass def endbself skip pass def unknownstarttagself tag attributes selffilewriteselfgetstarttagtext def unknownendtagself tag get verbatim selffilewrite tag def handlecommentself comment verbatim either selffilewrite comment def handledataself data selffilewritedata def convertentityrefself ref return amp ref def removeboldhtml parser sgmlmodifier parserfeedhtml return parsergetvalue this might need bit work mangle input check documentation details everything,i using python elementtree read modify content html files when i done changes use elementtreewrite function adds extra html infront tags how i avoid it also adds amp i special characters how avoid thank divya,1 thanks responses i use mount smbfs instead smbmount get working this worked cmdparts mount smbfs password cmdpartsappendo passwordsusers password username share driveletter ossystem joincmdparts,question similar copy files nework path drive using python however i linux trying copy files windows shared network accessed samba i tried code contextlib import contextmanager contextmanager def networkshareauthshare usernamenone passwordnone driveletter p context manager mounts given share using given username password given drive letter entering context unmounts exiting cmdparts net use driveletter share password cmdpartsappendpassword username cmdpartsappendusers username ossystem joincmdparts try yield finally ossystemnet use delete driveletter networkshareauthrcomputernamesharename username password shutilcopyfilefootxt rpfootxt i get error sh net found i think net use windows specific how i something similar linux thanks harmaini,1 it likely means hostname passing run resolved import socket socketgetaddrinfo localhost if work going work bottle example you try instead localhost case problem,file cpythonlibsocketpy line meth return getattrselfsocknameargs gaierror errno getaddrinfo failed getting error launching hello world sample httpbottlepyorgdocsdev,3 use ospathbasenamepath get filename,is way i use glob directory get files specific extension filename whole path,3 if perl implementations already write python wrapper calls perl code that way python project make use functionality rewrite actual algorithms there lot things nltk already work exactly way,i would like find relatedness similarity two words using python the hso hirst stonge lesk banerjee pedersen vector patwardhan algorithms implemented perl cant seem find python nltk lib i need use python part larger team project python any leads,1 use glob combination ospathbasename,is way i use glob directory get files specific extension filename whole path,3 some people might consider answer bear minute i highly recommend against trying parse street addresses regex street addresses regular sense word there infinite variation unless restrict limited grammar always strings cannot parse a huge amount time money invested solutions parse addresses starting us post office many many providers list cleanup services just google parsing street addresses get hint scope problem there commercial solutions free solutions comments web indicate nobody gets right time i also speak experience during i worked database typesetting company parse addresses we never able develop solution worked perfectly data captured large keyboarding department developed special notation syntax operators could insert delimiters appropriate locations help parsing process take look free services you save lot hassle,i attempting create regular expression parse address five parts address street address address apartment number whatever else shows line address city state zip code when i run python django throwing error states unexpected end pattern i run research can anyone tell modify regular expression match correctly i much regular expression noob i make one supposed i could never written i got httpregexlibcomredetailsaspxregexpid recompiler xn address xazaz po box ds city azaz xazaz x state alkszrap caot dec flm gau hi iadl n ksy la madehinopst ncdehjmvy ohkr parw ri scd tnx ut vait waivy azaz xazazx zipcode dd reverbose newlines added readability as followup question regex separated multiple lines like readability need one line work i could concatenate separate lines i suppose ps i know smells like homework actually work edit actual code used requested i left everything actually already perhaps help the function part django view matter much purposes def parseaddressaddress pattern rnaddressd xazaz po box dsiaddressaptapartmentbldgbuildingdeptdepartmentflfloorhngrhangerlotpierrmroomslippcteoptrlrtrailerunitxwbsmtbasementfrntfrontlbbylobbylowrlowerofcofficephrearsideupprupperscityazazxazaz xstatealkszrapcaotdecflmgauhiiadl nksylamadehinopstncdehjmvyohkrparwriscd tnxutvaitwaivyazazxazazxzipcodedd match researchpattern address i using home address input i tried main st austin tx input well result,2 well i know anything yahoo term extractor i presume call requestadddataquerydata simply tacks another data set iteration loop and call openeropenrequestread would probably process results first data set so either request object hold one query opener object inner workings process one query simple actually third reason comes mind i read documentation provided link probably true one rate limits the term extraction service limited queries per ip address per day noncommercial use see information rate limiting so would make sense api would limit usage one query time allow flood bunch queries single request in event i assume could fix problem naive way many request variables instead one maybe creating new request every iteration loop if worried storing results trying debug could try c comments print building query datadict appid appid context c querydata urlliburlencodedatadict request urllibrequest i know initialize variable requestadddataquerydata print fetching result result openeropenrequestread print result timesleep again i know yahoo term extractor i really time research may well better native way if post details code ie classes request opener objects coming i might able elaborate,i trying loop odd files directory each file text trying find keywords using yahoo term extractor i able extract text file i able iteratively call api using text input only keywords first file displayed here code snippet comments list i extracted stored text file c comments print building query datadict appid appid context c querydata urlliburlencodedatadict requestadddataquerydata print fetching result result openeropenrequestread print result timesleep,1 i opt parsing chunk xml separately you seem already sample code here take code def parsexmlbufferbuffer dom minidomparsestringjoinbuffer join list string xml parse dom buffer filereadline initialise first line line file linestartswithxml parsexmlbufferbuffer buffer reset buffer bufferappendline list operations faster concatenating strings parsexmlbufferbuffer parse final chunk once broken file individual xml blocks actually parsing depends requirements extent preference options lxml minidom elementtree expat beautifulsoup etc update starting scratch i would using beautifulsoup usrbinenv python beautifulsoup import beautifulsoup def separatedxmlinfile file openinfile r buffer filereadline line file linestartswithxml yield joinbuffer buffer bufferappendline yield joinbuffer fileclose xmlstring separatedxmlipgbxml soup beautifulsoupxmlstring num soupfindalldocnumber print numcontents this returns d d d d d d d d lots,my input file actually multiple xml files appending one file it google patents it structure xml version encodingutf doctype uspatentgrant system uspatentgrantdtd rootnoderootnode xml version encodingutf doctype uspatentgrant system uspatentgrantdtd rootnoderootnode xml version encodingutf doctype uspatentgrant system uspatentgrantdtd rootnoderootnode python xmldomminidom parse nonstandard file what better way parse file i code good performance line infile line xml version encodingutf xmldoc minidomparsexmlstring else xmlstring line,1 your database probably empty must setup tables corresponding models normally would done running python managepy syncdb first create database tables the problem case run syncdb python see running test try setup tables mysql database instead to get around temporarily change test sysargv true then run python managepy syncdb setup sqlite database tables now everything setup put back test everything run smoothly however probably want move database tmp directory django needs reuse database every time run tests otherwise create database tables every test note add new models need repeat procedure create new tables sqlite if add new fields existing model need manually add columns sqlite database using sqlite interface alter table automatically using tool like south,i trying run unittest django normally i use mysql database backend since painfully slow spinup single unittest i using sqlite so switch sqlite unittests settingspy i import sys test sysargv databases default engine djangodbbackendssqlite name tmpdatabasedb user password host when i run unittest python managepy test myapptesttestmyfunc i get error databaseerror table djangocontenttype googling shows possible reasons error none seem applicable i running apache i see permissions would issue the file tmpdatabasedb created tmp writable the app djangocontribcontenttypes included installedapps what i missing edit i ran problem django none proposed solutions work,1 here take using generator lxmletree extracted information purely example import urllib os zipfile lxml import etree def xmlsplitterdataseparatorlambda x xstartswith xml buff line data separatorline buff yield joinbuff buff buffappendline yield joinbuff def firstseqdefaultnone return first item sequence seq defaultnone value item seq return item return default datasrc httpcommondatastoragegoogleapiscompatentsgrantbibipgbwkzip filename datasrcsplit ospathexistsfilename openfilename wb filewrite r urlliburlopendatasrc filewritewriterread zf zipfilezipfilefilename xmlfile first x x zfnamelist xendswith xml assert xmlfile none count item xmlsplitterzfopenxmlfile count count break doc etreexmlitem docid joindocxpath publicationreferencedocumentidtext title firstdocxpath inventiontitletext assignee firstdocxpath assigneeaddressbookorgnametext print docid ntitle nassignee nformatdocidtitleassignee yields docid usds title glove backhand assignee blackhawk industries product group unlimited llc docid usds title belt sleeve assignee none docid usds title underwear assignee xtechnology swiss gmbh docid usds title portion compression shorts assignee nike inc docid usds title apparel assignee none docid usds title hooded shirt assignee none docid usds title hooded shirt assignee none docid usds title hooded shirt assignee none docid usds title headwear cap assignee none docid usds title footwear assignee vibram spa,my input file actually multiple xml files appending one file it google patents it structure xml version encodingutf doctype uspatentgrant system uspatentgrantdtd rootnoderootnode xml version encodingutf doctype uspatentgrant system uspatentgrantdtd rootnoderootnode xml version encodingutf doctype uspatentgrant system uspatentgrantdtd rootnoderootnode python xmldomminidom parse nonstandard file what better way parse file i code good performance line infile line xml version encodingutf xmldoc minidomparsexmlstring else xmlstring line,2 the unit test work isolated mode isolate dependent resources done using isolation framework mocking framework common frameworks legacy windows systems devmagicfake moq rhino mocks typemock devmagicfake make able fake db need create db even code save data save data memory retrieve anytime,i want know bestdifferent ways test rest api uses database backend i developed api flask python want use unittest nose but problem resources require another resource create first place is way say test creation blog post requires another test involving creation author successful,1 only import module import module consider apy import b class a def barself return bb bpy import class b def barself return aa this works perfectly fine,i know issue circular imports python come many times i read discussions the comment made repeatedly discussions circular import sign bad design code reorganised avoid circular import could someone tell avoid circular import situation i two classes i want class constructor method takes instance class returns instance class more specifically one class mutable one immutable the immutable class needed hashing comparing the mutable class needed things this similar sets frozensets lists tuples i could put class definitions module are suggestions a toy example would class a attribute list class b attribute tuple then class a method takes instance class b returns instance class a converting tuple list similarly class b method takes instance class a returns instance class b converting list tuple,3 you added new attribute name body model post application posts django cant automatically create database column new field create database table new model so need create new fields manually alter table database alter table postspost add column body text,i trying create new website django i starting web development however new many bits pieces eg sql i defined model various fields went ahead created instance etc django shell later i changed name fields i try things model like postobjectsall i get errors databaseerror column postspostbody how i update database entries delete i get get site thanks,1 i prefer init beginning i would actually write class way rather something like class aclass def initself methodtouse defaultmethod print getattrself methodtouse def defaultmethodself return name main aclass the problem compile time default arguments created function defaultmethod use inside init method,consider following code class aclass def defaultmethodself return def initself methodtouse defaultmethod print methodtouseself name main aclass in case one cannot move defaultmethod init method i causes nameerror name defaultmethod defined this means i need define method init else python know this means i longer init first method leaves wonder whether usual place init method end class beginning,1 django djangocontribsites framework nice sites running server access database if distributed application different sites different hosts different sites different databases resort single signon solutions i use openid custom provider centralize logins apps running different databases other solutions include cas provider consumer,i need split current django application two sites site a contain public facing site would contain static pages registration system the site — site b — site registered users they also login application site site b if i mistaken i use djangocontribsites framework accomplish task multiple sites common autheticationregistration backend how i accomplish thanks,1 i think things little peculiarly you still put init high first method readability key init exposes expect main instance fields here three alternatives my preference first documents default method require least modification code the last works could confusing anyone maintain code class aobject def initself methodfoo callablemethod methodself else getattrself method def fooself print something class bobject def initself method none method none selfdefaultmethod else methodself def defaultmethodself print foo def defaultmethodself print selfx class cobject def initself method defaultmethod selfx bleh methodself def anothermethodself print something else def defaultmethodproxyself defaultmethodself,consider following code class aclass def defaultmethodself return def initself methodtouse defaultmethod print methodtouseself name main aclass in case one cannot move defaultmethod init method i causes nameerror name defaultmethod defined this means i need define method init else python know this means i longer init first method leaves wonder whether usual place init method end class beginning,2 solution name south i use south django sites really useful easy use got used give shoot using south migrate table need run commands first create migrate script python managepy schemamigration posts auto afterwars actual apply table changes python managepy migrate posts,i trying create new website django i starting web development however new many bits pieces eg sql i defined model various fields went ahead created instance etc django shell later i changed name fields i try things model like postobjectsall i get errors databaseerror column postspostbody how i update database entries delete i get get site thanks,1 you could regular expressions deal nested structures instead could use pyparsing nestedexpr,i attempting use python alter text strings using module ie resub however i think question applicable languages regex implementations i number strings represent treelike data structures they look something like abcd abcd abcdefghi each letter represents branch edge letters parentheses represent branches coming another branch everywhere plain tuple values tuple comma separated single letter i would like take prefix x suffix x tuple apply values tuple under transformation strings would become acbcd abcbd abcdedfdgdhdi applying methodology repeatedly would ultimately yield acdbcd abcabd abacadeadfadgadhadi the strings tuples represent paths tree starting root ending leaf any help accomplishing task using regular expressions approaches would greatly appreciated,2 the problem describing one enumerating paths within graph you describe three graphs a b c d a b c d a b c d e f g h i want enumerate paths this involves distributing value across arbitrarily nested structure if could done regexes i certain would done i believe several passes my sense problem though best solved parsing string graph structure enumerating paths if want physically build graph probably generate strings within usersupplied actions parser generator a regexbased solution would know handle abc abcdefghi you match strings azazaz would distribute submatches without logic since need logic anyway might well perform real graph structure you also string would better auspices parser generator handle contextfree contextsensitive structures,i attempting use python alter text strings using module ie resub however i think question applicable languages regex implementations i number strings represent treelike data structures they look something like abcd abcd abcdefghi each letter represents branch edge letters parentheses represent branches coming another branch everywhere plain tuple values tuple comma separated single letter i would like take prefix x suffix x tuple apply values tuple under transformation strings would become acbcd abcbd abcdedfdgdhdi applying methodology repeatedly would ultimately yield acdbcd abcabd abacadeadfadgadhadi the strings tuples represent paths tree starting root ending leaf any help accomplishing task using regular expressions approaches would greatly appreciated,1 unfortunately opencv support tiff directories able read first frame multiframe tiff files,anyone know opencv capable loading multiframe tiff stack i using opencv python,3 edit given defining protocol useful might useful contexts assuming stream tcp socket need implement message framing mechanism use existing higher level protocol one straightforward way define message bit integer length field followed many bytes data sender take length json packet pack bytes struct module send socket send json packet receiver repeatedly read socket least bytes data use structunpack unpack length read socket least much data json packet anything left length next message if point going want send messages consist something json socket may want send message type code length data payload congratulations invented yet another protocol another slightly standard method djb netstrings protocol similar system proposed textencoded lengths instead binary directly supported frameworks twisted,i socket opened i like read json data the problem json module standard library parse strings load reads whole file calls loads inside it even looks way inside module depends parameter string this real problem sockets since never read string know many bytes read actually parse so questions is simple elegant workaround is another json library parse data incrementally is worth writing edit it xbmc jsonrpc api there message envelopes i control format each message may single line several lines i could write simple parser needs getc function form feed using srecv pythonic solution i little lazy,2 do control json try writing object single line then readline call socket described infile sockmakefile true line infilereadline line break result jsonloadsline,i socket opened i like read json data the problem json module standard library parse strings load reads whole file calls loads inside it even looks way inside module depends parameter string this real problem sockets since never read string know many bytes read actually parse so questions is simple elegant workaround is another json library parse data incrementally is worth writing edit it xbmc jsonrpc api there message envelopes i control format each message may single line several lines i could write simple parser needs getc function form feed using srecv pythonic solution i little lazy,1 it sounds like may using frozensets instead tuples x x setfrozensetts ts x setfrozenset,i currently working script lists looks like example now turning list set returns set for purposes i need recognize tuples equal well i dont care retaining order all solutions i think really messy anyone idea i would gratefull,3 if getting json http stream use contentlength header get length json data for example import httplib import json h httplibhttpconnection graphfacebookcom hrequest get response hgetresponse contentlength intresponsegetheader contentlength read data read contentlength bytes socket closed data lendata contentlength contentlength responsereadcontentlength lendata break data we full data decode j jsonloadsdata print j,i socket opened i like read json data the problem json module standard library parse strings load reads whole file calls loads inside it even looks way inside module depends parameter string this real problem sockets since never read string know many bytes read actually parse so questions is simple elegant workaround is another json library parse data incrementally is worth writing edit it xbmc jsonrpc api there message envelopes i control format each message may single line several lines i could write simple parser needs getc function form feed using srecv pythonic solution i little lazy,2 in settuplesortedelt elt example out set,i currently working script lists looks like example now turning list set returns set for purposes i need recognize tuples equal well i dont care retaining order all solutions i think really messy anyone idea i would gratefull,3 the solution traversing filesystem finding submodules ok long implement every plugin filesystem based module a flexible way would explicit plugin list main module every plugin whether module created file dynamically even instance class adding list explicitly maybe via registerplugin function remember explicit better implicit part zen python,while fairly trivial python import child module another module list attributes becomes slightly difficult want import child modules i building library tools existing d application each tool menu item sub menus i like tool responsible creating menus many change based context templates i like base module able find child modules check createmenu function call finds what easiest way discover child modules,1 i found hint librets need permethod basis httpcodecrtrealtorsorgprojectslibretsbrowserlibretstrunkprojectswigautoptrreleaseirevhead basically want unwrap autoptr receive c wrap passing c example code put file original prototype virtual void setsomethingstdautoptrvalueclass value replacement generated swig extend void setsomethingvalueclass value stdautoptrvalueclass tmpvalue selfsetsomethingtmp retrieving object wrapped autoptr using swig macro define swigreleaseautoptrreturntype methodname proto args extend returntype methodname proto stdautoptrreturntype autoresult selfmethodname args return autoresultrelease enddef inside class virtual autoptrvalueclass somemethodconst stringamp foo replaced swigreleaseautoptrvalueclasssomemethodconst stringamp foofoo,i trying wrap c library uses autoptr i using swig want generate python bindings i v seen section swig docu use swig smart pointers but i get work swig generates code wants initialize autoptr using const reference autoptr defines copy constructor nonconst reference eg autoptrautoptr amp the generated code compile discards const qualifiers when i manually delete const qualifier code compiles fine i v seen lots mailing list entries nothing helped can someone provide working example my non working sample module autoptrtest include memory include iostream using namespace std namespace std template class t class autoptr autoptr autoptrautoptr amp t operator const inline class test test cout test endl public static stdautoptrtest create const return autoptrtestnew test void greet cout hello endl template stdautoptrtest i compiled using cmake following cmakeliststxt cmakeminimumrequiredversion findpackageswig required includeswigusefile findpackagepythonlibs includedirectoriespythonincludepath includedirectoriescmakecurrentsourcedir setcmakeswigflags setsourcefilespropertiesautoptrtesti properties cplusplus on swigaddmoduleautoptrtest python autoptrtesti swiglinklibrariesautoptrtest pythonlibraries thanks httpwwwswigorgdocswigdocumentationhtmlswigplussmartpointers,1 this generates list items item followed lowercased letter character originally uppercase letter character then joins together string removes leading underscores might added process print join charlower charisupper else char char inputstringlstrip btw specified underscores already present string i sure handle case i punted,i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve,1 you initialize variables none check var none var none var which written one line var var none else var using shortcut checking none recommended var var alternatively anything assigned variable variable name exist hence using later raise nameerror also use knowledge something like try var except nameerror var i would advise,i ror programmer new python i trying find syntax allow set variable specific value previously assigned basically i want var previously assigned var,3 controllermate might job,i friend mouse scroll asked write program could scroll windows i familiar python thinking something could bind certain keys scroll are libraries way scroll another window like webpage text editor,1 this different style programming i always try rewrite things looked like bar none foo bar baz bar none bar quux foo bar baz else bar quux that say i try hard avoid situation code paths define variables others in code never path causes ambiguity set defined variables in fact i usually take step make sure types regardless code path it may matter personal taste i find pattern though little less obvious i writing much easier understand i later reading,i ror programmer new python i trying find syntax allow set variable specific value previously assigned basically i want var previously assigned var,3 post data treated unordered time maybe even don worry ordering,i looking get method parameters dictionary tuple pairs list later arguments get put urlliburlencode formed post statement i got far so questions def funcabcdenonefnone values locals data dictkv kv valuesiteritems v none this second line strips optional arguments used the problem i using post data later i need order arguments maintained so similar way i guess avoiding use dictionaries orderless edit i might overlooked something completely i send values post order right,1 you use selfnextcurrentstate want next method class scope the function next global nextobj works obj iterator you might want look yield statement python documentation,i began coding python recently encountered problem assigning value returned function variable class combolock def initselfnumnumnum selfx numnumnum def nextself state print enter combination combo rawinput combo selfxstate print correct return else print wrong return def lockself currentstate currentstate temp nextcurrentstate temp currentstate currentstate else currentstate print alarm when i call lock function i get error line temp nextcurrentstate saying int object iterator,3 as andrea pointed need tell python want call next method self object need call selfnextcurrentstate also note defined incorrect initializer aka constructor you use double underscores init instead init otherwise method called object creataion,i began coding python recently encountered problem assigning value returned function variable class combolock def initselfnumnumnum selfx numnumnum def nextself state print enter combination combo rawinput combo selfxstate print correct return else print wrong return def lockself currentstate currentstate temp nextcurrentstate temp currentstate currentstate else currentstate print alarm when i call lock function i get error line temp nextcurrentstate saying int object iterator,2 use csvdictwriter fieldnames restval arguments,i list dictionaries like item bla item bli item blu item love item python notice dict key item i want produce csv output i insert everything sql table itemitemitem blabliblu lovepython i found easy way dictionaries share keys i see elegantly case,1 i assuming want store theme name value value defaultinputmessage if case work form settingform theme sometheme defaultinputmessage hello formisvalid key formfieldskeys setting settingobjectscreatenamekey valueformcleaneddatakey,i simple form django looks like class settingformformsform theme formscharfieldrrequiredtrue initial multgi defaultinputmessage formscharfieldrequiredtrue initial type begin model store looks like class settingmodelsmodel name modelscharfield nullfalse maxlength value modelscharfield nullfalse maxlength when form submitted store form fields key value pairs page rendered i initialize form key value i tried looking implementation unable find one any help thanks,1 thanks comments stefan behnel mark florisson cython discussion group problem reference bound method going scope getting garbage collected the solution cdef class pyscene cdef scene mscene cdef object drillbuttonfunc def setdrillbuttoncallbackself func selfmscenesetdrillbuttoncallbackpyhdbuttoncallback voidfunc selfdrillbuttonfunc func by keeping reference bound method class get cleaned stops used,i implementing cythonbased interface c library i implemented callback system works normal functions fails strangely passing bound methods here portion cython code cdef extern volumehaptictoolh cdef cppclass hdbuttonevent bool ispressed unsigned int getbuttonid vecfloat getposition ctypedef void hdbuttoncallbackhdbuttonevent void cdef extern sceneh cdef cppclass scene scene void setdrillbuttoncallback hdbuttoncallback void cdef void pyhdbuttoncallbackhdbuttonevent e void userdata print objectuserdata objectuserdata eispressed egetbuttonid topyvecfegetposition cdef class pyscene cdef scene mscene def initself selfmscene new scene def delself del selfmscene def setdrillbuttoncallbackself func print func selfmscenesetdrillbuttoncallbackpyhdbuttoncallback voidfunc and i trying call class rendercanvasglcanvas def initself parent selfscene cybraincasepyscene selfscenesetdrillbuttoncallbackselfondrillbuttonpress def ondrillbuttonpressself event print event when code run initially printed bound method rendercanvasondrillbuttonpress uirendercanvas proxy swig object type wxglcanvas xba that seems right the problem callback triggered printed bound method shellreadline wxpyshellshell proxy swig object type wxstyledtextctrl xa a totally different bound method called however i make ondrillbuttonpress static method function ondrillbuttonpress xfc printed initialization triggering calls is incompatibility saving bound methods void,2 class class var classvar this copy current value classvar i need get variable first class use second use classvar instead making copy current value var,ok i two classes one dependent so i need get variable first class use second but second variable constantly changing like class class var def meth self selfvar class class var classvar def see self return selfvar obj class obj class objmeth objsee this would return if i say print var class one prints changed var but class gets still i guess still referring old var what i wrong i thanks,3 let runoff new pythonistas snide remarks maybe op legitimate needs code generation try cheetah cog jinja fun,quick question i wondering software django software generates python coding automatically if please let know,2 unfortunately possible convert django format though possible route take get hashes imported detailed django salted md algorithm uses simple algorithm mdsalt password encoded hexidecimal on hand hashes output php crypt begin simple md hashes instead use password hashing algorithm known mdcrypt this much complex secure simple md hash there section linked page describes mdcrypt format amp algorithm there way translate django format offer support algorithm within code while django code called python stdlib crypt function way django mangles hashes means easy way get hash beginning way django crypt way signal crypt want use mdcrypt instead older descrypt however possible route monkeypatch djangocontribauthmodelsuser supports normal django hashes well mdcrypt format that way import hashes unchanged one way manually overriding usersetpassword usercheckpassword methods another alternative use passlib library contains django app designed take care well provide crossplatform support mdcrypt et al disclaimer i author library unfortunately django plugin undocumented i tested much outside django deploys though works fine there beta documentation source edit as passlib extension officially released documented in order use install passlib add passlibextdjango list installed apps then within settingspy add following passlibconfig passlib schemes mdcrypt djangosaltedsha djangosaltedmd djangodescrypt hexmd djangodisabled default mdcrypt deprecated djangodescrypt hexmd this override usersetpassword usercheckpassword use passlib instead builtin code the configuration string configures passlib mimic django builtin hashes adds support mdcrypt hashes accepted asis,i porting bunch user accounts legacy php website new shiny djangobased site a bunch passwords stored md hash output php crypt function see third example given password hash legacy application fktbivnwwbncpigfcemoob how might i convert django form mdsalthash the crypt md output seems use different alphabet django md support appears using hexdigest update there similar unanswered question interesting potential solution convert php hash base encoding based initial poking seem produce usable md hexdigest concrete example a concrete example might help given password foo salt aofigrjlh in php crypt foo aofigrjlh produces hash aofigrjlxlnodxdkdukwwbx crypt operating md mode wacky danish translation md algorithm update it mdcrypt since python dutchderived language python crypt module supports desstyle hashing in python i need able reproduce hash regular derivation given original password salt,3 check passlibhashmdcrypt awesome passlib project,i porting bunch user accounts legacy php website new shiny djangobased site a bunch passwords stored md hash output php crypt function see third example given password hash legacy application fktbivnwwbncpigfcemoob how might i convert django form mdsalthash the crypt md output seems use different alphabet django md support appears using hexdigest update there similar unanswered question interesting potential solution convert php hash base encoding based initial poking seem produce usable md hexdigest concrete example a concrete example might help given password foo salt aofigrjlh in php crypt foo aofigrjlh produces hash aofigrjlxlnodxdkdukwwbx crypt operating md mode wacky danish translation md algorithm update it mdcrypt since python dutchderived language python crypt module supports desstyle hashing in python i need able reproduce hash regular derivation given original password salt,1 using regexp something trivial use give heartache pain if insist using regex not recommended look methods used here xml if dsl mean abbry lingvo dict format may want look stardict it read abbry dsl format,i need parse dsl file using python a dsl file text file text special markup tags used abbyy lingvo it looks like activate mbacâ·tiâ·vateb id c rosybrowncc darkslategraybactivatebc c darkslategraybactivatesbc c darkslategraybactivatedbc c darkslategraybactivatingbcc rosybrownc pbrep c darkgray cc darkcyanëˆã¦ktéªveéªtc szactivategbwavs pnamep c darkgray cc darkcyanëˆã¦ktéªveéªtc szactivateuswavs c orange verbc c darkgray cbcf sthcf b mdto make sth device chemical process start workingd mex• exexxthe burglar alarm activated movementx ex mex• exc darkgray cexxthe gene activated specific proteinx ex derivedâ wordmc darkslategrayuderivedâ worduc ↑activationderivedâ word sideverbformsmc darkslategrayuverbâ formsuc sxverbformsactivatejpgssideverbforms now i see option parse file using regexps but i doubt achieved since tags format hierarchy inside others i use special xml html parsers they perfect creating treestructure document designed special tags html xml what best way parse file format is python library purpose,1 engine allows create tree basing nesting tag structure look httpwwwdabeazcomply you may able define syntax quickly easily set lexical rules grammar productions if like one list alternatives httpwikipythonorgmoinlanguageparsing,i need parse dsl file using python a dsl file text file text special markup tags used abbyy lingvo it looks like activate mbacâ·tiâ·vateb id c rosybrowncc darkslategraybactivatebc c darkslategraybactivatesbc c darkslategraybactivatedbc c darkslategraybactivatingbcc rosybrownc pbrep c darkgray cc darkcyanëˆã¦ktéªveéªtc szactivategbwavs pnamep c darkgray cc darkcyanëˆã¦ktéªveéªtc szactivateuswavs c orange verbc c darkgray cbcf sthcf b mdto make sth device chemical process start workingd mex• exexxthe burglar alarm activated movementx ex mex• exc darkgray cexxthe gene activated specific proteinx ex derivedâ wordmc darkslategrayuderivedâ worduc ↑activationderivedâ word sideverbformsmc darkslategrayuverbâ formsuc sxverbformsactivatejpgssideverbforms now i see option parse file using regexps but i doubt achieved since tags format hierarchy inside others i use special xml html parsers they perfect creating treestructure document designed special tags html xml what best way parse file format is python library purpose,1 is number always length if could slice string compinfomapece,compinfomapece this string output cpu always specialnonprintable characters number aim obtain number excluding text specialnonprintable i trying split method sure use specialnonprintable characters can anyone please suggest something it would great help thanks,1 htmlparser construct representation memory html file you could handle methods simpler way would use beautifulsoup import beautifulsoup import beautifulsoup soup beautifulsoup titlea print soup titlea comma recompile soupfindalltextcomma treplacewithtreplace ampsbquo print soup titleampsbquoa,i need replace strings data content html page i use replace function directly i need change data section it modify tags attributes i used htmlparser but i stuck writing back file using htmlparser i parse get data content i necessary changes but put back html file please help here code class entityhtmlhtmlparserhtmlparser def initself filename htmlparserhtmlparserinitself f openfilename selffeedfread def handlestarttagself tag attrs needn anything pass def handledataself data print data data datareplace ampsbquo,1 does work toolsstaticdirroot ospathjoinospathabspathoscurdir trunkroot,i recently asked related question problems serving static files faviconico robotstxt cherrypy in config file i absolute path described is way make relative path the reason i team my teammates well server use different paths location code toolsstaticdiron true toolsstaticdirroot projectsmysitetrunkroot toolsstaticdirdir toolsstaticfileroot projectsmysitetrunkroot faviconico toolsstaticfileon true toolsstaticfilefilename imagesfaviconico robotstxt toolsstaticfileon true toolsstaticfilefilename robotstxt images toolsstaticdiron true toolsstaticdirdir images css toolsstaticdiron true toolsstaticdirdir css js toolsstaticdiron true toolsstaticdirdir js,1 though question quite old author seem responsive google still highly ranks page many people may come i post answer searching google custom search described answer similar question parameters follows key yes api key google account to obtain go apis console switch custom search api services tab find actual api key api access tab cx yes search engine unique code note code form abcdef omuauflfve part code param q actual search query siteexamplecom part google query language see search tips details,i writing python module query google custom search api return listings domain examplecom i have reading instructions httpscodegooglecomapiscustomsearchvgettingstartedhtml little stumped moment are assumptions listed correct for example search results examplecom url query httpswwwgoogleapiscomcustomsearchvkeymykeyampcxomuauflfveampqsiteexamplecom keymykey value key given google cx name search engine google is correct omuauflfve i idea qsiteexamplecom this return results examplecom eg wwwaexamplecom bexamplecom example com,2 standard pasteexceptionserrormiddlewareerrormiddleware already even little,is way create middleware catch every raised exception print stacktrace log stdout possibly additional information pylons framework,1 no i believe possible analyse rrule see intersect another one without creating datetime objects essentially asking output algorithm without running algorithm i think noncomputable however certain types rrule possible eg rrule every thursday intersect rrule every tuesday the problematical ones days month days year intersecting days week frequencies never intersect the best bet would rules analytically checkable analytically others generate next year data compare manually the algorithm run fast since cache existing occupied times add rule,i working application looks like google calendar one main difference events intersections events this means two events may share common time even minutes granularity this specially useful calendar store meetings since impossible time two meetings just like google calendar events may created using recurrence rules every friday sunday am pm example so i would like detect overlapping events using rrules pythondateutil module without needing create n datetime objects checking intersection one is possible detect overlapping dates using rrules is anything similar already implemented another library,1 okay suppose ordinary numpy array in x nparray you view socalled structured array using view in xravelviewdtype x xdtype xdtype now use npargsort order parameter in npargsorty order x,i scipy arraythe oigion one color channel rgb image i want find specific occurance element i use npargsortarr job but problem i want specific order along axis the scipy example follows x nparray dtype x npargsortx order x in example specified name filed type after used argument order specify order sorting in case i filed names how i thanks lot,2 even tailrecursive function needs return python def optimizecurrentprice lastprofit currentprofit profitcurrentprice lastprofit currentprofit currentprofit return bestprice currentprice bestprofit lastprofit else add return return optimizecurrentprice currentprofit,i created tail recursive function solve optimization problem def optimizecurrentprice lastprofit currentprofit profitcurrentprice lastprofit currentprofit currentprofit return bestprice currentprice bestprofit lastprofit print bestprice currentprice bestprofit lastprofit else optimizecurrentprice currentprofit def bestprice optimized optimize optimize return dict allowing optimized bestprice optimized bestprofit called printpricing tickets produce greatest profit formatoptimized bestprice optimized bestprofit the function operates correctly exception fails return anything i mean say first statement never called fact i uncomment print line print correct result return statement fails return dictionary this results typeerror i attempt call optimized bestprice nonetype object subscriptable i working error seem either make work find anything regarding online at point matter wanting know solution any ideas thanks,3 the method name str underscores surrounding str underscores surrounding,this script import math class vector def initself x selfx x selfy def strself return formatselfx selfy classmethod def vectorpointscls p p p p b p p return vectora b a b vectab vectorvectorpointsa b printvectab vect vector printvect when i run script i get mainvector object xfded mainvector object xfdff apparently str method returning anything,3 you using three underscores instead normal two,this script import math class vector def initself x selfx x selfy def strself return formatselfx selfy classmethod def vectorpointscls p p p p b p p return vectora b a b vectab vectorvectorpointsa b printvectab vect vector printvect when i run script i get mainvector object xfded mainvector object xfdff apparently str method returning anything,2 based code usrbinenv python pyqt import qtgui qtcore import sys class rotatedbuttonqtguiqpushbutton def initself text parent orientation west superrotatedbuttonselfinittext parent selforientation orientation def painteventself event painter qtguiqstylepainterself painterrotate paintertranslate selfwidth painterdrawcontrolqtguiqstylecepushbutton selfgetsyleoptions def minimumsizehintself size superrotatedbutton selfminimumsizehint sizetranspose return size def sizehintself size superrotatedbutton selfsizehint sizetranspose return size def getsyleoptionsself options qtguiqstyleoptionbutton optionsinitfromself size optionsrectsize sizetranspose optionsrectsetsizesize optionsfeatures qtguiqstyleoptionbuttonnone selfisflat optionsfeatures qtguiqstyleoptionbuttonflat selfmenu optionsfeatures qtguiqstyleoptionbuttonhasmenu selfautodefault selfisdefault optionsfeatures qtguiqstyleoptionbuttonautodefaultbutton selfisdefault optionsfeatures qtguiqstyleoptionbuttondefaultbutton selfisdown selfmenu selfmenuisvisible optionsstate qtguiqstylestatesunken selfischecked optionsstate qtguiqstylestateon selfisflat selfisdown optionsstate qtguiqstylestateraised optionstext selftext optionsicon selficon optionsiconsize selficonsize return options class mainqtguiqframe def initself qtguiqframeinitself selfapplication qtcoreqcoreapplicationinstance selflayout qtguiqhboxlayout selfbutton rotatedbuttonhello self orientationwest selflayoutaddwidgetselfbutton selfsetlayoutselflayout name main application qtguiqapplicationsysargv applicationmain main applicationmainshow sysexitapplicationexec,i would likewith python qtto rotate qpushbutton least text stand vertically i seen documentation online i make much sense itit c i cilliterate from i read though one needs reimplement paintevent handler instantiate rotate qpainter what i figure however one qstring qpushbutton i need i assumed qpaintevent would sender attribute like signals all i seem get event qrect qregion how i find event specific button label or question really rotate qpushbutton mru suggested c example reimplements qpushbutton completely since i clue c since i really need full reimplementation i tried reimplement painevent handler python based example here i translated work usrbinenv python pyqt import qtgui qtcore import sys class rotatedbuttonqtguiqpushbutton def initself text parent orientation west qtguiqpushbuttoninitself text parent selforientation orientation def painteventself event painter qtguiqstylepainterself selforientation west painterrotate elif selforientation east painterrotate else raise typeerror painterdrawcontrolqtguiqstylecepushbutton selfgetsyleoptions def getsyleoptionsself options qtguiqstyleoptionbutton optionsinitfromself size optionsrectsize sizetranspose optionsrectsetsizesize optionsfeatures qtguiqstyleoptionbuttonnone optionstext selftext optionsicon selficon optionsiconsize selficonsize return options class mainqtguiqframe def initself qtguiqframeinitself selfcount selfapplication qtcoreqcoreapplicationinstance selflayout qtguiqhboxlayout selfbutton rotatedbuttonhello self orientationwest selflayoutaddwidgetselfbutton selfsetlayoutselflayout name main application qtguiqapplicationsysargv applicationmain main applicationmainshow sysexitapplicationexec,2 just put blanktrue model ie rushingattempts modelscharfield maxlength verbosename rushing attempts blanktrue,every time i enter new player admin portion django i get error message says this field required is way make field required without create custom form can i within modelspy adminpy here class modelspy looks like class playerstatmodelsmodel player modelsforeignkeyplayer rushingattempts modelscharfield maxlength verbosename rushing attempts rushingyards modelscharfield maxlength verbosename rushing yards rushingtouchdowns modelscharfield maxlength verbosename rushing touchdowns passingattempts modelscharfield maxlength verbosename passing attempts thanks,3 here sections python tutorial may find helpful reading writing files using python calculator data structures,i new dummy pythonplease help following problem i data txt format colums nameitems i interested rd th column items column goes like set etc i need open text file read file group similar items colums one array find maximum array take average arrays formed similar items finally i get value average individual maximum array eg items greatest items items greatest items item greatest items average maximum items n x n total similar items instance name items sty sty sty sty sty sty sty sty sty sty sty sty sty sty sty,1 well bit hackish could something like make shell script run nosetests setting environment variable export nosetestflag nosetest then code check import os osenvironget nosetestflag testingmode else livemode,i running nosetests setup function needs load different database production database the orm i using peewee requires database model set definition so i need set conditional variable i know condition use order check nosetest running file i read stack overflow check nose sysmodules i wondering exact way check nose running,1 the logging module already implements singleton pattern call loggergetloggername create logger done already return although exactly asking i would suggest renaming getlog setuplog since then call setuplog beginning code afterwards actually need logger use logginggetlogger return alreadyconfigured logger,i python modules logmanagerpy runnerpy otherpy runnerpy first main module chain events module functions inside otherpy called so inside runnerpy i function call logmanagerpy logger logmanagergetlog i make simple logs eg loggercriticalohnoes what i want getlog function something similar singleton pattern logger set set logger return else return logger contents logmanagerpy import logging def getlog logger logginggetlogger pypro loggersetlevelloggingdebug create file handler logs even debug messages fh loggingfilehandler pyprolog fhsetlevelloggingdebug create console handler higher log level ch loggingstreamhandler chsetlevelloggingwarning create formatter add handlers fhformatter loggingformatter asctimes levelnames messages chformatter loggingformatter levelnames filenames line linenod messages fhsetformatterfhformatter chsetformatterchformatter add handlers logger loggeraddhandlerch loggeraddhandlerfh loggerinfo loggerinfolog system successfully initialised loggerinfo return logger as see logmanagergetlog attempt set log time called really i bit confused exactly happening runnerpy calls getlog function main method otherpy calls getlog global scope right imports function the result logs i make logged twice handlers made twice logger what simplest way i missing make getlog function return instance log elsewise,2 perhaps examining sysargv see command running,i running nosetests setup function needs load different database production database the orm i using peewee requires database model set definition so i need set conditional variable i know condition use order check nosetest running file i read stack overflow check nose sysmodules i wondering exact way check nose running,3 there way around multiple queries asking combined results set queries different addresses in queries implemented datastore you might want consider using ndb asynchronous queries run parallel perhaps explain trying achieve suggest efficient approach,i list addresses string type i like find events whose location value matches contents list because i thousands entries using in filter work i exceeded limit itemsfetch here i trying filter addresses come list string items addresses main st portland me broadway new york ny query eventall queryfilter location in addresses causes error class googleappengineapidatastoreerrorsbadargumenterror cannot satisfy query many subqueries max got probable cause many in filters query my model classes class eventgeomodel name dbstringproperty location dbpostaladdressproperty is better way find entries match specific criteria,2 here short version find rest wordy n table zipiterdatan let say start list data range data create iterator list dataiter iterdata now use zip function split list pay attention fun part table zipdataiter pprintpprinttable the expression dataiter results following list dataiter dataiter dataiter dataiter dataiter dataiter dataiter dataiter dataiter the expresion dataiter turns nine arguments zip function this zip function builds list tuples return list tuples tuple contains ith element argument sequences the returned list truncated length length shortest argument sequence because using iterator every time zip function looks new value gets next value sequence contrast behavior simply used list way table zipdata pprintpprinttable update my colleague points numpy available data numpyarrayrange datareshape array,flat one dimension tuple input data b c z output table two dimensions n say columns table code print table b c k l n shortest way,3 how table tupledatann n xrangelendata returns tuple made stepping data items time if want change number columns change nines generator,flat one dimension tuple input data b c z output table two dimensions n say columns table code print table b c k l n shortest way,1 use loop try conversions i added complex type demonstration def isvalidn int float complex try return tn except valueerror pass raise valueerrorinvalid number n print isvalid print isvalid print isvalidj,i trying get number cli input python valid input either int float i need maintain type so validating int returning float work this best thing i able come good def isvalidn try n return floatn return intn except valueerror print try def numinputs n rawinputs isvalidn none n rawinputs return isvalidn validnum numinputenter valid number clearly best way,3 your query messages dbgqlqueryselect from chatmessage order by time datastore model time property timestamp property attempting order property entities always return empty resultset,as beginner python app engine i ask assistance for time i working book code cloud learn basics using app engine the thing i successful far while issues i stemmed utf encodingdecoding time i problems making queries datastore to learn basics i recreated code simple chat service available chapter iv aforesaid book the key elements googleappengineext import webapp googleappengineextwebapputil import runwsgiapp import datetime googleappengineext import db start chatmessage class chatmessagedbmodel user dbstringpropertyrequiredtrue timestamp dbdatetimepropertyautonowaddtrue message dbtextpropertyrequiredtrue def strself return selfuser selftimestamp selfmessage end chatmessage above i defined datamodel message class chatroompagewebapprequesthandler def getself selfresponseheaderscontenttype texthtml selfresponseoutwrite html head titleappengine chat roomtitle head body hwelcome appengine chat roomh pcurrent time sp datetimedatetimenow messages dbgqlqueryselect from chatmessage order by time msg messages selfresponseoutwritepsp msg selfresponseoutwrite form actiontalk methodpost divbnameb textarea namename rows colstextareadiv pbmessagebp divtextarea namemessage rows colstextareadiv divinput typesubmit valuesend chatmessagediv form body html end mainpage in block i create ui performe gql query data i posted lastly class chatroomposterwebapprequesthandler def postself chatter selfrequestgetname msgtext selfrequestgetmessage msg chatmessageuserchatter messagemsgtext msgput selfredirect i create handler send collected data datastore having consulted book line line well google tutorial number threads website i still figure code work properly basically chat display past messages my guess i something wrong accessing stored data program throw exception i missing identifier something like perhaps i missing something obvious i would really appreciate help thank advance,1 i know scripting languages supporting probabilistic signature scheme however perl pss support cryptrsasspss use sample on perl chapter chilkat rsa perl library chilkat far i know libraries many languages well i sure either support pssr message recovery,i developing cryptographic software license system based digital signature message recovery rsapssr it means signed message case license block encoded directly signature usually encode hash message want sign the license keys generated server private rsa key verified client code public key for i developped server client code c library crypto everything working well now i want rewrite server code scripting language like php perl python web hosting service accept native code what scripting language supports rsapssr scheme i done quick search google i found information,1 i believe able use boundingrect method qgraphicstextitem calculate height width letter shift position qgraphicstextitem make look like centered around xy coordinates smth like qgraphicstextitem textitem new qgraphicstextitemtest text item scene int x x textitemboundingrectwidth int textitemboundingrectheight textitemsetposx hope helps regards,if i want place one letter qgraphicstextitem qgraphicsview way i set text display middle coordinates i specify if i use qgraphicstextitemsetposxy treats xy topleft corner i still want topleft qgraphicsscene remain though,1 as i recall python syntax showing class extension inheritance the equivalent scala would represents record class record represents respondent class respondent extends record represents pregnancy class pregnancy extends record scala comments form show documentation scaladoc type parameterization needed its main use allow classes accept return values arbitrary parameterized type for example listint liststring lists integers strings respectively,i trying translate httpthinkstatscomsurveypy script so i translating right python this file contains code use think stats allen b downey available greenteapresscom copyright allen b downey license gnu gplv httpwwwgnuorglicensesgplhtml import sys import gzip import os class recordobject represents record class respondentrecord represents respondent class pregnancyrecord represents pregnancy scala import sysprocess import javautilzipgzipinputstream import javaio class recordtval obj t class respondenttval record recordt class pregnancytval record recordt question did i class respondent class pregnancy correctly is type annotation correct class is logic correct i read type parameterization i bit iffy wanted see i correct path thank time,3 def numinputprompt error true result rawinputprompt candidate int float try return candidateresult except valueerror pass print error,i trying get number cli input python valid input either int float i need maintain type so validating int returning float work this best thing i able come good def isvalidn try n return floatn return intn except valueerror print try def numinputs n rawinputs isvalidn none n rawinputs return isvalidn validnum numinputenter valid number clearly best way,1 you use python builtin lib regular expressions to get timestamps something like import def main fileopenfile timestamprefindallr ssddsddss fileread print timestamp name main main,i trying get data text file following format jvm memorystatistics monidata depth recordssent rdoutdata depth recordssent rdoutreq totalrecordsreceived recordsreceived bytesreceived sender numreadoutrequestsreceived numhitsreceived numreadoutssent numhitscached numhitsqueued numreadoutrequestsqueued sndata depth recordssent stringhit depth recordssent stringhub timeoflasthitoutputfromhkn numberofactiveandtotalchannels numberofactivechannels timeoflasthitinputtohkn hitratelc hitrate totallbmoverflows system loadaverage networkio lotxerrs ethrxfifo ethrxpackets ethtxcompressed ethtxcompressed ethtxfifo ethtxpackets lotxcompressed ethrxcompressed lorxerrs ethtxfifo lotxfifo ethtxerrs ethrxmulticast ethtxcarrier ethrxcompressed ethtxdrop lotxdrop ethrxdrop ethtxdrop ethrxbytes ethtxpackets lorxbytes ethrxerrs ethtxerrs ethrxerrs ethtxerrs lorxpackets ethrxcompressed ethrxpackets ethtxdrop ethrxframe ethtxbytes ethrxmulticast ethrxpackets ethtxfifo ethtxerrs ethtxbytes ethrxframe ethrxframe ethrxbytes ethrxdrop ethrxdrop ethrxframe ethtxpackets ethtxbytes ethrxerrs ethrxbytes ethtxcompressed ethrxfifo lotxbytes ethrxerrs ethtxcarrier ethrxpackets lorxdrop ethtxcompressed ethrxfifo ethtxcolls ethtxcolls lotxpackets ethrxmulticast ethtxcolls ethtxfifo ethtxcolls lotxcarrier lorxframe ethrxdrop lotxcolls ethtxbytes lorxfifo ethtxdrop ethtxcarrier ethrxmulticast ethrxcompressed ethrxbytes ethtxcarrier ethtxpackets lorxmulticast lorxcompressed ethrxfifo availablediskspace devshm tcaldata depth recordssent pyratebuffermanager currentaquiredbuffers returnbuffercount currentaquiredbytes i trying get plot time versus various quantities stored file basically i would like get couple arrays similar format timestamp sndatadepth sndatarecordssend i got recommendations people use something like f openfile rreadlines dummy f dummyappendisplitsplit get numbers i trouble getting data sorted properly using categories text see timestamp thanks advance help as requested already used get data usrbinenv python import sys os import numpy np import pylab py def main snrate pyratebuffermanagercabu pyratebuffermanagerrbc pyratebuffermanagercaby endmonilog rangelensysargv file ospathsplitextsysargvi ext ospathsplitextsysargvi print file log ext fopensysargvi ru dummy dummy line f dummy refindall snrate dd line dummy refindall buffer overflow sn record channel line snrateappenddummy print ext moni ext fopensysargvi ru readlines print f timestamp dummy count line f timestamp refindallr ddsdddd line pyratebuffermanager line pyratebuffermanagercabu refindallr sscurrentaquiredbufferssd linecount print pyratebuffermanagercabu pyratebuffermanagerrbc refindallr returnbuffercountss linecount pyratebuffermanagercaby refindallr currentaquiredbytesss linecount timestamplistsettimestamp timestampsort print pyratebuffermanagercabu pyratebuffermanagerrbc print ext,1 for case simplest way class ba def newclsdataname obj anewcls data objname name return obj new actually static method takes class first argument class method call directly class want create instance for case view work inplace need assign result something simplest way class ba def newclsdata obj adata return objviewcls also got arrayfinalize defined a b probably typo need,i struggling subclass subclass numpyndarray i really understand problem would like someone explain goes wrong following cases i trying what i trying achieve i subclass numpyndarry behaves i want class a code i want subclass a class b code b contains additional information name methods decorated simpledata method case import numpy np class anpndarray def newclsdata obj npasarraydataviewcls return obj def arrayfinalizeselfobj obj none return class ba def initselfdataname superbselfinitdata selfname name property def simpledataself return datadata name main data nparangereshape b bdata b print typeb print bsimpledata running code produces output traceback recent call last file ndsubclasspy line module b bdata b typeerror new takes exactly arguments given i assume related name variable construction b due a subclass numpyarray a new method called b init method thus fix i assume b also needs new method appropriately handles additional argument my guess something like def newclsdataname obj adata objname name return obj i change class obj case import numpy np class anpndarray def newclsdata obj npasarraydataviewcls return obj def arrayfinalizeselfobj obj none return class ba def newclsdata obj adata objviewcls return obj def arrayfinalizeselfobj obj none return property def simpledataself return selfself name main data nparangereshape b bdata print typeb print bsimpledata when run output class maina traceback recent call last file ndsubclasspy line module print bsimpledata attributeerror a object attribute simpledata this surprises i expecting class mainb array array i assume call view b new somehow correctly setting class obj why i confused going would grateful someone could explain,2 a crash necessary mean trying gc used object it also mean calling python code without interpretor lock calling pyxdecref destructor leads think something like void mycallbackmyfunc myarg pygilstatestate gilstate pygilstateensure try myfuncmyarg catch pygilstatereleasegilstate myfunc goes scope crash longer gil simple solution try scopefunc myfunc myfunc emptyfunc scopefuncmyarg,i c library uses python callbacks the callback ie pyobject stored object class unaryfunction constructor pyincrefs the destuctor pyxdecrefs that problem the interpreter segfaults decref my solution decref seems wrong what proper way incdec reference count function importantly interpreter try gc function body live references edit on linux instead segfault i get assertion fail says python objectsfuncobjectc funcdealloc assertion ggcgcrefs failed,1 i really complete understanding query trying express weather union join third thing aside certainly possible map arbitrary selectable anything pass database returns rows i start assumption want kind union tablea tableb would rows a also rows b this easy enough change different concept reveal information shape data expressing we start setting real tables classes map declarative style sqlalchemy import import sqlalchemyextdeclarative base sqlalchemyextdeclarativedeclarativebase class tableabase tablename id columninteger primarykeytrue acode columnstring class tablebbase tablename b id columninteger primarykeytrue bcode columnstring since used declarative actually table instances work neccesary next part there many ways access tables way i prefer use sqlalchemy mapping introspection methods since work matter class mapped sqlalchemyormattributes import managerofclass atable managerofclasstableamappermappedtable btable managerofclasstablebmappermappedtable next need actual sql expression represents data interested this union results columns look columns defined first class id acode we could rename important part example abviewsel sqlalchemyaliasatableselectunionbtableselect finally map class it possible use declarative actually code way instead classic mapping style less notice class inherits object base class viewabobject pass sqlalchemyormmapperviewab abviewsel and pretty much of course limitations obvious trivial way save instances viewab back database,i sure called since new i want i two tables database tablea tableb tablea pk aid another field called acode tableb pk bid another field called bcode i tables mapped sqlalchemy code work fine i want create third object called tablec actually exist database contains combinations acode bcode something like class tablec acode string bcode string then i like query tablec like tablecqueryfilterand tablecacode x tablecbcode yall question does type thing name how i mapping using declarative would nice,1 test i like using timeit ipython in timeit str str loops best ns per loop in timeit str loops best ns per loop in timeit int loops best ns per loop apart though truly know input type much unless want make assumptions input data for example assume inputs equal type value could something like b stra strb equal which would faster normally type normally equal but slower normally type normally equal however sure cast everything strint enter code,what efficient way compare two python values probably strings might integers so far i using strxstry feels inefficient importantly ugly b c b true b c false i wanted true strbstrc true true desired my actual objects dictionary values retrieved get strings,2 wimwimacersandpit python mtimeit str str loops best usec per loop wimwimacersandpit python mtimeit int int loops best usec per loop wimwimacersandpit python mtimeit str str loops best usec per loop wimwimacersandpit python mtimeit int int loops best usec per loop conclusion probably already plenty fast enough optimise slowest parts program everything working,what efficient way compare two python values probably strings might integers so far i using strxstry feels inefficient importantly ugly b c b true b c false i wanted true strbstrc true true desired my actual objects dictionary values retrieved get strings,1 that invalid syntax you cannot concatenateformat strings unless strings quoted try addressstart r cltag xstreet addressend r prog recompileaddressstart r addressend result progmatchstring,i pulling hair trying parse craigslist rss feed extract location information i used feedparser parse script entries entry descriptions unfortunately address information contained irregular tags within description section addresses contained section looks like cltag xstreet se pl cltag xstreet cltag cityauburn cltag regionwa se pl feedparser like cltags my attempt capture first line regex looked like addressstart r cltag xstreet addressend r prog recompileaddressstartaddressend result progmatchstring but work what i wrong link rss feed i working httpseattlecraigslistorgseeapaindexrss any help greatly appreciated,1 try search instead match the reason line starts defined addressstart begin search finds match anywhere string match finds matches beginning alternatively could redefined addressstart contain leading import addressstart r cltag xstreet addressend r prog recompileaddressstart addressend string cltag xstreet se pl result researchprog string result sresrematch object xc resultgroup se pl,i pulling hair trying parse craigslist rss feed extract location information i used feedparser parse script entries entry descriptions unfortunately address information contained irregular tags within description section addresses contained section looks like cltag xstreet se pl cltag xstreet cltag cityauburn cltag regionwa se pl feedparser like cltags my attempt capture first line regex looked like addressstart r cltag xstreet addressend r prog recompileaddressstartaddressend result progmatchstring but work what i wrong link rss feed i working httpseattlecraigslistorgseeapaindexrss any help greatly appreciated,1 try using decimal module allow maintain exactly precision entered number eg import decimal def numinputs true try return decimaldecimalrawinputs except decimalinvalidoperation e print emessage validnum numinputenter decimal number print answer validnum see httpdocspythonorglibrarydecimalhtml,i trying get number cli input python valid input either int float i need maintain type so validating int returning float work this best thing i able come good def isvalidn try n return floatn return intn except valueerror print try def numinputs n rawinputs isvalidn none n rawinputs return isvalidn validnum numinputenter valid number clearly best way,1 the problem osfilestart exist you problably want osstartfile you also take look open document default application python how open file standard application recommend system open filepath mac system xdgopen filepath linux,i program help documentation pdf folder py module i need program open pdf system default pdf reader i using code program sysplatformstartswith darwin ossystemslannanhelppdf elif sysplatformstartswith linux ossystemslannanhelppdf elif sysplatformstartswith win osfilestartslannanhelppdf however run windows i get following error traceback recent call last file cusersusermousepaw gamesmousepaw labsslannanslannanpy line helpevent osfilestartslannanhelppdf attributeerror module object attribute filestart my guess osfilestart works nt systems windows is command works one works windows if latter i check see user running nt version windows thanks advance,2 as i understand question want write function interpolatexvalues yvalues x give value x the basic idea follows steps find indices values xvalues define interval containing x for instance x example lists containing interval would xx indices would calculate slope interval yvaluesiyvaluesixvaluesixvaluesi ie dydx the value x value x plus slope multiplied distance x you additionally need decide happens x outside interval xvalues either error could interpolate backwards assuming slope firstlast interval did help need specific advice,i fairly new programming thought i try writing linearinterpolation function say i given data follows x i want design function interpolate linearly using python i tried looking httpdocspythonorgtutorial i still unable get head around,3 you use xxxyyycomzzzcomreplacezzzcom if know always zzzcom otherwise could try data xxxyyycomzzzcom datacount data datarsplit or generally data xxxyyycomzzzcomcom datacount data datarsplit datacount you learn string methods i used python string methods,right i string form xxxyyycomzzzcom i want strip zzzcom comes xxxyyycom,2 string xxxyyycomzzzcom string joinstringsplit simple way job i think safe though,right i string form xxxyyycomzzzcom i want strip zzzcom comes xxxyyycom,1 when checking conditions numpy arrays i usually end using numpywhere condition arguments returns indices array numpywherer row indices column numpywherer r numpytakeri take slices r along axis v numpytakevi r numpytakeri v numpytakevi somewhat shorter use compress case combines larger r r numpycompresslargerr i know faster uses arrays intermediate lists edit might also want look masked arrays want operate r v directly,i two d numpy arrays real r contains points space given cartesian coordinates v complex vector defined points i would like split arrays based condition r eg r contains points first cartesian coordinate positive v gives corresponding values v all points corresponding vectors go based question fact zip essentially inverse i currently following solution r v ziprv rv zipr v rv r v ziprv rv zipr v rv r nparrayr r nparrayr v nparrayv v nparrayv this works well enough purposes however involves conversion large lists arrays surely quite inefficient is alternative solution fast concise avoids creation intermediate lists,1 xxxyyycomzzzcom rpartition xxxyyycom,right i string form xxxyyycomzzzcom i want strip zzzcom comes xxxyyycom,2 use bool array index filter values create random test data first import numpy np nprandomseed r nprandomrand v nprandomrand nprandomrandj idx r idx bool array r ridx v vidx r ridx idx compute bitwise not elementwise v vidx,i two d numpy arrays real r contains points space given cartesian coordinates v complex vector defined points i would like split arrays based condition r eg r contains points first cartesian coordinate positive v gives corresponding values v all points corresponding vectors go based question fact zip essentially inverse i currently following solution r v ziprv rv zipr v rv r v ziprv rv zipr v rv r nparrayr r nparrayr v nparrayv v nparrayv this works well enough purposes however involves conversion large lists arrays surely quite inefficient is alternative solution fast concise avoids creation intermediate lists,2 this code quite fragile it makes strong assumptions xml input would fail xml modified valid way eg immediately i suggest using standard library parsing xml element tree httpdocspythonorglibraryxmletreeelementtreehtml lxml httplxmlde also validate xml input the code i writing uses element tree works xml input i removed self arguments parent class it also tolerates ignores empty values xml elements import xmletreeelementtree et def getmapdata xmlfile result try tree etparse xmlfile except ioerror e print failure parsing xmlfile e root treegetroot root node child root childtag landmarkpointlistxml result looplandmarkchild elif childtext none result childtext return result def looplandmark landmarks result landmark landmarks landmarktag anytype check also xsitypelandmarkpointproperty child landmark childtext childtag landmarkpointx landmarkpointy result childtext return result getmapdata xmlin,given xml file would like extract data however trouble extracting data landmarkpointlistxml onwards the xml file xml version encodingutf map xmlnsxsihttpwwwworgxmlschemainstance xmlnsxsdhttpwwwworgxmlschema mapnameermapname mapurlergifmapurl nameername urlergifurl landmarkpointlistxml anytype xsitypelandmarkpointproperty landmarkpointxlandmarkpointx landmarkpointylandmarkpointy landmarkdescmy room doorlandmarkdesc anytype anytype xsitypelandmarkpointproperty landmarkpointxlandmarkpointx landmarkpointylandmarkpointy landmarkdescbro room doorlandmarkdesc anytype landmarkpointlistxml regionpointlistxml map python program def getmapdataself result haha selfxmldocfirstchild root node child hahachildnodes cmpchildnodename landmarkpointlistxml result result selflooplandmarkchildchildnodes else result result childfirstchildnodevalue return result def looplandmarkself landmarks result hahalandmarksgetelementsbytagname anytype child hahachildnodes cmphahafirstchildnodename landmarkpointx resultresultchildfirstchildnodevalue childnode childnodenextsibling resultresultchildfirstchildnodevalue childnode childnodenextsibling resultresultchildfirstchildnodevalue return result i able retrieve result erergiferergif till program reaches landmarkpointlistxml,1 while opencv open multiframe tiff files open image using pil pass data opencv i yet able get working new cv namespace tiff imageopen sampletif try convert pil image opencv image cvcreateimageheadertiffsize cvipldepthu cvsetdataimage tifftostring it tostring tostring do whatever going opencv data tiffseektifftell except eoferror pass,anyone know opencv capable loading multiframe tiff stack i using opencv python,3 thanks i written function def shakelist gets list reorders items one beginning one end print original list list newlist x lenlist lenlist xrangey listi newlist newlistappendlisti listix newlist newlistappendlistix x lenlist newlistappendlisty print new list newlist return newlist,i wondering standard library function python rearrange elements list like functiona print it get one element beginning original list one end second beginning then rearrange list regards,1 you importing stanford in order access stanfordtagger need use either nltktagstanford import stanfordtagger assuming stanfordtagger nested module access st stanfordstanfordtagger bidirectiondistsimwsjtagger,this probably trivial question i trying use stanford pos tagger nltk given the problem nltk lib doesnt contain stanford module so i copied appropriate folder compiled now try run example module getting detected class inside module can anyone tell i going wrong again probably dumb nltktag import stanford st stanfordtagger bidirectiondistsimwsjtagger i used pycompile compile stanfordpy file am missing something,2 yes pycurl bad api design curl powerful it futures urlliburllib maybe want try use humancurl it python curl wrapper you install sources httpsgithubcomlispythonhumancurl pip pip install humancurl example import humancurl hurl r hurlput httplocalhostopenrdfsesamerepositoriesrepstatements headers contenttype applicationrdfxmlcharsetutf files myfile open teardf r response also read response headers cookies etc,here bit code uploading file filesize ospathgetsize teardf f file teardf c pycurlcurl csetoptpycurlurl httplocalhostopenrdfsesamerepositoriesrepstatements csetoptpycurlhttpheader contenttype applicationrdfxmlcharsetutf csetoptpycurlput csetoptpycurlinfile f csetoptpycurlinfilesize filesize cperform cclose now i liking pycurl experience can suggest alternative maybe urllib httplib can write code showing huge thanks,2 i access envisage plugins documentation i sure installed in general need open windows preferences pydev interpreter python check package directory present system pythonpath window if add press apply if plugins installed standard location ie sitepackages another option remove current interpreter upper window press auto config,i installed envisagecore envisageplugin ubuntu i using eclipse sdk pydev plugin how i import plugin eclipse,1 thanks comments alexisdm varela found problem i something like class synoptique def initself w h selfview qgraphicsview selfscene synopscene initialization def opensynopbuapp fname w h synop synoptiquew h varexport additem synopadditem addcallback buappaddcallback exec openfname varexport synopviewshow name main app qapplicationsysargv buapp creation opensynopbuapp synoppy appexec but appears reference synop object containing qgraphicsview scene lost local variable opensynop function so references qgraphicsview scene objects scene lost one way handle declare synop instance outside function main call return save synop reference function this solved problem example def opensynopbuapp fname w h return synop name main opensynopbuapp synoppy appexec i understand i keep reference qgraphicsview scene order manipulate later qgraphicsitem inside scene wow obvious thanks,i simple program create qgraphicsscene view execute given file via exec statement python globals function export my aim define code scene new files helpers function already defined i also main program thread deliver callbacks want stuff qgraphicsitems callbacks the example define animation invisibility linked one callback pyside import qtgui definition animation invisibility class animinvisible def initself item selfitem item def oncallbackself tag selfitemsetvisibletaggetproperty creation simple qgraphicsrectitem monrect qtguiqgraphicsrectitem monrectsetbrushqtguiqbrushqtguiqcolor red add rect scene defined file exec statement done exported exec additemmonrect animinvisiblemonrect connect aoncallback changes thread exported exec addcallbackaoncallback systemcmdamg and works well but i put code animinvisible another module say animations i replace animations import animinvisible i got error saying internal c object pysideqtguiqgraphicsrectitem already deleted it really weird behavior i understand i also tried pyqt instead pyside i get behavior object deleted code animinvisible module problem file,1 there need implement anything qheaderview changed stylesheets like almost widgets edit you mentioned wanted change background color per column depending data easiest way probably derive new model qabstractitemmodel another model class reimplement headerdata call qvariant qabstractitemmodelheaderdata int section qtorientation orientation int role qtdisplayrole const virtual role want react qtbackgroundcolorrole function could look like qvariant variableheadermodelheaderdataint section qtorientation orientation int role qvariant result role qtbackgroundcolorrole result qcolor custom processing else result superclassheaderdatasection orientation role return result generally qt model decides show almost times change model view also data calls get called lot i know headerdata probably want cache results lot calculation going if using qstandarditemmodel probably call setheaderdatasection orientation acolor qtbackgroundcolorrole,i trying change background color certain header sections some use default coloring others get different color the headerview accept delegates like qtreeview painting it using two methods paintevent paintsection my initial attempt try override paintsection letting paint default stuff adding def paintsectionself painter rect logicalindex qheaderviewpaintsectionself painter rect logicalindex paintersave painterfillrectrect qbrushqtred painterrestore this appear anything it draw filled rect if i comment call base paintsection method draw filled rect consistently ie clicking resizing header causes fill sometimes others any help appreciated,1 i thought rather elegant solution imho i resist posting bisect import bisectleft class interpolateobject def initself xlist ylist anyy x x zipxlist xlist raise valueerrorxlist must strictly ascending order xlist selfxlist mapfloat xlist ylist selfylist mapfloat ylist intervals zipxlist xlist ylist ylist selfslopes yx x x x intervals def getitemself x bisectleftselfxlist x return selfylisti selfslopesi x selfxlisti i map float integer division python kick ruin things x x integers iterval in getitem i taking advantage fact selfxlist sorted ascending order using bisectleft quickly find index largest element smaller x selfxlist use class like interpolate get interpolated value x i dealt border conditions simplicity as ix x work line extended minus infinity ix x x raise indexerror better would raise indexerror cases left exercise reader,i fairly new programming thought i try writing linearinterpolation function say i given data follows x i want design function interpolate linearly using python i tried looking httpdocspythonorgtutorial i still unable get head around,3 do kind index notnull column example primary key if yes index scanned hopefully take long if full table scan way count rows,i single table sqlite db many rows i need get number rows total count items table i tried select count table seems access row super slow i also tried select maxrowid table that fast really safe ids reused table empty etc it hack any ideas find table size quickly cleanly using python sqlite version uses sqlite engine,1 try one recompilerpp means character means last token must repeated twice times regex means pp b matches word boundaries,i text file seqfasta contains sequence follows m mpmilgywnvrglthpirmlleytdssydekrytmgdapdfdrsqwlnekfklgldfpnl pylidgshkitqsnailrylarkhhldgeteeeriradivenqvmdtrmqlimlcynpdf ekqkpeflktipekmklyseflgkrpwfagdkvtyvdflaydildqyrmfepkcldafpn lrdflarfeglkkisaymkssryiatpifskmahwsnk i extract motif pxxp exactly characters xx characters i tried following code import infileopenseqfasta r outopenoutcsv w line infile line linestripn linestartswith nameline else motif recompilerbppb c linecount motif print ss namec outwrite ssn namec but finding motif,3 you use recompile rpwp recompile rpazp meta w means alphanumeric characters similar az,i text file seqfasta contains sequence follows m mpmilgywnvrglthpirmlleytdssydekrytmgdapdfdrsqwlnekfklgldfpnl pylidgshkitqsnailrylarkhhldgeteeeriradivenqvmdtrmqlimlcynpdf ekqkpeflktipekmklyseflgkrpwfagdkvtyvdflaydildqyrmfepkcldafpn lrdflarfeglkkisaymkssryiatpifskmahwsnk i extract motif pxxp exactly characters xx characters i tried following code import infileopenseqfasta r outopenoutcsv w line infile line linestripn linestartswith nameline else motif recompilerbppb c linecount motif print ss namec outwrite ssn namec but finding motif,2 of course there several ways first could work mdstdoutread would line separation then could operate file object mdstdout iterator but seems issue buffering e get results immediately and possibility call mdstdoutreadline repeatedly returns the third way preferred case i would suggest like f itermdstdoutreadline fc frstripn sysstdoutwriterchecked fc sysstdoutflush i also changed output text output che check done already if want rather really haveing every output captured separately switch point but makes complicated i think solution indication wanted there one must consider following points read blocks one read byte byte quite ugly there question output intermitting output,one function program checks mdsum hashfile def check print checking integrity status md subprocesspopenmdsum c hashfileshellfalse stdoutsubprocesspipe fopen openbasefile r f mdstdoutreadlines fc frstripn sysstdoutwriterchecking fc sysstdoutflush happens whole command first executed loop reads md using mdstdoutreadlines dynamic ie dont get output command executedis way get output command execution fixed using glglgl answer def check print checking integrity status md subprocesspopenmdsum c hashfileshellfalse stdoutsubprocesspipe fopen openbasefile r fc null f itermdstdoutreadline k fc fc frstripn failed fc print fc sysstdoutwriterchecking stri fc lenk lenfc sysstdoutflush,3 pycrypto pyk branch httpsgithubcomdlitzpycryptotreepyk,i writing program python needs encryption functions least aes rsa i found pycrypto seems work x versions is good tool available python i rather start translating program compatible python solution thank update mentioned pycrypto available pyk,1 other way get rows number table using trigger stores actual number rows table insert operation increment counter in way inserting new record little slower immediately get number rows,i single table sqlite db many rows i need get number rows total count items table i tried select count table seems access row super slow i also tried select maxrowid table that fast really safe ids reused table empty etc it hack any ideas find table size quickly cleanly using python sqlite version uses sqlite engine,1 i think need trailing forward slash i wsgi script apache i load django import os import sys syspathappend homedjangomofintrunk syspathappend homedjangomofintrunkmofin print sysstderr syspath osenviron djangosettingsmodule mofinsettings import djangocorehandlerswsgi application djangocorehandlerswsgiwsgihandler in case import os import sys osuname vivien syspathappend homewwwsitebuilderblacknightieweb osenviron djangosettingsmodule gibodevsettings elif osuname thingy syspathappend homewwwsitebuilderblacknightieweb osenviron djangosettingsmodule gibodevsettings else syspathappend homewwwsitebuilderblacknightieweb osenviron djangosettingsmodule gibosettings import djangocorehandlerswsgi application djangocorehandlerswsgiwsgihandler,i get wsgi import settings file project mofin the list errors apache error log follows modwsgi pid exception occurred within wsgi script varwwwwsgiscriptsdjangowsgi traceback recent call last file usrlibpythonsitepackagesdjangocorehandlerswsgipy line call selfloadmiddleware file usrlibpythonsitepackagesdjangocorehandlersbasepy line loadmiddleware middlewarepath settingsmiddlewareclasses file usrlibpythonsitepackagesdjangoconfinitpy line getattr selfimportsettings file usrlibpythonsitepackagesdjangoconfinitpy line importsettings selftarget settingssettingsmodule file usrlibpythonsitepackagesdjangoconfinitpy line init raise importerror could import settings is syspath does syntax errors selfsettingsmodule e importerror could import settings mofinsettings is syspath does syntax errors no module named mofinsettings i got hello world wsgi app listed httpcodegooglecompmodwsgiwikiquickconfigurationguide work fine the settingspy file loads fine python managepy runservershellsyncdbtest store application here wsgi file import os import sys syspathappend homedjangomofintrunk syspathappend homedjangomofintrunkmofin print sysstderr syspath osenviron djangosettingsmodule mofinsettings import djangocorehandlerswsgi application djangocorehandlerswsgiwsgihandler syspath printed error log usrlibpythonzip usrlibpython usrlibpythonplatlinux usrlibpythonlibtk usrlibpythonlibdynload usrlibpythonsitepackages usrlibpythonsitepackagesgtk homedjangomofintrunk homedjangomofintrunkmofin i open interactive shell managepy syspath homedjangomofintrunkmofin usrlibpythonzip usrlibpython usrlibpythonplatlinux usrlibpythonlibtk usrlibpythonlibdynload usrlibpythonsitepackages usrlibpythonsitepackagesgtk my django settings file looks like django settings mofin project debug true templatedebug debug admins dan xxxx xxxxyyyyyyyyyycom managers admins databaseengine mysql postgresqlpsycopg postgresql mysql sqlite oracle databasename mofin or path database file using sqlite databaseuser aaaaaa not used sqlite databasepassword bbbbbb not used sqlite databasehost set empty string localhost not used sqlite databaseport set empty string default not used sqlite local time zone installation choices found httpenwikipediaorgwikilistoftzzonesbyname although choices may available operating systems if running windows environment must set system time zone timezone europelondon language code installation all choices found httpwwwinguycomunicodelanguageidentifiershtml languagecode engb siteid if set false django make optimizations load internationalization machinery usein true absolute path directory holds media example homemediamedialawrencecom mediaroot homedjangomedia url handles media served mediaroot make sure use trailing slash path component optional cases examples httpmedialawrencecom httpexamplecommedia mediaurl httpmofinmywebsitecoukmedia url prefix admin media css javascript images make sure use trailing slash examples httpfoocommedia media adminmediaprefix adminmedia make unique share anybody secretkey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx list callables know import templates various sources templateloaders djangotemplateloadersfilesystemloadtemplatesource djangotemplateloadersappdirectoriesloadtemplatesource djangotemplateloaderseggsloadtemplatesource middlewareclasses djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangocontribauthmiddlewareauthenticationmiddleware rooturlconf mofinurls templatedirs put strings like homehtmldjangotemplates cwwwdjangotemplates always use forward slashes even windows don forget use absolute paths relative paths installedapps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribadmin mofinstore,3 after posting comment referring pyparsing invregex example i looked little closer input looked like could interpret infix notation binary operators pyparsing helper method awkwardly named operatorprecedence parses expressions according precedence operators grouping parentheses this little smarts using nestedexpr helper method matches expressions nested within grouping symbols so gettingstarted version parser using operatorprecedence data abcd abcd abcdefghisplitlines pyparsing import alphas oneof operatorprecedence opassoc node oneoflistalphas graphexpr operatorprecedencenode opassocleft opassocleft data print graphexprparsestringdaslist pyparsing actually returns complex structure type parseresults supports access parsed tokens elements list items dict attributes object by calling aslist get elements simple list form the output shows look right track a b c d a b c d a b c d e f g h i pyparsing also allows attach callbacks parse actions individual expressions called parse time for instance parse action parsetime conversion integer def tointtokens return inttokens integer wordnumssetparseactiontoint when value returned parseresults already converted integer classes also specified parse actions parseresults object passed class init method resulting object returned we specify parse actions within operatorprecedence adding parse action th element operator descriptor tuple here base class binary operators class binopobject def initself tokens selftokens tokens def strself return selfclassname strselftokens repr str from base class derive subclasses one operator class pathbinop pass class branchbinop pass and add operator definition tuples operatorprecedence node oneoflistalphas graphexpr operatorprecedencenode opassocleft path opassocleft branch data print graphexprparsestringdaslist this gives us nested structure objects input string pathbranch a b c d path a b branch c d path a branch b c path d branch e f g h i the generation paths structure left exercise op the pyparsing regex inverter using tangle generators hopefully simple recursion sufficient,i attempting use python alter text strings using module ie resub however i think question applicable languages regex implementations i number strings represent treelike data structures they look something like abcd abcd abcdefghi each letter represents branch edge letters parentheses represent branches coming another branch everywhere plain tuple values tuple comma separated single letter i would like take prefix x suffix x tuple apply values tuple under transformation strings would become acbcd abcbd abcdedfdgdhdi applying methodology repeatedly would ultimately yield acdbcd abcabd abacadeadfadgadhadi the strings tuples represent paths tree starting root ending leaf any help accomplishing task using regular expressions approaches would greatly appreciated,1 there also httpsgithubcommopidypyspotify actively used applications date,i building app needs get artwork information libspotify spotify api i building app python google appengine does anyone know package enable access libspotify api the official page c i googled around try find suitable wrapper seem find one thanks tom,2 if use python projects python others change environment variable change projects or startup script look like import sys sysversioninfo import startup else import startup split real startup code startuppy startuppy,i finally started using python alongside python linux i setup python shell using startupscript defined pythonstartup due incompatibilities i unable use script versions what easiest way get one script python another python,3 set pythonstartup point script like checks version python used delegates another startup script import sys sysversioninfo startupk import elif sysversioninfo startupk import else loggingwarn unsupported version python pass,i finally started using python alongside python linux i setup python shell using startupscript defined pythonstartup due incompatibilities i unable use script versions what easiest way get one script python another python,3 ok i answer i found way access method registercomposite psycopg sqlalchemy core api but able register new type via psycopg methods newtype registeradapter tutorial found this methods allows register mapping sql representation python class way from sqlalechemy connection access methods like sqlalchemy import e createenginepostgresqlxxxxxxlocalhostdb c econnect cdialectdbapiextensionsregisteradapter cdialectdbapiextensionsnewtype,possible somehow use function registercomposite psycopg using sqlalchemy connect postgresql database my problem i want sqlalchemy handle custom composite type created postgresql like create type card as value int suit text sqlalchemy returns values type string i would like somhow learn sqlalchemy new type if found information creating custom composite types sql alchemy orm i using sqlalechemy core api orm somebody sqlalchemy irc told psycopg i would happy advice would solve thank josh,2 remove listfilterlambda x x n list,i list contains item n i want remove however remove command working can anyone tell i wrong def main list nggngggn n nsnssn nddndnddddnn print list print listremove n name main main also list contain many entries n i remove i currently use set get duplicates trying get remove command work however set command seems change sorting list i rather iterate list incase n found remove,3 define alias one python versions in alias reset pythonstartup appropriate python version alias py pythonstartuppathtostartuppy otherpathtopython,i finally started using python alongside python linux i setup python shell using startupscript defined pythonstartup due incompatibilities i unable use script versions what easiest way get one script python another python,1 compile python distribute binaries sensible idea use cython something similar compile python c code distribute app python binary libraries pyd instead that way python byte code left done reasonable amount obscurification anyone ie employer could expect regular code i think net java less safe case bytecode obfuscated relatively easily decompiled reasonable source cython getting compatible cpython i think work i actually considering product we already building thirdparty libs pyddlls shipping python code binaries overly big step us see this blog post tutorial thx hithwen crazy idea you could probably get cython store cfiles separately module concatenate build heavy inlining that way python module pretty monolithic difficult chip common tools beyond crazy you might able build single executable link optimize python runtime libraries dlls statically that way sure difficult intercept calls tofrom python whatever framework libraries use this cannot done using lgpl code though,i developing piece software python distributed employer customers my employer wants limit usage software time restricted license file if distribute py files even pyc files easy decompile remove code checks license file another aspect employer want code read customers fearing code may stolen least novel ideas is good way handle problem preferably offtheshelf solution the software run linux systems i think pyexe trick,3 removing stuff list one many uses list comprehensions non x x list x n change original list list non,i list contains item n i want remove however remove command working can anyone tell i wrong def main list nggngggn n nsnssn nddndnddddnn print list print listremove n name main main also list contain many entries n i remove i currently use set get duplicates trying get remove command work however set command seems change sorting list i rather iterate list incase n found remove,2 the remove method modifies list inplace returns none thus use print listremove n list modified none printed do two steps instead listremove n print list to remove occurrences natural would construct new list excluding newlines for example list list n if must inplace reason repeatedly use listremove exception raised true try listremove n except valueerror break,i list contains item n i want remove however remove command working can anyone tell i wrong def main list nggngggn n nsnssn nddndnddddnn print list print listremove n name main main also list contain many entries n i remove i currently use set get duplicates trying get remove command work however set command seems change sorting list i rather iterate list incase n found remove,3 to compute endofthecurrentmonth date take first current month add month subtract day for example september end september month october october day september,i use datetime delta datetimedatetoday datetimetimedeltadays datetimetimedeltaisoformat i need replace day end month how,3 libglade separate library it since deprecated functionnalities integrated gtk uses gtk builder format bit different both formats allow almost things gtkbuilder one prefered,i using glade interface designer developing simple application i actually following tutorial based libglade format but i want use gtkbuilder format so i switched gtkbuilder format but i want know exact difference libglade format gtkbuilder format thanks advance,1 seems pylint execution exit nonzero status missing script bad options maybe exit script exception raised sysexitsomethingelsethanzero,i added build step execute python script in script pylint called lintrunargs check code the script works end build fails error message build step execute python script marked build failure someone idea happens,1 pylint unpleasant behavior return nonzero exit code even small warning issue found only everything fine returned see man page as usually nonzero code denotes error jenkins fails build i see two ways overcome use small script around pylint always returns then jenkins fail pylint i use small python script calling pylint ossystem sysexit you see overriding error code pylint patch pylint for example linux system sysexit call file usrlibpymodulespythonpylintlintpy,i added build step execute python script in script pylint called lintrunargs check code the script works end build fails error message build step execute python script marked build failure someone idea happens,3 you get exception taskalreadyexistserror already task queue url params so worry queue remember catch exceptions you find full list exceptions httpcodegooglecomintlenappenginedocspythontaskqueueexceptionshtml,i often models local copy remote resource needs periodically kept sync task urlkeepinsync params entityid entityid namesyncs entityid countdown add inside keepinsync changes saved model new task scheduled happen later now superficially seems like nice solution practice might become worried necessary tasks really added maybe entities representing level food pellets inside hamster cages automated email sent housekeeper feed but weeks later come back holiday find several hamsters starving it starts seeming like good idea make script goes entity makes sure proper task really queue but neither task queue classes method checking task exists can save hamsters come nicer way make sure method really sure periodically called entity update it seems want really sure tasks scheduled need keep track tasks nick johnson suggests not ready let go convenient task queue time tolerate uncertainty unable check tasks really scheduled,1 use nodependencies nodeps option pip install nodependencies r requirementstxt,i would like install python packages local directories downloaded github specified requirementstxt e srcdjangodjangoeca e srcdiviodjangoappmediab e srcojiidjangosekizaicf e srcojiidjangoclassytagsff e srctheatlanticdjangosouthbb e srcetianendjangoreversionbdbee e srcdjangompttdjangompttde e srcjezdezdjangoappconfcde e srcjezdezdjangocompressorc e srcmongodbmongopythondriverfcbee e srcdiviodjangocmsfbff pil wsgiref however pip installs packages local directories pip install r requirementstxt also installs remote repos djangocms dependencies versions how avoid,3 the answer similar is bounding box function slice nonzero values ndarray numpy numpy import array argwhere a array b argwherea ystart xstart ystop xstop bmin bmax,i d numpy array lets consider following example we need coordinates box around certain value for example value coordinates box around value upper left lower right how efficiently python thanks lot,2 you could head request check question info if get status code ok could check content type well,how i check file http exists using pythondjango i try check file httphostnamedirectoryfilejpg exist,3 try urlliburlopen import urllib ret urlliburlopen httphostnamedirectoryfilejpg retcode print exists note check file exists check resource exists edit the answer user geo better head request much efficient fetch resource content,how i check file http exists using pythondjango i try check file httphostnamedirectoryfilejpg exist,3 why using arrays do mean lists using lists append lists objects anything lists,i want store bunch arrays future use i python i usually use append method element storage work arrays thanks,1 floating point numbers infinite precision converting long give perfectly accurate results the difference seeing difference floating point representation gamma actual integer value,i function facn return n i comparing gamman math import gamma gammafac mathfloorgammafac longgammafac l gamma integer results different,1 this library seems example main page printinfovs httpcodegooglecompffvideo it wrapper around ffmpeg seems python libraries using ffmpeg,is way python get dimensions video file library would accomplish the equivalent media info something thank,2 reinstalling configobj source fixed problem damn i know,i python app works fine now i use pyexe create windows executable app however resulting exe fails complain lacks configobj module traceback recent call last file filepy line module file filepyc line module importerror no module named configobj line filepy merely configobj import configobj i tried explicitly add configobj list packed modules specifying configobj argument pyexe run fails similar error running pyexe creating cpathtoprojdist generate typelib stubs collected stubs type libraries searching required modules traceback recent call last file cpathtoprojpyexesetuppy line module options pyexe typelibs c file cpythonlibdistutilscorepy line setup distruncommands file cpythonlibdistutilsdistpy line runcommands selfruncommandcmd file cpythonlibdistutilsdistpy line runcommand cmdobjrun file cpythonlibsitepackagespyexebuildexepy line run selfrun file cpythonlibsitepackagespyexebuildexepy line run selffindneededmodulesmf requiredfiles requiredmodules file cpythonlibsitepackagespyexebuildexepy line findneededmodules mfimporthookmod file cpythonlibsitepackagespyexemfpy line importhook return baseimporthookselfnamecallerfromlistlevel file cpythonlibsitepackagespyexemfpy line importhook q tail selffindheadpackageparent name file cpythonlibsitepackagespyexemfpy line findheadpackage raise importerror no module named qname importerror no module named configobj the configobj module installed computer default location python r mar msc v bit intel win type help copyright credits license information import configobj print configobjversion import pyexe cpythonlibsitepackagespyexebuildexepy deprecationwarning sets module deprecated import sets print pyexeversion what i wrong,1 in last company similar problem i find python library so i ended using mediainfo python media info also command line option easy parse output practically python module uses mediainfo sufficient it advantage eventually find mediainfo type software support codecsformat use multiple softwarelibs hood single python wrapper,is way python get dimensions video file library would accomplish the equivalent media info something thank,2 the results different limited precision floating point type way subtraction operator coerces operands type the gamma function returns float cannot return accurate answer numbers large this page gives good description issues in gammafac fac term converted float subtraction operation gamma e floatfac e the significant part fac fits float matches gamma subtraction results for second test gamma fractional part mathfloor effect mathfloorgamma gamma true when convert gamma long clearly see inaccurate longgamma l fac l,i function facn return n i comparing gamman math import gamma gammafac mathfloorgammafac longgammafac l gamma integer results different,3 in scrapy i solved something like class myimagespipelineimagespipeline name download version def imagekeyself url imageguid urlsplit return fullsjpg imageguid name thumbnail version def thumbkeyself url thumbid imageguid thumbid urlsplit return thumbsssjpg thumbid imageguid def getmediarequestsself item info yield requestitem images,for scrapy project i currently using imagespipeline the downloaded images stored sha hash urls file names how i store files using custom file names instead what custom file name needs contain another scraped field item eg use item desc filename image item imageurl if i understand correctly would involve somehow accessing item fields image pipeline any help appreciated,3 import datetime datetimedate lastday datetimedatedyear dmonth datetimetimedelta,i use datetime delta datetimedatetoday datetimetimedeltadays datetimetimedeltaisoformat i need replace day end month how,2 solution since hidden comment you need use use include registrationurls instead include registrationbackendsdefaulturls,so i installed djangoregistration easyinstall i following quick start guide i trying setup urlconf however says module named backendsdefaulsurls found what might problem import registration r accounts include registrationbackendsdefaulturls,3 death doc string roomdeath print roomdoc prints none following ifelifs return function runnner results programs end your program work add missing doc string replace return death runner simple pass ommitting corresponding elif clause,working way lpthw stuck extra credit exercise extra credit add cheat codes game get past difficult rooms instead function print learn “doc string” style comments write room description doc comments change runner print once doc comments room description need function prompt even have runner prompt user pass function your functions ifstatements printing result returning next room as i understand far using docstrings like frowned upon i come sys import exit random import randint globvar def death quips you died you kinda suck nice job died jackass such loser i small puppy better print quipsrandint lenquips exit def centralcorridor the gothons planet percal invaded ship destroyed entire crew you last surviving member last mission get neutron destruct bomb weapons armory put bridge blow ship getting escape pod you running central corridor weapons armory gothon jumps red scaly skin dark grimy teeth evil clown costume flowing around hate filled body he blocking door armory pull weapon blast action globvar action shoot print quick draw yank blaster fire gothon print his clown costume flowing moving around body throws print aim your laser hits costume misses entirely this print completely ruins brand new costume mother bought print makes fly insane rage blast repeatedly face print dead then eats return death elif action dodge print like world class boxer dodge weave slip slide right print gothon blaster cranks laser past head print in middle artful dodge foot slips print bang head metal wall pass print you wake shortly die gothon stomps print head eats return death elif action tell joke print lucky made learn gothon insults academy print you tell one gothon joke know print lbhe zbgure vf fb sng jura fur fvgf nebhaq gur ubhfr fur fvgf nebhaq gur ubhfr print the gothon stops tries laugh busts laughing move print while laughing run shoot square head print putting jump weapon armory door return laserweaponarmory else print does not compute return centralcorridor def laserweaponarmory you dive roll weapon armory crouch scan room gothons might hiding it dead quiet quiet you stand run far side room find neutron bomb container there keypad lock box need code get bomb if get code wrong times lock closes forever get bomb the code digits code ddd randint randint randint guess globvar guesses cheat guess code guess cheat guesses print bzzzzeddd guesses guess rawinputkeypad guess code print the container clicks open seal breaks letting gas print you grab neutron bomb run fast print bridge must place right spot return thebridge elif guess cheat print the container clicks open seal breaks letting gas print you grab neutron bomb run fast print bridge must place right spot return thebridge else print the lock buzzes one last time hear sickening print melting sound mechanism fused together print you decide sit finally gothons blow print ship ship die return death def thebridge you burst onto bridge netron destruct bomb arm surprise gothons trying take control ship each even uglier clown costume last they pulled weapons yet see active bomb arm want set action globvar action throw bomb print in panic throw bomb group gothons print make leap door right drop print gothon shoots right back killing print as die see another gothon frantically try disarm print bomb you die knowing probably blow print goes return death elif action slowly place bomb print you point blaster bomb arm print gothons put hands start sweat print you inch backward door open carefully print place bomb floor pointing blaster print you jump back door punch close button print blast lock gothons get print now bomb placed run escape pod print get tin return escapepod else print does not compute return thebridge def escapepod you rush ship desperately trying make escape pod whole ship explodes it seems like hardly gothons ship run clear interference you get chamber escape pods need pick one take some could damaged time look there pods one take goodpod randint guess globvar greatpod intguess goodpod print you jump pod hit eject button guess print the pod easily slides space heading print planet as flies planet look print back see ship implode explode like print bright star taking gothon ship print time you exit elif intguess greatpod print you jump pod hit eject button guess print the pod easily slides space heading print planet as flies planet look print back see ship implode explode like print bright star taking gothon ship print time you exit else print you jump pod hit eject button guess print the pod escapes void space print implodes hull ruptures crushing body print jam jelly return death rooms death death centralcorridor centralcorridor laserweaponarmory laserweaponarmory thebridge thebridge escapepod escapepod def runnerthemap start next start true global variable order pass prompt value rooms global globvar room themapnext print n print roomdoc room dependent prompts room laserweaponarmory prompt rawinputkeypad elif room escapepod prompt rawinputpod elif room death return death else prompt rawinput set rawinput prompt global variable globvar globvar prompt next room runnerrooms centralcorridor everything runs fine except return death it exits printing following none in runner function near bottom i thought adding elif room death bit would work without hangs waiting rawinput prints random quip i press enter can someone help understand i missing any help appreciated edit thanks lighting quick feedback i got though rocksportrocker solution simpler def runnerthemap start next start true global variable order pass prompt value rooms global globvar room themapnext room dependent prompts room laserweaponarmory print n print roomdoc prompt rawinputkeypad elif room escapepod print n print roomdoc prompt rawinputpod elif room thebridge print n print roomdoc prompt rawinput elif room centralcorridor print n print roomdoc prompt rawinput else pass set rawinput prompt global variable globvar globvar prompt next room,2 i think give idea trying hope helps,i currently planning access mfc dialog based application dll file using python i new python latest version python installed ie i installed pythonwin well really sure would useful i understood like basics using python help ctypes in dll file i two functions double boxareadouble l double h double w double boxvolumedouble l double h double w i used extern dllimport command access mfc dialog application extern c declspecdllexportvoid boxpropertiesdouble length double height double width doubleamp area doubleamp volume all works fine trying access another mfc program now i trying access two functions using python could anyone suggest i go commands would directly let access many thanks advance,1 i problem turned pylint configuration file pylintrc default be sure outputformat field correct it reports section line outputformattext if ever used pylint another application i emacs might say outputformatparseable,i pylint installed works fine command line set within pydev eclipse pylint triggered ok i edit files outputting eclipse console but pylint warnings appear marks editor margin way compiler warnings errors newlygenerated warnings appear problems view either old ones showing disappear i resave relevant module i know possible i working previously i set ticking unticking redirect pylint output console seem make difference,1 try eval maplambda x selfself selfvarx the odd selfself create copy self outer context inner context body lambda expression,here simple code illustrating essence problem class test def initself selfvar def setself val selfvar val print eval maplambda x selfvarx f test fset it says nameerror global name self defined i know many people like eval case i use executes math formula string entered user programm execution any suggestions highly appreciated thanks advance,3 while i sure way without eval tried using string formatting eval maplambda x sx selfvar,here simple code illustrating essence problem class test def initself selfvar def setself val selfvar val print eval maplambda x selfvarx f test fset it says nameerror global name self defined i know many people like eval case i use executes math formula string entered user programm execution any suggestions highly appreciated thanks advance,1 mfc library platform it going depend certain assumptions proper initialization done program startup mfc message pump called periodically among others those assumptions met python impractical make work properly it possible program dll uses mfc internally completely selfcontained i guessing see httpmsdnmicrosoftcomenuslibraryctxvvsaspx,i currently planning access mfc dialog based application dll file using python i new python latest version python installed ie i installed pythonwin well really sure would useful i understood like basics using python help ctypes in dll file i two functions double boxareadouble l double h double w double boxvolumedouble l double h double w i used extern dllimport command access mfc dialog application extern c declspecdllexportvoid boxpropertiesdouble length double height double width doubleamp area doubleamp volume all works fine trying access another mfc program now i trying access two functions using python could anyone suggest i go commands would directly let access many thanks advance,1 this tricky situation first workaround use class test def initself selfvar def setself val selfvar val print eval maplambda xselfself selfvarx f test fset the reason simple explain let try when write lambda x selfvar x created closure capture current variable self nonlocal variable lambda expression self local variable current environment when lambda built eval however local variable self visible inside eval therefore lambda function generated refer global variable self exist case,here simple code illustrating essence problem class test def initself selfvar def setself val selfvar val print eval maplambda x selfvarx f test fset it says nameerror global name self defined i know many people like eval case i use executes math formula string entered user programm execution any suggestions highly appreciated thanks advance,3 eval also supports setting global local variables respectively could something like class test def initself selfvar def setself val selfvar val print eval maplambda x selfvarx dictglobalsitems self self f test fset update the example maintains previous global local variables,here simple code illustrating essence problem class test def initself selfvar def setself val selfvar val print eval maplambda x selfvarx f test fset it says nameerror global name self defined i know many people like eval case i use executes math formula string entered user programm execution any suggestions highly appreciated thanks advance,3 use operatoritemgetterba the function call means unpack value use elements arguments function,i integer list used indices another list retrieve value lets say following array we get specific elements using following code import operator operatoritemgettera it return nd rd th item lets say another list b but i try run following code gets error operatoritemgetterba i wondering someone could help please i think problem i convert b comma seprated indices butnot sure thanks lot,3 since tagged question numpy tag could also consider making array works numpy import array array b ab,i integer list used indices another list retrieve value lets say following array we get specific elements using following code import operator operatoritemgettera it return nd rd th item lets say another list b but i try run following code gets error operatoritemgetterba i wondering someone could help please i think problem i convert b comma seprated indices butnot sure thanks lot,2 the wxpython demo example shows done gridstdedrendpy file within demo see editors renderers demo part grid demo what looking gridcellchoiceeditor see also httpwikiwxpythonorggridcellchoiceeditor,i find good information place combobox inside cell wxgrid i tried google maybe i blind anyone simple sample share,1 take look gridchoicecelleditor you use follows choiceeditor wxgridgridcellchoiceeditorchoiceslist true gridsetcelleditorrow col choiceeditor,i find good information place combobox inside cell wxgrid i tried google maybe i blind anyone simple sample share,2 you parse c regex wt testing strings n comments printf haha gotcha epic stuff text typedef test val string typedef test val commentstring but want quick hack parse typedefs typedefsenums,for certain project mine i need parse enum typedefs h file for example lets take next simple case typedef enum data aaagege data data esample this simple declaration without assigns anything bit complex yet regular expression i wrote seems poor performance wise here expression typedefsenumsswnsws i tested expression one files lines code took ages the first thing i tried make everything possible greedy like typedefsenumsswnsws but made things worse any suggestions i make better performance wise if could add explanation suggested solution better mine it help lot thanks advance kfir,1 just use subset data contains points periods i assuming talking financial data interested rangelenx ilenx slope intercept rvalue pvalue stderr statslinregressxiiyii ilenx slope intercept rvalue pvalue stderr statslinregressxiiyii this efficient approach btw want slopes easy,if i array elements would i calculate period slope period slope the docs dont add much scipy import stats import numpy np x nprandomrandom nprandomrandom slope intercept rvalue pvalue stderr statslinregressxy would work def slopex n ilenxn slope statslinregressxiinyiin return slope would arrays length joe xx x npasarrayxx npfloat npdiffx window window slope npconvolvex window mode lenwindow slope npconvolvex window mode lenwindow print x print print slope print slope results the slope slope im except arent results i looking worked window slope npconvolvexx window mode valid floatlenwindow padlength lenwindow slope nphstacknponespadlength slope print slope,2 i assuming mean slope calculated every rd th element series exact leastsquares slopes if something along lines thirdperiodslope npdiffy npdiffx fifthperiodslope npdiffy npdiffx i probably entirely misunderstanding mean though i never head term period slope if want moving window calculation number input elements output elements model convolution window eg window slope npconvolvey window mode npconvolvex window mode,if i array elements would i calculate period slope period slope the docs dont add much scipy import stats import numpy np x nprandomrandom nprandomrandom slope intercept rvalue pvalue stderr statslinregressxy would work def slopex n ilenxn slope statslinregressxiinyiin return slope would arrays length joe xx x npasarrayxx npfloat npdiffx window window slope npconvolvex window mode lenwindow slope npconvolvex window mode lenwindow print x print print slope print slope results the slope slope im except arent results i looking worked window slope npconvolvexx window mode valid floatlenwindow padlength lenwindow slope nphstacknponespadlength slope print slope,3 run cmdexe prompt tasklist fi imagename eq dymopnpserviceexe v check user name if nt authoritysystem probably intentionally allowing even administrator account get cpu times etc proc grab copy process explorer find path process check security tab preferences right click menu option to fix may able edit owner permissions dymopnpserviceexe executable could cause unexpected issues windows you also continue loop process allow get details import psutil def process plist psutilgetprocesslist plist sortedplist keylambda iname plist try print iname igetcpupercent except accessdenied print process allowing us view cpu usage iname def main process main,os windows professional trying use psutil get list processes cpu usage ran script administrator fails encounters process dymopnpserviceexe could issue import psutil def process plist psutilgetprocesslist plist sortedplist keylambda iname plist print iname igetcpupercent def main process main acrordexe acrordexe dymopnpserviceexe traceback recent call last file cuserskrisdigitxdocumentswindowsutilpy line module main file cuserskrisdigitxdocumentswindowsutilpy line main process file cuserskrisdigitxdocumentswindowsutilpy line process print iname igetcpupercent file cpythonlibsitepackagespsutilinitpy line getcpupercent pt selfplatformimplgetcputimes file cpythonlibsitepackagespsutilpsmswindowspy line wrapper raise accessdeniedselfpid selfprocessname accessdenied pid name dymopnpserviceexe research strange run program windows command promptbut fails python ide,3 the first thing i tried make everything possible gready but made things worse of course how look regex ws it greedily eat word characters look space character now consider ws this eats one word character checks space failing eats another word character checks space it checks every word character see space generally nongreedy slower greedy check characters twice sometimes nongreedy produces different results always use greedy in fact perl possessive quantifiers ws which means greedy fails match bother giving characters back greedy the example works fine may optimizable really understand wh that example always fail h character end word get permanently eaten w whereas w get eaten given back match failed see would succeed unfortunately python possessive form knowledge though comments tchrist suggests alterative python regex library first example fast i suspect get you might also find speedup searching occurrences string enum working instead using single giant regex search entire file,for certain project mine i need parse enum typedefs h file for example lets take next simple case typedef enum data aaagege data data esample this simple declaration without assigns anything bit complex yet regular expression i wrote seems poor performance wise here expression typedefsenumsswnsws i tested expression one files lines code took ages the first thing i tried make everything possible greedy like typedefsenumsswnsws but made things worse any suggestions i make better performance wise if could add explanation suggested solution better mine it help lot thanks advance kfir,1 the reason slow nested repeats marked swn this causes nested backtracking leads exponential running times but larger problem putting group inside repeat means last match group kept print mgroups data esample,for certain project mine i need parse enum typedefs h file for example lets take next simple case typedef enum data aaagege data data esample this simple declaration without assigns anything bit complex yet regular expression i wrote seems poor performance wise here expression typedefsenumsswnsws i tested expression one files lines code took ages the first thing i tried make everything possible greedy like typedefsenumsswnsws but made things worse any suggestions i make better performance wise if could add explanation suggested solution better mine it help lot thanks advance kfir,2 there tool standard library tasks to iterate csv files directory use glob module import glob csvfilename globglobrcmydirectorycsv dosomething to parse csv file use csv module import csv opencsvfilename rb csvfile reader csvreadercsvfile delimiter row reader row list entries current row to parse date calculate difference use datetime module datetime import datetime startdate datetimestrptime ymd enddate datetimestrptime ymd delta enddate startdate difference days to add value beginning row row strdelta to append filename end row rowappendcsvfilename and write row new csv file opencsvfilename wb csvfile writer csvwritercsvfile delimiter writerwriterowrow taken together get import glob import csv datetime import datetime opencombinedfilescsv wb outfile writer csvwriteroutfile delimiter csvfilename globglobrcmydirectorycsv opencsvfilename rb infile reader csvreaderinfile delimiter row reader startdate datetimestrptimerow ymd enddate datetimestrptimerow ymd delta enddate startdate difference days row strdelta rowappendcsvfilename writerwriterowrow,i csv files i operate month i trying wrap head around i running wall i starting understand things python combining several things still giving issues i figure here problem i many csv files i need done add column front row back matter really front ideal in addition line rows counting filename added format digit id numberyyyymmddyyyymmddyyyymmdddigit number i need subtract yyyymmdd yyyymmdd every line file header row every csv given directory i need filename inside row i combine files included script would awesome i think i figure part i need know file records came format filename always digitnumbercsv i hope makes sense please let know i kind stumped even begin i sample code even really began work really frustrated i appreciate help guys may provide site rocks mylan,3 in print f val val l l list edit if quotes issue could use in print join f v v l,i list floating point number named when i print list print i get result follows can i tell list printer print format f get better result,3 if need work nested structures look pprint module the following want context pprint import prettyprinter class myprettyprinterprettyprinter def formatself object context maxlevels level isinstanceobject float return f object true false else return prettyprinterformatself object context maxlevels level print myprettyprinterpprint displays for details pprint see httpdocspythonorglibrarypprinthtml if flat list aix solution good or like extra quotes could print join f val val list,i list floating point number named when i print list print i get result follows can i tell list printer print format f get better result,3 the operation independent size container ie o given optimal hash function this nearly true python strings hashing strings always critical python clever thus expect nearoptimal results,what time complexity python set operations big o notation i using python set type operation large number items i want know operation performance affected size set for example add test membership myset set mysetadd foo foo myset googling around turned resources seems reasonable time complexity python set implementation would carefully considered if exists link something like would great if nothing like perhaps work extra marks finding time complexity set operations,2 you typically need supply login data sending email smtp if i i experiment code given answer linked try company smtp server,i python script runs ubuntu processes content mysql database i want informed script runs unhandled exception done processing what appropriate way make happen i thought sending email within python using method shown soanswer able i hardcode logindata i comfortable script runs public server within company any suggestions bypass make happen using appropriate way,1 here exception handler i wrote use emails exception script dies set sysexcepthook excepthook import os import sys import traceback import import smtplib import getpass def excepthooketype value tb formats traceback exception data emails error ampampampampampcom arguments etype exception class type value exception string value tb traceback string data exctype resub typeclass exceptions main stretypestrip email to com from getpassgetuser blizzardcom subject exception body snn exctype etypedoc line tracebackextracttbtb email body tfile sntts sn line line line line tbtbnext break tb tbtbnext stack f tbtbframe f stackappendf f ffback stackreverse email body nlocals frame innermost last frame stack email body nframe line framefcodeconame framefcodecofilename frameflineno key val frameflocalsitems email body nts key try email body strval except email body error while printing value thishost socketgethostname thisip socketgethostbynamethishost gmtime timegmtime logname sometoolvssssssssslog version thishost thisip gmtimetmmon gmtimetmmday gmtimetmyear gmtimetmhour gmtimetmmin gmtimetmsec ospathexistslogsdir try osmkdirlogsdir except baselogdir ospathjoinnetdir logs ospathexistsbaselogdir try osmkdirbaselogdir except pass else openospathjoinbaselogdir logname w writeemail body else openospathjoinlogsdir logname w writeemail body email all from snto snsubject snns email from email to email subject email body server smtplibsmtpmysmtp serversendmailemail from email to email all serverquit name main sysexcepthook excepthook try except sysexit,i python script runs ubuntu processes content mysql database i want informed script runs unhandled exception done processing what appropriate way make happen i thought sending email within python using method shown soanswer able i hardcode logindata i comfortable script runs public server within company any suggestions bypass make happen using appropriate way,1 b cdefrsplit b cde f,i would like know built function python break string parts based last occurrence separator eg consider string b cdef split separator want output b cde f i know manipulate string get desired output want know built function python,3 use rpartitions it exactly you also use rsplits,i would like know built function python break string parts based last occurrence separator eg consider string b cdef split separator want output b cde f i know manipulate string get desired output want know built function python,3 rsplit b cdefrsplit b cde f,i would like know built function python break string parts based last occurrence separator eg consider string b cdef split separator want output b cde f i know manipulate string get desired output want know built function python,3 you using open os module takes numeric file mode you want instead builtin open function also backslashes strings take special meaning python need double really mean backslashes try fin open cfoldertesttxt r,i need delete numbers text file windows xp i new python installed data scrubbing i stored test file cfoldertesttxt the contexts testtxt line this must b deletd number end yes i want created file resulttxt contains this must b deletd number end yes here i tried far import os fin osopen cfoldertesttxt r i get following error typeerror integer required i sure integer expecting can please let know go programming get result i want thanks lot help,3 according httpdocspythonorglibraryoshtmlfiledescriptoroperations osopen looking flag parameter made one flags r it also seems indicate probably want look using open rather osopen,i need delete numbers text file windows xp i new python installed data scrubbing i stored test file cfoldertesttxt the contexts testtxt line this must b deletd number end yes i want created file resulttxt contains this must b deletd number end yes here i tried far import os fin osopen cfoldertesttxt r i get following error typeerror integer required i sure integer expecting can please let know go programming get result i want thanks lot help,1 you still using default mac os python using new installed one check python version python must find new version inside usrlocalbin update bashprofile pathusrlocalbinpath try try import pyqt,i running python os x snow leopard i installed python using macports then i installed pypyqt pypyside i get work python give errors i import i get following errors terminal i test either pysideuic command found pyuic command found,1 it seems likely matplotlib set use backend wx try either setting matplotlibrc file set program must set matplotlib imported instructions,i like rectangle appear every time user clicks line i gotten work procedurally like example httpwwwdaniwebcomsoftwaredevelopmentpythoncode i implemented ipython compatibility started using classes i could longer use appmainloop without program crashing how i refresh wxframe object inside class why selffigurecanvasdraw work the code open ipython pylab option x x decent parameters problem import wx import numpy np import matplotlibpyplot plt import matplotlibpatches patches matplotlibbackendsbackendwxagg import figurecanvaswxagg figcanv pylab import import ipythonipapi ip ipythonipapiget import sys class maincanvaswxframe set canvas plot rectangle lie def initself args wxframeinitselfnone size selfx args selfy args selffigure pltfigure selfaxes selffigureaddsubplot selfaxesplotargs selfline selfaxesplotselfx selfy picker visible false selfcanvas figcanvself selffigure selfrect patchesrectangle visibletrue selfaxesaddpatchselfrect selffigurecanvasmplconnect pickevent selfonpick def onpickself event move rectangle last click line selfrectsetxeventmouseeventxdata selfrectsetyeventmouseeventydata selfrectsetvisibletrue print rect x selfrectgetx print rect selfrectgety selffigurecanvasdraw def runthisplotself args run ipython examples in import demo in runplot x z where x z numbers type args arg argssplit try argsappendselfshellusernsarg except keyerror raise valueerrorinvalid argument r arg mc maincanvasargs ipexposemagicrunplot runthisplot thanks erin,1 without code rather difficult help sure i take stab from question i guessing wanting retrieve value combo box user changes you going need create new event handler retrieve value upon user changing in order ensure entire module use data start creating global variable top module this must outside classes definitions combovalue here created variable called combovalue set value this important first defines variable type integer second value returned code nothing selected combo box now class pygtk code put definition i prefer putting event handlers inside init definition makes easier access def combochangedevent datanone this imports combovalue variable declared otherwise module would creating local variable instead would use rest program global combovalue this retrieves combo box selected index sets combovalue variable index combovalue comboboxgetactive now need connect combo box event using changed signal comboboxconnectchanged combochanged and you hook processes checking value combovalue variable just remember code sets variable index selected item combo box text value this extremely important remember try check string variable get nowhere the value nothing selected remember count zero index items it may useful write values combo box indexes reference it might look something like combobox choose color black white red green blue then code working combo box value may little something like combovalue pass in words nothing elif combovalue set color black elif combovalue set color white and forth so see everything context entire code minus corny little example combovalue class myapplication def initself your code def combochangedevent datanone this imports combovalue variable declared otherwise module would creating local variable instead would use rest program global combovalue this retrieves combo box selected index sets combovalue variable index combovalue comboboxgetactive your gui code this combobox created model assuming already declared point called mymodel combobox gtkcomboboxmymodel now connect changed signal combobox event created comboboxconnectchanged combochanged i hope helps again without code hard give specifics i helping since new please sure post specific examples code project future questions cheers,i new python pygtk i want use changed value combo main window i i need help thanks advance best regards,1 your guess correct wrap widget gtkeventbox example hope hopeful import gtk def callbackwidget event data print event data class wingtkwindow def initself superwin selfinit selfconnectdestroy gtkmainquit selfsetpositiongtkwinposcenter selfsetdefaultsize tb gtktoolbuttongtkstocknew wrap gtktoolbutton gtkeventbox evbox gtkeventbox evboxconnectenternotifyevent callback enter evboxconnectleavenotifyevent callback leave evboxaddtb selfaddevbox name main win gtkmain,on happy irrevelent note absolute last obstacle particular project if i fix i first significant dot release project going public thanks everyone so helping project two answers help across board now actual question i toolbar application python pygtk number gtktoolbutton objects these function fine i working clicked events tied however i need also connect enternotifyevent leavenotifyevent signals i display button functions statusbar this code i i receiving errors yet status bar messages appearing newtb gtktoolbuttongtkstocknew toolbarinsertnewtb newtbshow newtbconnectclicked newevent newtbconnectenternotifyevent statuspush create new empty project newtbconnectleavenotifyevent statuspop i know issue statuspush statuspop events i connected gtkmenuitem objects work swimmingly i know gtktoolbutton objects widgets class enternotifyevent leavenotifyevent should technically work my guess particular object emit signals clicked thus i put gtkeventbox what i wrong how i fix thanks advance,2 i know direct answer half hour trying get pyexe working i gave tried cxfreeze works wonderfully httpcxfreezesourceforgenetcxfreezehtml within five minutes i shiny executable waiting,i python project many modules directoriesthe main program run testmainpy import psicorebenchmanager bm import shutil import os manager bmbenchmanager i follow exacty procedure pyexe create exe file projectbut exe file created i run gives error importerror no module named psicorebenchmanager has anybody experience pyexe success,2 in python x print function statement include parens around list printed objects in python x print changed function you using python x syntax you two options use python x syntax instead skipping parens print b c add future import printfunction disable print statement use print function instead this enables use python x syntax recent enough python x at moment printing single tuple seeing repr tuple ie would get printabc python x print function note print adds spaces automatically need add strings,below code i working python list angle couples phipsi minimal deviation tolerated st number maximal deviation tolerated st number b minimal deviation tolerated nd number c maximal deviation tolerated nd number check couple fit intervals numbers lenphipsi phipsiia phipsiib phipsiic phipsiid print couple phipsii angles helix else print couple phipsii angles helix ii this i get couple angles helix couple angles helix couple angles helix couple angles helix couple angles helix how i get couple angles helix couple angles helix i checked help section symbols figure thank help,3 use string formatting here ya go lenphipsi phipsiia phipsiib phipsiic phipsiid print couple f f angles helix phipsii phipsii else print couple f f angles helix phipsii phipsii ii,below code i working python list angle couples phipsi minimal deviation tolerated st number maximal deviation tolerated st number b minimal deviation tolerated nd number c maximal deviation tolerated nd number check couple fit intervals numbers lenphipsi phipsiia phipsiib phipsiic phipsiid print couple phipsii angles helix else print couple phipsii angles helix ii this i get couple angles helix couple angles helix couple angles helix couple angles helix couple angles helix how i get couple angles helix couple angles helix i checked help section symbols figure thank help,1 swig would usually preferred solution problems like custom typed structures wrapped perfectly sensibly the thing need watch though limitations swig parser got everything header files,ok quick hopefully easy question i large c api basically sockets api top level xml type protocol this distributed source package company all source code written header files including function implementations odd reason i guess figure easier developers import h file worry compiling multiple cpp files the source also available c java net the application i writing python linux needs use api python my three options seem either running applications separately message passing protocol running swig similar generate python hookin reimplement source code python ultimately i like make asynchronous possible already using twisted parts application using swig seems quickest many custom typed structures used passing functions well returns functions i heard bit issue swig i rather write message protocol creates another point failure two different source codes two different languages i manage reimplementing c code python may ultimately good solution going require large amount effort time my question swig seem like good idea i need write c files compile wrap headers i forget swig look something else i appreciate help thoughts thanks edit turns i misspoke earlierthere lot source code header files i found bunch lib files well is possible use swig boost similar types files included or i need write top level api try way so far attempts failed miserably solution i ended implementing api straight python turns protocol spec complex c libraries actually made difficult needed i also added bonus building lib inside asynchronous framework instead threading synchronous calls,2 you consider boostpython it gives lot control pythonc interface actually easy use there simple tutorials using boostpython since boostpython c avoid adding third technology swig project,ok quick hopefully easy question i large c api basically sockets api top level xml type protocol this distributed source package company all source code written header files including function implementations odd reason i guess figure easier developers import h file worry compiling multiple cpp files the source also available c java net the application i writing python linux needs use api python my three options seem either running applications separately message passing protocol running swig similar generate python hookin reimplement source code python ultimately i like make asynchronous possible already using twisted parts application using swig seems quickest many custom typed structures used passing functions well returns functions i heard bit issue swig i rather write message protocol creates another point failure two different source codes two different languages i manage reimplementing c code python may ultimately good solution going require large amount effort time my question swig seem like good idea i need write c files compile wrap headers i forget swig look something else i appreciate help thoughts thanks edit turns i misspoke earlierthere lot source code header files i found bunch lib files well is possible use swig boost similar types files included or i need write top level api try way so far attempts failed miserably solution i ended implementing api straight python turns protocol spec complex c libraries actually made difficult needed i also added bonus building lib inside asynchronous framework instead threading synchronous calls,2 you combine html directories you combine coverage data files use coverage directly rather nose nosetest withcoverage proj mv coverage coverage nosetest withcoverage proj mv coverage coverage coverage combine combines coverage coverage new coverage coverage html directoryhappysauce,i many projects i programatically running nosetest withcoverage coverhtmldirhappysauce the problem project coverage module overwrites indexhtml file instead appending is way generate combined superindexhtml file contains results projects thanks,3 i think would faster pull good values use randomchoice pick one whenever need something like import numpy np import random itertools import izip data nprandomnormal row data goodones nplogicalandrow row good rowgoodones rowcopy nparrayx f else randomchoicegood f x izipgoodones row highlevel python code write slower c internals python if push work c internals usually faster in words try let python heavy lifting rather writing lot code it zen write less code get faster code i added loop run code times run code times measured long took execute according test code ten times faster additional explanation code rowcopy set building new list calling nparray new list convert numpy array object the new list built list comprehension the new list made according rule number good keep else take random choice among good values a list comprehension walks sequence values apply rule need two values number flag saying whether number good the easiest fastest way make list comprehension walk along two sequences use izip zip two sequences together izip yield tuples one time tuple f x f case flag saying good x number python builtin feature called zip pretty much thing actually builds list tuples izip makes iterator yields tuple values but play zip python prompt learn works in python unpack tuple variable names like b in example set b in list comprehension unpack tuples izip variables f x then heart list comprehension ternary statement like flag else b the return value flag value true otherwise return b the one list comprehension x f else randomchoicegood this implements rule,i wondering efficient way replace elements array random elements array given criteria more specifically i need replace element meet given criteria another random value row for example i want replace row data random cell datarow my inefficinet solution looks something like import numpy np data nprandomnormal index row enumeratedata rowcopy npcopyrow outliers nplogicalorrow row prob npwhereoutliers fixed fixed randomothervalue rrandint randomothervalue npwhereoutliers fixed else rowcopyprob rowrandomothervalue fixed obviously efficient,2 this import subprocess p subprocesspopencat filelog tail shellfalse stdoutsubprocesspipe stderrsubprocesspipe stdinsubprocesspipe try shelltrue work shellfalse pstdout pstdoutread pstderr pstderrread print pstdout or work import os result ossystemcat filelog tail,how would one call shell command python contains pipe capture output suppose command something like cat filelog tail the perl equivalent i trying would something like string cat filelog tail,1 use subprocesspipe explained subprocess docs section replacing shell pipeline import subprocess p subprocesspopencat filelog stdoutsubprocesspipe p subprocesspopentail stdinpstdout stdoutsubprocesspipe pstdoutclose allow p receive sigpipe p exits outputerr pcommunicate or using sh module piping becomes composition functions import sh output shtailshcat filelog,how would one call shell command python contains pipe capture output suppose command something like cat filelog tail the perl equivalent i trying would something like string cat filelog tail,3 import subprocess task subprocesspopencat filelog tail shelltrue stdoutsubprocesspipe data taskstdoutread assert taskwait note capture stderr and want capture stderr well need use taskcommunicate calling taskstdoutread taskstderrread deadlock buffer stderr fills if want combined able use amp part shell command but given exact case task subprocesspopen tail filelog stdoutsubprocesspipe data taskstdoutread assert taskwait avoids need pipe,how would one call shell command python contains pipe capture output suppose command something like cat filelog tail the perl equivalent i trying would something like string cat filelog tail,2 x text textnew xsplit textx textnew probably index line enumeratetext textindex linesplit the problem first example using x index text text array strings x always string using string array index textx raises error array indices must integers my example corrects enumerating text returns online string line number line index hope makes sense i suggest playing around get,for reason i get traceback trying split comma delimited items new list inserting higher list traceback recent call last file spersonal foldersandypython projectspeople cancelledanalyze customers testpy line module textx textnew typeerror list indices must integers str here code future import division future import printfunction infile openspersonal foldersandypython projectspeople cancelledanalyze authorize truncatedcsv text infilereadlines infileclose header text text text x text textnew xsplit textx textnew printtext a sample data used authcapturejackfranklinjackfrancypantscomapr pm pdtn voidjacobrasnipgoodnessfinlandcomapr pm pdtn i basically want make comma delimited piece information inside list separate list basically bunch lists inside one main list thanks,2 after considering early answers thinking bit solution i came def numinputprompt error rawinputprompt int float complex try return ts except valueerror pass print error return numinputprompt error better get first k tries i really want input function validation function however i think hyry suggestion loop int float complex good one i took win suggestion use recursion instead looping understanding really confused persistent user could exceed max recursion depth although i need i think karl knechtel correct making error arg instead hard coded,i trying get number cli input python valid input either int float i need maintain type so validating int returning float work this best thing i able come good def isvalidn try n return floatn return intn except valueerror print try def numinputs n rawinputs isvalidn none n rawinputs return isvalidn validnum numinputenter valid number clearly best way,1 see display sshaskpass section man sshadd,i attempting automate scp commands pexpect ubuntu however i keep getting password gui prompt title openssh how i disable behavior use command line prompts instead,1 i run ubuntu native python gcc import glib python appears work i installed pythonnumpy pythonmatplotlib pythonpyfits synaptic package manager nothing else particular nothing installed recent version found package site previous experience learned usually bad idea but i no usrsharepysharedglib folder know get is folder path pythonpath if yes try remove path retry import glib possible get second installation glib place installed maybe needed another package glib interface c compiler used several places what gcc version gtk also makes intensive use glib did installed gtk pygtk synaptic hard way separated little packes compiled if yes try install synaptic i mostly think comes installation mix python extension somewhere the radical solution course reformat computer fresh os probably something want i try uninstall packages python uses reinstall synaptic hope helps,i try import glib python get following error traceback recent call last file stdin line module file usrsharepysharedglibinitpy line module glibglib import importerror no module named glib seems glib found glib found has anybody hint solving problem i running ubuntu installed python pythongobject pythongda dbus ubuntu package manager,1 you information need error message typeerror list indices must integers str you probably whant something like thenewlist xsplit x text example text authcapturejackfranklinjackfrancypantscomapr pm pdtn voidjacobrasnipgoodnessfinlandcomapr pm pdtn thenewlist xsplit x text import pprint pprintpprintthenewlist authcapture jack franklin jackfrancypantscom apr pm pdtn void jacob rasnip goodnessfinlandcom apr pm pdtn,for reason i get traceback trying split comma delimited items new list inserting higher list traceback recent call last file spersonal foldersandypython projectspeople cancelledanalyze customers testpy line module textx textnew typeerror list indices must integers str here code future import division future import printfunction infile openspersonal foldersandypython projectspeople cancelledanalyze authorize truncatedcsv text infilereadlines infileclose header text text text x text textnew xsplit textx textnew printtext a sample data used authcapturejackfranklinjackfrancypantscomapr pm pdtn voidjacobrasnipgoodnessfinlandcomapr pm pdtn i basically want make comma delimited piece information inside list separate list basically bunch lists inside one main list thanks,1 tuples mutable cannot change the thing probably find creating tuples instead list expected,i d tuple actually i thought list error says tuple but anyways the tuple form floatnumberval prodid i dictionary contains key prodid value prodname want change prodid tuple prodname so waht i prodname tuple proddict dictionary rangelenprodname key prodnamei get prodid proddicthaskeykey value proddictkey prodnamei value umm pretty straightforward get error typeerror tuple object support item assignment thanks,3 unfortunately modify tuple use lists instead,i d tuple actually i thought list error says tuple but anyways the tuple form floatnumberval prodid i dictionary contains key prodid value prodname want change prodid tuple prodname so waht i prodname tuple proddict dictionary rangelenprodname key prodnamei get prodid proddicthaskeykey value proddictkey prodnamei value umm pretty straightforward get error typeerror tuple object support item assignment thanks,2 prodnamei tupleprodnamei value,i d tuple actually i thought list error says tuple but anyways the tuple form floatnumberval prodid i dictionary contains key prodid value prodname want change prodid tuple prodname so waht i prodname tuple proddict dictionary rangelenprodname key prodnamei get prodid proddicthaskeykey value proddictkey prodnamei value umm pretty straightforward get error typeerror tuple object support item assignment thanks,1 short answer cannot tuples immutable lists mutable that really key distinction if want mutate ordered collection items python going list if want stick tuples going make new one if i understood correctly starting prodname proddict name name name so get list want newprodname f proddictid f id prodname this fail id found proddict dict if want fail early great if set default ex none using get newprodname f proddictgetid none f id prodname,i d tuple actually i thought list error says tuple but anyways the tuple form floatnumberval prodid i dictionary contains key prodid value prodname want change prodid tuple prodname so waht i prodname tuple proddict dictionary rangelenprodname key prodnamei get prodid proddicthaskeykey value proddictkey prodnamei value umm pretty straightforward get error typeerror tuple object support item assignment thanks,2 namemain mydict reader csvreaderopenfilecsv rb rows reader k rows v rows mydictk v print mydict here mydict kv you making new dictionary every iteration previous data lost update you make something like mydict l el l k v el k mydict mydictk v else mydictkappendv print mydict this way value key stored your code namemain mydict reader csvreaderopenfilecsv rb rows enumeratereader continue k rows v rows k mydict mydictk v else mydictkappendv print mydict update you mean k v mydictitems print k v update this work namemain mydict reader csvreaderopenfilecsv rb rows enumeratereader continue k rows v rows k mydict mydictk v else mydictkappendv print mydict,new concept dictionaries python i csv file multiple columns want create dictionary keys taken st column values second keyvalue pair made rows two columns the code follows namemain reader csvreaderopenfilecsv rb rows reader k rows v rows mydict kv print mydict problem the output returned last bottom row first two columns ie want dictionary contain rows first two columns format how run loop row numbers first two columns thati dont know,3 if prodname list tuples want create new list tuples like explained create new tuples since tuple immutable ie changed example ifloatnumberval prodid enumerateprodname prodnamei floatnumberval proddictgetprodidprodid,i d tuple actually i thought list error says tuple but anyways the tuple form floatnumberval prodid i dictionary contains key prodid value prodname want change prodid tuple prodname so waht i prodname tuple proddict dictionary rangelenprodname key prodnamei get prodid proddicthaskeykey value proddictkey prodnamei value umm pretty straightforward get error typeerror tuple object support item assignment thanks,2 you creating new dict overwriting old one iteration develerx answer fixes problem i wanted point easier way using dict comprehensions assuming csv file contains two columns namemain reader csvreaderopenfilecsv rb mydict k v k v reader print mydict if using older versionolder i think use dict comprehensions use dict function mydict dictk v k v reader edit and i thought mydict dictreader could also work,new concept dictionaries python i csv file multiple columns want create dictionary keys taken st column values second keyvalue pair made rows two columns the code follows namemain reader csvreaderopenfilecsv rb rows reader k rows v rows mydict kv print mydict problem the output returned last bottom row first two columns ie want dictionary contain rows first two columns format how run loop row numbers first two columns thati dont know,2 why make tar file instead like def downloadlogsreq dir response httpresponsemimetype applicationxgzip response contentdisposition attachment filenamedownloadtargz tarred tarfileopenfileobjresponse mode wgz tarredadddir tarredclose return response,is possible make zip archive offer download still save file hard drive,3 this builtin strings word hello wordistitle true note stristitle looks whether every word string titlecased might give surprise hello worldistitle returns false if want check first character string use word hello world wordisupper true,i want create function would check first letter string uppercase this i came far def islowercaseword word range stringasciilowercase return true else return false when i try run i get error word range stringasciilowercase syntaxerror invalid syntax can someone look advise i wrong,3 the syntax error stems fact need parentheses rangestringasciilowercase but fact use range it simple word stringasciilowercase,i want create function would check first letter string uppercase this i came far def islowercaseword word range stringasciilowercase return true else return false when i try run i get error word range stringasciilowercase syntaxerror invalid syntax can someone look advise i wrong,1 why use strisupper in word asdf in wordisupper out false in word asdf in wordisupper out true,i want create function would check first letter string uppercase this i came far def islowercaseword word range stringasciilowercase return true else return false when i try run i get error word range stringasciilowercase syntaxerror invalid syntax can someone look advise i wrong,3 try outputprocess subprocesspopenjavac cp cusersmyusernamedesktophtmlcleanerjar scrappinglastfmjava shelltrue stdoutsubprocesspipe env environmental variableshere whatever javarelated environmental variables run javac normally items env dictionary asgs suggests need classpath you split command list i make easier see whole thing,i trying execute command inside python script import subprocess outputprocess subprocesspopenjavac cp cusersmyusernamedesktophtmlcleanerjar scrappinglastfmjava shelltrue stdoutsubprocesspipe but i getting error package orghtmlcleaner exist if i run javac command independently executes fine my current working directry cusersmyusername,1 the error raised python java subprocess most likely java machine finding libraries refines problem path configuration problem likely variable classpath set environment solve import shlex javacommandrjavac cp cusersmyusernamedesktophtmlcleanerjar scrappinglastfmjava cmdline shlexsplitjavacommand outputprocess subprocesspopencmdlineshelltrue stdoutsubprocesspipe env classpath pathtojavapackages,i trying execute command inside python script import subprocess outputprocess subprocesspopenjavac cp cusersmyusernamedesktophtmlcleanerjar scrappinglastfmjava shelltrue stdoutsubprocesspipe but i getting error package orghtmlcleaner exist if i run javac command independently executes fine my current working directry cusersmyusername,1 maybe settimeout looking,question is sort time interrupt socketaccept function python info i program child thread bound port constantly accepting tending passing queue main thread right i trying get child thread interrupt deconstruct appropriately i think possible simply stop child thread parent deconstruct child times i want able return early form accept i decided would useful approach so way i time cancel accept method thread return wo something connect first,2 you set default timeout import socket print socketgetdefaulttimeout socketsetdefaulttimeout afaik this affect socket operation,question is sort time interrupt socketaccept function python info i program child thread bound port constantly accepting tending passing queue main thread right i trying get child thread interrupt deconstruct appropriately i think possible simply stop child thread parent deconstruct child times i want able return early form accept i decided would useful approach so way i time cancel accept method thread return wo something connect first,3 the current api limits results you try altering coordinates precise avoid finding venue pagination would nice lot venues search,i trying get locations new york using foursquare api using following api call ttpsapifoursquarecomvvenuessearchllamplimit what i understand call imposes limit search results maximum i get locations when using facebook api results returned random i could issue multiple calls get results foursquare seems returning result set is good way get locations edit ok so comment saying i could breaking contractual agreement i sure would case i would gladly accept reasoning my doubt let us say hypothetically location i searching results returned in case pagination mechanism somewhere,1 use errnoeintr instead it safe import errno errnoeintr however tell signal interrupted system call signal interrupted from man select ebadf an invalid file descriptor given one sets per‐ haps file descriptor already closed one error occurred eintr a signal caught see signal einval nfds negative value contained within timeout invalid enomem unable allocate memory internal tables,i new python forgive question basic i trying handle keyboard interrupt accepting data socket using select module so i selectselect function call wait data socket output console when pressing ctrlc seems sometimes i get selecterror sometimes exceptionsioerror exception the corresponding error code exceptions there code handles keyboardinterrupt exception deeper call stack i get sigint function i accept socket connection i want reraise keyboardinterrupt exception i also want catch connection related exceptions would safe check exception error code raise keyboardinterrupt will affect ability catch connectionrelated exceptions is good resource error codes thanks,1 add item new list reverse also list item larger reverse newlist item oldlist rev item rev oldlist item rev newlistappenditem,list generated list want write values desired output list,1 since speaking pythonic good habit always use join instead addition join strings phone nphone nphone joinphonephonephone,i got db chock full phone numbers strings formatted like i like display django template i know i n contactsobjectsgetnamename nphone nphone nphone nphone better pythonic way,3 use string formating insert currentmonth regex pattern rpspeakerazazs pmonthmdformatmcurrentmonth by way pmonth probably expect the regex matches if wanted match one twelve need pmonth,suppose i following regular expression python i would like use variable instead for example variable currentmonth how i plug currentmonth regular expression rpspeakerazazs pmonth,2 just one solution nphone cccccccccc tuplemapord nphone nphone ssssssssss tuplenphone,i got db chock full phone numbers strings formatted like i like display django template i know i n contactsobjectsgetnamename nphone nphone nphone nphone better pythonic way,3 what looking called privilege escalation much depends platform running in general program would run portion superuser on unix systems instance might able use sudo read contents file but mentioned really depends system running,i open system file read this file usually readable root super user i way ask user superuser password i would like use credentials open file read without entire program running superuser process is way achieve multiplatform way,2 it may overkill use case numbers formatted way might consider using phonenumbers module it would allow add functionality eg international phone numbers different formatting etc easily you parse numbers like import phonenumbers parsednumber phonenumbersparse us parsednumber phonenumbercountrycode nationalnumberl extensionnone italianleadingzerofalse countrycodesourcenone preferreddomesticcarriercodenone then format way want could phonenumbersformatnumberparsednumber phonenumbersphonenumber u note could easily use formats phonenumbersformatnumberparsednumber phonenumbersphonenumberformatnational u phonenumbersformatnumberparsednumber phonenumbersphonenumberformatinternational u phonenumbersformatnumberparsednumber phonenumbersphonenumberformate u,i got db chock full phone numbers strings formatted like i like display django template i know i n contactsobjectsgetnamename nphone nphone nphone nphone better pythonic way,3 the ord chr functions need you need bit array convert integers,if i char char k i turn bit array truefalsetruetruetruefalsefalsetrue combine arrays single array anding bit turning combined array back char such c combine make c also sometimes results conversions ascii,1 if want narrow source bottleneck i would start calls timeit various sections code if help seems like much effort look python profilers,i currently creating image viewer python using tkinter pil i want image loading quicker therefore i would like know i could install utilize libjpeg turbo tkinter pil even i use different gui toolkit like pyqt different imaging library i found something called opencv so essentially best fastest way i load resize display large image python edit i believe main bottleneck image resizing visible image loading i tell sure though i know measure thing i essentially python newb and i basically minimalistic image viewer if want see code httppastebincomfwfbcu edit i run cprofile bunch fixed code fixed slowness so question essentially i using another gui toolkit like pyqt different imaging library i found something called opencv,1 i would split program two handles opening file accessing contents it assume started privileges needs everything else require special privileges put config entry describes exec subprocess command requires extra privileges ie accessspecialfile sudo accessspecialfile accessspecialfile runas useraccountwithprivs accessspecialfile this offloads system specifics privilege escalation system shell may convenient ways gaining permissions need,i open system file read this file usually readable root super user i way ask user superuser password i would like use credentials open file read without entire program running superuser process is way achieve multiplatform way,2 need make array chrord c amp ord,if i char char k i turn bit array truefalsetruetruetruefalsefalsetrue combine arrays single array anding bit turning combined array back char such c combine make c also sometimes results conversions ascii,2 twistedwebxmlrpcproxy uses factory set http connection usual way the noisy attribute factories twisted provides controls whether log start stop messages you change noisy attribute proxy factory like sys import stdout twistedwebxmlrpc import proxy twistedinternet import reactor twistedpythonlog import startlogging startloggingstdout p proxy httplocalhostrpc class quietqueryfactorypqueryfactory noisy false pqueryfactory quietqueryfactory pcallremote echo foo reactorrun compare output program noisy set true for xmlrpc server log messages come twistedwebserversite hosting xmlrpc resource the site initializer accepts logpath argument pass path parameter request logs written path instead main log you also override sitelog method emits log messages either omit ones want omit nothing disable request log entirely,i xmlrpc methods application generate lot twisted log messages like turn logged python logging module utc info xxxxxxxxxxxx sep post rpc http xmlrpclibpy wwwpythonwarecom these log messages necessary i would like either change level loggingdebug suppress entirely is supported edit these serverside log messages logged i call methods twistedwebxmlrpcxmlrpc objects these objects used hierarchy putchild underneath twistedwebserversite twistedwebvhostnamevirtualhost objects i using default selectreactor i suppose classes request object could one actually logging,2 openfilenametxt w f fwritetest,i trying create python script edits file file already error like traceback recent call last file openorcreatfilepy line module filehandle pathtofile w ioerror errno no file directory homemethefiletxt it works fine file exists i also tried filehandle pathtofile w but comes error do i need explicitly check file if i create file edit sorry i realized folder missing i idiot,1 i think could let python keep track function calls parameters instead stack suppose yaml parse tree node represents function call child node parameter also function call could potentially parameters then define function evaluate evaluates node tree follows pseudocode def evaluatenode evaluate parameters call params child node paramsappendevaluatechild make call whatever function node represents passing parameters return nodefunctioncallparams finally call evaluate passing root yaml tree parameter get desired behaviour a slightly different evalapply structure def evaluatenode evaluate parameters call params evaluatechild child node apply whatever function node represents return nodefunctioncallparams,i python library builds special iterators behavior tree nested function calls while api fairly nice lightweight syntax due python could really use declarative dsl here rough sketch i envisioning the dsl using yaml tree sequence doaction doaction select doaction sequence doaction doaction doaction would result following nested function calls visit sequence doaction doaction select doaction sequence doaction doaction doaction i trouble visualizing exactly because dsl must represent tree simple depthfirst traversal seems appropriate but order build nested function calls i turn inside somehow it probably involves something clever intermediary stack somesuch i quite grasp what correct way perform transformation,2 to check file import ospath ospathisfilepathtofile handle exists ospathisfilepathtofile filehandle pathtofile w else pass thing there several ways create file python want create text file take look numpysavetxt i think one easiest effective ways,i trying create python script edits file file already error like traceback recent call last file openorcreatfilepy line module filehandle pathtofile w ioerror errno no file directory homemethefiletxt it works fine file exists i also tried filehandle pathtofile w but comes error do i need explicitly check file if i create file edit sorry i realized folder missing i idiot,1 there standard ways approaching test depends something else object function call etc you use mocks place objects code testing depends you load fixture creationcall test setup some people like classical unit tests unit code tested in cases typically use mocks stubs replace dependencies other like integrative tests call stack tested in cases use fixture possibly even callscreations setup function generally would make one test depend another all tests clean runnable isolation runnable part suite consistent repeatable if make one test dependent another cannot run isolation also forcing order tests run enforcing order tests good fact many people feel randomize order tests run,i want know bestdifferent ways test rest api uses database backend i developed api flask python want use unittest nose but problem resources require another resource create first place is way say test creation blog post requires another test involving creation author successful,3 the error says no file directory since trying create file must missing so need create homeme directory see osmakedirs,i trying create python script edits file file already error like traceback recent call last file openorcreatfilepy line module filehandle pathtofile w ioerror errno no file directory homemethefiletxt it works fine file exists i also tried filehandle pathtofile w but comes error do i need explicitly check file if i create file edit sorry i realized folder missing i idiot,3 since privileges work completely differently unixlike systems windows going need platformspecific code in case need break program two separate programs one runs elevated permissions runs standardreduced permissions in unixlike systems including linux mac os x executable runs elevated permissions assume running root open file reading since mentioned file large actually read whole file keep open file descriptor if opening fails print error message exit use setreuid setregid set user id group id back unprivileged user use one exec functions execute unprivileged executable if want make run program without using sudo make owned root make setuserid executable chown root theprogram chmod theprogram the unprivileged program run normal permissions starts open file descriptor file descriptor used read special file for windows similar slightly different assume running root open file reading using createfile do use default security attributes create securityattributes structure binherithandle set true handle inherited child processes if opening file failed print error message exit use createprocess launch child process pass handle command line eg printed numerical value could also use shared memory region trouble worth problem embed manifest executable requireadministrator set true after run program get uac prompt asking want allow program makes changes the child process grabs inherited handle parsing command line read data pleases one problem approach inherit handle use lowlevel system calls read unix readfile windows read use higherlevel functions like c fread c iostream ok unix fdopen equivalent windows far i aware as i sure noticed everything c in unix translates pretty straightforwardly python since os module lots goodies like setreuid exec fdopen on windows might able stuff ctypes module andor pywin probably easier stick c,i open system file read this file usually readable root super user i way ask user superuser password i would like use credentials open file read without entire program running superuser process is way achieve multiplatform way,2 i problem ubuntu box prior installing mysqlpython via pip i needed compile module dependencies source using following command sudo aptget builddep pythonmysqldb see article httptheviceprogrammercomp,i trying set virtualenv django project it needs mysqlpython i trying replicate production environment uses python my ubuntu desktop python i install python virtualenv virtualenv pythonusrbinpython however i try pip install mysqlpython i get output pip install mysqlpython downloadingunpacking mysqlpython running setuppy egginfo package mysqlpython warning files found matching manifest warning files found matching changelog warning files found matching gpl installing collected packages mysqlpython running setuppy install mysqlpython building mysql extension gcc pthread fnostrictaliasing dndebug g fwrapv o wall wstrictprototypes fpic dversioninfo final dversion iusrincludemysql iusrincludepython c mysqlc buildtemplinuximysqlo dbigjoins fnostrictaliasing dunivlinux dunivlinux in file included mysqlc pymemcompath fatal error pythonh no file directory compilation terminated error command gcc failed exit status i installed pythondev ubuntu deb package python how else i get mysqlpython installed,3 if want read standard input example pipeline write import sys line sysstdin and rest work sysstdin open file corresponding standard input if lines list iterate across list using code,code line open musictxt file line c linesplit file del c djoinc aresub eresub urlsappende is way without file,1 not sure help searching source code i found abbreviated class hlobjectobject def nonzeroself registerthread return selfidnonzero class grouphlobject dictcompat class filegroup def reprself registerthread self return closed hdf file return hdf file mode ospathbasenameselffilename selfmode extrassizestringselffidgetfilesize because str method repr called produce output repr first calls registerthread checks see self alive better known evaluating true false python searches classes finds nonzero calls registerthread returns selfidnonzero apparently returning false so correct issue name binding assignment registerthread andor selfid bombing i know,i using hpy access hdf files store hpy file objects class but i experiencing strange behavior attempting reassign closed hpy file instance variable new one class myclass def initself filename selfhfile none selffilename filename def vartestself selfhfile hpyfileselffilename r print selfhfile selfhfileclose print selfhfile newhfile hpyfileselffilename r print newhfile selfhfile newhfile print selfhfile print newhfile def main filename sysargv mycls myclassfilename myclsvartest output hdf file testh mode r m closed hdf file hdf file testh mode r m closed hdf file closed hdf file attempting update instance variable newly opened hpy file object appears somehow affected state object closing regardless implementation hpy side i see behavior makes sense understanding python language ie overloading assignment operator this example run python hpy if want try example hdf file sitting around change file access mode r,1 the first problem statement tsoupfindid table there nothing id table i think mean tsoupfind table finds table unfortunately finds first table you could tsoupfindalltable would quite brittle i would suggest something like following html filewhateverhtml soup beautifulsouphtml rows soupfindalltr class odd even dat row rows datappend map str rowfindall td the resulting dat variable td classlefta hrefwhateverabxatd td classleftbarrick gold corptd tdtd tdtd td classuptd tdtd tdtd tdcenterampnbspa hrefwhatever classbcqlinkampnbspqampnbspaampnbspa hrefchartaspsymabxampampcodexdaily classbcqlinkampnbspcampnbspaampnbspa hreftexpertaspsymabxampampcodexdaily classbcqlinkampnbspoampnbspaampnbspcentertd edit wrong array index,hi i trying parse html table using beautiful soup the table looks something like table width border cellpadding cellspacing bgcoloreecc tr td width height aligncenter valignmiddle bgcoloreecc bordercolorlight bordercolordarkwhite bfont faceverdana sizea hrefhttpwwwdailystockscom altdailystockscom titlehomehomeafontbtd tr table table width border cellpadding cellspacing tr classoddtd classlefta hrefwhateverabxatdtd classleftbarrick gold corptdtdtdtdtdtd classuptdtdtdtdtdtdcenterampnbspa hrefwhatever classbcqlinkampnbspqampnbspaampnbspa hrefchartaspsymabxampcodexdaily classbcqlinkampnbspcampnbspaampnbspa hreftexpertaspsymabxampcodexdaily classbcqlinkampnbspoampnbspaampnbspcentertdtr table i would like get information second table far i tried code html filewhateverhtml soup beautifulsouphtml soupfindid table dat mapstr rowfindalltd row tfindalltr that doesnt seem work help would much appreciated thanks,3 your best option use map reduce library export relevant data blobstore upload completed file google storage note integration google storage app engine work progress,i k entities model python gae i would like export csv file offline testing i use appcfgpy downloaddata option case i want backup local machine i like faster way create file gae save google storage elsewhere download later multiple machines i assuming i need task since likely take seconds operation complete class mymodeldbmodel foo dbstringpropertyrequiredtrue bar dbstringpropertyrequiredtrue def backupmymodeltofile what,1 maybe want something like urls refindallr file linereplace line file file line works file object list for standard input use file sysstdin example file file test abcde line file zzzzzzzzz output test abcde zzzzzzzzz,code line open musictxt file line c linesplit file del c djoinc aresub eresub urlsappende is way without file,1 i late party i trying figure finally solution have look code used httpscodedjangoprojectcomticket you access multipart values getlist if html form form enctypemultipartformdata action methodpost input typefile namemyfiles multiple input typesubmit nameupload valueupload form my django code process would look like afile requestfilesgetlist myfiles something afile writing form fieldwidget handle properly next step i still rather new using django i learning i go,how handle multiple file fields django for example i one form field would pass requestfiles file handling function but way go files,3 there numpyloadtxt x numpyloadtxt somefilecsv delimiter documentation edit list numpy arrays x scipyarraylinesplit dtype float line open somefilecsv r,i find parsing lots data files usually csv file similar using csv reader loop iterate every line the data usually table floats example reader csvreaderopen somefilecsv header readernext reslist list header line reader rangelenline reslistiappendfloatlinei resultdict dictzipheaderreslist refer column title this ok way populate i get column separate list however i would prefer default data container lists items nested lists numpy arrays since times numbers get pumped various processing scriptsfunctions power numpy lists makes life easier the numpy appendarr item append inplace therefore would require recreating arrays every point table slow unneccesary i could also iterate list datacolumns wrap array i done i sometimes clear cut i done parsing file may need append stuff list later line anyway i wondering lessboilerheavy way use overused phrase pythonic process tables data similar way populate arrays underlying container list dynamically without copying arrays time on another note kind annoying general people use columns organize data csv reads rows reader incorporated readcolumn argument yes i know super efficient i think many people would avoid boiler plate code like parse csv data file,3 you looking strptime convert string datetime instance see properly use comparing two datetime instances give timedelta instance read essentially give difference two times nearest milisecond learn everything datetime time calendar modules once learn dealing times dates python becomes really easy,i learning python one basic challenges suggested friends i working alarm clock i successfully made alarm clock played wav sound predetermined time now i using pygame gui worked great i set buttons adjust alarm time see i compare alarm time clock time clock time string form alarm time well but buttons unable string i kind stuck i tried ways turning string everything fairly unsuccessful far wondering anyone suggestion here code usrbinpython import ospath sys datetime time import os sys math import pygame random pygamelocals import maindir ospathsplitospathabspathfile datadir ospathjoinmaindir data currenttime datetimedatetimenow clocktime currenttimestrftimehm alarmtime pygameinit screen background width height screen pygamedisplaysetmodewidth height pygamedisplaysetcaptionalarm clock background pygameimageloadospathjoindatadir diamondplatejpg background pygametransformscalebackground width height current time font pygamefontfontnone text fontrenders clocktime true textrect textgetrect textrectcenterx screengetrectcenterx textrectcentery screengetrectcentery alarm time text fontrenders true textrect textgetrect textrectcenterx screengetrectcenterx textrectcentery screengetrectcentery alarm noise def alarmsoundfilepathospathjoinmaindir data boomwav pygamemixerinit sound pygamemixersoundfilepath channel soundplay pygametimewait image load function def loadimagefile file ospathjoindatadir file surface pygameimageloadfile return surfaceconvertalpha hour arrow class houruppygamespritesprite def initself pygamespritespriteinitselfselfgroups image loadimage arrowuppng image pygametransformscaleimage selfimage image selfrect selfimagegetrect surface pygamedisplaygetsurface selfarea surfacegetrect selfrectbottomleft textrecttopleft def clickcheckselfeventpos selfrectcollidepointeventpos pass def updateself pass hour arrow class hourdownpygamespritesprite def initself pygamespritespriteinitselfselfgroups image loadimage arrowdownpng image pygametransformscaleimage selfimage image selfrect selfimagegetrect surface pygamedisplaygetsurface selfarea surfacegetrect selfrectbottom textrecttop selfrectleft def clickcheckselfeventpos selfrectcollidepointeventpos pass def updateself pass minute arrow class minuteuppygamespritesprite def initself pygamespritespriteinitselfselfgroups image loadimage arrowuppng image pygametransformscaleimage selfimage image selfrect selfimagegetrect surface pygamedisplaygetsurface selfarea surfacegetrect selfrectbottomright def clickcheckselfeventpos selfrectcollidepointeventpos pass def updateself pass minute arrow class minutedownpygamespritesprite def initself pygamespritespriteinitselfselfgroups image loadimage arrowdownpng image pygametransformscaleimage selfimage image selfrect selfimagegetrect surface pygamedisplaygetsurface selfarea surfacegetrect selfrectbottomright textrecttopright def clickcheckselfeventpos selfrectcollidepointeventpos pass def updateself pass groups allsprites pygamespritegroup hourupgroups allsprites hourdowngroups allsprites minutedowngroups allsprites minuteupgroups allsprites hourup hourup hourdown hourdown minutedown minutedown minuteup minuteup clickableobjects hourup hourdown minutedown minuteup def main currenttime datetimedatetimenow clocktime currenttimestrftimehm screenblitbackground text fontrenders clocktime true text fontrenders alarmtime true screenblittexttextrect screenblittexttextrect event pygameeventget eventtype pygamequit eventtype keydown eventkey kescape sysexit eventtype mousebuttondown eventbutton object clickableobjects objectclickcheckeventpos clocktime alarmtime soundcheck false alarmsound soundcheck true allspritesdrawscreen allspritesupdate pygamedisplayupdate pygamedisplayflip name main main,1 the readlines method returns list lines words code would work one words line since files iterators lines done much easier infile messydatafiletxt outfile cleanedfiletxt deletelist word word wordn fin openinfile fout openoutfile w line fin word deletelist line linereplaceword foutwriteline finclose foutclose,i data file unstructed messy file i scrub specific list strings delete strings here i result infile rmessydatafiletxt outfile rcleanedfiletxt deletelist firstname lastnamefirstname lastnamefirstnamen lastnamen finopeninfile fout openoutfilew line fin word deletelist line linereplaceword foutwriteline finclose foutclose when i execute file i get following error nameerror name word defined please help,2 i similar issues fixes i describe app engine default django version change when use app engine templaterender sets templatedirs directory template rendering the extends tag django checks templates included inside templatedirs directory if parent sibling directory fails the solution i found use app engine templaterender instead write using django template class i also set templatedirs root project directory this going memory i first looked behaviour might changed since although workarounds still work fine,due app engine warning you using default django version the default django version change app engine release near future please call uselibrary explicitly select django version for information see httpcodegooglecomappenginedocspythontoolslibrarieshtmldjango i added two lines code top mainpy googleappenginedist import uselibrary uselibrarydjango this code totally broke app raising error file homeadelsoftwaregoogleappenginelibdjangodjangotemplateloaderpy line findtemplate raise templatedoesnotexistname templatedoesnotexist homeadelworkspacejeeneositecommontemplatesenustemplatehtml i googling found developers similar problem relative path longer supported django case i used absolute path code structured way site frontpage templateenusindexhtml indexpy events templateenuseventhtml templateenuscreatehtml eventpy createpy common templateenustemplatehtml templatepy every class inherent template class like common import template class eventtemplate def getself then call selfrenderfile eventhtml to render html file render function inside def renderself path html selfbase selfgetbase email none selfuser selfauthurl userscreatelogouturl email selfuseremail else selfauthurl userscreateloginurlselfrequesturi selftemplateupdate base selfbase user selfuser lang selflang templatehtml ospathjoinospathdirnamefile templatesstemplatehtml selflang email email authurl selfauthurl html ospathjoinospathdirnamepath templatesss selflang html selftemplateupdateselfdata selfresponseoutwritetemplaterenderhtml selftemplate and html file eventhtml code extends templatehtml i two solutions mind perhaps restructure everything make templates one folder local install django app engine i pretty sure must easier solution,1 i would recommend command line curl less secure less reliable you urllib json modules get access token want make call httpsgraphfacebookcomoauthaccesstokenclientidyourappidampclientsecretyourappsecretampgranttypeclientcredentials would url httpsgraphfacebookcomoauthaccesstokenclientidyourappidampclientsecretyourappsecretampgranttypeclientcredentials targeturlliburlopenurl token targetread edit my bad i forgot facebookoauth gives access token plain text need json module i updated example show note targetread give string accesstokenaccesstoken parsing remove identifier see response go url put information json dict acesstoken second half page information need,i trying post wall facebook page i administrator profile however luck how i achieve i stucked page access token retrieval part usrbinpython coding utf import facebook import urllib import urlparse import subprocess import warnings hide deprecation warnings the facebook module uptodate facebookgraphapierror warningsfilterwarnings ignore categorydeprecationwarning parameters app id profile want mess facebookappid xxxxxxxxxxxxxx facebookappsecret xxxxxxxxxxxxxxxxxxxxx facebookprofileid xxxxxxxxxxx trying get access token very awkward oauthargs dictclientid facebookappid clientsecret facebookappsecret scope managepages responsetype token oauthcurlcmd curl httpsgraphfacebookcomoauthaccesstoken urlliburlencodeoauthargs oauthresponse subprocesspopenoauthcurlcmd stdout subprocesspipe stderr subprocesspipecommunicate print urlliburlencodeoauthargs try oauthaccesstoken urlparseparseqsstroauthresponse accesstoken except keyerror print unable grab access token exit print oauthaccesstoken facebookgraph facebookgraphapioauthaccesstoken try post something wall try fbresponse facebookgraphputwallpost hello python profileid facebookprofileid print fbresponse except facebookgraphapierror e print something went wrong etype emessage,1 you passing query object delete method iterate fetching batches submit single enormous delete this inefficient requires multiple fetches work results fetch available time available memory the task either complete require chaining likely fail repeatedly since fetch every blob also calling count executes query determine count waste time since going try fetching results anyway instead fetch results batches using fetch delete batch use cursors set next batch avoid need query iterate tombstoned records finding first live one ideally delete multiple batches per task using timer determine stop chain next task,what best way remove blob blobstore i using python i quite lot blobs i like delete i currently following class deleteblobswebapprequesthandler def getself blobstoreblobinfoall allcount blobstoredeleteall taskqueueaddurl deleteblobs method get which seems using tons cpu far i tell nothing useful,2 delete autocompletion attempts forget problems install neocomplcache script site i exact problem script solved autocompletion needs really feature rich notice need,im trying get code completion python vim when i install vim i use configuration configure prefixhomevim enablepythoninterpyes withpythonconfigdirhomeetobkrupythonlibpythonconfig make ampamp make install i copy file httpvimcybermirrororgruntimeautoloadpythoncompletevim vimsharevimvimautoload directory file sharevimvimftpluginpythonvim i change setlocal omnifuncpythoncompletecomplete setlocal omnifuncpythoncompletecomplete but i press cx co i get error message error required vim compiled python e unknown function pythoncompletecomplete i write python i get e sorry command available version,1 instead enqueueing task per entity handle multiple entities single task this triggered daily cron job instance fans multiple tasks as well ensuring execute code entity also take advantage asynchronous urlfetch synchronize external resource efficiently batch puts gets datastore make updates efficient,i often models local copy remote resource needs periodically kept sync task urlkeepinsync params entityid entityid namesyncs entityid countdown add inside keepinsync changes saved model new task scheduled happen later now superficially seems like nice solution practice might become worried necessary tasks really added maybe entities representing level food pellets inside hamster cages automated email sent housekeeper feed but weeks later come back holiday find several hamsters starving it starts seeming like good idea make script goes entity makes sure proper task really queue but neither task queue classes method checking task exists can save hamsters come nicer way make sure method really sure periodically called entity update it seems want really sure tasks scheduled need keep track tasks nick johnson suggests not ready let go convenient task queue time tolerate uncertainty unable check tasks really scheduled,1 you need custom clean function form check def cleanself startdate cleaneddatagetstartdate enddate cleaneddatagetenddate enddate startdate msg uend date greater start date selferrorsenddate selferrorclassmsg,i startdate enddate fields model i want assign error enddate bigger startdate i looking docs find example,2 based comment i double clicking py file it seems invoke python application disappears couple seconds i dont get error thought i believe issue script finding input file that also getting output when double click i actually recall interpreter going look i think pythonexe installed use fully qualified path like depends os infile rctmpmessydatafiletxt outfile rctmpcleanedfiletxt infile retctmpmessydatafiletxt outfile retctmpcleanedfiletxt also sanity run commandline instead double clicking it much easier catch errorsoutput,i data file unstructed messy file i scrub specific list strings delete strings here i result infile rmessydatafiletxt outfile rcleanedfiletxt deletelist firstname lastnamefirstname lastnamefirstnamen lastnamen finopeninfile fout openoutfilew line fin word deletelist line linereplaceword foutwriteline finclose foutclose when i execute file i get following error nameerror name word defined please help,1 the error code description may little confusing situation when application binds port without setting soreuseport option second application tries bind port bind fail error the problem binding address though port soreuseport flag as aside linux equivalent multiple multicast listeners functionality achieved using soreuseaddr flag per soreuseport linux the first application bind soreuseport flag set otherwise exclusive bind application binds fail for example for bsd based platforms socksetsockoptsocketsolsocket socketsoreuseport sockbind mcastport it turns mdnsresponder start soreuseport flag set fails bind exclusively service started you following make go mode shutdown mdnsresponder service info bind addressport application using soreuseport restart mdnsresponder service the mdnsresponder service start bind using soreuseport flag other applications share port next reboot you may need restart applications use bonjour registered old mdnsresponder instance,i want bind multicast dns group port mac os x machine prototype bonjour functionality however i try bind port i get following error incidentally run python socketerror errno address already use it looks like mdnsresponder binds addressport soreuseaddr unset is possible run mdnsresponder way lets agents bind addressport combination,1 i think difficult improve much python lists relatively cheap build append numpy arrays expensive create offer append method so best bet build lists like already coerce nparray time comes a small points it slightly faster use create list call list this tiny amount runtime program feel free ignore point when actually use loop index use variable name document it usually better iterate sequence find length sequence build range index sequence lot you use enumerate get index also need index put together i think slightly improved version but almost unchanged original i think really good improvements reader csvreaderopen somefilecsv header readernext reslist header row reader val enumeraterow reslistiappendfloatval build dict refer column title resultdict dictn reslisti n enumerateheader,i find parsing lots data files usually csv file similar using csv reader loop iterate every line the data usually table floats example reader csvreaderopen somefilecsv header readernext reslist list header line reader rangelenline reslistiappendfloatlinei resultdict dictzipheaderreslist refer column title this ok way populate i get column separate list however i would prefer default data container lists items nested lists numpy arrays since times numbers get pumped various processing scriptsfunctions power numpy lists makes life easier the numpy appendarr item append inplace therefore would require recreating arrays every point table slow unneccesary i could also iterate list datacolumns wrap array i done i sometimes clear cut i done parsing file may need append stuff list later line anyway i wondering lessboilerheavy way use overused phrase pythonic process tables data similar way populate arrays underlying container list dynamically without copying arrays time on another note kind annoying general people use columns organize data csv reads rows reader incorporated readcolumn argument yes i know super efficient i think many people would avoid boiler plate code like parse csv data file,1 if need authenticate one user get access token offlineaccess permission last forever bake script,i writing tabbed application facebook requires background process run server periodically upload images album application page what i trying create script authenticate app b upload image specific album all entirely command line completely new graph api my problem right trying locate documentation allow get token without popup window sorts thoughts,1 beautiful soup another good alternative scraping pdfminer best pdf parser python i found i use pdftxtpy mostly reformat needed,i bunch reports i handcompiling every day taking forever i thinking automating whole process i scraping data html csvxls pdf i mainly scraped data csvhtml php wondering dependable libraries ways grabbing table data pdf php i also started learning python see might good idea try pdfminer conjunction scrapy would better or options please let know thanks,2 if command line access linux server try pdftotext command pdftotext filepdf if lucky get something work depending pdf text may come weird way tables originally formatted experience anyway good luck,i bunch reports i handcompiling every day taking forever i thinking automating whole process i scraping data html csvxls pdf i mainly scraped data csvhtml php wondering dependable libraries ways grabbing table data pdf php i also started learning python see might good idea try pdfminer conjunction scrapy would better or options please let know thanks,1 i say limitationbug osx terminal try running script input via idle see whether still hit problem as better ways dealing large input totally depends requirements ways could import text file create kind guifrontend handle text input via user friendly controls,i wrote python script running terminal mac os x snow leopard using python i used rawinput import text several places i seem reach limit longer accept characters is limit python rawinput something terminal mac osx is better way user input larger amounts text python,1 i think problem regular expressions ttable tcolumn also matching reserved words select from in words select from b tokenizes something like column column column column end ambiguous tokenization match productions get syntax error as quick sanity check change regular expressions match exactly typing like ttable r b tcolumn r you see syntax select from b passes regular expressions b match reserved words and another problem regular expressions table column overlap well lexer tokenize without ambiguity respect tokens either there subtle relevant section ply documentation regarding not sure best way explain trick tokenization pass happens first really use context production rules know whether come across table token column token you need generalize kind id token weed things parse if i energy i try work code provide actual solution code i think since already expressed learning exercise perhaps content pointing right direction,i know tools parse sql statements i rolling educational purposes i getting stuck grammar right if spot error real quick please let know select r select from r from column table r azaz comma r star r end r tignore ignores spaces statement select columns from table end columns star reccolumns reccolumns column reccolumns comma column when i try parse statement like select from b i get syntax error from token any help greatly appreciated edit code usrbinpython import plylex lex import plyyacc yacc tokens select from where table column star comma end tselect r selectselect tfrom r fromfrom twhere r wherewhere ttable r azaz tcolumn r azaz tstar r tcomma r tend r tignore def terrort print illegal character tvalue tlexerskip lexlex none select insert delete update range states none select insert delete update currentstate none def pstatementexprt statement expression print statescurrentstate def pexprselectt expression select columns from table end global currentstate currentstate select print def precursivecolumnst recursivecolumns recursivecolumns comma column joint def precursivecolumnsbaset recursivecolumns column def pcolumnst columns star recursivecolumns def perrort print syntax error tvalue else null global currentstate currentstate none yaccyacc true try input rawinput sql except eoferror break yaccparseinput,2 you try overriding modeladmingetobject add flag instance def getobjectself request objectid superorder selfgetobjectrequest objectid ooldstatus ostatus return now use ostatus ooldstatus savemodel,i need trigger signal form field status updated the signal works fine triggered regardless change submissions form below savemodel override adminpy orderadmin class def savemodelself request obj form change change requestuserissuperuser objorganization requestuser orderisdirty customsignalsnotifystatussendsenderself statusobjstatus objsave here model class orderdirtyfieldsmixin modelsmodel statusoptions pending confirmation pending confirmation confirmed confirmed modified modified placed placed en route en route completed completed cancelled cancelled organization modelsforeignkeyuser relatedname orders default helptext only visible admins status modelscharfieldmaxlength choicesstatusoptions default helptext only visible admins ordername modelscharfieldmaxlength blanktrue helptext optional name order easy reference example munchies contactperson modelsforeignkeycontact helptext this person charge order we may contact himher regarding order deliverydate modelsdatefield delivery day helptext please use yyyymmdd format example,1 you could parse input data using lepl usrbinenv python import ast import fileinput import logging datetime import datetime pprint import pprint string import asciiletters digits lepl import any iterate newline regexp skipto space abnf property name colon pythonliteral name anyasciilettersdigits w colon space amp amp space ss pythonliteral regexpr astliteraleval property name amp colon amp pythonliteral tuple record consists name timestamp one properties abnf record name colon timestamp colon newline indent property timestamp regexpr lambda datetimestrptimes ymd hmsf record name amp colon amp timestamp amp colon amp newline amp space amp property dict tuple file consists one records interlaced newlines abnf file newline record skip unrecognized text upto new line unknown skiptonewline lambda loggingerror unknown r iteraterecord newline unknown consume input one record time itconfignofullfirstmatchnomemoize improve performance iterparse itgetparsefileall output one record time pprintlst lst iterparsefileinputinput lst output jvm datetimedatetime memorystatistics monidata datetimedatetime depth recordssent rdoutdata datetimedatetime depth recordssent rdoutreq datetimedatetime bytesreceived recordsreceived totalrecordsreceived sender datetimedatetime numhitscached numhitsqueued numhitsreceived numreadoutrequestsqueued numreadoutrequestsreceived numreadoutssent sndata datetimedatetime depth recordssent snip pyratebuffermanager datetimedatetime currentaquiredbuffers currentaquiredbytes returnbuffercount,i trying get data text file following format jvm memorystatistics monidata depth recordssent rdoutdata depth recordssent rdoutreq totalrecordsreceived recordsreceived bytesreceived sender numreadoutrequestsreceived numhitsreceived numreadoutssent numhitscached numhitsqueued numreadoutrequestsqueued sndata depth recordssent stringhit depth recordssent stringhub timeoflasthitoutputfromhkn numberofactiveandtotalchannels numberofactivechannels timeoflasthitinputtohkn hitratelc hitrate totallbmoverflows system loadaverage networkio lotxerrs ethrxfifo ethrxpackets ethtxcompressed ethtxcompressed ethtxfifo ethtxpackets lotxcompressed ethrxcompressed lorxerrs ethtxfifo lotxfifo ethtxerrs ethrxmulticast ethtxcarrier ethrxcompressed ethtxdrop lotxdrop ethrxdrop ethtxdrop ethrxbytes ethtxpackets lorxbytes ethrxerrs ethtxerrs ethrxerrs ethtxerrs lorxpackets ethrxcompressed ethrxpackets ethtxdrop ethrxframe ethtxbytes ethrxmulticast ethrxpackets ethtxfifo ethtxerrs ethtxbytes ethrxframe ethrxframe ethrxbytes ethrxdrop ethrxdrop ethrxframe ethtxpackets ethtxbytes ethrxerrs ethrxbytes ethtxcompressed ethrxfifo lotxbytes ethrxerrs ethtxcarrier ethrxpackets lorxdrop ethtxcompressed ethrxfifo ethtxcolls ethtxcolls lotxpackets ethrxmulticast ethtxcolls ethtxfifo ethtxcolls lotxcarrier lorxframe ethrxdrop lotxcolls ethtxbytes lorxfifo ethtxdrop ethtxcarrier ethrxmulticast ethrxcompressed ethrxbytes ethtxcarrier ethtxpackets lorxmulticast lorxcompressed ethrxfifo availablediskspace devshm tcaldata depth recordssent pyratebuffermanager currentaquiredbuffers returnbuffercount currentaquiredbytes i trying get plot time versus various quantities stored file basically i would like get couple arrays similar format timestamp sndatadepth sndatarecordssend i got recommendations people use something like f openfile rreadlines dummy f dummyappendisplitsplit get numbers i trouble getting data sorted properly using categories text see timestamp thanks advance help as requested already used get data usrbinenv python import sys os import numpy np import pylab py def main snrate pyratebuffermanagercabu pyratebuffermanagerrbc pyratebuffermanagercaby endmonilog rangelensysargv file ospathsplitextsysargvi ext ospathsplitextsysargvi print file log ext fopensysargvi ru dummy dummy line f dummy refindall snrate dd line dummy refindall buffer overflow sn record channel line snrateappenddummy print ext moni ext fopensysargvi ru readlines print f timestamp dummy count line f timestamp refindallr ddsdddd line pyratebuffermanager line pyratebuffermanagercabu refindallr sscurrentaquiredbufferssd linecount print pyratebuffermanagercabu pyratebuffermanagerrbc refindallr returnbuffercountss linecount pyratebuffermanagercaby refindallr currentaquiredbytesss linecount timestamplistsettimestamp timestampsort print pyratebuffermanagercabu pyratebuffermanagerrbc print ext,1 to efficiently load data numpy arraya like numpy fromiter function advantages context streamlike loading prespecify data type reesult array preallocate empty output array populated stream iterable the first inherent fromiter accepts data input iterable formthe last two managed second third arguments passed fromiter dtype count import numpy np create data load import random sourceiterable randomchoicerange c range target npfromitersourceiterable dtypenpint countvsize target array dtypeint if want load data using iterable still preallocate memory target array using numpy functions empty emptylike sourcevec nprandomrand target npemptylikesourcevec target sourcevec target array alternatively create empty preallocated array calling empty passing shape want this function contrast emptylike let pass data type target npemptyshapesshape dtypenpfloat target array target source target array,i find parsing lots data files usually csv file similar using csv reader loop iterate every line the data usually table floats example reader csvreaderopen somefilecsv header readernext reslist list header line reader rangelenline reslistiappendfloatlinei resultdict dictzipheaderreslist refer column title this ok way populate i get column separate list however i would prefer default data container lists items nested lists numpy arrays since times numbers get pumped various processing scriptsfunctions power numpy lists makes life easier the numpy appendarr item append inplace therefore would require recreating arrays every point table slow unneccesary i could also iterate list datacolumns wrap array i done i sometimes clear cut i done parsing file may need append stuff list later line anyway i wondering lessboilerheavy way use overused phrase pythonic process tables data similar way populate arrays underlying container list dynamically without copying arrays time on another note kind annoying general people use columns organize data csv reads rows reader incorporated readcolumn argument yes i know super efficient i think many people would avoid boiler plate code like parse csv data file,1 you probably looking iobytesio class it works exactly like stringio except supports binary data io import bytesio bio bytesiobsome initial binary data xx stringio throw typeerror io import stringio sio stringiobsome initial binary data xx,in python use stringio filelike buffer character data memorymapped file basically similar thing binary data requires file used basis does python file object intended binary data memory equivalent java bytearrayoutputstream the usecase i i want create zip file memory zipfile requires filelike object,3 what mean the first sql executes second you get error or data db i assume data database using mysql this commit changes a conncommit end script help,hi i following python c conncursor get account id specific user actidsql select id accounts userid select id authuser username user cexecuteactidsql actid cfetchone print actid fill latencies table currently firing sure latenciessql insert latenciesaccount replier sender replyemail origemail replydate origdate select maccount cid replier cid sender mid replyemail mid origemail mdate replydate mdate origdate contacts c contacts c emails emails mid mid mreply mmid mreply null cid mfr cid mfr maccount maccount maccount actid print latenciessql cexecutelatenciessql the first sql executes second is reason,1 if already using multiple threads epoll offer much additional benefit the point epoll single thread listen activity many file selectors simultaneously respond events occur thus provide eventdriven multitasking without requiring spawning additional threads threads relatively cheap compared spawning processes one require overhead maintain call stack if wanted could rewrite pool processes singlethreaded using epoll would reduce overall thread usage count course consider whether something care general low numbers simultaneous requests worker overhead spawning threads matter want worker able handle open connections overhead become significant epoll shines but what describing sounds suspiciously like basically reinventing wheel main loop request interpreter pool processes sounds almost exactly like nginx load balancerreverse proxy a preforking tornado app tornado singlethreaded web server python module using epoll capability builtin preforking meaning spawns multiple copies separate processes effectively creating process pool tornado based tech created power friendfeed needed way handle huge numbers open connections longpolling clients looking new realtime updates if learning process means reinvent away it great way learn but actually trying build application top kinds things i highly recommend considering using existing stable communallydeveloped projects save lot time false starts potential gotchas ps i approve avatar,i trying write scalable custom web server here i far the main loop request interpreter cython the main loop accepts connections assigns sockets one processes pool processes threads get benefit multicore hardware gil each process thread pool the process assigns socket thread the thread calls recv blocking socket waits data when shows gets piped request interpreter sent via wsgi application running thread now i heard epoll little confused is benefit using epoll get socket data pass directly processes or i go usual route thread wait recv ps what epoll actually used it seems like multithreading blocking fd calls would accomplish thing,3 you definitely trying reimplement sql python i believe would better use relational database run sql queries however regarding question easily let user enter python expressions eval row data this working example uses exec bind column values local variables nasty hack i admit cvs parsing omitted brevity import optparse sys assume csv data read list dictionaries sheet studentid studentfirstname john studentlastname doe studentzipcode studentcommutemethod bus studentid studentfirstname bob studentlastname chen studentzipcode studentcommutemethod bus studentid studentfirstname jane studentlastname smith studentzipcode studentcommutemethod train studentid studentfirstname dave studentlastname burns studentzipcode studentcommutemethod bus options parsing parser optparseoptionparser parseraddoption filter type string dest filter options args parserparseargs filter option required optionsfilter none print sysstderr error filter expression given sysexit process rows build result set result row sheet bind column local variable studentid studentfirstname etc allows evaluating python expressions row example studentcommutemethod bus studentzipcode col val rowiteritems exec col reprval apply filter row evaloptionsfilter resultappendrow print result set row result print row i tested using following filter expressions mypythonscriptpy filter studentcommutemethod bus studentzipcode mypythonscriptpy filter studentcommutemethod bus studentzipcode beware shell quoting rules running program command line,i csv comma separated values file contains student information the column headers look like studentid studentfirstname studentlastname studentzipcode studentheight studentcommutemethod etc subsequent rows contain information individual students now i would like write python script takes filtering condition command line parameter return set students rows match filter condition for example filter condition could something like using pseudo code format studentcommutemethod bus and studentzipcode python script could invoked mypythonscriptpy filter string inputcsv this return list students rows live area zip code commute bus the filter could also arbitrarily complex may include number and or operators questions what best format program could user specify filter condition command line parameter the format simple simple expressions must powerful enough express types conditions the formats i thought sql python language in either case i know python apply filters runtime that i take expression entered command line apply row get true false i would like ui expressing filter condition visual manner perhaps something allows entering simple twooperand condition per row inutive way combine using ands ors it able emit filter expression format decided is open source project i could reuse if think better way solve problem passing command line expression ui feel free mention in end user electrical engineer know lot programming able enter filter expression easily thanks note i control input output format csv files,1 first urlfetch call error passing two parameters function you use two strings pass one url parameter function urlfetchfetchhttpswwwgooevrunpagespeedurlsampkeymykey httpwwwmywebsitedk then tried urlencode second url import urllib yoururl url httpwwwmywebsitedkampkeymykey urlfetchfetchhttpswwwgvrunpagespeeds urlliburlencodeyoururl,im trying request httpswwwgoogleapiscompagespeedonlinevrunpagespeedurlhttpwwwmywebsitedkampkeymykey using urlfetch app engine working when i access hardcode myurl request like httpswwwgoogleapiscompagespeedonlinevrunpagespeedurlhttpwwwmywebsitedkampkeymykey working fine i use urlfetchfetchhttpswwwgoogleapiscompagespeedonlinevrunpagespeedurlsampkeymykey httpwwwmywebsitedk working i also tried pagecontent urlfetchfetch urlhttpswwwgoogleapiscompagespeedonlinevrunpagespeed payloadparams methodurlfetchget serving parameters payload like params urlliburlencode url pagelink key mykey result working service gives http status code i also tried adding urlfetchfetchuhttp pagelink result i edited code based reply systempuntoout incase one run problem params urlliburlencode url pagelink key aizasyafpmwomjqljcmapkvrdgmrriy pagecontent urlfetchfetchhttpswwwgoogleapiscompagespeedonlinevrunpagespeeds params,1 this slight variation danilo suggestion you avoid exec bind variables row passing locals dictionary eval dicts returned csvdictreader work well import csv optparse infile open datafilecsv reader csvdictreaderinfile parser optparseoptionparser parseraddoption filter type string dest filter options args parserparseargs row reader evaloptionsfilter row print row this assumes first line input file column headers headers want use expression valid python identifiers,i csv comma separated values file contains student information the column headers look like studentid studentfirstname studentlastname studentzipcode studentheight studentcommutemethod etc subsequent rows contain information individual students now i would like write python script takes filtering condition command line parameter return set students rows match filter condition for example filter condition could something like using pseudo code format studentcommutemethod bus and studentzipcode python script could invoked mypythonscriptpy filter string inputcsv this return list students rows live area zip code commute bus the filter could also arbitrarily complex may include number and or operators questions what best format program could user specify filter condition command line parameter the format simple simple expressions must powerful enough express types conditions the formats i thought sql python language in either case i know python apply filters runtime that i take expression entered command line apply row get true false i would like ui expressing filter condition visual manner perhaps something allows entering simple twooperand condition per row inutive way combine using ands ors it able emit filter expression format decided is open source project i could reuse if think better way solve problem passing command line expression ui feel free mention in end user electrical engineer know lot programming able enter filter expression easily thanks note i control input output format csv files,1 why simplicity import regx recompile sndata ddddd ddddddd depth recordssent redotall timestamp sndatadepth sndatarecordssend open dataforplottxt f ch fread abc regxsearchchgroups timestampappenda sndatadepthappendb sndatarecordssendappendc print timestamp print sndatadepth print sndatarecordssend result,i trying get data text file following format jvm memorystatistics monidata depth recordssent rdoutdata depth recordssent rdoutreq totalrecordsreceived recordsreceived bytesreceived sender numreadoutrequestsreceived numhitsreceived numreadoutssent numhitscached numhitsqueued numreadoutrequestsqueued sndata depth recordssent stringhit depth recordssent stringhub timeoflasthitoutputfromhkn numberofactiveandtotalchannels numberofactivechannels timeoflasthitinputtohkn hitratelc hitrate totallbmoverflows system loadaverage networkio lotxerrs ethrxfifo ethrxpackets ethtxcompressed ethtxcompressed ethtxfifo ethtxpackets lotxcompressed ethrxcompressed lorxerrs ethtxfifo lotxfifo ethtxerrs ethrxmulticast ethtxcarrier ethrxcompressed ethtxdrop lotxdrop ethrxdrop ethtxdrop ethrxbytes ethtxpackets lorxbytes ethrxerrs ethtxerrs ethrxerrs ethtxerrs lorxpackets ethrxcompressed ethrxpackets ethtxdrop ethrxframe ethtxbytes ethrxmulticast ethrxpackets ethtxfifo ethtxerrs ethtxbytes ethrxframe ethrxframe ethrxbytes ethrxdrop ethrxdrop ethrxframe ethtxpackets ethtxbytes ethrxerrs ethrxbytes ethtxcompressed ethrxfifo lotxbytes ethrxerrs ethtxcarrier ethrxpackets lorxdrop ethtxcompressed ethrxfifo ethtxcolls ethtxcolls lotxpackets ethrxmulticast ethtxcolls ethtxfifo ethtxcolls lotxcarrier lorxframe ethrxdrop lotxcolls ethtxbytes lorxfifo ethtxdrop ethtxcarrier ethrxmulticast ethrxcompressed ethrxbytes ethtxcarrier ethtxpackets lorxmulticast lorxcompressed ethrxfifo availablediskspace devshm tcaldata depth recordssent pyratebuffermanager currentaquiredbuffers returnbuffercount currentaquiredbytes i trying get plot time versus various quantities stored file basically i would like get couple arrays similar format timestamp sndatadepth sndatarecordssend i got recommendations people use something like f openfile rreadlines dummy f dummyappendisplitsplit get numbers i trouble getting data sorted properly using categories text see timestamp thanks advance help as requested already used get data usrbinenv python import sys os import numpy np import pylab py def main snrate pyratebuffermanagercabu pyratebuffermanagerrbc pyratebuffermanagercaby endmonilog rangelensysargv file ospathsplitextsysargvi ext ospathsplitextsysargvi print file log ext fopensysargvi ru dummy dummy line f dummy refindall snrate dd line dummy refindall buffer overflow sn record channel line snrateappenddummy print ext moni ext fopensysargvi ru readlines print f timestamp dummy count line f timestamp refindallr ddsdddd line pyratebuffermanager line pyratebuffermanagercabu refindallr sscurrentaquiredbufferssd linecount print pyratebuffermanagercabu pyratebuffermanagerrbc refindallr returnbuffercountss linecount pyratebuffermanagercaby refindallr currentaquiredbytesss linecount timestamplistsettimestamp timestampsort print pyratebuffermanagercabu pyratebuffermanagerrbc print ext,1 if want functionality need pass base example guy class exampleitem def initself base selfbase base selfbasegetitemexampledosomething want store base call method basegetitemexampledosomething name main base base baseadditemexample baseadditemexample base,how i call method getitemexampledosomething class base inside class example class base items def additemself item selfitemsappenditem def getitemself item return selfitems class item pass class exampleitem def dosomethingself print dosomething class exampleitem def initself how call method getitemexampledosomething name main base base baseadditemexample baseadditemexample,1 as author pywinauto i think going hard time pywinauto really helps standard windows controls i think flash controls implemented standard windows controls buttons edit boxes etc off top head i would think sikuli may better starting point httpsikuliorg another option may httpcodegooglecompflashselenium i googled automating flash input turned one first articles i clicked thanks trying pywinauto i think best suited flash automation,i trying send couple basic text commands flash program running firefox windows i unable get pywinauto working right i able accomplish basic task connecting firefox plugincontainer directing path using following code pywinauto import application app applicationapplication appconnectpath rcprogram files xmozilla firefoxplugincontainerexe the next step seems something effect appplugincontaineredittypekeys text however i reference plugincontainer window using plugincontainer combination words i tried adding title variable connect function i tried everything i think find type command the example i basing notepad sample pywinauto import application appstarturnotepadexe appnotepadedittypekeysuendentersendtext dxfxes usxfcppxfrt xeccexfted characters withspaces true it matter i use pywinauto firefox if easier using different module internet explorer i board whatever accomplishes task i using python version would prefer version changes any help appreciated i pretty lost,2 something like def repeatf n n return lambda x x return lambda x f repeatf nx,i trying write function python like def repeatedf n f function takes one argument n positive integer for example i defined square def squarex return x x i called repeatedsquare would square times,1 that def repeatedf n def rfunp return reducelambda x fx xrangen p return rfun def squarex print squared x return x x print repeatedsquare output square square square square square lambda less def repeatedf n def rfunp acc p xrangen acc facc return acc return rfun,i trying write function python like def repeatedf n f function takes one argument n positive integer for example i defined square def squarex return x x i called repeatedsquare would square times,3 figured removing subtree works fine removing subtree’s root node row notify model path gone conditionally toggling parenthaschild same goes insertion new subtree i need tell model stuff recursively however combination critical first remove notify model insert notify model,i custom generictreemodel works fine now i want user able rearrange nodes using drag drop i move node new parent data model however treemodel wants notified using methods like rowhaschildtoggled rowdeleted rowinserted so apparently rowmoved calling rowdeleted original path rowinserted new path seems enough so i thought i may recursively issue changes consider following example a b c d now i move c a following things happened rowdelete c rowdelete d rowinserted c rowinserted d childtoggle a childtoggle b childtoggle c however gtk still complains inconsistent state model two things come mind maybe order calling functions relevant idea technically childtoggle also happens however row already deleted b rowhaschildtoggled needs treeiter reference i get exist maybe i following totally wrong approach what’s best way go,1 if parameters query beyond in list following extension jg answer may useful ids sql select person types id inids joinmaplambda x ids sql sql inids params paramsappendtype paramsextendids cursorexecutesql tupleparams that join params linear array pass tuple execute method,i problem executing sql within python despite similar sql working fine mysql commandline the table looks like mysql select from foo fooid bar a b c d rows set sec i execute following sql query mysql commandline without problem mysql select fooid from foo where bar in a c select fooid from foo where bar in a c fooid rows set sec however i try within python i get rows i expected rows import mysqldb import config connectionmysqldbconnect hostconfighostuserconfiguserpasswdconfigpassdb test cursorconnectioncursor sql select fooid from foo where bar in args a c cursorexecutesqlargs datacursorfetchall printdata so question python code modified select fooid bar a c by way i noticed i switch roles bar fooid i get code select bar fooid successfully i understand one query works one sql select bar from foo where fooid in args cursorexecutesqlargs datacursorfetchall printdata a c and absolutely clear foo table created mysql drop table if exists foo query ok rows affected sec mysql create table foo fooid int not null autoincrement bar varchar not null primary key fooid query ok rows affected sec mysql insert foo bar values a b c d query ok rows affected sec records duplicates warnings edit when i enable general query log mysqld l tmpmyquerylog i see mysqld version ubuntulog ubuntu started tcp port unix socket varrunmysqldmysqldsock time id command argument connect unutbulocalhost test query set autocommit query select fooid from foo where bar in a c query select bar from foo where fooid in quit indeed looks like many quotes placed around a c thanks amber comment i understand better going wrong mysqldb converts parametrized argument a c a c is way make parametrized query using in sql syntax or must one manually construct sql string,3 have tried setting scaledcontents property true,qlabel image inside qgridlayout form resizes qgridlayout automatically resize qlabel image stretch,1 upgrading python running update shell profile command file located python directory changing python settings netbeans according new installation worked,i getting error every time i run python file eclipse using pydev traceback recent call last file systemlibraryframeworkspythonframeworkversionsextraslibpythonsitepy line module boot file systemlibraryframeworkspythonframeworkversionsextraslibpythonsitepy line boot import sys imp os ospath importerror bad magic number systemlibraryframeworkspythonframeworkversionslibpythonospyc i using python this problem occur i run python terminal the substantial thing i changed since everything last worked update osx lion snow leopard similar discussions seem suggest kind removal pyc file kind mismatch originally using pyc files i entirely sure magic number but i bit cautious idea deleting ospyc frameworks directory when file ospyo file sure difference rather ospy i installed osx lion updates eclipse updates pydev updates this problem occurs even code name main pass any help resolving would appreciated,1 you call open zerytxt r identifier text it text file handler file described filelike object docs i never understood means filelike object way open cdatatxt r f better f open cdatatxt r fclose you read instructions concerning split see open cdatatxt r f text fread wordsall lentextsplit print total words wordsall if structure text p bla bla bla p bla bla bla bla p bla bla p bla wordsparendswithp p p always false hence desired spliting performed consequently wordspar become list remains string characters counted also code certainly wrong if splitting performed would last line obtained first forloop beginning code would repeatedly splitted so instead wordspar lines wordsparstartswithp p p wordspar linesplit certainly line lines line ppp wordspar linesplit,i started learn python question might bit silly i trying create program would import text file got count total number words got count number words specific paragraph starting specific phrase eg p ending another participant p exclude words word count somehow i ended something counts number characters instead print paragraphs separately got exclude p p etc words word count my text files look like p bla bla bla p bla bla bla bla p bla bla p bla i ended code text open r cdatatxt r lines listtext textclose wordsall line lines wordsall wordsall lenlinesplit print total words wordsall wordspar wordspar lines wordsparstartswithp p p amp wordsparendswithp p p wordspar linesplit print lenwordspar print wordsparreplace p display still counts else print no words any ideas improve thanks,1 maybe i understand requirements completely i best the first part counting words quite ok i shorten bit open cdatatxt r textfile lines listtextfile wordsall sumlenlinesplit line lines print total words wordsall in second part something seems go wrong wordspar you leave line wordspar initialized forstatement more problems wordsparstartswithp p p amp wordsparendswithp p p p p p evaluates p nonempty strings truthy values so could shorten line wordsparstartswithp amp wordsparendswithp probably wanted when condition evaluates false splitmethod called wordspar remains string list strings expected so lenwordspar returns number characters instead number words a little disgression names imho error arose inaccurate naming variable a different naming line lines linestartswith wordspar linesplit print lenwordspar would produced clear error message in second reading must meant anyway,i started learn python question might bit silly i trying create program would import text file got count total number words got count number words specific paragraph starting specific phrase eg p ending another participant p exclude words word count somehow i ended something counts number characters instead print paragraphs separately got exclude p p etc words word count my text files look like p bla bla bla p bla bla bla bla p bla bla p bla i ended code text open r cdatatxt r lines listtext textclose wordsall line lines wordsall wordsall lenlinesplit print total words wordsall wordspar wordspar lines wordsparstartswithp p p amp wordsparendswithp p p wordspar linesplit print lenwordspar print wordsparreplace p display still counts else print no words any ideas improve thanks,1 reducelambda ab ab mapsquare range,i trying write function arguments python def sequenceoperation start n term operation function start beginning number sequence n th last number sequence term function manipulates terms sequence for example sequenceadd square would return summation square given def squarex return x x,1 if i understand question correctly need calculate number points first picture different pictures irrespective pictures differ if case unless i missing something simply something like following boolean diffs values set true int original store first pictures color values foreach image images first image int current image store current image color values j diffsij diffsij originalij currentij then left dimensional matrix diffs position indicates corresponding pixel original image differs pictures,there one image ima size xpx images imn x all images black white the task finding minimum number points distinguish first image ima others imn sorry bad english i add img comment the first thing i turned images matrix numpy q file inputimages eachimage ospathjoingeneratorfolder file aqnumpyasarrayimageopeneachimage q bnumpyasarrayimageopentemplateimage byxcolor color list ayxcolor next i use nested comparison nonrecursive search depth point looks something like rangebshape x rangebshape rangebshape x rangebshape rangebshape x rangebshape yyy xxxcontinue check ael rangeashape numpyarrayequalbyxaaelyx numpyarrayequalbyxaaelyx numpyarrayequalbyxaaelyx check break checkreturn unic dots the problem code slow for instance first image different others least five points get comparisons true i use slightly different algorithm allows turn little is way solve problem beautiful brute force update add img line image imn x line template image ima image red marked difference ima xor imn line image blue marked two dots two points comparison image green difference red compare difference yes next image red compare difference no break two points enough say ima differs imn line like line dots line we chose two dots enough say ima differs imn,1 do use sax use elementtree instead xmletree import celementtree et event elem etiterparsepathtoyourfile elemtag page processing elemclear the elemclear call important otherwise keep processed elements memory eventually consume ram the element objects lightweight domlike objects quite easy use compared sax if individual page elements large already fit memory revert sax i assume example many small page elements rather large ones,i xml like example xml page lol lol lel lel page page lol lol lel lel page page lol lol lel lel page xml i need way something like sax code page something parsepage how sax the xml file contains gb data,1 import math def factorialn return mathfactorialn alternative implementation def factorialn return reducelambda xyxyrangen using recursion def factorialn n return else return n factorialn,i trying create function takes one argument number returns factorial number for example f return what i far def productn term return product first n terms sequence term function takes one argument k total k n k total k total termk return total def factorialn return n factorial calling product factorial return productn mul however possible make term takes argument,1 computing factorial n standard example recursive function def facn return n facn n else,i trying create function takes one argument number returns factorial number for example f return what i far def productn term return product first n terms sequence term function takes one argument k total k n k total k total termk return total def factorialn return n factorial calling product factorial return productn mul however possible make term takes argument,1 i fixed installing development libjpeg sudo aptget install libjpegdev then reinstall pil module altogether i using virtual environment work well running python standard,a bit background pil setuppy build pil setup summary version platform linux releasemaint apr gcc tkinter support available jpeg support available zlib pngzip support available freetype support available littlecms support available this ubuntu installation i need pil enable django upload resize various images different formats unfortunately currently process jpegs after performing pil selftestpy came the imaging c module installed i tried importing image imaging using python v interpreter worked pil import image import pil directory pil pilinitpyc matches pilinitpy import pil precompiled pilinitpyc pilimagepyc matches pilimagepy import pilimage precompiled pilimagepyc continues successfully quite import imaging dlopenusrlocallibpythondistpackagespilimagingso import imaging dynamically loaded usrlocallibpythondistpackagespilimagingso so imaging available using python interpreter reason imported properly instances i looking solutions problem last several hours come closer finding one am i missing something stupidly obvious or ideas working thanks advance also i aware httpeffbotorgzonepilimagingnotinstalledhtm demonstrates error provides solution edit i snooping around appears importing imagingmath problem i python vv selftestpy see breaking happened dlopenusrlocallibpythondistpackagespilimagingmathso import imagingmath dynamically loaded usrlocallibpythondistpackagespilimagingmathso the imaging c module installed clear builtin etc etc etc,1 any ideas get started using pickle dynamically updated data store website great in order avoid concurrency issues implement lockfile mechanism hope everything else accesses file respect i strongly suggest use data store supports concurrent access eg database have read httpenwikipediaorgwikiconcurrencycontrol you could start easy sqlite see httpdocspythonorglibrarysqlitehtml,i dictionary containing name email address i seperate py pickle emaildict kilizo infokilizocom aboutgooglecom write python dict file output open origpkl wb pickledumpemaildict output outputclose works pickles original dictionary origpkl then main website pickling deleting old temp amp creating new one tmp ospathisfiletmppkl tmp true osremovetmppkl shutilcopyfileorigpkl tmppkl pickling loading file pklfile open tmppkl rb emaildict pickleloadpklfile pklfileclose i two form inputs website take email address corresponding name processing input emailadded fsgetvalue emailadd nameadded fsgetvalue nameadd emailadded none nameadded none print emailadded print nameadded emaildictnameadded emailadded else print please enter name amp email address output open tmppkl wb pickledumpemaildict output outputclose print emaildict however new data gets stored either tmppkl origpkl any ideas get started thanks,1 def sequenceoperation start n term return reduceoperation mapterm rangestart n the range function python halfopen ie rangestart stop returns list integers start stop so example range therefore solve problem would need rangestart n to apply function term integer range would use builtin function map eg mapsquarerange the final part function requires builtin function reduce takes arguments function iterable optional initial value required instance reduce applies given function first two elements iterable applies function result first calculation third element iterable so example operator import add reduceadd equivalent add add add reduceadd equivalent add add add add add add add add,i trying write function arguments python def sequenceoperation start n term operation function start beginning number sequence n th last number sequence term function manipulates terms sequence for example sequenceadd square would return summation square given def squarex return x x,1 try doctype html body pcreate new userp form actionprocessform methodpost input typetext namelogin valuelogin input typetext nameemail valuemecompanycom input typetext namepassword value input typesubmit form body note final slash processform,i write tiny webapp cherrypy but i problem i get post data get ok hosted local host win viewed opera using cherrypy builtin server here code class expose def initself fn selffn fn cherrypyexpose def indexself loginnone print login strlogin return selffnloginlogin import auth rootprocessform exposeauthprocessform this url switch login prints none form uses post proper value get here form template doctype html body pcreate new userp form actionprocessform methodpost input typetext namelogin valuelogin input typetext nameemail valuemecompanycom input typetext namepassword value input typesubmit form body i guess goes wrong what may i check,3 i think need split string an example tags selfrequestget tags split imgreftagsextendtags imgrefput,following class imagedbmodel author dbuserproperty img dbblobproperty rating dbratingproperty tags dblistproperty user upload image enter list tags choose sperating comma i store database using stringlistproperty listproperty thanks,1 look numpy everything ask see sparse matrix support,two sq matrix b size order x i take difference two matrix c ab resultant matrix c sparse matrix i want find indices nonzero elements i operation many times simplest way use two loops but computationally intensive can tell algorithm packagelibrary preferably rpythonc quickly possible,1 you could use cnonzero method scipysparse import lileye c lileye example c x sparse matrix type type numpyfloat stored elements linked list format cnonzero array dtypeint array dtypeint import numpy np npascontiguousarrayc array dtypeobject you need calculate c matrix find indexes nonzero elements c b could bnonzero nprandomrandomintegers size b nprandomrandomintegers size bnonzero array array b array,two sq matrix b size order x i take difference two matrix c ab resultant matrix c sparse matrix i want find indices nonzero elements i operation many times simplest way use two loops but computationally intensive can tell algorithm packagelibrary preferably rpythonc quickly possible,1 in r use matrix package sparsematrix conversion coordinate list sparse matrix convert back column via tmpx asm dgtmatrix xcol matrixctmpxi tmpxj tmpxval ncol this give coordinates values sparse matrix depending locations nonzero entries a b may find much better work coordinate list sparse matrix representation way dozens sparse matrix representations take direct advantage vectorized operations rather rely upon sparse matrix package perform optimally i tend alternate using coo sparse matrix support different languages depending i get fastest performance algorithm interest update i unaware two matrices a b dense as easiest solution finding nonzero entries c quite simply even subtract first compare entries a b a logical comparison faster subtraction first find entries a b a b subtract entries next simply need convert vectorization indices a b row col representation this similar indsub subind matlab take look r reference calculations,two sq matrix b size order x i take difference two matrix c ab resultant matrix c sparse matrix i want find indices nonzero elements i operation many times simplest way use two loops but computationally intensive can tell algorithm packagelibrary preferably rpythonc quickly possible,2 as point gil often prevents python threads running parallel however always case one exception iobound code when thread waiting io request complete would typically released gil entering wait this means threads make progress meantime in general however multiprocessing safer bet true parallelism required,i writing little crawler fetch url multiple times i want threads run time simultaneously i written little piece code import thread urllib import request urlopen urlerror httperror def getpagefetchaddress attempts attempts req requestfetchaddress none try response urlopenreq timeout fetching url print fetched url fetchaddress except httperror e print the server request print error code strecode address fetchaddress timesleep attempts except urlerror e print failed reach server print reason strereason address fetchaddress timesleep attempts except exception e print something bad happened gatpage print reason strereason address fetchaddress timesleep attempts else try return responseread except error responseread return none return none url httpwwwdomaincom range threadstartnewthreadgetpage url apache logs seems like threads running simultaneously little gap requests almost undetectable i see threads really parallel i read gil way bypass calling cc code i really understand threading possible gil python basically interpreters next thread soon finishes previous one thanks,2 i read gil way bypass calling cc code not really functions called ctypes release gil duration calls functions perform blocking io release there similar situations always involve code outside main python interpreter loop you let go gil python code,i writing little crawler fetch url multiple times i want threads run time simultaneously i written little piece code import thread urllib import request urlopen urlerror httperror def getpagefetchaddress attempts attempts req requestfetchaddress none try response urlopenreq timeout fetching url print fetched url fetchaddress except httperror e print the server request print error code strecode address fetchaddress timesleep attempts except urlerror e print failed reach server print reason strereason address fetchaddress timesleep attempts except exception e print something bad happened gatpage print reason strereason address fetchaddress timesleep attempts else try return responseread except error responseread return none return none url httpwwwdomaincom range threadstartnewthreadgetpage url apache logs seems like threads running simultaneously little gap requests almost undetectable i see threads really parallel i read gil way bypass calling cc code i really understand threading possible gil python basically interpreters next thread soon finishes previous one thanks,1 what import operator def productnums return reduceoperatormul nums def factorialnum return productrange num,i trying create function takes one argument number returns factorial number for example f return what i far def productn term return product first n terms sequence term function takes one argument k total k n k total k total termk return total def factorialn return n factorial calling product factorial return productn mul however possible make term takes argument,1 since two dense matrices double loop option you need sparse matrix class since want know list indices ij aij bij in languages like r python double loop perform poorly i probably write native code double loop add indices list object but doubt wizards interpreted code ie r python etc know efficient ways without resorting native coding,two sq matrix b size order x i take difference two matrix c ab resultant matrix c sparse matrix i want find indices nonzero elements i operation many times simplest way use two loops but computationally intensive can tell algorithm packagelibrary preferably rpythonc quickly possible,2 you already python code creates foos lets call populatefoos somehow program call now next thing need storefoos loadfoos function saving loading if want keep generic define storefunc loadfunc callback depending context depending program structure might also need keep python list foos created associated container,in c i following two classes i expose using boost python struct foo empty struct foocontainer i use boostsharedptr compatibility boostpython vectorboostsharedptrfoo foos in python side i might create special type foo actually something instead empty class add foocontainer class usefulfoo def initself b selfa selfb b x useful add x foocontainer back c side foocontainer foos know care python the application runs data foo objects changes then i decide i want save state program i load later time but problem foocontainer know much foo objects even know come python i want pollute foocontainer data really belong singleresponsibility principle do advice i organize application saving loading data well loading fresh data ie state i saved past done clear way,1 have look mediainfo handles formats if looking way parse output ffmpeg use regexp dxd example using perl ffmpeg testgp amp perl lane print dxd x example using python perfect ffmpeg nfshomeenilfrepubtestgp amp python c import sysresysstdoutwritestrrefindallr dxd line line sysstdin x python oneliners catchy perl ones,how would i get height width video ffmpeg information output for example following output ffmpeg videomp input movmpmagpgmj usersdaviddesktopvideomp metadata majorbrand isom minorversion compatiblebrands isomavc creationtime duration start bitrate kbs stream und video h high yuvp x par dar kbs fps tbr k tbn tbc metadata creationtime stream und audio aac hz stereo kbs metadata creationtime at least one output file must specified how would i get height width thank,3 take look osname the name operating system dependent module imported the following names currently registered posix nt os ce java riscos there also sysplatform osuname require finer granularity,i writing posixspecific code although i supporting platforms i like make sure get nice clear error import time rather strange errors tried use code is neat way check i guess i could import posix catch importerror seems kind verbose,3 this code takes less matrixrpoisncol lapplyseqncolmfunctionx whichmx edit for sparse matrices size fits memory data librarydatatable n e n e ta datatablersampleseqn nreplacetrue csampleseqn nreplacetrue asamplenreplacetrue tb datatablersampleseqn nreplacetrue csampleseqn nreplacetrue bsamplenreplacetrue setkeytarc setkeytbrc code systemtimetw tatbisnaaisnabab listrrcc,two sq matrix b size order x i take difference two matrix c ab resultant matrix c sparse matrix i want find indices nonzero elements i operation many times simplest way use two loops but computationally intensive can tell algorithm packagelibrary preferably rpythonc quickly possible,1 def isposix try import posix return true except importerror return false you also parse sysplatform osuname i think natural ask system feature rather system one i know feature,i writing posixspecific code although i supporting platforms i like make sure get nice clear error import time rather strange errors tried use code is neat way check i guess i could import posix catch importerror seems kind verbose,1 the script linked create selfsigned certificate creates request to create selfsigned certificate could use openssl available major oses openssl req new x key privkeypem cacertpem days if like using mcrypto take look xtestcasetestmkcert method,i trying generate self signed ssl certificates using python platform independent my target pem format i found script generates certificates information selfsign,2 you use approach like create threads wait condition object start fetching url simultaneously usrbinenv python import threading import datetime import urllib allgo threadingcondition class threadclassthreadingthread def runself allgoacquire allgowait allgorelease print sn selfgetname datetimedatetimenow url urlliburlopenhttpwwwibmcom range threadclass tstart allgoacquire allgonotifyall allgorelease this would get bit closer fetches happen time but the network packets leaving computer pass along ethernet wire sequence time even cores machine router bridge modem equipment machine web host likely fewer cores may serialize requests the web server fetching stuff use accept call respond request for correct behavior implemented using serverglobal lock ensure one server processthread responds query even requests arrive server simultaneously cause serialisation you probably get requests overlap greater degree ie others starting finish never going get requests start simultaneously server,i writing little crawler fetch url multiple times i want threads run time simultaneously i written little piece code import thread urllib import request urlopen urlerror httperror def getpagefetchaddress attempts attempts req requestfetchaddress none try response urlopenreq timeout fetching url print fetched url fetchaddress except httperror e print the server request print error code strecode address fetchaddress timesleep attempts except urlerror e print failed reach server print reason strereason address fetchaddress timesleep attempts except exception e print something bad happened gatpage print reason strereason address fetchaddress timesleep attempts else try return responseread except error responseread return none return none url httpwwwdomaincom range threadstartnewthreadgetpage url apache logs seems like threads running simultaneously little gap requests almost undetectable i see threads really parallel i read gil way bypass calling cc code i really understand threading possible gil python basically interpreters next thread soon finishes previous one thanks,1 the first part ok get total words print result where fall wordspar wordspar lines wordsparstartswithp p p amp wordsparendswithp p p wordspar linesplit print lenwordspar print wordsparreplace p display still counts else print no words the wordspar first string containing line file under condition never meet turned list linesplit expression this expression wordsparstartswithp p p amp wordsparendswithp p p ever return true would always splitting last line file due last time assigned first part program full count number words file that really wordsparsplit also wordsparstartswithp p p always wordsparstartswithp since p p p always evaluates first one true first string case read httpdocspythonorgreferenceexpressionshtml want know while unless wanting bitwise comparisons avoid something amp something instead something something the first evaluate expressions matter result first second evaluate second expression first true if code operate little efficiently the print lenwordspar next line always going counting number characters line since statement always going evaluate false wordpar never got split list words also else clause loop always executed matter whether sequence empty have look httpdocspythonorgreferencecompoundstmtshtmltheforstatement information i wrote version i think example according i think want i tried keep simple avoid using things like list comprehension since say starting learn optimal hopefully clear also note i made comments feel free hassle explain things words none open datatxt f words freadsplit totalwords lenwords print total words totalwords inpara false paracount paratype none paragraph list word words p word p word p word inpara false inpara true paratype word else print words paragraph paratype paracount print joinparagraph paracount del paragraph paratype word else paragraphappendword paracount else inpara true print words last paragraph paratype paracount print joinparagraph else print no words edit i actually noticed redundant code example the variable paracount needed since words appended paragraph variable so instead print words paragraph paratype paracount you could print words paragraph paratype lenparagraph one less variable keep track here corrected snippet inpara false paratype none paragraph list word words p word p word p word inpara false inpara true paratype word else print words paragraph paratype lenparagraph print joinparagraph del paragraph paratype word else paragraphappendword else inpara true print words last paragraph paratype lenparagraph print joinparagraph else print no words,i started learn python question might bit silly i trying create program would import text file got count total number words got count number words specific paragraph starting specific phrase eg p ending another participant p exclude words word count somehow i ended something counts number characters instead print paragraphs separately got exclude p p etc words word count my text files look like p bla bla bla p bla bla bla bla p bla bla p bla i ended code text open r cdatatxt r lines listtext textclose wordsall line lines wordsall wordsall lenlinesplit print total words wordsall wordspar wordspar lines wordsparstartswithp p p amp wordsparendswithp p p wordspar linesplit print lenwordspar print wordsparreplace p display still counts else print no words any ideas improve thanks,1 what want research instead refindall this trick even oneliner bit ugly tmpp sample data gave cat tmpp amp python c import resys print researchr dxd sysstdinreadgroup x any reason using grep egrep case cat tmpp egrep x x,input ffmpeg testgp ffmpeg version unknown copyright c ffmpeg developers built may gcc configuration libavutil libavcodec libavformat libavdevice libavfilter libswscale input movmpmagpgmj testgp metadata majorbrand gp minorversion compatiblebrands gp creationtime duration start bitrate kbs stream und audio aac hz stereo kbs metadata creationtime stream und video mpeg yuvp x par dar kbs fps tbr k tbn tbc metadata creationtime at least one output file must specified let say i would like extract width amp height using following regexp dxd using perl i something like ffmpeg testgp amp perl lane print dxd x then i tried construct similar python oneliner sortof works perfectly ffmpeg testgp amp python c import sysresysstdoutwritestrrefindallr dxd line line sysstdin x what python oneliner looks like corresponds perl one,3 when run python script terminal terminal likely encoded utf specially using linux mac when set l variable string latin characters string encoded default encoding using terminal l utf script wont crash a little tip string encoded latin want unicode variabledecode latin,i python program running well it connects several websites outputs desired information since websites encoded utf i requesting charset headers using unicodestring encoding method decode i sure whether appropriate way works pretty well when i run python program i receive marks works fine but i run program using php system function i receive error unicodeencodeerror ascii codec encode character u u position ordinal range this python specific error confuses i receive error i run program using terminal i receive i use php system function call program php what may cause behind problem here sample code php code calls python program systempython somefilepy search search variable coming input python code encoding iso l string latin characters print unicodediv class line sdiv l encoding i run code terminal works perfect i receive marks i run code php i receive error,1 cat sampletxt python c import sysre print n joinrefindallr dxd sysstdinread x,input ffmpeg testgp ffmpeg version unknown copyright c ffmpeg developers built may gcc configuration libavutil libavcodec libavformat libavdevice libavfilter libswscale input movmpmagpgmj testgp metadata majorbrand gp minorversion compatiblebrands gp creationtime duration start bitrate kbs stream und audio aac hz stereo kbs metadata creationtime stream und video mpeg yuvp x par dar kbs fps tbr k tbn tbc metadata creationtime at least one output file must specified let say i would like extract width amp height using following regexp dxd using perl i something like ffmpeg testgp amp perl lane print dxd x then i tried construct similar python oneliner sortof works perfectly ffmpeg testgp amp python c import sysresysstdoutwritestrrefindallr dxd line line sysstdin x what python oneliner looks like corresponds perl one,1 what binasciiunhexlifyhexstr see docs binascii module httpdocspythonorglibrarybinasciihtml,i hex stream like abcdefg longer i want split char hex values list convert ascii,3 one liner abc print joinchrintai ai xrange lena explanation xrange lena gives alternating indecis string ai ai pair characters string int string interpreted hex number chr character corresponding given hex number join obtain single string sequence characters,i hex stream like abcdefg longer i want split char hex values list convert ascii,1 import os thisfile mysequencefasta base ospathsplitextthisfile osrenamethisfile base aln where thisfile absolute path file changing,suppose indexpy post file fasta display file i want change fasta file extension aln display file how i working right python cgi thanks listening,3 you think function yield simply pauses comes across yield the next time call resume yield keeping state left,i reading yield keyword python trying understand running sample def countfromn true print yield yield n n print yield countfrom print enter loop print else break the output yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop it looks like yield return specified value continue runnning function till end parallel thread maybe is understand correct if could answer without mentioning generators i would thankful i trying understand one time,3 no single thread each iteration loop runs countfrom function yields something returns after yield body loop runs new iteration starts countfrom function picks exactly left runs yields returns this modified version example helpfully make clearer path execution takes def countfromn n print yield n n yield n n print yield n n countfrom print enter loop print print end loop iteration output yield n enter loop end loop iteration yield n yield n enter loop end loop iteration yield n yield n enter loop end loop iteration yield n,i reading yield keyword python trying understand running sample def countfromn true print yield yield n n print yield countfrom print enter loop print else break the output yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop it looks like yield return specified value continue runnning function till end parallel thread maybe is understand correct if could answer without mentioning generators i would thankful i trying understand one time,2 the function countfrom run parallel thread what happens whenever construct asks next value function execute hits yield statement when next value required function resumes execution left and asked mention generators intimately linked yield really make sense talk separately what countfrom function actually returns generator object it returns object immediately called function body executed something eg loop requests values generator using method next,i reading yield keyword python trying understand running sample def countfromn true print yield yield n n print yield countfrom print enter loop print else break the output yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop it looks like yield return specified value continue runnning function till end parallel thread maybe is understand correct if could answer without mentioning generators i would thankful i trying understand one time,1 from printfails wiki when python finds output attached terminal sets sysstdoutencoding attribute terminal encoding the print statement handler automatically encode unicode arguments str output this program works called terminal when python detect desired character set output sets sysstdoutencoding none print invoke ascii codec this program fails called php to make work called php need make explicit encoding print use for example make explicit want output encoded utf attached terminal encoding sysstdoutencoding sysstdoutencoding else utf print unicodediv class line sdiv l encodingencodeencoding alternatively could set pythonioencoding environment variable then code work without changes terminal called php,i python program running well it connects several websites outputs desired information since websites encoded utf i requesting charset headers using unicodestring encoding method decode i sure whether appropriate way works pretty well when i run python program i receive marks works fine but i run program using php system function i receive error unicodeencodeerror ascii codec encode character u u position ordinal range this python specific error confuses i receive error i run program using terminal i receive i use php system function call program php what may cause behind problem here sample code php code calls python program systempython somefilepy search search variable coming input python code encoding iso l string latin characters print unicodediv class line sdiv l encoding i run code terminal works perfect i receive marks i run code php i receive error,1 there simple approximation problem worked fine define grid for instance pixel grid writes xy intxinty the grid elements overlap either put object different grid randomly inside grid look prettier either put randomly objects grid allow objects overlap i used randomly generate d map zelda like my objects images smaller i used grid size allowed objects grid,i working d games pygame i need place several objects time randomly without intersecting i tried obvious methods work obvious methods follow pseudo create list objects object list object list object collides object create new list objects that method took forever other method i tried create list objects object list object list object collides object remove object list that method returned near empty lists i dealing list anywhere objects large any suggestions edit the rectangles random different sizes,1 cannot explain meaning yield statement without mentioning generators would like trying explain stone without mentioning rock that yield statement one responsible transform normal function generator while find well documented httpdocspythonorgreferencesimplestmtshtmltheyieldstatement brief explaination when function using yield statement called returns generator iterator next method standard iterable objects each time next method generator called eg iterating object loop function called first yield encountered then function execution paused value passed return value next method the next time next called function execution resumed next yield etc function returns something some advantages less memory usage since memory allocated currently yielded value whole list returned values would returning list values realtime results return produced passed caller without waiting generation end used return output running process,i reading yield keyword python trying understand running sample def countfromn true print yield yield n n print yield countfrom print enter loop print else break the output yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop yield yield enter loop it looks like yield return specified value continue runnning function till end parallel thread maybe is understand correct if could answer without mentioning generators i would thankful i trying understand one time,2 replace sliceaxis slice sliceaxis slice none sliceaxis slicenone d equivalent f f by sliceaxis slice sliceaxis slice sliceaxis slicenone d equivalent f f left differences sliceaxis slice sliceaxis slice none sliceaxis slice d equivalent f f right one numpygradient function and remove statement outslice fslice fslice,use numpygradient working left right it works default central difference thanks lot,1 of course mock queryset mock anything you create object give interface need return data like at heart mocking nothing providing test double acts enough like real thing tests purposes the lowtech way get started define object class mockquerysetobject pass create one hand test the test fail likely attributeerror that tell need implement mockqueryset repeat object rich enough tests,i utility function django project takes queryset gets data returns result i like write tests function is anyway mock queryset i like create object touch database provide list values use ie fake rows act like queryset allow someone field lookups itfiltergetall etc does anything like exist already,3 in python x use binasciiunhexlify import binascii binasciiunhexlify abcdef xabxcdxefxegx in python elegant method using builtin bytes type bytesfromhex abcdef b xabxcdxefxegx,i hex stream like abcdefg longer i want split char hex values list convert ascii,2 you get number head revision like follows client pysvnclient headrev clientinfosvnurlrevisionnumber then need define revisions according way want fromrevision pysvnrevisionpysvnoptrevisionkindnumber headrev torevision pysvnrevision pysvnoptrevisionkindhead finally use log output list inside loop extract info want l log print idate print iauthor,i using pysvn monitor changes subversion directory this get informations revisions svnroot httpsvn client pysvnclient fromrevision pysvnrevisionpysvnoptrevisionkindnumber torevision pysvnrevision pysvnoptrevisionkindhead revisions clientlogsvnroot torevision torevision discoverchangedpathstrue now i want get changes specific revision like example changes within last revisions head head how i accomplish how get number head revision i could calling shell python but i guess pythonic way using pysvn,2 i timed simplest code allindices c arrindt,two sq matrix b size order x i take difference two matrix c ab resultant matrix c sparse matrix i want find indices nonzero elements i operation many times simplest way use two loops but computationally intensive can tell algorithm packagelibrary preferably rpythonc quickly possible,1 have tried running inside screen session screen l sudo python webserverpy,i wrote simple http server python manage database hosted server via web ui it perfectly functional works intended however one huge problem stay put it work hour left unused long periods time returning use i reinitialize every time right method i use make serve def main global db db dblocalhost server httpserver myhandler print started httpserver serverserveforever name main main i run background linux server i would run command like sudo python webserverpy amp detach i mentioned previously quits any advice appreciated cause stands i see shuts,1 you write unix daemon python using pythondaemon package windows service using pywin unfortunately i know portable solution writing daemon service processes python otherwise,i wrote simple http server python manage database hosted server via web ui it perfectly functional works intended however one huge problem stay put it work hour left unused long periods time returning use i reinitialize every time right method i use make serve def main global db db dblocalhost server httpserver myhandler print started httpserver serverserveforever name main main i run background linux server i would run command like sudo python webserverpy amp detach i mentioned previously quits any advice appreciated cause stands i see shuts,2 here one piece advice story driving you certainly want drive safely figure program failing fix in rare case crash monitoring infrastructure like monit helpful restart crashed processes you probably want use paper crash like want deploy air bag every time stopped car,i wrote simple http server python manage database hosted server via web ui it perfectly functional works intended however one huge problem stay put it work hour left unused long periods time returning use i reinitialize every time right method i use make serve def main global db db dblocalhost server httpserver myhandler print started httpserver serverserveforever name main main i run background linux server i would run command like sudo python webserverpy amp detach i mentioned previously quits any advice appreciated cause stands i see shuts,1 you need mode l however looks like pil mode l hardcoded filec loading pgm you’d write decoder want able read bit pgm however bit image support still seems flaky im imagefromstring i xcaxfe raw i imgetcolors traceback recent call last file stdin line module file usrlibpythondistpackagespilimagepy line getcolors return selfimgetcolorsmaxcolors valueerror image wrong mode i think pil capable reading images bits actually storing manipulating still experimental im imagefromstring l xcaxfe raw l im imageimage image model sizex xb imgetcolors see interpreted xcafe value xfe isn’t exactly correct,i bit pgm images i trying read python it seems like pil support format import image im imageopen testpgm imshow shows roughly image right there dark bands throughout img reported model i think related early question i bit tiff files is bit rare pil support any advice i read bit pgm files python using pil another standard library homegrown code,2 since know types want convert probably get performance boost trying optimize conversions the poor performance probably comes repeatedly iterating errordata if possible reconstruct errordata list set exploit nature type errorset seterr none err errordata then proceed further improvements would require profiling code actually determine time spent,i list values strings i want convert values respective datatypes i mapping values types information available there three different datatypes int str datetime the code needs able handle error cases data i something like tlist datetime value string convert datetime object string errordata lambda x datetimestrptimex x errordata else x lambda x intx x errordata else lambda x x result dij j enumeratetlist the list convert long like values i need thousands lists the performance code poor what fastest way thank,1 tcl sensitive whitespace much like bourne shell you probably want source distcl instead sourcedistcl,i want able run tcl script python script specifically i want run tcl script much like i knowledge python none tcl i trying things like import tkinter rtkintertk rcall sourcedistcl rtkeval sourcedistcl any ideas would access things tcl script thanks,1 retrieving remote resources usually bound bandwidth ftp protocol decent job using are sure saturating network connection network link client running ftplib server downloading back envelope calc gbmins mbsec mbps so downloading megabit that decent speed remote dslcablewan connection obviously pretty low local network,i trying retrieve lines file ftp connection using ftplib module python it takes mins read file size gb i wondering ways read lines faster manner i included code show i ftphostname xxx ftpuserid xxx ftpconnretrlines retr filename process,1 something like values bcd types int int str float defaults int float res v f itertoolsizipvalues types just use zip python try resappendfv except valueerror resappenddefaultsf printres bcd edit this handle datetime values my solution use str convert datetime loop like res datetimestrptimeres both getting setting list item o complexity problem,i list values strings i want convert values respective datatypes i mapping values types information available there three different datatypes int str datetime the code needs able handle error cases data i something like tlist datetime value string convert datetime object string errordata lambda x datetimestrptimex x errordata else x lambda x intx x errordata else lambda x x result dij j enumeratetlist the list convert long like values i need thousands lists the performance code poor what fastest way thank,1 if datetime value always consistant let type casting handle invalid data trying manage errordata this sexy solutions makes managing type conversion based position data list little easier maintain expand upon def convertposition val position try return datetimestrptimeval ymd hms assuming date constant format except valueerror return val elif position assuming int values columns try return intval except valueerror return else string type return val result convertij j enumeratetlist,i list values strings i want convert values respective datatypes i mapping values types information available there three different datatypes int str datetime the code needs able handle error cases data i something like tlist datetime value string convert datetime object string errordata lambda x datetimestrptimex x errordata else x lambda x intx x errordata else lambda x x result dij j enumeratetlist the list convert long like values i need thousands lists the performance code poor what fastest way thank,1 there incongruity code elements list strings write datetimex x string edit it depicts nothing since incongruous the complexity code justify weirdness code as long explain pass string argument function datetimedatetime nobody able help imo edit i think better create directly list moment file read i wrote example first i created csv file following code import csv random import randintchoice time import gmtime xx whose birth infant william dearest rooms find deserts saucy his considerate houses fanny dispense early words thus pettish worth def genn xrangen yield aaaa ddd ddd gmtimerandint yield bbbb randint yield cccc choicexx open zzztxt wb f writ csvwriterf delimiter writwriterowsx x gen the structure csv file aaaa bbbb ccccdearest aaaa bbbb cccc aaaa bbbb ccccinfant aaaa bbbb cccc aaaa bbbb ccccfind aaaa bbbb ccccfind aaaa bbbb ccccrooms aaaa bbbb cccc aaaa bbbb ccccwilliam etc the following code extracts data similar way want there need dictionary tuple sufficient given structure csv file created i defined funcs todt int lambda x x use succession functions dictionary values sorted import import csv datetime import datetime itertools import izip reg recompile ddddd dddddd def todtx errordata x errordata return x else return datetimemapintregmatchxgroups def tegerx errordata x errordata return else return intx funcs todt int lambda open zzztxt rb f rid csvreaderf delimiter li fctx fctx izipfuncsrid display strel el linext print n join ititit xrange result dearest infant find find rooms william william deserts william whose dearest william rooms find etc,i list values strings i want convert values respective datatypes i mapping values types information available there three different datatypes int str datetime the code needs able handle error cases data i something like tlist datetime value string convert datetime object string errordata lambda x datetimestrptimex x errordata else x lambda x intx x errordata else lambda x x result dij j enumeratetlist the list convert long like values i need thousands lists the performance code poor what fastest way thank,1 well first step figure crashing there two likely possibilities the serveforever call throwing exception the python process crashingbeing terminated in former case make live forever wrapping loop tryexcept probably good idea log error details the latter case bit trickier could caused variety things does happen run script foreground if maybe kind maintenance service running terminating script not really complete answer perhaps enough help diagnose problem,i wrote simple http server python manage database hosted server via web ui it perfectly functional works intended however one huge problem stay put it work hour left unused long periods time returning use i reinitialize every time right method i use make serve def main global db db dblocalhost server httpserver myhandler print started httpserver serverserveforever name main main i run background linux server i would run command like sudo python webserverpy amp detach i mentioned previously quits any advice appreciated cause stands i see shuts,1 to convert proper csv file keys header row something like data string containing json import json csv import dictwriter dicts jsonloadsdata thefile opensamplecsv w writer dictwriterthefile dictskeys writerwriteheader writerwriterowsdicts thefileclose note python simplejson included standard library json,i python script retrieves data api json format least i think json format i want loop object write csv file here data returned api bidswon partnerrevenue profit campaignid test postclickconversions totalcost totalmediacost postviewconversions adjustedpartnercost clicks day august bidswon partnerrevenue profit campaignid test postclickconversions totalcost totalmediacost postviewconversions adjustedpartnercost clicks day august how i loop objects write csv file my current attempt loop results script interating letter appreciate help ps i using python,2 remove script dailybasicpy url dailybasic script dailybasicpy login admin,i coding gae python i tried make two script files so i make appyaml like application mathgirlna version runtime python apiversion handlers url static staticdir static url dailybasic script dailybasicpy login admin url script mainpy and i see logs says file referenced handler found dailybasicpy i idea appyaml written here file tree static indexcss appyaml indexyaml cronyaml indexhtml mainpy dailybasicpy i also hesitating tree should i move files and last i installed python library ssl could reason error,3 i would generally refrain putting nonascii encoded characters source code despite fact python interpreter honor source file utf header problem dumb meaning non utf aware text editors shells oses developers eventually corrupt carefully crafted unicode strings i would stay ascii character set source file since pretty much universally supported everywhere thus run source code corruption you almost unicode escaped string in python simply need put u front ie u sociuetue otherwise python would treat characters literal characters rather intended unicode escape characters an easy way test correctness unicode encoded string binary string string without u front fire python interpreter print print sociuetue sociuetue ewwwwwww print u sociuetue sociã©tã© yay note for test shell better support utf logged locally mac probably otherwise print output gibberish that fine well correct gibberish meaning input string formatted ideal sense unless middleware methods properly dealing unicode view function rendering django properly output unicode string fine btw good practice prefix strings u u test good test the difference string manipulation operations involving unicode designated string u test tell python unicode aware yes python sense defaults unicode dumb just like text editors u magic sauce,i trying send latin characters 㩠㨠client side using django i get work in django i tried write directly latin characters python files i errors i used unicode writing sociuetue sociã©tã© sending client side i get raw unicode characters can anybody help julien,1 ossystem cause subprocesspopen but i think using subprocesscall best choice commands pdflatex bibtex pdflatex pdflatex command commands subprocesscallcommand srcfile,i trying build latex document using python problems getting commands run sequence for familiar latex know usually run four commands completing running next eg pdflatex file bibtex file pdflatex file pdflatex file in python i therefore define commands commands pdflatex bibtex pdflatex pdflatex commands element srcfile element commands problem running i tried suss things thread ndash eg using ossystem loop subprocess stuff like mapcall commands popen collapsing list single string separated amp ndash seems like commands run separate processes without waiting previous one complete for record i windows would like crossplatform solution edit the problem bug speciyfing srcfile variable tex the following code works testpy import subprocess commands pdflatex bibtex pdflatex pdflatex command commands subprocesscallcommand test testtex documentclassarticle usepackagenatbib begindocument this test citepbody bibliographystyleplainnat bibliographyrefs enddocument refsbib bookbody authorne body titleintroductory widgets publisherwidgets international year,3 i would suppose commands starting cli client backend so chance would file reading executing queries ie python,this might obvious error i trying create database within python script i already created conn sqliteconnect testdb c conncursor cexecute read createsql this gives error sqliteoperationalerror near syntax error if i thing sqlite cmd line works fine memypc sqlite testdb sqlite version enter help instructions sqlite read createsql sqlite it seems commands start give problems,1 did see httpsteamcommunitycomdev steam web api documentation valve provides apis website developers use data steam new interesting ways they allow developers query steam information present sites at moment apis offer provide item data team fortress list grow time,i looking method get steam users status this includes things like game playing online offline i originally going scrape page i figured must easier way i looked around pages might json users current status perhaps even api but i found anything yet any answers would appreciated thanks much rlr,1 the simple answer question usage argparseargumentparserparseknownargs method this parse arguments wrapping script knowns ignore others here something i typed based code supplied coding utf import argparse def main parser argparseargumentparser subparsers parseraddsubparsersdest command help commands vcs subparsersaddparser vcs help control vcs vcsmain vcsaddsubparsersdest vcscommand help vcs commands vcscommit vcsmainaddparser commit helpcommit changes new revision vcscheckout vcsmainaddparser checkout helpcreate new checkout existing branch args otherargs parserparseknownargs argscommand vcs argsvcscommand commit printcall wrapped command print bzr commit joinotherargs elif argsvcscommand checkout printcall wrapped command print bzr checkout joinotherargs return name main main,script i try wrap bazaar executable when i read certain options meant bzr script react in case arguments given bzr executable of course i want specify arguments bzr handle inside script so way handle unknown amount arguments argpase my code currently looks like parser argparseargumentparserhelp vcs subparsers parseraddsubparsershelp commands vcs subparsersaddparser vcs help control vcs epilog arguments directly passed bzr vcsmain vcsaddsubparsershelp vcs commands vcscommit vcsmainaddparser commit helpcommit changes new revision vcscommitaddargument bzrcmd action store nargs help arugments meant bzr vcscheckout vcsmainaddparser checkout helpcreate new checkout existing branch the nargs option allows many arguments i want course but another unknown optional argument like fixes unchanged,2 start steam web api i think looking work getplayersummaries,i looking method get steam users status this includes things like game playing online offline i originally going scrape page i figured must easier way i looked around pages might json users current status perhaps even api but i found anything yet any answers would appreciated thanks much rlr,1 basically need following steps get distinct club types for club type select clubs include type also see sort selection alphabetically there many ways achieve i would recommend putting logic template simple fact expressing logic behind probably easier view custom manager get adventurous later django life an example warning untested code step clubtypes clubtypesobjectsdistinct step amp clubsets currentclubtype clubtypes cset clubsobjectsfilterclubtypeidcurrentclubtypepkorderby name clubsetsappendcurrentclubtype cset what left end list club type lists sorted name form clubtype club club clubtype club club,i list organizations full different organization types i table holds name phone etc another table id fixed organization type then table holds many many relationship organization many different organization types what i wanting list clubs alphabetically fall every organizational type i sure needs done viewspy done template file here models class clubtypemodelsmodel name modelscharfieldmaxlength def unicodeself return selfname class clubmodelsmodel name modelscharfieldmaxlength verbosename club organization name createddate modelsdatetimefield autonowadd true updateddate modelsdatetimefield autonow true autonowadd true clubtype modelsmanytomanyfieldclubtype username modelscharfieldmaxlength blank true null true contactname modelscharfieldmaxlength blank true null true phonenumber modelscharfieldmaxlength blank true null true def unicodeself return selfname class meta ordering name i noob python django help would greatly appreciated thanks,2 your problem likely iobound computational parallelization help as seen probably making problem worse requiring io requests jump back forth various threadsprocesses there practical limits fast move data computer especially disk involved,i writing python code copy bunch big filesfolders one location location desktop network everything local i using shutil module but problem takes time i want speed copy process i tried using threading multiprocessing modules but surprise taking time sequential code one observation time required increases increase number processes number folders what i mean suppose i following directory structure aa aa bb bb if i create processes copy folders b time taken suppose minutes now i create processes copy folders aa aa bb bb takes around minutes i tried multiprocessing sure threading i sure going would one similar problem are best practices share use multiprocessingthreading python thanks abhijit,3 you could use enumerate compare counter length list formdata enumeratestephashes lenstephashes whatever,i template i placed let say forms disabled posted except first one the next form filled i click button enables first i looking way implement djangolike forlooplast templatetag variable loop inside acceptance test decide whether execute method enables next form basically i need something like formdata stephashes get fill current form data formdata forlooplast click button enables next form submit filled forms,1 i know anything builtin easily write generator give required information def firstlastseq seq iterseq el prev nextseq isfirst true el seq yield prev isfirst false isfirst false prev el yield el isfirst true listfirstlastrange true false false false false false false true listfirstlastrange listfirstlastrange true true listfirstlastrange true false false true count isfirst islast firstlastrange printcount first isfirst else last islast else first last,i template i placed let say forms disabled posted except first one the next form filled i click button enables first i looking way implement djangolike forlooplast templatetag variable loop inside acceptance test decide whether execute method enables next form basically i need something like formdata stephashes get fill current form data formdata forlooplast click button enables next form submit filled forms,2 formdata stephashes get fill current form data formdata formdata stephashes get fill current form data formdata click button enables next form submit filled forms don like repetition get fill current form data formdata define function,i template i placed let say forms disabled posted except first one the next form filled i click button enables first i looking way implement djangolike forlooplast templatetag variable loop inside acceptance test decide whether execute method enables next form basically i need something like formdata stephashes get fill current form data formdata forlooplast click button enables next form submit filled forms,1 to unlock user need set lockouttime attribute,i recently implemented password reset ad using python ldap module this involved passing modified attributes manner addpass ldapmodreplace unicodepwd this worked since passwords ad stored attribute unicodepwd now i want unlock locked user account i cannot find attribute must changed achieve could guys please tell attribute i change,2 generator buffer def firstlast iterable iteriterable f nexti yield f first n nexti another yield n none n another yield n last item state firstlist iterable state first none last zipping two sequences flags first leniterablenone last item state zip iterable flags state first none last,i template i placed let say forms disabled posted except first one the next form filled i click button enables first i looking way implement djangolike forlooplast templatetag variable loop inside acceptance test decide whether execute method enables next form basically i need something like formdata stephashes get fill current form data formdata forlooplast click button enables next form submit filled forms,1 don use lists use set instead you could find unsubscribed jan feb simply using set difference subs feb jan unsubs jan feb that said would better following daenyth suggestion put database add joined left date field finer granularity months need stored duplicated data,i lists jan feb mar apr may jun jul aug contain names list format ie john smith cat stevens andrew alexander el gordo baba louis le roy etc how i compare lists order see name appeared ie subscribed name disappeared ie unsubscribed so say john smith appear february i want information lets say unsubscribed july i want information far important former,3 have checked rawidfields attribute i think might find useful,i simple django model consisting sensor values specific sensor the number values per pyranometer high k is somehow possible paginate pyranometervalues specific day generell apply paginator admin inline view class pyranometermodelsmodel name modelscharfieldmaxlength class pyranometervaluesmodelsmodel timestamp modelsdatetimefield value modelsdecimalfieldmaxdigitsdecimalplaces sensor modelsforeignkey pyranometer,1 what written basically pip based code wrote using setuptools setup function imported setuptools setuptools paves distutils setup function initpy therefore mater setuppy script imports distutils setuptools always win if reason still issues running command try compiling file execution execcompile rather execfile in response jknair answer i also discourage use ezsetuppy code duplication unexpected behavior often excluded package distribution makes hard tools like pip run setuppy without importerror,i using code code import setuptoolsfilerexecfilefile formatospathjoinpath setuppy args install singleversionexternallymanaged subprocesscheckcallsysexecutable c code args to execute setuppy install package the problem occurs setuppy uses distutils instead setuptools singleversionexternallymanaged recognized distutils how i force setuppy use setuptools,1 map keys names attributes use setattrself attributename inttokens set value eg attributedict dictcolswidth rowsheight turntimeturntime value inttokens key playerseed randomseedvalue else setattrself attributedictkey value,i refactoring code friend wrote recently stumbled across function def setupparametersself data parse raw data determine game settings line datasplit n line linestriplower line tokens linesplit selfldebugtokens strtokens key tokens key cols selfwidth inttokens elif key rows selfheight inttokens elif key playerseed randomseedinttokens elif key turntime selfturntime inttokens elif key loadtime selfloadtime inttokens elif key viewradius selfviewradius inttokens elif key attackradius selfattackradius inttokens elif key spawnradius selfspawnradius inttokens as see nasty kind switch statement clearly calls dictionary i tempted write class dictionary since keys constant since keys map attributes instance ie cols selfwidth compile my question right way refactor code,3 you build dictionary keys accessors lambda functions execute code key,i refactoring code friend wrote recently stumbled across function def setupparametersself data parse raw data determine game settings line datasplit n line linestriplower line tokens linesplit selfldebugtokens strtokens key tokens key cols selfwidth inttokens elif key rows selfheight inttokens elif key playerseed randomseedinttokens elif key turntime selfturntime inttokens elif key loadtime selfloadtime inttokens elif key viewradius selfviewradius inttokens elif key attackradius selfattackradius inttokens elif key spawnradius selfspawnradius inttokens as see nasty kind switch statement clearly calls dictionary i tempted write class dictionary since keys constant since keys map attributes instance ie cols selfwidth compile my question right way refactor code,1 setup dict actions like actions dictcols lambda tokens setattrself width inttokens playerseed lambda tokens randomseedinttokens actionskeytokens,i refactoring code friend wrote recently stumbled across function def setupparametersself data parse raw data determine game settings line datasplit n line linestriplower line tokens linesplit selfldebugtokens strtokens key tokens key cols selfwidth inttokens elif key rows selfheight inttokens elif key playerseed randomseedinttokens elif key turntime selfturntime inttokens elif key loadtime selfloadtime inttokens elif key viewradius selfviewradius inttokens elif key attackradius selfattackradius inttokens elif key spawnradius selfspawnradius inttokens as see nasty kind switch statement clearly calls dictionary i tempted write class dictionary since keys constant since keys map attributes instance ie cols selfwidth compile my question right way refactor code,1 x data listprice astype int and csvrec converterd argument httpmatplotlibsourceforgenetapimlabapihtmlmatplotlibmlabcsvrec,i learning matplotlib trying implement simple linear regression hand however i run problem importing working data using csvrec data matplotlibmlabcsvrec kcfilteredcsv delimiter x data listprice data squarefeet sumx xsum sumy ysum sumxsq sumsq sq x sumysq sumsq sq i reading list housing prices trying get sum squares however csvrec reads prices file stores values int since sum squares housing prices greater bit integer overflows however i see method changing data type assigned csvrec reads file how i change data type array read assigned,1 request request different domains it understandable cookies googlecom sent domaincom,i serious issues trying get mechanize preserve cookies set first requested url requesting second url in order test anything sent i put following file server cookiesphp php echo cookies printrcookie the following python file means accomplish goal i like cookies set first site i output testing outputted php file well aka set second request beautifulsoup import beautifulsoup beautifulstonesoup import mechanize pprint import class nullcookieprocessormechanizehttpcookieprocessor def httprequestself request return request def httpresponseself request response return response opener mechanizebuildopenernullcookieprocessor request mechanizerequest httpwwwgooglecom response mechanizeurlopenrequest cj mechanizecookiejar cjextractcookiesresponse request pprintcj request mechanizerequest httpdomaincomcookiesphp cjaddcookieheaderrequest response mechanizeurlopenrequest print responsegeturl print responseinfo headers print responseread body readline readlines work the following output mechanizeclientcookiecookiejarcookieversion name nid value rkjmmbuflkrmjtmfrixvnygzwkpvgbamvoryusbbhpxvcyeduecgnbnyqzzgbkmwhcwqwvnklperbwevsguvxehgyroazqrp portnone portspecifiedfalse domain googlecom domainspecifiedtrue domaininitialdottrue path pathspecifiedtrue securefalse expires discardfalse commentnone commenturlnone rest httponly none rfcfalse cookieversion name pref value idecabfbfftmlmsrppxtfagwvsgkzij portnone portspecifiedfalse domain googlecom domainspecifiedtrue domaininitialdottrue path pathspecifiedtrue securefalse expires discardfalse commentnone commenturlnone rest rfcfalse httpmy domaincomcookiesphp date thu sep gmt server apache modfcgid modauthpassthrough modbwlimited frontpage xpoweredby php connection close transferencoding chunked contenttype texthtml cookiesarray any ideas get work it noted code copypasted docs i also tried sample code provided documentation found httpwwwsearchsourceforgenetmechanizedochtml,2 instead mlabcsvrec use equivalent function numpy numpyloadtxt documentation read data this function argument specify dtype data or want work column names example code function numpygenfromtxt documentation this like loadtxt options read column names first line file names true an example usage in import numpy np stringio import stringio data stringioa b cn n npgenfromtxtdata namestrue dtype int delimiter out arrayl l l l l l dtype b c another remark code using numpy arrays use forloops to calculate square xsq x sumxsq xsqsum one line sumxsq numpysumx,i learning matplotlib trying implement simple linear regression hand however i run problem importing working data using csvrec data matplotlibmlabcsvrec kcfilteredcsv delimiter x data listprice data squarefeet sumx xsum sumy ysum sumxsq sumsq sq x sumysq sumsq sq i reading list housing prices trying get sum squares however csvrec reads prices file stores values int since sum squares housing prices greater bit integer overflows however i see method changing data type assigned csvrec reads file how i change data type array read assigned,1 i think use httpsdocsdjangoprojectcomendevrefmodelsinstancesvalidatingobjects just define clean method model like example docs link def cleanself djangocoreexceptions import validationerror don allow draft entries pubdate selfstatus draft selfpubdate none raise validationerror draft entries may publication date set pubdate published items set already selfstatus published selfpubdate none selfpubdate datetimedatetimenow,i django model start end date range i want enforce validation two records overlapping date ranges what simplest way implement i repeat writing logic eg i want reimplement logic form modelform admin form model overridden save as far i know django make easy globally enforce types criteria googling helpful since model validation typically refers validating specific model fields entire model contents relations fields,3 repository directory pythonpath python testsextestspy make sure expy filespackages path,i trying complete exercise learn python the hard way nd edition i receiving error i run testsextestspy file testsextestspy line module exgame import room importerror no module named exgame i thought something i wrong within code i new i cloned repo github user seems successfully completed exercise not relevant parts code identical i receive error i try run testsextestspy i cloned so i lost hoping someone solution any ideas,2 the error python error shell error you add shebang line run via python executable and definitely python python conflict python handles parens quite well corner cases breaks,i scripts folder scripts i added path so i tried test i run calling i python linux mint userpc scripts python aekpy aek userpc scripts aekpy homeuserscriptsaekpy line syntax error near unexpected token aek homeuserscriptsaekpy line print aek the code one line print aek,3 you need add first line script usrbinpython or whatever interpreter want use if shell probably bash think shell script choke if want get python interpreter path instead usrbinenv python for extra information see shebang,i scripts folder scripts i added path so i tried test i run calling i python linux mint userpc scripts python aekpy aek userpc scripts aekpy homeuserscriptsaekpy line syntax error near unexpected token aek homeuserscriptsaekpy line print aek the code one line print aek,3 you even need save previous stdout python yes use cstringio import sys cstringio import stringio sysstdout captured stringio print test string test stuff captured capturedgetvalue sysstdout sysstdout print capturedcaptured,as part trying test legacy function print stdout sideeffect i want capture stdout later replay i use mock goals fulfill many possible stdout still prints normally would additional recorder ideally patched occur context my implementation patching seems bit heavy gross is saner way cstringio any better parts mock i use rather getattr hack class streamcapturingobject def initself stream selfcaptured selfstream stream def getattrselfattr return getattrselfstreamattr def writeself data selfcapturedappenddata selfstreamwritedata import sys import mock mockpatch sysstdout streamcapturingsysstdout ctx sysstdoutwrite print stdout sysstdoutwritethe real onen print sysstdoutcaptured sysstdoutflush assert getattrsysstdout captured none,1 if i understand want code want def initself args kwargs superclassname selfinitargs kwargs sitea helptext foo else helptext bar selfformfieldsfieldnamehelptext helptext that example using logic modify overriden form so put modeladmin constructor overrode,in django app i would like able add customized help text admin change form models note i talking field specific helptext attribute i set individual fields for example top change form mymodel myapp i like able add html says for additional information my model see httpexamplecom order provide link internal documentation wiki is simple way accomplishing i need create custom admin form model if give example i would,1 fabriziom answer get work here little explanation when python loads file searches filesystem so import statement exgame import room it looks file expy modules search path accessible syspath python code the modules search path contains directories based installation details python directories listed pythonpath environment variable contains parent directory script you’re executing it find expy path sees directory named ex initpy inside it finds gamepy folder the problem current folder modules search path because extestspy run cwdtests path you need cwd path pythonpath python testsextestspy exactly it puts cwd modules search path python find source files you also python testsextests this run module instead file use current directory path adds automatically modules search path instead directory file located inside,i trying complete exercise learn python the hard way nd edition i receiving error i run testsextestspy file testsextestspy line module exgame import room importerror no module named exgame i thought something i wrong within code i new i cloned repo github user seems successfully completed exercise not relevant parts code identical i receive error i try run testsextestspy i cloned so i lost hoping someone solution any ideas,2 i would override validateunique method model to make sure ignore current object validating use following djangodbmodels import model datetimefield djangocorevalidators import nonfielderrors validationerror class mymodelmodel startdate datetimefield enddate datetimefield def validateuniqueself args kwargs supermymodel selfvalidateuniqueargs kwargs qs selfclassdefaultmanagerfilter startdateltselfenddate enddategtselfstartdate selfstateadding selfpk none qs qsexcludepkselfpk qsexists raise validationerror nonfielderrors overlapping date range modelform automatically call fullclean use manually ppr nice discussion simple correct range overlap condition,i django model start end date range i want enforce validation two records overlapping date ranges what simplest way implement i repeat writing logic eg i want reimplement logic form modelform admin form model overridden save as far i know django make easy globally enforce types criteria googling helpful since model validation typically refers validating specific model fields entire model contents relations fields,3 in original question seems likely beaten race condition the device inserted code executed mounting process completed try putting popen calls loop see path count count path p subprocesspopendf h stdoutsubprocesspipe p subprocesspopengrep devicefile stdinpstdout stdoutsubprocesspipe p subprocesspopenawk print stdinpstdout stdoutsubprocesspipe path pcommunicate count path timesleep print path this bit resourcehungry solution want,i program written python uses dbus detect inserted usb drives prints dir mounted detected here code import dbus import gobject import shutil import os import subprocess import time class deviceaddedlistener def initself selfbus dbussystembus selfhalmanagerobj selfbusgetobject orgfreedesktophal orgfreedesktophalmanager selfhalmanager dbusinterfaceselfhalmanagerobj orgfreedesktophalmanager selfhalmanagerconnecttosignaldeviceadded selffilter def filterself udi deviceobj selfbusgetobject orgfreedesktophal udi device dbusinterfacedeviceobj orgfreedesktophaldevice devicequerycapabilityvolume return selfdosomethingdevice def dosomethingself volume devicefile volumegetpropertyblockdevice label volumegetpropertyvolumelabel fstype volumegetpropertyvolumefstype mounted volumegetpropertyvolumeismounted mountpoint volumegetpropertyvolumemountpoint try size volumegetpropertyvolumesize except size p subprocesspopendf h stdoutsubprocesspipe p subprocesspopengrep devicefile stdinpstdout stdoutsubprocesspipe p subprocesspopenawk print stdinpstdout stdoutsubprocesspipe path pcommunicate print path name main dbusmainloopglib import dbusgmainloop dbusgmainloopsetasdefaulttrue loop gobjectmainloop deviceaddedlistener looprun the problem i print path variable mount point usb prints empty string however i execute commands popen etc python interactive interpreter prints path fine mediacbc why occur any edits suggestions code would much appreciated thanks advance,1 i idea various completion options python vim but want roll well advised study modify one existing ones like httpwwwvimorgscriptsscriptphpscriptid also omnicompletion listing words current file set properly pythonspecific completion not sure good specialized python completion systems get certainly compete based python units external current file,i web trying find way get vim code completion similar pydev it seem like possible i tried use omnicompletion suggested link httpblogdispatchedchvimaspythonide i tried several addons alleviate problem none work the omnicomplete functionality not i looking it takes words file working uses try complete i for example i wrote import numpy asinglearray range npathen i hit cntrln code complete it would spit asinglearray possible completion absurd that valid completion numpya what issue all addon would run dirwork want find folder filter output this cannot difficult i suppose would also read file currently editing filter well take note name changes pretty much speaking easy would anything already made i thinking writing script any guides that,1 the globbing done shell argparse module print sysargv beginning see argparse gets input,i using python argparse following argument definition parseraddargument path nargs help file path process but i enter command wildcard argument argparse globs file paths terminates error how i get argparse glob files,2 the shell expanding wildcard argument argparse gets chance see put quotes around wildcard argument prevent shell expanding you could later perform wildcard expansion globglob,i using python argparse following argument definition parseraddargument path nargs help file path process but i enter command wildcard argument argparse globs file paths terminates error how i get argparse glob files,2 how i get argparse glob files you you get shell stop globbing however let think moment you saying code parseraddargument path nargs help file path process but actually providing wildcards run one two wrong either stop providing wildcards run time fix argparse allow multiple filenames,i using python argparse following argument definition parseraddargument path nargs help file path process but i enter command wildcard argument argparse globs file paths terminates error how i get argparse glob files,3 add coding whateverencodingyouuse top file,i learning bottle framework new python just stumbled upon difficulty when i write simple method return arabic string like route hello def hello return u ø³ù„ø§ù i get error message terminal syntaxerror nonascii character xd file hellopy line encoding declared see httpwwwpythonorgpepspephtml details i imported bottle tried adding methods mentioned docs talks changing default encoding however i unable resolve issue so i appreciate hints,3 save file utf insert encoding utf first line file,i learning bottle framework new python just stumbled upon difficulty when i write simple method return arabic string like route hello def hello return u ø³ù„ø§ù i get error message terminal syntaxerror nonascii character xd file hellopy line encoding declared see httpwwwpythonorgpepspephtml details i imported bottle tried adding methods mentioned docs talks changing default encoding however i unable resolve issue so i appreciate hints,1 at top script enter encoding utf the thing script might run latin encoding iso limited compared utf,i learning bottle framework new python just stumbled upon difficulty when i write simple method return arabic string like route hello def hello return u ø³ù„ø§ù i get error message terminal syntaxerror nonascii character xd file hellopy line encoding declared see httpwwwpythonorgpepspephtml details i imported bottle tried adding methods mentioned docs talks changing default encoding however i unable resolve issue so i appreciate hints,1 at moment takes two parameters word letter there already variable code used index pull promote parameter default value,def findword letter index index lenword wordindex letter return index index index return i get the exercise says modify find third parameter index word start looking pardon newbiness says modify find third parameter findwordletterthirdparameter put third para within function definition also index word start looking i sure i misinterpreting wants take index word start looking random index number h,1 says modify find third parameterfindwordletterthirdparameter right put third para within function definition um that thing add third parameter function definition,def findword letter index index lenword wordindex letter return index index index return i get the exercise says modify find third parameter index word start looking pardon newbiness says modify find third parameter findwordletterthirdparameter put third para within function definition also index word start looking i sure i misinterpreting wants take index word start looking random index number h,1 no omni completion functionality exactly looking you using cn instead cxco type cn amp cp complete words buffer cursor respectively type cxco complete methodproperties names it specifically explained article linked in v vim introduced omni completion – given configured recognize python feature plugin away ctrlx ctrlo opens drop dialog like ide – even whole pydoc gets displayed split window,i web trying find way get vim code completion similar pydev it seem like possible i tried use omnicompletion suggested link httpblogdispatchedchvimaspythonide i tried several addons alleviate problem none work the omnicomplete functionality not i looking it takes words file working uses try complete i for example i wrote import numpy asinglearray range npathen i hit cntrln code complete it would spit asinglearray possible completion absurd that valid completion numpya what issue all addon would run dirwork want find folder filter output this cannot difficult i suppose would also read file currently editing filter well take note name changes pretty much speaking easy would anything already made i thinking writing script any guides that,3 data jan john smith cat stevens andrew alexander el gordo baba feb louis le roy john smith mar cat stevens louis le roy itertools import izip keys jan feb mar split mm izipkeyskeys setdatam b setdatam print ntsubscribed joinba ntquit joina b result jan subscribed louis le roy quit andrew alexandercat stevensel gordo baba feb subscribed cat stevens quit john smith,i lists jan feb mar apr may jun jul aug contain names list format ie john smith cat stevens andrew alexander el gordo baba louis le roy etc how i compare lists order see name appeared ie subscribed name disappeared ie unsubscribed so say john smith appear february i want information lets say unsubscribed july i want information far important former,1 the question asking create third parameter starting index the new signature would something like findletter word startindex it would work like find red blue starts index finds index find red blue starts index finds find red blue e starts index misses e index,def findword letter index index lenword wordindex letter return index index index return i get the exercise says modify find third parameter index word start looking pardon newbiness says modify find third parameter findwordletterthirdparameter put third para within function definition also index word start looking i sure i misinterpreting wants take index word start looking random index number h,1 this means modify function takes additional parameter index start string looking match here sample output making change may help understand find abc abc b starting beginning find first b find abc abc b starting first b find second b find abc abc b starting b find match,def findword letter index index lenword wordindex letter return index index index return i get the exercise says modify find third parameter index word start looking pardon newbiness says modify find third parameter findwordletterthirdparameter put third para within function definition also index word start looking i sure i misinterpreting wants take index word start looking random index number h,1 ctrl n insertcompletion ctrl x ctrl omnicompletion i remap omnicompletion ctrl space inoremap cspace cxco you could also try supertab,i web trying find way get vim code completion similar pydev it seem like possible i tried use omnicompletion suggested link httpblogdispatchedchvimaspythonide i tried several addons alleviate problem none work the omnicomplete functionality not i looking it takes words file working uses try complete i for example i wrote import numpy asinglearray range npathen i hit cntrln code complete it would spit asinglearray possible completion absurd that valid completion numpya what issue all addon would run dirwork want find folder filter output this cannot difficult i suppose would also read file currently editing filter well take note name changes pretty much speaking easy would anything already made i thinking writing script any guides that,2 i think possible your questions implies memory used tasklets completly separated probably case python optimizing small objects like integers as far i know example code using object problem imutable so two tasklets use small integer already sharing memory,we system one interpreter many user scripts come interpreter we want put cap script memory usage there process process invokes tasklets script so since one interpreter one process know way put cap scripts memory usage what best way,2 you create mask parse using tryexcept determine whether date string matches one many masks i code project i slightly modified time import mktime strptime datetime import datetime date split result none format ymd ymdh try result datetimestrptimedate format except pass result none print malformed date else print date fine,i trying think way accomplish best pythonic way possible right method i think brute force user inputs date via command line one following manners ex mypypy date date date date all three examples result matter populates list i sort even two sorted separate variables cases yyyymmddhh needs make sure indeed date text any ideas thank edit after plugging away i thinking i needed lot date checkingmanipulating first which seems working great except end i run list date validation fails every time even passing i launch testpy date variation date ie date date date etc import sys time datetime datetimedatetimenow tempdate strfirstdatenone strtempdatenone temparg sysargv del temparg tempdate tempargreplace date date tempdatesplit tempdate datesortkeylen reversetrue result none if date passed create list according yymmddhh yymmddhh date none tempdateextendnowstrftime ymd nowstrftime ymdh if length date list see yymmdd hh create list according yymmddhh yymmddhh elif lendate lendate tempdateextend date date elif lendate tempdateextendnowstrftime ymd date nowstrftime ymd date else tempdateextenddate date iterate list see value yymmdd hh yyyymmddhh create list accoring yyyymmddhh yyyymmddhh maximum values else range lendate strfirstdate date tempdateappend date elif lendate values passed could hours tempdateappendnowstrftime ymd date else must nd value passed strfirstdate none tempdateappendnowstrftime ymd date else tempdateappendstrfirstdate date else strfirstdate date tempdateappenddate tempdatesort tempdate try result datetimedatetimestrptimes ymdh except pass result none print malformed date else print date fine print tempdate edit if i remove bottom part tempdatesort replace strfirstdate recompiler tempdate rematchstrfirstdate result validated else print print print error date print print exit it validate appropriately this entire method seem pythonic,3 pass content file execute method conn sqliteconnect testdb c conncursor sql open createsql read cexecutescriptsql,this might obvious error i trying create database within python script i already created conn sqliteconnect testdb c conncursor cexecute read createsql this gives error sqliteoperationalerror near syntax error if i thing sqlite cmd line works fine memypc sqlite testdb sqlite version enter help instructions sqlite read createsql sqlite it seems commands start give problems,1 sorry zombie question i problem ended writing solution httpsgistgithubcom,i spent two whole days trying figure verify return signatures using amazon simple pay button it feeling simple anymore isn amazon url i make serverside call all i find difficult understand apis examples never show urls can anyone help square one i button generated i python script listening return url it captures get data i know thanks everyone,1 bloglist blogobjectsfilter towncountrycountryname canada orderby id,i models django i attach location blog published class countrymodelsmodel countryname modelstextfield class townmodelsmodel country modelsforeignkeycountry townname modelscharfieldmaxlength class blogmodelsmodel town modelsforeignkeytown i trying filter country name i getting syntaxerror keyword expression i try following bloglist blogobjectsfilter towncountrycountryname canada orderby id any ideas i could filter based country name,3 first i change model use decimalfield stats query stat top playerstatobjectsorderby receivingyards you also give order listing one field order playerstatobjectsorderby receivingyardsreceptionsreceivingtouchdowns,i list players i would like gather stats separate categories rushing passing receiving every week player gets new stats category what i like able list top players category ordered ever yards particular statistic i quite sure set querys viewspy file i need anything within template file django here models look like class playermodelsmodel firstname modelscharfield maxlength verbosename first name lastname modelscharfield maxlength verbosename last name position modelscharfield maxlength choices qb qb rb rb wr wr blank true team modelscharfield maxlength choices dallas dallas new york new york tampa bay tampa bay blank true number modelscharfield maxlength blank true class playerstatmodelsmodel player modelsforeignkeyplayer weeknum modelscharfield maxlength choices sep nd sep th sep th sep rd sep th nov nd nov th nov th nov st nov th dec th dec th blank true nulltrue rushingattempts modelscharfield maxlength verbosename rushing attempts blanktrue rushingyards modelscharfield maxlength verbosename rushing yards blanktrue rushingtouchdowns modelscharfield maxlength verbosename rushing touchdowns blanktrue passingattempts modelscharfield maxlength verbosename passing attempts blanktrue passingcompletions modelscharfield maxlength verbosename passing completions blanktrue passingyards modelscharfield maxlength verbosename passing yards blanktrue passingtouchdowns modelscharfield maxlength verbosename passing touchdowns blanktrue receptions modelscharfield maxlength verbosename receptions blanktrue receivingyards modelscharfield maxlength verbosename receiving yards blanktrue receivingtouchdowns modelscharfield maxlength verbosename receiving touchdowns blanktrue i noob python django help would greatly appreciated thanks,1 you space n elif causing elif block indented therefore syntax error,i using compile exec execute python code specified user below cases reprsenting usert code needs compiled the user code read string compiled shown the compile works fine case throws syntax error syntaxerror unexpected character line continuation character case case works len return true elif len return false case fails len n return truen elif len n return false compiled compileusercde string exec any ideas thanks,1 in case additional space elif causes error also note use return inside function need def somewhere,i using compile exec execute python code specified user below cases reprsenting usert code needs compiled the user code read string compiled shown the compile works fine case throws syntax error syntaxerror unexpected character line continuation character case case works len return true elif len return false case fails len n return truen elif len n return false compiled compileusercde string exec any ideas thanks,1 from fredrik tip i using mediainfo httpmediainfosourceforgeneten p subprocesspopen mediainfo informvideowidthxheight usersdaviddesktopstestpmov stdoutpipe dimensionspcommunicatestrip n dimensions x,how would i get height width video ffmpeg information output for example following output ffmpeg videomp input movmpmagpgmj usersdaviddesktopvideomp metadata majorbrand isom minorversion compatiblebrands isomavc creationtime duration start bitrate kbs stream und video h high yuvp x par dar kbs fps tbr k tbn tbc metadata creationtime stream und audio aac hz stereo kbs metadata creationtime at least one output file must specified how would i get height width thank,2 i done something like past different approach i used weblogicdeployer interface listapps option list appslibraries deployed domain i would compare displayname element applicationxml generated archive the problem i found using plain filenames case archives came date generated which would lead always false comparison using displayname i standardized app name would deployed later compared new archive redeployed,i trying create simple python script deploys ear file adminserver weblogic i searched internet documentation provided oracle i cannot find way determine application previously deployed i would like script check issue redeploy command if issue deploy command i tried modify example scripts i found although worked behaving intended one things i trying check using cd command ear deployments folder weblogic issue redeploy if throw exception i would issue deploy however exception thrown everytime i issue cd command script try print checking existence applicationname application cd coraclemiddlewareuserprojectsdomainsbasedomainconfigdeploymentsmytestearear print redeploying commands redeploy except wlstexception commands deploy i running script windows using execfilecmytestdeployerpy command setting environment variables using wlst scripting tool any ideas i also tried use different path cd command avail any ideas,1 mysql docs say cannot create table if error message refers error table creation failed foreign key constraint correctly formed if error message refers error – table creation probably failed table includes column name matched name internal innodb table post model code let us see wrong if know wrong try bisecting repository revisions bisecting application turn half applications see syncs correctly bisect part contains bad model,first current setup django version mysql version st choice when i run syncdb i get following error creating tables creating table authpermission creating table authgrouppermissions traceback recent call last file cpathtoappmanagepy line module executemanagersettings file cpythonlibsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file cpythonlibsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file cpythonlibsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file cpythonlibsitepackagesdjangocoremanagementbasepy line execute output selfhandleargs options file cpythonlibsitepackagesdjangocoremanagementbasepy line handle return selfhandlenoargsoptions file cpythonlibsitepackagesdjangocoremanagementcommandssyncdbpy line handlenoargs cursorexecutestatement file cpythonlibsitepackagesdjangodbbackendsutilpy line execute return selfcursorexecutesql params file cpythonlibsitepackagesdjangodbbackendsmysqlbasepy line execute return selfcursorexecutequery args file cpythonlibsitepackagesmysqldbcursorspy line execute selferrorhandlerself exc value file cpythonlibsitepackagesmysqldbconnectionspy line defaulterrorhandler raise errorclass errorvalue mysqlexceptionsoperationalerror can create table databasenamesqldeffrm errno from i understand something innodb handles foreign keys here setting file looks like databases default options initcommand set tabletypeinnodb charset latin when set tabletypeinnodb specfied everything runs smoothly i looked around net seems innodb engine like something sql django generating for work around i found tho create tables use inspectdb generate models is fix thanks,2 i net expert code looks method exposed com object so try httpstarshippythonnetcrewmhammondwin package access,anyone share working example call simple c library actually wpf python code i tried using ironpython much trouble unsupported cpython library python code using i thought trying way around calling c code python here example i playing using systemruntimeinteropservices using systementerpriseservices namespace dataviewerlibrary public interface isimpleprovider dispidattribute void start comvisibletrue classinterfaceclassinterfacetypenone public class plotdata servicedcomponent isimpleprovider public void start plot plotter new plot plottershowdialog plotter wpf windows plots ellipse i know call code python any suggestions,1 personally i found easiest reliable way install scipynumpy mac os lion scipy superpack shellscript maintained stronginference weblog as steve jobs says works nothing steps install scipy virtual env download install script stronginference weblog open install script change pythonusrbinpython pythonwhich python activate virtual env inside virtual env run script bingo need,i trying install scipy vertualenv mac python using virtualenv djangomikimacdjango miki python python default aug gcc based apple inc build llvm build darwin type help copyright credits license information i tries installing scipy fails svn co httpsvnscipyorgsvnscipytrunk scipy python setuppy build python setuppy install then i tried pip install scipy also per suggestion i tried pip install e gitgithubcomscipyscipyeffaffadabeggscipydev logs here complete logs insallation steps long stackoverflow python setuppy build httpwwwdiglocomdownloaddfcaafdeefaabeaea python setuppy install httpwwwdiglocomdownloadabcadbfadaabea pip install scipy httpwwwdiglocomdownloadefebbbadbdaea pastebin httppastepocooorgshow pip install e gitgithubcomscipyscipyeffaffadabeggscipydev httpwwwdiglocomdownloadfbdecbbecacdea please help i new thank advance,3 yes known bug hpy shows use hdf newer it related changes way identifiers handled you fix using hdf earlier upgrading hpy,i using hpy access hdf files store hpy file objects class but i experiencing strange behavior attempting reassign closed hpy file instance variable new one class myclass def initself filename selfhfile none selffilename filename def vartestself selfhfile hpyfileselffilename r print selfhfile selfhfileclose print selfhfile newhfile hpyfileselffilename r print newhfile selfhfile newhfile print selfhfile print newhfile def main filename sysargv mycls myclassfilename myclsvartest output hdf file testh mode r m closed hdf file hdf file testh mode r m closed hdf file closed hdf file attempting update instance variable newly opened hpy file object appears somehow affected state object closing regardless implementation hpy side i see behavior makes sense understanding python language ie overloading assignment operator this example run python hpy if want try example hdf file sitting around change file access mode r,1 python net pythonnet may reasonable alternative ironpython situation httpsgithubcompythonnetpythonnetblobmasterreadmemd from site note package implement python firstclass clr language produce managed code il python code rather integration cpython engine net runtime this approach allows use use clr services continue use existing python code cbased extensions maintaining native execution speeds python code also python net uses pythonpath syspath look assemblies load addition usual application base gac to ensure implicitly import assembly put directory containing assembly syspath this package still requires local cpython runtime machine see full readme info httppythonnetgithubioreadmehtml,anyone share working example call simple c library actually wpf python code i tried using ironpython much trouble unsupported cpython library python code using i thought trying way around calling c code python here example i playing using systemruntimeinteropservices using systementerpriseservices namespace dataviewerlibrary public interface isimpleprovider dispidattribute void start comvisibletrue classinterfaceclassinterfacetypenone public class plotdata servicedcomponent isimpleprovider public void start plot plotter new plot plottershowdialog plotter wpf windows plots ellipse i know call code python any suggestions,3 i go ahead post comment answer answer you calling dict string the dict function expects one two types input either a list tuples form key value pairs b keyword arguments come form key value you passing either extra detail comments input key value key value typeinput type dict dictinput key value key value input key value key value this nd form typeinput type str dictinput traceback recent call last file stdin line module valueerror dictionary update sequence element length required also worth first example call dict superfluous you already dictionary declared using literal syntax,i trying send urlencode data web server the data used urlencode function read text file located local machine when i read input data urlencode function py script error thrown however input data urlencode function comming local input text file i get following error traceback recent call last file activedirectoryssltestpy line params urlliburlencodedictline valueerror dictionary update sequence element length required i following fileopeninfile r line filereadline line print line line filereadline params urlliburlencodedictline try fhandler urlopen httpshostnamepathnamefilename params why difference error reading data text file in cases variable used parameter urlencode function this content input text file hostname hostcom port basedn cnusersdcpremdclocal username cnadministratorcnusersdconpremdclocal password passwd roupname cngroupcnusersdconpremdclocal attribute name enabled sync impsync sync enabled enabled username usercom password passwd update update,1 well turns little googling makes plain import makoruntime makoruntimeundefined now undefined variables produce empty string reading source original value undefined enlightening class undefinedobject represents undefined value template all template modules constant value undefined present instance object def strself raise nameerrorundefined def nonzeroself return false and go thanks google,i found trying access undefined variable within mako template raises nameerror quite logically in applications however desirable fail gracefully perhaps substituting empty string errors attributeerror another candidate this default behavior django template language is way get behavior mako,3 print sreplace b c right see ing reprsreplace interpreter without print statement repr show actual character string interpreter uses default method print result operations unless wanted spaces instead would print sreplace b c,this probably basic i find solution i string eg abcd i like convert commas tabs but using replace eg sreplace gives sreplace atbtctd i also tried converting list adding tabs join eg joinssplit gives result how i tabs actually inserted tabs,3 in addition mark answer one reason build suite dynamically building tests also took figure get pydev pick suite run graphical test runner the trick put method like def loadtestsloader tests pattern return suite such method gets picked graphical test runner,following example pyunit i came following unittest code works fine import unittest class board def initself x selfx x selfy def eqself return selfx otherx selfy othery class boardtestunittesttestcase def setupself selfb board selfbp board selfb board def teardownself pass def testself selfassertselfb selfbp def testself selfassertnot selfb selfb class boardtestunittesttestcase def setupself selfb board selfbp board selfb board def teardownself pass def testself selfassertselfb selfbp def testself selfassertnot selfb selfb def suite suite unittestmakesuiteboardtest suite unittestmakesuiteboardtest return unittesttestsuitesuite suite name main unittestmain but thing even i remove def suite result in words looks like fixturesuite useless pyunit is correct,1 remember system first spawnsforks subshell execute commands in effect asking subshell exit,my friend macos environment wanted call ossystem exit end python script make terminal close it this surprise i would like know exactly going python script terminal call made in mental simulation terminal tell still running jobs happen either as side question less common terminals close process calls,1 the system function starts another shell execute command so case python scripts starts shell runs exit command makes process exit however python script including terminal running continues run if intent kill terminal get parent process id send signal requesting stop that kill python script terminal,my friend macos environment wanted call ossystem exit end python script make terminal close it this surprise i would like know exactly going python script terminal call made in mental simulation terminal tell still running jobs happen either as side question less common terminals close process calls,1 read help execute command string subshell a subshell launched exit run subshell to exit enclosing terminal kill parent one way ossystemkill dosgetppid,my friend macos environment wanted call ossystem exit end python script make terminal close it this surprise i would like know exactly going python script terminal call made in mental simulation terminal tell still running jobs happen either as side question less common terminals close process calls,2 you say rocksportrocker repralbumtitletext returns str xdxxdxbxdxb xdxbxdxb xdxbexdxbaxdxbdxdxb dk yep i tried the result for example repralbumtitletextencode utf returns str xdxxdxbxdxb xdxbxdxb xdxbexdxbaxdxbdxdxb this cannot true if first statement correct second cause unicodedecodeerror ascii codec decode byte xd position ordinal range it appears str object utf encoded cyrillic string foo xdxxdxbxdxb xdxbxdxb xdxbexdxbaxdxbdxdxb unicodedata import name uc foodecode utf print ux orduc nameuc u cyrillic capital letter ve u cyrillic small letter i u cyrillic small letter de u space u cyrillic small letter i u cyrillic small letter ze u space ue cyrillic small letter o ua cyrillic small letter ka ud cyrillic small letter en u cyrillic small letter a also quite unlike text error message xdxexdxxdxbxdxbdxdxcautumnalequinoxjpg bar xdxexdxxdxbxdxbdxdxcautumnalequinoxjpg uc bardecode utf print ux orduc nameuc ue cyrillic capital letter o u cyrillic small letter es u cyrillic small letter ie ud cyrillic small letter en uc cyrillic small letter soft sign uc reverse solidus u latin capital letter a u latin small letter u u latin small letter t snipped remainder the reverse solidus backslash indicates running windows windows grok utf convert text unicode input use unicode paths filenames simple example works bar xdxexdxxdxbxdxbdxdxctxt ubar bardecode utf print reprubar u ueuuuductxt f openubar wb fwrite hellon fclose openubar rb read hellon,i wrote simple client googles picasa service what i want create folder albums title name download original photo service folder if nonlatin characters title i got ioerror ioerror errno no file directory xdxexdxxdxbxdxbdxdxcautumnalequinoxjpg code sample import gdataphotosservice import gdatamedia import os import urllib gdclient gdataphotosservicephotosservice username chacomua albums gdclientgetuserfeeduserusername album albumsentry photos gdclientgetfeed datafeedapiusersalbumidskindphoto username albumgphotoidtext photo photosentry destination ospathjoinalbumtitletext phototitletext opendestination wb outwriteurlliburlopenphotocontentsrcread outclose i tried decode title decode utf work,1 the idea use find find next index given letter in code use find function,so i working diligently examples homework came across yet another error the original word banana count letter word letter count count print count ok looks simple i used code function name count generalized accepts string letter argument def countstr letter count word str specificletter word specificletter letter count count print count this i still sure i wrong i rewrite function instead traversing string uses threeparameter version find previous section which def findword letter startat index startat index lenword wordindex letter return index index index return this far i got program work way i want def findstr letter startat index startat word str count index lenword wordindex letter specificletter word specificletter letter count count print count index index can someone point right direction i want understand i instead given answer thanks,1 if want try something interesting pythonic change original find yield index remove final return oh fix bug def findword letter startat index startat index lenword wordindex letter yield index index index print listfind hello l now find returns results you use like i example position find you also simply write count terms length result sorry hints final function question i tell trying looks like maybe left much original function jumbled purposes together,so i working diligently examples homework came across yet another error the original word banana count letter word letter count count print count ok looks simple i used code function name count generalized accepts string letter argument def countstr letter count word str specificletter word specificletter letter count count print count this i still sure i wrong i rewrite function instead traversing string uses threeparameter version find previous section which def findword letter startat index startat index lenword wordindex letter return index index index return this far i got program work way i want def findstr letter startat index startat word str count index lenword wordindex letter specificletter word specificletter letter count count print count index index can someone point right direction i want understand i instead given answer thanks,1 this i def apiresponserequest try datajsonloadsrequestrawpostdata labeldata label urldata url print label url except print nope return httpresponse,i trying set view received json notification api i trying figure get json data i currently starting point see request properly received def apiresponserequest print request return httpresponse i know json object print request shows meta contentlength fri sep error contenttype applicationjson however post get querydicts empty how would i set view receive json object i process thank,3 i understand header information separated either spaces carriage returns others if separated spaces inform otherwise open imgpgm f lines freadlines data nparraylinesplit line lines dtypenpintt data array int format suppose still interested header information class headerobject def initself type width height maxval selftype type selfwidth intwidth selfheight intheight selfmaxval intmaxval h headerlinessplit check image data read lines assert hwidth hheight datashape assert hmaxval datamax edit image data binary file opened rb read header information import numpy np def asarrayfilepath f openfilepath r w h size tupleintv v nextfsplit datasize w h fseek filesize ftell fclose iheaderend filesize datasize f openfilepath rb fseekiheaderend buffer fread fclose convert binary data array right shape data npfrombufferbuffer dtypenpuintreshapew h return data asarray foopgm,what efficient clear way read bit pgm images python numpy i cannot use pil load bit pgm images due pil bug i read header following code dt npdtype type space x space space maxval header npfromfile imgpgm dtypedt print header this prints correct data p but i feeling quite best way and beyond i trouble figure read following data x case x bit offset sizeheader edit image added matlab code read display image i imread foopgm imagesci and looks like,1 fixed httplin handle one cookie patch found httpcodegooglecomphttplibissuesdetailid,fixed httplin handle one cookie patch found httpcodegooglecomphttplibissuesdetailid i coding facebook login script get last notifications i problem i changed urllib httplib seemed easier faster using urllib i able get correct cookie use ever i needed retrieve notifications i using example httplib page useragent mozilla windows u windows nt zhcn rv gecko firefox headers useragent useragent contenttype applicationxwwwformurlencoded accept texthtmlapplicationxhtmlxmlapplicationxmlq q connection keepalive acceptencoding gzip deflate referer httpmfacebookcom data email myusername pass mypassword postformid charsettest version ajax pxr gps login entrar response content hrequesthttpwwwfacebookcomloginphpmmamprefsrchttpmfacebookcomamprefid post urllibparseurlencodedata headersheaders and header i getting status xcnection close contentlocation httpmfacebookcomhomephprefsrchttpaffmfacebookcomfamprefidampmsess tamamprdr transferencoding chunked setcookie datr foqstcnbwcaa expiresfri sep gmt path domainfacebookcom httponly expires sat jan gmt xfbserver contentlength contentencoding gzip pragma nocache cachecontrol private nocache nostore mustrevalidate date wed sep gmt pp cpfacebook pp policy learn httpfbmepp contenttype texthtml charsetutf xframeoptions deny if i use hfollowallredirects true option redirect home page set cookies first page redirecting the cookies i get setcookie datrffoqstcnbwcaa expiresfri sep gmt path domainfacebookcom httponly but cookies enough get session active in browser i getting larger cookie datrezilejfjl luwgrrq localeesla l act muser gmailcomaan aavcajaxcwidthcpxrcgpsa p fl w regfbrefhttpsaffwwwfacebookcomfloginphpfmdmrefsrcdhttpaffmfacebookcomfrefidd what could problem,1 the point exercise use previously defined function find building block implement new function count so going wrong trying redefine find trying change implementation count however wrinkle find given slight error would need change order work properly with could enter body loop index lenword would cause indexerror string index range so fix find function first def findword letter startat index startat index lenword wordindex letter return index index index return and reimplement count time using find body def countword letter result startat startat lenword nextletterposition findword letter startat nextletterposition result startat nextletterposition else break return result name main print count banana,so i working diligently examples homework came across yet another error the original word banana count letter word letter count count print count ok looks simple i used code function name count generalized accepts string letter argument def countstr letter count word str specificletter word specificletter letter count count print count this i still sure i wrong i rewrite function instead traversing string uses threeparameter version find previous section which def findword letter startat index startat index lenword wordindex letter return index index index return this far i got program work way i want def findstr letter startat index startat word str count index lenword wordindex letter specificletter word specificletter letter count count print count index index can someone point right direction i want understand i instead given answer thanks,1 you delete class method way class methods properties classes objects when invoke method via objectmethod python actually calling classmethodobject this also must declare self argument class methods yet actually pass value self invoking method if want could call del classwmtitle i sure want though,i trying remove method class instance derived tkinter window using delattr built function however i get following error what i wrong error attributeerror class instance attribute wmtitle an example import tkinter tk class class tktk def init self tktkinitself the method clearly seeing works selfwmtitle this raises attributeerror delattrself wmtitle c class cmainloop,1 you close try dictfromkeysmycsvdictkeys this initialize dictionary keys parsed csv file one map empty list i assume append suspect row values try there several subtler changes necessary like initialize unsurerows start reading csv unsurerows none row csvreader row start time none try beforedate strptimerow start time ymd hms afterdate continue except valueerror unsurerows initialize unsure rows dictionary unsurerows dictfromkeyscsvreaderfieldnames key unsurerows unsurerowskeyappendrowkey,i reading csv file using dictreader the function returns dictionary header items keys cells values pretty cool but i trying account rows data may i expect in case i catching valueerror exception i would like rows suspect go separate dictionary manual processing my question since first dictionary object returned dictreader keys set properly i copy keys second dictionary one i want dictionary suspect rows manually processed i toying around dictfromkeys i getting anywhere halp edit pasting erroneous code going go hide shame code don judge unsurerows dictfromkeysdictcsvreaderkeys row csvreader row start time none try beforedate strptimerow start time ymd hms afterdate continue except valueerror unsurerows row valueerror dictionary update sequence element length required,3 i terribly familar pgm format generally speaking use numpyfromfile fromfile start whatever position file pointer pass simply seek read end header use fromfile read rest you need use infilereadline instead nextinfile import numpy np open foopgm r infile header infilereadline width height maxval intitem item headersplit image npfromfileinfile dtypenpuintreshapeheight width on side note foopgm file pointed comment appears specify wrong number rows header if going reading lot files potentially problem pad array zeros truncate like import numpy np open foopgm r infile header nextinfile width height maxval intitem item headersplit image npfromfileinfile dtypenpuint imagesize width height pad npzeroswidth height imagesize dtypenpuint image nphstackimage pad imagesize width height image imagewidth height image imagereshapeheight width,what efficient clear way read bit pgm images python numpy i cannot use pil load bit pgm images due pil bug i read header following code dt npdtype type space x space space maxval header npfromfile imgpgm dtypedt print header this prints correct data p but i feeling quite best way and beyond i trouble figure read following data x case x bit offset sizeheader edit image added matlab code read display image i imread foopgm imagesci and looks like,2 indeed string header binary file i solved found following ndarray another problem file long enough counts numbers instead i terribly sorry exageration making class import numpy np import image class pgmobject def initself filepath openfilepath f suppose header info first line info freadlinesplit selftype info selfwidth selfheight selfmaxval intv v info size selfwidth selfheight lines freadlines dt npint npintselfmaxval try work lines integers separated eg spaces selfdata nparraylsplit l lines dtypedtt except valueerror data binary data npfromstringlines dtypedt datasize size case dbttphar foopgm raise valueerror data binary string probably uncomplete data nphstackdata npzerossizedatasize selfdata datasizereshapeselfwidth selfheight assert selfwidth selfheight selfdatashape assert selfmaxval selfdatamax selfimg none def getimgself selfimg none executed size selfwidth selfheight mode l data selfdata selfimg imagefrombuffermode size data return selfimg image propertygetimg mypgm pgm foopgm mypgmimage edit great idea joe kington fill image zeros,what efficient clear way read bit pgm images python numpy i cannot use pil load bit pgm images due pil bug i read header following code dt npdtype type space x space space maxval header npfromfile imgpgm dtypedt print header this prints correct data p but i feeling quite best way and beyond i trouble figure read following data x case x bit offset sizeheader edit image added matlab code read display image i imread foopgm imagesci and looks like,1 copy object bucket delete original one botoskey import key kkeybucket kkey cliimagesimagethumbjpg kcopy bucketname cliimagesmovedimagethumbjpg kdelete,is way change key s file for example i want able equivalent botoskey import key kkeybucket kkey cliimagesimagethumbjpg original key kkey cliimagesmovedimagethumbjpg key i want change ksave in looking boto documentation i could find way copy key another bucket case i need file stay bucket move position ie change key thank,3 use imagemagick convert append photojpg photojpg photojpg rowjpg or try append change orientation repeat needed convert append rowjpg rowjpg rowjpg ajpg i may gotten append append mixed,i know possible since knowledge image processing low i need put passport size photo a sheet i could print i tried using gimp great tool like i said earlier expertise low field i find difficult place photos efficiently a sheet is way placing programmatically looking scripts using python i could get perfect output or program makes work easier or last chance use gimp effectively,1 on launch code instantiated smppclientfactory called connect this particular instance connectdeferred attribute however connect also instantiated another smppclientfactory factory smppclientfactoryselfconfig selfmsghandler instance used create actual connection this connectdeferred attribute instance connect never called,having client factory import logging traceback twistedinternetprotocol import clientfactory twistedinternet import defer reactor ssl twistedapplication import service protocolssmppprotocol import smppclientprotocol class smppclientfactoryclientfactory protocol smppclientprotocol def initself config selfconfig config def getconfigself return selfconfig def clientconnectionfailedself connector reason print clientconnectionfailed selfconnectdeferrederrbackreason def clientconnectionlostself connector reason print clientconnectionlost def connectself selfconnectdeferred deferdeferred factory smppclientfactoryselfconfig selfmsghandler selflogwarning establishing tcp connection sd selfconfighost selfconfigport reactorconnecttcpselfconfighost selfconfigport factory return selfconnectdeferred and launching code import logging traceback twistedinternet import reactor defer protocolssmppconfigs import smppclientconfig protocolssmppsmppoperations import smppoperationfactory testbedclient import smppclientfactory class smppobject def initself confignone config none config smppclientconfig selfconfig config selfopfactory smppoperationfactoryconfig def runself try bind smppclientfactoryselfconfig selfhandlemsgconnectadderrbackselfconnectfailed except exception e print error stre def connectfailedself reason print connection failed strreason def handlemsgself smpp pdu pass name main config smppclientconfighost port username smppclient password password loglevelloggingdebug loggingbasicconfiglevelconfigloglevel filenameconfiglogfile formatconfiglogformatdatefmtconfiglogdateformat smppconfigrun reactorrun when connection failing remote server get factory clientconnectionfailed called strangely getting exceptionsattributeerror smppclientfactory instance attribute connectdeferred i need call errback connection fails seems something missing dealing deferreds,1 the ppm hard parse the header p p means image ascii pixmap color width height max color value the body just remove newlines bodyreplace n and parse triplets elegant raw bodysplit range lenraw red rawi green rawi blue rawi,needing little helpdirection project our task take ppm file one required test found httpbeastiecsuaeducsprojectsasciiarttuxppm reprint screen using ascii characters we required convert pixels greyscale this really i stuck cannot figure read every three elements every three pixel ppm files convert greyscale move again pil allowed any help links read would awesome,2 import import numpy def readpgmfilename byteorder return image data raw pgm file numpy array format specification httpnetpbmsourceforgenetdocpgmhtml openfilename rb f buffer fread try header width height maxval research bpssrn bdssrn bdssrn bdssrns buffergroups except attributeerror raise valueerrornot raw pgm file filename return numpyfrombufferbuffer dtype u intmaxval else byteorder u countintwidthintheight offsetlenheader reshapeintheight intwidth name main matplotlib import pyplot image readpgmfoopgm byteorder pyplotimshowimage pyplotcmgray pyplotshow,what efficient clear way read bit pgm images python numpy i cannot use pil load bit pgm images due pil bug i read header following code dt npdtype type space x space space maxval header npfromfile imgpgm dtypedt print header this prints correct data p but i feeling quite best way and beyond i trouble figure read following data x case x bit offset sizeheader edit image added matlab code read display image i imread foopgm imagesci and looks like,3 if see import string never see stringsomething someone forgot remove unused import while use things string standard methods str objects still either prefix string importing library use string import whatever syntax typically times see something properly imported never explicitly used future import withstatement like forwardsbackwards compatability triggers used python new language features,so i reading old module i think around line import string did python require import string module explicitly able use string type variables something i see used like code stringsomething,1 if complicated given examples faster probably look pyparsing otherwise could write something hacky like contentlines gameavailableplayeravailablelocationchelsea london englandtimeavailabledateavailable gameavailableplayeravailablelocationchelsea london englandtimeavailable def getdictline keys values line linereplace replace contlist linesplit keysappendcontliststrip strip entry contlist entry entrystrip entry entry endpos entryfindentry else endpos entryfind valuesappendentryendposstrip strip keysappendentryendpos strip strip valuesappendcontliststrip strip return dictzipkeys values line contentlines print getdictline,i file list dictionaries unproperly marked quotations marks an example following gameavailableplayeravailablelocationchelsea london englandtimeavailable gameavailableplayeravailablelocationchelsea london englandtimeavailabledateavailable as see keys also differ dictionary another i tried read json module dictreader csv module time i difficulties due always present location value always keys values up point i see two possibilities replacing location value getting rid quotes adding quotes every value key except location one ps my final point able format dictionaries create sql table columns union dictionaries row one dictionary blank missing values,1 found via trial error employeedepartmentsremovedepartmentkey,in google app engine solution python i used dblistproperty way describe manytomany relation like class departmentdbmodel name dbstringproperty property def employeesself return employeeallfilter departments selfkey class employeedbmodel name dbstringproperty departments dblistpropertydbkey i create manytomany relations simply appending department key dblistproperty like employeedepartmentsappenddepartmentkey the problem i know actually remove relationship longer needed i tried googling i seem find documentation describes dblistproperty details any ideas references,1 reading ppm file open ppm file process first lines f opentuxppm color freadlinesplitlines sizex sizey freadlinesplit max freadlinesplitlines you really need know first lines file you must know working rgb image means values pixel to convert image grayscale two options either generate another ppm file values per pixel generate pgm file format ppm first line p instead p one value per pixel cool way to convert rgb color value rgb one grayscale intensity value apply formula better simply apply average r g b generate grayscale image one value per pixel want values repeat times rgb getting image data read first lines data freadsplit generate new array pixels grayscale values per pixel graydata datai datai datai rangelendata,needing little helpdirection project our task take ppm file one required test found httpbeastiecsuaeducsprojectsasciiarttuxppm reprint screen using ascii characters we required convert pixels greyscale this really i stuck cannot figure read every three elements every three pixel ppm files convert greyscale move again pil allowed any help links read would awesome,1 solved making simple changes code normalizedhttpmethod get post oauthheader oauth realmhttpwww the word authorization unnecessary i taken earlier listed things i tried without success error listed threw track with solved i could see authorization indeed unnecessary the oauth request token tumblr sent i finally got right oauthtokenmbrugydkpepfkeztilelmqulkynxecatccwpbsoxdfmhitfampoauthtokensecretpxllxgkaoraauatgckifmfyupjumbageelukemzocpvampoauthcallbackconfirmedtrue ↑ this onetime token i listed sake completeness,i using libraries handle oauth far lately i digging deeper trying understand underlying oauth process currently i trying connect tumblr api v using oauth simple code import urllib urllib time random hmac base hashlib def makenonce randomnumber join str randomrandint range hashlibmd str timetime str randomnumber return mhexdigest def encodeparamss return urllibquote str safe actual key secret test app created using dummy tumblr account consumerkey oaujqhsaqnvxdxzcjdzloxwnyhobmdwmuejbchwsffswly consumersecret qdpfsogsubeoaayoudnqoujuencgadrwomlf oauth urls requesttokenurl httpwwwtumblrcomoauthrequesttoken oauth params oauthparameters oauthconsumerkey consumerkey oauthnonce makenonce oauthtimestamp strinttimetime oauthsignaturemethod hmacsha oauthversion normalizedparameters encodeparams amp join ss encodeparams str k encodeparams str oauthparametersk k sorted oauthparameters normalizedhttpmethod post since i focusing getting request token i set post normalizedhttpurl encodeparams requesttokenurl signaturebasestring amp join normalizedhttpmethod normalizedhttpurl normalizedparameters oauthkey consumersecret amp hashed hmacnew oauthkey signaturebasestring hashlibsha oauthparameters oauthsignature basebencode hasheddigest oauthheader authorization oauth realmhttpwwwtumblrcom oauthnonce oauthparameters oauthnonce oauthtimestamp oauthparameters oauthtimestamp oauthconsumerkey oauthparameters oauthconsumerkey oauthsignaturemethodhmacshaoauthversionoauthsignature oauthparameters oauthsignature sample oauthheader generated code authorization oauth realmhttpwwwtumblrcomoauthnoncecaefbbaceaboauthtimestampoauthconsumerkeyoaujqhsaqnvxdxzcjdzloxwnyhobmdwmuejbchwsffswlyoauthsignaturemethodhmacshaoauthversionoauthsignaturekvalmwolcxwjivtfmbuvrnu req urllibrequest requesttokenurl reqaddheader authorization oauthheader print urlliburlopen req read if goes well tumblr send oauth request token instead oauth request token tumblr returns http error unauthorized things i tried without success changed oauthversion changed back a guide oauth mandated adding amp end consumersecret get oauthkey i tried removing amp later see made difference checked oauth parameters sorted did add string authorization oauthheader added back later neither made difference where i gone wrong,2 it looks like problem date formatting in case datetimestrptimepmsg date b y hms z give date time object give message searchfor on astrftimedby bear mind give messages date since ignores time timezone info as alternative worth looking emails seeing messageid header could help since account genuinely duplicate emails,using python imaplib i connecting imap servers gmail trying match emails using date date time i problems the date returned parsing header directly usable searching format wrong it clear imap search use search date time returned parsing header i oldmail newmail imap connections newmailselectgmailall mail readonlytrue oldmailselectgmailall mail just choosing random email typ msg newmailfetch bodyheader parser headerparser pmsg parserparsestrmsg pmsg date tue dec but right formate use like surly easy way searchfor on pmsg date searchfor on tue dec oldmailsearchnone searchfor traceback recent call last file console line module file libraryframeworkspythonframeworkversionslibpythonimaplibpy line search typ dat selfsimplecommandname criteria file libraryframeworkspythonframeworkversionslibpythonimaplibpy line simplecommand return selfcommandcompletename selfcommandname args file libraryframeworkspythonframeworkversionslibpythonimaplibpy line commandcomplete raise selferror command error name typ data error search command error bad could parse command my goal find matching emails servers failed transfer using googles migration app then delete email old server transferred if suggest better way would helpful also,1 as starter import print rematchddd print rematchddd print rematchddd print rematchddd if want learn regular expressions python i recommend httpdiveintopythonnetregularexpressionsindexhtml httpcodegooglecomintldedeedulanguagesgooglepythonclassregularexpressionshtml httpdocspythonorgdevhowtoregexhtml thanks stals httpwwwyoutubecomwatchvkwyoytvjpe,how write regex string like i googled found python module using import but i figured exact way,3 if want measure elapsed wallclock time two points could use timetime import time start timetime printhello end timetime printend start this gives execution time seconds edit a better option might use timeclock thanks amber on unix return current processor time floating point number expressed seconds the precision fact definition meaning “processor time” depends c function name case function use benchmarking python timing algorithms on windows function returns wallclock seconds elapsed since first call function floating point number based win function queryperformancecounter the resolution typically better one microsecond,what i want start counting time somewhere code get passed time measure time took execute function i think i using timeit module wrong docs confusing import timeit start timeittimeit print hello end timeittimeit print end start,3 using timetime measure execution gives overall execution time commands including running time spent processes computer it time user notices good want compare different code snippets algorithms functions more information timeit using timeit module timeit – time execution small bits python code if want deeper insight profiling httpwikipythonorgmoinpythonspeedperformancetipsprofilingcode how profile python script update i used httppythonhostedorglineprofiler lot last year find helpfull recommend use instead pythons profile module,what i want start counting time somewhere code get passed time measure time took execute function i think i using timeit module wrong docs confusing import timeit start timeittimeit print hello end timeittimeit print end start,3 given function like time testpy def foo print hello return hello easiest way use timeit call command line python mtimeit import test testfoo loops best usec per loop do try use timetime timeclock naively compare speed functions they give misleading results ps do put print statements function wish time otherwise time measured depend speed terminal,what i want start counting time somewhere code get passed time measure time took execute function i think i using timeit module wrong docs confusing import timeit start timeittimeit print hello end timeittimeit print end start,3 yes possible new django classbased views djangoviewsgenericbase import view class myviewview def getself request args kwargs return response def postself request args kwargs return response usually use view base class many views geared towards kinds cases eg templateview formview reinout van rees two excellent blog posts go details httpreinoutvanreesorgweblogclassbasedviewswalkthroughhtml httpreinoutvanreesorgweblogclassbasedviewsusagehtml,learning django gave webpy try first reading django documentation found need check request type method like def myview requestmethod post blah balh keha jst kiddn else balhx webpy type classes implemented django like class myview def getself cool def postself double cool would super cool,2 def savefileself outputfilename none outputfilename outputfilename selfimagefilename selffilereadoutputfilename,def savefileself outputfilename selfimagefilename selffilereadoutputfilename gives nameerror name self defined first line it seems python accept how i rewrite code i violate rules please feel free add tags change title,2 use default none detect def savefileself outputfilenamenone outputfilename none outputfilename selfimagefilename selffilereadoutputfilename,def savefileself outputfilename selfimagefilename selffilereadoutputfilename gives nameerror name self defined first line it seems python accept how i rewrite code i violate rules please feel free add tags change title,3 the documentation states default parameter values evaluated function definition executed this explains instance cannot referenced as others said use none default fix value function execution time instance available,def savefileself outputfilename selfimagefilename selffilereadoutputfilename gives nameerror name self defined first line it seems python accept how i rewrite code i violate rules please feel free add tags change title,3 here complete code i think first i created following file surprise perturbating start gameavailable universal dices game playerftroelocation lakeview school kingsmere boulevard saskatoon saskatchewan canadatimeh gameavailable playerloi location perth australiatimehdateavailable gameavailableplayerpllilocationchelsea london englandtimeh specialmidnight happeninggameavailableplayerytr locationparis francetimeh dateavailable gameavailablesurprise hretyuuhuhu playerftlocation timeh gameavailableplayerloilocation damassyriatimeunavailabledateavailable surprise garamananatala tower gameavailable dicesplayer pulululocation westminster london england timeh gameavailablespecialovernight playerytrlocation madrid spain time h dateavailable then following code treats content file two phases first running content intervening keys dictionaries collected dictionary posis deducted gives key place corresponding value must occupy row secondly thanks another run file rows build one collected list rows by way note condition value associated key location location respected import dicreg recompile kvregx recompile rn location rn rn rn checkingdict checkinglist filename zzztxt openfilename f first part gather keys dictionaries precchunk go ecr chunk chunk fread ss joinprecchunk ecrappend nnnss r ss matdic none matdic dicregfinditerss ecrappend nmmmmmmm dictionary found ss mmmmmmmmmmmmmm matkv kvregxfinditermatdicgroup kv matkvgroup ecrappend kv k checkinglist checkingdictk else checkinglistappendk checkingdictk matdic prec ssmatdicend else prec chunk print n joinecr print nnncheckingdict snncheckinglist checkingdictcheckinglist the keys sorted order less frequent ones end checkinglistsortkeylambda k checkingdictk reversetrue posis dictki ik enumeratecheckinglist print ncheckinglist sorted snnposis checkinglistposis now file read build list rows fseek file pointer move backed beginning file precchunk go base xrangelencheckinglist rows chunk chunk fread ss joinprecchunk matdic none matdic dicregfinditerss li base matkv kvregxfinditermatdicgroup kv matkvgroup liposisk v rowsappendli matdic prec ssmatdicend else prec chunk print nnsns checkinglist print n joinstrli li rows result ss surprise perturbating start gameavailable universal dices gamen playerftroelocationnlakeview s ss surprise perturbating start gameavailable universal dices gamen playerftroelocationnlakeview school kingsmere boulevard saskatoon saskatchewan canadatimehnngameavailable playerloinl mmmmmmm dictionary found ss mmmmmmmmmmmmmm surprise perturbating start game available universal dices game player ftroe location lakeview school kingsmere boulevard saskatoon saskatchewan canada time h ss nngameavailable playerloinlocation perth australiatimehdateavailablenngameavailableplayerpllilocationchelsea lo mmmmmmm dictionary found ss mmmmmmmmmmmmmm game available player loi location perth australia time h date available ss nngameavailableplayerpllilocationchelsea london englandtimehnnspecialmidnight happeninggameavailableplayerytrnlocationparis francet mmmmmmm dictionary found ss mmmmmmmmmmmmmm game available player plli location chelsea london england time h ss nnspecialmidnight happeninggameavailableplayerytrnlocationparis francetimehnndateavailablenngameavailablesurprise hretyuuhuhu playerftlocationntimehnn mmmmmmm dictionary found ss mmmmmmmmmmmmmm special midnight happening game available player ytr location paris france time h date available mmmmmmm dictionary found ss mmmmmmmmmmmmmm game available surprise hretyuuhuhu player ft location time h ss nngameavailableplayerloilocationndamassyriatimeunavailabledateavailablennsurprise mmmmmmm dictionary found ss mmmmmmmmmmmmmm game available player loi location damassyria time unavailable date available ss nnsurprise garamananatala tower gameavailable dicesplayer n pulululocation westminster london england time ss nnsurprise garamananatala tower gameavailable dicesplayer n pulululocation westminster london england timehnngameavailablespecialovernight playerytrlocationnmadrid spain timenhnda mmmmmmm dictionary found ss mmmmmmmmmmmmmm surprise garamananatala tower game available dices player pululu location westminster london england time h ss nngameavailablespecialovernight playerytrlocationnmadrid spain timenhndateavailablen mmmmmmm dictionary found ss mmmmmmmmmmmmmm game available special overnight player ytr location madrid spain time h date available ss checkingdict player game location time date surprise special checkinglist surprise game player location time date special checkinglist sorted game player location time date surprise special posis player game location time date surprise special game player location time date surprise special available universal dices game ftroe lakeview school kingsmere boulevard saskatoon saskatchewan canada h perturbating start available loi perth australia h available available plli chelsea london england h available ytr paris france h available midnight happening available ft h hretyuuhuhu available loi damassyria unavailable available available dices pululu westminster london england h garamananatala tower available ytr madrid spain h available overnight i wrote code thinking enormous file several gb read entirely treatment big file must done chunk chunk that instructions chunk chunk fread ss joinprecchunk ecrappend nnnss r ss matdic none matdic dicregfinditerss matdic prec ssmatdicend else prec chunk but evidently file big hence readable one shot code simplified import dicreg recompile kvregx recompile rn location rn rn rn checkingdict checkinglist filename zzztxt openfilename f content fread first part gather keys dictionaries ecr matdic dicregfinditercontent ecrappend nmmmmmmm dictionary found ss mmmmmmmmmmmmmm matkv kvregxfinditermatdicgroup kv matkvgroup ecrappend kv k checkinglist checkingdictk else checkinglistappendk checkingdictk print n joinecr print nnncheckingdict snncheckinglist checkingdictcheckinglist the keys sorted order less frequent ones end checkinglistsortkeylambda k checkingdictk reversetrue posis dictki ik enumeratecheckinglist print ncheckinglist sorted snnposis checkinglistposis now file read build list rows base xrangelencheckinglist rows matdic dicregfinditercontent li base matkv kvregxfinditermatdicgroup kv matkvgroup liposisk v rowsappendli print nnsns checkinglist print n joinstrli li rows,i file list dictionaries unproperly marked quotations marks an example following gameavailableplayeravailablelocationchelsea london englandtimeavailable gameavailableplayeravailablelocationchelsea london englandtimeavailabledateavailable as see keys also differ dictionary another i tried read json module dictreader csv module time i difficulties due always present location value always keys values up point i see two possibilities replacing location value getting rid quotes adding quotes every value key except location one ps my final point able format dictionaries create sql table columns union dictionaries row one dictionary blank missing values,1 why loop it going much slower otherwise def fxposlist v pos poslist v xposxpos return v if really want python like i beleive going slow def addtermf pos def gx return fxxposxpos return g def zerox return f zero pos poslist faddtermf pos there real analogue c c closures one could simulate could use list loop instead anyway,i array contanining position different objects scene to calculate next movement step i want build function like fx xpos xpos term term termn i know many objects scene i want add terms function objects something like object scene addonetermtothefunction return function way program preferably c python two languages i know ps thx answers loop i looking this would extremly slow calculate function everytime i call next event i want calculte pass events calculated function,1 function lambda x sumxobjpos obj scene functionfunction,i array contanining position different objects scene to calculate next movement step i want build function like fx xpos xpos term term termn i know many objects scene i want add terms function objects something like object scene addonetermtothefunction return function way program preferably c python two languages i know ps thx answers loop i looking this would extremly slow calculate function everytime i call next event i want calculte pass events calculated function,1 here good btree pure python implementation you adapt needed,i heard btree datbases faster hash tables i thought using btree db project is existing framework python allows us use data structure i code scratch,1 i sorry say way efficiently recursively finding files least platform filesystem independent if filesystem help anything help the reason possible without recursive scanning filesystem designed a directory seen file contains list files contains to find something subdirectory first open directory open subdirectory search,i building music file organizerin python i read metadata files amp put file required folder now i already ready command line interface script shows feedback way shows which file working right if directory contains say mp files kind feedback so i would like know efficient way find total number mps available directory scanning recursively subsequent directories my idea keep track total files processed show progress bar according is better way performance wise please feel free guide i want app kind platform dependent code if serious performance penalty sticking idea please suggest linux,1 cmp old way deprecated posterity aaabbccde sorteds lambda xy cmpxlower ylower cmpxy,i want sort string list lexicographic order str aaabbccde a b b c c e sorted gives output a b c e b c how i sort lexicographically,2 mongodb support exactly operation requesting therefore neither mongoengine you perform slicing operations arrays lists adhoc filtering slicing mongodb arrays works similarly slicing lists python mongoengine using slice keyword syntax mainobjectsfiltersubsnameexiststruefieldsslicesubs this return subs starting index ie first element returning two elements,if i models class subembeddeddocument name stringfield class maindocument subs listfieldembeddeddocumentfieldsub i want query returns mains subs filtered name existing mainobjectsfiltersubsnameexiststrue this returns correct mains subs always entire list subset how i get subset do i need rely list comprehensions,1 change elif comp rock scissors paper elif comp rps what equivalent elif comp rock scissors paper so condition always met have close look scissors paper part in python nonempty strings treated true empty strings treated false have look interactive session bool false bool true also python statements without comparison eg var inexplicity checking expression true so var var true if combine two ideas together rock always executed never executed back original statement elif comp rock scissors paper both scissors paper always return true contained statements always evaluated so operator the operator elif comp rps see contents comp item tuple rps equal rock paper scissors the front negate checking contents comp item tuple rps therefore contained statements executed user input stored comp invalid,i currently coding little rock paper scissors game python however i appear stumbled upon problem the game works even though code little rough i tried make program inform player made error i test randomly informs player made error here block code problem whole game def gameself print this rock paper scissors rps rock paper scissors comp rawinputrock paper scissorsn comp randomchoicerps comp rock comp scissors comp scissors comp paper comp paper comp rock print you the computer chose comp return game elif comp rock comp rock print in stalemate winners losers nthe computer also chose comp return game elif comp scissors comp scissors print in stalemate winners losers nthe computer also chose comp return game elif comp paper comp paper print in stalemate winners losers nthe computer also chose comp return game elif comp rock scissors paper print try choosing rock paper scissors next time it might help return game else print the computer you failed problem comp return game,3 it comp rock scissors paper scissors paper always evaluate true case comp rock scissors paper also use comp comp much simple,i currently coding little rock paper scissors game python however i appear stumbled upon problem the game works even though code little rough i tried make program inform player made error i test randomly informs player made error here block code problem whole game def gameself print this rock paper scissors rps rock paper scissors comp rawinputrock paper scissorsn comp randomchoicerps comp rock comp scissors comp scissors comp paper comp paper comp rock print you the computer chose comp return game elif comp rock comp rock print in stalemate winners losers nthe computer also chose comp return game elif comp scissors comp scissors print in stalemate winners losers nthe computer also chose comp return game elif comp paper comp paper print in stalemate winners losers nthe computer also chose comp return game elif comp rock scissors paper print try choosing rock paper scissors next time it might help return game else print the computer you failed problem comp return game,1 the problem logic elif comp rock scissors paper the strings scissors paper evaluated boolean value true null what want elif comp rock comp scissors comp paper since already rps tuple elif comp rps,i currently coding little rock paper scissors game python however i appear stumbled upon problem the game works even though code little rough i tried make program inform player made error i test randomly informs player made error here block code problem whole game def gameself print this rock paper scissors rps rock paper scissors comp rawinputrock paper scissorsn comp randomchoicerps comp rock comp scissors comp scissors comp paper comp paper comp rock print you the computer chose comp return game elif comp rock comp rock print in stalemate winners losers nthe computer also chose comp return game elif comp scissors comp scissors print in stalemate winners losers nthe computer also chose comp return game elif comp paper comp paper print in stalemate winners losers nthe computer also chose comp return game elif comp rock scissors paper print try choosing rock paper scissors next time it might help return game else print the computer you failed problem comp return game,1 you immediately delete lines file create new file write remaining lines that chonws example,i file f content huge numbers eg f so want loop file f delete lines contain numbers file say f f openfile f line f linecontainsany number f delete line f,2 for special case import glob shutil ospath globglob returns list pathes according given pattern path globglobmusicfoldermp ospathdirname gives directory name musicfolder dirname ospathdirnamepath example artistnamealbumtitlesongtitlesomethingelsemp split returns songtitlesomethingelsemp interesting pathsplit titlepart list song title beginning somehting string removed choosing slice titlepart interestingsplit capitalize converts song song title title join gluest songtitle newname joinpcapitalize p titlepartmp shutilmove renames given file shutilmovepath ospathjoindirname newname if want use regular expression replace mresearchsspath none raise exceptionfile name match regular expression songname mgroups titlepart songnamesplit,i often find situation i folder containing files named according certain file naming convention i go manually rename one i want a laborious repetitive task eg artistnamealbumtitlesongtitlesomethingelsemp songtitlemp so removal certain bits information replacement underscores spaces capitalisation not music example i thinking automating task using python basically i want able input starting convention wanted convention rename accordingly ideally i want able python windows i ubuntu machine i could use easier bash python unix if anyone shed light i might approach problem suggestion io python commands read contents folder rename files windows i might go stripping information filename categorising maybe using regex i see i make update progress,1 it clear form file trying modify i going assume looks like something like might work filter set lines opendatatxtreadlines outlines line lines linenumbers setintnum num linesplit filter amp linenumbers outlinesappendline lenoutlines lenlines opendatatxt wwritelinesoutlines i never clear implications open oneoff i use pretty regularly seem cause problems,i file f content huge numbers eg f so want loop file f delete lines contain numbers file say f f openfile f line f linecontainsany number f delete line f,1 import numpy np npeye print ashape b areshape print bshape,i array shape x i want convert array shape x is nice pythonic way,1 numpyreshapearray arrayshape,i array shape x i want convert array shape x is nice pythonic way,2 exclude set faster find items set open filteredtxt w open numberstxt iterates lines file l anyintx exclude x lsplit outwritel outclose i assuming file contains integer numbers separated,i file f content huge numbers eg f so want loop file f delete lines contain numbers file say f f openfile f line f linecontainsany number f delete line f,1 do use lambda functions builtin ones job also never use cmp argument sorted deprecated sorteds keystrlower sorteds keystrupper but may keep a order sortedsorteds keystrupper nature sorted operation fast almost sorted lists second sorted,i want sort string list lexicographic order str aaabbccde a b b c c e sorted gives output a b c e b c how i sort lexicographically,3 phpseclib pure php rsa implementation supports pss just rsasetsignaturemodecryptrsasignaturepss doesn pssr though,i developing cryptographic software license system based digital signature message recovery rsapssr it means signed message case license block encoded directly signature usually encode hash message want sign the license keys generated server private rsa key verified client code public key for i developped server client code c library crypto everything working well now i want rewrite server code scripting language like php perl python web hosting service accept native code what scripting language supports rsapssr scheme i done quick search google i found information,1 shadyabhi many subdirectories maybe speedup process using oslistdir multiprocessingprocess recurse folder,i building music file organizerin python i read metadata files amp put file required folder now i already ready command line interface script shows feedback way shows which file working right if directory contains say mp files kind feedback so i would like know efficient way find total number mps available directory scanning recursively subsequent directories my idea keep track total files processed show progress bar according is better way performance wise please feel free guide i want app kind platform dependent code if serious performance penalty sticking idea please suggest linux,1 in addition answers also use slicing numpynewaxis numpy import zeros newaxis zeros ashape b newaxis bshape or even work arbitrary number dimensions b newaxis bshape,i array shape x i want convert array shape x is nice pythonic way,3 you rely del called objects especially program ending see answer according pyqt documentation however slot lambda function partial function reference count automatically incremented prevent immediately garbage collected some circular references browser object might created connect signal lambda functions keeps destroyed as ui referenced browser get destroyed either so disconnect slots manually slots lambda functions use another method lambda bind extra parameters slot eg qsignalmapper signal qmenutriggered qaction parameter def initself parent item menuitems entry menuaddactionitem menutriggeredconnectselfdostuff def dostuffself entry print entrytext,i following files main windowui files ui coding utf form implementation generated reading ui file mainwindowui created sat apr pyqt ui code generator warning all changes made file lost pyqt import qtcore qtgui class uimainwindowobject presetting model model qtguiqfilesystemmodel def setupuiself mainwindow mainwindowsetobjectnamemainwindow mainwindowresize selfcentralwidget qtguiqwidgetmainwindow selfcentralwidgetsetobjectnamecentralwidget selfhorizontallayout qtguiqhboxlayoutselfcentralwidget selfhorizontallayoutsetobjectnamehorizontallayout selfhorizontallayout qtguiqhboxlayout selfhorizontallayoutsetobjectnamehorizontallayout selftreeview qtguiqtreeviewselfcentralwidget sizepolicy qtguiqsizepolicyqtguiqsizepolicyexpanding qtguiqsizepolicyexpanding sizepolicysethorizontalstretch sizepolicysetverticalstretch sizepolicysetheightforwidthselftreeviewsizepolicyhasheightforwidth selftreeviewsetsizepolicysizepolicy selftreeviewsetheaderhiddentrue selftreeviewsetobjectnametreeview selfhorizontallayoutaddwidgetselftreeview selfplaintextedit qtguiqplaintexteditselfcentralwidget sizepolicy qtguiqsizepolicyqtguiqsizepolicyexpanding qtguiqsizepolicyexpanding sizepolicysethorizontalstretch sizepolicysetverticalstretch sizepolicysetheightforwidthselfplaintexteditsizepolicyhasheightforwidth selfplaintexteditsetsizepolicysizepolicy selfplaintexteditsetobjectnameplaintextedit selfhorizontallayoutaddwidgetselfplaintextedit selfhorizontallayoutaddlayoutselfhorizontallayout mainwindowsetcentralwidgetselfcentralwidget menu selfmenubar qtguiqmenubarmainwindow selfmenubarsetgeometryqtcoreqrect selfmenubarsetobjectnamemenubar mainwindowsetmenubarselfmenubar setting tree view model selftreeviewsetmodelselfmodel selftreeviewsetselectionmodeqtguiqabstractitemviewextendedselection selftreeviewsetrootindexselfmodelsetrootpathxmldocumentdirectorypath hiding additional info treeview hheader selftreeviewheader hheaderhidesection hheaderhidesection hheaderhidesection mainwindowsetwindowtitleqtguiqapplicationtranslatemainwindow veloconddb browser none qtguiqapplicationunicodeutf qtcoreqmetaobjectconnectslotsbynamemainwindow def delself print destructor main window import sys import os browserclassui import uimainwindow pyqt import qtcore qtgui class browserqtguiqmainwindow def initself parentnone constructor main window qtguiqwidgetinitself parent selfui uimainwindow selfuisetupuiself menuitems open close menu selfuimenubaraddmenu file item menuitems entry menuaddactionitem selfconnectentry qtcoresignal triggered lambda itemitem selfdostuffitem def dostuffself item print item name main browser qtguiqapplicationsysargv myapp browser myappshow sysexitbrowserexec when lines menuitems selfconnect commented destructor ui never called if commented everything works fine any ideas,1 you best bet parsing excel files would xlrd library the pythonexcelorg site links examples xlrd related python excel libraries including pdf document good examples using xlrd of course also lots related xlrd questions stackoverflow might use one caveat xlrd library work xls excel earlier versions excel file formats recent xlsx file format there newer library openpyxl dealing xlsx i never used update as per john comment xlrd library supports xls xlsx file formats hope helps,i want parse excel document lists python is python library helpful action and functions relevant library,3 so i answering — sorry thatâ — i think might useful someone lost i wasâ so use arraybuffer set responsetype property xmlhttprequest object instance arraybuffer retrieving native array bytes converted base using following convenient function found author may blessed function basearraybufferarraybuffer var base var encodings abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz var bytes new uintarrayarraybuffer var bytelength bytesbytelength var byteremainder bytelength var mainlength bytelength byteremainder var b c var chunk main loop deals bytes chunks var mainlength combine three bytes single integer chunk bytesi bytesi bytesi use bitmasks extract bit segments triplet chunk amp b chunk amp c chunk amp chunk amp convert raw binary segments appropriate ascii encoding base encodingsa encodingsb encodingsc encodingsd deal remaining bytes padding byteremainder chunk bytesmainlength chunk amp set least significant bits zero b chunk amp base encodingsa encodingsb else byteremainder chunk bytesmainlength bytesmainlength chunk amp b chunk amp set least significant bits zero c chunk amp base encodingsa encodingsb encodingsc return base so working code var xhr new xmlhttprequest xhropen get httpsometldfaviconpng false xhrresponsetype arraybuffer xhronload functione consolelogbasearraybufferecurrenttargetresponse xhrsend this log valid base encoded string representing binary file contents edit for older browsers access arraybuffer btoa failing encoding characters another way get base encoded version binary function getbinaryfile var xhr new xmlhttprequest xhropenget file false xhroverridemimetypetextplain charsetxuserdefined xhrsendnull return xhrresponsetext function baseencodestr var chars abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz var len strlength c c c len c strcharcodeati amp xff len charscharatc charscharatc amp x break c strcharcodeati len charscharatc charscharatc amp x c amp xf charscharatc amp xf break c strcharcodeati charscharatc charscharatc amp x c amp xf charscharatc amp xf c amp xc charscharatc amp xf return consolelogbaseencodegetbinary httpwwwgooglefrimagessrprlogowpng hope helps others,i trying download binary file using xmlhttprequest using recent webkit baseencode contents using simple function function getbinaryfile var xhr new xmlhttprequest xhropenget file false xhroverridemimetypetextplain charsetxuserdefined xhrsendnull return xhrresponsetext function baseencodebinary return btoaunescapeencodeuricomponentbinary var binary getbinary httpsometldsamplepdf var baseencoded baseencodebinary as side note everything standard javascript stuff including btoa encodeuricomponent httpsdevelopermozillaorgendomwindowbtoa this works pretty smoothly i even decode base contents using javascript function basedecodebase return decodeuricomponentescapeatobbase var decodedbinary basedecodebaseencoded decodedbinary binary true now i want decode baseencoded contents using python consume json string get baseencoded string value naively i import urllib import base retrieving base encoded string json base uehdq……………oacga sourcecontents urllibunquotebasebdecodebase destinationfile opendestination wb destinationfilewritesourcecontents destinationfileclose but resulting file invalid looks like operation messaed utf encoding something still unclear if i try decode utf contents putting destination file error raised import urllib import base retrieving base encoded string json base uehdq……………oacga sourcecontents urllibunquotebasebdecodebasedecode utf destinationfile opendestination wb destinationfilewritesourcecontents destinationfileclose python testpy unicodeencodeerror ascii codec encode character u ufffd position ordinal range as side note screenshot two textual representations file left original right one created basedecoded string httpcllyugzcoex is known trick circumvent problems encoding attempting recreating file how would achieve any help hint much appreciatedâ,3 you copy code use configuratorinclude method include main application configuration new application the documentation explains pretty well essentially declare main apps configuration inside callable def mainappconfigconfig configaddroute imageupload adminimageupload view mainappviewsuploader viewrenderer siteuploadmako then include main app new app configuration like mymainapp import mainappconfig new application configurator setup etc include configincludemainappconfig continue new app configuration,simple question extending application lets say i main application application i following initpy file configaddroute imageupload adminimageupload view mainappviewsuploader viewrenderer siteuploadmako viewspy i def uploaderrequest code goes return xyz xyz now i create new application i want extend use view route in new application initpy file i would manually copy configaddroute code configaddroute imageupload adminimageupload view mainappviewsuploader viewrenderer mainapptemplatessiteuploadmako and i would need from would application able use view template main application i missing something else thanks reading,1 xlrd great simple tasks need work excel deeper functionality macros advanced plotting etc working windows machine use pywin library control wincom layer this provides access everything controlled via macros visual basic,i want parse excel document lists python is python library helpful action and functions relevant library,2 your modules automatically compiled pyc files imported memory affraid getting memory modules small common thousands modules loaded time you need know memory management python work edit you also write lot documentation code modules module read docstrings without increasing size speed modules loading compilingstep takes unnecessary text comments etc,i finished exercise beginners creating importing modules python i wondering everything module get imported computer memory will implications later memory code gets longer modules imported become numerous will i need know memory management write resourceefficient code,3 i imagine one way imports could abused leak memory you could dynamically create import modules arbitrary name say purpose creating plugin system use stop using if normal import machinery ie importvariablemodulename modules would added sysmodules even though used the solution well if really creating plugin system dynamic imports sort probably fine since plugins would get reused if really need use dynamically generated single use code use eval if really really need use importing dynamically generated code say automated testing probably need poke around sysmodules erase modules imported here nice article explaining something like,i finished exercise beginners creating importing modules python i wondering everything module get imported computer memory will implications later memory code gets longer modules imported become numerous will i need know memory management write resourceefficient code,2 operatorattrgetter,i vaguely remember learning sort builtin function would equivalent f lambda x xattr am i imagining thing exist,3 if want parse xlsx try pythonxlsx,i want parse excel document lists python is python library helpful action and functions relevant library,1 this slight touch glen maynard solution i think right way it adds padding element def hextobinself hexval takes string representation hex data arbitrary length converts string representation binary includes padding thelen lenhexval binval bininthexval lenbinval lt thelen binval binval return binval pulled class just take self working standalone script,i abcefff i want ie binary repr say digits leading zeroes how,3 getattrobj attr get attribute attr obj raise attributeerror exist you also supply default value getattrobj attr none case default returned instead raising exception attribute found object,i vaguely remember learning sort builtin function would equivalent f lambda x xattr am i imagining thing exist,1 try code usrbinenv python coding utf import pygtk pygtkrequire import gtk import gtkglade class hellowworldgtk def initself selfgladefile helloworldglade selfglade gtkbuilder selfgladeaddfromfileselfgladefile selfgladeconnectsignalsself selfgladegetobjectmainwindowshowall def onmainwindowdeleteeventself widget event gtkmainquit name main try hellowworldgtk gtkmain except keyboardinterrupt pass remember in glade edit preferences file gtkbuilder libglade,i made gui glade i want put python program i adapting instructions tutorial i found online load glade file httpwwwpygtkorgarticlespygtkgladeguicreatingaguiusingpygtkandgladehtm when i problems i tried something basic one button calling thing tutorial copy pasting code still work i also took look httpwwwlinuxjournalcomarticlepage function called slightly differently selfwtreegtkgladexml gladefilewindowname instead without windowname implemented equivalent mine fix i definitely pygtk working i made something without using glade worked fine the error i getting usrsharethemesnoxgtkgtkrc murrine configuration option gradients longer supported ignored helloworldpy libgladewarning expected gladeinterface got interface helloworldpy libgladewarning finish parserfinish state traceback recent call last file helloworldpy line module hwg hellowworldgtk file helloworldpy line init selfwtree gtkgladexmlselfgladefile runtimeerror could create gladexml object i running xubuntu the murrine configuration thing comes gtk application opens i included case relevant here code i took tutorial working usrbinenv python import sys try import pygtk pygtkrequire except pass try import gtk import gtkglade except sysexit class hellowworldgtk this hello world gtk application def initself set glade file selfgladefile pyhelloworldglade selfwtree gtkgladexmlselfgladefile get main window connect destroy event selfwindow selfwtreegetwidgetmainwindow selfwindowshow selfwindow selfwindowconnectdestroy gtkmainquit name main hwg hellowworldgtk gtkmain,3 as listed code always return none it goes recursion condition met drops end function returns none for example try def fx x return fx return x build something useful,how program exit function call i recursive function condition satisfied calls def function arg condition return function arg my guess works condition satisfied function call terminate in program seem case condition violated program jumps return statement perhaps return statement sees is sort exit i could put else clause,2 the best tool i know sage project it supports symbolic computation prettyprint equation terminal ascii terminal latex code straight pdf using latex it supersedes suggestions also offers interfaces matlab mathmatica maple etc,i writing code long mathematical equations many trigonometric identities is way visualising expression latex making c python expression way around how enter check mathematical expressions see brackets etc right position use latex documents thanks advance,1 combomethod create method object accessed specially wrapped function like methods access creates new object case new function object class a def initself selfdata instance combomethod def fooparam isinstanceparam a printthis paramdata method elif param a printthis class method a afoo function foo xcfe afoo function foo xcfe afoo this class method afoo this instance method it new access afoo afoo false afoo afoo false foo really wrapper disguise afoocodeconame wrapper when called class closure obj none note self refers combomethod reference original function object selfmethod printzipafoocodecofreevars afooclosure sep n obj cell xf nonetype object xedff self cell x combomethod object xd objtype cell xdd type object x when called attribute instance obj instance printzipafoocodecofreevars afooclosure sep n obj cell x a object xdfd self cell x combomethod object xd objtype cell xdd type object x here original function stored combomethod afooclosurecellcontentsmethod function foo xdcb afooclosurecellcontentsmethodcodeconame foo wrapper executes selfmethod either class instance first argument given value obj obj none return selfmethodobj args kwargs else return selfmethodobjtype args kwargs,one something like class master combomethod def fooparam parambar param could type well object class slaveclass master classmethod def barcls printthis class method slavetype slaveclass slavetypefoo class slaveinstance master def initself data selfdata data def barself printthis selfdata method slavetype slaveinstanceinstance slavetypefoo combomethod defined creating method simultaneously instance class method my question like default first parameter used parameter comboclass or least i pass object classmethod first parameter i know whats difference classmethod instancemethods decorators i might understand builtin classmethod self parameter passing made is technical limitations or combomethod allready built,1 pep style guide python code recomends order imports fallowing order standart library imports blank line google sdk imports blank line django imports blank line code imports import things use code remove unused imports you use one tools detect unused imports pydev eclipse pyflakes pylint you quite lot imports how big actual code it might good idea split modules why import single time single file well actually could like warning this example illustrates bad coding practices importallpy import import b import c otherpy importall import but please it good practices python development the zen python explicit better implicit namespaces one honking great idea let i also recommend read python documentation modules something python namespaces,the code works looks messy might code review question i study enough pythons conventions know structure organize beginning file pythonic i basically pasted imports could duplicates needed anymore wrongly ordered can advice anything structure imports i leave code like focus functions file future import withstatement import logging import os googleappengineapiusers import iscurrentuseradmin usernotfounderror import time import cgi import geogeotypes import main import captcha googleappengine import api googleappengineruntime import deadlineexceedederror googleappengineextwebapputil import runwsgiapp googleappengineextblobstore import blobinfo googleappengineextdb import djangoforms django import forms djangocoreexceptions import validationerror djangoutils import translation datetime import datetime timedelta osenviron djangosettingsmodule confsettings djangoconf import settings djangotemplate import requestcontext util import inhandler import util googleappengineapi import urlfetch taskqueue djangotemplatedefaultfilters import register djangoutils import simplejson json functools import wraps googleappengineapi import urlfetch taskqueue users images googleappengineext import db webapp search blobstore googleappengineextwebapp import util template googleappengineruntime import deadlineexceedederror random import randrange import cookie import base import cgi import conf import datetime import hashlib import hmac import logging import time import traceback import urllib import twitteroauthhandler twitteroauthhandler import oauthclient geogeomodel import geomodel djangoutilstranslation import gettextlazy webapptemplateregistertemplatelibrary commontemplatefilters file several instructions i understand future import withstatement coding utf import facebookconf import os wsgirefhandlers osenvironu djangosettingsmodule u conf import util import time import logging import urllib import wsgirefhandlers import appengineadmin import cgi import captcha import import hashlib import string import hmac import twitteroauthhandler twitteroauthhandler import oauthclient osenviron djangosettingsmodule confsettings geogeomodel import geomodel googleappenginedist import uselibrary googleappengineext import blobstore webapp db search template import must run django modules imports googleappengineextwebapp import blobstorehandlers util template googleappengineextblobstore import blobinfo googleappengineextwebapputil import runwsgiapp googleappengineapi import files images mail memcache users djangoconf import settings force django reload settingstarget none util import inhandler facebookbasehandler googleappengineextdb import djangoforms djangoutils import translation djangoutils import simplejson json djangocontribformtoolspreview import formpreview random import choice urllib import quote googleappengineapiusers import iscurrentuseradmin usernotfounderror googleappengineapi import urlfetch import random import datetime datetime import timedelta djangoutilstranslation import gettextlazy djangotemplate import defaultfilters how i know import longer used since function moved removed why i specify import multiple files one place i must spec import files i imagine moveing handling imports separate file ie importsyaml specify imports python files directory likewise,3 pep section imports i link directly basically organizing want imports grouped following order standard library imports related third party imports local applicationlibrary specific imports you put blank line group imports oh i believe pydev eclipse organize imports command,the code works looks messy might code review question i study enough pythons conventions know structure organize beginning file pythonic i basically pasted imports could duplicates needed anymore wrongly ordered can advice anything structure imports i leave code like focus functions file future import withstatement import logging import os googleappengineapiusers import iscurrentuseradmin usernotfounderror import time import cgi import geogeotypes import main import captcha googleappengine import api googleappengineruntime import deadlineexceedederror googleappengineextwebapputil import runwsgiapp googleappengineextblobstore import blobinfo googleappengineextdb import djangoforms django import forms djangocoreexceptions import validationerror djangoutils import translation datetime import datetime timedelta osenviron djangosettingsmodule confsettings djangoconf import settings djangotemplate import requestcontext util import inhandler import util googleappengineapi import urlfetch taskqueue djangotemplatedefaultfilters import register djangoutils import simplejson json functools import wraps googleappengineapi import urlfetch taskqueue users images googleappengineext import db webapp search blobstore googleappengineextwebapp import util template googleappengineruntime import deadlineexceedederror random import randrange import cookie import base import cgi import conf import datetime import hashlib import hmac import logging import time import traceback import urllib import twitteroauthhandler twitteroauthhandler import oauthclient geogeomodel import geomodel djangoutilstranslation import gettextlazy webapptemplateregistertemplatelibrary commontemplatefilters file several instructions i understand future import withstatement coding utf import facebookconf import os wsgirefhandlers osenvironu djangosettingsmodule u conf import util import time import logging import urllib import wsgirefhandlers import appengineadmin import cgi import captcha import import hashlib import string import hmac import twitteroauthhandler twitteroauthhandler import oauthclient osenviron djangosettingsmodule confsettings geogeomodel import geomodel googleappenginedist import uselibrary googleappengineext import blobstore webapp db search template import must run django modules imports googleappengineextwebapp import blobstorehandlers util template googleappengineextblobstore import blobinfo googleappengineextwebapputil import runwsgiapp googleappengineapi import files images mail memcache users djangoconf import settings force django reload settingstarget none util import inhandler facebookbasehandler googleappengineextdb import djangoforms djangoutils import translation djangoutils import simplejson json djangocontribformtoolspreview import formpreview random import choice urllib import quote googleappengineapiusers import iscurrentuseradmin usernotfounderror googleappengineapi import urlfetch import random import datetime datetime import timedelta djangoutilstranslation import gettextlazy djangotemplate import defaultfilters how i know import longer used since function moved removed why i specify import multiple files one place i must spec import files i imagine moveing handling imports separate file ie importsyaml specify imports python files directory likewise,1 ok yield ing tuple four numbers time iterated so convert whole thing list l listgroupiteryourlist n then list tuples l you get first item tuple way firsts tup tup l there ways course,i new python list numbers eg i grouped fours etc using code post def groupiteriterator n strictfalse transforms sequence values sequence ntuples eg n if strict raise valueerror group fewer n items end sequence accumulator item iterator accumulatorappenditem lenaccumulator n tested fast separate counter yield tupleaccumulator accumulator tested faster accumulator tested fast reusing one list object strict lenaccumulator raise valueerrorleftover values how i access individual arrays i perform functions for example i like get average first values every group eg example numbers,1 let say following tuple tuples to access first element tuple use forloop print to calculate average first values elementsi avgsumelementsfloatlenelements,i new python list numbers eg i grouped fours etc using code post def groupiteriterator n strictfalse transforms sequence values sequence ntuples eg n if strict raise valueerror group fewer n items end sequence accumulator item iterator accumulatorappenditem lenaccumulator n tested fast separate counter yield tupleaccumulator accumulator tested faster accumulator tested fast reusing one list object strict lenaccumulator raise valueerrorleftover values how i access individual arrays i perform functions for example i like get average first values every group eg example numbers,1 you created tuple tuples list tuples list lists tuple lists whatever you access element nested list directly toplistxy yields yth element xth nested list you also access nested structures iterating top structure list lists print listy,i new python list numbers eg i grouped fours etc using code post def groupiteriterator n strictfalse transforms sequence values sequence ntuples eg n if strict raise valueerror group fewer n items end sequence accumulator item iterator accumulatorappenditem lenaccumulator n tested fast separate counter yield tupleaccumulator accumulator tested faster accumulator tested fast reusing one list object strict lenaccumulator raise valueerrorleftover values how i access individual arrays i perform functions for example i like get average first values every group eg example numbers,1 once used pylint identify duplicate unused imports organized according pep answers suggest clean changing way import packages instead googleappengineapi import urlfetch taskqueue users images could googleappengine import api would need put apiurlfetch apitaskqueue etc wherever use this right way another way you choose one prefer also note use aliases googleappengine import api gaeapi would put gaeapiurlfetch this useful need import modules called api multiple packages also answer question why i specify import multiple files one place i must spec import files importing packages multiple files could indicate files closely related merged single file unlike c java every class file pythonic way make module file selfcontained possible usually means contain multiple classes functions,the code works looks messy might code review question i study enough pythons conventions know structure organize beginning file pythonic i basically pasted imports could duplicates needed anymore wrongly ordered can advice anything structure imports i leave code like focus functions file future import withstatement import logging import os googleappengineapiusers import iscurrentuseradmin usernotfounderror import time import cgi import geogeotypes import main import captcha googleappengine import api googleappengineruntime import deadlineexceedederror googleappengineextwebapputil import runwsgiapp googleappengineextblobstore import blobinfo googleappengineextdb import djangoforms django import forms djangocoreexceptions import validationerror djangoutils import translation datetime import datetime timedelta osenviron djangosettingsmodule confsettings djangoconf import settings djangotemplate import requestcontext util import inhandler import util googleappengineapi import urlfetch taskqueue djangotemplatedefaultfilters import register djangoutils import simplejson json functools import wraps googleappengineapi import urlfetch taskqueue users images googleappengineext import db webapp search blobstore googleappengineextwebapp import util template googleappengineruntime import deadlineexceedederror random import randrange import cookie import base import cgi import conf import datetime import hashlib import hmac import logging import time import traceback import urllib import twitteroauthhandler twitteroauthhandler import oauthclient geogeomodel import geomodel djangoutilstranslation import gettextlazy webapptemplateregistertemplatelibrary commontemplatefilters file several instructions i understand future import withstatement coding utf import facebookconf import os wsgirefhandlers osenvironu djangosettingsmodule u conf import util import time import logging import urllib import wsgirefhandlers import appengineadmin import cgi import captcha import import hashlib import string import hmac import twitteroauthhandler twitteroauthhandler import oauthclient osenviron djangosettingsmodule confsettings geogeomodel import geomodel googleappenginedist import uselibrary googleappengineext import blobstore webapp db search template import must run django modules imports googleappengineextwebapp import blobstorehandlers util template googleappengineextblobstore import blobinfo googleappengineextwebapputil import runwsgiapp googleappengineapi import files images mail memcache users djangoconf import settings force django reload settingstarget none util import inhandler facebookbasehandler googleappengineextdb import djangoforms djangoutils import translation djangoutils import simplejson json djangocontribformtoolspreview import formpreview random import choice urllib import quote googleappengineapiusers import iscurrentuseradmin usernotfounderror googleappengineapi import urlfetch import random import datetime datetime import timedelta djangoutilstranslation import gettextlazy djangotemplate import defaultfilters how i know import longer used since function moved removed why i specify import multiple files one place i must spec import files i imagine moveing handling imports separate file ie importsyaml specify imports python files directory likewise,3 i guess equivalent typeerror unbound method must called instance first argument got instance instead to add setter property via decorator use setter membermethod property object static methodclassmethod property the code supposed look like class tableobject a csv backed sql table property def fieldnamesself openselffilename f return csvdictreaderffieldnames fieldnamessetter def fieldnamesself fieldnames openselffilename w f dr csvreaderf dw csvdictwriterf fieldnamesfieldnames dwwriterowdictfield field field fieldnames row self dwwriterowrow also see example documentation,so i code table object property fieldnames class tableobject a csv backed sql table property def fieldnamesself openselffilename f return csvdictreaderffieldnames propertysetter def fieldnamesself fieldnames openselffilename w f dr csvreaderf dw csvdictwriterf fieldnamesfieldnames dwwriterowdictfield field field fieldnames row self dwwriterowrow while may seem well good i try import file i get error seaspennappsuite ceasarbautista python python r jun gcc based apple inc build llvm build darwin type help copyright credits license information import table traceback recent call last file stdin line module file tablepy line module class tableobject file tablepy line table propertygetter typeerror descriptor getter requires property object received function can anybody explain error means,3 in general replace shell pipeline pattern p popendmesg stdoutpipe p popengrep hda stdinpstdout stdoutpipe pstdoutclose allow p receive sigpipe p exits output pcommunicate however case pipeline necessary import subprocess import shlex import url httpurlvideomp procsubprocesspopenshlexsplit ffmpeg f formatfurl stdoutsubprocesspipe stderrsubprocesspipe dimensionsnone line procstderr matchresearchr dxd line match dimensionsmatchgroup break printdimensions,i following command ffmpeg httpurlvideomp amp perl lane print dxd x i trying set output command python variable here i far subprocess import popen pipe p popen ffmpeg httpurlvideomp amp stdoutpipe ppopen perl lane print dxd stdinpstdout stdoutpipe dimensions pcommunicate what i incorrectly would i get correct value dimensions,1 i suggest use gdb look core dump file you control gdb python invoke control gdb python but recent versions gdb python built you might able want within gdb rather running gdb within python httpsourcewareorggdbwikipythongdb ps you would probably interested book gray hat python httpnostarchcomghpythonhtm,i looking python script dump elf file type coredump any pointers existing scripts,1 no need call perl within python if output ffmpeg variable something like print researchr dxd strgroup,i following command ffmpeg httpurlvideomp amp perl lane print dxd x i trying set output command python variable here i far subprocess import popen pipe p popen ffmpeg httpurlvideomp amp stdoutpipe ppopen perl lane print dxd stdinpstdout stdoutpipe dimensions pcommunicate what i incorrectly would i get correct value dimensions,2 in general speaking terms property attribute thing however property decorator python provides gettersetter access attribute data class myobjectobject this normal attribute foo property def barself return selffoo barsetter def barself value selffoo value obj myobject assert objfoo assert objbar objfoo objbar assert objfoo assert objbar objfoo,i generally confused difference property attribute find great resource concisely detail differences,3 with property complete control getter setter deleter methods thing using caveats attribute class aobject x ax attribute property def xself ax property this getter method return selfx xsetter def xself value this setter method i check assigned value value raise valueerrormust selfx value a ax ax traceback recent call last file expy line module ax file expy line x raise valueerrormust valueerror must,i generally confused difference property attribute find great resource concisely detail differences,3 just thought instead list variation word look difflib getclosematches appel ape apple peach puppy apple ape import keyword getclosematches wheel keywordkwlist getclosematches apple keywordkwlist getclosematches accept keywordkwlist except,i text file contains several spelling variants many words for eg identification id identitycontract contr contractormedicinepillstables so i want synonym text file contains words synonyms would like replace variants primary word essentially i want normalize input file for eg synonym list file would look like identification id identify contracting contract contractor contractors contra word word word word wordn medicine pills tables drugs i want end output file look like identification identification identificationcontractor contractor contractormedicinemedicinemedicine how i got programming python thanks lot help,2 the property allows get set values like would normal attributes underneath method called translating getter setter it really convenience cut boilerplate calling getters setters lets say example class held x coordinates something needed to set might want something like myobjx myobjy that much easier look think writing myobjsetx myobjsety the problem one day class changes need offset x value now would need go change class definition code calls could really time consuming error prone the property allows use former syntax giving flexibility change latter in python define getters setters delete methods property function if want read property also property decorator add method httpdocspythonorglibraryfunctionshtmlproperty,i generally confused difference property attribute find great resource concisely detail differences,3 yes we new relic announced python agent djangocon week sign newreliccom enjoy,does django anything equivalent new relic rpm performance monitoring app rails httpwwwnewreliccom looking app django would really like able use something like new relic monitoring performance,3 you could read synonym file convert dictionary table import table open synonyms r syn line syn matchrematchr wss line match primarysynonymsmatchgroups synonymssynonymlower synonym synonymssplit synonym synonyms tablesynonymprimarylower printtable yields word word word word word word contr contracting contract contracting contractor contracting contra contracting identify identification contractors contracting wordn word id identification next could read text file replace word primary synonym table open textfile r f line f print jointablegetwordlowerword word refindallr ww line yields identification identification identity contracting contracting contracting medicine medicine medicine refindallr ww line used split line preserving whitespace if whitespace interest could also use easier linesplit tablegetwordword returns tableword word table simply returns word word synonym table,i text file contains several spelling variants many words for eg identification id identitycontract contr contractormedicinepillstables so i want synonym text file contains words synonyms would like replace variants primary word essentially i want normalize input file for eg synonym list file would look like identification id identify contracting contract contractor contractors contra word word word word wordn medicine pills tables drugs i want end output file look like identification identification identificationcontractor contractor contractormedicinemedicinemedicine how i got programming python thanks lot help,2 have considered using json instead xml it less verbose readable converted readytouse python data structure for example import json x field name health value name toxicity value name life class heroattributeslife attributejsonloadsx u class u heroattributeslife u field u name u health u value u name u toxicity u value u name u life and convert dict back json attrjsondumpsattribute,i developing video game i like highly modable currently game logic defined python engine logic c data xml i like explain entity defined game listen think example verbose first background entities made components componentbased entity model components two types attributes behaviors attributes dumb data they things like health speed etc behaviors define entity interacts attributes world entities defining attribute i go piece piece first i explain define attribute in python attribute might look something like class lifeattribute def initself default values selfhealth selftoxicity pretty basic now xml file field attribute given different value entity define attribute namelifename classheroattributeslifeclass field namehealthname valuevalue field field nametoxicityname valuevalue field attribute name mdash identifier attribute kinda like objects python will useful define behaviors class mdash python class attribute field mdash field attribute fieldname mdash must python field selfhealth rarr health fieldvalue mdash value field defining behavior as i said earlier behaviors interact entity attributes for example damage behavior needs know life attribute class damagebehavior def initself selflife none the xml code setting behavior similar attribute identical behavior classherobehaviorsdamageclass attribute fieldlifefield linklifelink attribute behavior class mdash python class behavior attributefield mdash field behavior reference attribute placed attributelink mdash attribute link must one value name tags attributes defined,1 you use command line tool syslog os x get syslog events,i pretty new python programming i question how i log python application activity varlog mac os x i tried using syslog module seem write anything i tried also logging module i always run permission error how i update import logging import time logfilename varlogwriteuplog timestrftimeymd logformat asctimes filenames levelnames messages log logginggetloggermainpy logsetlevelloggingdebug ch loggingfilehandlerlogfilename chsetlevelloggingdebug format loggingformatterlogformat chsetformatterformat logaddhandlerch,1 the path least resistance migrating app engine application probably using appscale implements major portion app engine api in particular might want use hypertable datastore closely mirrors google app engine datastore edit ok going redesign i like go points make question low memory usage that pretty much opposite want database you want much dataset core memory possible this could mean tuning dataset fit efficiently adding memcached nodes spread dataset across several hosts host small enough fraction dataset fits core to drive point home consider reading value ram times faster reading disk a database satisfy every query core handle times workload compared database visit disk queries i planning huge dataset around gb i think could call gb huge dataset in fact something could probably fit ram reasonably large database server you need one memcached node much less additional persistance nodes typical disk sizes terabytes times larger expected dataset based information i would definitely advise using mature database product like postgresql would give plenty performance data describing easily provides features talking if time comes need scale past postgresql actually provide actually real workload analyse know bottlenecks really,i migrating gaejava app python nongae due new pricing i getting little server i would like find database fits following requirements low memory usage tuneable predictible fastest querying capability simple documenttreelike data identified key i care performance writing i assume indexes bindings pypy compatibility python least my data goes something like id short key string title creators array another data structure id used key name site address etc tags array tags each multiple parent tags name id etc license data structure describes license cc gpl say name associated url etc addition time add site translations pointers entries translations one creation my queries simple usual cases filter tag ordered addition time select pagination ordered addition time maybe done already filter creator not done planned autocomplete features forms i going need search fields contains substring like queries the data volume big right i mb data i planning huge dataset around gb also i want rebuild scratch i open option what database think meet requirements edit i want benchmarks around different options share results i selected far mongodb postgresql mysql drizzle riak kyoto cabinet,2 since post tagged ironpython want use sample c following work import clr clraddreference assembly name dataviewerlibrary import plotdata p plotdata pstart,anyone share working example call simple c library actually wpf python code i tried using ironpython much trouble unsupported cpython library python code using i thought trying way around calling c code python here example i playing using systemruntimeinteropservices using systementerpriseservices namespace dataviewerlibrary public interface isimpleprovider dispidattribute void start comvisibletrue classinterfaceclassinterfacetypenone public class plotdata servicedcomponent isimpleprovider public void start plot plotter new plot plottershowdialog plotter wpf windows plots ellipse i know call code python any suggestions,3 the table class extending class called object it argument the reason may want extend object explicitly turns class newstyle class if explicitly specify extends object python default oldstyle class since python classes newstyle whether explicitly extend object for information newstyle oldstyle classes please see question,i trying translate python code scala code so i total noob python but classes object parameter never explicitly use what reasoning parameter first place example class tableobject thank time,3 class table class tableobject different python it parameter extending object base class like many languages all says inherits whatever defined object this default behaviour,i trying translate python code scala code so i total noob python but classes object parameter never explicitly use what reasoning parameter first place example class tableobject thank time,1 in python declares table newstyle class opposed classic class in python classes newstyle classes longer necessary new style classes special attributes classic classes lack class classic pass class newstyleobject pass printdirclassic doc module printdirnewstyle class delattr dict doc format getattribute hash init module new reduce reduceex repr setattr sizeof str subclasshook weakref also properties super work classic classes in python good idea make classes newstyle classes though lot classes standard library still classic classes sake backwardcompatibility in general statement class foobase base foo declared class inheriting base classes base base object mother classes python it newstyle class inheriting object makes table newstyle class,i trying translate python code scala code so i total noob python but classes object parameter never explicitly use what reasoning parameter first place example class tableobject thank time,3 you could use tuple key text aaabbccde sortedtextkeylambda xstrlowerxx a b b c c e the first element tuple strlowerx primary key making come b x breaks ties making a come,i want sort string list lexicographic order str aaabbccde a b b c c e sorted gives output a b c e b c how i sort lexicographically,3 use celery subtasks this allow start longrunning task many shortrunning subtasks underneath keep good data execution status within celery task result store as added bonus subtasks spread across worker proccesses allowing take full advantage multicore servers even multiple servers order reduce task runtime httpaskgithubcomceleryuserguidetasksetshtmltasksets httpdocsceleryprojectorgenlatestreferencecelerytasksetshtml edit example import time logging log celerytask import task celerytasksets import taskset app import entry tasksenderroremailstrue def longrunninganalysis entries listentryobjectsallvalues id numentries lenentries taskset tasksetanalyseentrysubtaskentryid entry entries results tasksetapplyasync resultsready timesleep print loginfolongrunninganalysis complete completedcountnumentries resultsfailed logerroranalysis failed resultset resultsjoin brings back results order entries perform collating count percentage calculations logerroranalysis complete task def analyseentryid inputs must serialisable logger analyseentrygetlogger entry entryobjectsgetidid try analysis entryanalyse loggerinfo found entry analysis status return analysis must dict serialisable except exception e loggererrorcould process entry e return none if calculations cannot seggregated perentry tasks always set one subtask performs tallys one subtask performs another analysis type still work still allow benifit parelelleism,longtime days think tasks django orm data i look around didnt find good solutions djangotasks httpcodegooglecompdjangotasks well documented dont ideas use celery httpaskgithubcomcelery excessive tasks is good longtime tasks so need get data parts data database like entryobjectsall and need execute function one queryset i think work around days so maybe someone explain build psat moment one idea use cron database store process execution timeline,1 x rawinput enter number enter number x typex type str x traceback recent call last file stdin line module typeerror cannot concatenate str int objects typeintx type int intx using python use input instead rawinput,edit solvedsource code here httpmatthewdowneyblogspotcomsourcecodeforrokuremotehackhtml thanks advance reading possibly answering so i slice code looks like commands down select up predefined def crow rowdown row rowup row rowdown down rowdown rowdown timesleep select timesleep rowup up rowup rowup timesleep so i run either c c jut number stops responding error anything executes first down command doesnt seem get past rowdown rowdown so figure maybe stuck timesleep isnt executing select remove timesleep code get error like traceback recent call last file testpy line module c file testpy line c rowdown rowdown typeerror unsupported operand types str int code snippet part larger program designed controlling roku player computer far everything worked automate typing search field continually scroll find letter select crow would column row x would like source code program would happy send anyway thanks listening,1 perhaps meant rowdown note written without quotes if call c c c also cpython version version integers comparable strings answer might expect false when comparing integer string integer always less string believe integer comes string alphabet as tokenmacguy already pointed addition integers strings raises typeerror typeerror unsupported operand types int str this might explain error seeing calling c,edit solvedsource code here httpmatthewdowneyblogspotcomsourcecodeforrokuremotehackhtml thanks advance reading possibly answering so i slice code looks like commands down select up predefined def crow rowdown row rowup row rowdown down rowdown rowdown timesleep select timesleep rowup up rowup rowup timesleep so i run either c c jut number stops responding error anything executes first down command doesnt seem get past rowdown rowdown so figure maybe stuck timesleep isnt executing select remove timesleep code get error like traceback recent call last file testpy line module c file testpy line c rowdown rowdown typeerror unsupported operand types str int code snippet part larger program designed controlling roku player computer far everything worked automate typing search field continually scroll find letter select crow would column row x would like source code program would happy send anyway thanks listening,2 i think asking lambda function treefunction lambda xy mult addx then use treefunction edit have read closures python definitely worth time learn,i want something like def multx return x def addx return x treefunction mult addx outputs print treefunction basically way runtime change add return value multiplying value,3 proxybypassregistry urllibpy handle proxyoverride registry value properly treats empty override ie bypass proxy hosts this behavior match programs eg chrome there number possible workarounds set urllibproxybypass lambda h disable bypass checking specify proxy settings httpproxy environment variable proxybypassregistry called case in fiddler go page toolsfiddler options connections remove trailing semicolon value ie bypass fiddler field restart fiddler,i fiddler listening try data proxy urllibproxyhandler http also tried http http opener urllibbuildopenerproxy urllibinstallopeneropener req urllibrequest httpwwwgooglecom response urlliburlopenreq thepage responseread print thepage except exception detail print err detail i see get request google fiddler i see requests way debug seems like python bypasses fiddler ignores proxy i also configured winhttp work fiddler cwindowssystemnetsh winhttp set proxy current winhttp proxy settings proxy servers bypass list none matter request ssl address fiddler supports https thanks,1 sure use slice indexing alist blist just demonstrate general algorithm implement myextend function hypothetical custom list class would look like def myextendself otherlist index selfindexindex otherlist but actually make function use slice notation need,i looking pythonic way implement version list extend function extends given index instead end list alist i rad list blist alistmyextend blist insert items blist alist index print alist would output i rad list is way without building new list like alist i rad list blist clist clistextend alist clistextend blist clistextend alist print clist outputs i rad list that approach actually bad i hunch could easier could,3 you import ed gdata gdatadocsclient add rest import import gdatadocsclient,i trying set oauth google services following example i using try xmletree import elementtree except importerror elementtree import elementtree import gdatacalendardata import gdatacalendarclient import gdataacldata import gdata import atom import getopt import sys import string import time consumerkey xxx consumersecret xxx token xxx tokensecret xxx client gdatadocsclientdocsclientsource xxx and python throws attributeerror module object attribute docs tries create client,1 yes possible i think error done put class meta abstract true abstractadminmodel class try without meta class,is inheritance possible admin models like for example consider following file modelspy class abstractmodel modelsmodel meta information common classes author modelsforeignkeyauthmodelsuser null false relatednameclasssrelatedauthor the user created editor modelsforeignkeyauthmodelsuser null truerelatednameclasssrelatededitor the user last edited createdat modelsdatetimefieldautonowadd true create time editedat modelsdatetimefieldautonow true modify time class meta abstract true class topic abstractmodel name modelscharfieldmaxlength namemaxlength unique true versionnumber modelsintegerfielddefault updatefrequency modelsintegerfield a similar inheritance seem produce correct result used modeladmin file adminpy class abstractadminmodel adminmodeladmin fields author editor createdat editedat readonlyfields author editor createdat editedat def savemodelself request obj form change change objauthor requestuser else objeditor requestuser objsave class admintopic abstractadminmodel fields name versionnumber updatefrequency adminsiteregister topic admintopic edit i modified model based suggestions if adminpy like i get error model appears admin class abstractadminmodel adminmodeladmin passfields author editor createdat editedat class admintopic abstractadminmodel pass adminsiteregister topic admintopic but if modify like class abstractadminmodel adminmodeladmin fields author editor createdat editedat class admintopic abstractadminmodel pass adminsiteregister topic admintopic i get following error here stack trace link problem the model even appear admin page extra info using django pinax ubuntu python,1 the problem class admintopic adminmodeladmin this line controls inheritance class admintopic abstractadminmodel also worth noting may wish use topicadmin rather admintopic better match django convention,is inheritance possible admin models like for example consider following file modelspy class abstractmodel modelsmodel meta information common classes author modelsforeignkeyauthmodelsuser null false relatednameclasssrelatedauthor the user created editor modelsforeignkeyauthmodelsuser null truerelatednameclasssrelatededitor the user last edited createdat modelsdatetimefieldautonowadd true create time editedat modelsdatetimefieldautonow true modify time class meta abstract true class topic abstractmodel name modelscharfieldmaxlength namemaxlength unique true versionnumber modelsintegerfielddefault updatefrequency modelsintegerfield a similar inheritance seem produce correct result used modeladmin file adminpy class abstractadminmodel adminmodeladmin fields author editor createdat editedat readonlyfields author editor createdat editedat def savemodelself request obj form change change objauthor requestuser else objeditor requestuser objsave class admintopic abstractadminmodel fields name versionnumber updatefrequency adminsiteregister topic admintopic edit i modified model based suggestions if adminpy like i get error model appears admin class abstractadminmodel adminmodeladmin passfields author editor createdat editedat class admintopic abstractadminmodel pass adminsiteregister topic admintopic but if modify like class abstractadminmodel adminmodeladmin fields author editor createdat editedat class admintopic abstractadminmodel pass adminsiteregister topic admintopic i get following error here stack trace link problem the model even appear admin page extra info using django pinax ubuntu python,1 the builtin fraction class appear support mixed fractions like hard split space for example fractionsfraction simplistic def convertf whole frac fsplit return intwhole fractionsfractionfrac,i wondering i could easily convert mixed number entered number string floating point number integer i looked fractions module seems like i want i read well just wanted know something already exists i write function here i looking btw convert convert thanks,3 in trying duplicate error i following i assume homebrewer done brew install python to install python brew install mysql to install mysql system needed various drivers configured mysql per homebrew recommendations downloaded mysqlpython unzipped installed mysqlpython using python setuppy install tested interactive session python import mysql after walking steps lion i unable reproduce error now debugging issue a things check in terminal type python point homebrew install keep mind homebrew sitepackages stored cellar stored usrlocallibpythonsitepackages see post info i add sitepackages location path might give try the last thing i could suggest try order get easyinstall work homebrew python i add usrlocalsharepython path edit after rereading error messages mainly scrolling way right i noticed unable load mysql library a quick google search library made seem installing mysql os x difficulties linking try locate file libmysqlclientdylib note path after installing mysql via homebrew mine usrlocalcellarmysqllib the common fix i seen fix environment variable dyldlibrarypath for information i got check site using path example i would add line bashprofile export dyldlibrarypathdyldlibrarypathusrlocalcellarmysqllib if work i would strongly look possibility mysql installed correctly issues with mindset hopefully something pop lastly sql databaes yet might i suggest uninstalling mysql installing via homebrew i zero trouble setup,i running python brew install i went install mysqlpython egg setup tools standard install according mysqlpython instructions installed usrlocallibpythonsitepackages the dependencies processed etc then i went run python console i import things eg import django print djangoversion works i import mysqldb i get following error traceback recent call last file stdin line module file usrlocalcellarpythonlibpythonsitepackagesmysqlpythonpymacosxxeggmysqldbinitpy line module import mysql importerror dlopenusrlocalcellarpythonlibpythonsitepackagesmysqlpythonpymacosxxeggmysqlso library loaded libmysqlclientdylib referenced usrlocalcellarpythonlibpythonsitepackagesmysqlpythonpymacosxxeggmysqlso reason image found any insight thanks much,3 there two ways send json object form server side processing saving database st way extajaxrequest url yourserverurltopostto method post get put delete case sensitive jsondata yourjsonobject params yourrequestparameters success functionresponse callback function failure functionresponse callback failure function for direct form submission extformactionsubmit form yourforminstance method post url urltopostto params request params another way yourformsubmit config options except form yourforminstance read docs config options suit needs documentation pretty good for learning good coding style ext js check examples part download package,i new extjs i wanted know i send json object backend extjs page i using python connect databse what i wanted user enters data form data transfered database i getting good tutorials online can someone please help thanks advance,2 your best bet would natural language toolkit httpwwwnltkorg one data modules called wordnet shows approximate distance meaning words example assuming countries national adjectives could certainly use api find need,i looking python library return adjectival form country for example given brazil would return brazilian given greece would return greek if lib like available i crawl thie wiki page make i want replicate effort case someone already done httpenwikipediaorgwikilistofadjectivalanddemonymicformsofplacenames,1 i really sure want code i read display image via hexbin the thresholding wether display hexagon part seems like mincnt parameter hexbin if none display cells mincnt number points cell for complicated things generate masked arrays x c is want if code give starting point import numpy np import matplotlibpyplot plt def generatexyprobmap probmapshape x npmeshgridnparanges nparanges return xravel yravel def heatmapprobmap x generatexyprobmap pltfigure plthexbinx cprobmapravel probs nprandomrand heatmapprobs pltshow the difference functions additional probs nprandomrand heatmapprobs pltshow seen figures code including stripes code random like,i want produce heatmap image akin one answer the difference i want array values what i tried def generatexyvectorsprobmap multiplier xs ys rangelenprobmap x rangelenprobmapy count intprobmapyx multiplier xsextendx count ysextendy count return xs ys def heatmapprobabilities probabilities nxn array n lenprobabilitymap gridsize n xs ys generatexyvectorsprobabilitymap pltfigure plthexbinxs ys cnone gridsizegridsize mincnt pltaxis n n the major problem i cannot tune gridsize make neat map lots white space end making striped effect etc in either case i imagine much better way without go tedious generating points ideally i like mechanism threshold whether plot hexagon i done my motivation i simple variable markov chain sum variables cannot exceed value n i got array probability initial condition so heat map would triangle encompassed area x ny,1 the issue explained httpinputvalidationblogspotcompythonpyqtandmissingqstringhtml the reason load qstring missing pyqt maybe earlier knows since pyk opposed pyk supports unicode default need class instead qstring compatibility reasons use snippet somewhere around import try pyqtqtcore import qstring except importerror qstring str,my development eviroment os windows xp python pythonmsi pyqt pyqtpygplexe code import sys pyqt import qtcore qtgui app qtguiqapplicationsysargv qtcoreqtstring sysexitappexec it always show module qtcoreqtstring attributeerror module object attribute qtstring i chaged code import sys pyqtqtgui import pyqtqtcore import app qapplicationsysargv qtstring sysexitappexec then always show like module qtstring nameerror name qtstring defined,1 what exactly local variable mean context i struggling terminology mean variables created function also variable created function parameters what variables scope eg globals self local variables name bindings created inside function this includes function parameters variables assigned eg following def funcfruwappah qitzynone fruwappah fruitcake plain else fruitcake qitzy frosting orange variables fruwappah qitzy fruitcake frosting local oh since self function header example also local how closures affect potential circular references traceback the general thought closure reference everything enclosing function traceback reference closure end referencing quite bit i struggling come concrete example combination inner function code returns sysexcinfo expensiveshortlivedobjects scope somewhere as answer linked states traceback references every function variables active time exception occurred in words whether closure involved irrelevant assigning closure nonlocal matter global variable create circular reference there two basic ways deal define function called exception raised stack frame traceback ends variables including traceback go away make sure del tracebackobject done having said i yet need traceback object code exception along various attributes sufficient far,i aware sysexcinfo documentation says take care dealing traceback objects still uncertain safe unsafe cases additionally documentation says warning don followed immediately note actually ok confuses in case docs why need explicitly delete sysexcinfo traceback python alex martelli answer seem imply local variables reference traceback value assigned cause problem this leaves questions what exactly local variable mean context i struggling terminology mean variables created function also variable created function parameters what variables scope eg globals self how closures affect potential circular references traceback the general thought closure reference everything enclosing function traceback reference closure end referencing quite bit i struggling come concrete example combination inner function code returns sysexcinfo expensiveshortlivedobjects scope somewhere feel free tell conclusions assumptions wrong i reasoned belief nonbelief statements several times i written while i like answers specific examples i also asking general advice knowledge war stories safely deal tracebacks esoteric situations eg run loop want accumulate raised exceptions spawn new thread need report raised exceptions create closures callbacks communicate back raised exceptions etc example inner function error handling def dowebrequest thread errorqueue createthreaderrorraisingfunc threadstart threadjoin errorqueueempty purposefully calling errorqueueget illustrative purposes print error def createthreadfunc errorqueue queuequeue def handled try func except exception errorqueueputsysexcinfo thread threadingthreadtargethandled return thread errorqueue does handled closure cause raised exception reference errorqueue result circular reference errorqueue also contains traceback is removing traceback errorqueue ie calling get enough eliminate circularreference example long lived object scope excinfo returning excinfo longlivedcache def alphakey expensiveobject longlivedcachegetkey expensiveobject expensiveobject computeexpensiveobject longlivedcachekey expensiveobject excinfo alphasubexpensiveobject excinfo print error excinfo def alphasubexpensiveobject try errorraisingfuncexpensiveobject return none except exception return sysexcinfo does raised exception alphasub reference expensiveobject expensiveobject cached traceback never goes away if one break cycle alternatively excinfo contains alpha stack frame alpha stack frame contains reference excinfo resulting circular reference if one break cycle,2 if understand question need use attributes width height reference googleappengineapiimagesimage an example flux imgread from request imageref imageimagedataflux w imagerefwidth h imagerefheight,how know width height image using appengine image api wit python someone adviesed use composite function pass image sole input image specify canvas size desired size output image understand simple example helpful thanks advance,2 properties special kind attribute basically python encounters following code spam someobject printspameggs looks eggs spam examines eggs see get set delete methodthinspmdashthinspif property if property instead returning eggs object would attribute call get method since lookup return whatever method returns more information python data model descriptors,i generally confused difference property attribute find great resource concisely detail differences,3 use pythonbrew experiment different version python one system pythonbrew program automate building installation python users home,i python installed mac os x i wanted play around python created virtual enviromant using virtualenv python activated using source pythonbinactivate i update python virtualenv leave system python untouched if yes i install python using pip install,1 why i specify import multiple files one place i must spec import files to answer question allimportspy import googleappengine gae import geo import catptcha otherpy allimports import using import bad practice handled poorly example importing five modules way end lots names module namespace becomes difficult track variablefunctionclass came when handled properly example great tool gae come oh must allimports i check,the code works looks messy might code review question i study enough pythons conventions know structure organize beginning file pythonic i basically pasted imports could duplicates needed anymore wrongly ordered can advice anything structure imports i leave code like focus functions file future import withstatement import logging import os googleappengineapiusers import iscurrentuseradmin usernotfounderror import time import cgi import geogeotypes import main import captcha googleappengine import api googleappengineruntime import deadlineexceedederror googleappengineextwebapputil import runwsgiapp googleappengineextblobstore import blobinfo googleappengineextdb import djangoforms django import forms djangocoreexceptions import validationerror djangoutils import translation datetime import datetime timedelta osenviron djangosettingsmodule confsettings djangoconf import settings djangotemplate import requestcontext util import inhandler import util googleappengineapi import urlfetch taskqueue djangotemplatedefaultfilters import register djangoutils import simplejson json functools import wraps googleappengineapi import urlfetch taskqueue users images googleappengineext import db webapp search blobstore googleappengineextwebapp import util template googleappengineruntime import deadlineexceedederror random import randrange import cookie import base import cgi import conf import datetime import hashlib import hmac import logging import time import traceback import urllib import twitteroauthhandler twitteroauthhandler import oauthclient geogeomodel import geomodel djangoutilstranslation import gettextlazy webapptemplateregistertemplatelibrary commontemplatefilters file several instructions i understand future import withstatement coding utf import facebookconf import os wsgirefhandlers osenvironu djangosettingsmodule u conf import util import time import logging import urllib import wsgirefhandlers import appengineadmin import cgi import captcha import import hashlib import string import hmac import twitteroauthhandler twitteroauthhandler import oauthclient osenviron djangosettingsmodule confsettings geogeomodel import geomodel googleappenginedist import uselibrary googleappengineext import blobstore webapp db search template import must run django modules imports googleappengineextwebapp import blobstorehandlers util template googleappengineextblobstore import blobinfo googleappengineextwebapputil import runwsgiapp googleappengineapi import files images mail memcache users djangoconf import settings force django reload settingstarget none util import inhandler facebookbasehandler googleappengineextdb import djangoforms djangoutils import translation djangoutils import simplejson json djangocontribformtoolspreview import formpreview random import choice urllib import quote googleappengineapiusers import iscurrentuseradmin usernotfounderror googleappengineapi import urlfetch import random import datetime datetime import timedelta djangoutilstranslation import gettextlazy djangotemplate import defaultfilters how i know import longer used since function moved removed why i specify import multiple files one place i must spec import files i imagine moveing handling imports separate file ie importsyaml specify imports python files directory likewise,1 i would recommend postresql want scale fast rather easy work stable it exceptionally fast example queries given could even faster document querying,i migrating gaejava app python nongae due new pricing i getting little server i would like find database fits following requirements low memory usage tuneable predictible fastest querying capability simple documenttreelike data identified key i care performance writing i assume indexes bindings pypy compatibility python least my data goes something like id short key string title creators array another data structure id used key name site address etc tags array tags each multiple parent tags name id etc license data structure describes license cc gpl say name associated url etc addition time add site translations pointers entries translations one creation my queries simple usual cases filter tag ordered addition time select pagination ordered addition time maybe done already filter creator not done planned autocomplete features forms i going need search fields contains substring like queries the data volume big right i mb data i planning huge dataset around gb also i want rebuild scratch i open option what database think meet requirements edit i want benchmarks around different options share results i selected far mongodb postgresql mysql drizzle riak kyoto cabinet,1 define calculate outside namemain block child processes see windows,i trying make first simulation using multiple processes right simulation takes hour complete for im using multiprocessing import all code works fine run simulation inside loop when program run workers pool start task end copies finished start whats pool created whole program run line four times simultaneously instead running simulation the code almost entirely copypaste example multiprocessing documentation httpdocspythonorglibrarymultiprocessinghtml i working windows try running linux machine soon could somebody explain going wrong thank much pd windows bits python code simulation pulse pulse solref model algorithm defined also various imports made also print statements name main freezesupport def calculatefunc args result funcargs return says ss multiprocessingcurrentprocessname funcname args result processes print creating pool processesn processes pool poolprocesses print pool pool print tasks simulation pulsepulsesolrefmodelalgorithmi deltatau results poolapplyasynccalculate tasks r results print rget print edit errror log the lines print number points simulation come code main statement in code simulation run inside loop check work correctly gives expected results cusershpdesktopexperimentpython amplifierparallelpy number z points dist mm dz um number points window span ps dt fs deltatau deltatau deltatau deltatau deltatau deltatau deltatau deltatau simulation time seconds creating pool processes pool multiprocessingpoolpool object xeb number z points dist mm dz um number points window span ps dt fs times deltatau times deltatau tiemes deltatau tiemes deltatau tiemes deltatau tiemes deltatau tiemes deltatau tiemes deltatau tiemes simulation time seconds times slightly different times depending worker job process poolworker traceback recent call last file cpythonlibmultiprocessingprocesspy line bootstrap selfrun file cpythonlibmultiprocessingprocesspy line run selftargetselfargs selfkwargs file cpythonlibmultiprocessingpoolpy line worker task get file cpythonlibmultiprocessingqueuespy line get return recv attributeerror module object attribute calculate number z points dist mm dz um number points window span ps dt fs process poolworker traceback recent call last file cpythonlibmultiprocessingprocesspy line bootstrap selfrun file cpythonlibmultiprocessingprocesspy line run selftargetselfargs selfkwargs file cpythonlibmultiprocessingpoolpy line worker task get file cpythonlibmultiprocessingqueuespy line get return recv attributeerror module object attribute calculate deltatau kind stuff goes ever controlc,1 just note “newstyle vs “oldstyle” class distinction specific python x x classes “newstyle”,i trying translate python code scala code so i total noob python but classes object parameter never explicitly use what reasoning parameter first place example class tableobject thank time,1 one use make sure operations run atomically example swinterval sysgetswitchinterval try setting switch interval big number make sure thread context switching running operations came syssetswitchintervalsysmaxint expressions run atomic finally syssetswitchintervalswinterval another use case tune code specially facing convoy effect edge case new gil give bad performance maybe maybe changing context switch interval give speed disclaimer the first method sited consider dark magic totally recommended threadinglock likes preferred use case in general i think changing thread context switch interval something normal circumstances i paraphrase tim peters already say metaclasses changing thread context switch interval deeper magic people going need,python introduced new gil implementation antoine pitrou exposes function syssetswitchinterval when would changing useful,1 i wouldn’t worry thnk imports read provide crossreference someone comes across unqualified identifier wonders came search backwards first occurrence it’s defined locally file hit mention import statement tell came conversely check imports unused searching forwards import see mentions imported identifier safe remove note doesn’t work wildcard imports don’t use wildcard imports,the code works looks messy might code review question i study enough pythons conventions know structure organize beginning file pythonic i basically pasted imports could duplicates needed anymore wrongly ordered can advice anything structure imports i leave code like focus functions file future import withstatement import logging import os googleappengineapiusers import iscurrentuseradmin usernotfounderror import time import cgi import geogeotypes import main import captcha googleappengine import api googleappengineruntime import deadlineexceedederror googleappengineextwebapputil import runwsgiapp googleappengineextblobstore import blobinfo googleappengineextdb import djangoforms django import forms djangocoreexceptions import validationerror djangoutils import translation datetime import datetime timedelta osenviron djangosettingsmodule confsettings djangoconf import settings djangotemplate import requestcontext util import inhandler import util googleappengineapi import urlfetch taskqueue djangotemplatedefaultfilters import register djangoutils import simplejson json functools import wraps googleappengineapi import urlfetch taskqueue users images googleappengineext import db webapp search blobstore googleappengineextwebapp import util template googleappengineruntime import deadlineexceedederror random import randrange import cookie import base import cgi import conf import datetime import hashlib import hmac import logging import time import traceback import urllib import twitteroauthhandler twitteroauthhandler import oauthclient geogeomodel import geomodel djangoutilstranslation import gettextlazy webapptemplateregistertemplatelibrary commontemplatefilters file several instructions i understand future import withstatement coding utf import facebookconf import os wsgirefhandlers osenvironu djangosettingsmodule u conf import util import time import logging import urllib import wsgirefhandlers import appengineadmin import cgi import captcha import import hashlib import string import hmac import twitteroauthhandler twitteroauthhandler import oauthclient osenviron djangosettingsmodule confsettings geogeomodel import geomodel googleappenginedist import uselibrary googleappengineext import blobstore webapp db search template import must run django modules imports googleappengineextwebapp import blobstorehandlers util template googleappengineextblobstore import blobinfo googleappengineextwebapputil import runwsgiapp googleappengineapi import files images mail memcache users djangoconf import settings force django reload settingstarget none util import inhandler facebookbasehandler googleappengineextdb import djangoforms djangoutils import translation djangoutils import simplejson json djangocontribformtoolspreview import formpreview random import choice urllib import quote googleappengineapiusers import iscurrentuseradmin usernotfounderror googleappengineapi import urlfetch import random import datetime datetime import timedelta djangoutilstranslation import gettextlazy djangotemplate import defaultfilters how i know import longer used since function moved removed why i specify import multiple files one place i must spec import files i imagine moveing handling imports separate file ie importsyaml specify imports python files directory likewise,1 telnet wwwbkstrcom trying connected wwwbkstrcom escape character get webappwcsstoresservletcoursematerialsresultsviewcatalogidampcategoryidampstoreidamplangidampprogramidamptermidampdivisiondisplaynamestanfordampdepartmentdisplaynameilacampcoursedisplaynameampsectiondisplaynameampdemokeydamppurposebrowse http connection closed foreign host you going joy fetching url python anywhere else if works browser must something else going like cookies authentication or possibly server broken changed configuration try opening browser never accessed site check then log try edit it cookies import cookielib urllib cj cookielibcookiejar opener urllibbuildopenerurllibhttpcookieprocessorcj need set cookie openeropenhttpwwwbkstrcom now open page want data openeropenhttpwwwbkstrcomwebappwcsstoresservletcoursematerialsresultsviewcatalogidampcategoryidampstoreidamplangidampprogramidamptermidampdivisiondisplaynamestanfordampdepartmentdisplaynameilacampcoursedisplaynameampsectiondisplaynameampdemokeydamppurposebrowseread the output looks ok check want,i trying scrape page using python the problem i keep getting errno connection reset peer the error comes i run code urlliburlopenhttpwwwbkstrcomwebappwcsstoresservletcoursematerialsresultsviewcatalogidampcategoryidampstoreidamplangidampprogramidamptermidampdivisiondisplaynamestanfordampdepartmentdisplaynameilacampcoursedisplaynameampsectiondisplaynameampdemokeydamppurposebrowse happens urls pag issue,1 can paste data row causing problem at guess i say badly formatted date entry hard say can comment answer,i using psycopg postgresql while reading huge table i suddenly get cryptic error following line code line code successfully fetched hundred thousand rows somerows cursortofetchdatafetchmany psycopgdataerror invalid value lムdd detail value must integer my problem i column named dd columns table i know columns design flaw i would appreciate hint meaning error message figure problem lies i understand psycop requirements datatype fetching rows,1 yes wanting pygame its nice idea keep something light hand reinvent wheel someone already written code play midi files use code the option i think searching midi playing library python i find right spawning inside subprocess feeding commands jazz,i making simple text adventure python thought background midi music would make little less boring is simple lightweight midi player api python or i need use full game library like pygame because i rather pass i want make lightweight possible,2 or collecting many numbers use loop num xrange numappendrawinput enter number print num,know take single input user python rawinputenter st number opens one input screen takes first number want take second input need repeat command opens another dialogue box how take two inputs together dialogue box opens enter st number enter second number,1 only certain values parametrized even table column names parametrized your experiment shows pragma values also parametrized the userversion expected integer you use string formatting protect time curexecute pragma userversion vdformatvversion the format vd raise valueerror version integer,i trying change userversion sqlite database via python i tried following curexecute pragma userversion version it fails following error curexecute pragma userversion version sqliteoperationalerror near syntax error i tried named style substitution instead question marks also fails error if i drop number part sql string using python string operations works fine i rather either so working and i safety insert number variable call,2 if http traffic scan headers like xforwardedfor but whatever always heuristic,is way find ip address comming server proxy python i tried scan common ports want ban ips open port proxy is way python i would prefere using externalpaid services,1 dictionary values objects kind this means essentially must encapsulate code want run within function defined elsewhere you could toy exec could create dict strings exec string dict example i recommend lambda partially answer question lambda limited applicability create oneline functions among limitations still simple functions adequate lambda b lambda the best way longer blocks code simply define function method,i new python i really like concept using dictionaries instead switchcase statements one problem i figure let say pythonic case statement somemethod b othermethod this works fine i figure run block code like languages like java something would look like commands b commands executed maybe lambda could help thank much,2 seems like want itertoolscombinations listitertoolscombinations if want sets convert explicitly set mapset itertoolscombinationss set set set,i set values would like create list subsets containing elements for example source set following element subsets set set set is way python,3 this subset power set whatever set containing twoelement sets see python itertools documentation search term powerset general answer problem,i set values would like create list subsets containing elements for example source set following element subsets set set set is way python,1 just use ifelifelse it bad x pass elif x b pass elif x c pass else pass,i new python i really like concept using dictionaries instead switchcase statements one problem i figure let say pythonic case statement somemethod b othermethod this works fine i figure run block code like languages like java something would look like commands b commands executed maybe lambda could help thank much,2 i use indent object plugin this plugin defines new text object based indentation levels this useful languages python syntax defines scope terms indentation using objects defined plugin entire structure quickly selected example with select delete change etc blocks using standard vim text object commands using refer block vii dii etc it languageagnostic though especially usefulrelevant whitespacestructured languages python,is possible mark block vim based indentation already place similarly v it would extremely useful programming languages whitespacesensitive syntax like haskell python for example mark everything first let return function checkarg comarg ns com addsource let v lift savelinks return com removesource let filter hasword str lift savelinks return httpenwikipediaorgwikioffsiderule,3 you need put code functions you could create dictionary functions already concept python use class class foo def cmdaself def cmdbself def cmdcself def defaultactionself def executeself cmd action getattrself cmd cmd selfdefaultaction return action foo foo fooexecute,i new python i really like concept using dictionaries instead switchcase statements one problem i figure let say pythonic case statement somemethod b othermethod this works fine i figure run block code like languages like java something would look like commands b commands executed maybe lambda could help thank much,1 that possible script read etcpasswd etcshadow files contain details usernames passwords linux system do note script read access files depending situation may may possible here two good articles explaining format files tell everything need know order script read understand understanding etcpasswd file format understanding etcshadow file format by way talks encrypted password means encrypted using des algorithm you probably need use pydes another python implementation des algorithm order script create encrypted password compare one etcshadow,i writing python program allow user login i want implement authentication would rather take advantage oslinux mechanism that user trying sign app inputing usernamepassword pairwhich valid os user i need authenticate pair os how it may need subprocess module yet i tried luck,1 try using pam via python pam similar,i writing python program allow user login i want implement authentication would rather take advantage oslinux mechanism that user trying sign app inputing usernamepassword pairwhich valid os user i need authenticate pair os how it may need subprocess module yet i tried luck,3 findall returns list matches single match a python list attribute string however try data instead edit string seems work tag one child string divsomethingdiv would work divpsomethingpdiv use selectors use contents instead,i trying get image page httpwwwbkstrcomwebappwcsstoresservletcoursematerialsresultsviewcatalogidampcategoryidampstoreidamplangidampprogramidamptermidampdivisiondisplaynamestanfordampdepartmentdisplaynamemathampcoursedisplaynameampsectiondisplaynameampdemokeydamppurposebrowse i normal urllib open stuff need track cookies anyone going follow along data soupfindalldivclassefmaterialimage left works fine weirdly i test datastring print result console shows none any idea,1 try sendcontrol pexpext module import pexpect child pexpectspawn screen childsendcontrol childsend c the documentation many examples,hi everyone need find send ctrl ac using python make new screen using gnu screen i lost found code get working i need control gnu screen using python more info httplifehackercomhowtorunmultipleapplicationsinasingleterminalwindow,1 don use instance methods use class methods already using class attributes might realize that way instantiate object instead call methods class acts singleton class updatemanagerobject waiters attrs otherattrs classmethod def setattrcls attr clsattrsappendattr classmethod def setotherattrcls attr clsotherattrsappendattr classmethod def addcallbackcls cb clswaitersappendcb classmethod def sendcls cb clswaiters cbclsattrs clsotherattrs this make update import updatemanager updatemanagersend work desire,i working project tornado relies heavily asynchronous features library by following chat demo i managed get longpolling working application however i seem run problem way works basically i want able call function updatemanager class finish asynchronous request callbacks waiting list here code explain i mean updatepy class updatemanagerobject waiters attrs otherattrs def setattrself attr selfattrsappendattr def setotherattrself attr selfotherattrsappendattr def addcallbackself cb selfwaitersappendcb def sendself cb selfwaiters cbselfattrs selfotherattrs class longpolltornadowebrequesthandler updatemanager tornadowebasynchronous def getself selfaddcallbackselffinishrequest def finishrequestself attrs otherattrs render json give client etc class setsomethingtornadowebrequesthandler def postself handle stuff selfaddattrsomeattr there code implementing url handlersserver however i believe necessary question so i want make i call updatemanagersend another place application still send data waiting clients the problem try update import updatemanager updatemanagersend gets updatemanager class instance holding user callbacks so question way create persistent object tornado allow share single instance updatemanager throughout application,2 well growth unlikely linear since algorithm complexity ozz to draw conclusions linearity points error bar also quite useful analysis gpu threads far enough fully utilize computational power experiment shows gpu starts beating cpu k threads quite normal situation times speedup cpu also improbable since python interperted language fast opencl actively uses simd instructions cpu also gives quite good speed boost even compared copenmp,i little modified standard code httpsgithubcominducerpyopenclblobmasterexamplesbenchmarkallpy replaced numbers variable zz import pyopencl cl import numpy import numpylinalg la import datetime time import time zz numpyrandomrandzzastypenumpyfloat b numpyrandomrandzzastypenumpyfloat cresult numpyemptylikea speed normal cpu usage time time rangezz j rangezz cresulti ai bi cresulti cresulti ai bi cresulti cresulti ai time time printexecution time test without opencl time time platform clgetplatforms device platformgetdevices print printplatform name platformname printplatform profile platformprofile printplatform vendor platformvendor printplatform version platformversion print printdevice name devicename printdevice type cldevicetypetostringdevicetype printdevice memory deviceglobalmemsize mb printdevice max clock speed devicemaxclockfrequency mhz printdevice compute units devicemaxcomputeunits simnple speed test ctx clcontextdevice queue clcommandqueuectx propertiesclcommandqueuepropertiesprofilingenable mf clmemflags abuf clbufferctx mfreadonly mfcopyhostptr hostbufa bbuf clbufferctx mfreadonly mfcopyhostptr hostbufb destbuf clbufferctx mfwriteonly bnbytes prg clprogramctx kernel void sumglobal const float global const float b global float c int loop int gid getglobalid forloop loopsloop cgid agid bgid cgid cgid agid bgid cgid cgid agid zzbuild execevt prgsumqueue ashape none abuf bbuf destbuf execevtwait elapsed eexecevtprofileend execevtprofilestart printexecution time test g elapsed c numpyemptylikea clenqueuereadbufferqueue destbuf cwait error rangezz ci cresulti error error printresults match else printresults ok if zz execution time test without opencl platform name amd accelerated parallel processing platform profile fullprofile platform vendor advanced micro devices inc platform version opencl amdappsdkv device name cypressxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx device type gpu device memory mb device max clock speed mhz device compute units execution time test results ok platform name amd accelerated parallel processing platform profile fullprofile platform vendor advanced micro devices inc platform version opencl amdappsdkv device name intelr coretm cpu ghzxxxxxxxxxxxxxxxx device type cpu device memory l mb device max clock speed mhz device compute units execution time test e results ok we time normal execution time test without opencl pyopencl radeon execution time test pyopencl cpu execution time test e first questions pack pyopencl cpu faster normal execution time test without opencl times faster pyopencl radeon times if zz normal execution time test without opencl pyopencl radeon execution time test pyopencl cpu execution time test iradeon inormal if zz normal long comment code redeon execution time test execution time test here see win video card still interesting compare sequence times results normalstagenormalstage normalstagenormalstagebased experience istageistage istageistage radeonstageradeonstage radeonstageradeonstage ð¡an somebody explain results opencl growth linear,1 httpwwwboostorgdoclibslibspythondoc boostpython c library enables seamless interoperability c python programming language,i want call functions c program python code how make c functions available python program,2 you find simple example python native c api works well c if deal numerical calculations use numpy python code consider numpy extensive additions c api manual,i want call functions c program python code how make c functions available python program,1 you need myinput myinputsplit dataappend intmyinput intmyinput adding mytuple printdformatadding adding,done following code order fill tuple user input add elements tuplefor example giving input tuple then want add this first part works ok data mytuple true myinputrawinputenter two integers myinput printfinished break else myinputsplit dataappendmyinput mytupletupledata printdata printmytuple then try sth like adding mytuple printd dformatadding adding herei print i two problems i know add elements when add second part codethe adding press enter instead causing break program continues ask enter two integers thank,1 using builtin map function data mytuple true myinputrawinputenter two integers myinput printfinished break else myinputmapintmyinputsplit dataappendmyinput mytupletupledata printdata printmytuple print join formatsumt mytuple use mapint convert strings integers also note error orginal code myinputsplit expression assignment to change value myinput say myinput myinputsplit use mapsum apply sum tuple mytuple,done following code order fill tuple user input add elements tuplefor example giving input tuple then want add this first part works ok data mytuple true myinputrawinputenter two integers myinput printfinished break else myinputsplit dataappendmyinput mytupletupledata printdata printmytuple then try sth like adding mytuple printd dformatadding adding herei print i two problems i know add elements when add second part codethe adding press enter instead causing break program continues ask enter two integers thank,1 might overkill application check library pandas stuff like pretty simple groupby functionality httppandassourceforgenetgroupbyhtml to atatime thing would need compute bucketing array import numpy np bucketsize n lenyourlist buckets nparangen bucketsize then simple datagroupbybucketsmean,i new python list numbers eg i grouped fours etc using code post def groupiteriterator n strictfalse transforms sequence values sequence ntuples eg n if strict raise valueerror group fewer n items end sequence accumulator item iterator accumulatorappenditem lenaccumulator n tested fast separate counter yield tupleaccumulator accumulator tested faster accumulator tested fast reusing one list object strict lenaccumulator raise valueerrorleftover values how i access individual arrays i perform functions for example i like get average first values every group eg example numbers,1 the flag python refers module dgpy try python like saying import python shell looks like dgpy interpreter custom language the top half image looks like code snippet dg language it running kde seems use qt library can find online though,on background image find code looks like written extended python dialect processed “python dg” get “normal” python code google results “python dg” query yandexru one page cache briefly mention one example python dg sum map int str seems equivalent summapint str do know i want take look tool find links…,2 here could debianlike systems import subprocess import shlex process subprocesspopen shlexsplitxterminalemulator e bash c testpy stdoutsubprocesspipe processwait print processreturncode something like work nix system many thanks eudoxos pointing xterminalemulator,i trying launch python script another python script new shell window so far i unable does anyone knows i accomplish example import subprocess process subprocesspopen testpy shelltrue stdoutsubprocesspipe processwait print processreturncode i run script launch testpy new new shell window i using linux helpful provide solution windows,2 you use finally this want try things finally myclassclose,somebody help following piece code try things myclassclose except exception error myclassclose raise error you see i use finally case i know error actually occured i need raise error raise error question i avoid using two times myclassclose thanks advance help,1 you chain try except finally since python try do things pass except exception error log error raise finally myclassclose,somebody help following piece code try things myclassclose except exception error myclassclose raise error you see i use finally case i know error actually occured i need raise error raise error question i avoid using two times myclassclose thanks advance help,1 this equivalent code try things finally myclassclose first calls myclassclose error raised you also handle specific exceptions try things except exception error raise reraise original exception finally myclassclose,somebody help following piece code try things myclassclose except exception error myclassclose raise error you see i use finally case i know error actually occured i need raise error raise error question i avoid using two times myclassclose thanks advance help,1 next finally would work could also use context manager calls myclassclose method exit,somebody help following piece code try things myclassclose except exception error myclassclose raise error you see i use finally case i know error actually occured i need raise error raise error question i avoid using two times myclassclose thanks advance help,1 instead launching shell launch terminal running script on linux xterm e testpy windows equivalent would cmdexe testpy i believe i could wrong,i trying launch python script another python script new shell window so far i unable does anyone knows i accomplish example import subprocess process subprocesspopen testpy shelltrue stdoutsubprocesspipe processwait print processreturncode i run script launch testpy new new shell window i using linux helpful provide solution windows,1 using itertools written import itertools alist itertoolschain itertoolsimapfun alist aiming code golf alist summapfun alist alternatively write newelements mapfun alist itertoolsimap python x ne newelements alistextendne,i would like extend list looping idx xrangelenalist item alistidx alistextendfunitem fun function returns list question is already best way something nicer compact possible remarks matplotlibcbook import flatten alistextendflattenfunitem item alist work i want code depend matplotlib item alist alistextendfunitem would nice enough taste seems cause infinite loop context i large number nodes dict special boundary alist contains keys specialboundary nodes sometimes nodes added every new node boundary needs added alist the new boundary nodes determined old boundary nodes expresses fun every boundary node add several new nodes,1 paper gives algebraic way find equation points plane httpwwwmathwashingtonedukingcoursedirmwnotesvectorequationshtml detailed description cross product method httpwwwmathwashingtonedukingcoursedirmwnotesvectornormalsplaneshtmlcross,i want find d plane equation given points i got normal calculated applying cross product but equation plane known normal multiply another vector i taught pop i substitute main reference point op want p x z form so i get something like eg op i want get something like x z may i know below reference codenote planepointx planepointy planepointz functions asking user input respective points i used point p reference point i make use section vectorpopx int x intplanepointx vectorpopy int intplanepointy vectorpopz int z intplanepointz print vectorpopx vectorpopy vectorpopz all reason work i think problem lies x z part,1 you need call legend legend appear the label kwarg sets label attribute artist object question it convenience label legend clearly associated plotting command it add legend plot without explicitly calling axlegend also want axsetxlim axxlim adjust xaxis limits have look axaxis well it sounds like want something like import matplotlib mpl mpluse agg import matplotlibpyplot plt import numpy np generate data x nparange f f f f npcumsumnprandomrandom xsize axis it much convenient use pyplot factory functions fig ax pltsubplots axsettitlefunction performancefontsize axsetxlabelcode executionsfontsize axsetylabeltimesfontsize axgridtruelinestyle color colors tomato violet blue green labels thing one thing two thing three thing four func color label zipf f f f colors labels axplotx func colorcolor markersize labellabel axlegendnumpoints loc upper left axsetxlim xmax figsavefig performancepng dpi,i using code plot time spent run functions the x axis represents number executions whereas axis represents time spent running function i wondering could help accomplish following set limits x axis positive values shown x represents number times function executed therefore always positive create legend functions thank mark import matplotlib matplotlibbackendsbackendagg import figurecanvasagg figurecanvas matplotlibfigure import figure import matplotlibmlab mlab r mlabcsvrec performancecsv fig figurefigsize canvas figurecanvasfig ax figaddsubplot axsettitlefunction performancefontsize axsetxlabelcode executionsfontsize axsetylabeltimesfontsize axgridtruelinestyle color axscatterrrunrfunctionscolor tomato axscatterrrunrfunctionscolor violet axscatterrrunrfunctionscolor blue axscatterrrunrfunctionscolor green canvasprintfigure performancepng dpi,3 as want extend list loop original list loop copy instead original item alist alistextendfunitem,i would like extend list looping idx xrangelenalist item alistidx alistextendfunitem fun function returns list question is already best way something nicer compact possible remarks matplotlibcbook import flatten alistextendflattenfunitem item alist work i want code depend matplotlib item alist alistextendfunitem would nice enough taste seems cause infinite loop context i large number nodes dict special boundary alist contains keys specialboundary nodes sometimes nodes added every new node boundary needs added alist the new boundary nodes determined old boundary nodes expresses fun every boundary node add several new nodes,1 have tried list comprehensions this would work creating separate list memory assigning original list comprehension complete basically second example instead importing flattening function flattens stacked list comprehensions edit matthias changed alist x lst funitem item alist x lst edit to explain going so first thing happen part middle code funitem item alist this apply fun every item alist add new list problem funitem returns list list lists so run second stacked list comprehension loop lists new list created original comprehension lst funitem item alist this allow us loop lists order so x lst funitem item alist x lst this means take every x every item every lst lists created original comprehension add new list hope clearer if i always willing elaborate,i would like extend list looping idx xrangelenalist item alistidx alistextendfunitem fun function returns list question is already best way something nicer compact possible remarks matplotlibcbook import flatten alistextendflattenfunitem item alist work i want code depend matplotlib item alist alistextendfunitem would nice enough taste seems cause infinite loop context i large number nodes dict special boundary alist contains keys specialboundary nodes sometimes nodes added every new node boundary needs added alist the new boundary nodes determined old boundary nodes expresses fun every boundary node add several new nodes,1 check indentation retcode if line spaces line tab look editor python complain,i never done python programming i done lot net c there need python trying learn throw exceptions python future import withstatement import dbi import timeit import datetime import wincomclient import os import datetime import sys import codecs import subprocess import time import winreg def main retcode datetimedatetimenow print print start executing script print try print testing testing except exception err sysstderrwrite error sn strerr retcode retcode print print errors occured please investigate print else print print no errors found print print retcode retcode sysexitretcode main does anyobody know code gives error the error file csamplepy line retcode indentationerror unexpected indent,2 in original code mix tabs spaces make sure line number spaces per indentation,i never done python programming i done lot net c there need python trying learn throw exceptions python future import withstatement import dbi import timeit import datetime import wincomclient import os import datetime import sys import codecs import subprocess import time import winreg def main retcode datetimedatetimenow print print start executing script print try print testing testing except exception err sysstderrwrite error sn strerr retcode retcode print print errors occured please investigate print else print print no errors found print print retcode retcode sysexitretcode main does anyobody know code gives error the error file csamplepy line retcode indentationerror unexpected indent,1 sqlalchemy common choice it also used orm,i php guy trying python cherrypy whenever i work php i use simmple wrapper mysql functions form class make things easier maintain there also pdo layer widely used i never really used projects do people building applications python using microframeworks use kind wrappers mysql instead straightout mysqldb library,2 you use metaclass follows import copy new class makeacopyofconstructorargumentstype def newcls name bases dct rv typenewcls name bases dct oldinit dctgetinit oldinit none clsoldinit oldinit def newinitself kw copydeepcopya kw copydeepcopykw clsoldinitself kw rvinit newinstancemethodnewinit rv cls return rv class testobject metaclass makeacopyofconstructorarguments def initself li li print li li range print li testli print li,a times i accidentally modified input function since python constant references i wondering coding techniques might help avoid making mistake often example class table def initself fields rawdata fields dictionary field names keys types value sometimes want delete elements fieldname datatype fieldsitems someconditionfieldname rawdata del fieldsfieldname another module fields already initialized dictionary table tablefields rawdata fields corrupted table init table tablefields rawdata of course fix make copy parameter i change def initself fields rawdata fields copycopyfields copycopy safer generally applicable copy but easy forget i half thinking make copy argument beginning every function unless argument potentially refers large data set may expensive copy unless argument intended modified that would nearly eliminate problem would result significant amount useless code start function in addition would essentially override python approach passing parameters reference presumably done reason,1 first general rule modify containers create new ones so modify incoming dictionary create new dictionary subset keys selffields dict key value key value fieldsitems acceptkeykey data such methods typically slightly efficient going deleting bad elements anyways more generally often easier avoid modifying objects instead create new ones second general rule modify containers passing you generally assume containers passed data made copies as result try modify containers given any modifications done handing data once passed container somebody else longer sole master third general rule modify containers create if get passed sort container know else might using container so modify either use unmodified version invoke rule creating new container desired changes fourth general rule stolen ethan furman some functions supposed modify list that job if case make apparent function name list methods append extend putting together a piece code modify container piece code access container,a times i accidentally modified input function since python constant references i wondering coding techniques might help avoid making mistake often example class table def initself fields rawdata fields dictionary field names keys types value sometimes want delete elements fieldname datatype fieldsitems someconditionfieldname rawdata del fieldsfieldname another module fields already initialized dictionary table tablefields rawdata fields corrupted table init table tablefields rawdata of course fix make copy parameter i change def initself fields rawdata fields copycopyfields copycopy safer generally applicable copy but easy forget i half thinking make copy argument beginning every function unless argument potentially refers large data set may expensive copy unless argument intended modified that would nearly eliminate problem would result significant amount useless code start function in addition would essentially override python approach passing parameters reference presumably done reason,3 in python use bytes object also known str python python key bytesx x x x x x python key joinchrx x x x x x x x i find convenient use base module python key basebdecodeb python key basebdecode you also use literals python key b xx python key xx,how i represent byte array like java byte python i need send wire gevent byte key x x x x x x,3 just use bytearray python later represents mutable sequence bytes key bytearrayx x x x x x key bytearrayb xxxxxx indexing get sets individual bytes key keyxff key bytearrayb xxffxxxx need str bytes python simple byteskey xxffxxxx,how i represent byte array like java byte python i need send wire gevent byte key x x x x x x,3 time sort cleaneddata bits since access field values pictureobjectsfilteridformcleaneddata orderedpicture exists,i simple form trying post simple service the form model class orderformformsform name formscharfieldmaxlength phone formscharfieldmaxlength email formscharfieldmaxlength address formscharfieldmaxlength orderedpicture formscharfield view sorted cleareddata bits stuff yet def placeorderrequest result dict requestmethod post try form orderformrequestpost pictureobjectsfilteridformorderedpictureexists result status error result message ordered picture exist neworder order newordername formdataname neworderphone formdataphone neworderemail formdataemail neworderaddress formdataaddress neworderorderedpicture intformdataorderedpicture newordersave result status ok result message neworderid except exception e result status error result message emessage else result status error result message only http post method supported service return httpresponsecontentsimplejsondumpsresult here copy post data goes csrfmiddlewaretokendbaefefcab nameqwe phoneqwe emailqwe addressqwe orderedpicture i get following status error message orderform object attribute orderedpicture object attribute thing popping exception right form orderformrequestpost attempted i break head telling form attribute reality,2 i think reason work element single element but numpy function ind documentation numpy array with code npwherenpindfoo false true to complete answer comment case using redundant output ind used index foo foonpindfoo foonpindfoo note ind available numpy higher,lets say i array foo two columns column values indicating months column corresponding measurement values if i wanted create mask measurement values december january february i would suspect i could numpywherefoo false true but would appear clever work conditional nor appear work etc is another clever way is better way collect measurements array what numpy way reshaping array question irregular number measurements month,2 unfortunately bisect allow specify key function what though add xffxffxffxff string using find highest index take elements,i want search sorted list strings elements start given substring here example finds exact matches import bisect names adam bob bob bob bobby bobert chris namessort leftindex bisectbisectleftnames bob rightindex bisectbisectrightnames bob printnamesleftindexrightindex which prints bob bob bob instead i want search names start bob the output i want bob bob bob bobby bobert if i could modify comparison method bisect search i could use namestartswith bob as example java would easy i would use arraysbinarysearchnames bob mycustomcomparator mycustomcomparator comparator takes advantage startswith method additional logic how i python,2 so want something quick dirty need simply remember last publisher parsed assign bookdetail next publisherdetails found add something like fastiter function extract bookdetail bookdetail element publisherdetails bookdetail id none currentpublisher bookdetail bookdetail element bookdetail bookdetail publisherid currentpublisher id text,i tried parsing huge xml document using xml minidom while worked fine sample file choked system trying process real file mb i tried adapting code processes data streaming fashion rather inmemory load codereview xml file i trouble isolating datasets due nested nature elements i worked simple xml files memory intensive task like is right approach how i associate inventory publisher ids book that i planning relate tables eventually any feedback much appreciated bookxml bookdatabase bookheader namebookdataname bookuniverseallbookuniverse asofdateasofdate versionversion bookheader inventorybody inventory id publisherclass id publisher publisherdetails namemicrosoft pressname typetechtype idid publisherdetails publisher publisherclass booklist listing booklistsummary datedate booklistsummary book bookdetail id booknamecode complete bookname authorsteve mcconnellauthor pagespages isbnisbn bookdetail bookdetail id booknameapplication architecture guide bookname authormicrosoft teamauthor pagespages isbnxisbn bookdetail book listing booklist inventory inventory id publisherclass id publisher publisherdetails nameo reilly medianame typetechtype idid publisherdetails publisher publisherclass booklist listing booklistsummary datedate booklistsummary book bookdetail id booknamehead first design patternsbookname authorkathy sierraauthor pagespages isbnisbn bookdetail book listing booklist inventory inventorybody bookdatabase python code import sys import os import mysqldb lxml import etree categories set bookheader inventory publisherclass publisherdetails bookdetail skipcategories set bookheader dataitems name type id bookname author pages isbn def clearelementelement elementclear elementgetprevious none del elementgetparent def extractbookelementscontext event element context elementtag categories yield element clearelementelement def fastitercontext bookcounter element enumerateextractbookelementscontext books booktext book elementfindallbookdetail bookdetail element elementtag id elementget id dataitem dataitems data elementfinddataitem data none bookdetaildataitem data bookdetail element skipcategories populatedatabasebookdetail books cursor print bookdetail books print bookcounter def main cursor connecttodatabase cursorexecuteset names utf context etreeiterparsebookxml eventsstart end fastitercontext cursor fastitercontext cursorclose name main main python output python lxmletreebookpy id element inventory id element publisherclass name element name xaf type element type xb id element id xb element publisherdetails id none element publisherdetails id none element publisherclass isbn element isbn xeb name element name xdc author element author xe id element bookdetail pages element pages xe id none element bookdetail isbn element isbn xa name element name xf author element author xfa id element bookdetail pages element pages x id none element bookdetail id none element inventory id element inventory id element publisherclass name element name x type element type x id element id xd element publisherdetails id none element publisherdetails id none element publisherclass isbn element isbn xf name element name x author element author x id element bookdetail pages element pages xa id none element bookdetail id none element inventory desired output eventually stored mysql list python publishers inventoryid publisherclassid name type id microsoft press tech o reilly media tech books publisherid bookdetailid name author pages isbn code complete steve mcconnell application architecture guide microsoft team x head first design patterns kathy sierra,1 you might try something like import mysqldb lxml import etree import config def fastitercontext func args kwargs httpwwwibmcomdeveloperworksxmllibraryxhiperfparse author liza daly event elem context funcelem args kwargs elemclear elemgetprevious none del elemgetparent del context def extractpaperelementselementcursor pub pub inventoryid elementattrib id try pub publisherclassid elementxpath publisherclassid except indexerror pub publisherclassid none pub publisherclassid elementxpath publisherclassid key name type id try pubkeyelementxpath publisherclasspublisherpublisherdetailsktext formatkkey except indexerror pubkeynone sql insert into publishers inventoryid publisherclassid name type id values argspubgetkey key inventoryid publisherclassid name type id printargs cursorexecutesqlargs bookdetail elementxpath descendantbooklistlistingbookbookdetail pub bookdetailid bookdetailattrib id key bookname author pages isbn try pubkeybookdetailxpath ktext formatkkey except indexerror pubkeynone sql insert into books publisherid bookdetailid name author pages isbn values argspubgetkey key id bookdetailid bookname author pages isbn cursorexecutesqlargs printargs def main context etreeiterparsebookxml eventsend tag inventory connectionmysqldbconnect hostconfighostuserconfiguser passwdconfigpassdbconfigmydb cursorconnectioncursor fastitercontextextractpaperelementsargscursor cursorclose connectioncommit connectionclose name main main don use fastiter the original fastiter separates useful utility specific processing function extractpaperelements fastiter mixes two together leaving repeatable code if set tag parameter etreeiterparsebookxml eventsend tag inventory processing function extractpaperelements see inventory elements given inventory element use xpath method burrow scrape desired data args kwargs parameters added fastiter cursor passed extractpaperelements,i tried parsing huge xml document using xml minidom while worked fine sample file choked system trying process real file mb i tried adapting code processes data streaming fashion rather inmemory load codereview xml file i trouble isolating datasets due nested nature elements i worked simple xml files memory intensive task like is right approach how i associate inventory publisher ids book that i planning relate tables eventually any feedback much appreciated bookxml bookdatabase bookheader namebookdataname bookuniverseallbookuniverse asofdateasofdate versionversion bookheader inventorybody inventory id publisherclass id publisher publisherdetails namemicrosoft pressname typetechtype idid publisherdetails publisher publisherclass booklist listing booklistsummary datedate booklistsummary book bookdetail id booknamecode complete bookname authorsteve mcconnellauthor pagespages isbnisbn bookdetail bookdetail id booknameapplication architecture guide bookname authormicrosoft teamauthor pagespages isbnxisbn bookdetail book listing booklist inventory inventory id publisherclass id publisher publisherdetails nameo reilly medianame typetechtype idid publisherdetails publisher publisherclass booklist listing booklistsummary datedate booklistsummary book bookdetail id booknamehead first design patternsbookname authorkathy sierraauthor pagespages isbnisbn bookdetail book listing booklist inventory inventorybody bookdatabase python code import sys import os import mysqldb lxml import etree categories set bookheader inventory publisherclass publisherdetails bookdetail skipcategories set bookheader dataitems name type id bookname author pages isbn def clearelementelement elementclear elementgetprevious none del elementgetparent def extractbookelementscontext event element context elementtag categories yield element clearelementelement def fastitercontext bookcounter element enumerateextractbookelementscontext books booktext book elementfindallbookdetail bookdetail element elementtag id elementget id dataitem dataitems data elementfinddataitem data none bookdetaildataitem data bookdetail element skipcategories populatedatabasebookdetail books cursor print bookdetail books print bookcounter def main cursor connecttodatabase cursorexecuteset names utf context etreeiterparsebookxml eventsstart end fastitercontext cursor fastitercontext cursorclose name main main python output python lxmletreebookpy id element inventory id element publisherclass name element name xaf type element type xb id element id xb element publisherdetails id none element publisherdetails id none element publisherclass isbn element isbn xeb name element name xdc author element author xe id element bookdetail pages element pages xe id none element bookdetail isbn element isbn xa name element name xf author element author xfa id element bookdetail pages element pages x id none element bookdetail id none element inventory id element inventory id element publisherclass name element name x type element type x id element id xd element publisherdetails id none element publisherdetails id none element publisherclass isbn element isbn xf name element name x author element author x id element bookdetail pages element pages xa id none element bookdetail id none element inventory desired output eventually stored mysql list python publishers inventoryid publisherclassid name type id microsoft press tech o reilly media tech books publisherid bookdetailid name author pages isbn code complete steve mcconnell application architecture guide microsoft team x head first design patterns kathy sierra,3 yes there number ways if running linux look proc directory information a generic solution might listen socket script provide http interface querying state continuously runing script for example script starts print something like for status visit httplocalhost then visit link socket script gets http requests handle printing whatever status information want get script,i software support python scripting fire forget scripts anyway track memory something like make interactive tools or possible track memory external tools something like keylogger advanced example run script loop script running amp wait ctrlx exit loop exit script,1 bisect fooled using custom comparison using instance uses custom comparator chosing class prefixcomparesobject def initself value selfvalue value def ltself return selfvalue otherlenselfvalue import bisect names adam bob bob bob bobby bobert chris namessort key prefixcompares bob leftindex bisectbisectleftnames key rightindex bisectbisectrightnames key printnamesleftindexrightindex adam bob bob bob bobby bobert doh right bisect worked left one obviously adam prefixed bob fix adapt sequence class hasprefixobject def initself value selfvalue value def ltself return selfvaluelenothervalue othervalue class prefixobject def initself value selfvalue value def ltself return selfvalue othervaluelenselfvalue class adaptprefixobject def initself seq selfseq seq def getitemself key return hasprefixselfseqkey def lenself return lenselfseq import bisect names adam bob bob bob bobby bobert chris namessort needle prefix bob haystack adaptprefixnames leftindex bisectbisectlefthaystack needle rightindex bisectbisectrighthaystack needle printnamesleftindexrightindex bob bob bob bobby bobert,i want search sorted list strings elements start given substring here example finds exact matches import bisect names adam bob bob bob bobby bobert chris namessort leftindex bisectbisectleftnames bob rightindex bisectbisectrightnames bob printnamesleftindexrightindex which prints bob bob bob instead i want search names start bob the output i want bob bob bob bobby bobert if i could modify comparison method bisect search i could use namestartswith bob as example java would easy i would use arraysbinarysearchnames bob mycustomcomparator mycustomcomparator comparator takes advantage startswith method additional logic how i python,3 pydoc w write html documentation module file current directory if contains treated filename names directory documentation written contents,pydoc creates html documentation current directory generating documentation modules i really need specify another directory placeholder generated documentation instead directory pydoc called i using python pydoc w modulesdir generate documentation is possible,2 try pynxc httpcodegooglecomppynxc,i want start coding python ruby since i lego midstorms kit i thought would nice program are good translators interpeters mindstorms brick,1 variables shared instances myclass b variable exist within init function c attribute specific myclass instance part external interface myclass ie surprised programmer mucks around variable the disadvantage using c reduces flexibility make changes myclass point someone probably going rely fact c exists certain things decide reorganize class need prepared keep c around forever attribute specific myclass instance part internal implementation myclass assumed code myclass readwrite attribute makes look many ways like c however advantage using example computed attribute would possible eliminate additional storage also ensure read externally written externally,i spent time looking guide decide store data functions python class i point i new oop answers data attributes correspond “instance variables” smalltalk “data members” c seen httpdocspythonorgtutorialclasseshtml leave scratching head i suppose i primer oop targeted python programmers i would hope guideprimer would also include sort glossary definitions reading i would able speak intelligently different types variables available i want understand thought processes behind deciding use forms b c following code class myclassobject def initself b selfc selfd def getdself return selfd propertygetd none none none,1 check beautifulsoup documentation httpwwwcrummycomsoftwarebeautifulsoupdocumentationhtml ps it much flexible including future requirements,i html page tables each table layout different values eg table alignright classcustomtableclass tr aligncenter td width height classusernumvaluetd td width height classusernumvaluetd td width height classusernumvaluetd td width height classusernumvaluetd td width height classusernumvaluetd td width height classusernumvaluetd td width height classtotalnumothervaltd tr table my rest server running djangopython urlspy i calling def parseurl function obviously i want work my problem i pretty much newbie comes python literally know put code i gotten code htmlparser python docs changed follows import urllib urllib djangohttp import httpresponse htmlparser import htmlparser class myhtmlparserhtmlparser def handlestarttagself tag attrs print encountered beginning tag tag def handleendtagself tag print encountered end tag tag def handledataself data httpresponseencountered data data def parseurlrequest p myhtmlparser url httpwwwmysitecomlistsasp content urlliburlopenurlread pfeedcontent return httpresponse done this code moment doesnt output anything useful it prints done isnt useful how i use class methods handlestarttag shouldnt called automatically i use pfeedcontent basically i trying accomplish end i go mysitecomshowlist able output list saying value value value value value value othervalue this needs done loop roughly tables different values table thanks helping beginner,2 a newbiefriendly online book widelyrecommended dive python see chapter especially as questions class variable identical objects class b local temporary variable related class assigning inside init method might make think persists init call you might think b could refer global would languages python scope explicitly specified global b statement effect variable refers innermost scope cd instance variables object different values different semantics mean c ordinary instance variable read written objectc class define getter setter private variable readonly intended accessed getter function getd property line shows setter setd hence cannot changed the doubleunderscore prefix signifies internal intended accessed anything outside class property allows readonly access michael points without needing storage extra variable computed dynamically getd called,i spent time looking guide decide store data functions python class i point i new oop answers data attributes correspond “instance variables” smalltalk “data members” c seen httpdocspythonorgtutorialclasseshtml leave scratching head i suppose i primer oop targeted python programmers i would hope guideprimer would also include sort glossary definitions reading i would able speak intelligently different types variables available i want understand thought processes behind deciding use forms b c following code class myclassobject def initself b selfc selfd def getdself return selfd propertygetd none none none,1 guess print lines containing sizex elements original list rangelenmylistsizex printmylistisizexisizex guess new list elements strings sizex characters newlist rangelenmylistsizex newlistappend joinmylistisizexisizex printing newlist guess screen quicker first guess print n joinnewlist also note prior python xrange used instead range generates ivalues go instead creating whole list indices first python standard range example mylist list hello supposed long line sizex rangelenmylistsizex printmylistisizexisizex h e l l h u p p e b e l n g l n e newlist rangelenmylistsizex newlistappend joinmylistisizexisizex print n joinnewlist hello uppos ed long line,quick hopefully easy question let say i variable equal numerical width value ie sizex i want print list wrapping width elements how i,2 b c show different scopes variables meaning variables different visibility environment valid at first need understand difference class object a class vehicle describe generic behavior an object created based class the objects inherits methods class define variables bound object the idea objects encapsulate data required behavior work data this main difference procedural programming modules define behavior data c instance variable meaning variable lives scope instance myclass self always reference current object instance current code run technically works c scope the difference convention python variables methods starting two underscores considered private used code outside class this required python way define truely private proteted methods variables many languages b simple variable valid inside init method if execution leaves init method b variable going garbage collected accessible anymore c still valid note b prepended self now defined directly class that makes called class variable typically used store static data this variable instances myclass class note description bit simplified omits things like metaclasses difference functions bound methods get idea,i spent time looking guide decide store data functions python class i point i new oop answers data attributes correspond “instance variables” smalltalk “data members” c seen httpdocspythonorgtutorialclasseshtml leave scratching head i suppose i primer oop targeted python programmers i would hope guideprimer would also include sort glossary definitions reading i would able speak intelligently different types variables available i want understand thought processes behind deciding use forms b c following code class myclassobject def initself b selfc selfd def getdself return selfd propertygetd none none none,1 you printing beginning answer stdout django here get htmlparser bidding import urllib urllib djangohttp import httpresponse htmlparser import htmlparser class myhtmlparserhtmlparser def initself args kwargs selfcapturedata false selfdatalist htmlparserinitself args kwargs def handlestarttagself tag attrs tag td selfcapturedata true def handleendtagself tag tag td selfcapturedata false def handledataself data selfcapturedata data dataisspace selfdatalistappenddata def parseurlrequest p myhtmlparser url httpwwwmysitecomlistsasp content urlliburlopenurlread pfeedcontent return httpresponsestrpdatalist i would recommend putting class utilspy file keeping folder viewspy then import this help keep viewspy manageable containing views,i html page tables each table layout different values eg table alignright classcustomtableclass tr aligncenter td width height classusernumvaluetd td width height classusernumvaluetd td width height classusernumvaluetd td width height classusernumvaluetd td width height classusernumvaluetd td width height classusernumvaluetd td width height classtotalnumothervaltd tr table my rest server running djangopython urlspy i calling def parseurl function obviously i want work my problem i pretty much newbie comes python literally know put code i gotten code htmlparser python docs changed follows import urllib urllib djangohttp import httpresponse htmlparser import htmlparser class myhtmlparserhtmlparser def handlestarttagself tag attrs print encountered beginning tag tag def handleendtagself tag print encountered end tag tag def handledataself data httpresponseencountered data data def parseurlrequest p myhtmlparser url httpwwwmysitecomlistsasp content urlliburlopenurlread pfeedcontent return httpresponse done this code moment doesnt output anything useful it prints done isnt useful how i use class methods handlestarttag shouldnt called automatically i use pfeedcontent basically i trying accomplish end i go mysitecomshowlist able output list saying value value value value value value othervalue this needs done loop roughly tables different values table thanks helping beginner,3 each package contain setuppy file run command python setuppy install for information httpwwwscipyorginstallingscipywindows httppygameorginstallhtml,i working python bit windows vista i downloaded libraries including numpy scipy pygame when i try import modules output says traceback recent call last file pyshell line module import numpy importerror no module named numpy i find modules python folders reason want recognize thing i made sure file compatible downloading,2 your problem randomsample returns list really want something like izvucena randomsamplespil grab element list returned although simpler use randomchoice instead izvucena randomchoicespil,arrays one main array temp temp array chooses random number supposed remove member main array since content arrays identical code import random spil k k k k k k k k k k k k k e e e e e e e e e e e e e p p p p p p p p p p p p p printspil izvucena randomsample k k k k k k k k k k k k k e e e e e e e e e e e e e p p p p p p p p p p p p p spilremoveizvucena printspil,2 the problem randomsample returns list single element case izvucena list one element just replace second last line spilremoveizvucena remove element,arrays one main array temp temp array chooses random number supposed remove member main array since content arrays identical code import random spil k k k k k k k k k k k k k e e e e e e e e e e e e e p p p p p p p p p p p p p printspil izvucena randomsample k k k k k k k k k k k k k e e e e e e e e e e e e e p p p p p p p p p p p p p spilremoveizvucena printspil,1 the easiest thing probably combine lists python look combined list template combinedlist placelistispeakerlisti range entry combinedlist tr td entry td tdtd td entry td tr endfor or transparency could make combinedlist list objects dictionaries example combinedlist place placelisti speaker speakerlisti range entry combinedlist tr td entryplace td tdtd td entryspeaker td tr endfor,basically i want template system loop two independent lists fill two columns table my approach use index list numlist way access index two lists i tried using dot notation list index lookup within template loop seem work loop any ideas i remedy numlist placelist park store home school speakerlist bill john jake tony table tr thlocationth thtimeth thspeakerth tr num numlist tr td placelistnum td tdtd td speakerlistnum td tr endfor table,3 quick answer just install django via documentation even need apache running run server you use sqlite db even worry mysql this goal learn django get things running asap otherwise want take full route need start learning lot bad thing i say take look slicehost guides setting apache mysql ubuntu httparticlesslicehostcominstallingapacheonubuntu httparticlesslicehostcominstallingmysqlserveronubuntu and pick installing django going the django tutorial awesome there plenty documentation web amp tutorials setting dev environments,finally made switch windows linux ubuntu i teaching python django goal i want setup local development environment i build django application run locally deploying live online so far python comes installed linux gedit also ok great after i lost i sure proceed i total linux noob i guessing i need apache running mysql running django run i know setup things run set proper directories i need link really i even sure right questions ask,2 unless need temporary list something else really need remove random value could spilremoverandomchoicespil,arrays one main array temp temp array chooses random number supposed remove member main array since content arrays identical code import random spil k k k k k k k k k k k k k e e e e e e e e e e e e e p p p p p p p p p p p p p printspil izvucena randomsample k k k k k k k k k k k k k e e e e e e e e e e e e e p p p p p p p p p p p p p spilremoveizvucena printspil,1 it easy actual json preferably jsondump cat tjson label hd url google format mp videocodec h audiocodec aac size x python eof import json f open tjson print jsonloadf fclose eof u format u mp u url u google u label u hd u audiocodec u aac u videocodec u h u size u x,i following json view simplified example video label hd url google format mp videocodec h audiocodec aac size x and i call function like dosomethingvideo however i try extract json external file follows fileopen datajson videofileread i get error appears related newlines excessive spaces file how would i format json document put external file would i import i use function thank,2 if name files tests test prefix ie rename somethingpy testsomethingpy running nose pick default you say i prefer pollute module names testname pattern nose expects include testing something descriptive file file tests something what problem using nonconfusing standard way naming tests,i package several subpackages one tests named tests since subpackage name makes clear contained modules test modules i prefer pollute module names testname pattern nose expects include testing that setup i thinking foo initpy bar initpy baz initpy tests initpy somethingpy now default nose run tests found footestssomething i know nose accepts option define regular expressions additional stuff search tests so nose something job however i bunch modules tests package want name explicitely nose tests work looks like nose matches module basenames as last resort i could run nose allmodules also inspects foobar foobaz i like avoid so could i instruct nose look tests modules within given package tests case i could write nose plugin task i looking standard solution,2 well says documentation create sqlite database file file location configure name django guess uses file path specify only use something sqlite name actual database name database server,i settingspy file django tutorial i confused i put name field i want use sqlite understanding i need create anything database created automatically if created called i tried running managepy syncdb got djangocoreexceptionsimproperlyconfigured please fill database name settings module using database so i guessing i fill name file i understood directions httpsdocsdjangoprojectcomenintrotutorial name the name database if using sqlite database file computer case name full absolute path including filename file if file exist automatically created synchronize database first time see,2 create db file install sqlite machine create database file point settingspy name example homeusernameprojectchatdb thats linux windows chomesusermysitesqlitedb,i settingspy file django tutorial i confused i put name field i want use sqlite understanding i need create anything database created automatically if created called i tried running managepy syncdb got djangocoreexceptionsimproperlyconfigured please fill database name settings module using database so i guessing i fill name file i understood directions httpsdocsdjangoprojectcomenintrotutorial name the name database if using sqlite database file computer case name full absolute path including filename file if file exist automatically created synchronize database first time see,1 from httpdevscrapyorgwikiscrapyrecipes how spoof requests http compliant you overriding scrapy http client factory following undocumented setting downloaderhttpclientfactory myprojectdownloaderhttpclientfactory here possible implementation myprojectdownloader module scrapycoredownloaderwebclient import scrapyhttpclientfactory scrapyhttppagegetter class pagegetterscrapyhttppagegetter def sendcommandself command path selftransportwrite httprn command path class httpclientfactoryscrapyhttpclientfactory protocol pagegetter,it looks like scrapy using http default is setting make use http send request thanks,2 i would go setup you probably need lxml parse manipulate post content html extract tags,neophyte post apologies thanks front my goal build small app monitors parses set blogs posts outbound links i display top linkedto articles among blogs one frame for given linkedto article display posts blogosphere link so far idea use python django somesuch front end feedparser read feeds extract links posts urlparse the big question i missing anything obvious would make way easier smaller question i figure yet since outbound link urls may differ even pointing article nyt urls tinyurls example i check url see already list linkeditems beyond comparing absolute url this so post helpful high level parsing blogroll style link lists seems lot easier actively comparing urls within post particularly news sites may sorts funny things urls,1 your code seems good attempt achieve desired behavior two suggestions instead taking desktop parameters try directly find left top width height qmainwindow use geometric information move potentially size dialog center application calling exec method hope helps,i qmainwindow creates multiple qdialog child windows sets parent when single monitor everything ok windows centered correctly current monitor but i multiple monitors child windows tend open primary monitor monitor qmainwindow currently resides note windows must able navigate outside parent qtwindow flag set so i center widget relative parent position ie centered qmainwindow avoid opening somewhere else here i currently use center windows def centeronscreenwidget desktopwidget qapplicationdesktop screenrect desktopwidgetavailablegeometrywidget widgetmovescreenrectcenter widgetrectcenter,2 it used making hashes look grep inr secretkey confglobalsettingspysecretkey confprojecttemplatesettingspysecretkey contribauthtokenspy hash shaconstructorsettingssecretkey unicodeuserid contribcommentsformspy info contenttype objectpk timestamp settingssecretkey contribformtoolsutilspy order pickles result secretkey setting takes md contribformtoolsutilspy dataappendsettingssecretkey contribmessagesstoragecookiepy secretkey modified make unique present purpose contribmessagesstoragecookiepy key djangocontribmessages settingssecretkey contribsessionsbackendsbasepy pickledmd mdconstructorpickled settingssecretkeyhexdigest contribsessionsbackendsbasepy mdconstructorpickled settingssecretkeyhexdigest tampercheck contribsessionsbackendsbasepy use settingssecretkey added salt contribsessionsbackendsbasepy settingssecretkeyhexdigest contribsessionsmodelspy pickledmd mdconstructorpickled settingssecretkeyhexdigest contribsessionsmodelspy mdconstructorpickled settingssecretkeyhexdigest tampercheck coremanagementcommandsstartprojectpy create random secretkey hash put main settings coremanagementcommandsstartprojectpy settingscontents resubrsecretkey secretkey settingscontents middlewarecsrfpy randrange maxcsrfkey settingssecretkeyhexdigest middlewarecsrfpy return mdconstructorsettingssecretkey sessionidhexdigest,what exactly point secretkey django i google searches checked docs httpsdocsdjangoprojectcomendevrefsettingssecretkey i looking indepth explanation required for example could happen key compromised others knew thank,3 you use keyword check typedname names typedname names whatcha,i fairly new python life i get work i want set little script check see user types equal names list execute function if user types one names different function this seems like simple i figure i gotten work multiple elif statements check case seems like elegant solution simply typing elif statements every time i want check name current script names scott doug sam harry typednamestrinput what name typedname scott doug sam harry print typedname else print you names list,2 typedname scott doug sam harry print you typedname else print you names list python brings optmization cases typedname scott doug sam harry translated frozenset search constant time set built compiling bytecode,i fairly new python life i get work i want set little script check see user types equal names list execute function if user types one names different function this seems like simple i figure i gotten work multiple elif statements check case seems like elegant solution simply typing elif statements every time i want check name current script names scott doug sam harry typednamestrinput what name typedname scott doug sam harry print typedname else print you names list,3 ok duh quick experiment obj aesnew blablablablablab aesmodecbc objencrypt z rxdxcxcbxxclxdxemr k objencrypt z xaqlxxcbxacyxcegxcexextxexc objencrypt z xcxxlxxbcxexfxwxexx same input different results so cipher object create must retain iv state call encode cipher object next chunk message,i encryptingdecrypting files sizes kinds small text files video files gb the pycrypto classes encodestring encoding method implying i must pass whole file one big string python bytesstring this seems less ideal how i feed pycrypto blocks piecemeal if i split file chunks fixed number blocks size encrypt chunks individually key would thwart cipher block chaining btw i using aes bit keys unique iv file edit answered question raises another good chunk size use one block time several and anyone know convenient method reads file pads multiple block size,3 i actually quite sure work might issue qt handles focus transition windows anyways might fix i changed code bit pyqtqtcore import pyqtqtgui import import sys class mywindowqmainwindow def initself parentnone supermywindow selfinit selflabel qlabel window selfsetcentralwidgetselflabel selfsetfocuspolicyqtstrongfocus def focusineventself event selflabelsettext got focus def focusouteventself event selflabelsettext lost focus def changedfocusslotold nownone qapplicationactivewindownone print set focus active window qapplicationactivewindowsetfocus def main app qapplicationsysargv qobjectconnectapp signalfocuschangedqwidget qwidget changedfocusslot win mywindow win mywindow winshow winshow sysexitappexec name main main hope helps regards,i pyqt program i trying get notified window gets focus following advice qundogroup docs it programmer responsibility specify stack active calling qundostacksetactive usually associated document window receives focus but i weird problem one window actually gets focusin focusout events others either receive one creation else never receive here example program usrbinenv python pyqtqtcore import pyqtqtgui import import sys class mywindowqmainwindow def initself supermywindow selfinit selflabel qlabel window selfsetcentralwidgetselflabel selfsetfocuspolicyqtstrongfocus def focusineventself event selflabelsettext got focus def focusouteventself event selflabelsettext lost focus def main app qapplicationsysargv win mywindow win mywindow winshow winshow sysexitappexec name main main,2 i say model rather comparison template zeekay suggests that leads unpleasant dependency internal detail changed class name things would break i rather like class modelamodelsmodel issuchandsuch false class modelbmodela issuchandsuch true it could done property either isinstance comparison selfclassname i think defining real boolean better idea end result template objissuchandsuch else endif i also featurebased thing rather modelbased think isstaff django user model it using separate classes idea applies make sure far lies appears template makes sense someone knows nothing implementation backend,i django models model a model b model b inherits model a class modelamodelsmodel fields class modelbmodela more fields i want able treat model differently templates shown objismodela this problem lies do something elif objismodelb this problem lies do something else endif i sure i could hack something together i really like know preferred way many thanks advance,1 pseudocode symbol push symbol onto stack item x popped stack x contains nonterminal calculate possible result variation leftmost nonterminal variation lower max length push stack else add popped x set q results deduping print contents q sorted desired note nonterminal singleevaluated variant means string aab evaluate a b since nonterminal options then evaluate a separate path wind pushing two things onto stack note python simply use appendingremoving end list stack set set,i trying generate terminal strings given file certain length so instance something like a a b a b b b then would get something like this something i thought overly difficult i getting stuck i currently read values append dictionary rules stored list like b a a b b it would seem like want start one nonterminal symbols ex a b iterate rule if symbol rule nonterminal symbol print save nonterminal symbol replace rule check i stumped go python i done much any help would much appreciated,1 i recommend something like accumarray your output dimensional data cube dimension corresponds variable age year cause each index dimension corresponds unique value input lists you use something like cookbook example accumulate datasets variable appropriate bins using age year cause you might also consider using proper relational database they quite fast sorts things python ships sqlite part core unfortunately rather steep learning curve never worked relational database you want use group aggregate functionality,i trying sum elements separate data array characteristics efficiently i three identifying characteristics age year cause given array age year cause i values i need add values another data array characteristics for i something like datasets import numpy np datasets npvstackdataset dataset ages years c causes output npsumdatasetsagea amp yeary amp causec axis however iterations incredibly slow the challenge arrays necessarily shape any thoughts,1 the surfacefill clear r g b a values img pygameimageloadhasalphapng print imggetat surfacefill print imggetat it sounds like describing if trying something specific alpha values pygamesurfarraypixel functions give directly editable values that quick requires numpy dependency,i trying write d game using python pygame blits several layers top one another every screen refresh my basic setup bottom top background surface nontransparent scrolls different rate rest midground srcalpha transparent surface static player sprites enemies sprite group forground srcalpha transparent surface static right i blitting four layers one top another every screen the background scrolls different rate three layers i separate midground as i game structured runs fairly modest laptop fps but i trouble sprite group i blitting directly screen having adjust rect every sprite according current viewport seems like ugly way program things i like elegant solution i love blit sprites another transparent surface i could manage therin lies problem i find way clearing transparent layer half performance some setups i tried i tried filling layer white surface blend mode rgbasub surffill area blendrgbasub super super slow i tried surfacecopy blank surface faster still halves fps i tried combining sprites midground layer using pygamespritelayeredupdates update sprites this effect performance work midground transparent i get trails sprites background layer the best solution i found far current setup drawing sprites directly screen it looks great runs fast pain manage i make sure sprites rect adjusted according viewport every frame its also making collision detection difficult is another quick way clear pygame transparent surface quick done times second alternately setup layers would still accomplish effect,1 on cpython always return number bytes requested unless eof reached,does python read method behave like c read might return less requested number bytes last chunk file reached or guarantee always return full amount bytes bytes exist read,1 may leverage example import random def rollnum return small medium large huge huge huge num print rollrandomrandrange,ok i need help i attempting write program rolls die internally randrange referenced list print result onto screen example user inputs activating dice roll the program rolls checks list see means means medium prints medium however i figure i look tutorial i figure i even search everyone i ask gets confused question so i come pasted set code here pastebin better viewing httppastebincompgemnqtm import random def main print testing print print print sum rawinput sum numberr randomrandrange numberr print small elif numberr print medium elif numberr print large elif numberr print huge input rawinputpress enter continue q quitupper input q break elif input main,1 use lambda object httpcodepadorgitfhnrgi def welcomeemail temporarypassword model type lamdbaobject object modeltemporarypassword temporarypassword modelemail email return model welcome abcom printstrttemporarypassword,when i following def welcomeemail temporarypassword model object modeltemporarypassword temporarypassword modelemail email i get error attributeerror object object attribute temporarypassword how i dynamically create object like i,1 aside small details code seems pretty good those your numberr x lines indented part new block you need double sign test number you need colon knew missing lines rawinput rawimput quotes around testing here code fixes import random def main print testing print print print sum rawinput sum numberr randomrandrange numberr print small elif numberr print medium elif numberr print large elif numberr print huge input rawinputpress enter continue q quitupper input q break elif input main so i say already seem right also vishal advice good,ok i need help i attempting write program rolls die internally randrange referenced list print result onto screen example user inputs activating dice roll the program rolls checks list see means means medium prints medium however i figure i look tutorial i figure i even search everyone i ask gets confused question so i come pasted set code here pastebin better viewing httppastebincompgemnqtm import random def main print testing print print print sum rawinput sum numberr randomrandrange numberr print small elif numberr print medium elif numberr print large elif numberr print huge input rawinputpress enter continue q quitupper input q break elif input main,1 try something like import random mynum small medium large huge def main mysum rawinput mysum numberr randomrandrange printmynumnumberr myinput rawinputpress enter continue q quit myinput q break elif myinput main be careful naming variable names reserved keywords,ok i need help i attempting write program rolls die internally randrange referenced list print result onto screen example user inputs activating dice roll the program rolls checks list see means means medium prints medium however i figure i look tutorial i figure i even search everyone i ask gets confused question so i come pasted set code here pastebin better viewing httppastebincompgemnqtm import random def main print testing print print print sum rawinput sum numberr randomrandrange numberr print small elif numberr print medium elif numberr print large elif numberr print huge input rawinputpress enter continue q quitupper input q break elif input main,1 use ajax,is good way fetch data datastroe app engine without refreshing whole page like twitter new tweets come facebook like comments status appears thanks,1 for simple solution download try audiere module this open first available audio device import audiere ds audiereopendevice os dsopenarrayinputarray samplingfrequency osplay where inputarray dim numpy array floats could eg decompress input mps left right dim arrays use inputarray npcleft right since data raw array need specify samplingfrequency input if different lengths need pad one zeros,is way python play two different mono mp files left right channels i two mp files i want play one left speaker mp right speaker programatically python any solution ok if crossplatform solution great does one suggestions,1 it sounds like talking asynchronous notifications server notifies client new data available this done app engine using channel api,is good way fetch data datastroe app engine without refreshing whole page like twitter new tweets come facebook like comments status appears thanks,3 it something regex engines tend able i know python perl using following local matches foofoobarfoobaz z push matches fail xs this specific problem probably solved using regex engine many languages using following technique matches foofoobarfoobaz zgsp push matches prematch prematch refers comes regex matched refers first matched but easily solve specific problem outside regex engine parts split foofoobarfoobaz matches parts push matches join parts join partsparts sorry using perl syntax able get idea translations python welcome,i regex match string multiple overlapping possible ways however seems capture one possible match string i get possible matches i tried finditer success maybe i using wrong the string i trying parse foofoobarfoobaz the regex i using foofoobarfoobaz matches refinditerr matchgroup match matches foofoobar i want match foo foobarfoobaz seems get foofoobar foobaz,1 if want detect overlapping matches implement essentially string foo find first match starts string index run matching function fooi repeat steps incrementally short remaining portion string it gets trickier using arbitrarylength capture groups eg probably want foofoobar oofoobar matches extra analysis move even farther match need move entire length first captured group value plus one,i regex match string multiple overlapping possible ways however seems capture one possible match string i get possible matches i tried finditer success maybe i using wrong the string i trying parse foofoobarfoobaz the regex i using foofoobarfoobaz matches refinditerr matchgroup match matches foofoobar i want match foo foobarfoobaz seems get foofoobar foobaz,1 just provide default values loggedin username session initializer dict the error seems appear attributes set ie user logged try access,i using webpy framework project i logging login class mainpy program i want get username class i tried session experimented long time i implemented session like store websessiondiskstore sessions session websessionsessionappstoreinitializer login privilege login class mainpy following code work user submit username passwordthis post method f login class class login def postself webinputformsubmitlogin authdb sqliteconnect databaseusersdb conn authdbcursor iformsubmit login check connexecute select userdetails usernameand password iusername ipassword ncheckfetchall lenn sessionloggedin true sessionusername iusername return renderhome home else return renderdisplay wrong username password i want get username class i tried access username sessionusername shows following error attributeerror threadeddict object attribute username,1 no problem regex result refinditerregex foofoobarfoobaz printjoinresultgroups foofoobar foobarfoobaz by putting second capturing parenthesis lookahead assertion capture contents without consuming overall match i also used instead dot also matches separator probably want,i regex match string multiple overlapping possible ways however seems capture one possible match string i get possible matches i tried finditer success maybe i using wrong the string i trying parse foofoobarfoobaz the regex i using foofoobarfoobaz matches refinditerr matchgroup match matches foofoobar i want match foo foobarfoobaz seems get foofoobar foobaz,3 not big gotcha with boolean slicing i sometimes wish i could x like python double comparison instead i write x nplogicalandy unless know something better also nplogicaland nplogicalor take two arguments i would like take variable number list i could feed two logical clauses numpy maybe changed later versions,folks collection gotchas numpy differs python points puzzled cost time the horror moment i shall never never forget you though queen said make memorandum for example nans always trouble anywhere if explain without running give point numpy import array nan isnan pynan floatnan print pynan pynan pynan nan nan nan pynan print pynan anyaa pynan aa array nan print nan isnan i knocking numpy lots good work think faq wiki gotchas would useful edit i hoping collect half dozen gotchas surprises people learning numpy then common gotchas better common explanations could talk adding community wiki it look like enough far,1 the listproperty python list helper methods make work gae anything applies list applies listproperty employeedepartmentsremovedepartmentkey employeeput keep mind data must deserializedreserialized every time change made looking speed adding removing single values may want go another method modelling relationship like one relationship model section page the listproperty method also disadvantage sometimes producing large indexes want search lists datastore request this may problem since lists relatively small something keep mind future projects,in google app engine solution python i used dblistproperty way describe manytomany relation like class departmentdbmodel name dbstringproperty property def employeesself return employeeallfilter departments selfkey class employeedbmodel name dbstringproperty departments dblistpropertydbkey i create manytomany relations simply appending department key dblistproperty like employeedepartmentsappenddepartmentkey the problem i know actually remove relationship longer needed i tried googling i seem find documentation describes dblistproperty details any ideas references,2 well python standard library says filereadsize read size bytes file less read hits eof obtaining size bytes if size argument negative omitted read data eof reached an empty string returned eof encountered immediately also note nonblocking mode less data requested may returned even size parameter given,does python read method behave like c read might return less requested number bytes last chunk file reached or guarantee always return full amount bytes bytes exist read,1 although parsing html regexes i point common error regexes use w that matches az az underscores not slashes parentheses if trying pull data attributes use,i trying extract two strings string using regular expressions img srchttpimagesefollettcombooksgif width height altorganic chemistry i second language i want url src text alt organic chemistry i second language url i tried img srcw width img srcw srcwswidth url return empty i also tried altw name luck can anyone help,1 you try r imgssrc r imgsalt i know dealing html ensure inside brackets used avoid tags like xxxsrc take care newlines,i trying extract two strings string using regular expressions img srchttpimagesefollettcombooksgif width height altorganic chemistry i second language i want url src text alt organic chemistry i second language url i tried img srcw width img srcw srcwswidth url return empty i also tried altw name luck can anyone help,1 it really depends much stuff want expose globally obviously anything put h available throughout application whereas could return createblog function views want one littleknown tidbit use classbased views actual class instance available view view global variable for example class fooobject def initself request selfrequest request def createblogself return render blogmako viewconfig def myviewself return now template call render blog using viewcreateblog,in pyramid i created helpers functionality similar pylons one particular function helperspy file like pyramidrenderers import rendertoresponse def createblog lots code return rendertoresponse blogmako xyz xyz and applications i import helpers something like following templates hcreateblog creates blog page but i wondering good way using helpers create module style plugins i easily use anywhere projects or flaws technique i really thought yet thanks,2 how using needlemanwunsch algorithm the scoring matrix would trivial distance two numbers difference but probably feel like killing sparrow tank,two d numpy arrays the lengths unequal i want make pairs arrayelemntarrayelement elements close lets consider following example b the expected result it important note left alone it could easily done loops i large arrays i considered using nearest neighbor but felt like killing sparrow canon can anybody please suggest elegant solution thanks lot,1 when create basicrobottestcase lose b variable store member instance ie selfb edit well missing self origin problem maybe way nose instanciate class change something usb grabbing try instanciate class directlry import nxtlocator nxtmotor import class basicrobottestcase test true def initself selfb nxtlocatorfindonebrick store brick selfb def flipcubeself marm motorselfb portb use stored brick selfb create motor marmturn marmturn def testflipcubeself selfflipcube namemain basicrobottestcasetestflipcube,i simple working example using pythonnxtlibusb follows note using lego nxt usb interface import nxtlocator nxtmotor import def flipcubeb marm motorb portb marmturn marmturn b nxtlocatorfindonebrick flipcubeb above works fine as training exercise i try objectize python code i could start putting libraries around code libusb library complains cant find usb device huh what i wrong here attempt code using class structure import nxtlocator nxtmotor import class basicrobottestcase test true def initself b nxtlocatorfindonebrick def flipcubeself marm motorb portb marmturn marmturn def testflipcubeself flipcube when i execute i get following error even though i reexecute first sample executes fine e error failure usberror no device may disconnected traceback recent call last file librarypythonsitepackagesnosepyeggnoseloaderpy line maketest return selfmaketestobj parent file librarypythonsitepackagesnosepyeggnoseloaderpy line maketest return methodtestcaseobj file librarypythonsitepackagesnosepyeggnosecasepy line init selfinst selfcls file usersgnunezgitprojectspdcaautomationrubicstestsbasicrobottestcasepy line init b nxtlocatorfindonebrick file usersgnunezgitprojectspdcaautomationnxtlocatorpy line findonebrick findbrickshost name silent method file usersgnunezgitprojectspdcaautomationnxtlocatorpy line findbricks socks file usersgnunezgitprojectspdcaautomationnxtusbsockpy line findbricks bus usbbusses file buildbdistmacosxuniversaleggusblegacypy line busses return bus file buildbdistmacosxuniversaleggusblegacypy line init selfdevices deviced corefindfindalltrue file buildbdistmacosxuniversaleggusblegacypy line init selfconfigurations configurationc c dev file buildbdistmacosxuniversaleggusbcorepy line iter yield configurationself file buildbdistmacosxuniversaleggusbcorepy line init configuration file buildbdistmacosxuniversaleggusbdebugpy line dotrace return fargs namedargs file buildbdistmacosxuniversaleggusbbackendlibusbpy line getconfigurationdescriptor config byrefcfg file buildbdistmacosxuniversaleggusbbackendlibusbpy line check raise usberrorstrerrorretvalvalue usberror no device may disconnected,1 define dummy class first class myobjectobject pass obj myobject objtemporarypassword temporarypassword,when i following def welcomeemail temporarypassword model object modeltemporarypassword temporarypassword modelemail email i get error attributeerror object object attribute temporarypassword how i dynamically create object like i,1 you try see works i test moment results cursorfetchalldict returning first result set far mysqldb concerned ie result first select try adding nextset call like def executesp spname paramaters helper method run sp return results db db cursor dbcursor cursorcallprocspnameparamaters cursornextset need second result set proc results cursorfetchalldict cursorclose return results let know work,see stored procedure routine ddl delimiter create definerrootlocalhost procedure getfollowersin userid intin topicid intin type int mainbegin select sqlcalcfoundrows followuserid countfollowuserid as topicidcount from follow where followfolloweeuserid userid and topicid topicid or topicid group by followuserid select foundrows as count end when i use test call stored procedure function mysql workbench giving expected result number count but when i execute python code dump json put query giving following result userid userid userid according view considering select foundrows as count statement i call sp form python code fallow results executespgetfollowers userid topicid type execut custom function def executesp spname paramaters helper method run sp return results db db cursor dbcursor cursorcallprocspnameparamaters results cursorfetchalldict cursorclose return results pleas help solve,1 this works statichandler cherrypytoolsstaticdirhandlersection dirsettingsstaticroot cherrypytreemountstatichandler static case csshandler cherrypytoolsstaticdirhandlersection dir pathtocss cherrypytreemountcsshandler css,i devil time getting cherrypy serve necessary css file page returned my directory structure application abpy cherrypy application abconfig cherrypy config file html html template folder abhtml html template file css css folder abcss css file the link statement abhtml link hrefcssabcss relstylesheet typetextcss and finally abconfig toolsstaticdirroot cssabcss toolsstaticfileon true toolsstaticfilefilename cssabcss my template loaded rendered browser i expected styling applied if i change template use relative address cssabcss open template file browser styling applied it took get configuration file point cherrypy complain bad paths starting application at point starts renders returns fine simply appear serve css file browser any help greatly appreciated update based kind suggestions fumanchu preferring use staticdir understanding root refers filesystem absolute path i config file toolsstaticdirroot cusersmyaccountdocumentsclientnameapplication css toolsstaticdiron true toolsstaticdirdir css in html i style sheet link link hrefcssabcss relstylesheet typetextcss and i starting cherrypy cherrypyquickstartabroot abconfig in configuration i still get styling web page when i check page source click cssabcss link directly i get notfound the path cssabcss found note i developing windows machine,1 just quick google search i found the calculations noaa sunrisesunset solar position calculators based equations astronomical algorithms jean meeus the sunrise sunset results verified accurate within minute locations â° latitude within minutes outside latitudes a detailed explanation calculation details found page also,i writing python program needs determine whether postsunrise given current utc time target latitude longitude i see apps sort thing time i idea done any ideas,1 a complete layout algorithm not lot add really the points document quoted break simple reproduce steps implemented language really,i writing python program needs determine whether postsunrise given current utc time target latitude longitude i see apps sort thing time i idea done any ideas,1 there almost certainly better way someone points work import inspect class testclass def testmethodself log def log stack inspectstack try print whole stack print njoinstrx x stack print print caller strstack finally del stack testclasstestmethod the output following whole stack stack inspectstackn fn testclasstestmethodn exec code selflocalsn ret methodargs kwargsn none caller testclasstestmethodn,if i want function name i simply include funcnames formatter but i get name class containing logging call instead i gone documentation logging i find mentioning,1 if need know length indices lenindices but question,i using numpy i want store result calculation inside three fourdimensional matrix i want something like result indices iteration somefunction work dimension understood length indices tuple so indices equals say i want equivalent result iteration somefunction result iteration somefunction normally i put coordinates tuple use index presence prevents the dimension result set earlier correct dimension check would nice use length indices determine is way accomplish,1 here someone implementation sunrisesunset calculation python httpmichelandersblogspotcomcalulatingsunriseandsunsetinpythonhtml,i writing python program needs determine whether postsunrise given current utc time target latitude longitude i see apps sort thing time i idea done any ideas,2 i solved admin model class myobjectadminformformsmodelform class meta model mymodel def cleantagsself tags selfcleaneddata tags lentags raise validationerror return tags class myobjectadminadminmodeladmin form myobjectadminform,i really impressed implementation djangotaggit application handling tags within django however i unable find way set maximum number tags applied object maxtag is possible i like limit application example tags per object thanks j,2 try using resultslicenone indices iteration,i using numpy i want store result calculation inside three fourdimensional matrix i want something like result indices iteration somefunction work dimension understood length indices tuple so indices equals say i want equivalent result iteration somefunction result iteration somefunction normally i put coordinates tuple use index presence prevents the dimension result set earlier correct dimension check would nice use length indices determine is way accomplish,1 so customprintpy skins directory available portalskins used default skin in words visiting httpyourplonesitecustomprint returns string hello world then customize loginnext script custom map portalskins skin file system call contextcustomprint,i plone instance setup i trying call custom python script function loginnext script how would i say eg customprintpy def disp return hello world how would i call disp inside loginnext script,1 can help without proper errortraceback for updated point remember need requestpostgetlistfieldname expecting multiple values,it happened i use arrays postgresql in django models native support arrays i used djangoarrayfields but display admin i use field hoprizontalfilter integerarrayfield modelspy class groupmodelsmodel name modelstextfield class usermodelsmodel name modelstextfield groups integerarrayfield adminpy class groupadminformformsmodelform groups formsmodelmultiplechoicefield querysetgroupobjectsall label select groups requiredtrue widgetfilteredselectmultiple groups false class useradminadminmodeladmin fields groups form groupadminform as result widget displayed works properly but maintaining writes adapt type queryset please help upd request information field post variable groups value corresponds last id selected group rather array i expect,1 depends put script script skin directory use acquisition maurits says contextcustomprint just aware acquisition pitfalls filesystem module use like import mymodule mymodulecustomprint,i plone instance setup i trying call custom python script function loginnext script how would i say eg customprintpy def disp return hello world how would i call disp inside loginnext script,1 one way simply refer variable full name myspidercommentlist class myspiderobject commentlist def parsepostself response myspidercommentlistappendsomedata def parsecommentsself response myspidercommentlistappendsomedata this way instances myspider share variable if might multiple instances myspider want instance commentlist simply create constructor refer selfcommentlist class myspiderobject def initself selfcommentlist def parsepostself response selfcommentlistappendsomedata def parsecommentsself response selfcommentlistappendsomedata if versions would work case i suggest using latter,i two methods write list class myspider def parsepostself response commentlist commentlistappendsomedata def parsecommentsself response commentlist commentlistappendsomedata in code two commentlist lists i need single list i append data i want access list method class i tried class myspider commentnum def parsepostself response commentlistappendsomedata def parsecommentsself response commentlistappendsomedata but gives error global name commentlist defined any ideas single list accessed methods class,2 just selfcommentlistappendsomedata note normal python style use commentlist somedata though,i two methods write list class myspider def parsepostself response commentlist commentlistappendsomedata def parsecommentsself response commentlist commentlistappendsomedata in code two commentlist lists i need single list i append data i want access list method class i tried class myspider commentnum def parsepostself response commentlistappendsomedata def parsecommentsself response commentlistappendsomedata but gives error global name commentlist defined any ideas single list accessed methods class,1 just make instance attribute class myspiderobject def initself selfcommentlist def parsepostself response selfcommentlistappendsomedata the instance self python convention java eg explicit python if initialize array outside methods like nd listing make class attribute ie static one global instances referenced using full name myspidercommentlist typeselfcommentlist want avoid class name eg inheritance due lookup attributes selfcommentlist also work attribute found instance level class looked distinction less obvious explicit better implicit,i two methods write list class myspider def parsepostself response commentlist commentlistappendsomedata def parsecommentsself response commentlist commentlistappendsomedata in code two commentlist lists i need single list i append data i want access list method class i tried class myspider commentnum def parsepostself response commentlistappendsomedata def parsecommentsself response commentlistappendsomedata but gives error global name commentlist defined any ideas single list accessed methods class,1 use lxml import lxmlhtml htmlstring img srchttpimagesefollettcombooksgif width height altorganic chemistry i second language img lxmlhtmlfromstringhtmlstring print src imggetsrc print alt imggetalt gives src httpimagesefollettcombooksgif alt organic chemistry i second language,i trying extract two strings string using regular expressions img srchttpimagesefollettcombooksgif width height altorganic chemistry i second language i want url src text alt organic chemistry i second language url i tried img srcw width img srcw srcwswidth url return empty i also tried altw name luck can anyone help,1 it would help mentioned data format storeofauthornames output currently getting expecting instead all i tell view authors storeofauthornames produced getauthornamesoup checkifvalidclass returns false end nameerror trying reference storeofauthornames since undeclared if i guess problem based solely example template i say problem authorssafe you want apply safe filter value printing list ie ul author authors li authorsafe li endfor ul,i pretty new django template system basically i trying print contents list i passing django context the relevant part urlspy urlr class twobooksclassesviewsgetallinformation templatename classesdisplaybookshtml now views getallinformation follows def getallinformationsearchtermtemplatename nameandnumberstore modifysearchtermsearchterm url modifyurlnameandnumberstore soup gethtmlurl information checkifvalidclasssoupnameandnumberstore storeofeditions geteditionsoup storeofauthornames getauthornamesoup storeofbooknames getbooknamessoup storeofimages getimagessoup informationappendstoreofauthornamesremember list two lists informationappendstoreofeditions return rendertoresponse templatename authors storeofauthornames displaybookshtml follows html head body htesting class page backendh ul author authorssafe li author li endfor ul body html i think fairly simple i sure going thought i ask help thanks,1 try page httpzetcodecomtutorialspygtktutorialdialogs hope helps,i drawing interface pygtk application using glade i made dialog i trouble close button dialog the close button credits operates expected dialog button nothing closed windows manager i went select button clicking expanding items contained gtkhbuttonbox i expand top right section i click selects gtkhbuttonbox i looked found gtkaboutdialog close button bug about dialog i tried following instructions thought seemed bit funny since puts destroy immediately show exactly destroys straight away showing i also looked pygtk tutorial updated since anything dialog filename sudokuguiglade builder gtkbuilder builderaddfromfilefilename builderconnectsignalsself aboutwindow buildergetobject aboutsudoku aboutwindowshow please help i much appreciated solution because solution directly provide detail needed i put reference the last line changed aboutwindowrun show add aboutwindowdestroy close dialog close button clicked,1 applying safe filter turn anything string if start literal foo u bar going end approximately literal u foo u bar something like itmdashi quite certain rendered i never tried also i say approximately actually safestring instance unicode instance then iteration going character produced string want instead use safeseq filter applies safe filter element sequence ul author authorssafeseq li author li endfor ul or could apply safe value inside iterator ul author authors li authorsafe li endfor ul i would recommend safeseq may able optimise template wish unorderedlist filter wish display values note i certain behavesmdashit possible would unmark safe you need try ul authorssafesequnorderedlist ul,i pretty new django template system basically i trying print contents list i passing django context the relevant part urlspy urlr class twobooksclassesviewsgetallinformation templatename classesdisplaybookshtml now views getallinformation follows def getallinformationsearchtermtemplatename nameandnumberstore modifysearchtermsearchterm url modifyurlnameandnumberstore soup gethtmlurl information checkifvalidclasssoupnameandnumberstore storeofeditions geteditionsoup storeofauthornames getauthornamesoup storeofbooknames getbooknamessoup storeofimages getimagessoup informationappendstoreofauthornamesremember list two lists informationappendstoreofeditions return rendertoresponse templatename authors storeofauthornames displaybookshtml follows html head body htesting class page backendh ul author authorssafe li author li endfor ul body html i think fairly simple i sure going thought i ask help thanks,2 you could try binary package lion available pygame website it worked osx bundled python,i tried install pygame via pip fails based google searches sounds like easyinstall also fails i also checked httpwwwpygameorgwikimaclioncompile solution incomplete i running python bundled lion suggestions appreciate help,3 looks like using scrapy if list part item i usually pass item another callback using meta parameter requestresponse object,i two methods write list class myspider def parsepostself response commentlist commentlistappendsomedata def parsecommentsself response commentlist commentlistappendsomedata in code two commentlist lists i need single list i append data i want access list method class i tried class myspider commentnum def parsepostself response commentlistappendsomedata def parsecommentsself response commentlistappendsomedata but gives error global name commentlist defined any ideas single list accessed methods class,1 and template layer still use underlying django utils ex djangoutilsdateformat import format print formatmymodelmydatefield u,hello in model i field mydate modelsdatefield javascript graph function requires unix timestamp i return unix timestamp mydate input thanks,3 you looking pythonbrew perhaps,i know question already exists really old i know i looking i used application earlier let easily install version python set default one command i life remember name reason i find via google either,2 to quote qt documentation the desktop may composed multiple screens would incorrect example attempt center widget desktop geometry so see qt says incorrect way center widget as kroonwijk recommended i say either use qmainwindow geometry centering in case get mainwindow access widget scope one way get top level widgets using qapplicationtoplevelwidgets then use tricks meta information obtain mainwindow,i qmainwindow creates multiple qdialog child windows sets parent when single monitor everything ok windows centered correctly current monitor but i multiple monitors child windows tend open primary monitor monitor qmainwindow currently resides note windows must able navigate outside parent qtwindow flag set so i center widget relative parent position ie centered qmainwindow avoid opening somewhere else here i currently use center windows def centeronscreenwidget desktopwidget qapplicationdesktop screenrect desktopwidgetavailablegeometrywidget widgetmovescreenrectcenter widgetrectcenter,1 if use object data structure ie methods use namedtuple collections package collections import namedtuple def welcomeemail tmppasswd model namedtuple mymodel email temporarypassword email tmppasswd by way welcome function creates object returns need just collections import namedtuple welcome namedtuple welcome email temporarypassword ex welcome meexamplecom foobar print exemail print extemporarypassword,when i following def welcomeemail temporarypassword model object modeltemporarypassword temporarypassword modelemail email i get error attributeerror object object attribute temporarypassword how i dynamically create object like i,1 if python version recent enough create class decorator in case indirect one def runifmainmainname def decoclas mainname main clasrun return clas return deco runifmainname class ba job define runifmain somewhere centrally use runifmainname wherever needed,i generic class a subclassed lot like class a def runself selfdosomething abstract function def dosomethingself pass class ba def dosomethingself the subclasses separate files i running directly adding code file b name subclass file name main brun my question i avoid add code files subclasses since thing changes code class used b example,3 i believe requests library mentioned well,what i trying get headers given url i determine mime type i want able see httpsomedomainfoo return html document jpeg image example thus i need figure send head request i read mime type without download content does anyone know easy way,3 just use oswalk recursively walk file tree osstat file paths gives goes,i would like write script deletes new folderexe regsvrexe viruses my algorithm following get current working directory check directory contains file extension exe size bytes isare files delete recursiveley steps subfolders parent folder i want ask efficiency since root folder may contain thousands folders better implement imports use,1 yes if store variable named would use results geometry location et cetera notice due fact dict key geometry inside list simplejsonload maps json objects python dict json lists list very straightforward overthink simplejsondumps simply opposite simplejsonloads takes standard python object dumps string json representation object for instance q q foo bar q baz simplejsondumpsq baz foo bar,dictionary data returned simplejsonload function looks like status ok results geometry locationtype approximate bounds northeast lat lng southwest lat lng viewport northeast lat lng southwest lat lng location lat lng addresscomponents longname trawden types sublocality political shortname trawden longname colne types locality political shortname colne longname lancashire types administrativearealevel political shortname lancs longname united kingdom types country political shortname gb formattedaddress trawden colne lancashire uk types sublocality political how i get eg resultsgeometrylocationlat is structure regular python dictionary edit please could someone also explain simplejsondumps function i find docs enlightening thanks edit nonop json prettyprinted statusok results geometry location lat lng locationtypeapproximate viewport northeast lat lng southwest lat lng bounds northeast lat lng southwest lat lng addresscomponents longnametrawden shortnametrawden types sublocality political longnamecolne shortnamecolne types locality political longnamelancashire shortnamelancs types administrativearealevel political longnameunited kingdom shortnamegb types country political formattedaddresstrawden colne lancashire uk types sublocality political,2 sysgetdefaultencoding not grumble much probably something googled first result python os default encoding second python system default encoding,the documentation fileobjectencoding mentions none case system default encoding used how i find encoding,3 how something like input rawinputenter three numbers separated commas inputlist inputsplit numbers floatxstrip x inputlist you would probably want error handling,know take single input user python rawinputenter st number opens one input screen takes first number want take second input need repeat command opens another dialogue box how take two inputs together dialogue box opens enter st number enter second number,3 i made following changes mainpy program changes made instead giving session websessionsessionappstoreinitializer login privilege user anonymous loggedin false i added following lines code webconfigget session none session websessionsessionappstoreinitializer login privilege user anonymous loggedin false webconfigsession session else session webconfigsession i also made small change initilizer dictionary inititialized user anonymous loggedin false thanks andrey giving thread,i using webpy framework project i logging login class mainpy program i want get username class i tried session experimented long time i implemented session like store websessiondiskstore sessions session websessionsessionappstoreinitializer login privilege login class mainpy following code work user submit username passwordthis post method f login class class login def postself webinputformsubmitlogin authdb sqliteconnect databaseusersdb conn authdbcursor iformsubmit login check connexecute select userdetails usernameand password iusername ipassword ncheckfetchall lenn sessionloggedin true sessionusername iusername return renderhome home else return renderdisplay wrong username password i want get username class i tried access username sessionusername shows following error attributeerror threadeddict object attribute username,2 what looking denis otkidach excellent cachedattribute class cachedattributeobject computes attribute value caches instance from python cookbook denis otkidach this decorator allows create property computed accessed many times sort like memoization def initself method namenone record unboundmethod name selfmethod method selfname name methodname selfdoc methoddoc def getself inst cls self maincache object xbc inst mainfoo object xbc cls class mainfoo inst none instance attribute accessed class return self you get write foobar return self compute cache return instance attribute value result selfmethodinst setattr redefines instance attribute get called setattrinst selfname result return result it used like def democache class fooobject cachedattribute def barself print calculating selfbar return foofoo printfoobar calculating selfbar notice accessing foobar subsequent times call getter function calculating selfbar printed printfoobar foobar printfoobar deleting foobar foodict reexposes property defined foo thus calling foobar recalculates value del foobar printfoobar calculating selfbar democache the decorator published python cookbook also found activestate this efficient although property exists class dict computation attribute name created instance dict python attribute lookup rules gives precedence attribute instance dict property class becomes effectively overridden,situation similar question i want replace property unlike question i want override subclass i want replace init property efficiency call function calculates value time property called i class property the constructor may take value property if passed value i want replace property value set property this property calculates value expensive operation similarly i want replace property value calculated property calculated future calls property recalculate class myclassobject def initself somevarnone somevar none selfsomevar somevar property def somevarself selfsomevar calcsomevar return selfsomevar problem the code work selfsomevar replace somevar function it tries call property setter defined potential solution i know i achieve thing slightly different way follows class myclassobject def initself somevarnone selfsomevar somevar property def somevarself selfsomevar none selfsomevar calcsomevar return selfsomevar this marginally less efficient check none every time property called the application performance critical may may good enough question is way replace property instance class how much efficient would i able ie avoiding none check function call,3 sure set attribute private dictionary class instance takes precedence calling property function foo static dictionary adict class a def initself selffoo selfdict foo property def fooself return selffoo assert afoo if want reset work property del selfdict foo,situation similar question i want replace property unlike question i want override subclass i want replace init property efficiency call function calculates value time property called i class property the constructor may take value property if passed value i want replace property value set property this property calculates value expensive operation similarly i want replace property value calculated property calculated future calls property recalculate class myclassobject def initself somevarnone somevar none selfsomevar somevar property def somevarself selfsomevar calcsomevar return selfsomevar problem the code work selfsomevar replace somevar function it tries call property setter defined potential solution i know i achieve thing slightly different way follows class myclassobject def initself somevarnone selfsomevar somevar property def somevarself selfsomevar none selfsomevar calcsomevar return selfsomevar this marginally less efficient check none every time property called the application performance critical may may good enough question is way replace property instance class how much efficient would i able ie avoiding none check function call,1 your data sounds like would better represented dictionary lists consecutive elements special relationship sound odd if instead represented data like stephane philippe hã©lã¨ne hugo jeanmichel fernand gustave then simply sort keys dictionaries get order want,i following list stephane philippe hã©lã¨ne hugo jeanmichel fernand gustave and i would like order like gustave hã©lã¨ne fernand hugo jeanmichel philippe stephane nb if nested list following user list must stay right user in addition nested lists works way it recursive,3 you write custom form check author exists system use existing create new provided name class customformformsmodelform author formscharfield def saveself committrue author created authorobjectsgetorcreatenameselfcleaneddata author instance supercustomformselfsavecommitcommit instanceauthor author commit instancesave return instance class meta modelbook not sure code working i suppose explain idea,if i two models django application like class authormodelsmodel name modelscharfieldmaxlength class bookmodelsmodel author modelsforeignkeyauthor title modelscharfieldmaxlength how i create single form allows add author book simultaneously if author exists system i could simply display book form link author often i need allow users create book author simultaneously how i thanks,2 you use following code convert numpy arrays qimage pyqtqtgui import qimage qrgb import numpy np class notimplementedexception pass graycolortable qrgbi range def toqimageim copyfalse im none return qimage imdtype npuint lenimshape qim qimageimdata imshape imshape imstrides qimageformatindexed qimsetcolortablegraycolortable return qimcopy copy else qim elif lenimshape imshape qim qimageimdata imshape imshape imstrides qimageformatrgb return qimcopy copy else qim elif imshape qim qimageimdata imshape imshape imstrides qimageformatargb return qimcopy copy else qim raise notimplementedexception convert opencv cvmat numpy array calling toqimage arr numpyasarraymat qim toqimagearr see also httpopencvwillowgaragecomdocumentationpythoncookbookhtml conversion opencv cvmat numpy arrays,i trying process videos using opencv put inside pyqt qimage i saw examples c i understand python can anyone help please thank,1 probably frame never focus try give focus first theframegrabfocus hope works i test so i need detect focus moves element contained frame you may connect event focusoutevent every entry frame def outoffocusself widget focusinframe false child widgetgetparent childhasfocus focusinframe true focusinframe false theframehide i still test time evening,i gtkframe containing set gtkentries i want hide gtkframe focus removed gtkframe i connected handler focusoutevent signal frame nevers get invoked any ideas achieve,1 here great python module someone wrote solve problem seeing question httpsgithubcomjohnkurkowskitldextract the module looks tlds public suffix list mantained mozilla volunteers quote tldextract hand knows gtlds generic toplevel domains cctlds country code toplevel domains look like looking currently living ones according public suffix list so given url knows subdomain domain domain country code,would extract domain name url excluding subdomains my initial simplistic attempt joinurlparseurlparseurlnetlocsplit this works httpwwwfoocom httpwwwfoocomau is way properly without using special knowledge valid tlds top level domains country codes change thanks,3 as specific function asking i know net includes the quickest way however would something like int id foreachvar elem somelist dostuff id edit here function ask using yield return downside requiring one gc allocation per iteration public static ienumerabletupleint t enumeratetienumerablet list int id foreachvar elem list yield return new tupleint tid elem id,i could find related question in python easily loop sequence list generator etc collect index iteration time thanks enumerateseq like iitem enumeratetototititutu print item toto titi tutu is something similar ienumerable would instance transform ienumerablet ienumerabletupleintt i know would easily done thanks correct function select exists i rather use update fyi i curious kind possibility able something like give index last item fulfils condition would accomplished myenumerationfirstt condition titem item,2 you able seek back start stream see werkzeug docs werkzeugdatastructuresfilestorage when try read file second time start reading end file filesaveospathjoinappconfig uploadfolder filename filestreamseek go back start file print filestreamread work,it seems cannot access filestreamread file written filesave path filename vice versa example code derived file uploading pattern import os flask import flask request redirect urlfor sendfromdirectory werkzeug import securefilename uploadfolder uploads allowedextensions set txt pdf png jpg jpeg gif app flaskname appconfig uploadfolder uploadfolder def allowedfilefilename return filename filenamersplit allowedextensions approute methods get post def uploadfile requestmethod post file requestfiles file file allowedfilefilefilename filename securefilenamefilefilename print print ospathjoinappconfig uploadfolder filename filesaveospathjoinappconfig uploadfolder filename print filestreamread gives output print return redirecturlfor uploadedfile filenamefilename return doctype html titleupload new filetitle hupload new fileh form action methodpost enctypemultipartformdata pinput typefile namefile input typesubmit valueupload form approute uploadsfilename def uploadedfilefilename return sendfromdirectoryappconfig uploadfolder filename name main apprundebugtrue,2 i used ned proposal came stephane philippe helene hugo jeanmichel fernand gustave def sortdictaslistd sortedlist k v sortedditems k sortedlistappendk v sortedlistappendv return sortedlist def sortrecursived k v ditems dk sortrecursivev return sortdictaslistd else return name main print sortrecursived output python sortitpy gustave helene fernand hugo jeanmichel philippe stephane i tested thoroughly starting point i trying solve list data structure i ended nesting recursive functions way ugly ned proposal really good,i following list stephane philippe hã©lã¨ne hugo jeanmichel fernand gustave and i would like order like gustave hã©lã¨ne fernand hugo jeanmichel philippe stephane nb if nested list following user list must stay right user in addition nested lists works way it recursive,1 the best place look documentation acmelab example envisage source tree i assuming talk custom buttons mean buttons toolbar first need create workbenchactionset add toolbar define actions assign button image here slightly modified acmelab example nonrelevant parts taken testactionsetpy enthought library imports envisageuiactionapi import action group menu toolbar envisageuiworkbenchapi import workbenchactionset class testactionsetworkbenchactionset an action test useful testing actionset interface toolbars toolbarname fred groups atoolbargroup toolbarname wilma toolbarname barney actions action path toolbar classname acmeworkbenchactionnewviewactionnewviewaction newviewactionpy an action dynamically creates adds view enthought library imports pyfaceapi import imageresource pyfaceactionapi import action pyfaceworkbenchapi import view class newviewactionaction an action dynamically creates adds view action interface a longer description action description create add new view the action name displayed menustool bar tools etc name new view a short description action used tooltip text etc tooltip create add new view image imageresourceyour image file name goes here action interface def performself event perform action you give view position default left view viewid myviewfred name fred position right selfwindowaddviewview specify call addview view viewid myviewwilma name wilma selfwindowaddviewview position top return eof,i started envisage framework in x version i saw example i need good documentation link how i add custom buttons envisage workbench i create similar one,1 here answer question if exist i might well like without actually writing foreach var items new liststring toto titi tutu var enumerated itemsselectx new tupleint stringi x foreach var enumerated consolewritelinestringformat titem titem prints toto titi tutu it oneliner ugly one oneliner anyway,i could find related question in python easily loop sequence list generator etc collect index iteration time thanks enumerateseq like iitem enumeratetototititutu print item toto titi tutu is something similar ienumerable would instance transform ienumerablet ienumerabletupleintt i know would easily done thanks correct function select exists i rather use update fyi i curious kind possibility able something like give index last item fulfils condition would accomplished myenumerationfirstt condition titem item,1 instead using tuple class use keyvaluepair struct this avoid memory allocations enumerated expensive still public static ienumerablekeyvaluepairint t enumeratetthis ienumerablet items return itemsselectitem key new keyvaluepairkey item,i could find related question in python easily loop sequence list generator etc collect index iteration time thanks enumerateseq like iitem enumeratetototititutu print item toto titi tutu is something similar ienumerable would instance transform ienumerablet ienumerabletupleintt i know would easily done thanks correct function select exists i rather use update fyi i curious kind possibility able something like give index last item fulfils condition would accomplished myenumerationfirstt condition titem item,2 everytime i run command python setuppy install python shell says syntaxerror invalid syntax please create folder unzip numpyzip file say folder name cnumpy open msdos terminal described httpenwikipediaorgwikicommandlineinterface type cd cnumpy python setuppy config python setuppy install this set needed files correct folders python enjoy,i working python bit windows vista i downloaded libraries including numpy scipy pygame when i try import modules output says traceback recent call last file pyshell line module import numpy importerror no module named numpy i find modules python folders reason want recognize thing i made sure file compatible downloading,1 you mix html image document like use img tag embed images html,i webpage generated python works using print contenttype texthtmlnn print blank line end headers print link hrefdefaultcss relstylesheet typetextcss print htmlhead i want add images webpage i sysstdoutwrite contenttype imagepngnn filepngrbread print contenttype texthtmlnn print blank line end headers print link hrefdefaultcss relstylesheet typetextcss all i get image i place image code htmltext header i get text image ie ãâ·ã¶ããŽâ´ãzâºmâ¾â€°kã—â®å¾ã²ã¥ã‹ã›â¶ãƒgå¾yfk–ã‘ã´ã©ã“uâ½zuiã’ã·ãâ§ampmå¡h’vâ¯â­ã¼ã°â¼â±â±â±zã½ãµã—iã±ã±ã±ãšâºuâ«wâ®â¬wãŸw—kgãŽã”ãŒâ„¢ã¿w‹ãšâ€â€i’â¹wâ¤â¥hdã’dâ½qã·x•å ë†â²mâ¿ã¾fã¯ãžâ½âºâ´ã©ãˆsâ¥â¤â¤ã˜â¿illã”ë†r㊠also i try print img src png i get broken image browser browing directly image produces internal server error apache log saying exec format error exec png failed premature end script headers png,1 images web pages typically second request server the html page images simply references images like img src theurltotheimage then browser makes second request server gets image data the option serve images html together use data url img tag,i webpage generated python works using print contenttype texthtmlnn print blank line end headers print link hrefdefaultcss relstylesheet typetextcss print htmlhead i want add images webpage i sysstdoutwrite contenttype imagepngnn filepngrbread print contenttype texthtmlnn print blank line end headers print link hrefdefaultcss relstylesheet typetextcss all i get image i place image code htmltext header i get text image ie ãâ·ã¶ããŽâ´ãzâºmâ¾â€°kã—â®å¾ã²ã¥ã‹ã›â¶ãƒgå¾yfk–ã‘ã´ã©ã“uâ½zuiã’ã·ãâ§ampmå¡h’vâ¯â­ã¼ã°â¼â±â±â±zã½ãµã—iã±ã±ã±ãšâºuâ«wâ®â¬wãŸw—kgãŽã”ãŒâ„¢ã¿w‹ãšâ€â€i’â¹wâ¤â¥hdã’dâ½qã·x•å ë†â²mâ¿ã¾fã¯ãžâ½âºâ´ã©ãˆsâ¥â¤â¤ã˜â¿illã”ë†r㊠also i try print img src png i get broken image browser browing directly image produces internal server error apache log saying exec format error exec png failed premature end script headers png,1 you use code directly embed image html datauri open png rb readencode base replace n imgtag img srcdataimagepngbase formatdatauri printimgtag alternatively python datauri open png rb readencode base replace n imgtag img srcdataimagepngbases datauri printimgtag for python replace first line datauri basebencodeopen graphpng rb readdecode utf replace n,i webpage generated python works using print contenttype texthtmlnn print blank line end headers print link hrefdefaultcss relstylesheet typetextcss print htmlhead i want add images webpage i sysstdoutwrite contenttype imagepngnn filepngrbread print contenttype texthtmlnn print blank line end headers print link hrefdefaultcss relstylesheet typetextcss all i get image i place image code htmltext header i get text image ie ãâ·ã¶ããŽâ´ãzâºmâ¾â€°kã—â®å¾ã²ã¥ã‹ã›â¶ãƒgå¾yfk–ã‘ã´ã©ã“uâ½zuiã’ã·ãâ§ampmå¡h’vâ¯â­ã¼ã°â¼â±â±â±zã½ãµã—iã±ã±ã±ãšâºuâ«wâ®â¬wãŸw—kgãŽã”ãŒâ„¢ã¿w‹ãšâ€â€i’â¹wâ¤â¥hdã’dâ½qã·x•å ë†â²mâ¿ã¾fã¯ãžâ½âºâ´ã©ãˆsâ¥â¤â¤ã˜â¿illã”ë†r㊠also i try print img src png i get broken image browser browing directly image produces internal server error apache log saying exec format error exec png failed premature end script headers png,3 you dump image data html you need either file served link embed image encoded base,i webpage generated python works using print contenttype texthtmlnn print blank line end headers print link hrefdefaultcss relstylesheet typetextcss print htmlhead i want add images webpage i sysstdoutwrite contenttype imagepngnn filepngrbread print contenttype texthtmlnn print blank line end headers print link hrefdefaultcss relstylesheet typetextcss all i get image i place image code htmltext header i get text image ie ãâ·ã¶ããŽâ´ãzâºmâ¾â€°kã—â®å¾ã²ã¥ã‹ã›â¶ãƒgå¾yfk–ã‘ã´ã©ã“uâ½zuiã’ã·ãâ§ampmå¡h’vâ¯â­ã¼ã°â¼â±â±â±zã½ãµã—iã±ã±ã±ãšâºuâ«wâ®â¬wãŸw—kgãŽã”ãŒâ„¢ã¿w‹ãšâ€â€i’â¹wâ¤â¥hdã’dâ½qã·x•å ë†â²mâ¿ã¾fã¯ãžâ½âºâ´ã©ãˆsâ¥â¤â¤ã˜â¿illã”ë†r㊠also i try print img src png i get broken image browser browing directly image produces internal server error apache log saying exec format error exec png failed premature end script headers png,1 a simple google search lead links arabic natural language processing using python quranic arabic corpus howto working python unicode arabic are useful,i process assessing capabilities nltk processing arabic text research analyze extract sentiments question follows is ntlk capable handling allows analysis arabic text is python capable manipulatingtokenizing arabic text will i able parse store arabic text using python if python ntlk tools job tools would recommend existent thank edit based research ntlk capable stemming arabic text link python capable handling arabic text since supports utf unicode link parsing lemmatization arabic text done using snlpg the stanford natural language processing group statistical parser link,2 i think want instantiate two separate popen objects one ls sed you want pass first popen object stdout attribute stdin argument nd popen object example p subprocesspopen ls stdoutsubprocesspipe p subprocesspopen sed stdinpstdout stdoutsubprocesspipe print pcommunicate you keep chaining way commands p subprocesspopen prog stdinpstdout see subprocess documentation info work subprocesses,i know run command using cmd subprocesspopen subprocesscommunicate most time i use string tokenized shlexsplit argv argument popen example ls l import subprocess import shlex print subprocesspopenshlexsplitr ls l stdin subprocesspipe stdout subprocesspipe stderr subprocesspipecommunicate however pipes seem work for instance following example returns noting import subprocess import shlex print subprocesspopenshlexsplitr ls l sed sabg stdin subprocesspipe stdout subprocesspipe stderr subprocesspipecommunicate can tell i wrong please thx,3 afaik first variant still gets tuples table one sql query builds orm presentation entity iterating so efficient building list entities iterating still fetch raw data memory thus using limit huge tables sounds like good idea,i m record mysql table i interface using sqlalchemy i found queries large subsets table consume much memory even though i thought i using builtin generator intelligently fetched bitesized chunks dataset thing sessionquerythings analyzething to avoid i find i build iterator bites chunks lastthingid none true things queryfilterthingid lastthingidlimitquerysizeall rows lenrows break thing things lastthingid rowid analyzething is normal something i missing regarding sa builtin generators the answer question seems indicate memory consumption expected,1 shlex splits spaces according shell rules deal pipes it however work way import subprocess import shlex spls subprocesspopenshlexsplitr ls l stdin subprocesspipe stdout subprocesspipe stderr subprocesspipe spsed subprocesspopenshlexsplitr sed sabg stdin splsstdout stdout subprocesspipe stderr subprocesspipe splsstdinclose makes similiar devnull output splscommunicate makes ignore errors print putput according helpsubprocess replacing shell pipe line outputdmesg grep hda p popendmesg stdoutpipe p popengrep hda stdinpstdout stdoutpipe output pcommunicate hth,i know run command using cmd subprocesspopen subprocesscommunicate most time i use string tokenized shlexsplit argv argument popen example ls l import subprocess import shlex print subprocesspopenshlexsplitr ls l stdin subprocesspipe stdout subprocesspipe stderr subprocesspipecommunicate however pipes seem work for instance following example returns noting import subprocess import shlex print subprocesspopenshlexsplitr ls l sed sabg stdin subprocesspipe stdout subprocesspipe stderr subprocesspipecommunicate can tell i wrong please thx,1 in old zopecmf portalskins world portalskinsfoopy object treated like method iow need wrap contents def funcname skin object called traversing contextfoo no importing normal python stuff while trying move away stuff quickly back pythonic sanity loginnext still portalskins script using portalskins script trying appropriate so loginnext script return hello world,i plone instance setup i trying call custom python script function loginnext script how would i say eg customprintpy def disp return hello world how would i call disp inside loginnext script,1 use dir for example x dir builtins doc name package x,i work python shell weeks ago i defined variable refers important list the shell stays always open i forgotten name how get list global names i ever defined,3 you examine globals shows modulelevel variables locals local scope in prompt also vars shows names available matter,i work python shell weeks ago i defined variable refers important list the shell stays always open i forgotten name how get list global names i ever defined,1 all globals userdefined ones globals builtins module builtin builtin name main doc none package none x globals builtins module builtin builtin name main x doc none package none to get things defined appears filter list keyvalue pairs whose keys match regex update here better answer python python r jun gcc apple inc build darwin type help copyright credits license information x import name name dir rematchr name x here i excluded special names beginning ending two underscores used show the end regex prevent accepting abc also i switched dir gets symbols current scope necessarily global one seems cleaner it add leading list comprehension variable like globals,i work python shell weeks ago i defined variable refers important list the shell stays always open i forgotten name how get list global names i ever defined,2 don readline enabled you look interpreter history find want i think easier digging globals dir,i work python shell weeks ago i defined variable refers important list the shell stays always open i forgotten name how get list global names i ever defined,1 you could implement form directive python for instructions see httpdocutilssourceforgenetdocshowtorstdirectiveshtml,i form like times raw html form actiontxmtopenurlfileuserssmchosmchoworksprgtasknigtestboostoptionsreadmetxt button typesubmiteditbutton form is macro equivalent restructuredtext i get result example form userssmchosmchoworksprgtasknigtestboostoptionsreadmetxt,3 name name dir namestartswith f nameisdigit example f name name dir namestartswith f nameisdigit f,i work python shell in order produce list global names i use dir generates long list i would like filter i interested names begin f end digits sometimes i also need userdefined names names is greplike method python shell filter output,1 n n dir rematchf n i set pythonstartup environment variable point startuppy contains ned startuppy file loaded interactive python prompts printstartuppy import datetime os pprint sys time printimported datetime os pprint sys time def dirxthing regex return n n dirthing researchregex n pp pprintpprint now i always handy modules imported i shortcuts available things i often shell,i work python shell in order produce list global names i use dir generates long list i would like filter i interested names begin f end digits sometimes i also need userdefined names names is greplike method python shell filter output,1 maybe use module httpcodeactivestatecomrecipescronliketriggers i used module making userspace cron python works well this module handle crontablike lines,i need parse crontablike schedule definition python eg get last run is good preferably small library parses strings translates dates,1 you also specify model name string preferredgenre modelsforeignkeygenre,i building large django application would like split data models classperfile structure attempting i running circular dependency issues complex models for example i three models separate files class bookmodelsmodel title modelscharfieldmaxlength author modelsforeignkeyauthor genre modelsforeignkeygenre class genremodelsmodel name modelscharfieldmaxlength samplebook modelsforeignkeybook class authormodelsmodel name modelscharfieldmaxlength preferredgenre modelsforeignkeygenre since book depends genre genre depends book i import book anywhere would start chain circular model dependencies since file imports model files how i avoid this kind project grow large quickly i want lump models one file,1 most dbapi implementations fully buffer rows fetched usually sqlalchemy orm even gets hold one result whole result set memory but way query works fully loads given result set default returning objects the rationale regards queries simple select statements joins tables may return object identity multiple times one result set common eager loading full set rows needs memory correct results returned otherwise collections might partially populated so query offers option change behavior yieldper call httpwwwsqlalchemyorgdocsormqueryhtmlhighlightyieldpersqlalchemyormqueryqueryyieldper this call cause query yield rows batches give batch size as docs state appropriate kind eager loading collections basically really know and also underlying dbapi prebuffers rows still memory overhead approach scales slightly better using i hardly ever use yieldper instead i use better version limit approach suggest using window functions limit offset huge problem large offset values cause query get slower slower offset n causes page n rows like query fifty times instead one time reading larger larger number rows with windowfunction approach i prefetch set window values refer chunks table i want select i emit individual select statements pull one windows time the window function approach wiki httpwwwsqlalchemyorgtracwikiusagerecipeswindowedrangequery i use great success also note databases support window functions need pg oracle sql server imho using least postgresql definitely worth using relational database might well use best,i m record mysql table i interface using sqlalchemy i found queries large subsets table consume much memory even though i thought i using builtin generator intelligently fetched bitesized chunks dataset thing sessionquerythings analyzething to avoid i find i build iterator bites chunks lastthingid none true things queryfilterthingid lastthingidlimitquerysizeall rows lenrows break thing things lastthingid rowid analyzething is normal something i missing regarding sa builtin generators the answer question seems indicate memory consumption expected,3 import item item dir rematchr fd item item item dir researchr fd item,i work python shell in order produce list global names i use dir generates long list i would like filter i interested names begin f end digits sometimes i also need userdefined names names is greplike method python shell filter output,1 change quickly the static handlers take paths absolute filesystem by setting toolsstaticdirroot saying serve file hard drive whew now panic let analyze detail first staticdir staticfile different tools interact really risk config showing us like toolsstaticdiron true if want stick staticfile need provide toolsstaticfileroot toolsstaticdirroot if rather expose whole directories replace staticfile staticdir throughout second let fix root setting it path application folder folder contains abpy etc third staticdir staticfile tools determine disk path simple ospathjoinroot dir root filename supplying root dir filename start slash import os ospathjoin pathtoapplication cssabcss cssabcss ospathjoin pathtoapplication cssabcss pathtoapplicationcssabcss given try config toolsstaticfileroot pathtoapplication cssabcss toolsstaticfileon true toolsstaticfilefilename cssabcss,i devil time getting cherrypy serve necessary css file page returned my directory structure application abpy cherrypy application abconfig cherrypy config file html html template folder abhtml html template file css css folder abcss css file the link statement abhtml link hrefcssabcss relstylesheet typetextcss and finally abconfig toolsstaticdirroot cssabcss toolsstaticfileon true toolsstaticfilefilename cssabcss my template loaded rendered browser i expected styling applied if i change template use relative address cssabcss open template file browser styling applied it took get configuration file point cherrypy complain bad paths starting application at point starts renders returns fine simply appear serve css file browser any help greatly appreciated update based kind suggestions fumanchu preferring use staticdir understanding root refers filesystem absolute path i config file toolsstaticdirroot cusersmyaccountdocumentsclientnameapplication css toolsstaticdiron true toolsstaticdirdir css in html i style sheet link link hrefcssabcss relstylesheet typetextcss and i starting cherrypy cherrypyquickstartabroot abconfig in configuration i still get styling web page when i check page source click cssabcss link directly i get notfound the path cssabcss found note i developing windows machine,3 i run problem i development gunicorn remove adminmedia magic serve admin media like media urlspy import os import django adminmediaurl settingsadminmediaprefixlstrip ppath adminmediapath ospathjoindjangopath contrib admin media urlpatterns patterns urlr admin includeadminsiteurls urlr adminmediaurl djangoviewsstaticserve documentroot adminmediapath name adminmedia also httpdjangosnippetsorgsnippets and course include productiondisclaimerh,i mostly entirely plain django project adding media customization admin interface way running server python managepy runserver results nicelyformatted admin interface running server gunicorndjango why case i fix it definitely issue finding css files stored i never configured mediaroot setting edit i want know djangoadmin serves nonexistent admin files i get gunicorndjango,1 depending whether using python could use built optparse argparse respectively httpdocspythonorglibraryargparsehtml they may slightly heavyweight conversion intsfloats whatever type need part parsing automatically build usage message nice argument parsing things,i writing simple python application using cmd module provide clitype interface the commands provided cli parameter lists vary widely each command handler receives string argument containing portion line contains arguments i plan tokenize tuple using shlexsplit subsequently i looking pythonic way take tuple strings validate wellformed convert tuple cleanlyspecified numeric types example i function foo takes arguments first path file disk second floatingpoint value third integer like foo homejasonfilebin i like clean way specifying something akin using c sscanf format string f i understand whitespacehandling issues inherent approach illustration i know i accomplish writing boilerplate code handler function calls int float etc catches exceptions appropriately it seems cleaner way,1 i would suggest providing production rules functions parse arguments raise exception invalid arguments example might look like foosyntax file float int def foocmdinfile infloat inint pass def parseargsrule args lenrule lenargs raise valueerror wrong number arguments return ruleitemarg ruleitem arg ziprule args commands foo foosyntax foocmd def dispatchline cmd rest linesplitnone args restsplit syntax cmdfunc commandscmd cmdfuncparseargssyntax args,i writing simple python application using cmd module provide clitype interface the commands provided cli parameter lists vary widely each command handler receives string argument containing portion line contains arguments i plan tokenize tuple using shlexsplit subsequently i looking pythonic way take tuple strings validate wellformed convert tuple cleanlyspecified numeric types example i function foo takes arguments first path file disk second floatingpoint value third integer like foo homejasonfilebin i like clean way specifying something akin using c sscanf format string f i understand whitespacehandling issues inherent approach illustration i know i accomplish writing boilerplate code handler function calls int float etc catches exceptions appropriately it seems cleaner way,1 what adding extra function main class a class a def runifmainselfname name main selfrun in subclass one line less class ba brunifmainname,i generic class a subclassed lot like class a def runself selfdosomething abstract function def dosomethingself pass class ba def dosomethingself the subclasses separate files i running directly adding code file b name subclass file name main brun my question i avoid add code files subclasses since thing changes code class used b example,1 instead assigning mylist mylist need make copy this done using list constructor mylist listmylist or copycopy copydeepcopy import copy mylist copycopymylist the copy module used copy objects eg dict make deep copies see wiki page difference shallow deep copy finally slice syntax mylist mylist but i personally avoid using rather cryptic syntax reasons listed,i problem python lists the simplified version mylist items list mylist mylist mylistpopi mylistinsertiitem printmylist printmylist problem i want mylist remain original version mylist is workaround problem,3 you need make shallow copy mylist mylist mylist see blog post details however list contains lists objects wish recursively copy need deep copy instead copy import deepcopy mylist deepcopymylist footnote i see all answers mention standard mylist idiom see rd paragraph introduction list got downvoted for worth using slice notation copying seems fastest method version python anyway ymmv mehome python v python mehome python timeit l range l l loops best msec per loop mehome python timeit l range l listl loops best msec per loop mehome python timeit copy import copy l range l copyl loops best msec per loop that said i agree listmylist beginner friendly mylist however valid used wild i see beginners insulated one,i problem python lists the simplified version mylist items list mylist mylist mylistpopi mylistinsertiitem printmylist printmylist problem i want mylist remain original version mylist is workaround problem,1 use mylist mylist instead mylist mylist this standard idiom making copy list,i problem python lists the simplified version mylist items list mylist mylist mylistpopi mylistinsertiitem printmylist printmylist problem i want mylist remain original version mylist is workaround problem,1 according fabric faq longer effectively instead use tmux screen dtach even better use python daemon package import daemon spam import domainprogram daemondaemoncontext domainprogram,in remote server i script testsh like binbash echo i nohup sleep amp from local i run fab runtest call remote testsh def runtest run xxxxtestsh i get output i i not find sleep process remote sever what i miss thanks,2 use mylist mylist copy library complex cases need shallow copycopyx deep copies copydeepcopyx object note simple copy work list lists x import copy copycopyx x oo x oo oo edit mark lutz learning python ed p there variety ways copy list including using builtin list function standard library copy module perhaps common way slice start finish,i problem python lists the simplified version mylist items list mylist mylist mylistpopi mylistinsertiitem printmylist printmylist problem i want mylist remain original version mylist is workaround problem,1 it probably due fact windows new lines rn instead n also escape instead use,hello i following script import os import stat curdir osgetcwd autorunsignature autorun openregsvrexe shellexecuteregsvrexe shellopencommandregsvrexe shellopen content def readsignaturefilepath try openfilepath data range contentappenddatareadline except ioerror err printfile error strerr readsignatureosgetcwd autoruninf ifcontentautorunsignature printequal content else printnot equal it prints equal i tried method import os import stat curdir osgetcwd autorunsignature autorunnopenregsvrexenshellexecuteregsvrexenshellopencommandregsvrexenshellopen content def readsignaturefilepath try openfilepath data content dataread except ioerror err printfile error strerr readsignatureosgetcwd autoruninf ifcontentautorunsignature printequal content else printnot equal it also print equal i want store content autoruninf file script every time find file i want check content i could anyone help content autoruninf autorun openregsvrexe shellexecuteregsvrexe shellopencommandregsvrexe shellopen,1 linebreaks windows rn different linux n so try replacing n rn,hello i following script import os import stat curdir osgetcwd autorunsignature autorun openregsvrexe shellexecuteregsvrexe shellopencommandregsvrexe shellopen content def readsignaturefilepath try openfilepath data range contentappenddatareadline except ioerror err printfile error strerr readsignatureosgetcwd autoruninf ifcontentautorunsignature printequal content else printnot equal it prints equal i tried method import os import stat curdir osgetcwd autorunsignature autorunnopenregsvrexenshellexecuteregsvrexenshellopencommandregsvrexenshellopen content def readsignaturefilepath try openfilepath data content dataread except ioerror err printfile error strerr readsignatureosgetcwd autoruninf ifcontentautorunsignature printequal content else printnot equal it also print equal i want store content autoruninf file script every time find file i want check content i could anyone help content autoruninf autorun openregsvrexe shellexecuteregsvrexe shellopencommandregsvrexe shellopen,1 edit it sounds like want write parser fsm among things tokenizes comma characters escaped the following regex works identifier possibly containing escaped commas you could use antlrlex input r aaaaabbbbcccccdddddd pat recompiler w mat refinditerpat input stuff matgroup original answer that could good solution giving us enough context tell does character occur multiply if occurs could check whether index stringfindchar lies inside spans regex matches is character arbitrary character give us specific example why percharacter basis presumably sequentially checking multiple chars is desired result boolean yes char found inside span regex match case char found outside regex match,i regex pattern i used large piece text single string several discontiguous regions original text matches regexp now i attempting build state machine iterate text different things based char position whether position within span regex match with refinditertext i find substrings extract spans thus i list tuples work eg etc with information given index character string i write algorithm see character part regex string for example given character go list spans determine part matched substring is better way thanks advance jw,1 edit here regex grab text ignoring escaped original answer here pseudo python code looking pattern recompile pos match patternsearchhaystack pos rangepos matchstart these chars outside match group the chars match pos matchend finish rest chars matched rangepos lenhaystack these chars outside match,i regex pattern i used large piece text single string several discontiguous regions original text matches regexp now i attempting build state machine iterate text different things based char position whether position within span regex match with refinditertext i find substrings extract spans thus i list tuples work eg etc with information given index character string i write algorithm see character part regex string for example given character go list spans determine part matched substring is better way thanks advance jw,1 from wikipedia sigpipe signal sent process attempts write pipe without process connected end when first create p using stdoutpipe one process connected pipe python process read output using pstdout when create p using stdinpstdout two processes connected pipe pstdout generally running processes pipeline want processes end processes end for happen automatically need close pstdout pstdin process attached pipe way p ends p writes additional data stdout receive sigpipe since longer processes attached pipe,here i read python subprocess module documentation replacing shell pipeline outputdmesg grep hda p popendmesg stdoutpipe p popengrep hda stdinpstdout stdoutpipe pstdoutclose allow p receive sigpipe p exits output pcommunicate the pstdoutclose call starting p important order p receive sigpipe p exits p i really understand close pstdout created p when exactly executed pstdoutclose what happens p never ends what happens p p end,3 i going assume first meant indent lines starting path second i guessing intent route url webplayerunityd however regexes match since everything slash optional mainhandler receive request since first third looks like trying serve static files dynamic handler also templating engine why if trying serve static files verbatim use static handlers assuming placed unityd files directory named static render webplayerunityd url staticfiles staticwebplayerunityd upload staticwebplayerunityd match unityd files url unityd staticfiles static upload staticunityd match html anything else url script mainpy,i problem hosting unityd web application gae when application loads web player starts request unityd file use following python script make http response class unityhandlerwebapprequesthandler def get self q q none q webplayerunityd path ospathjoin ospathdirname file q selfresponseheaders contenttype texthtml selfresponseoutwrite templaterender path def main application webappwsgiapplication html mainhandler unityd unityhandler debugtrue utilrunwsgiapp application it work quite well finds file unity web player give bad file length error so anyone tell problem i think something setting contenttype know fix thanks samer samy,2 i presume constant string literal if easy double percent signs want keep testtestmonetizationsourcedampchannelidd mid cid,i trying interpolate string correctly testtestmonetizationsourcedampchannelidd mid cid i want rendered serve placeholderes variables mid cid how i,1 in general want urlliburlencode import urllib url testtest urlliburlencode monetization source mid channel id cid,i trying interpolate string correctly testtestmonetizationsourcedampchannelidd mid cid i want rendered serve placeholderes variables mid cid how i,3 ok i see pstdout closed python script remains open p p p communicate together except p already closed p receives sigpipe am i correct,here i read python subprocess module documentation replacing shell pipeline outputdmesg grep hda p popendmesg stdoutpipe p popengrep hda stdinpstdout stdoutpipe pstdoutclose allow p receive sigpipe p exits output pcommunicate the pstdoutclose call starting p important order p receive sigpipe p exits p i really understand close pstdout created p when exactly executed pstdoutclose what happens p never ends what happens p p end,1 actually pay close attention search variable set list contain empty unicode string u evaluated true search u boolsearch true and seeing different behavior test production sadly sure maybe doc help,i lines code view get query param filter based parameter search requestgetget search none search accounts userprofileobjectsfilterfullnameicontainssearchorderby fullname else accounts userprofileobjectsallorderby fullname for odd reason local machine appears i give url something like localhostaccountsadmin localhostaccountsadminsearch works fine production server however seems think search empty string passes ifthen conditional returns empty queryset getquerydict u search u why python seem think empty string something x x print exists else print none none x u x print exists else print none none,1 use stringio turn read string filelike object stringio import stringio import urllib imageopenstringiourlliburlopenurlread,what i trying fairly simple dealing local file problem comes i try remote url basically i trying create pil image object file pulled url sure i could always fetch url store temp file open image object feels inefficient here i imageopenurlopenurl it flakes complaining seek available i tried imageopenurlopenurlread but work either is better way writing temporary file accepted way sort thing,3 could try using stringio import urllib cstringio file cstringiostringiourlliburlopenurlread img imageopenfile,what i trying fairly simple dealing local file problem comes i try remote url basically i trying create pil image object file pulled url sure i could always fetch url store temp file open image object feels inefficient here i imageopenurlopenurl it flakes complaining seek available i tried imageopenurlopenurlread but work either is better way writing temporary file accepted way sort thing,3 you half running time replacing inner loop rangensamples j rangei dijquadraticchidistxixj djidij even quadraticchidist symmetric matter symmetrize matrix forget divide d d dt for speedup i would recommend optimize speed quadraticchidist further i recommend httpcythonorg especially httpdocscythonorgsrctutorialnumpyhtml this gives speed c many cases,i would like compute kernel matrix python fastest way possible input matrix x nsamples nfeatues output symmetric matrix d nsamples nsapmles method i using right even though based iterators seems really slow loop anybody think something better thanks method far itertools import combinations def computekernelxdlambda nsamplesxshape dnumpyzerosnsamplesnsamples el combinationsrangensamples ijel delquadraticchidistxixj dddt dnumpyexpdlambdad dnumpyeyedd return d quadraticchidist function evaluated every possible pair rows x,1 use scalexscaley kw arg plotx sinx scaleyfalse,i use matplotib axes api plot figures one lines i plot represents theoretical expected line it meaning outside original x limits what i want matlplotlib ignore autoscaling limits what i used check current limits plot reset limits the problem i plot third plot limits get recalculated together theoretical line really expands graph boilerplate matplotlibfigure import figure matplotlibbackendsbackendpdf import figurecanvaspdf numpy import sin linspace fig figure ax figaddsubplot x linspace axplotx sinx axplotx sinx i wish matplotlib would consider second plot rescaling axplotx sinx but would consider first last canvaspdf figurecanvaspdffig canvaspdfprintfiguretestpdf,3 the simplest solution could add unused get parameter avoid caching request ie while true try resultbropen httpwwwexamplecomsampletxtrd iread break except timesleep the extra parameter ignored web application a http head probably correct way see question example,i writing app connect web server i owner server sends information provided user process information send result back application the time needed process results depends user request seconds minutes i use infinite loop check file exist may intelligent approach may i could estimated maximum time request could take avoid using infinite loop important part code looks like import time import mechanize br mechanizebrowser brsethandlerefreshfalse proxyvalues http proxy brsetproxiesproxyvalues while true try resultbropen httpwwwexamplecomsampletxt read break except pass timesleep behind proxy loop never ends change code something like timesleep resultbropen httpwwwexamplecomsampletxt read ie i wait enough time ensure file created trying read i indeed get file it seems like mechanize ask file exits everytime mechanize ask i get file i replicated behavior using firefox i ask nonexisting file i create file remember i owner server i get file and using mechanize firefox i get deleted files i think problem related proxy cache i think i canâ´t delete cache may way tell proxy i need recheck file exists any suggestion fix problem,1 the easiest way set web service script pings run the web service return version number script check version number if version number higher update rerun,tldr i need module automatically update script background silently i python script i distribute users i frequently update ask update via pip obviously high priority users want use app think updating i like update app automatically like google chrome silently background automatically is library allows already if straightforward way use pipdistribute module,1 httpsbitbucketorgkentpythontutorsamplessrcfaebabinpackingpy partition list sublists whose sums exceed maximum using first fit decreasing algorithm see httpwwwamsorgnewinmathcoverbinshtml simple description method class binobject container items keeps running sum def initself selfitems selfsum def appendself item selfitemsappenditem selfsum item def strself printable representation return binsumd itemss selfsum strselfitems def packvalues maxvalue values sortedvalues reversetrue bins item values try fit item bin bin bins binsum item maxvalue print adding item bin binappenditem break else item fit bin start new bin print making new bin item bin bin binappenditem binsappendbin return bins name main import random def packandshowalist maxvalue pack list bins show result print list sum sumalist requires least sumalistmaxvaluemaxvalue bins bins packalist maxvalue print solution using lenbins bins bin bins print bin print alist packandshowalist alist randomrandint range packandshowalist,for application i working i need something like packing algorithm implemented python see details the basic idea i n objects varying sizes i need fit n bins number bins limited size objects bins fixed the objects bins either interested seeing i think objects probably i need i know variety algorithms address problem asbest fit decreasing first fit decreasing i hoping might implementation python phpcjava really i picky any ideas,3 i experimented bitrock opensource application i developing they provide crossplatform installers application automatic updates licensing free application opensource commercial products require purchasing license it might overkill application small i thought i still give one option,tldr i need module automatically update script background silently i python script i distribute users i frequently update ask update via pip obviously high priority users want use app think updating i like update app automatically like google chrome silently background automatically is library allows already if straightforward way use pipdistribute module,1 you use wincom accessing photoshop python possible pseudo code work load psd file collect layers make layers visibleoff turn one layer another mark visibleon export png import wincomclient papp wincomclientdispatch photoshopapplication def makealllayerinvisiblelyrs ly lyrs lyvisible false def makeeachlayervisibleandexporttopnglyrs ly lyrs lyvisible true options wincomclientdispatch photoshoppngsaveoptions optionsinterlaced false tf png file name path docsaveassaveintfoptionsoptions lyvisible false pappopenpsd file doc pappactivedocument makealllayerinvisibledoclayers makeeachlayervisibleandexporttopngdoclayers,i need write python program loading psd photoshop image multiple layers spit png files one layer can python i tried pil seem method accessing layers help ps writing psd loader png writer shown way slow,1 yet another method based file behavior textchars bytearray setrangex x xf isbinarystring lambda bytes boolbytestranslatenone textchars example isbinarystringopen usrbinpython rb read true isbinarystringopen usrbindhpython rb read false,how i tell file binary nontext python i searching large set files python keep getting matches binary files this makes output look incredibly messy i know i could use grep i i data grep allows in past i would searched characters greater xf utf like make impossible modern systems ideally solution would fast solution,3 i going answer question i realized answer repeat user answer but posted resolution answer i anyway below i would posted figured expand fill seem causing bit fight space various objects box i assuming objects i used habit problem in pygtk documentation expand defined true child given extra space allocated box the extra space divided evenly children box use option fill true space given child expand option actually allocated child rather padding this parameter effect expand set false a child always allocated full height gtkhbox full width gtkvbox this option affects dimension so essentially box giving everything spaceyou give one gives objects take get bigger the window expand compensate to fix set one options false setting expand false also shut fill setting fill false cause box give extra space fillfalse objects padding instead,i treeview left side hpaned i try move bar left make treeview smaller automatic size instead resizing treeview expands entire program window right any ideas fix the relevant portions source following for hpaned selfvpan gtkvpaned selfhpan gtkhpaned selfvpanshow selfhpanshow selfvboxpackendselfhpan true true selfhpanpackselfvpantrue true and tree view selfftree gtktreestorestrstrstr selftreefillnone ospathabspathospathdirnamefile selftree gtktreeviewselfftree selftvcolumn gtktreeviewcolumn project selftreeappendcolumnselftvcolumn selfcellpb gtkcellrendererpixbuf selfcelltxt gtkcellrenderertext selftvcolumnpackstartselfcellpbfalse selftvcolumnpackstartselfcelltxttrue selftvcolumnsetattributesselfcellpb stockid selftvcolumnsetattributesselfcelltxt text selftvcolumnsetresizabletrue selfhpanpackselftreetruetrue selftreeshow,1 you also need initpy b directories for example work first add base directory path import sys syspathappend import inittestaaaa,i trying learn initpy file works packaging calling modules different directories i directory structure like inittest initpy aaapy b bbbpy aaapy function called test bbbpy looks like import inittestaaaa name main inittestaaaatest gives importerror no module named aaaa what i wrong i tried basic thing module package structure opposed inside package work either my initpy,3 you add empty initpy then recognized sub package inittest imported see httpdocspythonorgtutorialmoduleshtmlpackages then change import inittestaaaa import aaaa work this achim says relative import see httpdocspythonorgwhatsnewhtmlpep if really want run bbbpy put inittest python path eg import sys import os dirname ospathdirnamefile syspathinsert ospathjoindirname import sys syspathinsert import inittestaaaa name main inittestaaaatest and start python inittestbbbby inside b python bbbpy,i trying learn initpy file works packaging calling modules different directories i directory structure like inittest initpy aaapy b bbbpy aaapy function called test bbbpy looks like import inittestaaaa name main inittestaaaatest gives importerror no module named aaaa what i wrong i tried basic thing module package structure opposed inside package work either my initpy,1 try print soupstriso,i code read html modify text using beatiful soup it works fine i read output part html file changed automatically original meta httpequivcontenttype contenttexthtml charsetiso modified meta httpequivcontenttype contenttexthtml charsetutf i want file contents change automatically can someone help here code import import sys beautifulsoup import beautifulsoup f opensysargvrw data fread soup beautifulsoupdata comma recompile soupfindalltextcomma treplacewithtreplace ampsbquo print soup,1 as delnan said maintainer lighthouse api really create setuppy script anyway two ways achieve want require understand python modules when import module python like import lighthouse interpretor searches file named lighthousepy directory input script run cannot find searches directories specified environment variable pythonpath if know environment variable i suggest reading httpenwikipediaorgwikienvironmentvariable if find directories specified pythonpath envi var defaults syspath var installation dependent what maintainer lighthouse i think symlinking files whatever directory downloaded installation default directory you quickly figure directory running python interpretor looking syspath var syspath usrlocallibpythondistpackagespastepyegg usrlocallibpythondistpackagestornadopyegg usrlocallibpythondistpackagespymongopylinuxxegg usrlocallibpythondistpackagesmongoenginepyegg usrlocallibpythondistpackagesdjangodebugtoolbarpyegg usrlibpython usrlibpythonplatlinux usrlibpythonlibtk usrlibpythonlibold usrlibpythonlibdynload usrlocallibpythondistpackages usrlocallibpythondistpackagespil usrlibpythondistpackages usrlibpythondistpackagespil usrlibpythondistpackagesgst usrlibpymodulespython usrlibpythondistpackagesgtk usrlibpymodulespythongtk you see usrlocallibpthondistpackages folder modules i believe maintainer symlinking files this is not a good idea you modify directly the better approach simply download files place directory script place directory add directory pythonpath environment var,i like use httpsgithubcomerikvoldgithubtolighthouseissuemigratorblobmastermigratorpy comments starting line says pip install lighthousepythonapi probably manually but i try i get following error pip install lighthousepythonapi downloadingunpacking lighthousepythonapi could find downloads satisfy requirement lighthousepythonapi no distributions found lighthousepythonapi storing complete log userserikvoldpippiplog i guess i need install package manually someone plz explain link docs explain,2 the problem renderunicode cannot convert python unicode object utf string object exists assumes ascii holds non ascii data start beginning decode incoming strings unicode internally you string input needs fixing i suggest try naming variables boundary sort hungarian notation perhaps rawstrmyvar umyvar,i trying read db table contents display web page using mako bottle the table unicode utf fields unicodedecodeerror ascii motorola milestonexexxa plus ordinal range with following stack trace traceback recent call last file workspacewebcontrollerbottlepy line handle return handlerargs file webserverwebserverpy line download return htmltmpltmpl kwds file webserverwebserverpy line htmltmpl return tmplrenderkwds file usrlibpythonsitepackagesmakopyeggmakotemplatepy line render return runtimerenderself selfcallable args data file usrlibpythonsitepackagesmakopyeggmakoruntimepy line render rendercontexttemplate callable context args kwargsforcallablecallable data file usrlibpythonsitepackagesmakopyeggmakoruntimepy line rendercontext exectemplateinherit lclcontext argsargs kwargskwargs file usrlibpythonsitepackagesmakopyeggmakoruntimepy line exectemplate callablecontext args kwargs file downloadandroidindexhtml line renderbody file downloadandroidindexhtml line filldevices file downloadandroidindexhtml line renderfilldevices unicodedecodeerror ascii codec decode byte xe position ordinal range the calling function def htmltmpltmpl kwds kwds nav templateslookupgettemplate navhtml render kwds navbottom templateslookupgettemplate navbottomhtml render basepath requestpathreplacedereplacefr kwds languages templateslookupgettemplate languageshtml renderenurlbasepathfrurlfrbasepath kwds analytics return tmplrenderkwds how i go aboutthis i tried return tmplrenderunicodekwds return tmplrenderunicodekwdsencode utf replace luck answer help much any ideas,1 args must tuple cmd cmd want oneelement tuple instead thread threadtargetthreadedcommand argscmd,i executing command thread almost k times like threaded true thread threadtargetthreadedcommand argscmd threadstart threadjoin def threadedcommandcommand command none print execute threaded command sysexit print executing command ossystemcommand command like cp file dir i see traceback recent call last file usrlibpythonthreadingpy line bootstrapinner selfrun file usrlibpythonthreadingpy line run selftargetselfargs selfkwargs typeerror threadedcommand takes exactly argument given cexception thread thread traceback recent call last file usrlibpythonthreadingpy line bootstrapinner selfrun file usrlibpythonthreadingpy line run selftargetselfargs selfkwargs typeerror threadedcommand takes exactly argument given,3 combos stri strn x n generator combinations dictic ic enumeratecombos only python newer combinations dictenumeratecombos only python newer combinations ic ic enumeratecombos,i found useful bit code among series tubes internet x combosin x n combos what i trying something like following combinationsi nd range n x combinations etc but obviously working can done if,3 you probably want at least great reason need i see able track positions want result list already if need know indexes something like idx combo enumeratecombinations print idx combo if actually need accessible position list index something like lookup dictidx combo idx combo enumeratecombinations,i found useful bit code among series tubes internet x combosin x n combos what i trying something like following combinationsi nd range n x combinations etc but obviously working can done if,1 assuming website provide search api need automated scraping case curl etc way lowlevel errorprone here widelyused recommendations for automation linkfollowing formfilling etc i strongly recommend twill api automation layer sits top mechanize twill bunch useful extension modules as one example filling authentication forms twillformfill multisub great for manual scraping beautifulsoup twill probably already need scrapes links forms etc,i attempting write script log specific website use website search function the script write list search results standard output i select one results various actions page i lost start i already attempted curl python various web libraries i able come anything works,2 iziplongestnext code iziplongest sentinel used instead cpython keeps track many iterators still active counter stops number active reaches zero if error occurs ends iteration iterators still active allows error propagate the code item pyiternextit item null lznumactive lznumactive pyerroccurred lznumactive pydecrefresult return null else pyincreflzfillvalue item lzfillvalue pytuplesetitemlzittuple null pydecrefit the simplest solution i see def iziplongestmodifiedargs kwds iziplongest abcd xy fillvalue ax by c d fillvalue kwdsget fillvalue class longestexhaustedexception pass def sentinelcounter fillvaluelenargspop try yield counter yields fillvalue raises indexerror except raise longestexhausted fillers repeatfillvalue iters chainit sentinel fillers args try tup izipiters yield tup except longestexhausted pass,in question lazyr asks following code iziplongest iterator works def iziplongestfromdocsargs kwds iziplongest abcd xy fillvalue ax by c d fillvalue kwdsget fillvalue def sentinelcounter fillvaluelenargspop yield counter yields fillvalue raises indexerror fillers repeatfillvalue iters chainit sentinel fillers args try tup izipiters yield tup except indexerror pass when i trying understand works i stumbled question what indexerror raised inside one iterators sent iziplongest parameters then i wrote testing code itertools import iziplongest repeat chain izip def iziplongestfromdocsargs kwds the code exactly shown def gen range yield def gen range raise indexerror simulation indexerror raised inside iterator yield iziplongestfromdocsgengen fillvalue print formatlocals print n iziplongestgengen fillvalue print formatlocals and turned function itertools module iziplongestfromdocs work differently the output code traceback recent call last file c line module iziplongestgengen fillvalue file c testindexerrorinside iteratorpy line gen raise indexerror indexerror so clearly seen code iziplonges itertools propagate indexerror exception i think iziplongesfromdocs swallowed indexerror exception took signal sentinel stop iterating my question worked around indexerror propagation code itertools module,2 you want mysqldb but favour look one excellent python wrappersorms sqlalchemy sqlobject django,i database set mysql workbench i want connect query database python script i idea go,1 are thinking boost python,there library python enables calling ability call functions c format without extern c please could remind name library i forgot name find it boostpython thank much your answer rewarded,1 element missing trailing comma you simplify line debug errors start removing half string curly braces if problem persists continue halving remainder find tiny piece caused error correct,i keep getting error referencing one dictionaries code but i seem find anything would causing problem something probably slipping past eyes error command line pdb anyways to explain going rather large dictionary telling giving program syntax error invalid syntax the arrow make much sense telling keynote result pdb distinctivefeatures beak blooddrenched boiling steaming b ody constantly shedding distinctive markings elongated neck hood expanded bone structure albino eye stalks glowing eyes h air horns lizardlike fin fishlike fin icy cold body illusionary features metallike features multiple arms multiple heads antlers multiple legs multiple eyes stinger odor on fire oozing sores plant features prehensile tongue pulsating skin faces rocklike features rubber boned rubbery body scales serpent appendages shade form shambling gait shell shimmering body skeletal appearance slimy speech suction cups limbs tail tentacles transparent unusual c olor weapons hands wet drenched body wings mechanical features multiple features special,1 not familiar enough django judge whether right way simple gotcha return iterselfformssort sort method list sorts inplace returns none you probably meant return itersortedselfforms,i writing custom modelformset i need forms sorted value field ordering i overloaded iter method baseformset child formset class my class inherited baseformset class sortedcatformsbaseformset def iterself return iterselfformssort keylambda form form ordering value line problem line def getitemself index return listselfindex i use modelformset ordercatsformset modelformsetfactoryparentcategory fields category ordering formsetsortedcatforms extra the problem caught typeerror rendering nonetype object iterable exception location formspy iter line but source baseformset def iterself yields forms order rendered return iterselfforms what wrong code how right way edit full traceback edit after bobince advice code became class sortedcatformsbaseformset def iterself return iter sortedselfforms keylambda form form ordering value def getitemself index return listselfindex it returns empty list without forms are problem getitem,3 missing comma in future help trace kind error helpful put everything one giant line split across several lines that way arrow helpful,i keep getting error referencing one dictionaries code but i seem find anything would causing problem something probably slipping past eyes error command line pdb anyways to explain going rather large dictionary telling giving program syntax error invalid syntax the arrow make much sense telling keynote result pdb distinctivefeatures beak blooddrenched boiling steaming b ody constantly shedding distinctive markings elongated neck hood expanded bone structure albino eye stalks glowing eyes h air horns lizardlike fin fishlike fin icy cold body illusionary features metallike features multiple arms multiple heads antlers multiple legs multiple eyes stinger odor on fire oozing sores plant features prehensile tongue pulsating skin faces rocklike features rubber boned rubbery body scales serpent appendages shade form shambling gait shell shimmering body skeletal appearance slimy speech suction cups limbs tail tentacles transparent unusual c olor weapons hands wet drenched body wings mechanical features multiple features special,3 you missing comma by way put dictionary brackets you make dictionary first element tuple plain dictionary using editor shows syntax coloring like eg idle scite helps lot because keys integers perhaps easier option would make list distinctivefeatures beak blooddrenched boiling steaming body constantly shedding distinctive markings elongated neck hood expanded bone structure albino eye stalks glowing eyes hair horns lizardlike fin fishlike fin icy cold body illusionary features metallike features multiple arms multipleheads antlers multiple legs multiple eyes stinger odor on fire oozing sores plant features prehensile tongue pulsating skin faces rocklike features rubber boned rubberybody scales serpent appendages shade form shambling gait shell shimmering body skeletal appearance slimy speech suction cups limbs tail tentacles transparent unusual color weapons hands wet drenched body wings mechanicalfeatures multiple features special get element distinctivefeatures gives beak,i keep getting error referencing one dictionaries code but i seem find anything would causing problem something probably slipping past eyes error command line pdb anyways to explain going rather large dictionary telling giving program syntax error invalid syntax the arrow make much sense telling keynote result pdb distinctivefeatures beak blooddrenched boiling steaming b ody constantly shedding distinctive markings elongated neck hood expanded bone structure albino eye stalks glowing eyes h air horns lizardlike fin fishlike fin icy cold body illusionary features metallike features multiple arms multiple heads antlers multiple legs multiple eyes stinger odor on fire oozing sores plant features prehensile tongue pulsating skin faces rocklike features rubber boned rubbery body scales serpent appendages shade form shambling gait shell shimmering body skeletal appearance slimy speech suction cups limbs tail tentacles transparent unusual c olor weapons hands wet drenched body wings mechanical features multiple features special,1 perhaps thinking swig,there library python enables calling ability call functions c format without extern c please could remind name library i forgot name find it boostpython thank much your answer rewarded,1 class maskingproperty def initself fgetnone namenone docnone selffget fget fget none selfname fgetname selfdoc doc fgetdoc def callself func selffget func selfname funcname selfdoc selfdoc funcdoc return self def getself instance cls instance none return self selffget none raise attributeerrorseriously confused attribute ss cls selfname result selffgetinstance setattrinstance selfname result return result this basically denis otkidach cachedattribute slightly robust allows either maskingproperty def spamself maskingproperty notice parens def spamself,situation similar question i want replace property unlike question i want override subclass i want replace init property efficiency call function calculates value time property called i class property the constructor may take value property if passed value i want replace property value set property this property calculates value expensive operation similarly i want replace property value calculated property calculated future calls property recalculate class myclassobject def initself somevarnone somevar none selfsomevar somevar property def somevarself selfsomevar calcsomevar return selfsomevar problem the code work selfsomevar replace somevar function it tries call property setter defined potential solution i know i achieve thing slightly different way follows class myclassobject def initself somevarnone selfsomevar somevar property def somevarself selfsomevar none selfsomevar calcsomevar return selfsomevar this marginally less efficient check none every time property called the application performance critical may may good enough question is way replace property instance class how much efficient would i able ie avoiding none check function call,1 also ctypes lets access dlls wrap c code ctypes doc,there library python enables calling ability call functions c format without extern c please could remind name library i forgot name find it boostpython thank much your answer rewarded,1 if call x simply resolves calling adoit problem access contents a,how come function x access self object part see following code usrbinenv python class aobject def initself selfa def doitself print selfa a x adoit x see classespy,2 it something call binding the short stupid explanation method remember bound created operate context the longer explanation goes closures thing things like cites alonzo church pretty nifty stuff like locally defined functions classes but long short always simply recalling context,how come function x access self object part see following code usrbinenv python class aobject def initself selfa def doitself print selfa a x adoit x see classespy,1 twisted logging naive however reason needs case since twistedpythonlog featureful capable kind selective reporting others interested a log event dictionary arbitrary keys values the default observer knows dictionaries message key perhaps log messages emitted twisted try anything except provide humanreadable string associated key also many emitted messages added prior current twisted logging system older primitive system consumer not long ago problem bothered someone prompted file ticket start working resolution udp part problem particular the issue mostly resolved things remain done the solution attempted log structured message conveys information message recorded default observer this avoids messages appearing log default allows observer specifically interested events observe handle desired the ticket sitting untouched time it would probably easy someone pick patch get last bit way completion,my twistedbased client sends udp packets loop therefore i using class datagramprotocol this source usrbinpython coding utf twistedapplicationservice import service twistedinternet import reactor twistedinternettask import loopingcall twistedinternetprotocol import datagramprotocol twistedpython import log import logging class heartbeatclientservice def initself host port data beatperiod selfip host selfport intport selfdata data selfbeat intbeatperiod def startserviceself selfcall loopingcallselfheartbeat selfcallstartselfbeat def stopserviceself selfcallstop def heartbeatself protocol datagramprotocol protocolnoisy false port reactorlistenudp protocol portwriteselfdata selfip selfport portstoplistening i run client twistd i permanently get log messages twisted classes namely class datagramprotocol port closed twistedinternetprotocoldatagramprotocol starting port closed twistedinternetprotocoldatagramprotocol starting port closed twistedinternetprotocoldatagramprotocol starting since log messages polluting logs i wonder i disable log messages as see i already reduced amount logs calling protocolnoisy false i still getting log messages also command g protocolclientfactorynoisy false help is possible disable logging twistedinternal classes generic way all modules maybe using twistedlogging configuration,3 if pip install already works ossystempip install u myscript script startup this kinda dirty distributing via pip nondevelopers,tldr i need module automatically update script background silently i python script i distribute users i frequently update ask update via pip obviously high priority users want use app think updating i like update app automatically like google chrome silently background automatically is library allows already if straightforward way use pipdistribute module,1 unless real need keep objects list names like karta karta etc i would suggest use list loop initialize somerange kartaikarte,class karte want know way dynamic name creation new objects normal object creation would kartakarte curious something like kartaikarte something like would number loop end would call object like kartaboja kartaboja kartaboja achieve im new python thanks,3 you create list objects like karta range kartaappendkarte or using list comprehension karta karte range now access objects like kartai to accomplish last example modify globals dictionary i endorse g globals range gkarte stri karte this pythonic though use list,class karte want know way dynamic name creation new objects normal object creation would kartakarte curious something like kartaikarte something like would number loop end would call object like kartaboja kartaboja kartaboja achieve im new python thanks,3 in python i found pythonlibidlelibidlebat useful would let open python files supplied args idle,i trying teach komodo fire idle i hit right keystrokes i use exact path shortcut start menu windows explorer location bar launch idle i hoping komodo would able use well but giving path komodo causes say returned this appears failure idle start i thought i avoid shortcut use exact path i go start menu find shortcut idle right click look properties the target grayed says python the start set cpython the open file location button also grayed how i find shortcut really pointing i tried starting pythonexe pythonwexe cpython neither starts idle,3 try set l supdatel print set b lists this add list set give unique set elements lists if edit to preserve order elements original list use sets b l l b bappendi print b the order set case since thats order appear list,i looking way make list containing list single list b conditions the order new list b based number times value occurred lists a value appear basically turn b value occurs times list gets first position value occurs times list get second position b i figure one could set list magic but get head around contain number list the list created based user input i guess contain list items list my trying something along line setl l know perform setl amp setl get matched items is possible without loop iterating sublist count items sublist times,1 i think probably closest going get collections import defaultdict defaultdictint sub outer val sub dval print sorteddkeys keylambda k dk reverse true output there chance order elements appear identical number times may indeterminate output dkeys ordered,i looking way make list containing list single list b conditions the order new list b based number times value occurred lists a value appear basically turn b value occurs times list gets first position value occurs times list get second position b i figure one could set list magic but get head around contain number list the list created based user input i guess contain list items list my trying something along line setl l know perform setl amp setl get matched items is possible without loop iterating sublist count items sublist times,2 import itertools allitems setitertoolschaina b sortedallitems key lambda sumxcounty x,i looking way make list containing list single list b conditions the order new list b based number times value occurred lists a value appear basically turn b value occurs times list gets first position value occurs times list get second position b i figure one could set list magic but get head around contain number list the list created based user input i guess contain list items list my trying something along line setl l know perform setl amp setl get matched items is possible without loop iterating sublist count items sublist times,1 orioles fileoriolescsv ru stats dictrow mapfloat row row orioles in python stats row mapfloat row row orioles now access stats like printsumstats nickmarkakis,i csv file first column name baseball player subsequent item file statistic i like able import file player name equal tuple statistics right i import file using code orioles fileoriolescsv ru row orioles print row i get something like nickmarkakis adamjones i like statistics listed floats rather strings able pull player name use later like nickmarkakis adamjones,1 this asked many times many forms read number questions mutable default arguments new python nonlocal keyword on python could use function attribute def sentinelfillvalue fillvalue def ret sentinelcounter sentinelcounter lenargs raise longestexhausted yield fillvalue return ret sentinelcounter use global inside ret inside iziplongest always referencing global variable global counter counter def sentinelfillvalue fillvalue def ret global counter counter counter lenargs raise longestexhausted yield fillvalue return ret however using global restricts one iziplongest time see comments answer you also defining new ret every time sentinel called per iterator could instead something like global counter counter arglen lenargs def ret global counter counter counter arglen raise longestexhausted return fillvalue def sentinel yield ret example code sentinel outside iziplongest question comments def sentinelcounter arglen fillvalue def ret counter counter arglen raise longestexhausted yield fillvalue return ret def iziplongestmodifiedmyargs kwds iziplongest abcd xy fillvalue ax by c d fillvalue kwdsget fillvalue class longestexhaustedexception pass fillers repeatfillvalue counter arglen lenargs iters chainit sentinelcounter arglen fillvalue fillers args try tup izipiters yield tup except longestexhausted pass here using list container get around problems accessing outer scopes python,here i asked question iziplongest function itertools module the code def iziplongestfromdocsargs kwds iziplongest abcd xy fillvalue ax by c d fillvalue kwdsget fillvalue def sentinelcounter fillvaluelenargspop yield counter yields fillvalue raises indexerror fillers repeatfillvalue iters chainit sentinel fillers args try tup izipiters yield tup except indexerror pass there appeared error documentation pure python equivalent function the error real function abovementioned equivalent propagate indexerror exceptions raised inside generators sent function parameters agf solved problem gave corrected version pure python equivalent but time writing solution i made and making i faced one problem i hope unraveled asking question the code i came def iziplongestmodifiedmyargs kwds iziplongest abcd xy fillvalue ax by c d fillvalue kwdsget fillvalue class longestexhaustedexception pass def sentinelfillvalue fillvalue counter def ret counter counter lenargs raise longestexhausted yield fillvalue return ret fillers repeatfillvalue iters chainit sentinel fillers args try tup izipiters yield tup except longestexhausted pass in original code sentinel generator implements lazy evaluation so counter returned actually needed iterator created using chain function in code i added counter holds list one value the reason put mutable object place accessed returned iterators ret changed the place i found suitable functiondefaults sentinel if i put inside sentinel function counter would assigned every call sentinel would different lists ret def sentinelfillvalue fillvalue counter def ret counter counter lenargs raise longestexhausted yield fillvalue return ret i tried put outside sentinel function counter def sentinelfillvalue fillvalue def ret counter counter lenargs raise longestexhausted yield fillvalue return ret but exception rose unboundlocalerror local variable counter referenced assignment i added global keyword help i think counter really global scope counter def sentinelfillvalue fillvalue global counter def ret counter counter lenargs raise longestexhausted yield fillvalue return ret so question is approach i used put mutable list counter functiondefaults best case better way solve problem,1 they going allow post html wall post two main reasons malicious users insert script page dom nasty things rant facebook like formatting posts makes people look unique the first point important allow html makes site insecure would site they might nice enough allow certain tags like formattingonly stuff unlikely,does anyone know i create wall posts html content using facebook graph api and i could find documentationexamples i see anything useful httpdevelopersfacebookcomdocsreferenceapipost it would appear i using fbml also appears trying phase fbml,2 the option customizing wall posts embedded image video you html body things like bold italized texts possible what exactly trying allow,does anyone know i create wall posts html content using facebook graph api and i could find documentationexamples i see anything useful httpdevelopersfacebookcomdocsreferenceapipost it would appear i using fbml also appears trying phase fbml,1 if x array c factor xnpdiagindicesfromx c see diagindicesfrom numpy manual,way numpy get reference array diagonal i want array diagonal divided certain factor thanks,3 import itertools collections import defaultdict def listbycountlists datastream itertoolschainfromiterablelists counts defaultdictint item datastream countsitem return item item count sortedcountsitems keylambda x x x having x sort key ensures items count kind sequence well,i looking way make list containing list single list b conditions the order new list b based number times value occurred lists a value appear basically turn b value occurs times list gets first position value occurs times list get second position b i figure one could set list magic but get head around contain number list the list created based user input i guess contain list items list my trying something along line setl l know perform setl amp setl get matched items is possible without loop iterating sublist count items sublist times,1 using global bad idea imho you need make sure reset counter properly calls but seriously generator even need threading multiple calls generator flight time wreck havoc attempt sanely use global keep track state you could explicitly pass reference mutable object sentinel ret it looks like code controls calls function parameters original boring way transferring references scopes,here i asked question iziplongest function itertools module the code def iziplongestfromdocsargs kwds iziplongest abcd xy fillvalue ax by c d fillvalue kwdsget fillvalue def sentinelcounter fillvaluelenargspop yield counter yields fillvalue raises indexerror fillers repeatfillvalue iters chainit sentinel fillers args try tup izipiters yield tup except indexerror pass there appeared error documentation pure python equivalent function the error real function abovementioned equivalent propagate indexerror exceptions raised inside generators sent function parameters agf solved problem gave corrected version pure python equivalent but time writing solution i made and making i faced one problem i hope unraveled asking question the code i came def iziplongestmodifiedmyargs kwds iziplongest abcd xy fillvalue ax by c d fillvalue kwdsget fillvalue class longestexhaustedexception pass def sentinelfillvalue fillvalue counter def ret counter counter lenargs raise longestexhausted yield fillvalue return ret fillers repeatfillvalue iters chainit sentinel fillers args try tup izipiters yield tup except longestexhausted pass in original code sentinel generator implements lazy evaluation so counter returned actually needed iterator created using chain function in code i added counter holds list one value the reason put mutable object place accessed returned iterators ret changed the place i found suitable functiondefaults sentinel if i put inside sentinel function counter would assigned every call sentinel would different lists ret def sentinelfillvalue fillvalue counter def ret counter counter lenargs raise longestexhausted yield fillvalue return ret i tried put outside sentinel function counter def sentinelfillvalue fillvalue def ret counter counter lenargs raise longestexhausted yield fillvalue return ret but exception rose unboundlocalerror local variable counter referenced assignment i added global keyword help i think counter really global scope counter def sentinelfillvalue fillvalue global counter def ret counter counter lenargs raise longestexhausted yield fillvalue return ret so question is approach i used put mutable list counter functiondefaults best case better way solve problem,1 the rows painted qtreeviewdrawrow branches expand icons drawn drawbranches reimplement nothing get rid automatically drawn stuff def drawbranchesselfpainterrectindex pass unfortunately simply exchanging buttons checkboxes painting work clicks checkbox trigger button vice versa,i using qtreeview qitemdelegate reimplement paint routine however expandcollapse buttons siblingchild lines drawn automatically paint routine what drawing i control edit right qt draws qtreeview item order expand button checkbox rest treeitem stuff i want draw order checkbox expand button rest treeitem stuff the problem painting qitemdelegate right expand button,1 please discard java ideas they confuse python different language must learn pythonic approach here example openpowersearchtxt filein firstnum secondnum mapint linesplit line filein print firstnum secondnum,i input file i reading file like openpowersearchtxt filein line filein print line i wondering i want every single line st integer stored firstnum nd stored secondnum with java i use scanner nextint hasnext get integers equivalent python,3 well parse int string use ints string i think would logic way example openpowersearchtxt filein line filein n n ints linesplit printn n python different language java opinion expressive i one line i java still write readable code if try write java stuff python find language lot less effective,i input file i reading file like openpowersearchtxt filein line filein print line i wondering i want every single line st integer stored firstnum nd stored secondnum with java i use scanner nextint hasnext get integers equivalent python,3 edit nightcracker solution pretty much equivalent i assuming using python x x syntax it matter taste i would prefer mix slott nightcracker solutions openpowersearchtxt filein line filein firstnum secondnum ints linesplit print firstnum secondnum list comprehension bit easier read map destructuring assignment lets us take two item list assign element values two different local variables,i input file i reading file like openpowersearchtxt filein line filein print line i wondering i want every single line st integer stored firstnum nd stored secondnum with java i use scanner nextint hasnext get integers equivalent python,2 for future reference saveas blobstoredownloadhandler documented httpcodegooglecomappenginedocspythontoolswebappblobstorehandlershtml it seem like bit easier find let see improved,i using google app engine blobstore store range file types pdf xls etc trying find mechanism original filename uploaded file stored blobinfo used name downloaded file ie user sees somefilepdf save dialogue rather verylongdbkeypdf i see anything docs would allow httpcodegooglecomappenginedocspythonblobstoreoverviewhtml i seen hints posts could use information blobinfo set contentdisposition header is best approach achieving desired end,1 having player name variable helpful might think iterate collection one code fixed fragile addremove lines player name added removed file etc if however dictionary well iterate still ask players name playerdata fileoriolescsv ru orioles dict row playerdata row rowsplit oriolesrow tuplemapfloat row print orioleskeys adamjones nickmarkakis print orioles adamjones rather rowsplit trick probably want use csv module real code,i csv file first column name baseball player subsequent item file statistic i like able import file player name equal tuple statistics right i import file using code orioles fileoriolescsv ru row orioles print row i get something like nickmarkakis adamjones i like statistics listed floats rather strings able pull player name use later like nickmarkakis adamjones,2 root webpy folder create new folder called templates webpytemplates put layouthtml views extend pathtowebpytemplateslayouthtml,i three applications i want use layouthtml css is way achieve edit i put static folder layouthtml etc common webpy root here i model import os global webpypath webpypath osenvironget webpypath osgetcwd sessionlayoutpath webpypath commonlayouthtml print sessionlayoutpath sessionlayoutpath then views extend sessionlayoutpath edit regarding comment compiling i decided put common folder applications place static folder css images inside common folder like regular app i placed layouthtml root common then another app view i used extend commonlayouthtml which referenced layouthtml common app this layouthtml file referenced files static folder within common using url common static css stylecss as would regular application,3 zip files folders archives they files open reading like files i reckon look zipfile module if actually file called contents zip zipfile myzipfilezip r z fzopencontents r line freadlines linestartswithprogram logo something line i sure want shows look inside zip archive ps os using made think zip folder how seeing contents file how create contents file text file particular relevant line containing program logo look like without information answer question,i zip folder current directory how i tell python read contents file zip folder the contents file names files zip archive i basically want python read contents file look specific item word program logo record memory corresponding value program logo for example python query contents file stop reaches words program logo i assigned value program logo how i tell python record value variable should i use read file module python,1 the python tvrage api expecting integers strings get argv name tempseasonintbepisodeintc correct error season episode exists you take look command line parsing modules come python for newer use argparse for older versions use optparse if already know c getopt use getopt,i trying execute python script python seriespy supernatural supernatural tv series name season number episode number now script i using three arguments fetch title episode import tvrageapi import sys sysargv b sysargv c sysargv temp tvrageapishowa name tempseasonbepisodec line print nametitle but i getting error file seriespy line module name superseasonbepisodec file cpythonlibsitepackagestvrageapipy line season return selfepisodesn keyerror i using python,2 a keyerror means trying access item dictionary exist this code generate error three key dictionary dictone two two one three traceback recent call last file stdin line module keyerror three see python wiki entry keyerrors,i trying execute python script python seriespy supernatural supernatural tv series name season number episode number now script i using three arguments fetch title episode import tvrageapi import sys sysargv b sysargv c sysargv temp tvrageapishowa name tempseasonbepisodec line print nametitle but i getting error file seriespy line module name superseasonbepisodec file cpythonlibsitepackagestvrageapipy line season return selfepisodesn keyerror i using python,1 i figured fast way clearing sprites transparent layer applying peter solution selectively layer selflevelsprites spritelayerfill srect this seems working fine erasing everything frame still runs fps,i trying write d game using python pygame blits several layers top one another every screen refresh my basic setup bottom top background surface nontransparent scrolls different rate rest midground srcalpha transparent surface static player sprites enemies sprite group forground srcalpha transparent surface static right i blitting four layers one top another every screen the background scrolls different rate three layers i separate midground as i game structured runs fairly modest laptop fps but i trouble sprite group i blitting directly screen having adjust rect every sprite according current viewport seems like ugly way program things i like elegant solution i love blit sprites another transparent surface i could manage therin lies problem i find way clearing transparent layer half performance some setups i tried i tried filling layer white surface blend mode rgbasub surffill area blendrgbasub super super slow i tried surfacecopy blank surface faster still halves fps i tried combining sprites midground layer using pygamespritelayeredupdates update sprites this effect performance work midground transparent i get trails sprites background layer the best solution i found far current setup drawing sprites directly screen it looks great runs fast pain manage i make sure sprites rect adjusted according viewport every frame its also making collision detection difficult is another quick way clear pygame transparent surface quick done times second alternately setup layers would still accomplish effect,1 here solution works asfloat could extended asfloat replacing i l f see struct documentation explanation def asfloatself see httpenwikipediaorgwikiieee struct import packunpack selfbitlist return unpackfpacki bitsints where bitsint function converts bits integer def bitsintbits you may want change depending bit assumed significant bits intx x bits x rangelenbits x bitsii return x,i object i storing bits class bitset def initself bitstring selfbitlist char bitstring selfbitlistappendintchar def flipbitself index val selfbitlistindex val val selfbitlistindex val selfnewbitstring def bitstringself newstring val selfbitlist newstring newstring strval return newstring def lenself return lenselfbitlist def strself return selfbitstring def reprself return selfbitstring is anyway i convert bits float thanks,2 each xml document supposed exactly one root element you need adjust xml want support multiple foo elements,i xml document str now xsd foo unbounded time could i trying use elementtree running issue xmletreeelementtree import fromstring xmlstr xml version foo bar bazspambaz quxeggsqux bar foo try get document el fromstringxmlstr elfindall foo elfindall bar element bar xacb clearly i need loop foo foo root i obviously i could create element called root put el inside correct way,2 this collectionsdefaultdict you simply defaultdictint and da da intb and find works without statement,i data form i wish go line make value column key value column value also current key already exists mathematically add new value column current value column tried searchresult searchesstdoutreadlines output searchresult ab outputsplit astrip b bstrip da da da b else da b and got traceback recent call last file getidmanagerstatspy line module da keyerror,3 collectionsdefaultdictint output searchresults ab outputsplit dinta intb,i data form i wish go line make value column key value column value also current key already exists mathematically add new value column current value column tried searchresult searchesstdoutreadlines output searchresult ab outputsplit astrip b bstrip da da da b else da b and got traceback recent call last file getidmanagerstatspy line module da keyerror,1 you could simply fill text file names delimited line open namestxt f names freadsplitlines,i want list names john jack daniels whisky susan alex txt file called names now i want import file script use import random module this i import random name jay luis bob sofi susan x randomsamplenameinput please enter number volunteers needed print x instead name xxxxxxxxxxxxx i want name txt file everytime want change names i change txt file i trying make program schools volunteer club number volunteers chosen random biased that way everyone somewhat fair chance,1 file open myfiletxt r names filereadsplit fileclose use place name line good go you read reading writing files python note i assumed commadelimited list file you also put name separate line names filereadlines instead,i want list names john jack daniels whisky susan alex txt file called names now i want import file script use import random module this i import random name jay luis bob sofi susan x randomsamplenameinput please enter number volunteers needed print x instead name xxxxxxxxxxxxx i want name txt file everytime want change names i change txt file i trying make program schools volunteer club number volunteers chosen random biased that way everyone somewhat fair chance,2 hint anything references self going require instantiation class you could like class app emailqueue emailqueue appemailqueuedosomething but come seems like lot fluff i slaks initialize outside class alternatively could look singleton pattern,is thing static constructor python how i implement static constructor python here code the init fire i call app like the init static constructor static initializer appemailqueuedosomething i call like instantiates app class every time appemailqueuedosomething here class class app def initself selfmailqueue emailqueue property def emailqueueself return selfmailqueue the problem calling init every time app object gets recreated my real app class quite long,3 welcome python something like import random fid open namestxt r names fidreadlines numberneeded rawinput please enter number volunteers needed print randomsamplenames intnumberneeded,i want list names john jack daniels whisky susan alex txt file called names now i want import file script use import random module this i import random name jay luis bob sofi susan x randomsamplenameinput please enter number volunteers needed print x instead name xxxxxxxxxxxxx i want name txt file everytime want change names i change txt file i trying make program schools volunteer club number volunteers chosen random biased that way everyone somewhat fair chance,1 as noted syntax errors occur compile time run time while python interpreted language python code actually directly interpreted compiled byte code interpreted there compile step happens module imported alreadycompiled version available form pyc pyd file getting error quite exactly code running you put compile step make happen run time single line code want using eval noted i personally prefer avoid causes python perform potentially unnecessary runtime compilation one thing another creates feels like code clutter if want generate code generates code generates code absolutely fabulous time modifying debugging months so i would recommend instead something like import sys syshexversion x mymodule import thisfunc thatfunc theotherfunc else mymodule import thisfunc thatfunc theotherfunc i would even i one function used newer syntax short in fact i would take every reasonable measure minimize number size functions i might even write function like iftrueaelsebcond b single line syntax another thing might worth pointing i little amazed one pointed yet earlier versions python support code like value yes myvaristrue else support code like value myvaristrue yes that old way writing ternary expressions i python installed yet far i know old way still works day decide whether worth conditionally use new syntax need support use older versions python,if i python script requires least particular version python correct way fail gracefully earlier version python used launch script how i get control early enough issue error message exit for example i program uses ternery operator new blocks new i wrote simple little interpreterversion checker routine first thing script would call except get far instead script fails python compilation routines even called thus user script sees obscure synax error tracebacks pretty much require expert deduce simply case running wrong version python i know check version python the issue syntax illegal older versions python consider program import sys sysversioninfo raise must use python greater else syntax error ok x true else print x when run i want result binpython ternpy must use python greater result binpython ternpy file ternpy line x true else syntaxerror invalid syntax channeling coworker,1 a website usually project in website may multiple features blog wiki etc each features application project,i finished tutorial django app i want build app should i create new app within tutorial project folder i create new project folder new app i unsure cases makes sense reuse project create multiple apps project vs making new projects new app,1 the obvious way manually set limits want eg axaxisxmin xmax ymin ymax if want bother finding limits manually couple options as several people tillsten yann vorticity mentioned plot function want ignore last disable autoscaling plotting pass scaleyfalse kwarg plot import numpy np import matplotlibpyplot plt fig ax pltsubplots x nplinspace axplotx npsinx axplotx npsinx axautoscalefalse you could skip line use scalexfalse axplotx npsinx theoretical plot it last either way figsavefig testpdf note adjust zorder last plot drawn middle want control if want depend order want specify list lines autoscale based could something like note this simplified version assuming dealing lined objects rather matplotlib artists general import numpy np import matplotlibpyplot plt import matplotlibtransforms mtransforms def main fig ax pltsubplots x nplinspace line axplotx npsinx line axplotx npsinx line axplotx npsinx autoscalebasedonax line line pltshow def autoscalebasedonax lines axdatalim mtransformsbboxunit line lines xy npvstacklinegetdatat axdatalimupdatefromdataxyxy ignorefalse axautoscaleview name main main,i use matplotib axes api plot figures one lines i plot represents theoretical expected line it meaning outside original x limits what i want matlplotlib ignore autoscaling limits what i used check current limits plot reset limits the problem i plot third plot limits get recalculated together theoretical line really expands graph boilerplate matplotlibfigure import figure matplotlibbackendsbackendpdf import figurecanvaspdf numpy import sin linspace fig figure ax figaddsubplot x linspace axplotx sinx axplotx sinx i wish matplotlib would consider second plot rescaling axplotx sinx but would consider first last canvaspdf figurecanvaspdffig canvaspdfprintfiguretestpdf,3 use mapping multidimensional index values don use list lists lists arrayd now worry preallocating size number dimensions anything,if i want array example and i give simple example in fact number array dimensional changed different conditions and i want use multiplication list i want create every element directly how thank,3 there fundamental difference static dynamic languages always apparent first in static language class defined compile time everything nice set concrete program ever runs in dynamic language class actually defined runtime as soon interpreter parses starts executing class def statements equivalent static constructor run the class definitions executed point you put number statements class body want effect static constructor if want place function take self end class call function,is thing static constructor python how i implement static constructor python here code the init fire i call app like the init static constructor static initializer appemailqueuedosomething i call like instantiates app class every time appemailqueuedosomething here class class app def initself selfmailqueue emailqueue property def emailqueueself return selfmailqueue the problem calling init every time app object gets recreated my real app class quite long,3 you need create project app when create project define new apps inside project want fact managepy inside project folder djangoadminpy outside so startapp directly using djangoadminpy djangoadminpy startproject foo djangoadminpy startapp bar ls foo bar bar initpy modelspy testspy viewspy foo initpy managepy settingspy urlspy,i finished tutorial django app i want build app should i create new app within tutorial project folder i create new project folder new app i unsure cases makes sense reuse project create multiple apps project vs making new projects new app,1 yes namespaces ideally suited simply store configuration data like admin emails perdomain configuration record store records given domain namespace named domain,my gae app serves multiple domains ifelse conditions rather namespaces i see someone else solved namespaces i single app multiple namespaces defined i like set multiple domains acom bcom ccom app detect domain write domain data respective namespace i know namespaces i want better way add domain app settings like content languages for example sending email via form i use condition instead namespace class fileuploadhandlerblobstorehandlersblobstoreuploadhandler def postself adminemail admindomaincom gethost domain else admindomaincom message mailemailmessagesenderadminemail subjectselfrequestpostget subject messagebody messageto infodomain messagesend selfredirect customerservicehtm i use workaround queries localization cases even template render i able make domains able based templates differ content app hardcode domains settings easy add change are namespaces great idea case the way managed problem different domains far variable entity domains came utilgethostfind mydotcom url wwwmydotcomcom i function defines i mean may confuse wwwdomaincom domaincom problems subdomains def gethost return osenvirongethttphost osenvironservername i glad know idea i mistaken use namespaces case thanks,1 you need instantiate app use instead myapp app myappemailqueuedosomething,is thing static constructor python how i implement static constructor python here code the init fire i call app like the init static constructor static initializer appemailqueuedosomething i call like instantiates app class every time appemailqueuedosomething here class class app def initself selfmailqueue emailqueue property def emailqueueself return selfmailqueue the problem calling init every time app object gets recreated my real app class quite long,1 you need send list bunch different input name getlist get elements mylist string string string print form nameinput actionmyscriptpy element mylist print input typehidden namemylist values cgiescapeelement print input typesubmit namesubmit valuesubmit print form,i list object i sending script using cgi the list sent using hidden field html form when i extract object receiving script using mylist formgetlist nameofhiddenfield list stored single large text string first element mylist rather list i want what i wrong snippet code script html mylist string string string print form nameinput actionmyscriptpy print input typehidden namemylist values mylist print input typesubmit namesubmit valuesubmit print form snippet code myscriptpy mylist formgetlist mylist i seeing myscriptpy print mylist string string string thanks advice,1 sending via cgi turn list string to convert back use import ast mylist string string string mynewlist astliteralevalmylist print mynewlist,i list object i sending script using cgi the list sent using hidden field html form when i extract object receiving script using mylist formgetlist nameofhiddenfield list stored single large text string first element mylist rather list i want what i wrong snippet code script html mylist string string string print form nameinput actionmyscriptpy print input typehidden namemylist values mylist print input typesubmit namesubmit valuesubmit print form snippet code myscriptpy mylist formgetlist mylist i seeing myscriptpy print mylist string string string thanks advice,1 neolaser i think want achieved using dismax search it allows searching multiple fields specify boost value for details httpwikiapacheorgsolrsolrrelevancyfaq httpwikiapacheorgsolrdismaxqparserplugin,i solr search engine set multiple fields i want able search all fields i filtercontent string searches whatever fields documenttrue edit also non documenttrue fields different filterstokenisers applied im guessing would work adding single field,1 no possible you cannot cause arbitrary programs executed user computer without user installing otherwise would grievous security vulnerability,is possible write javascript execute python script preset file location user local hard disk collect output processing something like httpwwwjailbreakmecom,1 i think problem processkill kills immediate child process bash subprocesses bash script the problem solution described httpwwwdoughellmanncompymotwsubprocessprocessgroupssessions how terminate python subprocess launched shelltrue use popen preexecfnossetsid create process group ospgkill kill entire process group eg import os import signal import subprocess import time threading import thread process none def executecommandcommand runcommand threadtargetruncommand argscommandstart def runcommandcommand global process args commandstripsplit process subprocesspopen args shellfalse stdoutsubprocesspipe preexecfnossetsid line processcommunicate line print process line name main executecommandascriptsh runcommand timesleep oskillpgprocesspid signalsigkill time python pocpy process sleeping five real ms user ms sys ms,i wonder possible shut communication pipe killing subprocess started different thread if i call communicate kill work expected terminating process one second instead five i found discussion similar problem i got real answers i assume i either able close pipe explicitly kill subsubprocess sleep example kill unblock pipe i also tried find answer so i found directly address problem far i tell so thing i want able run command second thread get output able kill instantly i desire i could go via file tail similar i think better way import subprocess time threading import thread process none def executecommandcommand runcommand threadtargetruncommand argscommandstart def runcommandcommand global process args commandstripsplit process subprocesspopenargs shellfalse stdoutsubprocesspipe line processcommunicate line print process line name main executecommandascriptsh runcommand timesleep processkill this script binbash echo sleeping five sleep echo slept five output time python pocpy process sleeping five real ms user ms sys ms,3 the code gives ability override formset essentially limits ability nonsuperusers edit permissions they still create users modify permissions they even edit users fine class useradminuseradmin def changeviewself request objectid want limit ability normal user edit permissions requestuserissuperuser selffieldsets none fields username password personal info fields firstname lastname email permissions fields isactive isstaff issuperuser userpermissions important dates fields lastlogin datejoined groups fields groups else selffieldsets none fields username password personal info fields firstname lastname email permissions fields isactive isstaff issuperuser userpermissions important dates fields lastlogin datejoined groups fields groups return superuseradmin selfchangeviewrequest objectid,i gave editors permissions auth user addchange user on auth permissions addchange permissions off still editing change permissions allow actions i found ticket yrs ago httpcodedjangoprojectcomticket still works way how allow user edition email passwords etc block permissions change,1 i sure think characterbycharacter inherently characterbycharacter operation there certainly code simpler way characterbycharacter first need strip b prefix leftzeropad string length divisible make dividing bitstring characters easy bitstring bitstring bitstring lenbitstring bitstring then divide string blocks eight binary digits convert ascii characters join back string stringblocks bitstringii range lenbitstring string joinchrintchar char stringblocks if actually want treat number still account fact leftmost character seven digits long want go lefttoright instead righttoleft,using code take string convert binary binreducelambda x xy ordc c hello outputs b which i put site right hand site i get message hello back i wondering method uses i know i could splice apart string binary match corresponding value binordcharacter way really looking something simpler thanks,3 here girepository import gtk gdkpixbuf store gtkliststorestr gdkpixbufpixbuf bool,in pygtk i always used create liststore image using iconview displaying files store gtkliststorestr gtkgdkpixbuf bool but i figure python pygobject,3 this looks like hack i think works copying result aspem splitting import mcrypto def f mcryptorsanewpubkeyaspemciphernonesplitn i using python mcrypto pylint,i running lint follows python pylintlint mtestpy code import mcrypto def f mcryptorsanewpubkeyaspemciphernonesplitn the lint output ends exception attributeerror shutdown module threading usrlibpythonsitepackagesmcryptopylinuxxeggmcryptothreadingpyc ignored this code works fine run actually minimal test case full version work the exception ignored bitten considers failure stops step i tried adding mcryptothreadinginit mcryptothreadingcleanup around definition function fix problem how i prevent problem occurring i using mcrypto pylint python also tried debian lenny x,1 you cannot use controller page template cpt macro unchanged first controller python script expects parameters environment optionsstate structure one present reusing tal statements you rework template rely parts secondly html form form requires target send data in controller page template controlled metadata file set target explicitly,i trying work contact form baked plone site maintemplate i make functionality present get touch nav button site work plone setting my approach slightly reworking contactinfocpt make macro using macro within maintemplatept i get locationerror i try view page site unless remove taldefineerrors optionsstategeterrors line contactinfocpt this error i get line code if i remove line page render actually looks exactly way i want error upon submitting form this error situation i basically stumped situations would appreciate advice update solution i used just wanted post update i actually got work the information martijn pieters helpful understanding working i really position getting working i ended falling back jquery get working siteactions custom dropdown i wrapped contents form metalmain tags div gave simple id contactinfo then main template i also entered generic div simple id loadarea the last piece puzzle change contactjs file contactjspt enter lines talblock defineportalurl contextploneportalstateportalurl jq loadarea load span talreplaceportalurlspancontactinfo contactinfo talblock thought i post incase help anyone else later,2 no when import module later time another script imports module time program still running get clean copy module so testpy contains single line x get test import x x x import test testx impreloadtest module test testpy testx test rebound new object x old local variable affected course,i read importing module mutable objects changing inplaceaffects original imported module objects well for instance mymod import x x so i import mymod printmymodx prints bla my question isdoes inplace change affect module compiled byte codea module sourceunlikely namespace i importedso i change something like thatimport later time module somewhere else try access mutable objectwhat would i getcheers,1 for ascii characters range python import binascii binintbinasciihexlify hello b in reverse n int b binasciiunhexlify x n hello in python binintfrombytes hello encode big b in reverse n int b ntobytesnbitlength big decode hello to support unicode characters python def texttobitstext encoding utf errors surrogatepass bits binintfrombytestextencodeencoding errors big return bitszfill lenbits def textfrombitsbits encoding utf errors surrogatepass n intbits return ntobytesnbitlength big decodeencoding errors here singlesource python compatible version import binascii def texttobitstext encoding utf errors surrogatepass bits binintbinasciihexlifytextencodeencoding errors return bitszfill lenbits def textfrombitsbits encoding utf errors surrogatepass n intbits return intbytesndecodeencoding errors def intbytesi hexstring x n lenhexstring return binasciiunhexlifyhexstringzfilln n amp example texttobits hello textfrombits u hello true,using code take string convert binary binreducelambda x xy ordc c hello outputs b which i put site right hand site i get message hello back i wondering method uses i know i could splice apart string binary match corresponding value binordcharacter way really looking something simpler thanks,3 look connectorpython written geert it pure python implementation mysql protocol means installs wherever python installs you find instructions install httpgeertvanderkelenorgpost,i database set mysql workbench i want connect query database python script i idea go,1 i quiet sure i understand exact format wanting put calender table rows try months import calendar mycal calendarmonthcalendar make multi rowed month single row list days list x mycal daysextendx match week names enough weeks cover month weeks lenmycal sun mon tue wed thu fri sat images images image image make sure least zero end list daysappend find start end indexes actual day numbers lie startindex daysindex zeros end list fail endindex daysstartindexindex lendays lendaysstartindex header dec create table rows items startindex endindex weekdayrow trstr join tdstd x x weeksstartindexendindex dayrow trstr join tddtd x x daysstartindexendindex imagerow trstr join tdstd x x images finally put together form month block html divsdivtablennsnnsnnstable header weekdayrow dayrow imagerow you repeat many times need,rephrasing question suggested moderator i need create calendar python amp css web page i tried following python usrbinenv python import os sys calendar datetime import datetime mycal calendarmonthcalendar html strmycal mycal mycal cal mycal cal mycal cal mycal cal mycal html strmycal br html strcal br html strcal br html strcal br html strcal br html br this following output web page br br br br br how i arrange following format this sample format i done actual day date match the format needs two rows eg day date imgn day date imgn next month dec sun mon tue wed thu fri sat sun mon tue wed thu fri sat sun br img img img jan sun mon tue wed thu fri sat sun mon tue wed thu fri sat sun br img img img feb sun mon tue wed thu fri sat sun mon tue wed thu fri sat sun br img img img,1 your error message indicates really passing tue sep gmt are sure pass correct parameters strptime my python works fine following datetimestrptimeu tue sep gmt b y hms z returns datetimedatetime this also works fine dateutil imoprt parser dparser dparserparsetue sep gmt returns datetimedatetime tzinfotzutc,in standard python i convert string representation time datetime datestring u tue sep gmt dateobject datetimestrptimedatestring b y hms z this works fine i invoke app engine i get error time data match format data fmta b y hms z how would i convert date string correctly i get datetime representation,1 this hard python regex current implementation support unicode property shortcuts like plu pll azaz course match ascii letters regardless whether unicode option set so module updated install regex package currently development either need programmatically iterate string charislower charisupper characters specify unicode code points manually probably worth effort,suppose i want match lowercase letter followed uppercase letter i could something like recompilerazaz now i want thing unicode strings ie match something like aã y㜠tried recompilerazaz reunicode work any clues,3 i sure exactly looking produces table rows describe entire month first days i may starting point import calendar import itertools blank ampnbsp mycal calendarmonthcalendar daynames itertoolscycle mon tue wed thu fri sat sun endless list cal day week mycal day week flatten list lists empty lists hold data headers numbers imgs fill lists cal headersappenddaynamesnext numbersappendd imgsappendimagestrd else headersappenddaynamesnext numbersappendblank imgsappendblank format data html tabletrtrtrtrtrtrtableformat jointdstd h h headers jointdstd n n numbers jointdstd imgs,rephrasing question suggested moderator i need create calendar python amp css web page i tried following python usrbinenv python import os sys calendar datetime import datetime mycal calendarmonthcalendar html strmycal mycal mycal cal mycal cal mycal cal mycal cal mycal html strmycal br html strcal br html strcal br html strcal br html strcal br html br this following output web page br br br br br how i arrange following format this sample format i done actual day date match the format needs two rows eg day date imgn day date imgn next month dec sun mon tue wed thu fri sat sun mon tue wed thu fri sat sun br img img img jan sun mon tue wed thu fri sat sun mon tue wed thu fri sat sun br img img img feb sun mon tue wed thu fri sat sun mon tue wed thu fri sat sun br img img img,2 plistlib python standard library deals plist files refer pymotw article quick tutorial see also zipfile class zipfile module also python standard library reading zip files,i zip file in zip i plist file restoreplist how i tell python read plist file stop reaches part keysupportedproducttypeskey array stringiphonestring array i want tell python stop supportedproducttypes key record corresponding string iphone memory variable x print x how i,2 try xml import xmletreeelementtree et tree etparsekeysxml doc treegetroot sup docgetiteratorsupportedproducttypes print docgetiteratorstringtext gives iphone test file called keysxml keys keysupportedproducttypeskey array stringiphonestring array keys,i zip file in zip i plist file restoreplist how i tell python read plist file stop reaches part keysupportedproducttypeskey array stringiphonestring array i want tell python stop supportedproducttypes key record corresponding string iphone memory variable x print x how i,1 you want use raise cause exception created travel call stack something handles exception tryexcept block for example using triangle function real code would something like try trianglex z except triangleerror print triangle x z good that way able handle error bad triangle made program crash,i learning python python koans days i came problem raising exceptions python specifically i even confused tryexcept going koan i know similar question toward rudy koan ruby koan raising exceptions but i python newbie know nothing ruby so koan you need finish implementing triangle file trianglepy triangle import class abouttriangleprojectkoan the first assignment talk handle errors let handle part def testillegaltrianglesthrowexceptionsself calls triangle selfassertraisestriangleerror triangle selfassertraisestriangleerror triangle selfassertraisestriangleerror triangle selfassertraisestriangleerror triangle following trianglepy def trianglea b c delete pass and write this code b b c c return equilateral b b c c return isosceles else return scalene error class used part no need change code class triangleerrorstandarderror pass i supposed finish triangle function to understanding tryexcept functions like certain criteria satisfied something else exception then situation i use raise triangleerror try except what differences thank much,1 it install ipython different versions python installed system starting ipython version bring shell appropriate version python,i install ipython mac os x lion following how install ipython snow leopard as i mac sudo usrbineasyinstall python turns i originally easyinstall installed then i choose easyinstall install python works but i install ipython version easyinstall what going behind,1 use select it basically pause program wake data available socket,i looking optimum sleep value receive data nonblocking socket eg true datasrecv data timesleep ms else pass no sleep would lead cpu usage idea get best cpu usage bandwith how long sleep cpu thread switch btw make sense set buffer socket via sosndbufsorecvbuf set tcpnodelay combined,1 if plan use sleep use blocking sockets,i looking optimum sleep value receive data nonblocking socket eg true datasrecv data timesleep ms else pass no sleep would lead cpu usage idea get best cpu usage bandwith how long sleep cpu thread switch btw make sense set buffer socket via sosndbufsorecvbuf set tcpnodelay combined,2 it appears queue empty put buffers flushed may take the solution problem use sentinels maybe builtin taskdone call taskdone indicate formerly enqueued task complete used queue consumer threads for get used fetch task subsequent call taskdone tells queue processing task complete if join currently blocking resume items processed meaning taskdone call received every item put queue raises valueerror called times items placed queue,i program using python packages multiprocessing queue one functions structure multiprocessing import process queue def fooqueue true try queuegetblock false doandprintstuffa except print end break name main nthreads queue queuequeue put stuff queue stuff morestuff queueputstuff procs processtarget foo args queue xrangenthreads p procs pstart p procs pjoin idea i try extract queue empty raise exception terminate loop so i two questions safe idiom are better ways i tried find exact exception raised i try get empty queue currently program catching exceptions sucks error somewhere else i get end message i tried import queue queue queuequeue queueputx x xrange try print queuegetblock false except queueempty print end break i got error i caught exception what correct exception catch,1 you use select call timeout need code wake every often even data received btw tcpnodelay sending side influence read,i looking optimum sleep value receive data nonblocking socket eg true datasrecv data timesleep ms else pass no sleep would lead cpu usage idea get best cpu usage bandwith how long sleep cpu thread switch btw make sense set buffer socket via sosndbufsorecvbuf set tcpnodelay combined,1 perhaps python package croniter suits needs usage example import croniter import datetime datetimedatetimenow cron cronitercroniter crongetnextdatetimedatetime datetimedatetime crongetnextdatetimedatetime datetimedatetime crongetnextdatetimedatetime datetimedatetime,i need parse crontablike schedule definition python eg get last run is good preferably small library parses strings translates dates,3 i think would optimized see first url contains womenshoes check whether contains women querystr anotcontainshref womenshoes containshref women,link hxsselectacontainshref women anotcontainshrefwomenshoes selfloglinks attributehref the first statement selecting hyperlinks contain women url basically i want select links women url womenshoes how i put condition loop i looking correct usage operator loop condition also if i want something like select links women url condition i want check link womenshoes url i,1 given unusual requirements implementation seems correct in particular if updating one attribute python gil sufficient single bytecode instructions atomic if anything complex add locking it basically harmless anyway cared performance multicore scalability probably using python in particular aware selfthing selfn code updated separate bytecode instructions the gil could releasedacquired get consistent view two unless add locking if going i suggest removing selfn attractive nuisance easily misused least adding commentdocstring caveat consumers need make copy you ever mutating particular object pointed selfthing string objects immutable python garbagecollected long consumer grabbed reference keep accessing without worrying much threads the worst could happen program using lot memory several generations selfthing kept alive i bit curious requirements came in particular care thing never used used many times,filepy class producerself def initself selfchunksize open devzero f selfthing freadselfchunksize selfn selfstart def startself import subprocess import threading def produce selfproc subprocesspopen producerproc stdoutsubprocesspipe true selfthing selfprocstdoutreadselfchunksize lenselfthing selfchunksize msg expected bytes read bytes formatselfchunksize lenselfthing raise exceptionmsg selfn threadingthreadtargetproduce tdaemon true tstart selfthread def stopself selfthreadisalive selfprocterminate selfthreadjoin producer producer producerstart i written code less like design i want able consume output producerproc files going someotherfilepy import file mything fileproducerthing multiple consumers might grabbing reference fileproducerthing need use producerproc and producerproc never blocked is sane implementation does python gil make thread safe i need reimplement using queue getting data worker thread do consumers need explicitly make copy thing i guess trying implement something like producerconsumer pattern observer pattern i really clear technical details design patterns a single producer constantly making things multiple consumers using things arbitrary times producerthing replaced fresh thing soon new one available things go unused ok it ok multiple consumers read thing read thing twice succession they want sure got recent thing asked stale old thing a consumer able keep using thing long scope even though producer may already overwritten selfthing fresh new thing,1 the fact png small uses zlib library i think would rather use library instead png wrapper less confusing see httpzlibnet if still want use png library fact tuples png images usually alpha channel thus format rgba use reconstruct data,as output files measurement i get large ascii files containing x table float numbers mb as impractical large numbers ie another measurements per series i would like effectively compress exploiting data structure basically mp map picture i tried use pylabs imsave function generate png files raw data worked nicely yielded kb png to analyse data later point i obviously need reverseprocess png would like get identical initial table back however alleged function imread yields tuple i cannot figure does anybody experience process better idea solve compressing problem simply zipping doesnt even remotely compress enough import numpy import image import matplotlib import pylab datanumpygenfromtxt raw datatxt autostriptrue casesensitivetrue pylabimsave convertpng data outpylabimread convertpng numpysavetxt convertedtxt fmt e,2 the example singletoned would work sqlalchemy from sqlalchemy docs connecting sql server if require connection string outside options presented use odbcconnect keyword pass urlencoded connection string what gets passed urldecoded passed directly so make work i used import urllib quoted urllibquoteplus driverfreetdsservermydbserverdatabasemydbuidmyuserpwdmypwdtdsversionport sqlalchemycreateengine mssqlpyodbcodbcconnect formatquoted this apply sybase well,the following works import pyodbc pyodbcconnect driverfreetdsservermydbserverdatabasemydbuidmyuserpwdmypwdtdsversionport the following fails import sqlalchemy sqlalchemycreateenginemssqlmyusermypwdmydbservermydbdriverfreetdsamp odbcoptions tdsversion connect the error message dbapierror error unixodbcfreetdssql serverunable connect data source sqldriverconnectw none none can someone please point right direction is way i simply tell sqlalchemy pass specific connect string pyodbc please note i want keep dsnless,3 field settingsformfields print fieldinitial,i simple form looks like class settingsformformsmodelform theme formscharfieldrequiredtrue initial yellow defaultinputmessage formscharfieldrequiredtrue initial type i iterate form fields field settingsformfields print field is way i could access default values form fields well thanks,1 pythonautomata seems able things asking what missing perhaps want contribute missing feature,what would complete finite automata library python able basic manipulations minimization determinization nondeterministic finite automata union intersection product languages generated automata etc all libraries i finding either incomplete work plugandplaywise,1 using virtualenv want upgrade packages added virtualenv may want pip install pip freeze l cut fields upgrade,is possible upgrade python packages one time pip note feature request official issue tracker,3 there libraries want reinvent wheel my bitstring library could help bitstring import bitarray bitarrayfloat length abin afloat abin afloat abytes helloall afloat e the float interpretation allowed either bits take look documentation details,i object i storing bits class bitset def initself bitstring selfbitlist char bitstring selfbitlistappendintchar def flipbitself index val selfbitlistindex val val selfbitlistindex val selfnewbitstring def bitstringself newstring val selfbitlist newstring newstring strval return newstring def lenself return lenselfbitlist def strself return selfbitstring def reprself return selfbitstring is anyway i convert bits float thanks,2 it entirely clear mean determining place list use slicing originallist newlist originallist newlist,i updating legacy python script wondering possible unwrap list inside another list generally unwrap list elements my specific problem i large list passed another list place middle list instead single element ie i list form passed parameter i passed list form list parameters goal generating list list parameters the obvious solution write list parameters i worried iterate list parameters instead list parameters this matters apart performance critical part program elements list expensive evaluate,1 if form posts correctly django without js able progressively enhance ajax without hacking messy passing csrf token just serialize whole form automatically pick form fields including hidden csrf field myform submitfunction var action thisattr action var ajax url action type post data thatserialize success functiondata consolelog success return false i tested django jquery obviously work html form django apps,i could use help complying django csrf protection mechanism via ajax post i followed directions httpdocsdjangoprojectcomendevrefcontribcsrf i copied ajax sample code page exactly httpdocsdjangoprojectcomendevrefcontribcsrfajax i put alert printing contents getcookie csrftoken xhrsetrequestheader call indeed populated data i sure verify token correct i encouraged finding sending something but django still rejecting ajax post here javascript postmemorize data function result result failure getrandomcard else alertfailed save card data here error i seeing django feb post memorize http i sure i missing something maybe simple i know i searched around so saw information turning csrf check view via csrfexempt decorator i find unappealing i tried works i rather get post work way django designed expect possible just case helpful gist view def myviewrequest profile requestuserprofile requestmethod post process post return httpresponseredirect memorize else requestmethod get ajax requestgethaskey ajax some irrelevent code ajax response httpresponse profilegetstackjsonresponse return response else get data send along content page return rendertoresponse memorizememorizehtml my data contextinstancerequestcontextrequest thanks replies,3 i managed help solve problem the problem installation pycurlso copied sitepackages virtualenv when installing via pip v install pycurl following output given downloadingunpacking pycurl using version newest versions downloading pycurltargz kb kb downloaded running setuppy egginfo package pycurl using curlconfig libcurl running egginfo creating pipegginfopycurlegginfo writing pipegginfopycurlegginfopkginfo writing toplevel names pipegginfopycurlegginfotopleveltxt writing dependencylinks pipegginfopycurlegginfodependencylinkstxt writing manifest file pipegginfopycurlegginfosourcestxt warning manifestmaker standard file c found reading manifest file pipegginfopycurlegginfosourcestxt reading manifest template manifestin writing manifest file pipegginfopycurlegginfosourcestxt installing collected packages pycurl running setuppy install pycurl using curlconfig libcurl running install running build running buildpy creating build creating buildliblinuxx creating buildliblinuxxcurl copying pythoncurlinitpy buildliblinuxxcurl running buildext building pycurl extension creating buildtemplinuxx creating buildtemplinuxxsrc gcc pthread fnostrictaliasing g o dndebug g fwrapv o wall wstrictprototypes fpic dhavecurlssl ioptpythonincludepython c srcpycurlc buildtemplinuxxsrcpycurlo srcpycurlc warning warning libcurl compiled ssl support configure could determine library used thus ssl crypto locking callbacks set may cause random crashes ssl requests srcpycurlc in function ‘domultiinforead’ srcpycurlc warning call ‘curleasygetinfoerrstring’ declared attribute warning curleasygetinfo expects pointer char info srcpycurlc in function ‘multisocketcallback’ srcpycurlc warning call ‘curleasygetinfoerrstring’ declared attribute warning curleasygetinfo expects pointer char info in function ‘utilcurlunsetopt’ inlined ‘docurlunsetopt’ srcpycurlc srcpycurlc warning call ‘curleasysetopterrcurlsh’ declared attribute warning curleasysetopt expects curlsh argument option gcc pthread shared buildtemplinuxxsrcpycurlo loptpythonlib lcurl lpython buildliblinuxxpycurlso unknown option staticlibs usage curlconfig option available values option include ca ca bundle install path cc compiler cflags preprocessor compiler flags checkfor version check libcurl specified version features newline separated list enabled features help display help exit libs library linking information prefix curl install prefix protocols newline separated list enabled protocols version output version information vernum output version information number hexadecimal gcc gcc red hat copyright c free software foundation inc this free software see source copying conditions there no warranty even merchantability fitness for a particular purpose running installlib creating homeecuservirtualenvsxxxlibpythonsitepackagescurl copying buildliblinuxxcurlinitpy homeecuservirtualenvsxxxlibpythonsitepackagescurl bytecompiling homeecuservirtualenvsxxxlibpythonsitepackagescurlinitpy initpyc running installdata copying changelog homeecuservirtualenvsxxxsharedocpycurl copying copying homeecuservirtualenvsxxxsharedocpycurl copying copying homeecuservirtualenvsxxxsharedocpycurl copying install homeecuservirtualenvsxxxsharedocpycurl copying readme homeecuservirtualenvsxxxsharedocpycurl copying todo homeecuservirtualenvsxxxsharedocpycurl copying doccurlshareobjecthtml homeecuservirtualenvsxxxsharedocpycurlhtml copying docpycurlhtml homeecuservirtualenvsxxxsharedocpycurlhtml copying doccurlobjecthtml homeecuservirtualenvsxxxsharedocpycurlhtml copying doccurlmultiobjecthtml homeecuservirtualenvsxxxsharedocpycurlhtml copying doccallbackshtml homeecuservirtualenvsxxxsharedocpycurlhtml copying examplesretrieverpy homeecuservirtualenvsxxxsharedocpycurlexamples copying examplesfileuploadpy homeecuservirtualenvsxxxsharedocpycurlexamples copying exampleslinksyspy homeecuservirtualenvsxxxsharedocpycurlexamples copying examplesxmlrpccurlpy homeecuservirtualenvsxxxsharedocpycurlexamples copying examplesretrievermultipy homeecuservirtualenvsxxxsharedocpycurlexamples copying examplessfquerypy homeecuservirtualenvsxxxsharedocpycurlexamples copying examplesbasicfirstpy homeecuservirtualenvsxxxsharedocpycurlexamples copying teststestpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestftppy homeecuservirtualenvsxxxsharedocpycurltests copying teststestsharepy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultipy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultitimerpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestpostpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestgtkpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestpostpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestdebugpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultipy homeecuservirtualenvsxxxsharedocpycurltests copying teststestcbpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultivsthreadpy homeecuservirtualenvsxxxsharedocpycurltests copying teststeststringiopy homeecuservirtualenvsxxxsharedocpycurltests copying teststestxmlrpcpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultisocketselectpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultipy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultisocketpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultipy homeecuservirtualenvsxxxsharedocpycurltests copying testsutilpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultipy homeecuservirtualenvsxxxsharedocpycurltests copying teststestinternalspy homeecuservirtualenvsxxxsharedocpycurltests copying teststestpostpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmemleakpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestmultipy homeecuservirtualenvsxxxsharedocpycurltests copying teststestsocketopenpy homeecuservirtualenvsxxxsharedocpycurltests copying teststestgetinfopy homeecuservirtualenvsxxxsharedocpycurltests running installegginfo running egginfo creating pycurlegginfo writing pycurlegginfopkginfo writing toplevel names pycurlegginfotopleveltxt writing dependencylinks pycurlegginfodependencylinkstxt writing manifest file pycurlegginfosourcestxt warning manifestmaker standard file c found reading manifest file pycurlegginfosourcestxt reading manifest template manifestin writing manifest file pycurlegginfosourcestxt copying pycurlegginfo homeecuservirtualenvsxxxlibpythonsitepackagespycurlpyegginfo running installscripts writing list installed files tmppiplewzobrecordinstallrecordtxt successfully installed pycurl cleaning removing temporary dir homeecuservirtualenvsxxxbuild the key error gcc pthread shared buildtemplinuxxsrcpycurlo loptpythonlib lcurl lpython buildliblinuxxpycurlso unknown option staticlibs usage curlconfig option available values option include ca ca bundle install path cc compiler cflags preprocessor compiler flags checkfor version check libcurl specified version features newline separated list enabled features help display help exit libs library linking information prefix curl install prefix protocols newline separated list enabled protocols version output version information vernum output version information number hexadecimal which shows curlconfig called argument staticlibs fails recognise instead prints usage output most importantly returning nonerrorcode output makes compiler assume pycurlso compilation successful this described detail the solution problem modify pycurl setuppy change line read libs instead staticlibs this causes pycurlso built copied sitepackages directory successfully,i trying install pycurl virtualenv easyinstall appears install correctly xxx easyinstall pycurl searching pycurl reading httppypipythonorgsimplepycurl reading httppycurlsourceforgenet reading httppycurlsourceforgenetdownload best match pycurl downloading httppycurlsourceforgenetdownloadpycurltargz processing pycurltargz running pycurlsetuppy q bdistegg distdir tmpeasyinstallbwdypycurleggdisttmprmisvr using curlconfig libcurl srcpycurlc warning warning libcurl compiled ssl support configure could determine library used thus ssl crypto locking callbacks set may cause random crashes ssl requests srcpycurlc in function ‘domultiinforead’ srcpycurlc warning call ‘curleasygetinfoerrstring’ declared attribute warning curleasygetinfo expects pointer char info srcpycurlc in function ‘multisocketcallback’ srcpycurlc warning call ‘curleasygetinfoerrstring’ declared attribute warning curleasygetinfo expects pointer char info in function ‘utilcurlunsetopt’ inlined ‘docurlunsetopt’ srcpycurlc srcpycurlc warning call ‘curleasysetopterrcurlsh’ declared attribute warning curleasysetopt expects curlsh argument option gcc gcc red hat copyright c free software foundation inc this free software see source copying conditions there no warranty even merchantability fitness for a particular purpose zipsafe flag set analyzing archive contents adding pycurl easyinstallpth file installed homeecuservirtualenvsxxxlibpythonsitepackagespycurlpylinuxxegg processing dependencies pycurl finished processing dependencies pycurl however trying use i get following error xxx python python r sep gcc red hat linux type help copyright credits license information import pycurl traceback recent call last file stdin line module importerror no module named pycurl despite fact i clearly see pycurlpylinuxxegg virtualenvsxxxlibpythonsitepackages directory any suggestions solve problem would much appreciated distribution amazon linux ec bit python installed source curl libcurl libcurldev supplied amazon yum repos version i install pycurl package provided amazon repos distrosupplied version python project runs it path issue contents syspath follows import sys syspath homeecuservirtualenvsxxxlibpythonsitepackagessetuptoolscpyegg homeecuservirtualenvsxxxlibpythonsitepackagespippyegg homeecuservirtualenvsxxxlibpythonsitepackagespygeoippyegg homeecuservirtualenvsxxxlibpythonsitepackagesdaryllibpyegg homeecuservirtualenvsxxxlibpythonsitepackagesxxxpyegg homeecuserdealutilspyegg homeecuservirtualenvsxxxlibpythonsitepackagessixpyegg homeecuserfmcpyegg homeecuservirtualenvsxxxlibpythonsitepackagesaffiliatewindowpyegg homeecuservirtualenvsxxxlibpythonsitepackagesicodespyegg homeecuservirtualenvsxxxlibpythonsitepackagessupervisorapyegg homeecuservirtualenvsxxxlibpythonsitepackagesmeldpyegg homeecuservirtualenvsxxxlibpythonsitepackagestornadopyegg homeecuservirtualenvsxxxlibpythonsitepackagespycurlpylinuxxegg homeecuservirtualenvsxxxlibpythonsitepackages root homeecuservirtualenvsxxxlibpythonzip homeecuservirtualenvsxxxlibpython homeecuservirtualenvsxxxlibpythonplatlinux homeecuservirtualenvsxxxlibpythonlibtk homeecuservirtualenvsxxxlibpythonlibold homeecuservirtualenvsxxxlibpythonlibdynload optpythonlibpythonsitepackagessetuptoolscpyegg optpythonlibpythonsitepackagespippyegg optpythonlibpython optpythonlibpythonplatlinux optpythonlibpythonlibtk optpythonlibpythonsitepackages,3 no scikitlearn play tricks gil instead uses joblib parallelism spawns multiple processes work you achieve want custom joblib parallel construct if intend train multiple classifiers dataset different settings find optimal one consider using gridsearchcv class handles parallelism,i would like train multiple one class svms different threads does anybody know scikitslearnsvm releases gil i find answer google thanks,2 use oswalk import os dirpathdirsfiles oswalk a folderanother folder f files fn ospathjoindirpath f myzipfilewritefn,is possible write folder contents existing zipfile i messing around manage write folder structure archive anything inside folder copied i want point specific file idea folder contents change program copy whole folder archive matter inside currently i myzipfilewrite a folderanother folder i want contents another folder copied well empty folder hopefully understand i mean thanks,1 i take dictionaries way cases def setdictdictxyzval set values dictionary dictgetx none dictx z val elif dictxgety none dictxy z val else dictxyz val setdictd setdictd setdictd in anology i getter def getdictdict x z presetnone read values dictionary dictgetx preset preset return preset elif dictxgety preset preset return preset elif dictxygetz preset preset return preset else return dictxygetz getdictd getdictd none keyerror in opinion advantage lies iterating field quite simple x dkeys dxkeys z dxykeys print dxyz,if i want array example and i give simple example in fact number array dimensional changed different conditions and i want use multiplication list i want create every element directly how thank,1 in lines current currentnext next currentnext happens currentnext none i know python exercise actually need functionality latter already builtin class it collectionscounter python x using earlier version make one subclassing collectionsdefaultdict it also uses python dictionaries instead storing data keyvalue pairs example collections import counter x counter x x b x c x counter b c you recover sorted keyvalue pair representation data xmostcommon,can please help trying sort linked lists according documentation add function getting error says fadd b file line add attributeerror nonetype object attribute next avoid thankyou class frequencyobject stores letterfrequency pair f frequency c fletter c ffrequency f c def initself letter frequency selfletter letter selffrequency frequency selfnext none def reprself return selfletter selffrequency class sortedfrequencylistobject stores collection frequency objects sorted linked list items sorted highest frequency lowest def initself selfhead none def addself letter frequency adds given letterfrequency combination frequency object list if given letter already list given frequency added frequency f sortedfrequencylist fadd f fadd b f b fadd c f c b fadd b f b c current selfhead found false selfhead none selfhead frequencyletter frequency else prev none current none currentletter letter currentfrequency currentfrequency frequency found true prev current current currentnext next currentnext next none current next currentfrequency nextfrequency temp current current next next temp else current next next currentnextnext found false prevnext frequencyletter frequency,1 if kbytes i would load instance memory amongst storage choices memcache datastore blobstore google app engine instance memory option shoud fastest,i couple smaller asset files text templates typically k bytes app i considering caching using memcached but anyone know loading local file requesting memcache fastestmost resource efficient i using python version app engine,3 swig boostpython sip shiboken pybindgen swig boostpython popular ie largest user base active development teams which two use largely matter taste so want use boostpython swig obvious choice,there library python enables calling ability call functions c format without extern c please could remind name library i forgot name find it boostpython thank much your answer rewarded,1 alas wrapping element elementtree tree elementtreeel trying treefindall foo seem work either seems search beneath element even search done full tree searches beneath root as elementtree claim really implement xpath difficult say whether intended bug solution without using lxml full xpath support elxpath foo example easiest solution would use elementiter method foo elitertag foo print foo want results list listelitertag foo note use complex paths way find elements certain tagname starting including element,i xml document str now xsd foo unbounded time could i trying use elementtree running issue xmletreeelementtree import fromstring xmlstr xml version foo bar bazspambaz quxeggsqux bar foo try get document el fromstringxmlstr elfindall foo elfindall bar element bar xacb clearly i need loop foo foo root i obviously i could create element called root put el inside correct way,1 there currently feature ie keywords hardcoded single color if fell really needed please create feature request explaining usecase pydev tracker see httppydevorgabouthtml,in preferencespydeveditorappearance color options i edit colors i edit color keywords instance is way edit color specific keyword say range,1 add contentdisposition attachment filenamefile header response,i trying use cherrypy simple website never done python web programming i stuck trying allow download file dynamically created i create file return handler call servefileobj file either case contents file simply rendered screen rather downloaded does cherrypy offer useful methods how accomplished,1 don think i get question here however snippets get started just read letters one go use partitioning generator described use split send generator def chunksl n yield successive nsized chunks l xrange lenl n yield liin import pprint arawinput letters letters b c e f g h j k l n p q r u v w x pprintpprintlistchunksasplit b c e f g h j k l n p q r u v w x if looking approximate matching look difflib getclosematches appel ape apple peach puppy apple ape import keyword getclosematches wheel keywordkwlist getclosematches apple keywordkwlist getclosematches accept keywordkwlist except after i think need clarify question bit,i want program take letters input put sort list make rules letter connect another get three words overlapping what def matris matris counter counter counter counter counter counter matrisappendrawinput one letter counter counter matrisappendrawinput one letter counter counter matrisappendrawinput one letter counter counter matrisappendrawinput one letter counter counter matrisappendrawinput one letter counter return matris so example i run ask one letter could generate matrix looking something like matris g u r g f e c r f x if anyone better way i would thankful shared and way work i want program im sure i able version i dictionarytxt i made something like dictionary open dictionarytxt r thought would try start matching matrismatris see word starting ie g take next letter find lets say three best valued words i guessing would need class so far i come class hypotes def init self usedposiiton word selfu usedposition selfw word positions bestwords there maximum three words list words highest score i thought i save positions array i later make sure words best use letters guessing i going need help class lettervaluepoints a b c d e f g h i j k l m n o p r s t u v x y z ã ㄠ㖠i thought later i would give letter value i would like i dont know good way,1 you clear queue joining process qempty unreliable the best way clear queue count number successful gets loop receive sentinel value like socket reliable network,i trying use queue multiprocessing library python after executing code print statements work processes quit i call join queue still alive how i terminate remaining processes thanks def multiprocesstestself print starting multiprocess print number cpusmultiprocessingcpucount numprocs def doworkmessage print workmessage completed def worker true item qget doworkitem qtaskdone q multiprocessingjoinablequeue rangenumprocs p multiprocessingprocesstargetworker pdaemon true pstart source hi item source qputitem print q close qjoin qclose print finished everything print num active childrenmultiprocessingactivechildren,2 add new constructor template typename t bart header implement template barbartupple,in c code i class foo many methods taking bar type variable argument class foo public void dothisbar b void dothatbar b bar number constructors create new object many common types int stdstring float etc class bar public barint barfloat f barstdstring i wrapped boostpython i able call foo methods using python literals directly get implicitly converted bar objects f foo fdothis fdothathello now i would like able use also python types tuples like fdothat but i want touch original bar definition i want pollute c library boostpython stuff i want write wrapper function binding code i understand possible correct way in words i register factory function used automatic conversion python,1 one way handle optional parts use regex text optional part the part inside parenthesis match either optional part regex nothing,i logfile contains log using data yyyymmdd files queued scanning warning etesthã¤ndlerpdf file found loading com please wait file scanned i want write regex detect warning message optional warning comming sometimes i wrote basic regext data coming compulsory logd recompileusingsdatasfromsyyyymmdds pdefsdatedddwd data researchlogd loggroupdict output defsdate since warning optional i handle i good writting regex and please suggest good examples links get master regex,1 this instance packing problem a nice algorithm packing rectangles inside rectangle described you need write python obviously,how would use python work many blocks given size would fit area given size lets say i rectangle x x y i area x x how would i work many rectangle would fit area would best fit,2 you could render latex via matplotlib use figures pygame sprites httpmatplotlibsourceforgenetusersusetexhtml,i trying read text latex formatting render using pygame i novice pygame help appreciated i looked glyph package the problem i would rewrite txt files glyph formatting useful if i try define macros i would essentially build latex translator both options seem practical considering number text files i,1 i found recent link cross compiling arm ppc using something like openembedded buildroot whatever else make complete embedded distribution build environment use tutorials openembedded buildroot amp others using methods patches cross compile python,i c wrapper python module in order compile c code i need libs python code compiles installation ubuntu g now i want compile make cxxarmnonelinuxgnueabig got armnonelinuxgnueabig path got standard libs includes arm except python libs arm so afaik i need compile python source code arm maybe using link any options,1 do hesitate memory maybe later the java equivalent class map as map interface take hashmap class moment map method values get values map as key scalar may create coordinates class be aware override equals hashcode,i strong python background total newbie java i try things pythonic way java end struggling currently i problem figure store objects indexed coordinates iterable i could create dimensional array objects i afraid would take lot memory and i would iterate indexes every time i want occassionally get objects in python i would use dictionary tuples keys looks like thing possible java eg class bar pass bar bar bar bar etc foo bar bar x foovalues dosomething,1 check pylasem yes says mathml rendering library also supports subset latex lasem via gobjectintrospection,i trying read text latex formatting render using pygame i novice pygame help appreciated i looked glyph package the problem i would rewrite txt files glyph formatting useful if i try define macros i would essentially build latex translator both options seem practical considering number text files i,1 if set correct content type worry rendering browser return unless appropriate try responseheaders contenttype applicationfoo whatever correct mime type content return content,i trying use cherrypy simple website never done python web programming i stuck trying allow download file dynamically created i create file return handler call servefileobj file either case contents file simply rendered screen rather downloaded does cherrypy offer useful methods how accomplished,2 while snippet works escapes repr works treat bytestrings text decode first operate later data utest ä å›å¼åºä‡ test test ä å›å¼åºä‡ testdecode utf splitdata datasplitu,i use builtin split function problem data test ä å›å¼åºä‡ test splitteddata datasplit print splitteddata test xcxxcxbxcxbcxcxbaxcx test why happen what i prevent python,1 according python docs zipfilewrite method supports second argument destination name ie name archive try tto use like root dirs files oswalk a folder f files fname ospathjoinroot f newpath ospathnormpathfnamereplace a folder myzipwritefname newpath,basically i need copy files certain type within folder zipfile highest level within folder for example i folder a folder within folder load png files i want copy files existing zipfile currently i get folder copy well i end zipfilea folderlots pngs rather zipfilelots pngs the code i using move files folder root dirs files oswalk a folder f files fname ospathjoinroot f myzipwritefname another quick thing i ask another question would go deleting folder within zipfile hopefully clear enough thanks lot,1 personnaly i use ospathexpanduser find good place caches quite common unix environnement current user configcache saved home directory use directory name starting dot making hidden directory i would something like directory ospathjoinospathexpanduser mycache as modification date distant file use urlib import urllib u urlliburlopenhttpwwwgooglecom uinfogetlastmodified however check http server provides lastmodified http header coherent value this always case,my pygtk program editor xmlbased documents reference documents possibly online may turn reference documents when i load file references resolved documents loaded already asynchronously however process repeats every time i start editor i want local caching save bandwidth time user server hosting referenced documents are typical ways done my idea far would get path cache directory somehow platformindependent any ideas put file named mdurl if cache file already existing older cachepolicyage take otherwise use http urllib check modified since downloaded,2 that purely output get strrepr calling repr string the xc etc actual way stored when print still data test ä å›å¼åºä‡ test data test xcxxcxbxcxbcxcxbaxcx test print data test ä å›å¼åºä‡ test liststr listrepr use representation string access item inside still correct splitteddata datasplit splitteddata test xcxxcxbxcxbcxcxbaxcx test print splitteddata ä å›å¼åºä‡,i use builtin split function problem data test ä å›å¼åºä‡ test splitteddata datasplit print splitteddata test xcxxcxbxcxbcxcxbaxcx test why happen what i prevent python,3 a straightforward workaround add next homepyo extra file contains home import you could call foopy could call homewsgi could call thequickbrownfoxatethelazydog wanted so problems extension py matter,i trying start apache modwsgi i strong restriction put source py files onto server i compile first put pyo files onto server that i apache conf loadmodule wsgimodule modulesmodwsgiso wsgipythonpath varwwwroot wsgipythonoptimize wsgiscriptalias home varwwwroothomepyo but modwsgi raises error cut apache error log failed parse wsgi script file varwwwroothomepyo exception occurred processing wsgi script varwwwroothomepyo file varwwwroothomepyo line mxf syntaxerror invalid syntax i tried google find answer modwsgi work precompiled python code,1 i think standard python unless write function numpy httpdocsscipyorgdocnumpyreferencegeneratednumpyrootshtml,is possible calculate n complex roots given number using python i shortly checked looks like python gives wrongincomplete answers j produces j proper roots complex numbers every nonzero number n different complex number nth roots is possible python,3 follow steps read file line line line following steps split line using split separator cast first element list step int keep second element string parse third value eg using slices make datetime object,in application i generated number values three columns type int str datetime see example values stored flat file commaseparated strings furthermore i store file containing type values see now i use information cast values flat file correct data type python is possible i need stuff data file idvaluedate b c type file idtype int valuetype str datetype datetimedatetime,1 i deal similar situation recent program convert many fields i used list tuples one element tuples conversion function use sometimes int float sometimes simple lambda sometimes name function defined elsewhere,in application i generated number values three columns type int str datetime see example values stored flat file commaseparated strings furthermore i store file containing type values see now i use information cast values flat file correct data type python is possible i need stuff data file idvaluedate b c type file idtype int valuetype str datetype datetimedatetime,1 you could give exactly hour close example came app i debuging cron description description want done url scriptpathgoeshere schedule every minutes synchronized timezone americanewyork below screenshot logs app gets traffic right entries cron entry edit just reread docs well maybe might better schedule every minutes,i need run task every hour hour every day week seem find example app engine docs there example running ask every hour fit start hour depends deploy application that i deploy pm cron scripts get executed instead so far way looks like would work different cron entries one specific hour day set run day specific time does anyone know anything would let use schedule like every hour even every day,2 i solved problem downgrading ipython version,i install ipython run paster shell devini command paster open standard python console how i make run ipython,1 yes make two bindings,i noticed bind keys tkinter python winxp binds case sensitive letter characters in words binding controlo work press controlo caps lock active does mean i need write two bindings case insensitive key combination letter characters or way solve thanks help,1 the problem line return qmyfunc argsy specifically argsy part what want argsy notice comma argsy the issue python tuples created commas parentheses look b print typea type tuple print b typeb type int,after reading occurs quad quadrature interchangeable atleast syntaxwise strangely seem scipyintegrate import quad q scipyintegrate import quadrature q def myfuncx return x def integr return qmyfunc print integr def myfuncx return x def integry return qmyfunc argsy return qmyfunc argsy print integr example runs fine quad quadrature i end traceback recent call last file testpy line module print integr file testpy line integr return qmyfunc argsy file usrlibpythondistpackagesscipyintegratequadraturepy line quadrature newval fixedquadvfunc b n file usrlibpythondistpackagesscipyintegratequadraturepy line fixedquad return basumwfuncyargs none file usrlibpythondistpackagesscipyintegratequadraturepy line vfunc return funcx args typeerror myfunc argument must sequence int i switch args tuple list cf commented line integr even though documentation says tuple it seemed interpreter complains right is intended or i something wrong in end i like able choose integration methods afterwards without change much rest code actually i really get choose two i understand difference gaussian quadrature adaptive quadrature i know adaptive gaussian quadrature supposed mean number nodes adapted,2 try eval eval int type int but sure give eval could dangerous,in python given string int i get type int using getattrcurrentmodule int work,1 with sort thing expecting limited set types use dictionary map names actual type typedict int int str str list list typedict int,in python given string int i get type int using getattrcurrentmodule int work,2 if want use eval store mapping string type dict look typemap dict type int float complex typemaptypename type userinput rawinputstrip int typemapgetuserinput type int userinput rawinputstrip monkeybutter typemapgetuserinput,in python given string int i get type int using getattrcurrentmodule int work,1 int part namespace current module part builtins namespace so would run getattr builtins to verify type check whether instance type since types derived getattrbuiltins int type int foo getattrbuiltins int isinstancefoo type true,in python given string int i get type int using getattrcurrentmodule int work,3 something like outputfile open outputplist w outputfilewritepproductversion outputfileclose,i save output i get programas variable instead printed import plistlib time import plistlib pl pplreadplistrestoreplist print pproducttypei want outputted variable x instead python printing print pproductversion print pproductbuildversion,1 is trying import math c x c c z xx w yy print mathsqrtzw,made function uses subtraction two values stored two lists follows import sysos import math c c x c c z xx w yy answer sqrtz w print answer my error typeerror unsupported operand types list list how i get error occurs due subtraction possible two lists ie lines dd cc is builtin function math module similar sqrt might use subtract lists,1 you subtract whole list like even one item list you one time you could loop map here map import operatorsub mapoperatorsub c mapoperatorsub c,made function uses subtraction two values stored two lists follows import sysos import math c c x c c z xx w yy answer sqrtz w print answer my error typeerror unsupported operand types list list how i get error occurs due subtraction possible two lists ie lines dd cc is builtin function math module similar sqrt might use subtract lists,1 you using one element lists if want perform calculation specifically remove braces i assume actually multivalued lists a reasonable solution combine map applies function element one lists well functions operator module turn many python operators like functions first well set lists import random randomrandrange ignored range randomrandrange ignored range c randomrandrange ignored range c randomrandrange ignored range c c next replace operations map call corresponding operator import operator x mapoperatorsub c mapoperatorsub c z mapoperatormul x x w mapoperatormul import math answer mapmathsqrt mapoperatoradd z w print answer,made function uses subtraction two values stored two lists follows import sysos import math c c x c c z xx w yy answer sqrtz w print answer my error typeerror unsupported operand types list list how i get error occurs due subtraction possible two lists ie lines dd cc is builtin function math module similar sqrt might use subtract lists,1 problem pyexe i narrowed impfindmodule call line pyexemfpy the suds module imports ok i see syspath import imp impfindmodule suds syspath reports module found opening followup question specific imp module,attempting build exe using pyexe python setuppy pyexe receiving error importerror no module named suds i done research suggests modules specifically included setuppy here setuppy distutilscore import setup import pyexe setupconsole script reportpy options pyexe bundlefiles includes suds i tried including package names sudsclient sudstransporthttps error persists pyexe seems several module specific requirements found i see suds specific documentation found information pyexe finds necessary modules the output cpythonpython pyexemf pathtoreportpy path cpythonlibsitepackagespyyamlpywinegg cpythonlibsitepackagesprogressbarpyegg cpythonlibsitepackagessqlalchemypywinegg cpythonlibsitepackagessoappypyegg cpythonlibsitepackageswstoolspyegg cpythonlibsitepackagesfpconstpyegg cpythonlibsitepackagespythonntlmpyegg cpythonlibsitepackagesdjangopyegg cpythonlibsitepackagespyodbcpywinegg cpythonlibsitepackagessudspyegg cwindowssystempythonzip cpythondlls cpythonlib cpythonlibplatwin cpythonliblibtk cpython cpythonlibsitepackages runscript reportpy loadmodule main fp reportpy loadmodule binascii none none loadmodule module binascii importerror no module named suds importerror no module named suds loadmodule module main reportpy name file main reportpy binascii missing modules sudsclient imported main sudstransporthttps imported main has anyone successfully built executable pyexe script using suds packages os windows bit python suds pyexe,1 the optionmenu widget nothing convenience class creates menubutton associated menu you get menu via menu attribute the trick knowing menu items nothing setting value associated variable here example import tkinter tk class sampleapptktk def initself args kwargs tktkinitself args kwargs selfomvariable tkstringvarself b tkbuttonself textcolors width commandselfusecolors b tkbuttonself textsizes width commandselfusesizes selfom tkoptionmenuself selfomvariable selfomconfigurewidth selfusecolors bpacksideleft bpacksideleft selfompacksideleft fillx expandtrue def resetoptionmenuself options indexnone reset values option menu index given set value menu option given index menu selfommenu menudelete end string options menuaddcommandlabelstring commandlambda valuestring selfomvariablesetvalue index none selfomvariablesetoptionsindex def usecolorsself switch option menu display colors selfresetoptionmenuredorangegreenblue def usesizesself switch option menu display sizes selfresetoptionmenuxsmall small medium large name main app sampleapp appmainloop,problem following i several files i made drop menu namesthe next thing i need option menu changed whenever file name selected show data specific file optionto clearmy question make option menu change choice drop selectedthanks help,2 as i understand already parsed file need get right type so let say id type value three strings contain values file note type contain int mdash example mdash type int def convertvalue type import importlib try check builtin type module importlibimportmodule builtin cls getattrmodule type except attributeerror separate module class module type typersplit module importlibimportmodulemodule cls getattrmodule type return clsvalue then use like value convert int unfortunately datetime doesnt work though simply initialized string representation,in application i generated number values three columns type int str datetime see example values stored flat file commaseparated strings furthermore i store file containing type values see now i use information cast values flat file correct data type python is possible i need stuff data file idvaluedate b c type file idtype int valuetype str datetype datetimedatetime,1 your types file simpler idint valuestr datedatetimedatetime then main program import datetime def convertdatetimetext return datetimedatetimestrptimetext ymd hms datatypes int int str str datetimedatetime convertdatetime fields line open exampletypestxt readlines key val linestripsplit fieldskey val datafile open actualdatatxt fieldinfo datafilereadlinestrip n split values store line datafilereadlines row element enumeratelinestripsplit elementtype fieldsfieldinfoi get int str datetime convert datatypeselementtype rowappendconvertelement valuesappendrow show working row values print row,in application i generated number values three columns type int str datetime see example values stored flat file commaseparated strings furthermore i store file containing type values see now i use information cast values flat file correct data type python is possible i need stuff data file idvaluedate b c type file idtype int valuetype str datetype datetimedatetime,1 modwsgi work pyo files i ran exact problem banged head wall couple hours trying figure modwsgi work without python source code regular old py format,i trying start apache modwsgi i strong restriction put source py files onto server i compile first put pyo files onto server that i apache conf loadmodule wsgimodule modulesmodwsgiso wsgipythonpath varwwwroot wsgipythonoptimize wsgiscriptalias home varwwwroothomepyo but modwsgi raises error cut apache error log failed parse wsgi script file varwwwroothomepyo exception occurred processing wsgi script varwwwroothomepyo file varwwwroothomepyo line mxf syntaxerror invalid syntax i tried google find answer modwsgi work precompiled python code,1 apparently pyscripter capability,i script i want debug classes functions i want test interactively interpreter window pyscripter i like able debug mode is possible,1 nadia regex matches alphanumeric characters value parameter that means fails parse least two fields namely uri qop according rfc uri field duplicate string request line ie first line http request and qop fails parse correctly value authint due nonalphanumeric this modified regex allows uri value contain anything space qoute comma that probably permissive needs cause problems correctly formed http requests reg recompile w bonus tip from fairly straight forward convert example code rfc python using python md api mdinit becomes mdnew mdupdate becomes mupdate mdfinal becomes mdigest,i need take header like authorization digest qopchap realmtestrealmhostcom usernamefoobear responsefaeacef cnonceccccebaffefe and parse using python protocol digest qop chap realm testrealmhostcom username foobear response faeacef cnonce ccccebaffefe is library something i could look inspiration i google app engine i sure pyparsing library available maybe i could include app best solution currently i creating myheaderparser object using reduce header string it working fragile brilliant solution nadia import reg recompile w w digest realmstackoverflowcom usernamekixx print strdictregfindalls,1 in first iteration reading file completely in subsequent iterations entire x trend loop therefore skipped how something like import csv def readcsv opendtrendcsv rb f trend csvreaderf delimiter temp row row trend return temp def gettdata pos return apos data apos now mydata readcsv gettmydata gettmydata,i function called gettint returns series upon every call it works fine i write like print gett print gett i try automate loop like range print getta it works fine first value i get following output series others empty i new python might naive any help highly appreciated thank ps gett function trend filedtrendcsv r def gettpos x trend temp xsplit temp temp tappendtemp temp apos tempappendapos temp return,2 you opening file outside function definition trying read global file object time function run after first time running function read pointer end file read nothing either read file time function seek start keep global reopen make local almost certainly preferably unless huge file memory issue read whole file list operate list,i function called gettint returns series upon every call it works fine i write like print gett print gett i try automate loop like range print getta it works fine first value i get following output series others empty i new python might naive any help highly appreciated thank ps gett function trend filedtrendcsv r def gettpos x trend temp xsplit temp temp tappendtemp temp apos tempappendapos temp return,2 you searching path smallest you need save check length path like def aheads path pathlen heads path return float inf impossible kill heads heads return float inf pathlen pathlen pathappenda heads print path return pathlen heads return minaheads path pathlen bheads path pathlen def bheads path pathlen heads path return float inf impossible kill heads heads return float inf pathlen pathlen pathappendb heads print path return pathlen heads return minaheads path pathlen bheads path pathlen a gives right answer you global variable store path instead simple printing,two guns a b need used kill monsterwith n heads when gun a used cuts heads monster dieno heads grow heads when gun b used cuts heads monster die grows heads if n heads gun cut case gun cannot used and n monster hunter dies it required problem find possible kill monster whether hunter dies trying kill monster shortest path i written following python program solve problem def aheads path heads path return impossible kill heads pathappenda heads print path path return monster dies heads return both monster human die heads aheads pathmonster dies bheads path monster dies return monster dies def bheads path heads path return impossible kill print b path heads heads pathappendb heads print path path return monster dies heads return both monster human die heads aheads pathmonster dies bheads path monster dies return monster dies print a sample dataprovided question for n shortest path aab where program i gone wrong better method go problem,1 underneath windows users home homepath equivalent linux mac underneath folder desktop like mac python automatically converts homepath windows mac command work box mac windows on linux bit trickier first understand linux box running may desktop user desktop folder if window manager may may follow desktop paradigm the wikipedia entry window managers goes far detail including comparisons several popular x window managers sublinks your best bet would step back ask i wantneed users desktop folder is create shortcut install you likely better installation writer utility nsis handling details if file storage even temporary may want rethink design or looking something case file system search may way go instead brittle single folder check like things depends want accomplish as eol noted comment windows slightly trickier first appears his link complete article windows desktop folder details localization desktop folder this important builders international applications take account either using automatic localization built toolset avoiding things use,is way obtaining desktop directory path crossplatform way ideally using standard modules python my current mac os x windows solution check system running python sysplatform following mac os x handled ospathjoinospathexpanduser desktop windows use nonstandard module wincom ctypesdependent module winpaths standard alternative and linux i would happy solution works mac os x windows linux,3 it easiest use vmin vmax arguments imshow assuming working image data rather subclassing matplotlibcolorsnormalize eg import numpy np import matplotlibpyplot plt data nprandomrandom make data range data data pltimshowdata vmin vmax pltcolorbar pltshow,i want set middle point colormap ie data goes want zero middle i think way subclassing normalize using norm find example clear exactly implement,3 take look ressource pages django packages model translation django packages internationalization django wiki model internationalization,i using django quite time i ask question which multilingual database backend i use i used djangomultilingual django djangomultilingualng django i add look djangonani django quite problems no modeladmin api support i cannot modify translatedfields save method since object created postsignal i people overthere could help find way handle multilingual websites i like way multilingual multilingualng nani handle languages admin tabs,1 see aix meant mymodel import universe use ctrl universeultimateanswer you asked add comment ignore error you also add model forced builtin prompting analyzis runtime said gave error,i using eclipseaptana python development i issue python path config autocomplete works fine everything however i following problem when i constant one classes i try access eclipse complains undefined variable import constant eg class universeobject ultimateanswer different module edit import universe bigbangmodels import universe print universeultimateanswer universeultimateanswer triggers warning additionally autocomplete works fine i type universex i get constants proposed it urgent issue however tends become annoying might make ignore actual errors any idea make eclipse behave one edit this happens importing class another module edit in case clear code works warning i tried replicated projects mine eclipse aptana pydev edit as comments bellow probably bug pydev submitted waiting,1 use etime find elapsed time process you modify awk command check time greater mins ps u xxxxxx rssetimecommand the format elapsed time ddhhmmss this means time could even you use awk parse time format convert seconds once seconds check minutes add running total rss here sample script ps u xxxxxx rssetimecommand grep v peruser grep v rss sed g awk splitarr split time len fori arr len secsarrlenarrlen convert seconds iflen secssecssubstrarrlenlengtharrlen ifsecs check minutes print print process sum endprint sumsum,my host offering limited amount ram websites i would like monitor memory consumption running script cron i made command ps u xxxxxx rsscommand grep v peruser awk sum end print sum but way host calculating memory particularity it ignores processes runs less minutes do know command python script show total used memory ignoring short lived processes,1 match list tuples the correct way iterating matches refindallr answercountdscommentcountd x posts comments matches posts comments intposts intpostsintcomments the conversion string integer fine,i want change contents list tuples returned findall function and i sure whether i could change elements string integer like and error always shows i need value ntuple match refindallr answercountdscommentcountd x print match tuples match posts comments tuples posts comments intposts intpostsintcomments error print match,1 check pyinstaller you give path python script analyzes package imports extracting binary files needed placing archive i used fairly complex python program worked,i want create simple mac application bundle calls simple python script i want python is easy way i tried use pyapp fails somehow eg setuptools import setup setupappfoopy setuprequirespyapp gives systemexit traceback recent call last usersazipython console module systemlibraryframeworkspythonframeworkversionslibpythondistutilscorepyc setupattrs ok distparsecommandline except distutilsargerror msg raise systemexit genusagedistscriptname nerror msg debug systemexit usage ipython globalopts cmd cmdopts cmd cmdopts ipython help cmd cmd ipython helpcommands ipython cmd help error commands supplied type exit quit exit ipython exit quit unconditionally i also tried import pyappbuildapp pyappbuildapppyappfoopy also work typeerror dist must distribution instance i really sure use pyappbuildapppyapp also really found much examples documentation maybe setuptoolspyapp anyway overkill use case i want create simple empty app bundle copy python script configure infoplist way calls python script,2 extracted suds egg cpythonlibsitepackagessudspyegg created cpythonlibsitepackagessuds directory contains source files module found impfindmodule suds none cpythonlibsitepackagessuds pyexe build completes successfully it appears impfindmodule requires directory module source files exist egg file recognized,having trouble pyexe importing suds module narrowed following impfindmodule suds syspath traceback recent call last file stdin line module importerror no module named suds however simple import works fine import suds sudsversion here syspath shows suds cpythonlibsitepackagessudspyegg pprintpprintsyspath cpythonlibsitepackagespyyamlpywinegg cpythonlibsitepackagesprogressbarpyegg cpythonlibsitepackagessqlalchemypywinegg cpythonlibsitepackagessoappypyegg cpythonlibsitepackageswstoolspyegg cpythonlibsitepackagesfpconstpyegg cpythonlibsitepackagespythonntlmpyegg cpythonlibsitepackagesdjangopyegg cpythonlibsitepackagespyodbcpywinegg cpythonlibsitepackagessudspyegg cwindowssystempythonzip cpythondlls cpythonlib cpythonlibplatwin cpythonliblibtk cpython cpythonlibsitepackages confirmed pyexe installed cpythonlibsitepackagesls l py rwrwrw beargle pyexepyegginfo pyexe total rwrwrw beargle initpy rwrwrw beargle initpyc rwrwrw beargle initpyo rwrwrw beargle bootcomserverspy rwrwrw beargle bootcomserverspyc rwrwrw beargle bootcomserverspyo rwrwrw beargle bootcommonpy rwrwrw beargle bootcommonpyc rwrwrw beargle bootcommonpyo rwrwrw beargle bootctypescomserverpy rwrwrw beargle bootctypescomserverpyc rwrwrw beargle bootctypescomserverpyo rwrwrw beargle bootservicepy rwrwrw beargle bootservicepyc rwrwrw beargle bootservicepyo rwrwrw beargle buildexepy rwrwrw beargle buildexepyc rwrwrw beargle buildexepyo rwrwrw beargle mfpy rwrwrw beargle mfpyc rwrwrw beargle mfpyo rwrwrw beargle pyexeutilpyd drwrwrw beargle resources rwxrwxrwx beargle runexe rwrwrw beargle runctypesdlldll rwrwrw beargle rundlldll rwrwrw beargle runisapidll rwxrwxrwx beargle runwexe drwrwrw beargle samples why impfindmodule locating suds module,3 the problem line posts comments tuples here tuples actually single tuple containing two strings need iterate you probably want something like matches refindall posts comments matches,i want change contents list tuples returned findall function and i sure whether i could change elements string integer like and error always shows i need value ntuple match refindallr answercountdscommentcountd x print match tuples match posts comments tuples posts comments intposts intpostsintcomments error print match,1 one way pass ip address request method override requesthandlerdecoderequestcontent decoderequestcontent returns xml string example xml version methodcall methodnamegetworkunitmethodname params param valueintintvalue param param valuestringwindowsstringvalue param param valuestringbitstringvalue param params methodcall just slip another parameter class hackyrequesthandlersimplexmlrpcrequesthandler def initself req addr server selfclientip selfclientport addr simplexmlrpcrequesthandlerinitself req addr server def decoderequestcontentself data data simplexmlrpcrequesthandlerdecoderequestcontentself data xmldomminidom import parsestring doc parsestringdata ps docgetelementsbytagname params pdoc parsestring paramvalue stringsstring valueparam selfclientip p pdocfirstchildclonenodetrue psinsertbeforep psfirstchild return doctoxml update method signatures accordingly,i simplexmlrpcserver server python how i get ip address client request handler this information appears log however i sure access information within request handler,1 try scikitslearn implementation httpscikitlearnsourceforgenetmodulesgeneratedscikitslearnclusterkmeanshtml,i looking python implementation kmeans algorithm examples cluster cache database coordinates,1 you post search form search view display results page,i basehtml pages inherit inside defines header contains search box the code search box thing along lines requestmethod post searchbutton requestpost location requestpost location do something location redirect another page return httpresponseredirect lostandfound i couple questions first i ensure code sat views without rewriting every time dry also i redirect another page pass variable location along httpresponseredirect right way sure,1 this exactly i wanted works fine usrbinpython import sys assert lensysargv apppath sysargv import os ospath assert ospathsplitextapppath app osmakedirsapppath contentsmacos version bundlename test bundleidentifier orgtesttest f openapppath contentsinfoplist w fwritexml version encodingutf doctype plist public appledtd plist en httpwwwapplecomdtdspropertylistdtd plist version dict keycfbundledevelopmentregionkey stringenglishstring keycfbundleexecutablekey stringmainpystring keycfbundlegetinfostringkey stringsstring keycfbundleiconfilekey stringappicnsstring keycfbundleidentifierkey stringsstring keycfbundleinfodictionaryversionkey stringstring keycfbundlenamekey stringsstring keycfbundlepackagetypekey stringapplstring keycfbundleshortversionstringkey stringsstring keycfbundlesignaturekey stringstring keycfbundleversionkey stringsstring keynsapplescriptenabledkey stringyesstring keynsmainnibfilekey stringmainmenustring keynsprincipalclasskey stringnsapplicationstring dict plist bundlename version bundleidentifier bundlename bundlename version version fclose f openapppath contentspkginfo w fwriteappl fclose f openapppath contentsmacosmainpy w fwriteusrbinpython print hi fclose import stat oldmode osstatapppath contentsmacosmainpystmode oschmodapppath contentsmacosmainpy oldmode statsixusr statsixgrp statsixoth,i want create simple mac application bundle calls simple python script i want python is easy way i tried use pyapp fails somehow eg setuptools import setup setupappfoopy setuprequirespyapp gives systemexit traceback recent call last usersazipython console module systemlibraryframeworkspythonframeworkversionslibpythondistutilscorepyc setupattrs ok distparsecommandline except distutilsargerror msg raise systemexit genusagedistscriptname nerror msg debug systemexit usage ipython globalopts cmd cmdopts cmd cmdopts ipython help cmd cmd ipython helpcommands ipython cmd help error commands supplied type exit quit exit ipython exit quit unconditionally i also tried import pyappbuildapp pyappbuildapppyappfoopy also work typeerror dist must distribution instance i really sure use pyappbuildapppyapp also really found much examples documentation maybe setuptoolspyapp anyway overkill use case i want create simple empty app bundle copy python script configure infoplist way calls python script,3 appending python lists well optimized operation cpython python allocate memory element incrementally growing arrays pointers objects list so switching cython help much you use c containers within cython follows libcmath cimport log libcpplist cimport list cpplist def mainint cdef cpplistint temp x ranget x temppushbackx cdef int n tempsize cdef list outputlist n rangen outputlisti tempfront temppopfront return outputlist you test speeds things maybe gain much speed another way use numpy arrays here cython good optimizing code so live numpy array return value main consider replace construction filling outputlist cython code allocating filling numpy array for information see httpdocscythonorgsrctutorialnumpyhtml ask need help update code bit faster avoid method lookup loops libcmath cimport log libcpplist cimport list cpplist def mainint cdef cpplistint temp pushback temppushback x ranget x pushbackx cdef int n tempsize cdef list outputlist n front tempfront popfront temppopfront rangen outputlisti front popfront return outputlist,i timecritical model i wrote cython the main function cython extension one loop according cython profiler shows amount python calls shades yellow yellow part currently i appending python list i output python object i calling cython function python script this basic idea function rest superfluous i tested every part function append operation bottleneck libcmath cimport log def mainsome args cdef vars cdef list outputlist nb vars declared types x ranget cythonic stuff uses cimported log condition true outputlistappendx yellow line main loop return outputlist return python object python script calls main unfortunately i know length output arraylistvector whatever i end using however i could set i end resizing line python code i like get major speed boost without setting output array length i gladly toss hope holding back i also tried going c cython use c data structures vector queue etc removes ability nicely cimport log i see cython documentationwiki write shim module use purec functions c cython i idea i find anything go anyway i welcome suggestions adhere question what best way build listarrayvector unknown size cython or clear alternative settling knownlength iterable object makes moot unknownlength problem update the c containers show speed increase item assignment item assignment show speed increase appending lists numpy arrays the best method would use c containers also able cimport purec functionsthis would prevent slowdown look beyond libcmath quick log function,1 when debug set false django renders html template instead debug stacktrace thing it might http found exception tries render html template found tries html internal error it problem configuration,i see django looks html debug false what could problem,1 python r apr gcc linux type help copyright credits license information teststr i red car i drove newjersey turnpike when i took exit lake i drove car muddy roads turned red car brown driving newjersey turnpike confusing teststrcount newjersey turnpike,edited question based response i list strings text file i want count occurrences strings another text file here example strings i file red car no lake newjersey turnpike here text file i want search strings mentioned i red car i drove newjersey turnpike when i took exit lake i drove car muddy roads turned red car brown driving newjersey turnpike confusing the answer i looking newjersey turnpike no lake red car how i program python thanks lot help here i tried far inputfilepath r inputfiletxt phrasepath r phrasewordstxt stringcountpath r stringcounttxt f openphrasepath r lines freadlines keys line lines keyappendline phraseword mapstringstripmapstrlowerkeys fclose dict key phrasewords dictkey fopeninputfilepath r lines mapstringstripmapstrlowerfreadlines w lines try dictw except keyerror pass fclose the strings getting assigned properly answer isnt right phrasewords red car lake newjersey turnpike lines red car drove newjersey turnpike took exit lake drove car muddy roads turned red car brown driving newjersey turnpike confusing dict red car newjersery turnpike lake,1 you need load dump try data jsonloadsreturnfromwebservice jsondumpsdata sortkeystrue indent to add bit detail receiving string asking json library dump string that make great deal sense what need first put data meaningful container by calling loads take string value return parse actual python dictionary then pass data dumps outputs string using requested formatting,after contacting server i get following strings response kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null stored type str script now i try decode using jsondumpsmystring sortkeystrue indent i get kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null really like shadyabhiarchlinux echo kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null python mjsontool data commentkarma created createdutc hasmail null hasmodmail null id zf isgold false ismod false linkkarma name shadyabhi kind shadyabhiarchlinux so going wrong,1 you things backwards if want convert string data structure need use jsonloadsthestring jsondumps converting data structure json encoded string,after contacting server i get following strings response kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null stored type str script now i try decode using jsondumpsmystring sortkeystrue indent i get kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null really like shadyabhiarchlinux echo kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null python mjsontool data commentkarma created createdutc hasmail null hasmodmail null id zf isgold false ismod false linkkarma name shadyabhi kind shadyabhiarchlinux so going wrong,1 you supposed dump object like dictionary becomes string way round see use jsonloads instead,after contacting server i get following strings response kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null stored type str script now i try decode using jsondumpsmystring sortkeystrue indent i get kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null really like shadyabhiarchlinux echo kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null python mjsontool data commentkarma created createdutc hasmail null hasmodmail null id zf isgold false ismod false linkkarma name shadyabhi kind shadyabhiarchlinux so going wrong,1 you want jsonloads the dumps method going way dumping object json string,after contacting server i get following strings response kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null stored type str script now i try decode using jsondumpsmystring sortkeystrue indent i get kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null really like shadyabhiarchlinux echo kind data hasmail null name shadyabhi created createdutc linkkarma commentkarma isgold false ismod false id zf hasmodmail null python mjsontool data commentkarma created createdutc hasmail null hasmodmail null id zf isgold false ismod false linkkarma name shadyabhi kind shadyabhiarchlinux so going wrong,1 there also web interface could access could presumably write python client query web interface get lesk vector values you find web interfaces httpmarimbadumnedu httptaliskerdumnedu good luck ted,i would like find relatedness similarity two words using python the hso hirst stonge lesk banerjee pedersen vector patwardhan algorithms implemented perl cant seem find python nltk lib i need use python part larger team project python any leads,2 python joinc c filename cisalpha cisdigit c rstrip accepts unicode characters removes line breaks etc example filename uadnbla ã§ gives adblaã§ edit strisalnum alphanumeric one step – comment queueoverflow danodonovan hinted keeping dot included keepcharacters joinc c filename cisalnum c keepcharactersrstrip,i want create sanesafe filename ie somewhat readable strange characters etc random unicode string mich might contain anything it matter wether function cocoa objc python etc of course might infinite many characters might strange thus really solution blacklist add list time i could whitelist however i really know define azaz start i also want accept unicode chars displayed normal way,3 if modify methods class utilobject def methodself return method none def methodself return method none def methodself return method def callmethodself methodfunc return methodfuncself name main u util name dictvalues listvalues ucallmethodutilmethod better print umethod and change class utilobject def methodself return method def methodself return method def methodself return method def callmethodself methodfunc results methodfuncself name list dict none obj results isinstanceobj string name obj elif isinstanceobj list list obj elif isinstacneobj dict dict obj return name dict list name main u util name dictvalues listvalues ucallmethodutilmethod,i need handle bunch similar exclusively called function single method eg maybe great example class utilobject def methodself return method def methodself return method def methodself return method def callmethodself methodfunc methodfuncname method name dictvalues selfmethodfunc methodfuncname method name listvalues selfmethodfunc methodfuncname method listvalues name dictvalues selfmethodfunc how best manage return optional interdependent values return name dictvalues listvalues name main u util name dictvalues listvalues ucallmethodutilmethod the callmethod return i trying visualize i got bunch exclusive subcalls i need make i need massage something returned would easier stuff util class member variables and whoever implements ucallmethod simply need know look before anyone complains design first place mine i simply need expose consistent api interested hear opinons handle return like it easily normalized though missing trailing return value pass runtime leading one any tips would great thank,1 why use attribute names keys dictionary class structmydictdict def getattrself name try return selfname except keyerror e raise attributeerrore def setattrself name value selfname value you initialize named arguments list tuples dictionary individual attribute assignments eg nautical structmydictleft port right starboard named args nautical structmydictleftportrightstarboard dictionary nautical structmydictleftportrightstarboard tuples list nautical structmydict fields tbd nauticalleft port nauticalright starboard x nautical nautical nautical nautical print xleftxright alternatively instead raising attribute error return none unknown values a trick used webpy storage class,is possible create object dictionary python way key attribute object something like dict name oscar lastname reyes age e employee dict print ename oscar print eage i think would pretty much inverse question python dictionary object fields,2 if need group several values often approach using dictionary ie changing code def methodself return name method list something possible python use object instead dictionary make code nicer read class bunch def initself kwargs selfdictupdatekwargs def methodself return bunchnamemethod list caller use resultname instead resultname another option recently got standardized python namedtuple,i need handle bunch similar exclusively called function single method eg maybe great example class utilobject def methodself return method def methodself return method def methodself return method def callmethodself methodfunc methodfuncname method name dictvalues selfmethodfunc methodfuncname method name listvalues selfmethodfunc methodfuncname method listvalues name dictvalues selfmethodfunc how best manage return optional interdependent values return name dictvalues listvalues name main u util name dictvalues listvalues ucallmethodutilmethod the callmethod return i trying visualize i got bunch exclusive subcalls i need make i need massage something returned would easier stuff util class member variables and whoever implements ucallmethod simply need know look before anyone complains design first place mine i simply need expose consistent api interested hear opinons handle return like it easily normalized though missing trailing return value pass runtime leading one any tips would great thank,1 your commit missing parens cxncommit should cxncommit run interpreter cxncommit without parens simply returns reference commit method something like conncommit builtin method commit connection object xcfec,i cant get insert work code i numpy mysql work fine but errors running code mysql gives errors using python pyodbc winx p nparange print p def prow fseries rowp series seriestolist ss series rowpappend rowpextendss print len rowp print rowp print typerowp insql insert into testt values print insql csrexecutemanyinsqlrowp csrexecuteinsql print cxncommit prow foo p mysql create table id int default null t float default null t decimal default null t float default null engineinnodb default charsetlatin this print statements give type list insert into testt values using insert into testt values mysql shell works fine alot redundant code right the idea use executemany i cant simple code work,1 namedtuple pythonic alternative returning nameless tuples httpdocspythonorglibrarycollectionshtmlcollectionsnamedtuple this way caller need extract tuple members needs read,i need handle bunch similar exclusively called function single method eg maybe great example class utilobject def methodself return method def methodself return method def methodself return method def callmethodself methodfunc methodfuncname method name dictvalues selfmethodfunc methodfuncname method name listvalues selfmethodfunc methodfuncname method listvalues name dictvalues selfmethodfunc how best manage return optional interdependent values return name dictvalues listvalues name main u util name dictvalues listvalues ucallmethodutilmethod the callmethod return i trying visualize i got bunch exclusive subcalls i need make i need massage something returned would easier stuff util class member variables and whoever implements ucallmethod simply need know look before anyone complains design first place mine i simply need expose consistent api interested hear opinons handle return like it easily normalized though missing trailing return value pass runtime leading one any tips would great thank,2 looking pytest code markpy experimentation shows following seems work pytest k slow long using collectonly option speeds experimentation,with pytest one mark tests using decorator pytestmarkslow def someslowtest pass then command line one tell pytest skip tests marked slow pytest kslow if i additional tag pytestmarklong def somelongtest pass i would like able skip long and slow tests i tried pytest kslow klong pytest kslowlong and neither seems work at command line i tell pytest skip slow and long tests,3 what happens print prestoreramdisks you probably get value simply prestoreramdisksupdate if plist may contain key called restoreramdisks use instead pgetrestoreramdisks dictupdatenonegetupdate none this get value available otherwise evaluate none,how i use working code import plistlib time import zipfile contextlib import closing import os closingzipfilezipfilefwzip zfile info zfileinfolist infofilenameendswith restoreplist zfileextractinfo import plistlib pl pplreadplistrestoreplist print pproducttype print pproductversion print pproductbuildversion outputfile open outputtxt w outputfilewrite pproductversion outputfilewrite outputfilewrite pproducttype outputfilewrite outputfilewrite pproductbuildversion outputfileclose use write string update key plist seeing update key another set keys called restoreramdisks keyrestoreramdiskskeythis key update key dict keyupdatekeyhere update key i talking stringdmgstringthis i want python spit keyuserkey stringdmgstring dict to clarify i want use method time get info update key the part confuses update key underneath another key called restoreramdisks i want program spit dmg asked locate update key,1 you either things python sense java anyway by convention names prefixed underscore considered private accessed outside implementation nothing python enforces convention it considered warning messing implementation detail may change without warning future version code,is way translate java code python class foo final static private listthingy thingies immutablelistofthing thing thing eg thingies immutable private list thingy objects belongs foo class rather instance i know define static class variables question static class variables python i know make immutable private,3 you want look property function it allows define custom getter setter member attribute class it might look something like class myclassobject x hard coded value def setxself val return def getxself return selfx def delxself return x propertygetx setx delx i immutable property named x i used enough certain whether used create something private delve isinstance may help,is way translate java code python class foo final static private listthingy thingies immutablelistofthing thing thing eg thingies immutable private list thingy objects belongs foo class rather instance i know define static class variables question static class variables python i know make immutable private,1 you make unwriteable subtly different immutable using properties way make private goes python philosophy class fooobject need object python property def thingiesself return thing thing thing f foo print fthingies thing thing thing fthingies traceback recent call last file testpy line module fthingies attributeerror set attribute whether immutable depends return return mutable object may able mutate changes show instanceclass class foomutableobject thingies property def thingiesself return selfthingies foo foomutable foothingiesappend print foothingies this let mutate thingies object returned object kept instanceclass changes reflected subsequent access compare class foomutableobject property def thingiesself return foo foomutable foothingiesappend print foothingies because brand new list returned time changes reflected subsequent accesses,is way translate java code python class foo final static private listthingy thingies immutablelistofthing thing thing eg thingies immutable private list thingy objects belongs foo class rather instance i know define static class variables question static class variables python i know make immutable private,2 in python convention use prefix attribute names mean protected prefix mean private this enforced language programmers expected know write code relies data public if really wanted enforce immutability could use metaclass docs class class just modify setattr delattr raise exceptions someone attempts modify make tuple immutable list docs class foometatype a type whose thingies attribute modified def setattrcls name value name thingies raise attributeerrorcannot modify thingies else return typesetattrcls name value def delattrcls name name thingies raise attributeerrorcannot delete thingies else return typedelattrcls name thing thing thing range class fooobject metaclass foometa thingies thing thing thing examples print foothingies prints foothingies raises attributeerror del foothingies raise attributeerror fooother fooother exception print fooother prints it would still technically possible modify going class internal dict attributes enough deter users difficult entirely secure python objects,is way translate java code python class foo final static private listthingy thingies immutablelistofthing thing thing eg thingies immutable private list thingy objects belongs foo class rather instance i know define static class variables question static class variables python i know make immutable private,3 phrasewords red car lake newjersey turnpike lines red car drove newjersey turnpike took exit lake drove car muddy roads turned red car brown driving newjersey turnpike confusing text joinlines join str phrase textcountphrase phrase phrasewords newjersey turnpike red car lake,edited question based response i list strings text file i want count occurrences strings another text file here example strings i file red car no lake newjersey turnpike here text file i want search strings mentioned i red car i drove newjersey turnpike when i took exit lake i drove car muddy roads turned red car brown driving newjersey turnpike confusing the answer i looking newjersey turnpike no lake red car how i program python thanks lot help here i tried far inputfilepath r inputfiletxt phrasepath r phrasewordstxt stringcountpath r stringcounttxt f openphrasepath r lines freadlines keys line lines keyappendline phraseword mapstringstripmapstrlowerkeys fclose dict key phrasewords dictkey fopeninputfilepath r lines mapstringstripmapstrlowerfreadlines w lines try dictw except keyerror pass fclose the strings getting assigned properly answer isnt right phrasewords red car lake newjersey turnpike lines red car drove newjersey turnpike took exit lake drove car muddy roads turned red car brown driving newjersey turnpike confusing dict red car newjersery turnpike lake,1 create table col typ col typ col typ constraint unq unique col col col httpwwwsqliteorglangcreatetablehtml,i trying populate new sqlite database rows based set data i trouble avoiding duplicate rows i could accomplish python certainly must design option sqlite handle i need row exist unique combination three text fields if i make text field constrained unique three must unique but i would instead like unique combination three strings in words records able exist b b b b b b if i make three fields unique insert rows aaa bbb inserted i could concatenate fields python use primary key seems like extra work,3 if three columns really primary key make composite primary key create table text null b text null c text null whatever columns primary key b c if three columns null want get cade unique constraint instead,i trying populate new sqlite database rows based set data i trouble avoiding duplicate rows i could accomplish python certainly must design option sqlite handle i need row exist unique combination three text fields if i make text field constrained unique three must unique but i would instead like unique combination three strings in words records able exist b b b b b b if i make three fields unique insert rows aaa bbb inserted i could concatenate fields python use primary key seems like extra work,1 i tried code added imports others try usrbinenv python import xmletreecelementtree et import urllib xmlurl httpwwwshoppingcaritfeedexportvelaspparametro req urlliburlopenxmlurl parser etxmlparserencodingwindows tree etparsereq parserparsergetxml runs fine if error happens server probably hit limit webpage trying parse errormessage so make sure actually parsing document eg data reqread dump data parse string xml,trying scrape xml file web urllib celementtree i using google app engine i think problem relevant platform this error type exceptionssyntaxerror wellformed invalid token line column traceback recent call last file basedatahomeappsmetautoitdailyupdatestartupdatepy line main shoppingcarxmlrippergetnew file basedatahomeappsmetautoitdailyupdateupdatecarssitecrawlersshoppingcarpy line getnew cardict newcars file basedatahomeappsmetautoitdailyupdateupdatecarssitecrawlersshoppingcarpy line itercardictsinxml tree selfgetxml file basedatahomeappsmetautoitdailyupdateupdatecarssitecrawlersshoppingcarpy line getxml return etparsereq parserparser file string line parse file string line parse the xml file long sample xml version encodingwindowsveicoli veicolo idcdataid linkcdatahttpwwwshoppingcaritautousatechryslerptcruiserasplink marcacdatachryslermarca modellocdatapt cruisermodello versionecdata lversione provinciacdatapadovaprovincia annocdataanno mesecdatamese chilometricdatachilometri cilindratacdatacilindrata potenzacdatapotenza alimentazionecdatabenzinaalimentazione cambiocdatacambio automaticocambio colorecdatanerocolore prezzocdataprezzo immaginecdatahttpwwwshoppingcaritpublicautousateberlineimagesadvjpg immagine veicolo veicoli my simplified code looks like xmlurl httpwwwshoppingcaritfeedexportvelaspparametro req urlliburlopenxmlurl parser etxmlparserencodingwindows tree etparsereq parserparsergetxml here kicker i downloaded uploaded public dropbox file using url xml parses fine i tried without declaring encoding tried windows utf encodings it really strange column nothing middle word encoding any help appreciated,1 the head tmp syntax bash feature called process substitution the basicportable binsh support this true even systems binsh binbash program allow feature invoked plain binsh inadvertently depend nonportable feature subprocesspopenbinbash c cat head tmp subprocesspopen object xcca,i want use magic subshells redirection python subprocess module seem work complaining unexpected tokens parenthesis for example command cat head tmp passed subprocess gives subprocesspopencat head tmp shelltrue subprocesspopen object xbbfef binsh c line syntax error near unexpected token binsh c line cat head tmp,3 is look f so according comment i come one although elegant anymore fmt lambda x x strx fmt fmt,i want format number decimal point leading zeros this zfill considers digits even decimal point is function python considers whole part i need format simple numbers five decimal places also using f seems consider trailing instead leading zeros,3 like f,i want format number decimal point leading zeros this zfill considers digits even decimal point is function python considers whole part i need format simple numbers five decimal places also using f seems consider trailing instead leading zeros,1 data u xk print data prints xk,in python i pull data via wincom tuple u xk how i parse i left xk i write file,2 print u xk xk,in python i pull data via wincom tuple u xk how i parse i left xk i write file,1 since unicode string want write unicode encoded file import codecs myfile codecsopen myfiletxt encoding utf mode w data u xk myfilewritedataencode utf myfileclose see reading writing unicode data python unicode howto,in python i pull data via wincom tuple u xk how i parse i left xk i write file,1 xf reported error message ascii value capital letter o it looks like made typographical error put o want zero,wrote small function job x invd x inv receive error valueerror unsupported format character o xf index works without problem want use external variable invd inv original value come saved variable,2 usrbinenv python import sys filelist sysargv pathwaylist infilename filelist sysstderrwriteprocessing file sn infile openinfilename r pathwaylistappendinfilereadlines infileclose assuming read two files following line line comparison pick extra lines longer file one lines enumeratezippathwaylist pathwaylist print match else print nonmatch for wanting might want take look difflib module python for sorting look mutable sequence types somelistvarsort sort contents somelistvar place,i like read contents several files unique lists i call later ultimately i want convert lists sets perform intersections subtraction this must incredibly naive question poring iterators loops sections lutz learning python i seem wrap head around approach here i written usrbinenv python import sys outfilename testtxt outfile openoutfilename w filelist sysargv len lenfilelist print len rangelen sysstderrwriteprocessing file sn filenum infilename filelist infile openinfilename r pathwaylist infilereadlines print pathwaylist infileclose with couple simple test files i get output like processing file processing file algn algn algn algn algn alg csrn csrn csrn csrn csrn csrn csrn algn alg these lists correct i assign one unique variable i call later example including index range variable name thanks much pointing complete programming beginner right direction,1 joinmap join itertoolsproduct ordc c open foo read,i seem able find information c perform operation python any advice suggestions would appreciated thank much,1 currently using class attributes instead instance attributes try changing class definitions following class house def initself selfid selfwindowlist class window def initself selfid the way code instances house sharing windowlist,i made two classes called house window i made list containing four houses each instance house list windows i trying iterate windows house print id however i seem get odd results s i greatly appreciate help usrbinenv python minimal house class class house id windowlist minimal window class class window id list houses houselist number windows build four houses windowsperhouse build houses newhouse range lenwindowsperhouse append new house house list houselistappendhouse give new house id houselistnewhouseid strnewhouse for new house build windows newwindow range windowsperhousenewhouse append window house window list houselistnewhousewindowlistappendwindow give window id houselistnewhousewindowlistnewwindowid strnewwindow iterate windows house printing house window ids house houselist print house houseid window housewindowlist print window windowid desired output house window house window window window house window window house window,3 def paddedbinnumber width padchar return binnumberrjustwidth padchar openr cpathtofiletxt rb f asbinary joinpaddedbinordc c fread,i seem able find information c perform operation python any advice suggestions would appreciated thank much,2 you could like need remeber contents come pathwaylist infilename filelist sysstderrwriteprocessing file sn infilename infile openinfilename r pathwaylistappendinfilereadlines infileclose contents pathwaylist something contents list strings print contents want keep track files names could use dictionary pathwaylist infilename filelist sysstderrwriteprocessing file sn infilename infile openinfilename r pathwaylistinfile infilereadlines infileclose filename contents pathwaylistitems something contents list strings print filename contents,i like read contents several files unique lists i call later ultimately i want convert lists sets perform intersections subtraction this must incredibly naive question poring iterators loops sections lutz learning python i seem wrap head around approach here i written usrbinenv python import sys outfilename testtxt outfile openoutfilename w filelist sysargv len lenfilelist print len rangelen sysstderrwriteprocessing file sn filenum infilename filelist infile openinfilename r pathwaylist infilereadlines print pathwaylist infileclose with couple simple test files i get output like processing file processing file algn algn algn algn algn alg csrn csrn csrn csrn csrn csrn csrn algn alg these lists correct i assign one unique variable i call later example including index range variable name thanks much pointing complete programming beginner right direction,1 you might want look entityattributevalue model httpweblogssqlteamcomdavidmarticlesaspx,say i object composed multiple pieces information rating like comment let call object preference each preference would associated user that user many preferences preference one user in ways would better preference object structured design database example table columns rating like comment foreign id key pointing user a user preference may may contain rating like comment entry specific column would left blank and ways would better preference object instead assembled outside design database collecting piece needs several tables table rating like comment table column pointing foreign id key user if user lacks rating like comment table would simply entry user specifically i using python sqlalchemy accomplish,1 you might want check python fileinput module part standard library allows process multiple files,i like read contents several files unique lists i call later ultimately i want convert lists sets perform intersections subtraction this must incredibly naive question poring iterators loops sections lutz learning python i seem wrap head around approach here i written usrbinenv python import sys outfilename testtxt outfile openoutfilename w filelist sysargv len lenfilelist print len rangelen sysstderrwriteprocessing file sn filenum infilename filelist infile openinfilename r pathwaylist infilereadlines print pathwaylist infileclose with couple simple test files i get output like processing file processing file algn algn algn algn algn alg csrn csrn csrn csrn csrn csrn csrn algn alg these lists correct i assign one unique variable i call later example including index range variable name thanks much pointing complete programming beginner right direction,1 it reliable determine pad type template name always property it better check capabilities here diff gtkgdkthreadsleave def demuxercallbackself demuxer pad padgetpropertytemplatenametemplate videod typ padgetcapsgetname typstartswithvideo qvpad selfqueuevgetpadsink padlinkqvpad elif padgetpropertytemplatenametemplate audiod elif typstartswithaudio qapad selfqueueagetpadsink padlinkqapad,i trying work gstreamer i following tutorial httppygstdocsberliosdepygsttutorialpipelinehtml gives following code usrbinenv python import sys os import pygtk gtk gobject import pygst pygstrequire import gst class gtkmain def initself window gtkwindowgtkwindowtoplevel windowsettitlempegplayer windowsetdefaultsize windowconnectdestroy gtkmainquit wm destroy vbox gtkvbox windowaddvbox hbox gtkhbox vboxpackstarthbox false selfentry gtkentry hboxaddselfentry selfbutton gtkbuttonstart hboxpackstartselfbutton false selfbuttonconnectclicked selfstartstop selfmoviewindow gtkdrawingarea vboxaddselfmoviewindow windowshowall selfplayer gstpipelineplayer source gstelementfactorymakefilesrc filesource demuxer gstelementfactorymakeoggdemux demuxer demuxerconnectpadadded selfdemuxercallback selfvideodecoder gstelementfactorymaketheoradec videodecoder selfaudiodecoder gstelementfactorymakemad audiodecoder audioconv gstelementfactorymakeaudioconvert converter audiosink gstelementfactorymakeautoaudiosink audiooutput videosink gstelementfactorymakeautovideosink videooutput selfqueuea gstelementfactorymakequeue queuea selfqueuev gstelementfactorymakequeue queuev colorspace gstelementfactorymakeffmpegcolorspace colorspace selfplayeraddsource demuxer selfvideodecoder selfaudiodecoder audioconv audiosink videosink selfqueuea selfqueuev colorspace gstelementlinkmanysource demuxer gstelementlinkmanyselfqueuev selfvideodecoder colorspace videosink gstelementlinkmanyselfqueuea selfaudiodecoder audioconv audiosink bus selfplayergetbus busaddsignalwatch busenablesyncmessageemission busconnectmessage selfonmessage busconnectsyncmessageelement selfonsyncmessage def startstopself w selfbuttongetlabel start filepath selfentrygettext ospathisfilefilepath selfbuttonsetlabelstop selfplayergetbynamefilesourcesetpropertylocation filepath selfplayersetstategststateplaying else selfplayersetstategststatenull selfbuttonsetlabelstart def onmessageself bus message messagetype gstmessageeos selfplayersetstategststatenull selfbuttonsetlabelstart elif gstmessageerror err debug messageparseerror print error err debug selfplayersetstategststatenull selfbuttonsetlabelstart def onsyncmessageself bus message messagestructure none return messagename messagestructuregetname messagename preparexwindowid imagesink messagesrc imagesinksetpropertyforceaspectratio true gtkgdkthreadsenter imagesinksetxwindowidselfmoviewindowwindowxid gtkgdkthreadsleave def demuxercallbackself demuxer pad padgetpropertytemplatenametemplate videod qvpad selfqueuevgetpadsink padlinkqvpad elif padgetpropertytemplatenametemplate audiod qapad selfqueueagetpadsink padlinkqapad gtkmain gtkgdkthreadsinit gtkmain i getting following error i try play ogv file videotestpy warning gobjectsetqdata assertion gisobject object failed padgetpropertytemplatenametemplate videod traceback recent call last file videotestpy line demuxercallback padgetpropertytemplatenametemplate videod attributeerror nonetype object attribute nametemplate traceback recent call last file videotestpy line demuxercallback padgetpropertytemplatenametemplate videod attributeerror nonetype object attribute nametemplate i really need able play video how i fix,1 here updated code minimal house class class house def initself id selfid id selfwindowlist minimal window class class window id list houses houselist number windows build houses windowsperhouse build houses newhouse rangelenwindowsperhouse append new house house list houselistappendhousestrnewhouse for new house build windows newwindow rangewindowsperhousenewhouse append window house window list houselistnewhousewindowlistappendwindow give window id houselistnewhousewindowlistnewwindowid strnewwindow iterate windows house printing house window ids house houselist print house houseid window housewindowlist print window windowid the actual problem windowlist attribute mutable different instances using end sharing one by moving windowlist init instance gets,i made two classes called house window i made list containing four houses each instance house list windows i trying iterate windows house print id however i seem get odd results s i greatly appreciate help usrbinenv python minimal house class class house id windowlist minimal window class class window id list houses houselist number windows build four houses windowsperhouse build houses newhouse range lenwindowsperhouse append new house house list houselistappendhouse give new house id houselistnewhouseid strnewhouse for new house build windows newwindow range windowsperhousenewhouse append window house window list houselistnewhousewindowlistappendwindow give window id houselistnewhousewindowlistnewwindowid strnewwindow iterate windows house printing house window ids house houselist print house houseid window housewindowlist print window windowid desired output house window house window window window house window window house window,1 apparently minidom cannot parse urls you import urllib doc urlliburlopenyoururl parsed minidomparsedoc,i done research trying parse xml file another web server came across something called minidom i tried implementing viewpy file xmldom import minidom import models def testrequest data docminidomparsehttpwwwsomeotherdomaincomxmlaspxidamplimit the problem i running i get error exception value errno no file directory httpwwwsomeotherdomaincomxmlaspxidamplimit i able find use minidom external document documents located server if possible ideal solution,3 use real html parser regex you happier lxmlhtml highly regarded beautifulsoup,so i data analysis i required extract page title breadcrumb h tags hundreds html shtml files those tags following format meaning stuffs inside breadcrumb titlemapping drive macintosh osx amplt mapping drive amplt ehelp amplt cal poly pomonatitle p instancebegineditable namebreadcrumb hrefindexhtmlehelpa ampraquo hrefindexshtmlmapping drivea ampraquo mac os x instanceendeditable p ha namecontentstart idcontentstarta instancebegineditable namepageheading nametop idtopamapping drivespan classgoldletter macintosh spanos x instanceendeditable h after getting tags i want extract first part title mapping drive macintosh osx last part breadcrumb mac os x whole h mapping drive macintosh osx any idea accomplished,3 since html basically xml easily trimmed compatible xml parsers i would suggest using xml parser most python htmlspecific parsers subclasses xml parser anyway check python xml here good tutorial python xml parser tutorial also xmldomminidom class super useful personally another similar method explained xmletreeelementtree this good example xmldomminidom reference page import xmldomminidom document slideshow titledemo slideshowtitle slidetitleslide titletitle pointthis demopoint pointof program processing slidespoint slide slidetitleanother demo slidetitle pointit importantpoint pointto thanpoint pointone slidepoint slide slideshow dom xmldomminidomparsestringdocument def gettextnodelist rc node nodelist nodenodetype nodetextnode rcappendnodedata return joinrc def handleslideshowslideshow print html handleslideshowtitleslideshowgetelementsbytagnametitle slides slideshowgetelementsbytagnameslide handletocslides handleslidesslides print html def handleslidesslides slide slides handleslideslide def handleslideslide handleslidetitleslidegetelementsbytagnametitle handlepointsslidegetelementsbytagnamepoint def handleslideshowtitletitle print titlestitle gettexttitlechildnodes def handleslidetitletitle print hsh gettexttitlechildnodes def handlepointspoints print ul point points handlepointpoint print ul def handlepointpoint print lisli gettextpointchildnodes def handletocslides slide slides title slidegetelementsbytagnametitle print psp gettexttitlechildnodes handleslideshowdom if absolutely must use regex instead parser check module in import in grps researchr abcabc in grps in print grpsgroups out abc,so i data analysis i required extract page title breadcrumb h tags hundreds html shtml files those tags following format meaning stuffs inside breadcrumb titlemapping drive macintosh osx amplt mapping drive amplt ehelp amplt cal poly pomonatitle p instancebegineditable namebreadcrumb hrefindexhtmlehelpa ampraquo hrefindexshtmlmapping drivea ampraquo mac os x instanceendeditable p ha namecontentstart idcontentstarta instancebegineditable namepageheading nametop idtopamapping drivespan classgoldletter macintosh spanos x instanceendeditable h after getting tags i want extract first part title mapping drive macintosh osx last part breadcrumb mac os x whole h mapping drive macintosh osx any idea accomplished,1 i could wrong i partially updated project correctly handle timezones i believe timezone variable used postgres backend determined grepping source so using postgres really matter use… and using postgres use utc relevant documentation,i building django application using utc time stamps datetime fields the users operators networks environmental research stations trained enter times utc gmt server well users work desktoplaptop computers set utc daylight saving time adjustment in settingspy i could set timezone none want rely server time i help how would set django configuration settings,1 try simple one line n,what easiest way generate string spaces length n python besides something like multiline presumably inefficient large n def spacesn rangen return,3 it simple n,what easiest way generate string spaces length n python besides something like multiline presumably inefficient large n def spacesn rangen return,1 off top head spaces lambda x x,what easiest way generate string spaces length n python besides something like multiline presumably inefficient large n def spacesn rangen return,1 you could function def spacesn return n or use expression n,what easiest way generate string spaces length n python besides something like multiline presumably inefficient large n def spacesn rangen return,1 essentially list files want change list lines files several ways result listopenn n sysargv this would get result like alg alg alg csr csr accessing would like result would result alg alg alg somewhat better might dictionary result dict n listopenn n sysargv if want concatenate would need chain import itertools result listitertoolschainfromiterableopenn n sysargv alg alg alg csr csr not oneliners beginnerhowever would good exercies try comprehend going,i like read contents several files unique lists i call later ultimately i want convert lists sets perform intersections subtraction this must incredibly naive question poring iterators loops sections lutz learning python i seem wrap head around approach here i written usrbinenv python import sys outfilename testtxt outfile openoutfilename w filelist sysargv len lenfilelist print len rangelen sysstderrwriteprocessing file sn filenum infilename filelist infile openinfilename r pathwaylist infilereadlines print pathwaylist infileclose with couple simple test files i get output like processing file processing file algn algn algn algn algn alg csrn csrn csrn csrn csrn csrn csrn algn alg these lists correct i assign one unique variable i call later example including index range variable name thanks much pointing complete programming beginner right direction,1 this happens setting mydict class level binds class instances class instances share mydict,i starting python encountered weird behaviour atleast class parent mystr myint mydict class childa def selfmydictsomething print selfmystr class childb def selfmydictsomething print selfmystr based understanding instances childa childb dictionaries but turns share dictionary to fix i need set selfmydict parent constructor on hand mystr myint appear intended values why happen,1 this happens names bound class level belong class instance therefore mydict dict since dict instances mutable changes make via one classinstance reference show strings numbers immutable rebound instead assigned via subclass instance,i starting python encountered weird behaviour atleast class parent mystr myint mydict class childa def selfmydictsomething print selfmystr class childb def selfmydictsomething print selfmystr based understanding instances childa childb dictionaries but turns share dictionary to fix i need set selfmydict parent constructor on hand mystr myint appear intended values why happen,2 you need synchronise x server get window xid here def onsyncmessagebus message messagestructure none return false messagestructuregetname preparexwindowid gtkgdkthreadsenter gtkgdkdisplaygetdefaultsync winid videowidgetwindowxid imagesink messagesrc imagesinksetpropertyforceaspectratio true imagesinksetxwindowidwinid gtkgdkthreadsleave,i project runs python pygtk recent version pygst i getting weird intermittent error following code with first longer error video play fine error appear after i close video window the second prevents window opening import pygtk pygtkrequire import gtk pango import pygst pygstrequire import gst import trailcrest import os sys class video def initself def onmessagebus message messagetype gstmessageeos end stream playersetstategststatenull elif messagetype gstmessageerror playersetstategststatenull err debug messageparseerror print error err debug def onsyncmessagebus message messagestructure none return false messagestructuregetname preparexwindowid sysplatform win winid videowidgetwindowhandle else winid videowidgetwindowxid assert winid imagesink messagesrc imagesinksetpropertyforceaspectratio true imagesinksetxwindowidwinid win gtkwindow winsetresizablefalse winsethasframefalse winsetpositiongtkwinposcenter fixed gtkfixed winaddfixed fixedshow videowidget gtkdrawingarea fixedputvideowidget videowidgetsetsizerequest videowidgetshow setup gstreamer player gstelementfactorymakeplaybin multimediaplayer bus playergetbus busaddsignalwatch busenablesyncmessageemission used get messages gstreamer emits busconnectmessage onmessage used connecting video application busconnectsyncmessageelement onsyncmessage playersetpropertyuri file osgetcwd vidseqgameopenogv playersetstategststateplaying winshow def main gtkgdkthreadsinit gtkmain return name main video main the program videopy received x window system error this probably reflects bug program the error badidchoice invalid resource id chosen connection details serial errorcode requestcode minorcode note programmers normally x errors reported asynchronously receive error causing to debug program run sync command line option change behavior you get meaningful backtrace debugger break gdkxerror function a quick note thisi followed instructions ran python videopy sync command line i kubuntu i got message again here error one prevents playback python srcxcbioc pollforevent assertion long eventsequence long dpyrequest failed aborted these literally alternate though perfectly i could get three first two second one first one second two first etc it always different what devil going,2 mydict classlevel python looks instance find searches inheritence tree if rebind name mydict anywhere instance instance version this behavior easy see using mutable objects dict list etc difficult observe immutable objects str int tuple etc order change value immutable rebind name something like class fooobject collection list number def changecollectionself newmember selfcollectionappendnewmember def changenumberself newnumber selfnumber newnumber foo b foo achangecollection howdy bchangenumber print acollection bcollection howdy howdy print anumber bnumber print acollection bcollection true print anumber bnumber false,i starting python encountered weird behaviour atleast class parent mystr myint mydict class childa def selfmydictsomething print selfmystr class childb def selfmydictsomething print selfmystr based understanding instances childa childb dictionaries but turns share dictionary to fix i need set selfmydict parent constructor on hand mystr myint appear intended values why happen,2 you easily iterate dictionaries team scores nleastiteritems runsscored floatscores runsallowed floatscores winpercentage roundrunsscoredrunsscoredrunsallowed print f team winpercentage,working python i dictionary team names keys amount runs scored allowed team value list nleast phillies braves mets i would like able feed dictionary function iterate team keys here code i using right i go team team how would i iterate team print expected winpercentage team def pythagleague runsscored floatleague phillies runsallowed floatleague phillies winpercentage roundrunsscoredrunsscoredrunsallowed print winpercentage thanks help,3 npdotweightstnpdotcovarweights array for d numpy arrays npdot equivalent matrix multiplication for d array npdotted d array npdot equivalent matrixvector multiplication for d arrays npdot equivalent inner product for numpy arrays performs elementwise multiplication broadcasting necessary weightstnpmatrixcovarweights matrix alternatively convert covar npmatrix equivalent matrix multiplication,portfolio variance calculated portvar w p s wp portfolio n assest w p transpose vector weights stocks portfolios s sample covariance matrix wp vector weights stocks portfolios i following numpy matrixes array vector weights stocks portfolio stocks weights nparray covariance matrix stock returns covar nparray when i compute weightst covar weights the result array size covar i new portfolio theory i would imagine variance portfolio scalar single value does anyone experience might help,2 dictionaries built function called iterkeys try team leagueiterkeys runsscored floatleagueteam runsallowed floatleagueteam winpercentage roundrunsscoredrunsscoredrunsallowed print winpercentage,working python i dictionary team names keys amount runs scored allowed team value list nleast phillies braves mets i would like able feed dictionary function iterate team keys here code i using right i go team team how would i iterate team print expected winpercentage team def pythagleague runsscored floatleague phillies runsallowed floatleague phillies winpercentage roundrunsscoredrunsscoredrunsallowed print winpercentage thanks help,3 all repositories care one python default i know archlinux,i would like know linux distribution easily install use python this means distribution provide python binaries updates also python modules i know probably going see python default python interpretor soon least i would like see latest x default one alternative one already installed probably question major distributions ubuntu fedora suse,3 this import csv import json class nodedict def initself nid name ndescr dictinitself self id nid self name namelstrip badly formed csv self description ndescrlstrip self children def addnodeself node child self children childisparentnode childaddnodenode break else self children appendnode def isparentself node lenself id self id return node id startswithself id return node id startswithself id class rootnodenode def initself nodeinitself root def isparentself node return true def prettyprintnode print sids names node id node name node description child node children prettyprintchild def main open inputcsv f freadline skip first line root rootnode node mapnode csvreaderf rootaddnodenode prettyprintroot print jsondumpsroot name main main,i sure elegant way python push javascript life i see i csv file form id name description a aname a aname adesc a aname adesc a aname adesc a aname adesc a aname adesc a aname adesc a aname adesc a aname adesc b bname b bname bdesc b bname bdesc b bname bdesc b bname bdesc i want generate hierarchical json structure i visualise data thejit var json id auniqueidentifier name usually nodes name data key value key value children nodes empty my plan map id id name name description datadesc organise hierarchy root parent a b a parent a a a parent a a a parent a a a b parent b b parent b b b parent b there also pathological case otherwise regular ordering id a parent a expected a present i hoping find elegant python solution defeating moment even ignoring pathological case,1 you several options iterating dictionary if iterate dictionary team league iterating keys dictionary when looping loop behavior whether loop dict league leaguekeys leagueiterkeys dictiterkeys generally preferable explicit efficient team leagueiterkeys runsscored runsallowed mapfloat leagueteam you also iterate keys values iterating leagueitems leagueiteritems team runs leagueiteritems runsscored runsallowed mapfloat runs you even perform tuple unpacking iterating team runsscored runsallowed leagueiteritems runsscored floatrunsscored runsallowed floatrunsallowed,working python i dictionary team names keys amount runs scored allowed team value list nleast phillies braves mets i would like able feed dictionary function iterate team keys here code i using right i go team team how would i iterate team print expected winpercentage team def pythagleague runsscored floatleague phillies runsallowed floatleague phillies winpercentage roundrunsscoredrunsscoredrunsallowed print winpercentage thanks help,3 dictionary objects allow iterate items also pattern matching division future simplify things bit finally separate logic printing make things bit easier refactordebug later future import division def pythagleague def winpercentages team runsscored runsallowed leagueiteritems winpercentage roundrunsscored runsscoredrunsallowed yield winpercentage winpercentage winpercentages print winpercentage,working python i dictionary team names keys amount runs scored allowed team value list nleast phillies braves mets i would like able feed dictionary function iterate team keys here code i using right i go team team how would i iterate team print expected winpercentage team def pythagleague runsscored floatleague phillies runsallowed floatleague phillies winpercentage roundrunsscoredrunsscoredrunsallowed print winpercentage thanks help,2 welcome sql now written two queries time learn join sql injection select urls sites urlssiteid sitesid sitename like good luck,trying write following python elegantlyfrom mysql perspective you notice i trying combine results one table based upon entries another what properclean industry smart way writing sql query essentially i would like say select urls urls table belong site group sites table thanks site sysargv checksanity logsite check syntax etc loginfo running site site cursor conncursor get siteid query select sitesid sites where sitename like site cursorexecute query siteidlong cursorfetchone siteid strsiteidlong query select searchforurlsurl from urls where siteid like siteid print query cursorexecute query resultstring cursorfetchall print resultstring cursorclose connclose,2 another way using glob module just seed rglob method starting base directory pattern match return list matching file names import glob import os def getdirsbase return x x globiglobospathjoin base ospathisdirx def rglobbase pattern list listextendglobglobospathjoinbasepattern dirs getdirsbase lendirs dirs listextendrglobospathjoinbased pattern return list,this i globospathjoin src c i want search subfolders src something like would work globospathjoin src c globospathjoin src c globospathjoin src c globospathjoin src c but obviously limited clunky,2 you looking sites framework,i writing web application django accessed multiple domains ip address the idea domain application accessed receive unique branding so example two domains resellercom oemcom went oemcom would take website resellercom differently themed content say sent staticoemcomfiles instead staticresellercomfiles basically idea define custom template tag receives servername argument would return location content are alternatives simply easier options edit i probably add i using mongodb project likely django orm used project edit more clarification i using nginx,1 list comprehension shorten things winpercentages n n ai nleast,working python i dictionary team names keys amount runs scored allowed team value list nleast phillies braves mets i would like able feed dictionary function iterate team keys here code i using right i go team team how would i iterate team print expected winpercentage team def pythagleague runsscored floatleague phillies runsallowed floatleague phillies winpercentage roundrunsscoredrunsscoredrunsallowed print winpercentage thanks help,1 would want keep source control they part inputs generate final built output you definately want lose track probably want keep track change time continue develop application what likely want create subdirectory distribution specific files live say debian packagingdebian commit you makefile run directory copies files need create package great shape,for last python project i developed i used git versioning system now time development cycle i begin ship packages beta testers case would deb packages in order build packages i need number extra files copyright iconxpm setuppy setupcfg stdebcfg etc i would like keep separate source program source might used prepare packages platforms would make sense debianspecific files lingering around my question standard waybest practice in google wanderings i stumbled couple times including so gitbuildpackage suite i sure i looking seems thought packagers download targz upstream repository i thought possible way achive i want would branch git repository i keep packagingfiles branch also able see files master branch without every time manually merge master packaging branch however i know good idea way done although i suspect might involve git symbolicref magic i idea i imagined any help appreciated thanks advance time,2 answer question depends somewhat particular python implementation to understand pay particular attention actual file object in code object mentioned expression becomes inaccessible immediatly read call returns this means file object garbage the remaining question when garbage collecter collect file object cpython uses reference counter kind garbage noticed immediately collected immediately this generally true python implementations a better solution make sure file closed pattern open pathtofile r contentfile content contentfileread always close file immediately block ends even exception occurs edit to put finer point other fileexit automatically called context manager setting way fileclose automatically called explicitly calling via filedel this leads us question del get called a correctlywritten program cannot assume finalizers ever run point prior program termination httpblogsmsdncomboldnewthingarchiveaspx in particular objects never explicitly destroyed however become unreachable may garbagecollected an implementation allowed postpone garbage collection omit altogether — matter implementation quality garbage collection implemented long objects collected still reachable cpython currently uses referencecounting scheme optional delayed detection cyclically linked garbage collects objects soon become unreachable guaranteed collect garbage containing circular references httpsdocspythonorgreferencedatamodelhtmlobjectsvaluesandtypes emphasis mine suggests implementations may behavior as example pypy different garbage collection implementations,if read entire file content open pathtofile r read file handle left open script exits is concise method read whole file,3 i think standard way handling bounds making function minimized residuals large whenever parameters exceed bounds import scipyoptimize optimize def residualspxy withinboundsp return modelpx else return e pcovinfodictmesgier optimizeleastsq residualspguessargsxyfulloutputtruewarningtrue,i using optimizeleastsq fit data i would like constrain fitting parameters certain range is possible define bounds using optimizeleastsq bounds implemented optimizefminslsqp i prefer use optimizeleastsq,3 this answered modwsgi list httpgroupsgooglecomgroupmodwsgibrowsethreadthreaddaeeabf the short answer wsgi script file needs source code others pointed appropriate lines set syspath necessary import actual wsgi application entry point pyo version module elsewhere,i trying start apache modwsgi i strong restriction put source py files onto server i compile first put pyo files onto server that i apache conf loadmodule wsgimodule modulesmodwsgiso wsgipythonpath varwwwroot wsgipythonoptimize wsgiscriptalias home varwwwroothomepyo but modwsgi raises error cut apache error log failed parse wsgi script file varwwwroothomepyo exception occurred processing wsgi script varwwwroothomepyo file varwwwroothomepyo line mxf syntaxerror invalid syntax i tried google find answer modwsgi work precompiled python code,1 why surprising retrieving lot records takes lot resources this on process really perrequest basis to answer questions order how much cpu time uses depends nature records result surprising note nearly cpu seconds wallclock seconds also note new billing model rolls charged datastore operations instance hours optimising the admin console shows authoritative figures billed based the appstats figures lower count time spent api calls time spent executing code if set records small fairly static cache instance memory rather fetching time storing memcache if larger dynamic use something like geomodel geographical queries fetch relevant records fetching records always takes amount api cpu time datastore access costs represented actually time taken the new model fixes breaking separate billable operations,when trying optimize query getting store records based location i dumped something strange i think getting large dataset takes alot cpu time basically i records need iterated find stores within users position i got quite high numbers admin console this lead datastore testing resulted interesting numbers getting records i tests methods i ran separately took cpu time admin console appstats resulted production r dbgqlqueryselect key from storerecordsfetch appstats realms cpums apims admin console ms cpums apicpums r dbgqlqueryselect key from storerecordsfetch appstats realms cpums apims admin console ms cpums apicpums r dbgqlqueryselect from storerecordsfetch appstats realms cpums apims admin console ms cpums apicpums r dbgqlqueryselect from storerecordsfetch appstats realms cpums apims admin console ms cpums apicpums r modelstorerecordsallfetch appstats realms cpums apims admin console ms cpums apicpums r modelstorerecordsallfetch appstats realms cpums apims admin console ms cpums apicpums here i take records need fetch my questions should fetch records really take almost cpums apicpums seconds why differences appstas admin console times what calculated quota one could easily get around pushing fetched records memcache protobuf but i curios high usage differences time appstas admin console bonus question how come fetching records always result apicpums,1 mayan edms complete free open source electronic document management system rest api yet parts need already coded,i recently learned python want project get hands dirty let knowledge settle so i thinking create simple document management system python i another project written java needs i want two linked soap dms web service i need dms basic operations files create delete manage versioning etc looking examples sample code best practices best using python tried search web could find full fledged cms tools support dms i need something simple examples dicussions wiki etc does something like exist thank,2 c java c etc really strange behaviour regarding instance variables whereby data members fields depending culture belong described within class block belongs instances functions well methods c programmers seem hate term say member functions instead described within block belong class strange confusing actually think a lot people think accept move but actually causes confusion lot beginners assume everything within block belongs instances this leads bizarre experienced programmers questions concerns perinstance overhead methods trouble wrapping heads around whole vtable implementation concept of course mostly teachers collective fault failing explain vtables one implementation failing make clear distinctions classes instances first place python confusion since python functions including methods objects would bizarrely inconsistent compiler make distinction like so happens python intuitively expect everything within class indented block belongs class and yes python classes objects well gives place put class attributes jump standard library hoops use reflectively the absence manifest typing quite liberating so i hear protest actually add data instances well default python restrict adding anything instance it even require make different instances class contain attributes and certainly preallocate single block memory contain object attributes it would able contain references anyway given python pure referencesemantics language c style value types java style primitives but obviously good idea things way usual convention add data time instance constructed add delete attributes when constructed python really constructors cjavac sense absence reserved space means real benefit considering initialization separate task ordinary assignment except course benefit initialization something automatically happens new object so python closest equivalent magic init method automatically called upon newlycreated instances class there another magic method called new behaves like constructor sense responsible actual creation object however nearly every case want delegate base object new calls builtin logic basically give us little pointerball serve object point class definition so real point worrying new almost every case it really analogous overloading operator new class c in body method cstyle initialization lists prereserved data initialize set initial values attributes possibly work based parameters given now want little bit neater things efficiency real concern another trick sleeves use magic slots attribute class specify class attribute names this list strings nothing fancy however still preinitialize anything instance attribute assign this prevents adding attributes names you even still delete attributes object whose class specified slots all happens instances given different internal structure optimize memory usage attribute lookup the slots usage requires derive builtin object type anyway although required python x intended backwardscompatibility purposes ok make code work but make right python first language constantly commenting explain alreadyselfexplanatory things bad idea it distracts user really help learner language either you supposed know class definition looks like need comment tell class definition class definition reading code comments kind help need with whole duck typing thing poor form include data type names variable attribute names you probably protesting i supposed keep track type otherwise without manifest type declaration don the code uses list windows care list windows list windows it cares iterate list windows thus obtain values used certain ways associated windows that duck typing works stop thinking object worry you notice code i put string conversion code house window constructors this serves primitive form typechecking also makes sure forget conversion if someone tries create house id even converted string raise exception easier ask forgiveness permission note actually go way bit python create as actual iteration python iterate actually iterating objects container java c concept well get c standard library although lot people bother we iterate indices useless distracting indirection we need number windowsperhouse values order use need look value turn how id numbers i hear ask simple python provides us function called enumerate gives us index element pairs given input sequence elements it clean lets us explicit need index solve problem purpose index builtin need interpreted like rest python code incur much overhead when memory concern possible use lazyevaluation version instead but even iterating create house manually appending one initiallyempty list lowlevel python knows construct list values need tell and bonus typically get better performance letting part since actual looping logic done internally native c we instead describe want list list comprehension we walk steps take windowcount turn make corresponding house add list say list houses corresponding windowcount windowcount input list directly that arguably clunkier english much cleaner programming language like python skip bunch little words expend effort describe initial list act appending finished houses list you describe process result madetoorder finally general programming concept makes sense whenever possible delay construction object everything ready needed object existence twophase construction ugly so make windows house first house using windows with list comprehensions simple nest list comprehensions class houseobject slots id windows def initself id windows selfid strid selfwindows windows class windowobject slots id def initself id selfid strid windowsperhouse build houses houses househouseid windowwindowid windowid rangewindowcount houseid windowcount enumeratewindowsperhouse see elegant list comprehensions if quite follow logic please try imagine implicitlydefined process trace pink elephants i know i know just understand described and iterate print house houses print house houseid window housewindows print window windowid,i made two classes called house window i made list containing four houses each instance house list windows i trying iterate windows house print id however i seem get odd results s i greatly appreciate help usrbinenv python minimal house class class house id windowlist minimal window class class window id list houses houselist number windows build four houses windowsperhouse build houses newhouse range lenwindowsperhouse append new house house list houselistappendhouse give new house id houselistnewhouseid strnewhouse for new house build windows newwindow range windowsperhousenewhouse append window house window list houselistnewhousewindowlistappendwindow give window id houselistnewhousewindowlistnewwindowid strnewwindow iterate windows house printing house window ids house houselist print house houseid window housewindowlist print window windowid desired output house window house window window window house window window house window,1 in order use data file needs imported database think file recipe mysql make database now need tell mysql make database recipe you import database using command line python script even mysql workbench however due size file using mysql workbench could problem note i familiar mysql workbench to import database command line use command mysql u username p h localhost kingtracking filename to actually use database python several step step tutorials available easily accessible google search a basic script import mysqldb conn mysqldbconnect host localhost user testuser passwd testpass db test cursor conncursor cursorexecute select version row cursorfetchone print server version row cursorclose connclose this shows version mysql however select version replaced query like select from tablename limit execute queries in order understand tutorials interfacing python mysql familiar separately a good sql tutorial one wschools the problem creating table separate original question may need addressed trying import file database,ok first please assume first time i writing single alphabet code sql please please please would kind explain step i using mac development so desktop i huge gb dumpfile database i mysqlworkbench yes i never worked either and i installed mysqldb so basically i want use data database python so i python mysqldb connect db huge db mysqlworkbench now i assume dumpfile useless form database i mount dump databasemysqlworkbench after i query python like port number username password it would huge help anyone help i stuck since morning,2 i problem my tests ran fine windows ubuntu in ubuntu run nosetests vv collectonly you probably see skipping test file executable toolslintcontrolfilestesthglintpy executable skipped in order get nose consider executables run like nosetests exe,is reason nose able find tests ubuntu i using nose python i run tests i explicitly specify filename if i specify filename says tests the project runs tests fine mac quite stumped,3 yes talk odbc database python include access you want windows version python includes stuff like odbc activestate i worried millions rows access get bit slow retrieval actually using relational tasks joining different tables together i also take look column tables — sometimes need columns often means decomposed data sufficiently get normal form finally use python read write access database i know i count learning access really learning access would using front end create maintain database creating forms reports access would available python programming visual basic applications vba i really like sqlite embedded database solution especially python sql dialect probably purer access,well i might work python would end hundreds thousands maybe millions rows data entries maybe columns i want way keep track data work since i also want learn microsoft access i suggest putting data is easy way i also want learn sas would fine or programmethod i know situation thanks help,1 the exception seeing caused bug astng package presumably “abstract syntax tree next generation” toolkit pylint depends written people i note passing i always encourage people use pyflakes instead pylint possible quick simple fast predictable whereas pylint tries several kinds deep magic slow get exactly kind trouble here two packages pypi httppypipythonorgpypipylint httppypipythonorgpypiastng and note problem necessarily bug pylint code pylint run code order produce report — imagine havoc could wreaked since code linted might delete files etcetera since code get run amount caution like protecting call threading init cleanup functions could possibly prevented error — unless code snippets happened reasons alter behavior investigate so actual exception i never actually heard shutdown a quick search python standard library showed definition threadingpy call function anywhere searching python c source code i discover pythonrunc interpreter shutdown function actually called static void waitforthreadshutdownvoid pyobject threading pymappinggetitemstringtstateinterpmodules threading threading null threading imported pyerrclear return result pyobjectcallmethodthreading shutdown result null pyerrwriteunraisablethreading apparently sort cleanup function threading standard library module requires specialcased python interpreter make sure gets called as see code python quietly without complaint handles case threading module never gets imported program run but threading get imported still exists shutdown time interpreter looks inside shutdown function goes far print error message — return nonzero exit status cause problems — cannot call so discover threading module exists shutdown method moment pylint done examining program python exiting some instrumention called can print module looks like pylint exits we the pylintlintpy module last lines runs “main program” instantiating run class defined name main runsysargv so i opened lintpy editor — one magnificent things little project installed python virual environment i jump edit thirdparty code quick experiments — added following print statement bottom run class init method syspathpop print sysmodules threading file added exit sysexitselflintermsgstatus i reran command python pylintlint mtestpy and came file string threading module homebrandonvenvlibpythonsitepackagesmcryptothreadingpyc well look this problem according path actually exists mcryptothreadingpy module normal circumstances called mcryptothreading therefore sit sysmodules dictionary name sysmodules mcryptothreading but somehow file also getting loaded main python threading module shadowing official threading module sits standard library because python exit logic quite correctly complaining standard library shutdown function missing how could happen toplevel modules appear paths listed explicitly syspath subdirectories beneath this leads new question point pylint run …mcrypto directory getting put syspath though contained toplevel modules let see we need instrumentation need python tell us moment directory mcrypto name appears syspath it really slow things let add trace function pylint initpy — first module gets imported run pylintlint — write output file telling us every line code executed whether syspath bad values def installtracer import sys output open mytracerout w def mytracerframe event arg broken anypendswith mcrypto p syspath outputwrite n format broken framefcodecofilename frameflineno event return mytracer syssettracemytracer installtracer del installtracer note careful i i define one name module namespace carefully delete clean i let pylint continue loading and resources trace function needs — namely sys module output open file — available installtracer closure outside pylint looks exactly always just case anyone tries introspect like pylint might this generates file mytracerout k lines look something like false homebrandonvenvlibpythonposixpathpy call the false says syspath looks clean filename line number line code executed call indicates stage execution interpreter so syspath ever get poisoned let look first true false line see many successive lines start value awk print mytracerout uniq c false true false true false true false true false wow that problem for runs several thousand lines time test case true means interpreter running …mcrypto — variant pathname mcrypto — path directory contains …mcrypto ever path looking first false true transition file i see false homebrandonvenvlibpythonsitepackageslogilabastngbuilderpy line false homebrandonvenvlibpythonposixpathpy call false homebrandonvenvlibpythonposixpathpy line false homebrandonvenvlibpythonposixpathpy return true homebrandonvenvlibpythonsitepackageslogilabastngbuilderpy line and looking lines builderpy file reveals culprit build astng representation try syspathinsert dirnamepath xxx syt iirk node selfstringbuilddata modname path finally syspathpop note comment part original code addition obviously xxx syt iirk exclamation programmer strange native language phrase “put module parent directory syspath pylint break mysteriously every time someone forces pylint introspect package threading submodule” it obviously compact native language if adjust tracing module watch sysmodules actual import threading — exercise i leave reader — see happens socketserver imported standard library module analysis turn tries innocently import threading so let us review happening pylint dangerous magic as part magic sees import foo runs trying find foopy disk parse predict whether loading valid invalid names namespace see comment because call split return value rsaaspem pylint tries introspect aspem method turn uses mcryptobio module turn makes calls induce pylint import threading as part loading module foopy pylint throws directory containing foopy syspath even directory inside package therefore gives modules directory privilege shadowing standard library modules name analysis when python exits upset mcryptothreading library sitting threading belongs wants run shutdown method threading you report bug pylint astng folks logilaborg tell i sent if decide keep using pylint done seem two solutions case either inspect code calls mcrypto import threading pylint import process — sticking import threading pylintinitpy example — module gets chance grab sysmodules threading slot pylint gets excited tries let mcryptothreadingpy grab slot instead in conclusion i think author astng says best xxx syt iirk indeed,i running lint follows python pylintlint mtestpy code import mcrypto def f mcryptorsanewpubkeyaspemciphernonesplitn the lint output ends exception attributeerror shutdown module threading usrlibpythonsitepackagesmcryptopylinuxxeggmcryptothreadingpyc ignored this code works fine run actually minimal test case full version work the exception ignored bitten considers failure stops step i tried adding mcryptothreadinginit mcryptothreadingcleanup around definition function fix problem how i prevent problem occurring i using mcrypto pylint python also tried debian lenny x,3 you draw border qtreewidgetitem alone use delegate and store border style item want border custom role able retrieve use inside delegate here complete working commented example import sys pyqt import qtgui qtcore class borderitemdelegateqtguiqstyleditemdelegate def initself parent borderrole superborderitemdelegate selfinitparent selfborderrole borderrole def sizehintself option index size superborderitemdelegate selfsizehintoption index pen indexdataselfborderroletopyobject pen none make room border when width cosmetic pen pixel anyways set width maxpenwidth size size qtcoreqsize width width return size def paintself painter option index pen indexdataselfborderroletopyobject copy rect later rect qtcoreqrectoptionrect pen none width maxpenwidth remove extra room added sizehint optionrectadjustwidth width width width painting base class method superborderitemdelegate selfpaintpainter option index paint borders pen none paintersave the pen drawn centered rectangle lines penwidth width side lines so rather shifting drawing penwidth double pen width clip part would go outside rect paintersetcliprectrect qtcoreqtreplaceclip pensetwidth width paintersetpenpen painterdrawrectrect painterrestore name main app qtguiqapplicationsysargv mainwindow qtguiqmainwindow mainwindowresize define qtitemdatarole using myborderrole qtcoreqtuserrole create populate view treewidget qtguiqtreewidgetmainwindow range item qtguiqtreewidgetitemitem di treewidgetaddtoplevelitemitem treewidgetexpanditemitem j range subitem qtguiqtreewidgetitemsubitem dij pen qtguiqpenqtguiqcolorfromhsvj pensetwidthj store border pen item role defined subitemsetdata myborderrole pen itemaddchildsubitem pass role stored border pen delegate constructor delegate borderitemdelegatetreewidget myborderrole treewidgetsetitemdelegatedelegate mainwindowsetcentralwidgettreewidget mainwindowshow sysexitappexec,i see way define stylesheet specific qtreewidgetitem i resolved attempt figure solution using either setbackground setforeground the effect i trying achieve border around single widgetitem treeview i figure draw one manually qbrush even go any ideas thanks advance,1 use dictionaries losedic rock paper paper scissors scissors rock get human move chose random move bla bla bla robotmove humanmove tie elif humanmove losedicrobotmove lose else win,i need help python game im working i started learning python days ago i still noob this i came import random time import sleep print please select print rock print paper print scissors player input choose player print you choose rock sleep print cpu chooses paper sleep print you lose never win elif player print you choose paper sleep print cpu chooses scissors sleep print you lose never win else print you choose scissors sleep print cpu chooses rock sleep print you lose never win i want program randomly choose three options rock paper scissors matter user inputs,2 i say somewhat unlucky the average but pick two numbers expect match time hence expect wait times get match,i code import random b x randomrandrangeb randomrandrangeb ab xc ab x x randomrandrangeb randomrandrangeb xc xc elif x print ab print number tries b xc ab ab xc essentially stats program i want see tries many times random number needs generated order match so far numbers getting running program get values ran program times would total tries all low numbers led wondering program extremely lucky something wrong code thanks note way get xc add loop loop true show total,1 check larger number iterations usrbinenv python import random maxnum x randomrandrange maxnum randomrandrange maxnum tries iterations totaltries iterations x x randomrandrange maxnum randomrandrange maxnum tries else printi print number tries maxnum tries totaltries tries tries printaverage tries totaltries iterations if i run i get every time note this could simplified usrbinenv python import random maxnum iterations totaltries rangeiterations printi tries x x x randomrandrange maxnum randomrandrange maxnum tries print number tries maxnum tries totaltries tries tries printaverage tries totaltries iterations,i code import random b x randomrandrangeb randomrandrangeb ab xc ab x x randomrandrangeb randomrandrangeb xc xc elif x print ab print number tries b xc ab ab xc essentially stats program i want see tries many times random number needs generated order match so far numbers getting running program get values ran program times would total tries all low numbers led wondering program extremely lucky something wrong code thanks note way get xc add loop loop true show total,1 are calling commit connection releasing by default python sqlite module use autocommit mode unless finish session ddl statement rolled back for info httpdocspythonorglibrarysqlitehtmlcontrollingtransactions,i created simple db using sqlalchemy after i connect via engine define tables classes create user outputs user fine when program ends i try accessing db via python prompt importing sqlalchemy creating new engine etc previous users gone can someone explain happening anything previously setup db file,2 general advice slicing dicing text python the slice operator str print formatstr str str read strings look part slices string formatting,i text needs handled the timestamp currently listed value the format timestamp yyyymmdd i want able alter yyyymmdd variation yyyymmdd etc i seem find string method inserts characters strings i unsure best way go looking efficiency general advice slicing dicing text python thanks advance,1 strings mutable inserting characters strings work try date print joindatedatedate,i text needs handled the timestamp currently listed value the format timestamp yyyymmdd i want able alter yyyymmdd variation yyyymmdd etc i seem find string method inserts characters strings i unsure best way go looking efficiency general advice slicing dicing text python thanks advance,1 i something like usrbinenv python datetime import datetime openstufftxt r f line f remove initial ending whitespace like line endings line linestrip split timestamp value rawtimestamp value linesplit make timestamp actual datetime object timestamp datetimestrptimerawtimestamp ymd print timestamp separated replace whatever printss timestampstrftimeymd value this lets import print timestamp using format allowed strftime,i text needs handled the timestamp currently listed value the format timestamp yyyymmdd i want able alter yyyymmdd variation yyyymmdd etc i seem find string method inserts characters strings i unsure best way go looking efficiency general advice slicing dicing text python thanks advance,2 how findnext import beautifulsoup import beautifulsoup html strongtextstrong href httpdomaincom urla soup beautifulsouphtml label soupfindstrong text text contact labelfindnext contactget href none print contact else print no href if looking specifically tag href use contact labelfindnext attrs href true with need condense whitespace i imagine next returning whitespace label,i like know handle situation href exist strongtextstrong is better way search content exists strongcontactstrong httppastebincomfymxtjkf,1 your array incorrect syntax you try something like array key key keym array key key keym keyn arraydict dict array array array key value arrayitems key arraydict arraydictkey list arraydictkeyappendvalue array key value key value arraydictitems arraysort print array key key keym keyn,i new pythoni two sorted arrays key i would like merge both arrays common keys exist uniquely one arrays i want outer join array key key keym array key key keym keyn i want merge using keykeyn array key key i numpy package installed computer do i need merge array best way code thanks,1 how usrbinenv python itertools import chain dict key key keym dict key key keym keyn dict go keys dictionaries key setchaindict dict find key either dictionary using empty string default found dictkey dictgetkey dict dict dict printdict now dict list every value input arrays or want key value value key value value format usrbinenv python itertools import chain dict key key keym dict key key keym keyn result key dictgetkey dict dict dict key setchaindict dict resultsort printresult,i new pythoni two sorted arrays key i would like merge both arrays common keys exist uniquely one arrays i want outer join array key key keym array key key keym keyn i want merge using keykeyn array key key i numpy package installed computer do i need merge array best way code thanks,1 you need ensure selenium server hub node set test please refer example hub run java jar seleniumserverstandalonejar role hub example node connect hub run java jar seleniumserverstandalonejar role webdriver hub httplocalhostgridregister port you many nodes want,i trying figure connect remote webdriver instance this code i currently using seleniumremotewebdriver import webdriver driver webdriverhttp firefox any driverget httpgooglecom driverquit i find i connect get connection refused play around code occasionally time any help appreciated,2 not sure simple rewrite rule nginx aside template tag swapping static content i think template tag way go sites gonna different templatewise handle writing custom template loader this allows pick templates would like use render page this method graceful way failing loader fails find matching template specific domain if find match fall back main templates directory so could custom stuff domains generic others but make decision serve based upon request header need make request available loader via threadlocals i middleware custommiddlewarepy try threading import local except importerror djangoutilsthreadinglocal import local threadlocals local def getcurrentrequest return getattrthreadlocals request none class requestmiddleware def processrequestself request threadlocalsrequest request next write template loader update path middleware customloaderspy ospath import join djangoconf import settings djangotemplate import templatedoesnotexist pathtomiddleware import getcurrentrequest def loadtemplatesourcetemplatename templatedirsnone request getcurrentrequest host requestgethost pathtotemplatedir none site settingssitetemplatefolders site host pathtotemplatedir site break pathtotemplatedir try filepath joinpathtotemplatedir templatename file openfilepath try return fileread filepath finally fileclose except ioerror pass raise templatedoesnotexisttemplatename lastly update settings file three things add template loader make sure listed first add middleware add new variable sitetemplatefolders tuple tuples containing domains paths template folders settingspy templateloaders customloadersloadtemplatesource djangotemplateloadersfilesystemloadtemplatesource djangotemplateloadersappdirectoriesloadtemplatesource middlewareclasses djangomiddlewarecommoncommonmiddleware domainmiddlewaresessionmiddleware custommiddlewarerequestmiddleware sitetemplatefolders mydomaincom pathtotemplates myotherdomaincom pathtoothertemplates seems like lot easily add new domain via settings file,i writing web application django accessed multiple domains ip address the idea domain application accessed receive unique branding so example two domains resellercom oemcom went oemcom would take website resellercom differently themed content say sent staticoemcomfiles instead staticresellercomfiles basically idea define custom template tag receives servername argument would return location content are alternatives simply easier options edit i probably add i using mongodb project likely django orm used project edit more clarification i using nginx,1 your logic strange you want use artificial sentinel values break loop just explicitly break you fundamentally two loops one iterate trials one see many attempts needed given trial don hide structure don cover cases else that else within loop generate numbers test that way clearer need extra generation step loop similarly reinitialize values within loop top rather bottom use clear variable names when meaningful variable name avoid creating variable you actually need set two variables randomrandrange b compare results otoh want simplify logic avoid writing seemingly weird comparison randomrandrange b note able prove interested enough kind stuff write program arbitrarily select target value get results also use variables name arbitrarily selected numeric constants you use python update variable use print formatting import random rangesize total iterations however many trial xrangeiterations attempts randomrandrange rangesize attempts print trial took tries match one numbersformat trial attempts rangesize total attempts print average trials formatfloattotal iterations if need debugging information make things even cleaner using builtin functions summation looping logic us random import randrange itertools import rangesize total iterations however many print average trials formatsum sumtakewhilelambda x randrange rangesize repeat i tested way probably logical even verbose lenlisttakewhile lambda x x imaprandrange repeat repeatrangesize lambda x x also spelled bool context explicit better implicit xrangeiterations floatiterations,i code import random b x randomrandrangeb randomrandrangeb ab xc ab x x randomrandrangeb randomrandrangeb xc xc elif x print ab print number tries b xc ab ab xc essentially stats program i want see tries many times random number needs generated order match so far numbers getting running program get values ran program times would total tries all low numbers led wondering program extremely lucky something wrong code thanks note way get xc add loop loop true show total,1 and since question still rated pretty highly searches google i add alternative mix httpdjangorestframeworkorg my initial impression good job embodying restful api design principles described httpreadthedocsorgdocsrestfulapidesignenlatest,i looking implement restful interface django application it primarily dataservice application interface point readonly the question django toolsets frameworks make sense task i see djangorest djangopiston there also option rolling the question asked good two years back i like know current state play in question circa strong majority vote use framework create django views reply eg json the question also addressed crica in current landscape makes sense,3 marekdo one thing try defining foreign key along schema name ie testtvfilersfilerid test schema namethis solve problem,i starting sqlalchemy i wondering i going lot tables model i would like file table i model i currently using following code sqlalchemy import metadata sqlalchemyorm import scopedsession sessionmaker sqlalchemyextdeclarative import declarativebase sqlalchemydialects import postgresql import sqlalchemy sa session engine metadata sqlalchemy database engine updated modelinitmodel engine none sqlalchemy session manager updated modelinitmodel session scopedsessionsessionmaker global metadata if multiple databases overlapping table names need metadata database metadata metadata declarative table definitions base declarativebase basemetadata metadata schema srbamdev metapy following init py the application model objects import sqlalchemy sa sqlalchemy import orm models import meta modelsfilers import filer modelsvfilers import vfiler modelsfileroptions import fileroption def initmodelsengine call using tables classes model reflected tables must defined mapped global reflectedtable reflectedtable satablereflected metametadata autoloadtrue autoloadwithengine ormmapperreflected reflectedtable metaengine sacreateengineengine metasessionconfigurebindmetaengine class basictableobject id sacolumn postgresqluuid nullablefalse primarykeytrue created sacolumn satypesdatetimetrue nullablefalse modified sacolumn satypesdatetimetrue nullablefalse and following models modelsmeta import base modelsmeta import basictable modelsmeta import schema import sqlalchemy sa sqlalchemydialects import postgresql class filerbasebasictable this works fine long i start use foreign keys tables i use foreign key says sqlalchemyexcnoreferencedtableerror foreign key associated column tvfilersfilerid could find table tfilers generate foreign key target column id i tried define id key directly filer class remove basictable declaration however solve issue my code creating database looks like usrbinpython import configparser sqlalchemyengineurl import url models import config configparserrawconfigparser configread confcoreconf dburl url postgresqlpsycopg configget database username configget database password configget database host configget database port configget database dbname initmodelsdburl metabasemetadatadropallbindmetaengine metabasemetadatacreateallbindmetaengine does anyone idea fix issue,1 check crontab cmd execute cmd manually eg usrbinscrond runparts etccrondaily,i trying get crontab work doesnt seem want work the python script i need initialise every midnight works perfectly command terminal the location python script homervncbiblastdatabasebackupbackuppy my contab looks like shellbinbash pathsbinbinusrsbinusrbinhomervncbiblastdatabasebackup mailtoroot home for details see man crontabs example job definition minute hour day month month or janfebmarapr day week sunday or sunmontuewedthufrisat command executed usrbinpython homervncbiblastdatabasebackupbackuppy my python script looks like following usrbinpython subprocess import popen import datetime today datetimedatetoday today strtoday print today f openhomervncbiblastdatabasebackupssql today w x popenmysqldump u root p normalisation stdout f xwait fclose any idea im going wrong just looked cron logs got time entry i tried root bad file mode etccrontab i got error tried shell script aswell,1 there many multivalued complex functions functions one value corresponding point domain for example roots logarithms inverse trigonometric functions the reason functions multiple values usually inverse function multiple values domain map value when calculations functions would impractical always return possible values for inverse trigonometric functions infinitely many possible values usually different function values expressed function integer parameter k for example values log z z rcos isin log r kpi k integer for nth root rnexpitkpin kn inclusive because returning possible values impractical mathematical functions python almost common programming languages return called principal value function reference the principal value usually function value k whatever choice made stated clearly documentation so get complex roots complex number evaluate function relevant values k def rootsz n nthrootofr abszn phasez return maplambda k nthrootofrexptkpijn rangen you need import cmath module make work this gives rootsj j ej j,is possible calculate n complex roots given number using python i shortly checked looks like python gives wrongincomplete answers j produces j proper roots complex numbers every nonzero number n different complex number nth roots is possible python,2 this interesting question i eagerly waiting answers the document httpwikipythonorgmoindebuggingwithgdb mainly debugging segfaults hung python processes normal stepping python code i sure i understand intention do want break c python c api code certain python line reached then matter python code python code myobjfoo python code where myobjfoo calls c api then place breakpoint function attached myobjfoo breakpoint right location do need functionality simply looking natural way achieve,let say following megasimple python script print initializing print variable value print all done say i like debug script placing breakpoint line stepping script now i like use gdb i like debug python bindings may come part shared object library hence i ideally place breakpoint python code line step c part shared object note debuggingwithgdb pythoninfo wiki really explicitly state possible the problem gdb cannot really recognize breakpoints placed python script line gdb python gnu gdb gdb cvs reading symbols usrbinpythonno debugging symbols founddone gdb b testpy no symbol table loaded use file command make breakpoint pending future shared library load n breakpoint testpy pending gdb run testpy starting program usrbinpython testpy entire python script run within gdb breakpoint simply never reached so i want possible gdb alternatives would i something similar,1 if element added list condition met state condition separately add element met a list comprehension existing list want process elements way lst somevar true lstappend lstextend b c othervar lstappend lstappend e,i want join list conditional statement str njoina somevar true b c othervar e each element different conditional clause normal list comprehension suitable case the solution i thought lst somevar true else none b c othervar else none e str njoinitem item lst item none if elegant pythonic solution thanks meir more explanation in example somevar equals true othervar equals i would like get following string b c e if somevar false othervar equals i would like get following string b c e if somevar true othervar equals i would like get following string b c e,1 if something might six months like said chron job probably suitable keeping python program running whole time,what good way call function datetime python there ways i know are yet check date passed interval timesleepinterval this obviously bad it precise interval low becomes inefficient sleep difference timesleeptimedeltaseconds this better i like idea putting thread sleep insanely long time eg months date hybrid two sleep difference difference bellow interval if sleep interval prevent long sleeps i think best three think long sleeps interval seems bad anyway are ways think is anything standard library help call function datetime behind scene edit i asking i actually developed cron implementation python the problem i decide code wait next occurrence one differences implementation original cron support seconds so simply sleeping minimum possible interval second case inefficient i realize question could perhaps changed cron ie cron check date passed does run constantly process run minute i believe latter case inefficient interval second another difference code reads crontab calculates exact date datetime object next occurrence pattern while cron i assume simply checks minute pattern crontab matches current time i stick hybrid way way,1 no conversion needed mymodelobjectsfiltercountriesinunicodecountries,i using django python unicodecountries requestpostgetlistu countries returns u ai u ag u aw u bs my goals convert unicodecountries mysql in string look like ai ag aw bs i use mysql statement where countries ai ag aw bs please help,1 you pass range view,i saw question similar one i ask assume i select list option elements i want fill years example current year how i start iterating zero value value another value for example,1 i found quite nice solution import argparse def aarg arg kwargs print arg print arg name main parser argparseargumentparser parsersetdefaultsmethod parseraddargument arg type str parseraddargument arg type str arguments parserparseargs argumentsmethodvarsarguments of course minor problem arguments method clash names arguments argparse uses though i think preferable passing namespace object around using getattr,i writing relatively simple python script supports couple different commands the different commands support different options i want able pass options parsed argparse correct method specified command the usage string looks like usage scriptpy h b c scriptpy error arguments i easily call appropriate method def def b def c name main parser argparseargumentparser parsersetdefaultsmethod arguments parserparseargs argumentsmethod however i pass arguments methods accept different sets arguments currently i pass namespace object returned argparse like def aarguments arg getattrarguments arg none this seems little awkward makes methods little harder reuse i pass arguments dict namespace rather usual parameters i would like someway defining methods parameters would normal function still able call dynamically passing appropriate parameters like def aarg arg name main parser argparseargumentparser parsersetdefaultsmethod arguments parserparseargs argumentsmethod arguments passed somehow any ideas,2 assuming precision really issue taking square instead circle ignoring terrain could something like select from where absfirstlong secondlong and absfirstlat secondlat if wish make circle instead write slightly complicated mathematical formula distance sqrtlongdeltalongdelta latdeltalatdelta,i working application user search items near location when user registers service longlat coordinates taken actually grabbed zippostcode gets looked via google longlats this also happens user adds item asked zippostcode item converted longlat my question would run query using mysql would search within say miles user location get items within mile radius,1 when store latlon data also store called geospatial index basically string encodes pieces data one indexing scheme geohash algorithm uses sequence bits subdivide globe increasingly small boxes then want search distance first narrow scope search based geohash filter results testing euclidean distance using haversine formula another option use separate database specifically performing kind query for example mongodb natively supports geospatial indexing couchdb little help geocouch skipping back mysql presentation may help geo distance search mysql,i working application user search items near location when user registers service longlat coordinates taken actually grabbed zippostcode gets looked via google longlats this also happens user adds item asked zippostcode item converted longlat my question would run query using mysql would search within say miles user location get items within mile radius,1 looks weird integer automatically cast try funccint edit according ctypes doc exception could raised wrong calling convention cdecl instead stdcall but function still called sort warning be sure declaration dll if load library windll must use stdcall calling convention otherwise use cdll module,i trying access function dll pass value integer but i getting valueerror procedure probably called many arguments bytes excess my python py script funcrestype cint funcargtypes cint func my actual function dll simple function like int dllfunint argtest return argtest looks like simple problem i guessing i missing something kindly help cheers,2 as skimantas said i think install pythondev sudo aptget install pythondev i able install reportlab home directory command pip install reportlab without sudo mentioned earlier answer i need root access install pythondev shortly i installed virtualenv sudo aptget install pythonsetuptools sudo easyinstall virtualenv virtualenv nositepackages virtual i installed sudo aptget install pythondev i activate virtual environment sure source virtualbinactivate cd virtualbin pip install reportlab and i recorded i ubuntu lts,i trying install reportlab server virtualenv in reportlab folder i use python setuppy install error i get error command gcc failed exit status,3 this looks like something could get inspiration,i want create d table format data stored dictionary example id experiment experiment experiment id experiment experiment experiment id experiment experiment experiment should give following table experiment experiment experiment experiment id id id where idx row labels experimentx column names if dataset value column name empty string added placeholder can anybody help is ready format python i could use thanks advance,2 there disadvantages putting api initpy danger causing cycling dependencies obvious place look browsing code base putting api dedicated module like apipy elevates issues furthermore advantages like offer another api later second module simplified different use case etc big python projects like enthought traitsapi trac tracapi use pattern,i written python package consists several py files contain classes i want expose client using facade pattern so i want clients learn internal classes methods exposed api interface question i put api do i define file apipy inside package i put api initpy package i explain better example mymodule initpy corepy submodulepy submodulepy utilpy i put public api,1 lxml provides nice way handle things xml an example xml posted lxml import etree document etreeparse yourexamplexmlrdf root documentgetroot namespace shortcuts ns rootnsmapgetnone rdf rootnsmapget rdf item rootxpath purlitem namespaces purl ns print itemattribget sabout rdf print itemxpath purldescriptiontext namespaces purl ns print however rdf parsing might rdf specific libraries available,given following data rdfrdf xmlnshttppurlorgrss xmlnsrdfhttpwwwworgrdfsyntaxns xmlnsslashhttppurlorgrssmodulesslash xmlnsdchttppurlorgdcelements channel rdfabouthttpwwwgmanewstv titlegmanewstvtitle description gma newstv bring latest news gma news teams highlights favorite shows subscribe stay uptodate gma newstvdescription linkhttpwwwgmanewstvlink channel item rdfabouthttpwwwgmanewstvstoryworldmagnitudequakehitschileancoastnodamage dcformattexthtmldcformat dcdatetdcdate dcsourcehttpwwwgmanewstvstoryworldmagnitudequakehitschileancoastnodamage dcsource titlecdatamagnitude quake hits chilean coast damagetitle linkhttpwwwgmanewstvstoryworldmagnitudequakehitschileancoastnodamage link descriptioncdatasantiago a magnitude quake hit coast central chile early wednesday state emergency office said reports damagedescription item item rdfabouthttpwwwgmanewstvstorynationhouseminorityblamespnoysadvisersforlegalsetbacks dcformattexthtmldcformat dcdatetdcdate dcsourcehttpwwwgmanewstvstorynationhouseminorityblamespnoysadvisersforlegalsetbacks dcsource titlecdatahouse minority blames pnoy advisers legal setbacks title linkhttpwwwgmanewstvstorynationhouseminorityblamespnoysadvisersforlegalsetbacks link descriptioncdatamembers opposition house representatives wednesday blamed president benigno aquino iii advisers various legal setbacksampquot suffered administration advised consider replacing advisersdescription item item rdfabouthttpwwwgmanewstvstorynationexshariajudgeothersmaytestifyinpollfraudprobe dcformattexthtmldcformat dcdatetdcdate dcsourcehttpwwwgmanewstvstorynationexshariajudgeothersmaytestifyinpollfraudprobe dcsource titlecdataexshari judge others may testify poll fraud probetitle linkhttpwwwgmanewstvstorynationexshariajudgeothersmaytestifyinpollfraudprobe link descriptioncdatathe former shari court judge claimed helped gloria macapagalarroyo cheat presidential elections least others may serve witnesses joint investigation commission elections department justice alleged poll fraud comelec chief sixto brillantes jr said wednesdaydescription item rdfrdf now i want get details elements inside item tag this trivial i new python i quite sure i going parse rdf extract item inside edit i use third partie libraries script going run embeded system,1 instead using device manager a graphical application programmatically access information usb devices via pyusb import usbcore alldevs usbcorefindfindalltrue now iterate alldevs get information connected devices,how i access device manager python get usb device serial numberother info python,1 you move file temporary folder remove files older hours you try result servefileobjreturnfiledisposition attachment contenttype txt namefilename osunlinkfilename return result try use stringio file object wrap string look like file,i need create file server serve client i would prefer delete file server afterwards here i currently trying def myaction fs factsgeneratefactsintlowinthighintamountop filename testtxt file openfilename w filewritelines mynstuffnhere fileclose returnfile openfilename r return servefileobjreturnfiledisposition attachment contenttype txt namefilename myactionexposed true there several things i like i think i would open file twice example i would expect way write content directly response object without ever creating file object question today the code accomplishes i want leaves file behind if i delete file returning response course file found is way remove file soon served i coming java world i bit disoriented suggestions improve appreciated,1 a quick dirty implementation fixing typos question id experiment experiment experiment id experiment experiment experiment id experiment experiment experiment columnwidth stringwhenmissing paddingstring first determine columns first line columns id always least id column columns columns colname colname colvalue ditems print join colljustcolumnwidth col columns browse lines order id ascending rowid rowvalues sortedditems key lambda x xlower print rowid print rowvalues rowvaluesdict dictrowvalues make dict access key rowvaluesdictid rowid print rowvaluesdict print join strrowvaluesdictgetcol stringwhenmissingljustcolumnwidth paddingstring col columns this prints id experiment experiment experiment id id id note the format orginal dictionary bit strange i would expect something like id experiment experiment experiment id experiment experiment experiment some comments for kind things want read python string methods center ljust rjust add characters andor string force total width appart idea mostly looping listsdictionaries extract value note use dict method get allows default value value exists given key,i want create d table format data stored dictionary example id experiment experiment experiment id experiment experiment experiment id experiment experiment experiment should give following table experiment experiment experiment experiment id id id where idx row labels experimentx column names if dataset value column name empty string added placeholder can anybody help is ready format python i could use thanks advance,2 with manifestin specify files embedd archive way installed to tell pythondistutils want install files add setuppy fill parameter datafiles setup method this way able specify install additional files,i manifestin recursiveinclude tables csv i see folder included created targz mypackage mypackage mypackageegginfo tables i find folder i install package pip install mypackagetargz easyinstall mypackagetargz any clue,2 jinja tries safe htmlescaping data so use safe filter though i used django jinja i believe work formaspsafe,i testing jinja django project strange output when i render form characters html encoded amplt ampgt etc in template formasp it renders browser plabel foridusernameutilisateurlabel input autocompleteoff ididusername typetext nameusername maxlength p plabel foridpasswordmot de passelabel input autocompleteoff typepassword namepassword ididpassword p looking sources ampampltpampampgtampampltlabel forampampquotidusernameampampquotampampgtutilisateurampampltlabelampampgt ampampltinput autocompleteampampquotoffampampquot idampampquotidusernameampampquot typeampampquottextampampquot nameampampquotusernameampampquot maxlengthampampquotampampquot ampampgtampampltpampampgt ampampltpampampgtampampltlabel forampampquotidpasswordampampquotampampgtmot de passeampampltlabelampampgt ampampltinput autocompleteampampquotoffampampquot typeampampquotpasswordampampquot nameampampquotpasswordampampquot idampampquotidpasswordampampquot ampampgtampampltpampampgt does anyone know problem,3 a weeks ago write access posebosematrix the armaturespace matrix bone granted python api if using latest trunk could use something like code mathutils import matrix ob bpycontextobject globalvector vector mw bpydataarmatures armature bones handikr matrixcopy obglobal obmatrixworld bpycontextobjectposebones handikr matrix obmatrixworldinvertedmatrixtranslationglobalvectormwtoxtox conversion dimension back clears original translation add globalvector invert whole thing take object global matrix account for good code examples manipulating bones look blender addon motion capture here function baketransform retargetenduser,i want move bone blender following script bpycontextobjectposebones handikl locationxyz global xyz how convert xyz matrix manipulations corresponding xyz i want achieve movement bpyopstransformtranslatevaluexyzconst raintorientation global i found following code move parentless bone ob bpycontextobject globalvector vector mw bpydataarmatures armature bones handikr matrixcopy bpycontextobjectposebones handikr location mwinvertedglobalvector but bone parent connected thanx,1 if change code follows work class firstobject def initself p p strp the decision whether perform default action done following tryexcept block in reality block complicated checks performed order assure proper work try strimport import modules p print strimport e evalstrimport hasattre p raise importerror selfoverrideobj getattre pp except importerror e none default behaviour selfoverrideobj none selfp p def actself selfoverrideobj return selfoverrideobjact else print default behaviour,i want able dynamically load instance methods object instantiation according design default behaviour coded base class however certain conditions met object instatination i dynamically change behaviour another piece code this i the default behaviour coded firstpy class firstobject def initself p p strp the decision whether perform default action done following tryexcept block in reality block complicated checks performed order assure proper work try strimport import modules p e evalstrimport hasattre p raise importerror except importerror e none default behaviour e none selfact getattre ppact special behaviour selfp p def actself print default behaviour import cpickle pickle name main print first first first f firstact pickledumpfirst open firstdump w print third third first third thirdact pickledumpthird open thirddump w in code first third perform default action i change behaviour third adding file modulethirdpy follows temp import first class thirdfirst def initself p p third p print third init superselfclass selfinitp def actself superselfclass selfact print third acted after file added third changes behaviour however i unable pickle resulting object due following error traceback recent call last file ctemptemppy line module pickledumpfff open fffdump w file cpythonlibcopyregpy line reduceex raise typeerror pickle objects basename typeerror pickle instancemethod objects it clear dynamically loading method thirdact causing problems pickle how i need change approach order get pickable objects elegant code is better way acheive goal,1 try without join format first parameter cursorexecute select tname from translation name n where nid in and tlinkid nid and tlangid order by charlengthtname limit tupleobjpk obj self getlanguagelanguagecodepk,i method cusom queryset performs raw sql query database class querysetmodelsqueryqueryset def getshortself languagecode en returns shortest name given language cursor connectioncursor cursorexecute select tname from translation name n where nid in and tlinkid nid and tlangid order by charlengthtname limit join objpk obj self getlanguagelanguagecodepk name cursorfetchone name return name but returns empty result cursorfetchone return none instead value when i execute raw sql database select tname from translation name n where nid in and tlinkid nid and tlangid order by charlengthtname limit it returns properly value where i wrong please help,2 though solution indeed little cumbersome i first say rectangles rect rect iterate intended try sth like pos pygamemousegetpos rect rectangles rectcollidepointpos changecolorrect you implement changecolor method course generally i recommend creating class clickable fields defines method changecolor,this first question english good please bare well i need create clickable grid pygame right something like usrbinpython imports amp inits import pygame sys pygamelocals import pygameinit settings width height fps screen setup window pygamedisplaysetmodewidthheight caption pygamedisplaysetcaption test screen pygamedisplaygetsurface transparent pygamesurfacewidthheight transparentsetalpha transparentfill misc stuff rect pygamedrawrectscreen rect pygamedrawrectscreen rect pygamedrawrectscreen rect pygamedrawrectscreen refresh display pygamedisplayflip main loop true pos pygamemousegetpos mouse pygamedrawcircletransparent pos event detection event pygameeventget eventtype quit sysexit elif eventtype mousebuttondown rectcontainsmouse rect pygamedrawrectscreen pygamedisplayflip now original code far rectangles need way something like rectangles hasbeenclickedon change color obviously solution far static so could accomplish,2 the problem line code button tkinterbuttonroot textsubmit commanddisplaytext the command option takes reference command what instead calling command displaytext giving results command option you need remove actual command run associated option like button tkinterbuttonroot textsubmit commanddisplaytext,i using tkinter programming assignment following problem i want user enter value textbox i want add additional fields gui based number entered textbox heshe clicks submitbutton i tried place code inside function displaytext called submitbutton pressed however guirelated code i placed inside loaded window loaded import tkinter when user clicks button def displaytext do change in gui root tkintertk button tkinterbuttonroot textsubmit commanddisplaytext buttonpack rootmainloop,1 i know works idle normal terminal import sys def printtherex text sysstdoutwritexbxbddfsxb x text sysstdoutflush this uses ansiescape sequences,edit i discovered possible obtain similar behaviour using standard library curses there demonstrations works example youtube httpwwwyoutubecomwatchvbjhupeau it strange silly question i know i curious i know much python works from terminal use idle way print string certain screen position i try explain better do remember old days used make small programs basic maybe commodore apple ii zx spectrum during days wanted print string certain position used write something like locate print hello world i curious know way tell python print string certain position way know many columns many rows actually displayed inside idle window since english native language i also made mockup draw explain concept little bit better thank,3 easy solution def printline sep end n filenone default full if file none defaults sysstdout file none file sysstdout but please consider using print file identifiers print esp break python compatibility forever,i function following parameter list def printline sep end n filesysstdout default full unfortunately pydoc help text module shows like functions printline sep end n fileiotextiowrapper name stdout mode w encoding cp default full how i make pydoc give file argument filesysstdout rather showing gory details object python way,1 you call command line tool ossystem import os ossystem netsh interface ip set dns local area connection static,i want change dns servers programmatically i want build dns server i want change primary secondary dns servers automatically this work needs done python,3 you call animaleat using super super uses python method resolution order mro figure class call c overshadowing animal mro in example superwolf selfeat effect ceatself calling animaleatself works long inheritance graph stays way currently having call method available due mro indication class modelling needs improved,class animalobject def eatself printi eat class cobject def eatself printi eat class wolfc animal def eatself printi non veg superwolf selfeat animaleatself w wolf weat i learning multiple inheritance python i want access animal c method eat derived class using super method default call super inside calls c class method eat call animal class method i used animaleatself my question i call animal class method using super method,1 super used lookup parent classes in case set inheritance order c animal order preference method finding following first parent class second parent class so super return closest parent method a remark though search done depthfirst class aobject def tself print a class bobject def tself print b class ca pass class dc b pass d dt a,class animalobject def eatself printi eat class cobject def eatself printi eat class wolfc animal def eatself printi non veg superwolf selfeat animaleatself w wolf weat i learning multiple inheritance python i want access animal c method eat derived class using super method default call super inside calls c class method eat call animal class method i used animaleatself my question i call animal class method using super method,1 if want sane multiple inheritance need everyone calling super except exactly one base class duty call super having two completelyindependent base classes method something makes sense using oop theory something python tooling handle well you might see two apparentlyindependent base classes used lot examples cases example method usually init single nonsupercalling base class object,class animalobject def eatself printi eat class cobject def eatself printi eat class wolfc animal def eatself printi non veg superwolf selfeat animaleatself w wolf weat i learning multiple inheritance python i want access animal c method eat derived class using super method default call super inside calls c class method eat call animal class method i used animaleatself my question i call animal class method using super method,3 attention this answer outdated since time written use requests library httpdocspythonrequestsorgenlatest this code sample works it uses multipartposthandler uploading files import urllib import multipartposthandler params file open filenamejpg rb opener urllibbuildopenermultipartposthandlermultipartposthandler urllibinstallopeneropener req urllibrequest processphp params textresponse urlliburlopenreqreadstrip multipartposthandler available httppypipythonorgpypimultipartposthandler,hi guys i wondering one upload pics image hosting site programmatically python java python preferred the site gives ftp access upload button site ie http access now i want code herei cant figure start u guide right direction helpful form methodpost name enctypemultipartformdata actionprocessphp onsubmitreturn validateformthis input typehidden value idthevalue div idmydiv input typefile nameimagefile sizebrbr input typefile nameimagefile sizebrbr input typefile nameimagefile sizebrbr input typefile nameimagefile sizebrbr input typefile nameimagefile sizebrbr input typehidden namemaxfilesize value div pa hrefjavascript onclickaddelementupload moreap input typesubmit valueupload nameupload pp form web form,1 if least python use strformat select somefield count where timestamp endtimestamp group providerusername query sformattablename fromdate todate that way use variable multiple times string also note futureproof old formatting,writing following sql query select sometablenamesomefield count sometablename where sometablenametimestamp sometablenameendtimestamp group sometablenameproviderusername fromdate todata query used three tables want fix table name like select ssomefield count where stimestamp sendtimestamp group sproviderusername tablename tablename tablename fromdate tablename todata tablename could see query use tablename multiple times need provide tablename occurance best way achieve edited python use strformat reason move latest versionof python using python version best solution environment,2 you use named variables string formatting like select tablenamessomefield count tablenames where tablenamestimestamp fromdates tablenamesendtimestamp todatas group tablenamesproviderusername tablename tablename fromdate fromdate todata todata,writing following sql query select sometablenamesomefield count sometablename where sometablenametimestamp sometablenameendtimestamp group sometablenameproviderusername fromdate todata query used three tables want fix table name like select ssomefield count where stimestamp sendtimestamp group sproviderusername tablename tablename tablename fromdate tablename todata tablename could see query use tablename multiple times need provide tablename occurance best way achieve edited python use strformat reason move latest versionof python using python version best solution environment,3 you substitute dictionary mydict table whatever startdate yourstartdate enddate yourenddate sql select tablessomefield count tables where tablestimestamp startdates tablesendtimestamp enddates group tablesproviderusername mydict,writing following sql query select sometablenamesomefield count sometablename where sometablenametimestamp sometablenameendtimestamp group sometablenameproviderusername fromdate todata query used three tables want fix table name like select ssomefield count where stimestamp sendtimestamp group sproviderusername tablename tablename tablename fromdate tablename todata tablename could see query use tablename multiple times need provide tablename occurance best way achieve edited python use strformat reason move latest versionof python using python version best solution environment,1 it commas print statement if use following work print looking str filename,argc lensysargv argc argc printusage sysexit insensitive sysargv else boundaries b sysargv else filename sysargvargc str sysargvargc print looking str filename the output python countwordspy b footballtxt goal looking goal footballtxt why space goal footballtxt when i try print str filename variable spaces i also tried using strstrip print effect any ideas,2 the space sysargv caused use commas printing try print looking str filename and try avoid shadowing builtin str,argc lensysargv argc argc printusage sysexit insensitive sysargv else boundaries b sysargv else filename sysargvargc str sysargvargc print looking str filename the output python countwordspy b footballtxt goal looking goal footballtxt why space goal footballtxt when i try print str filename variable spaces i also tried using strstrip print effect any ideas,3 the print statement prints space arguments see documentation print statement a space written object converted written unless output system believes positioned beginning line you could try using string concatenation instead print looking filename better yet use strformat print looking formats filename note avoid using str variable name,argc lensysargv argc argc printusage sysexit insensitive sysargv else boundaries b sysargv else filename sysargvargc str sysargvargc print looking str filename the output python countwordspy b footballtxt goal looking goal footballtxt why space goal footballtxt when i try print str filename variable spaces i also tried using strstrip print effect any ideas,1 it passing separate strings print statement rather concatenating one string printing one go print b b print b ab note concatenating strings relatively expensive it better use interpolation like print a string placeholders a string placeholders,argc lensysargv argc argc printusage sysexit insensitive sysargv else boundaries b sysargv else filename sysargvargc str sysargvargc print looking str filename the output python countwordspy b footballtxt goal looking goal footballtxt why space goal footballtxt when i try print str filename variable spaces i also tried using strstrip print effect any ideas,2 i assume get button reads parameter value config file displays value why need one get button parameter i would one get button tham when user clicks get button every parameter read file displays updated a similar approach set button one set button button pressed every parameter new value entered updated config file parameters user entered new value remain previous values this scheme easier code easier user also however i really suggest look wxpropertygrid widget this potential make life lot easier here screenshot showing one action,this one questions really frustrating ask i sure answer i able word searches correctly basically i new gui programming done decent amount embedded cc learning wxpython start i making app read write config file so i statictext display name parameter readwritten textctrl display value allow user input get button set button i call together group widgets for app obviously group repeated several times rather write maintain code hand i thought would easier simply list config parameters i want able edit iterate list generate instance group widgets item list i made work except one thing i bind get buttons function same thing set buttons is way within functions know get set button pushed thus parameter find edit config file i sure way parent ids something i new oop,1 others already answered spaces question some suggestions str builtin function assign anything may wonder later work want use also insensitive sysargv else pretty much insensitive sysargv,argc lensysargv argc argc printusage sysexit insensitive sysargv else boundaries b sysargv else filename sysargvargc str sysargvargc print looking str filename the output python countwordspy b footballtxt goal looking goal footballtxt why space goal footballtxt when i try print str filename variable spaces i also tried using strstrip print effect any ideas,1 how import numpy np nparray reverse along last dimension b b although i like later less since first two dimensions implicit difficult see going,what simplest way numpy reverse inner values array like array i get following result array thank much,3 another suggestion instead parsing argv try optionparser let handle linux style optionflags optparse import optionparser parser optionparserusageusage prog b filename parseraddoptionb boundaries actionstoretrue destboundaries helpboundaries options arguments parserparseargs optionsboundaries b activated filename arguments,argc lensysargv argc argc printusage sysexit insensitive sysargv else boundaries b sysargv else filename sysargvargc str sysargvargc print looking str filename the output python countwordspy b footballtxt goal looking goal footballtxt why space goal footballtxt when i try print str filename variable spaces i also tried using strstrip print effect any ideas,1 with django version class based approach djangoconfurlsdefaults import patterns url djangoviewsgeneric import redirectview urlpatterns patterns urlr someurl redirectviewasviewurl redirecturl name someredirect this example lives urlspy,how i accomplish simple redirect eg cflocation coldfusion headerlocationhttp django,3 if switch deprecated sgmlparser modern alternative lxml also handles html becomes trivial etreefromstring td classschooltexas aampampmtd text texas aampm,i using python library sgmlparser parse html i encounter html tag form td classschooltexas aampampmtd i like read texas aampm but handledata gets called gets called texas a separately m quotes clarity how i replace ampamp string amp call without replacing special ampersands whole string i may need thanks,2 entity references like ampamp handled handleentity check method knows translate ampamp the default implementation call handledata amp may accidentally overwritten also possible consider using far advanced lxml instead,i using python library sgmlparser parse html i encounter html tag form td classschooltexas aampampmtd i like read texas aampm but handledata gets called gets called texas a separately m quotes clarity how i replace ampamp string amp call without replacing special ampersands whole string i may need thanks,1 in button event handler something like btn eventgeteventobject btngetid btngetname then use if statement decide based whatever info want use note set button name create button like setbtn wxbuttonself labelset namesetx you might find article wxpython configobj helpful httpwwwblogpythonlibraryorgconfigobjwxpythongeekhappiness,this one questions really frustrating ask i sure answer i able word searches correctly basically i new gui programming done decent amount embedded cc learning wxpython start i making app read write config file so i statictext display name parameter readwritten textctrl display value allow user input get button set button i call together group widgets for app obviously group repeated several times rather write maintain code hand i thought would easier simply list config parameters i want able edit iterate list generate instance group widgets item list i made work except one thing i bind get buttons function same thing set buttons is way within functions know get set button pushed thus parameter find edit config file i sure way parent ids something i new oop,1 sgmlparser convertentityref method instead deprecated sgmlparser i would recommend using lxml beautiful soup better parser api,i using python library sgmlparser parse html i encounter html tag form td classschooltexas aampampmtd i like read texas aampm but handledata gets called gets called texas a separately m quotes clarity how i replace ampamp string amp call without replacing special ampersands whole string i may need thanks,1 my gut says using something like graphviz render graphs wx deal ui good way go reimplementing graph drawing bits opengl seems like huge waste effort pygraphviz easy use could probably get something functional quickly tune necessary performance,situation similar question i looking way create gui users able see graph graph theory sense interact vehicles move across graph none node time users able add nodes edges add vehicles set destination i already implemented underlying graph model business logic i need gui this means i need graph algorithm functionality djistra algorithm if possible solution platform independent the underlying model written python gui solution either needs python based would preferable easily interface python potentially ipc performance concern it need blindingly fast must fast enough keep underlying model notionally limit number nodes edges vehicles may present graph possible approaches i looked various visualisation libraries nodebox networkx matplotlib graphviz i contemplated using opengl i thought drawing straight wxpython problems i used graph libraries i know capable providing required functionality for example matplotlib appears lot non graphtheory graphs gallery i find example someone implementing graph aside networkx for another example networkx plot objects travelling along edges an opengl solution would almost certainly take time implement i would code functions moving objects across edges i would code function drawing edges right place drawing labels edges nodes vehicles etc i would need implement menus handle interactions scratch i sure i would go implementing wxpython i know use conjunction standard widgets update i found question answer points wxlibogl wxlibfloatcanvas mechanism implementing solution pure wxpython questions do visualisation libraries meet requirements of suited are libraries i missed would meet requirements something like jgraph python instead java would suitable what opinion implementing opengl wxpython opposed one libraries are approaches i considered think would appropriate,2 file playerpy line minvalue typeerror unorderable types nonetype float important hints you consider actual error messages important almost anything else said problems since read error message left us guess line line there comparisons ie min v alpha function seem relevant the error message suggests v none since v come value return selfevaluationmove cellown looks like selfevaluation returning none this often happens return return without expression,i would like implement artificial intelligence checkers game i must understand principle alpha beta pruning nothing works i would like algorithm stops certain time secs but i think algorithm never stops in addition algorithm never cuts branch edit i errors file playerpy line minvalue v minv selfmaxvaluepboard singlemove pdue alpha beta file playerpy line maxvalue v maxv selfminvaluepboard singlemove pdue alpha beta file playerpy line minvalue file playerpy line minvalue v minv selfmaxvaluepboard singlemove pdue alpha beta file playerpy line maxvalue v maxv selfminvaluepboard singlemove pdue alpha beta file playerpy line minvalue typeerror unorderable types nonetype float if someone could explain clearly process implement i would grateful here i written python the evaluation function gives value relative position piece board def calcmoveself pboard pdue score validmoves pboardfindpossiblemovescellown move validmoves pboarddomovemove scoremove selfmaxvaluepboard move pdue float inf float inf scoremove score score scoremove bestmove move return bestmove def maxvalueself pboard move pdue alpha beta pdue timetime moveiseog return selfevaluationmove cellown v float inf validmoves pboardfindpossiblemovescellown singlemove validmoves pboarddomovesinglemove v maxv selfminvaluepboard singlemove pdue alpha beta v beta return v alpha maxalpha v return v def minvalueself pboard move pdue alpha beta pdue timetime moveiseog return selfevaluationmove cellother v float inf validmoves pboardfindpossiblemovescellother singlemove validmoves pboarddomovesinglemove v minv selfmaxvaluepboard singlemove pdue alpha beta v alpha return v beta minbeta v return v thanks help,2 the difference pretty simple the latter exist if application userdefined might call firstargumentclose something else killing dog,can somebody please explain difference following handler openprintfile w handlerclose handler openprintfile w closeprintfile,3 it relative import,in one python packages initpy file contains statement import xxxx what mean i got technique looking another package i understand means thanks,3 its relative import from httpdocspythonorgpykreferencesimplestmtshtmltheimportstatement when specifying module import specify absolute name module when module package contained within another package possible make relative import within top package without mention package name by using leading dots specified module package specify high traverse current package hierarchy without specifying exact names one leading dot means current package module making import exists two dots means one package level three dots two levels etc so execute import mod module pkg package end importing pkgmod if execute subpkg import mod within pkgsubpkg import pkgsubpkgmod the specification relative imports contained within pep,in one python packages initpy file contains statement import xxxx what mean i got technique looking another package i understand means thanks,3 import numpy np import itertools import csv year nprepeat sex nparray male female disease nprepeat draws nprandomnormal sizesexshape yearsnpuniqueyear diseasesnpuniquedisease drawsums dictyd drawsyearyampdiseasedsumaxis yd itertoolsproductyearsdiseases this results dict associating yeardisease corresponding sum draws to write drawsums csv could something like open tmptestcsv w f writercsvwriterf writerwriterow year date drawi formatii range yeardatedraws sorteddrawsumsitems writerwriterowlistyeardatedrawstolist,i wondering efficient way sum elements array given characteristics for example i draws data i i looking sum draw column across sexes given yeardisease ie draws sex year disease i want sum sexes year disease import numpy np year nprepeat sex nparray male female disease nprepeat draws nprandomnormal sizesexshape any thoughts get array shape sum draw across sexes given yeardisease i also need able situations data perfectly square diseaseyears sex,1 try force gtk refresh screen gtkeventspending forces refresh screen gtkmainiteration opening file,i python script requesting file user using filechooserdialog when done calls destroy dialog immediately begins load file since usually large file dialog stays imprinted screen parsing done main window created mainloop run is possible refresh x sth i really create loading window,2 my suggestion structure data follows root subroot idsomeid value idavalue value idbvalue value idcvalue value iddvalue value idvalue value idvalue value idotherxyzvalue subroot subroot idanotherid value idaavalue value idbbvalue value idccvalue value idvalue value idvalue value idvalue value idotherxxyyzzvalue subroot root then parse i suggest etree library standard library python i found far nicer work anything else it simple case iterating subroots value elements extracting data xmletree import elementtree xml elementtreeparsetestxml root xmlgetroot group rootfindallsubroot temp value groupfindallvalue tempvaluegetid valuetext allgroupgetid temp someid c b xyz anotherid aa cc bb xxyyzz you could also dict comprehension groupgetid valuegetid valuetext value groupfindallvalue group rootfindallsubroot note little hard read fall apart try anything complex,i xml file following structure root subroot idsomeid val valuea val valueb val valuec val value val value val value otherval valuexyz subroot subroot idanotherid val valueaa val valuebb val valuecc val value val value val value otherval valuexxyyzz subroot root i trying retrieve values tag for example desired output would vala valb valc val val val othervalxyz here nonworking code produces blanks ie val val def getvaluesself xmldomminidom import parsestring import json file open myfilexml r data fileread dom parsestringdata rows domgetelementsbytagnamerootgetelementsbytagnamesubroot valuestring row rows valuestring valuestringjsondumps val rowgetattributeval val rowgetattributeval val rowgetattributeval val rowgetattributeval val rowgetattributeval val rowgetattributeval rowgetattributeotherval sortkeystrue indent responsegenerator valuestring return httpresponseresponsegenerator othervalxyz i know thisactually produces json thats important the important thing able extract values i whatever afterwards can someone show i missing also i change xml valvalval called val thanks,2 you got couple issues query the correct dotted field name goalid elements objects nested arrays goalsgoalid remove preceding match the correct order gt friends gte lt lte field operator value like dbmycollectionfindgoalsgoalid gt,i using pymongo currently single collection the collection holds documents representing matches football league each match goals currently goals implemented list contained match object matchid goals goalid scorer a goalid scorer b matchid goals goalid scorer c goalid scorer d what i want query goals id higher say what i would expect data i would get goals how i implement mongodb i trying things like x mycollectionfind gt matchgoalsgoalid getting anywhere should i splitting goals separate collection manually referencing instead once goal entered never touched read,1 val etc attributes subroot row they child rows value attribute contains data want you need get children subroot iterate calling rowgetattributevalue and lattyware says yes rename elements,i xml file following structure root subroot idsomeid val valuea val valueb val valuec val value val value val value otherval valuexyz subroot subroot idanotherid val valueaa val valuebb val valuecc val value val value val value otherval valuexxyyzz subroot root i trying retrieve values tag for example desired output would vala valb valc val val val othervalxyz here nonworking code produces blanks ie val val def getvaluesself xmldomminidom import parsestring import json file open myfilexml r data fileread dom parsestringdata rows domgetelementsbytagnamerootgetelementsbytagnamesubroot valuestring row rows valuestring valuestringjsondumps val rowgetattributeval val rowgetattributeval val rowgetattributeval val rowgetattributeval val rowgetattributeval val rowgetattributeval rowgetattributeotherval sortkeystrue indent responsegenerator valuestring return httpresponseresponsegenerator othervalxyz i know thisactually produces json thats important the important thing able extract values i whatever afterwards can someone show i missing also i change xml valvalval called val thanks,1 execution rates honored appdevserver this issue occur production answer discovered nick johnson andor question author posting community wiki something get marked accepted,i confused task execution using queues i read documentation i thought i understood bucketsize rate i send tasks queue set h size tasks execute one quickly possible finishing less minute deferreddeferspamcookeggs eggkeys queuetortoise name tortoise rate h bucketsize what i want whether i create tasks i want run per hour so would take tasks approximately hours complete i want execution spread update the problem i assumed running locally task execution rate rules followed case you cannot test execution rates locally when i deployed production rate bucket size i set executed i expected,3 literal value converted expression construct sqlalchemy import literalcolumn bindparam bound bindparam bindparam literals rendered inline quoting applied literalcolumnstr literalcolumnstr,i created one function create expression def testoperator operation operator return literalcolumnoperatoropoperationoperator now i call test works but i pass test abc abc then gives error abc column i tried convert def testoperator operation operator return literalcolumnoperator stringopoperationoperator but working this work call test abc abc is way get type operator bases create literalcolum map type content,1 python full reflection you following modulenamepyd python import modulename mtmp dirmtmp helpmtmp edit add help command propose mike graham,so python pyd module c i open text editor find contains so i i want know function names inside,3 if want grammar precisely captures penn treebank sample comes nltk assuming downloaded treebank data nltk see comment import nltk nltkcorpus import treebank nltkgrammar import contextfreegrammar nonterminal tbankproductions setproduction sent treebankparsedsents production sentproductions tbankgrammar contextfreegrammarnonterminal s listtbankproductions this probably however give something useful since nltk supports parsing grammars terminals specified able parse sentences containing words treebank sample also flat structure many phrases treebank grammar generalize poorly sentences included training this nlp applications tried parse treebank used approach learning cfg rules treebank the closest technique would ren bods data oriented parsing approach much sophisticated finally unbelievably slow useless so want see approach action grammar single sentence prove works try following code imports minigrammar contextfreegrammarnonterminal s treebankparsedsentsproductions parser nltkparseearleychartparserminigrammar print parserparsetreebanksents,i fairly new nltk python i creating sentence parses using toy grammars given examples i would like know possible use grammar learned portion penn treebank say opposed writing using toy grammars i using python mac many thanks,3 at basic level first want provide basic plugin class base plugins written application next need import class pluginloader def initself path selfpath path def iterself dirpath dirs files oswalkselfpath dirpath syspath syspathinsert dirpath file files name ext ospathsplitextfile ext osextsep py importname none none plugin pluginsubclasses yield plugin in python instead importname none none consider import importlib importlibimportmodulename this loads every plugin file gives us plugins you would select plugins saw fit use multiprocessing import process pipe plugins plugin pluginloaderplugins select plugins selected pluginspluginname child pipe p processtargetplugin argschild pstart plugin pluginsvalues pluginputeventhappened plugin pluginsvalues event plugingetfalse event handle event this comes mind first obviously much would needed flesh good basis work,i relatively new python already h scripts like little webserver local network chat want program plugin manager my idea interface plugins following features getdependencies dependencies plugin plugins getfunctions functions plugin introduces initialize function called loading plugin i could imagine topological sorting algorithm dependencies decide order plugins initialized i would like implement multithreading meaning plugin runs thread working queue functioncalls executed serially when plugin calls function another plugin calls manager turn insert functioncall queue plugin further manager provide kind event system plugins register events become listeners events others also i want able reload plugin code changed thread crashed without shutting managerapplication i already read how i unload reload python module conjunction to make clear the manager provide functionality supporting plugins common communication interface ability run side side multithreaded manner without requiring plugins aware restoring updatedcrashed plugins so questions is possible python and yes design mistakes rough sketch i would appreciate good advice other literature implementing plugin system python,3 python builtin compiler bytecode python oo pycompile programpy produces pyo file contains bytecode docstrings removed etc you rename pyo file py extension python programpy runs like program contain source code ps if program imports modules obfuscated like need rename pyc suffix instead i sure break one day work pyo run python o …pyo imports work this allow python find modules otherwise python looks py modules,i looking hide python source code print hello world how i encode example humanreadable i told use base i sure,3 found solution one access content scipyiomatlabmioparamsmatstruct object investigated via v b dict c dict,using given routines load matlab mat files scipy i could access deeper nested structures recover dictionaries to present problem i run detail i give following toy example load scipyio spio b c dictionary b c spiosavemat xymat now i want read matfile back python i tried following vigspioloadmat xymat squeezemetrue if i want access fields i get vig b arrayarray dtype c o vig b c arrayarray dtype o dtypeobject vig b c valueerror traceback recent call last ipython console module valueerror field named found however using option structasrecordfalse field could accessed vspioloadmat xymat squeezemetruestructasrecordfalse now possible access v b cd array,1 run start new python process rather executes code current onenot current namespace current python process note documentation explains because sysmodules still around old cached module used are familiar way python caches imported modules normally to fix run new python process time reload little problematic lead headaches i find worth,in filepy def foo import file print i old filepy filebar name main foo in filepy print i old filepy def bar print i old filebar on line interactive session making modifications filepy filepy changing three occurrences word old new new code filepy still used wimwimubuntusandpit ipython run filepy i old filepy i old filepy i old filebar rm filepyc modify file file run filepy i new filepy i old filebar where getting old code filepy i must misunderstand something i thought ipython help run the file executed namespace initially consisting name main sysargv constructed indicated it thus sees environment run standalone program i deleted pyc file see command whos file module present namespace but import executed running file second time,2 class newsbodyresourcemodelresource class meta queryset articlebodyobjectsall resourcename articlebody class newsresourcemodelresource newsbodies fieldstomanyfield yourappapiresourcesnewsbodyresource articlebodyset fulltrue class meta queryset articleobjectsfilterstatus pu datepublishedltdatetimedatetimenoworderby datepublished resourcename news the parameters tomanyfield represent following respectively projectrelative import path resource representing set name field parent model relatedname attribute field child model whether embed full data child feed true resource links child false,how i bring information another model i two models article articlebody article containing main info articlebody containing loop body image information class articlemodelsmodel author modelsforeignkeyuser title modelscharfieldmaxlength excerpt modelscharfieldmaxlength nulltrue blanktrue helptext a description longer characters explains article important seo category modelsmanytomanyfieldcategory datepublished modelsdatetimefield slug modelsslugfieldnulltrue status modelscharfieldchoicesstatus maxlength default dr tags tagfielddefault nulltrue blanktrue helptext just add comma tags ie my important name hunting scope rifle sourcename modelscharfielddefault blanktrue nulltrue helptext outdoor magazine maxlength sourceurl modelsurlfieldverifyexistsfalse maxlength nulltrue blanktrue helptext httpwwwsourcecomlongname class articlebodyimagemodel article modelsforeignkeyarticle body modelstextfieldverbosename blanktrue nulltrue image modelsimagefieldstoragecloudfilesstorage uploadto articles default avatarblankjpg verbosename blanktrue nulltrue caption modelscharfieldmaxlength nulltrue blanktrue in api resourcespy file i trying get articlebody information newsresource this i far class newsbodyresourcemodelresource class meta queryset articlebodyobjectsall resourcename articlebody class newsresourcemodelresource class meta queryset articleobjectsfilterstatus pu datepublishedltdatetimedatetimenoworderby datepublished resourcename news what correct tastypie way making changes i get loop articlebody newsresource,3 as mentioned use future import absoluteimport use relative imports needed,i developing package following structure disk foo initpy xmlpy barpy moopy the xmlpy package provides class custom xml parsing translation package components using sax stream parser so import xmlsax import xmlsaxhandler but i go use fooxml application i get traceback recent call last file testxmlparserpy line module import fooxml file codefooxmlpy line module import xmlsax importerror no module named sax i appear namespace conflict if i rename xmlpy something else like xmlparserpy everything works expected but feels like wrong thing i feel like i missing something fundamental package names resolution python is proper way make work involve renaming fooxmlpy file or really solution conflicting names edit the avoid naming things standard python modules seemswella mineshaft that moving target standard module set bound change grow time so unless get really creative names renamethingsuntilyoufindsomethingthatdoesn tconflict solutions seems poor besides i got unique package name foo already i using foo something definitely unique enough,3 if already read section pyexe website dealing eggs i know effective i never install eggs pyexe tricky enough without dealing egg installed packages i would one following download mechanize source package unzip edit setuppy change zipsafe option false then install mechanize command line python setuppy install use pip install pip install mechanize of course install pip first easyinstall pip pip installs packages flat default fyi end using pip windows need beware handle python packages require compiling mechanize problem something start using regularity other egg issue nothing i see mechanize package structure would indicate pyexe would problems picking installed flat,i racked brain getting mechanize install without egg win i tried easyinstall allwaysunzip method the easyinstall z method added pth file sitepackages directory added combinations pyexe play nice egg files if got working please reply thanks brad some links i followed mechanize installed easyinstall how install mechanize python httpwwwdaniwebcomsoftwaredevelopmentpythonthreads httpwwwvelocityreviewscomforumstremechanizenotrecognizedbypyexehtml,2 i would suggest creating custom widget perhaps inheriting expander here tutorial subclassing widgets pygtk,i triying put dinamically several gtkexpander inside gtkvbox custom widgetlabel gtkhbox gtklabel gtkbuttongtkimage inside delete button something similar list widgets found macos x example automator image look close button right title bar expanders exactly would like the problem click delete gtkbuttongtkimage expander gets closed opened instead gtkbutton clickgtkimage eventnotifyrelease callback called event captured gtkexpander i opened new question since problem similar one rightclick pygtk hbox expander found solution also better solution would find specific widget task exists instead hack expander d,1 i think hamlpy best choice simple fast one would expect abstraction language httpwwwredditcomrdjangocommentskafbhtmltheeasyway,i rather like use something like haml django seems alternatives i really tell difference hamlpy i leaning towards one djaml makes easy use dmsl also known damsel sure differs hamlpy announced nice looking website shpaml seems general used generate templates pamela looks similar shpaml can anyone share experiences which besteasiest use django thanks edit thanks truereligion nemo pyhaml,1 use copy instead willing overwrite destination files if want first tree go away rmtree separately done iterating httpdocspythonorglibraryshutilhtmlshutilcopy httpdocspythonorglibraryshutilhtmlshutilrmtree update do oswalk source tree for directory check exists destination side osmakedirs missing for file simply shutilcopy file created overwritten whichever appropriate,i directory dst directory files folders i src directory also files folders what i want move contents src directory dst directory overwrite anyfiles exist name so example src directoryfiletxt needs moved dst directory overwrite existing filetxt the applies folders moving folder merging contents folder dst directory i currently using shutilmove move contents src dst files already exist merge folders put folder inside existing folder update to make things bit clearer what i unzipping archive dst directory moving contents src directory rezipping effectively updating files zip archive this repeated adding new files new versions files etc needs overwrite merge solved i solved problem using distutilsdirutilcopytreesrc dst copies folders files src directory dst directory overwritesmerges neccesary hope helps people hope makes sense thanks,3 python allow assignments expressions since lead confusing code python designed make hard write confusing code make simple write obvious code you simply write def lcmnd nd return printlcm python tests two objects object instead equal consider following e assert empty dictionaries equal assert identical assert e e refer object there equivalent operator javascript equivalent javascript python python type checking builtin types the conditional operator b c javascript written python b else c,i trying learn python background javascript i saw someone make recursive function find least common denominator wondered use loop experience amuse i wrote simpler one i came def lcmnd whilend continue return printlcm needless say know python valid operator i also tried def lcmnd whilend continue return printlcm to make sure thinking i tried thing javascript function lcmbd whilebd return so python allow expressions like javascript also indentation way define something i know semicolons required used anything like terms closing loop function definition finally python equalitywithouttypecoersion operator ps i realize function practical without checking input various things point writing pps also python equivalent javascript evaluation true false statement abbreviation,3 sure you use dictionary myquerysetfilters user selfrequestuser dateyear selfkwargs year recordobjectsfiltermyquerysetfilters the expands dictionary keyword arguments there also expands list positional arguments,i fairly new python django would like follow best practices possible i would like tidy following code make easier work i trying set view accessed multiple urls provide different parameters queryset returned displayed i set following urls urlr myrecords loginrequiredrecordlistviewasview filter name myrecords urlr myrecordspageppage loginrequiredrecordlistviewasview filter name myrecords urlr myrecordspyeard loginrequiredrecordlistviewasview filter year name myrecords urlr myrecordslastpmonthsmonths loginrequiredrecordlistviewasview filter month name myrecords then view i something like there actually several parameters remain regardless url entered def getquerysetself selfkwargs filter month xmonthsago datetimedatetoday datetimetimedeltaintselfkwargs months queryset recordobjectsfilteruserselfrequestuser dategte xmonthsagoisoformat elif selfkwargs filter year queryset recordobjectsfilteruserselfrequestuser dateyearselfkwargs year else queryset recordobjectsfilteruserselfrequestuser this seems messy is anyway i make cleaner is possible put filter parameters sort data structure pass recordobjectsfilter line rather writing whole thing multiple times any advice would greatly appreciated thanks,3 this go source directory create directories already exist destination directory move files source destination directory import os import shutil rootsrcdir src directory rootdstdir dst directory srcdir dirs files oswalkrootsrcdir dstdir srcdirreplacerootsrcdir rootdstdir ospathexistsdstdir osmakedirsdstdir file files srcfile ospathjoinsrcdir file dstfile ospathjoindstdir file ospathexistsdstfile osremovedstfile shutilmovesrcfile dstdir any preexisting files removed first via osremove replace corresponding source file any files directories already exist destination source remain untouched,i directory dst directory files folders i src directory also files folders what i want move contents src directory dst directory overwrite anyfiles exist name so example src directoryfiletxt needs moved dst directory overwrite existing filetxt the applies folders moving folder merging contents folder dst directory i currently using shutilmove move contents src dst files already exist merge folders put folder inside existing folder update to make things bit clearer what i unzipping archive dst directory moving contents src directory rezipping effectively updating files zip archive this repeated adding new files new versions files etc needs overwrite merge solved i solved problem using distutilsdirutilcopytreesrc dst copies folders files src directory dst directory overwritesmerges neccesary hope helps people hope makes sense thanks,3 let start searching little bit find largest number expressible sum two abundant numbers actually then solve problem simple set membership test plus runs pretty fast usrbinenv python coding utf math import sqrt def dn sum sqrtn proper divisors start range intt n sum n count square root twice intt sum return sum limit sum set sets faster lists needs abn set n range limit dn n abnaddn difference number examining every number set set number sum two abundant numbers otherwise must add sum question na abn abn sum n runs seconds average based timeit,i trying solve project euler question a perfect number number sum proper divisors exactly equal number for example sum proper divisors would means perfect number a number n called deficient sum proper divisors less n called abundant sum exceeds n as smallest abundant number smallest number written sum two abundant numbers by mathematical analysis shown integers greater written sum two abundant numbers however upper limit cannot reduced analysis even though known greatest number cannot expressed sum two abundant numbers less limit find sum positive integers cannot written sum two abundant numbers my solution returns list divisors given number def divsnumber divisors range intnumber number divisorsappendi q rangelendivisors divisorsq number divisorsq divisorsappendnumber divisorsq divisorsinsert return divisors returns list abundant numbers including limit def ablistlimit abundant rangelimit sumdivsi abundantappendi return abundant finds sum positive integers cannot written sum two abundant numbers def absumlimit abundant ablistlimit noabsum range limit absum x x abundant x abundanti absum break absum noabsum return noabsum this took ghz processor minutes solve i searching better way i concerned first two functions together take less second run the third function kicker it runs range numbers limit case something time runs list abundant numbers subtracting current number checking answer list abundant numbers if match loop breaks tries next number way limit i know got better way i somewhat new programming how i speed algorithm,1 maybe interest anyone brmechanizebrowserfactorymechanizerobustfactory this resolve problem html parser,got little mechanize code bropen httptumblrcomcustomize print brresponseread print brform edittumblelogcname definitely edittumblelog brform edittumblelogenablecname works fine output br input typetext classtextfield stylewidthpx minwidthpx marginpx px bordersolid px ddd namecname idcname onchangeformchanged true valueblogyaycom traceback recent call last file tmptemptextmatewpgh line module print brform edittumblelogcname file librarypythonsitepackagesclientformpyeggclientformpy line getitem file librarypythonsitepackagesclientformpyeggclientformpy line findcontrol file librarypythonsitepackagesclientformpyeggclientformpy line findcontrol clientformcontrolnotfounderror control matching name edittumblelogcname what i wrong,3 is way process innermost decode others i cleanly replace decode statements case statements yes use decode place nested decode legally occur run regex loop be aware fail strings ie then values contain word decode if know data rule case regex approach goodenough oneoff use case,i migrating sql one platform another the sql contains decode statements supported target platform i using regular expressions translate decode statements case statements i failing nested decodes import sqlfrag select decodedim dim myfield decodedim dim myfield regrecompiledecodereignorecase matches regfindallsqlfrag match matches sqlfrag sqlfragreplacematch case else end matchmatchmatchmatch match occurrences decode select decodedim dim myfield decodedim dim myfield replace case statements select case dim else dim end myfield case dim else dim end myfield but code trips nested decode statements sqlfragselect decodefdecodeff myfield decodefoobarbazfoo myfield regfindallsqlfrag decodefdecodeff f decodeff decodefoobarbazfoo foo bar baz foo returns select case f else decodeff end myfield case foo bar baz else foo end myfield is way process innermost decode others i cleanly replace decode statements case statements,1 i sure would work cases def somepythonkungfumeth obj get bound method obj corresponding method meth return getattrobj methimfuncname,imagine f function member class instance class a def bself print hey a f ab if i another instance class let say c a i reconstruct new ff using f c calling ff would result cb instead ab c a ff somepythonkungfufc ff calling cb,2 it confusing first code really need virtual environment directory actually better put code inside environment might want use different environments code example test code different versions python different versions library virtualenvwrapper put environments single place virtualenvwrapper convenient tool top virtualenv need put code environments different places maybe get bit comfortable virtualenv starting use virtualenvwrapper you let paster create directory project name this directory commit version control eg git mercurial you want commit directory containing virtual environment,i new pyramid paster reading docs i use virtualenv inside virtualenv dir i want start pyramid project the problem i would like paster create dir project name instead put scaffold files current dir venv root i thought using paster i still know point app developmentini use option i could also virtualenv entirely different place filesystem seems weird maybe virtualenvwrapper could make easier any way,2 you session management python you session management framework may implemented python a session implemented many ways normally implemented via cookies for example django python framework writes cookie value called session containing given string say aabbccddeeff for every request django checks whether cookie exists maps user this far trivial however use django robust web frameworks language completely transparent if know cookie unfamiliar web security i think problem tackle use framework understand,i created application python and i using extjs frontend once valid user logs i want use username logged user transactions i wanted urgent help session management done python thanks advance,1 if use framework framework provide session management beaker popular library examples httpsbeakergroovieorgsessionshtmlusing show store username session object,i created application python and i using extjs frontend once valid user logs i want use username logged user transactions i wanted urgent help session management done python thanks advance,1 you run socket server thread import threading import socketserver server socketservertcpserver localhost socketserverbaserequesthandler th threadingthreadtargetserverserveforever thdaemon true thstart,how i socket server running accepts incoming connections deals part code code waiting new connections stuck loop i starting trying learn would tcp handler useful i need simple examples topic i wanting something like commands portion server so certain things server running edit what i trying tcp server multiple clients respond one time needed text input availability time used gettingsetting info a simple way getsave client address info currently using list save,1 so want know rebind already bound method another instance using bound method instance it done like def somepythonkungfumeth obj return typemethmethfunc obj objclass the func attribute really ned batchelders imfunc func forwardcompatible python there one case work methods builtin classes the func imfunc attributes available userdefined classes therefore fail ordinary rabbit b consult book armaments bsplit somepythonkungfuasplit b a slight modification ned solution work builtin userdefined classes def somepythonkungfumeth obj return getattrobj methname so always work well stumbling block rather obscure i guess seldom occuring problem name method methname name class dictionary b getattr either return wrong attribute raise attributeerror for example def externalself pass class aobject b external here abname external instead b getattrobj external called instead getattrobj b while previous approaches problems one builtin classes one patchedtogether classes problems occur simultaneously circumstance therefore combination work cases def somepythonkungfumeth obj try return typemethmethfunc obj objclass except attributeerror meth builtin method methname always correct return getattrobj methname as explained elsewhere page best bet would probably ignore whole mess cleaner way like instance using unbound methods passing first argument self manually cixates answer but knows may prove useful day perhaps somewhat bizarre set circumstances,imagine f function member class instance class a def bself print hey a f ab if i another instance class let say c a i reconstruct new ff using f c calling ff would result cb instead ab c a ff somepythonkungfufc ff calling cb,2 you still matching line change still iteration loop,python i need read files large gb what i need go file matches pattern then print line every line matches another pattern at point resume reading file next pattern match for example file contains alpha zeta text lines bravo delta text lines etc if matching alpha zeta print alpha zeta every line encounters bravo delta whatever alpha zeta read right matches alpha zeta the following matches looking prints matching line text follows any idea i going wrong import fh open texttxt r any single character any single character any single character any single character white space alpha word rea azaz word alternate white space any single character any single character any single character any single character white space zeta word rea azaz word alternate rg recompilerererererererererererererereignorecaseredotall rga recompilererererererearerererererereareignorecaseredotall line fh rematchrg line print line fhnext rematchrga line print fhnext fhclose example text file pappa oscar lorem ipsum dolor sit amet consectetur adipiscing elit mauris eleifend imperdiet lacus quis imperdiet nulla erat neque laoreet vel fermentum dapibus sem maecenas elementum nisi nec neque pellentesque ac rutrum urna cursus nam non purus sit amet dolor fringilla venenatis integer augue neque scelerisque ac dictum venenatis elementum libero etiam nec ante augue porttitor laoreet aenean ultrices pellentesque erat id porta nulla vehicula id cras eu ante nec diam dapibus hendrerit ac diam vivamus velit erat tincidunt id tempus vitae tempor vel leo donec aliquam nibh mi non dignissim justo alpha zeta sed molestie tincidunt euismod morbi ultrices diam nibh varius congue nulla velit erat luctus ac ornare vitae pharetra quis felis sed diam orci accumsan eget commodo eu posuere sed mi phasellus non leo erat mauris turpis ipsum mollis sed ismod nec aliquam non quam vestibulum sem eros euismod ut pharetra sit amet dignissim eget leo charley oscar cum sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus aliquam commodo metus vulputate hendrerit dui justo tempor dui posuere ante vitae lorem fusce rutrum nibh erat condimentum laoreet nullam eu hendrerit sapien suspendisse id lobortis urna maecenas ut suscipit nisi proin et metus urna euismod sollicitudin eu mi aliquam ac egestas magna quisque ac vestibulum lectus duis ac libero magna et volutpat odio cras mollis tincidunt nibh vel rutrum curabitur fringilla ante eget scelerisque rhoncus libero nisl porta leo ac vulputate mi erat vitae felis praesent auctor fringilla rutrum aenean sapien ligula imperdiet sodales ullamcorper ut vulputate enim bravo delta donec cursus tincidunt pellentesque maecenas neque nisi dignissim ac aliquet ac vestibulum ut tortor pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas aenean ullamcorper dapibus accumsan aenean eros tortor ultrices adipiscing sed lobortis nec dolor fusce eros ligula posuere quis porta nec rhoncus et leo curabitur turpis nunc accumsan posuere pulvinar eget sollicitudin eget ipsum sed nibh ac est porta sollicitudin pellentesque ut urna ut risus pharetra mollis tincidunt sit amet sapien sed semper sollicitudin eros quis pellentesque curabitur ac metus lorem ac malesuada ipsum nulla turpis erat congue eu gravida nec egestas id nisi praesent tellus ligula pretium vitae ullamcorper vitae gravida eu ipsum cras sed erat ligula alpha zeta cras id condimentum lectus sed sit amet odio eros ut mollis sapien etiam varius tincidunt quam nec mattis nunc eu varius magna maecenas id ante nisl cras sed augue ipsum non mollis velit fusce eu urna id justo sagittis laoreet non id urna nullam venenatis tincidunt gravida proin mattis est sit amet dolor malesuada sagittis curabitur lacus rhoncus mi posuere ullamcorper phasellus eget odio libero ut lacinia orci pellentesque iaculis ligula varius vulputate arcu leo dignissim massa non adipiscing lectus magna nec dolor quisque libero nec orci vestibulum dapibus nulla turpis massa varius quis gravida eu bibendum et nisl fusce tincidunt laoreet elit sed egestas diam pharetra eget maecenas lacus velit egestas nec tempor eget hendrerit et massa update the following code work matches header type row prints every line next header type pattern match skips next header type pattern only problem really really butt slow it takes minute lines any single character any single character any single character any single character white space alpha word rea azaz word alternate white space any single character any single character any single character any single character white space zeta word rea azaz word alternate rg recompilerererererererererererererereignorecaseredotall rga recompilererererererearerererererereareignorecaseredotall linestop fh open testtxt r line fh linestop rematchrg line print line linestop else rematchrga line linestop else print line fhclose if i add grep part first thinking speed things tremendously ie grep run regex script i got ossystem work good i see pass regex match via popen final update i calling completed what i ended grep file using ossystem writing results reading file using rematch i printing necessary items net result went taking seconds read million line file printing necessary items seconds i wish i could figured pass grep ossystem maybe well implimented python,1 for measuring elapsed cpu time look timeclock this equivalent linux times user time field for benchmarking use timeit the datetime module part python also microsecond time supported platform example import datetime dt ndtdatetimenow ndtdatetimenow nnmicroseconds nmicrosecondnmicroseconde ie took seconds type second n line slow nresolution datetimetimedelta e resolution claimed if concerned system time changes ds st check object returned datetimepresumably system time could small adjustment ntp reference adjustment this slewed corrections applied gradually ntp sync beats effect small millisec microsec time references you also reference alex martelli c function want something resolution i would go far reinvent wheel accurate time basic modern os pretty good job edit based clarifications sounds like need simple side check system clock changed just compare friendly local ntp server import socket import struct import time ntppoolntporg whatever ntp server handy client socketsocket socketafinet socketsockdgram data xb clientsendto data ntp data address clientrecvfrom data print response received address structunpack i data l seconds since epoch print ttimes timectimet ntp accurate milliseconds internet representation resolution resolution − seconds picoseconds should good enough be aware ntp bit data structure overflow every years thereafter really want robust solution better check overflow,is simple way module correctly measure elapsed time python i know i simply call timetime twice take difference yield wrong results system time changed granted happen often indicate i measuring wrong thing using timetime measure durations incredibly roundabout think you take difference two absolute time measurements turn constructed duration measurements performed timers known absolute times set manually via ntp interested so way query timer time directly i imagine represented millisecond microsecond value meaningful absolute representation thus need adjusted system time looking around bit seems exactly systemnanotime java i find corresponding python function even though hardwaretechnically easier provide timetime edit to avoid confusion address answers this dst changes i want cpu time either i want elapsed physical time it need finegrained even particularly accurate it give negative durations durations several orders magnitude granularity someone decided set system clock different value here python docs say timetime while function normally returns nondecreasing values return lower value previous call system clock set back two calls this exactly i want avoid since lead strange things like negative values time calculations i work around moment i believe good idea learn using proper solutions feasible since kludges come back bite one day edit some research shows get system time independent measurement like i want windows using gettickcount linux get return value times however i still find module provides functionality python,3 identifier none obj none else objid,say i following python code obj none identifier none else identifier objid obj python object whose class definition included i barely remember concise syntax like oneline code achieve if i dreaming someone please advise simpler syntax might thanks,3 identifier getattrobj id none,say i following python code obj none identifier none else identifier objid obj python object whose class definition included i barely remember concise syntax like oneline code achieve if i dreaming someone please advise simpler syntax might thanks,1 do click option element want selected,i using selenium webdriver firefox usually combobox eg months i set distinct month sendkeysmonthname i special listbox time i simply sendkeys webdriver manually i web developer i idea actual difference this html code combobox div classselectarea marke stylewidth px span classleftspan span classcentermonthspan span classselectbuttonspan div classdisabled styledisplay none div div select namesregisterdmc idsregisterdmc classmarke outtahere stylewidthpx multiple option valuemonthoption option valueoption options select i idea i could set option i found i get option values findelementsbytagname i actually set one thanks advance,1 defaults work way you need derivedproperty derivedproperty def etagself return hashlibmdselfimghexdigest,what i trying fly storing image datastore i would like fill entry mdsum image use later outputting image i feel like dummy error i looked cant see right code snippet import hashlib googleappengineapi import urlfetch googleappengineext import db def getimgurl result urlfetchfetchurl resultstatuscode return resultcontent else return none class imageblobsdbmodel img dbblobpropertydefaultnone lastupdate dbdatetimepropertyautonowtrue etag dbstringpropertydefaulthashlibmdimghexdigest img imageblobsimggetimg httpwwwarealdomaincomaworkingimagepng imgput the error typeerror must convertible buffer blobproperty ideassuggestions i solve little problem,1 import datetime tdatetimedatetimeutcnow tdatetimedatetimeutcnow tt datetimetimedelta using utc avoids embarassing periods clock shifts due daylight saving time as using alternate method rather subtracting two clocks aware os actually contain clock initialized hardware clock pc modern os implementations also keep clock synchronized official source drift this much accurate interval timer pc might running,is simple way module correctly measure elapsed time python i know i simply call timetime twice take difference yield wrong results system time changed granted happen often indicate i measuring wrong thing using timetime measure durations incredibly roundabout think you take difference two absolute time measurements turn constructed duration measurements performed timers known absolute times set manually via ntp interested so way query timer time directly i imagine represented millisecond microsecond value meaningful absolute representation thus need adjusted system time looking around bit seems exactly systemnanotime java i find corresponding python function even though hardwaretechnically easier provide timetime edit to avoid confusion address answers this dst changes i want cpu time either i want elapsed physical time it need finegrained even particularly accurate it give negative durations durations several orders magnitude granularity someone decided set system clock different value here python docs say timetime while function normally returns nondecreasing values return lower value previous call system clock set back two calls this exactly i want avoid since lead strange things like negative values time calculations i work around moment i believe good idea learn using proper solutions feasible since kludges come back bite one day edit some research shows get system time independent measurement like i want windows using gettickcount linux get return value times however i still find module provides functionality python,2 i see need use regex not bad looking specific pattern overkill use regex try something like def recordfilename pattern openfilename file recording false line file linestartswithpattern yield line recording recording elif recording yield line calling record filename pattern gives generator object yielding line line this better dealing large files slurp printing lines could work like assuming file named exampletxt rec recordfilename alpha zeta print rec to precise the record generator yields lines including line breaks might want join back together without additional line breaks print joinlistrecordfilename alpha zeta,python i need read files large gb what i need go file matches pattern then print line every line matches another pattern at point resume reading file next pattern match for example file contains alpha zeta text lines bravo delta text lines etc if matching alpha zeta print alpha zeta every line encounters bravo delta whatever alpha zeta read right matches alpha zeta the following matches looking prints matching line text follows any idea i going wrong import fh open texttxt r any single character any single character any single character any single character white space alpha word rea azaz word alternate white space any single character any single character any single character any single character white space zeta word rea azaz word alternate rg recompilerererererererererererererereignorecaseredotall rga recompilererererererearerererererereareignorecaseredotall line fh rematchrg line print line fhnext rematchrga line print fhnext fhclose example text file pappa oscar lorem ipsum dolor sit amet consectetur adipiscing elit mauris eleifend imperdiet lacus quis imperdiet nulla erat neque laoreet vel fermentum dapibus sem maecenas elementum nisi nec neque pellentesque ac rutrum urna cursus nam non purus sit amet dolor fringilla venenatis integer augue neque scelerisque ac dictum venenatis elementum libero etiam nec ante augue porttitor laoreet aenean ultrices pellentesque erat id porta nulla vehicula id cras eu ante nec diam dapibus hendrerit ac diam vivamus velit erat tincidunt id tempus vitae tempor vel leo donec aliquam nibh mi non dignissim justo alpha zeta sed molestie tincidunt euismod morbi ultrices diam nibh varius congue nulla velit erat luctus ac ornare vitae pharetra quis felis sed diam orci accumsan eget commodo eu posuere sed mi phasellus non leo erat mauris turpis ipsum mollis sed ismod nec aliquam non quam vestibulum sem eros euismod ut pharetra sit amet dignissim eget leo charley oscar cum sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus mus aliquam commodo metus vulputate hendrerit dui justo tempor dui posuere ante vitae lorem fusce rutrum nibh erat condimentum laoreet nullam eu hendrerit sapien suspendisse id lobortis urna maecenas ut suscipit nisi proin et metus urna euismod sollicitudin eu mi aliquam ac egestas magna quisque ac vestibulum lectus duis ac libero magna et volutpat odio cras mollis tincidunt nibh vel rutrum curabitur fringilla ante eget scelerisque rhoncus libero nisl porta leo ac vulputate mi erat vitae felis praesent auctor fringilla rutrum aenean sapien ligula imperdiet sodales ullamcorper ut vulputate enim bravo delta donec cursus tincidunt pellentesque maecenas neque nisi dignissim ac aliquet ac vestibulum ut tortor pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas aenean ullamcorper dapibus accumsan aenean eros tortor ultrices adipiscing sed lobortis nec dolor fusce eros ligula posuere quis porta nec rhoncus et leo curabitur turpis nunc accumsan posuere pulvinar eget sollicitudin eget ipsum sed nibh ac est porta sollicitudin pellentesque ut urna ut risus pharetra mollis tincidunt sit amet sapien sed semper sollicitudin eros quis pellentesque curabitur ac metus lorem ac malesuada ipsum nulla turpis erat congue eu gravida nec egestas id nisi praesent tellus ligula pretium vitae ullamcorper vitae gravida eu ipsum cras sed erat ligula alpha zeta cras id condimentum lectus sed sit amet odio eros ut mollis sapien etiam varius tincidunt quam nec mattis nunc eu varius magna maecenas id ante nisl cras sed augue ipsum non mollis velit fusce eu urna id justo sagittis laoreet non id urna nullam venenatis tincidunt gravida proin mattis est sit amet dolor malesuada sagittis curabitur lacus rhoncus mi posuere ullamcorper phasellus eget odio libero ut lacinia orci pellentesque iaculis ligula varius vulputate arcu leo dignissim massa non adipiscing lectus magna nec dolor quisque libero nec orci vestibulum dapibus nulla turpis massa varius quis gravida eu bibendum et nisl fusce tincidunt laoreet elit sed egestas diam pharetra eget maecenas lacus velit egestas nec tempor eget hendrerit et massa update the following code work matches header type row prints every line next header type pattern match skips next header type pattern only problem really really butt slow it takes minute lines any single character any single character any single character any single character white space alpha word rea azaz word alternate white space any single character any single character any single character any single character white space zeta word rea azaz word alternate rg recompilerererererererererererererereignorecaseredotall rga recompilererererererearerererererereareignorecaseredotall linestop fh open testtxt r line fh linestop rematchrg line print line linestop else rematchrga line linestop else print line fhclose if i add grep part first thinking speed things tremendously ie grep run regex script i got ossystem work good i see pass regex match via popen final update i calling completed what i ended grep file using ossystem writing results reading file using rematch i printing necessary items net result went taking seconds read million line file printing necessary items seconds i wish i could figured pass grep ossystem maybe well implimented python,2 if use old python version without conditional expressions resort evaluation semantics boolean expressions the value boolean expression value term expression determines final value that sounds quite abstract case say obj none none objid if obj none true none objid none objid as none represents true value ed expression without changing value expression result none none if obj none false none objid false objid objid objid this simulate ternary operator aka conditional expression former times the general pattern b else c b c,say i following python code obj none identifier none else identifier objid obj python object whose class definition included i barely remember concise syntax like oneline code achieve if i dreaming someone please advise simpler syntax might thanks,1 see httpdocsscipyorgdocscipyreferencegeneratedscipymiscfromimagehtmlscipymiscfromimage you say databack scipymiscfromimagepixback rmax numpymaxdataback gmax numpymaxdataback bmax numpymaxdataback much faster looping rgb triplets image then dataold scipmiscfromimagepixold r dataold pixback rmax g dataold pixback gmax b dataold pixback bmax datanew numpyarrayrgb imnew scipymisctoimagedatanew the code tested work somehow minor modifications,i working little problem sparetime involving analysis images obtained microscope it wafer stuff ultimately i want make program detect certain materials show anyways first step normalize intensity across image since lens give uniform lightning currently i use image stuff substrate background reference image i find maximum three intensity values rgb pil import image pil import imagedraw rmax gmax bmax rmin gmin bmin imold imageopentestimagepng imback imageopenbackgroundpng maxx imoldsize import size image maxy imoldsize imnew imagenewrgb maxxmaxy pixback imbackload x rangemaxx rangemaxy pixbackxy rmax rmax pixbackxy pixbackxy gmax gmax pixbackxy pixbackxy bmax bmax pixbackxy pixnew imnewload pixold imoldload x rangemaxx rangemaxy r floatpixoldxy floatpixbackxyrmax g floatpixoldxy floatpixbackxygmax b floatpixoldxy floatpixbackxybmax pixnewxy rgb the first part code determines maximum intensity red green blue channels pixel pixel background image needs done the second part takes real image stuff normalizes red green blue channels pixel pixel according background this takes time seconds x image way slow i need several images what i improve speed i thought moving images numpy arrays i seem find fast way rgb images i rather move away python since c quite lowlevel getting working fortran code would probably take longer i could ever save terms speed p,1 can use method reference class instead instance reference class a def whoamiself print i idself a c a func awhoami funca funcc,imagine f function member class instance class a def bself print hey a f ab if i another instance class let say c a i reconstruct new ff using f c calling ff would result cb instead ab c a ff somepythonkungfufc ff calling cb,2 if zip file folder loop never executes just like print hello print anything elements iterate if need error message filelist globglobospathjoinrootdir zip filelist f filelist code else print no files,i loop checks folder contains zip file file globglob ospathjoinrootdir zip print zip file check file exist ospathexistsfile print no files return else code now file exist else works zip file print happen any suggestions thank,1 if zip files looping empty list try something like files globglob ospathjoinrootdir zip lenfiles file files print zip file check file exist ospathexistsfile print file exist return else code else print no files,i loop checks folder contains zip file file globglob ospathjoinrootdir zip print zip file check file exist ospathexistsfile print no files return else code now file exist else works zip file print happen any suggestions thank,1 mapint def fool dtypelong return mapdtype l,i would like something like def fooxdtypelong return magicfunctionchanginglisttypetodtypex ie list full str list full int easy way nested lists ie change type int,3 overload setattr example class fooobject def setattrself attr val print setattr attr selfdict print new attr attr selfdictattr val else print extant attr attr selfdictattr val,i would like special obj following objnewlycreatedattribute somevalue obviously objects allow but i would like previous code automatically call method newlycreatedattribute yet attribute obj in particular case i wish set custom get set method objnewlycreatedattribute property is way some way specify callback run whenever new attribute added object,2 you accomplish overriding setattr class someclassobject def setattrself name value hasattrself name print new attribute name stuff return objectsetattrself name value,i would like special obj following objnewlycreatedattribute somevalue obviously objects allow but i would like previous code automatically call method newlycreatedattribute yet attribute obj in particular case i wish set custom get set method objnewlycreatedattribute property is way some way specify callback run whenever new attribute added object,3 setattr help called attribute assignment attempted this called instead normal mechanism ie store value instance dictionary name attribute name value value assigned usrbinenv python class klassobject def setattrself name value hasattrself name selfonfirstsetattr return objectsetattrself name value def onfirstsetattrself print i callback story seldom told obj klass objsomeattr call callback objsomeattr output,i would like special obj following objnewlycreatedattribute somevalue obviously objects allow but i would like previous code automatically call method newlycreatedattribute yet attribute obj in particular case i wish set custom get set method objnewlycreatedattribute property is way some way specify callback run whenever new attribute added object,3 import numpy np pil import image def normalizearr linear normalization httpenwikipediaorgwikinormalizationimageprocessing arr arrastype float do touch alpha channel range minval arrimin maxval arrimax minval maxval arri minval arri maxvalminval return arr def demonormalize img imageopenfilenameconvert rgba arr nparrayimg newimg imagefromarraynormalizearrastype uint rgba newimgsave tmpnormalizedpng,i working little problem sparetime involving analysis images obtained microscope it wafer stuff ultimately i want make program detect certain materials show anyways first step normalize intensity across image since lens give uniform lightning currently i use image stuff substrate background reference image i find maximum three intensity values rgb pil import image pil import imagedraw rmax gmax bmax rmin gmin bmin imold imageopentestimagepng imback imageopenbackgroundpng maxx imoldsize import size image maxy imoldsize imnew imagenewrgb maxxmaxy pixback imbackload x rangemaxx rangemaxy pixbackxy rmax rmax pixbackxy pixbackxy gmax gmax pixbackxy pixbackxy bmax bmax pixbackxy pixnew imnewload pixold imoldload x rangemaxx rangemaxy r floatpixoldxy floatpixbackxyrmax g floatpixoldxy floatpixbackxygmax b floatpixoldxy floatpixbackxybmax pixnewxy rgb the first part code determines maximum intensity red green blue channels pixel pixel background image needs done the second part takes real image stuff normalizes red green blue channels pixel pixel according background this takes time seconds x image way slow i need several images what i improve speed i thought moving images numpy arrays i seem find fast way rgb images i rather move away python since c quite lowlevel getting working fortran code would probably take longer i could ever save terms speed p,2 list comprehensions print ints nested print ints sublist sublist,i would like something like def fooxdtypelong return magicfunctionchanginglisttypetodtypex ie list full str list full int easy way nested lists ie change type int,1 here fairly simple recursive function converting nested lists depth def nestedchangeitem func isinstanceitem list return nestedchangex func x item return funcitem nestedchange int nestedchange int,i would like something like def fooxdtypelong return magicfunctionchanginglisttypetodtypex ie list full str list full int easy way nested lists ie change type int,3 that text namespace abbreviation defined odf schema try treexpath texta texth namespaces text urnoasisnamestcopendocumentxmlnstext set union operator see also lxml docs,i trying parse contentxml inside odffile i read file string got tree object lxmletree tree etreexmlstring but i need find every subelement texta or texth i told previous question i could use xpath i tried got stuck every single time can even find one elements if try elem treexpath textp i get xpathevalerror undefined namespace prefix so i get list both thoose subelements right order iterate,1 apparently latest version modwsgi compatible python according pep httpcodegooglecompmodwsgi the original wsgi specification pep supports python x there support modwsgi python x based guesses wsgi specification would look like python x the new wsgi specification pep finally accepted although tweaks need made modwsgi make strict write python wsgi application according pep work perfectly fine modwsgi if wish experiment python x need use python later,what wsgi servers available python pep,3 use exec method for example say dictionary want turn key variable original dictionary value following c one two kv citeritems execss kv one two,i want create variables dynamically via loop python anyone creative means,3 as pointed gabriel apachemodwsgi x supports python other options cherrypy wsgi server uwsgi,what wsgi servers available python pep,3 answering good comments led improvement understanding python variables as noted comments loop list something like member mylist member variable bound successive list element however reassigning variable within loop directly affect list for example code change list mylist member mylist member print mylist output if want change list containing immutable types need something like mylist ndx member enumeratemylist mylistndx print mylist output if list contains mutable objects modify current member object directly class c def initself n selfnum n def reprself return strselfnum mylist ci xrange member mylist membernum print mylist note still changing list simply modifying objects list you might benefit reading naming binding,i originally thought python pure passbyreference language coming cc i help think memory management hard put head so i trying think java perspective think everything primitives pass reference problem i list containing bunch instances user defined class if i use foreach syntax ie member mylist printmemberstr is member equivalent actual reference object is equivalent lenmylist printmylisti i think not i looking replace work work member mylist member someotherobj member someotherobj a simple find replace list can done foreach loop else i simply use random access syntax square brackets neither work i need remove entry insert new one ie member mylist member someotherobj mylistremovei mylistinserti member,3 you could replace something getting index along item foo b c a b c index item enumeratefoo printindex item b c a b c index item enumeratefoo item a fooindex replaced foo replaced b c replaced b c note want remove something list iterate copy list else get errors since trying change size something iterating this done quite easily slices wrong foo b c item foo isinstanceitem int fooremoveitem foo b c the still modified size list iterated the correct way would foo b c item foo isinstanceitem int fooremoveitem foo b c,i originally thought python pure passbyreference language coming cc i help think memory management hard put head so i trying think java perspective think everything primitives pass reference problem i list containing bunch instances user defined class if i use foreach syntax ie member mylist printmemberstr is member equivalent actual reference object is equivalent lenmylist printmylisti i think not i looking replace work work member mylist member someotherobj member someotherobj a simple find replace list can done foreach loop else i simply use random access syntax square brackets neither work i need remove entry insert new one ie member mylist member someotherobj mylistremovei mylistinserti member,3 so make way httpsgistgithubcom import sys gevent import server geventbaseserver import tcplistener gevent import pywsgi geventmonkey import patchall patchall multiprocessing import process currentprocess cpucount def helloworldenv startresponse env pathinfo startresponse ok contenttype texthtml return bhello worldb else startresponse not found contenttype texthtml return hnot foundh listener tcplistener def serveforeverlistener pywsgiwsgiserverlistener helloworldserveforever numberofprocesses print starting processes numberofprocesses rangenumberofprocesses processtargetserveforever argslistenerstart serveforeverlistener,the following code taken httpsbitbucketorgdenisgeventsrcceaebexampleswsgiserversslpy implements extremely fast greenlet powered wsgi webserver usrbinpython secure wsgi server example based geventpywsgi gevent import pywsgi def helloworldenv startresponse env pathinfo startresponse ok contenttype texthtml return bhello worldb else startresponse not found contenttype texthtml return hnot foundh print serving https server pywsgiwsgiserver helloworld keyfile serverkey certfile servercrt start server asynchronously call serverstart use blocking serveforever jobs serverserveforever however runs one core how would modify take advantage multiple processes not looking answer involves gunicorn looking something simpler hint here code sample using gevent multiprocessing i still figure make work wsgi taken httpsgistgithubcom import sys gevent import server geventbaseserver import tcplistener geventmonkey import patchall patchall multiprocessing import process currentprocess cpucount def noteformat args sysstderrwrite stsn currentprocessname formatargs def echosocket address print new connection ss address fileobj socketmakefile fileobjwrite welcome echo server type quit exitrn fileobjwrite in srn currentprocessname fileobjflush true line fileobjreadline line print client disconnected break linestriplower quit print client quit break fileobjwritecurrentprocessname line fileobjflush print echoed reprline listener tcplistener def serveforeverlistener note starting server serverstreamserverlistener echoserveforever numberofprocesses print starting processes numberofprocesses rangenumberofprocesses processtargetserveforever argslistenerstart serveforeverlistener,2 you might want look defaultdict collections module the following equivalent examples collections import defaultdict data b b defaultdictlist k v data dkappendv there,the following two expressions seem equivalent which one preferable data b b key val data variant dkey dgetkey val variant dsetdefaultkey appendval the results version better rather pythonic personally i find version harder understand setdefault tricky grasp if i understand correctly looks value key dictionary available enters dict returns reference either value appends val reference while certainly smooth intuitive least least to mind version easier understand available get value key get join list made val place result key but intuitive understand i fear version less performant list creating another disadvantage occurs twice expression rather errorprone probably better implementation using get presently eludes my guess version although difficult grasp inexperienced faster therefore preferable opinions,3 this really bike shedding create project virtualenv irrelevant place either anywhere including within however really want paster create pyramidstarter currentdirectoryname create project within current directory to create new project cd workmyrepo virtualenv nositepackages env envbinpip install pyramid envbinpaster create pyramidstarter myrepo git init echo env gitignore git add i usually setting new machine cd work git clone pathtomy repogit cd myrepo virtualenv nositepackages env envbinpip install e equivalent envbinpython setuppy develop using setup i mentioned want add env directory gitignore file,i new pyramid paster reading docs i use virtualenv inside virtualenv dir i want start pyramid project the problem i would like paster create dir project name instead put scaffold files current dir venv root i thought using paster i still know point app developmentini use option i could also virtualenv entirely different place filesystem seems weird maybe virtualenvwrapper could make easier any way,1 i believe point right direction httpmatplotlibsourceforgenetexamplespylabexamplesbarchartdemohtml the part interested def autolabelrects rect rects height rectgetheight plttextrectgetxrectgetwidth height intheight ha center va bottom the placement text determined height function height column number put top column written intheight so need create array strings called name want top columns iterate be sure change format string double def autolabelrects attach text labels iirect enumeraterects height rectgetheight plttextrectgetxrectgetwidth height nameii ha center va bottom autolabelrects that,i bar chart i want column display texthow i,3 your two examples thing mean get setdefault the difference two basically manually setting dkey point list every time versus setdefault automatically setting dkey list unset making two methods similar possible i ran timeit import timeit print timeitc dget cextend c number print timeitc dget cextend c number print timeitdsetdefault extend number print timeitdsetdefault extend number got so setdefault around faster get purpose the get method allows less setdefault you use avoid getting keyerror key exist something going happen frequently even want set key see use cases setdefault dict method dictget method returns pointer info two methods the thread setdefault concludes time want use defaultdict the thread get concludes slow often better speed wise double lookup using defaultdict handling error depending size dictionary use case,the following two expressions seem equivalent which one preferable data b b key val data variant dkey dgetkey val variant dsetdefaultkey appendval the results version better rather pythonic personally i find version harder understand setdefault tricky grasp if i understand correctly looks value key dictionary available enters dict returns reference either value appends val reference while certainly smooth intuitive least least to mind version easier understand available get value key get join list made val place result key but intuitive understand i fear version less performant list creating another disadvantage occurs twice expression rather errorprone probably better implementation using get presently eludes my guess version although difficult grasp inexperienced faster therefore preferable opinions,3 the example functions state edit two completely different things linux times returns process times cpu milliseconds python equivalent timeclock ostimes windows gettickcount returns system uptime although two different functions potentially could used reveal system clock burp methods first you could take system time timetime cpu time timeclock since wall clock time always greater equal cpu time discard measurements interval two timetime readings less paired timeclock check readings example ttimetime tchecktimeclock timed event ttimetime tchecktimeclock tt tcheck tcheck print things rotten denmark discard sample else second getting system uptime also promising concerned system clock since user reset reset uptime tick count cases i aware now harder question getting system uptime platform independent way especially without spawning new shell sub second accuracy hmmm probably best bet psutil browsing source use uptime gettickcount f windows sysctl kernboottime bsd os x etc unfortunately second resolution,is simple way module correctly measure elapsed time python i know i simply call timetime twice take difference yield wrong results system time changed granted happen often indicate i measuring wrong thing using timetime measure durations incredibly roundabout think you take difference two absolute time measurements turn constructed duration measurements performed timers known absolute times set manually via ntp interested so way query timer time directly i imagine represented millisecond microsecond value meaningful absolute representation thus need adjusted system time looking around bit seems exactly systemnanotime java i find corresponding python function even though hardwaretechnically easier provide timetime edit to avoid confusion address answers this dst changes i want cpu time either i want elapsed physical time it need finegrained even particularly accurate it give negative durations durations several orders magnitude granularity someone decided set system clock different value here python docs say timetime while function normally returns nondecreasing values return lower value previous call system clock set back two calls this exactly i want avoid since lead strange things like negative values time calculations i work around moment i believe good idea learn using proper solutions feasible since kludges come back bite one day edit some research shows get system time independent measurement like i want windows using gettickcount linux get return value times however i still find module provides functionality python,1 pheadfooabc python using module way faster import time import rec recompile pheadfooabc rec recompile fooabc total total def timerever x abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz timetime ver recsubdef x else recsubdef x return timetime x xrange total timere x xrange total timere print total print total outputs edit run times calls loop x xrange total timere total timere outputs edit fixing sub match question import time import rec recompile pheadfooabc rec recompile fooabc total total def timerever x abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz timetime ver recsubgheaddef x else recsubdef x return timetime x xrange total timere total timere print total print total outputs run run run edit string match regex import time import rec recompile pheadfooabc rec recompile fooabc total total def timerever x abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzheadtailheadtailabcdefghijklmnopqrstuvwxyzheadfoobarabcdefghijklmnopqrstuvwxyzabcdefghiojklmnopqrstuvwyz timetime ver recsubgheaddef x else recsubdef x return timetime x xrange total timere total timere print total print total output and one final run import time import rec recompile pheadfooabc rec recompile fooabc total total def timerever x abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzheadtailheadtailabcdefghijklmnopqrstuvwxyzheadfoobarabcdefghijklmnopqrstuvwxyzabcdefghiojklmnopqrstuvwyz timetime ver recsubgheaddef x else recsubdef x return timetime x xrange total timere total timere print method avg run took f with total f total total print method avg run took f with total f total total output method avg run took with total method avg run took with total,spheadfooabcgheaddef sfooabcdef which efficient are ways make efficient please note although i used perlstyle syntax illustration purposes i actually using python library allow k keep keyword,3 rpmbuild get pretty smart one cases it probably pulled usrlocalbinpython one script files containing something like usrlocalbinpython top try grep ing path files within bz file,because i install multiple versions python multiple oracle linux servers built via kickstart process i wanted build python rpm yum repository i able build python manually using make altinstall install default system python installation i thought would way go after much trial error i managed build rpm starting bz python package i try install i get error error failed dependencies usrlocalbinpython needed pythoni what python i trying install and system default python usrbinpython and prototyping location python directory tmppython executable tmppythonbinpython so looking usrlocalbin here core rpm spec prep setup q build configure prefixtmppython make install make altinstall i take closer look rpm build log i see requires binsh tmppythonbinpython usrbinenv usrlocalbinpython libcso libcsoglibca lot ok usrlocalbin comes now question determining requirements did i specify something wrong do i need override something like many rpm newbies i get build part i really grok happens end rpmbuild actually gets put rpm file files specify files actually happens rpm install can anyone suggest install failing i might read understand rpm build requiring i trying build,3 python java cc need stop thinking way really utilize power python python passbyvalue passbyreference instead uses passbyname passbyobject words nearly everything bound name use two obvious exceptions tuple listindexing when spam green bound name spam string object green eggs spam copied anything made reference pointers simply bound another name eggs object green case if bind spam something else spam eggs still bound green when forloop executes takes name give binds turn object iterable running loop call function takes names function header binds arguments passed reassigning name actually rebinding name take absorb anyway with forloops utilizing lists two basic ways assign back list item enumeratesomelist somelisti processitem newlist item somelist newlistappendprocessitem somelist newlist notice last somelist causing mutation somelist elements setting entire thing newlist elements instead rebinding name somelist newlist is important it depends if names besides somelist bound list object want see updates need use slicing method want see updates rebind somelist newlist,i originally thought python pure passbyreference language coming cc i help think memory management hard put head so i trying think java perspective think everything primitives pass reference problem i list containing bunch instances user defined class if i use foreach syntax ie member mylist printmemberstr is member equivalent actual reference object is equivalent lenmylist printmylisti i think not i looking replace work work member mylist member someotherobj member someotherobj a simple find replace list can done foreach loop else i simply use random access syntax square brackets neither work i need remove entry insert new one ie member mylist member someotherobj mylistremovei mylistinserti member,3 the excel dialect specified following attributes libcsvpy line delimiter quotechar doublequote true skipinitialspace false lineterminator rn quoting quoteminimal i see hint somehow localedependent hence always get default dialect but easily fixed eg class excelsemicoloncsvexcel delimiter writer csvwriteropendatacsv wb dialectexcelsemicolon,disclaimer i europe according page excel uses semicolon default separator europe prevent conflicts decimal comma now i python code import csv data test data foo bar writer csvwriteropendatacsv wb dialectexcel writerwriterowsdata which generate file testdata foobar instead uses commas why happening localegetdefaultlocale returns nlnl cp,3 you able fix issue adding following line spec file autoreq here understanding necessary when rpmbuild runs across py files shebang automatically add binary shebang specifies requirement not shebang usrbinenv python add dependency whatever resolves first python path you either need turn automatic requirement processing find shebangs cause problems change something else,because i install multiple versions python multiple oracle linux servers built via kickstart process i wanted build python rpm yum repository i able build python manually using make altinstall install default system python installation i thought would way go after much trial error i managed build rpm starting bz python package i try install i get error error failed dependencies usrlocalbinpython needed pythoni what python i trying install and system default python usrbinpython and prototyping location python directory tmppython executable tmppythonbinpython so looking usrlocalbin here core rpm spec prep setup q build configure prefixtmppython make install make altinstall i take closer look rpm build log i see requires binsh tmppythonbinpython usrbinenv usrlocalbinpython libcso libcsoglibca lot ok usrlocalbin comes now question determining requirements did i specify something wrong do i need override something like many rpm newbies i get build part i really grok happens end rpmbuild actually gets put rpm file files specify files actually happens rpm install can anyone suggest install failing i might read understand rpm build requiring i trying build,3 this csvexcel dialect locale aware if wish explicitly use semicolons delimiter need either explicitly pass delimiter csvopen writer csvwriteropendatacsv wb delimiter create new dialect register class excelsemicoloncsvexcel delimiter registerdialectexcelsemicolon excelsemicolon in either case test floating point numbers written i suspect written european format desire comma radix,disclaimer i europe according page excel uses semicolon default separator europe prevent conflicts decimal comma now i python code import csv data test data foo bar writer csvwriteropendatacsv wb dialectexcel writerwriterowsdata which generate file testdata foobar instead uses commas why happening localegetdefaultlocale returns nlnl cp,3 import modile whole import foreignmodule what claim drawback actually benefit namely prepending tne module name makes code easier maintain makes selfdocumenting six months look line code like foo barbaz may ask module bar came foo cleverlibbar much less mystery of course fewer imports less problem for small programs dependencies really matter much when find asking questions like ask makes code easier understand rather makes code easier write you write read lot,i developing python package dealing scientific data there multiple frequentlyused classes functions modules packages including numpy i need virtually every function defined module package what would pythonic way deal i considered multiple variants every drawbacks import classes modulelevel foreignmodule import class class function function then imported functions classes easily accessible every function on hand pollute module namespace making dirpackagemodule helppackagemodule cluttered imported functions import classes functionlevel foreignmodule import class class function function the functions classes easily accessible pollute module imports dozen modules every function look lot duplicate code import modules modulelevel import foreignmodule not much pollution compensated need prepend module name every function class call use artificial workaround like using function body manipulations returning objects exported like def export foreignmodule import class class function function def myfuncx return functionx functionx return myfunc myfunc export del export this manages solve problems module namespace pollution ease use functions seems pythonic so solution pythonic is another good solution i overlooked,3 the versionerpythonpreferbit environment variable applesupplied feature it applies applesupplied system pythons mac os x from path shown using nonsystem python installed libraryframeworks possibly pythonorg installer versionerpythonpreferbit affect have tried launching development server something like arch usrlocalbinpython djangoadminpy you still may run trouble django launches python interpreters subprocesses default bit you either get everything working bit mode stick complete bit chain python mysqldb you could save lot trouble installing complete solution thirdparty distributor like macports homebrew,i finally resolved ubiquitous mysqlpythonosx bit debacle python mysql working fine using bit mysql calling python arch py scripts outside django correctly querying mysql etc however i try fire django invoke development server i getting error i getting previously using bit python djangocoreexceptionsimproperlyconfigured error loading mysqldb module dlopenlibraryframeworkspythonframeworkversionslibpythonsitepackagesmysqlso suitable image found did find libraryframeworkspythonframeworkversionslibpythonsitepackagesmysqlso macho wrong architecture in bashprofile i alias python arch python export versionerpythonpreferbitno export versionerpythonpreferbityes so i understand django invoking python honoring i bashprofile what i need change django get invoke bit python the full traceback i python managepy runserver traceback recent call last file managepy line module executemanagersettings file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangocoremanagementbasepy line execute translationactivate enus file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangoutilstranslationinitpy line activate return transactivatelanguage file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangoutilstranslationtransrealpy line activate activevalue translationlanguage file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangoutilstranslationtransrealpy line translation defaulttranslation fetchsettingslanguagecode file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangoutilstranslationtransrealpy line fetch app importmoduleappname file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangoutilsimportlibpy line importmodule importname file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangocontribadmininitpy line module djangocontribadminhelpers import actioncheckboxname file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangocontribadminhelperspy line module djangocontribadminutil import flattenfieldsets lookupfield file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangocontribadminutilpy line module djangodb import models file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangodbinitpy line module connection connectionsdefaultdbalias file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangodbutilspy line getitem backend loadbackenddb engine file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangodbutilspy line loadbackend return importmodule base backendname file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangoutilsimportlibpy line importmodule importname file libraryframeworkspythonframeworkversionslibpythonsitepackagesdjangodbbackendsmysqlbasepy line module raise improperlyconfigurederror loading mysqldb module e djangocoreexceptionsimproperlyconfigured error loading mysqldb module dlopenlibraryframeworkspythonframeworkversionslibpythonsitepackagesmysqlso suitable image found did find libraryframeworkspythonframeworkversionslibpythonsitepackagesmysqlso macho wrong architecture,1 for situation i would go allimportspy file foreignmodule import another module import working modules import allimports fgn whatever want prepend something fgnclass another thing aware func func now functionsclassesvariablesetc module modules show help imported mymodule import see making python imports structured info,i developing python package dealing scientific data there multiple frequentlyused classes functions modules packages including numpy i need virtually every function defined module package what would pythonic way deal i considered multiple variants every drawbacks import classes modulelevel foreignmodule import class class function function then imported functions classes easily accessible every function on hand pollute module namespace making dirpackagemodule helppackagemodule cluttered imported functions import classes functionlevel foreignmodule import class class function function the functions classes easily accessible pollute module imports dozen modules every function look lot duplicate code import modules modulelevel import foreignmodule not much pollution compensated need prepend module name every function class call use artificial workaround like using function body manipulations returning objects exported like def export foreignmodule import class class function function def myfuncx return functionx functionx return myfunc myfunc export del export this manages solve problems module namespace pollution ease use functions seems pythonic so solution pythonic is another good solution i overlooked,2 i would compromise pick short alias foreign module import foreignmodule fm it saves completely pollution probably bigger issue least reduces prepending burden,i developing python package dealing scientific data there multiple frequentlyused classes functions modules packages including numpy i need virtually every function defined module package what would pythonic way deal i considered multiple variants every drawbacks import classes modulelevel foreignmodule import class class function function then imported functions classes easily accessible every function on hand pollute module namespace making dirpackagemodule helppackagemodule cluttered imported functions import classes functionlevel foreignmodule import class class function function the functions classes easily accessible pollute module imports dozen modules every function look lot duplicate code import modules modulelevel import foreignmodule not much pollution compensated need prepend module name every function class call use artificial workaround like using function body manipulations returning objects exported like def export foreignmodule import class class function function def myfuncx return functionx functionx return myfunc myfunc export del export this manages solve problems module namespace pollution ease use functions seems pythonic so solution pythonic is another good solution i overlooked,1 you could packages reportlab producing pdf calendar getting month lists lists python binding ghostscript transform pdf produced png you would start getting data calendar package using reportlab produce page us letter size the table manipulated grid cell box size alter text font size alignment you could leave want pdf convert pdf image using ghostscript python bindings or like run ghostscript using system gs also ghostscript must installed python ghostscript package work if want filter weekends use good old fashioned list manipulation calendar data here example could produce pdf i going whole year single month i going bother filtering zeros reportlablibunits import inch reportlablib import colors reportlablibpagesizes import letter reportlabplatypus import simpledoctemplate table tablestyle reportlabgraphicsshapes import drawing import calendar doc simpledoctemplate calendarpdf pagesizeletter cal mon tue wed thu fri sat sun calextendcalendarmonthcalendar table tablecal inch lencal inch tablesetstyletablestyle font helvetica font helveticabold fontsize innergrid colorsblack box colorsgreen align center valign middle create pdf docbuildtable if want another page add pagebreak followed next calendar list passed docbuild pagebreak part reportlabplatypus and convert pdf png import ghostscript args gs seems matter put st position dsafer dbatch dnopause sdevicepngm r soutputfilecalendarpng calendarpdf ghostscriptghostscriptargs both reportlab ghostscript packages available use pip i created virtualenv environment reportlab httpwwwreportlabcomsoftwareopensourcerltoolkit ghostscript python bindings httpsbitbucketorghtgoebelpythonghostscript calendar part standard python library,how i produce printable pdf file us letter sized page represents month partitioned day month gets box equal size what i want skip weekends display weekdays what python modules would i use accomplish following producing image resolution us letter iterating day month option skip specific days eg weekends partitioning image day month listed box fixed size repeating steps months given year producing pdf output,3 yes but expect standard modules build some system calls translate it would lot work port,would technically possible embed python flexair application compiling cpython code using alchemy i guessing project called flython,1 what seem looking monotonic timer a monotonic time reference jump go backwards there several attempts implement cross platform monotomic clock python based os reference windows posix bsd quite different see discussions attempts monotonic time so post mostly use ostimes ostimes return tuple floating point numbers indicating accumulated processor times seconds the items user time system time children’s user time children’s system time elapsed real time since fixed point past order see unix manual page times corresponding windows platform api documentation on windows first two items filled others zero availability unix windows but fill needed elapsed real time fifth tuple windows if need windows support consider ctypes call gettickcount directly done recipe,is simple way module correctly measure elapsed time python i know i simply call timetime twice take difference yield wrong results system time changed granted happen often indicate i measuring wrong thing using timetime measure durations incredibly roundabout think you take difference two absolute time measurements turn constructed duration measurements performed timers known absolute times set manually via ntp interested so way query timer time directly i imagine represented millisecond microsecond value meaningful absolute representation thus need adjusted system time looking around bit seems exactly systemnanotime java i find corresponding python function even though hardwaretechnically easier provide timetime edit to avoid confusion address answers this dst changes i want cpu time either i want elapsed physical time it need finegrained even particularly accurate it give negative durations durations several orders magnitude granularity someone decided set system clock different value here python docs say timetime while function normally returns nondecreasing values return lower value previous call system clock set back two calls this exactly i want avoid since lead strange things like negative values time calculations i work around moment i believe good idea learn using proper solutions feasible since kludges come back bite one day edit some research shows get system time independent measurement like i want windows using gettickcount linux get return value times however i still find module provides functionality python,3 if want join list strings use join like listofstrings one two three print tjoinlistofstrings tab character output one two three for commas replace tjoin join join also work tuples used example code it works iterable,i text file like one thisisatest thisisatest thisisatest thisisatest i following code parse def fileopen myfile openr cuserstestdesktopparsemetxt r encoding cp return myfile def parsecurrentline seq currentline seq currentline seq currentline seq currentline seq currentline returnseq seq seq seq seq def exportfilecurrentfile line currentfile x parseline print x exportfilefileopen here output i get interpreter test test test test what i want see text formatted like test thisisatest any ideas or good links explain text formatting thanks,3 go ahead usual w import x y z use special symbol define actual symbols intend people import module myclass myclass myvar … this defines symbols imported user module import module in general python programmers using dir figure use module might indicate problem somewhere else they reading documentation typing helpyourmodule figure use library or could browse source code case difference things import things define quite clear b see declaration know toys playing if try support dir situation like task designed place annoying limitations code i hope clear answers my advice take look standard library guidance … import … whenever code clarity conciseness require provides informative docstrings full documentation readable code one ever run dir module try tell imports apart stuff actually defined module,i developing python package dealing scientific data there multiple frequentlyused classes functions modules packages including numpy i need virtually every function defined module package what would pythonic way deal i considered multiple variants every drawbacks import classes modulelevel foreignmodule import class class function function then imported functions classes easily accessible every function on hand pollute module namespace making dirpackagemodule helppackagemodule cluttered imported functions import classes functionlevel foreignmodule import class class function function the functions classes easily accessible pollute module imports dozen modules every function look lot duplicate code import modules modulelevel import foreignmodule not much pollution compensated need prepend module name every function class call use artificial workaround like using function body manipulations returning objects exported like def export foreignmodule import class class function function def myfuncx return functionx functionx return myfunc myfunc export del export this manages solve problems module namespace pollution ease use functions seems pythonic so solution pythonic is another good solution i overlooked,3 in case someone searches question i getting error message mcryptorsarsaerror start line in case turned keys type unicode this solved converting key back ascii keyencode ascii,msg msg encrypt pubkey mcryptorsaloadpubkey mykeypy this method taking pem file encrypted pubkeypublicencryptmsg mcryptorsapkcspadding now i trying give file containing radix format public key parameter method unable get expected result ie encryption using radix format public key is method python api encrypt msg using public key trying mechanism i getting public key public key server html wrapping radix format how i convert public key accepted encryption method,3 you use numpy histogramdd compute histogram ndimensional array if want histogram slice sure set bins dimension to get overall histogram could compute individually r g b channels take maximum value three position,i got xd arrays red green blue channels d rgb image what elegant way numpy create histogram volume input channels the operation would equivalent assume r g b d arrays output d array filled zeros x xdim ydim z zdim output rxyz gxyz bxyz this code slow large images can numpy improve efficiency algorithm,1 you looking itertoolsgroupby here example code question step time itertools import groupby izip operator import itemgetter key group groupbyizipstep time itemgetter group item item group print step key min mingroup max maxgroup it groups time step finds min max group alternatively could something like stepreverse key group groupbytime lambda steppop group tuplegroup print step key min mingroup max maxgroup to group step without zip ping time,i currently two set lists combine steps time step time these values directly correlate meaning tuple looking like basically i trying find max value step min value step one well minmax step minstep maxstep minstep maxstep i accomplish python need create multidimensional list function iterate keyvalue pairs tuple i use zip function thanks,1 unless application actually responding generating ip packets would incredibly silly probably need testing layer simply testing tcp layer eg connect send recv shutdown probably sufficient events ones server aware,i working mobile i expect network loss common i payments request matters i would like able test server see precisely behave client network loss different points request cycle specifically given packet sendreceive entire network communication i suspect server behave slightly differently communication lost sending response vs waiting finack i want know timings disconnections i distinguish i tried simulating http request using scapy stopping communication tcp packet ie first send syn disappear send syn receive synack disappear send syn receive synack send ack disappear etc however i quickly got bogged details trying reproduce functional tcp stack is good existing tool automateenable kind testing,1 that currently possible please enter feature request pydev sf tracker see httppydevorgabouthtml links,for example def ffoo bar return foo bar answer f what i looking way highlight function call pydev automatically refactored reads answer ffoo bar,1 simply put use condition threads interested waiting something become true true exclusive access shared resource whereas use event threads interested waiting something become true in essence condition abstracted event lock gets interesting consider several different conditions underlying lock thus could different conditions describing state underlying resource meaning wake workers interested particular states shared resource,i yet find clear explanation differences condition event classes threading module is clear use case one would helpful all examples i find use producerconsumer model example queuequeue would straightforward solution,3 i think good idea seem common use case name main construct though usual structure def mainargvnone argv none argv sysargv etc name main sysexitmain this gives additional flexibility use main within interactive interpreter there nice examples guido others,i quickly explain exactly i mean i working project using python i multiple modules segments work let say example i module called parserpy module function parsefile main module mainpy calls order parse files as right i using main method inside parserpy name main linelist parsefilesysargv outfile opensysargv w rangelenlinelist outfilewritelinelistigetstringtrue it important exactly parsing important part call first argument input file parsing second argument output file parsing so i essentially i using batch file validate results parser typical input output baseline system echo set test source input output baseline directories set testdircd set srcdircdpyprosrc set indircdinput set outdircdoutput set basedircdbaseline parserpy main method base unit testing parsing echo begin parser testing cd indirparser for g in psma do srcdirparserpy g outdirparserg echo parser testing complete cd testdir cprogram fileswinmergewinmergeuexe outdir basedir as see diffs results baseline anything changed programmer knows longer valid requirements wrong is anything wrong method i would easy my plan continue many modules i valid make sense way well suite pyunit tests inside pydev,1 more likely griddata way hard it designed work randomly sampled data your data almost certainly regularly sampled grid target output grid look much simpler approach like affine transformation series affine transformations small chips earth topology curvature affect yoru results there box solutions might help gdal good example also type issue often discussed gis see httpgisstackexchangecomquestionschangingimageprojectionusingpython,i trying map irregularly gridded dataset raw satellite data associated latitudes longitudes regularly gridded set latitudes longitudes given basemapmakegrid i using matplotlibmlabgriddata mpltoolkitsnatgrid installed below list variables used output whos ipython stats variables variable type datainfo datalat ndarray x elems type float bytes mb datalon ndarray x elems type float bytes mb gridlat ndarray x elems type float bytes mb gridlon ndarray x elems type float bytes mb var ndarray x elems type float bytes mb in varmin out in varmax out in datalatmin out in datalatmax out in datalonmin out in datalonmax out in gridlatmin out in gridlatmax out in gridlonmin out in gridlonmax out datalat datalon orignal data coordinates gridlat gridlon coordinates interpolate var contains actual data using variables i call griddatadatalon datalat var gridlon gridlat taken long minutes complete returns array nan from looking data latitudes longitudes appear correct original coordinates overlapping portion new area data points lying outside new area does anyone suggestions the nan values suggest i something stupid,1 are looking socketsetdefaulttimeout,i process reworking personal site i run bit snag i hoping clean workaround i using variety os packages communicate stackexchange multiple sites twitter feed to speed things refreshing beakerdriven cache i multithreaded requests using generic queuedcall class design now works fine dandy providers however hang provider i obviously want avoid unfortunately libs i using expose method setting timeouts the way i see i one two options kill threads manually specified timeout i like avoid costs bad modify libraries accept timeout argument i particularly want get part reason i using rd party libs begin hoping able set global property sets timeout urllib recognize used external library question is property somewhere i set application code control default timeouts urllib,1 webpy form field uploads already cgifieldstorage get raw uploaded bytes using data requestvarsmyfilevalue for filelike object stringio needed use filelike requestvarsmyfilefile zip zipfilezipfilefilelike,i trying upload zip file webpy form read contents form formtable trtd upload file inputtype file name myfile id myfile requiresisnotempty trtdinputtype submit value submit formacceptsrequestvars datastringiostringiorequestvarsmyfile import zipfile zfilezipfilezipfiledata for reason code work complains file zip file although uploaded file zip file i new webpy how data represented zipfile,2 oauth purepython module run fine app engine bundle app,from app running gae i want able post tweets periodically i code i able post tweets localhost import urllib import urllib import simplejson json import oauth oauth consumerkey consumerkeysecret oauthtoken oauthtokensecret consumer oauthconsumerkeyconsumerkey secretconsumerkeysecret accesstoken oauthtokenkeyoauthtoken secretoauthtokensecret client oauthclientconsumer accesstoken url httpapitwittercomstatusesupdatejson data status post response data clientrequesturl post urlliburlencodedata since oauth library available gae i want know easiest means able run code gae,1 it working oswalk returns tuple current directory list directory names list filenames curdir dirs files oswalk homenb print searching files programpy files print found break your print statement shown the operator look deeply tuple since filename one three elements tuple point code find,i created file called programpy homenb directory i opened python i wanted see i could write script find location i f oswalk homenb print searching f programpy f print found break why working it seems searching file screen fills searching part never finds,2 description because reliance significant whitespace rather explicit block delimiters properly folding python code tricky the python syntax definition comes bundled vim contain fold directives simplest workaround set foldmethodindent usually ends folding lot really want there shortage vim plugins improved python folding seem suffer cobbledtogether algorithms bizarre intractable bugs corner cases simpylfold aims exactly name suggests simple correct folding python it nothing needs properly folds class functionmethod definitions leaves loops conditional blocks untouched there bs involved screwing around unrelated options several plugins choice algorithms scratch head one correct works simply httpwwwvimorgscriptsscriptphpscriptid,i tried bunch python code folding plugins i seen question asked seem useful achieve python code folding manner class myclassmodelsmodel folded code class meta folded code def unicodeself folded code def saveself args kwargs folded code so question is python code folding plugin i able find far i tried quite number vim plugins already,3 actually depends structure java code add source folder folder class files folder added pythonpath depending structure project may bin folder reference read last lines httppydevorgmanualprojectconfhtml,in project properties pydev pythonpath source folders tab i java source directory listed however i try run python file using rightclick run as jython run i get importerror cannot import name person this simple python script comentities import person person person print persongetfirstname i read people discuss creating jar java application referencing jar seems pretty clear i able reference source directory edit so i tested using jar reference containing class worked so source folder reference work,1 python passes function arguments reference maximum length string passed function purely dependent maximum length string it happens maximum length string platform dependent address space andor ram generally see question what max length python string details in python i assume would work jython well find value sysmaxsize import sys print sysmaxsize from docs maxsize the largest positive integer supported platform’s pyssizet type thus maximum size lists strings dicts many containers your max length string anywhere near many characters mind,what maximum length character function argument pythonjython i reviewed documentation pythonorg luck,1 recursion make simpler would make complicated item enumeratereverseditems item item itemsofinterest itemsi break else item found seems simplest efficient way you iterate list end item since reversed returns iterator edit mind iterating whole list create reversed version use listreverseditemsindex item itemsofinterest itemsi even simpler it raises error item list i using listreversed instead reverse one iteration list instead two edit based comment answer first version want searches item end without iterating whole list the version question iterate list reverse second version a minimally modified efficient version original would itemsofinterest item reverseditems itemsofinterestappenditem item item break itemsofinterestreverse,using python i trying read list strings backwards when finding item interest i want print items point end list i without recursion works fine i feel like nicer way recursion example without recursion items item item item item item itemsofinterest itemsreverse item items itemsofinterestappenditem item item break else continue itemsofinterestreverse print itemsofinterest item item item update to add clarity question list actually output grep set strings log file the set strings may repeating i want last set,3 i going assume might want build html email field django import forms djangoformswidgets import widget djangoutilssafestring import marksafe class htmlemailwidget def renderself name value attrsnone return marksafeu input namecustomemail typeemail class yourformformsform htmlemail formscharfieldwidgethtmlemail i came glancing django source code since i personally use actual project code probably need fleshed,i trying add special template property one form fields i use render form template tag here code form profileform field form fieldname email fieldtemplate emailfieldhtml this way original form variable modified is way achive goal,1 a recursive solution called to problem finding slice list last occurrence item end list one approach define auxiliary function def rindexs x enumeratereverseds x return raise valueerror itemsrindexitems b b f the auxiliary function called rindex python rindex method find last occurrence substring string if must recursively perhaps homework think pseudocode yet worked completely def tailfromlist x return tailfromauxlist x def tailfromauxlist element accumulated list empty return elif list ends element return elementaccumulated else last list return tailfromauxlist element lastaccumulated but memoryintensive goes whole list inefficient pythonic it may appropriate languages python do use since actual question refers files log files may able reduce problem array search therefore check read file reverse order using python interesting answers well links follow consider mixing tac awk grep able well,using python i trying read list strings backwards when finding item interest i want print items point end list i without recursion works fine i feel like nicer way recursion example without recursion items item item item item item itemsofinterest itemsreverse item items itemsofinterestappenditem item item break else continue itemsofinterestreverse print itemsofinterest item item item update to add clarity question list actually output grep set strings log file the set strings may repeating i want last set,1 well i think work datetime import datetime timedelta def daterangestartdate enddate n rangeenddate startdatedays yield startdate timedeltan startdate enddate format ymd startdateobject datetimestrptimestartdate format enddateobject datetimestrptimeenddate format day daterangestartdateobject enddateobject dayweekday print daystrftimeformat,how get saturday sunday dates given date range example startdate enddate now give put any help really appreciate,1 import datetime start datetimedatetimestrptime ymd end datetimedatetimestrptime ymd start end startweekday print startstrftimeymd start datetimetimedeltadays,how get saturday sunday dates given date range example startdate enddate now give put any help really appreciate,2 as version pip supports python,what current status easyinstall pip repository pypipythonorg regards python x are versions easyinstall andor pip install right versions packages else expected soon,1 firstly using match match beginning string see httpdocspythonorglibraryrehtmlmatchingvssearching also even using search grabbing group includes digits guaranteed lastly even using search starting regex carat force search beginning obviously work case postalcode researchr dd address postalcodegroups none,how i extract zip code us following string import address moab ut postalcode rematch dd address print postalcode,3 assuming zip code always digit case us rematch address comment right match vs search i want include extra chars research dd address,how i extract zip code us following string import address moab ut postalcode rematch dd address print postalcode,1 use postalcode rematch address postalcodenone print postalcodegroup,how i extract zip code us following string import address moab ut postalcode rematch dd address print postalcode,1 you could use built map function vectorize function for example ar nparray ar nparray def closestar ar iter x npabsariter ar index npwherexxmin value arindex return value def findx return closestar ar x c nparraymapfind rangearshape in example looked like wanted exclude values paired in case could include removal process first function like careful array sorted def closestar ar iter x npabsariter ar index npwherexxmin value arindex ararvalue return value,two d numpy arrays the lengths unequal i want make pairs arrayelemntarrayelement elements close lets consider following example b the expected result it important note left alone it could easily done loops i large arrays i considered using nearest neighbor but felt like killing sparrow canon can anybody please suggest elegant solution thanks lot,1 for python comprehensive list available xml libsmodules httpwikipythonorgmoinpythonxml if looking something simpler xslt xmlstarlet set command line tools may interest httpxmlstarsourceforgenet as command line tool especially made python easily integrated python script,i need bidirection transforms significantly complex xml flatfile formats python i date know people solving problem far future year i got back date various python xml libraries years since last time xslt hell i amazed googling around still common so go complex xml data transforms i like python documents direct mappings processing calculation required but i still like pass much rule engine possible edit to clear i interested techniques specific libraries tools please post i trying hard avoid word pattern surely common problem edit i still think good answers general techniques original problem i solved using bots edi framework document translations it quite heavily focussed edi used generic translation it heavyweight solution though,1 there thing general typo generation algorithm kind algorithm depends target language application ie generate spam domains basically need apply following strategies using metastackoverflowcom example missing dots met tackoverflowcom easy character insertion metastackoverflo ww com add dupe every character character omission metastackoverf lw com drop character character permutation metastackove fr lowcom pure mathematics character replacement meta tackoverflowcom least two strategies see in case character replacement least two scenarios similar sounding letters ie c k z ts depending language nearby letters proximity typos ie qwerty f duh i actually made typo case hope helps,i could add something creates typos based levenshtein distance two something like reverseengineer norvig article spellchecking however common ways typos has somebody written method,1 numpy arrays slice like b thearray thearray lists lists i understand normal arrays b thearray thearray,i d array python either normal one numpy array dimensions i wish split two arrays dimensions respectively somehow i able any suggestions,2 here way i argparse multiple args parser argparseargumentparserdescription description program parseraddargument f foo help description foo argument requiredtrue parseraddargument b bar help description bar argument requiredtrue args varsparserparseargs args dictionary containing arguments args foo hello code args bar world code in case simply add one argument,the documentation argparse python module excellent i sure much tiny beginner brain grasp right likewise many questions stack i need math command line meddle formatting lines screen change option characters all i want arg a b none show help quit,3 it may overkill consider using virtualenv it would let virtual python installation used standard everything except libraries want keep separate,i want install pygame system i want mix standard libraries thirdparty libs if i install pygame different path i modify syspath interpreter would know look,2 you set pythonpath directory additional modules and use python newer use default peruser module directory without additional configuration,i want install pygame system i want mix standard libraries thirdparty libs if i install pygame different path i modify syspath interpreter would know look,2 arg already tuple sort attribute item def functionargs thing sortedargs keyattrgetter attribute when iterate dict sorted get keys values so want use dict need def functionargs use dict comprehension items dictthingname thing thing args itemsvalues thing sorteditemsitervalues keyattrgetter attribute actually sort args attribute if want keys dict available well necessary key also attribute item use something like name thing sorteditemsiteritems keylambda item itemattribute,i want dict tuple i sort based attributes objects i using arguments arg the way i trying gives attributeerrors leads believe i weird def functionarg items thing arg itemsupdatethingnamething true thing items lots code basically game loop problem turn order based whatever python decides order arguments inside items i like able sort dict based object attributes ie highest thingspeed goes first loop the problem i try sort items based attribute objects i put function gives attributeerror str object attribute attribute which leads believe i either unpacking arg lousy way i trying something wrong way true thing sorteditems keyattrgetter attribute work either keeps telling i trying manipulate str object what i,1 the accepted answer agf comparing like like after print timeitd dget number contains list items whereas print timeitdsetdefault number simply ie dsetdefault version never modifies list stored the code actually print timeitdsetdefault append number fact faster faulty setdefault example the difference really append using concatenation whole list copied every time elements beginning become measurable using append list updates amortised o ie effectively constant time finally two options considered original question defaultdict simply testing dictionary see whether already contains key so assuming defaultdictlist variant dkey dgetkey val variant dsetdefaultkey appendval variant dkeyappendval variant key dkeyappendval else dkey val variant far slowest copies list every time variant second slowest variant fastest work need python older variant slightly slower variant i would say use variant variant option occasional places defaultdict exact fit avoid original variants,the following two expressions seem equivalent which one preferable data b b key val data variant dkey dgetkey val variant dsetdefaultkey appendval the results version better rather pythonic personally i find version harder understand setdefault tricky grasp if i understand correctly looks value key dictionary available enters dict returns reference either value appends val reference while certainly smooth intuitive least least to mind version easier understand available get value key get join list made val place result key but intuitive understand i fear version less performant list creating another disadvantage occurs twice expression rather errorprone probably better implementation using get presently eludes my guess version although difficult grasp inexperienced faster therefore preferable opinions,3 note r code appear correct you probably mean values c the use function c matters see currently rpy try guess one wants represent r python list tuple this found rpy documentation use either r function c rpy class floatvector,i feeling awfully silly i seem work i trying make pie chart using rpy python rpyrobjects import r import ospath image testpng values print using r rpngimage width height rpievalues rdevoff now thing directly r i know i want values pievalues that works fine r interpreter i tried using tuples instead lists python told valueerror nothing done type type tuple moment what python type corresponds r vector do i need use numpy,1 if attributes returned via custom getattr getattribute cannot know whether attribute returned without trying cannot get full list without trying possible names you get list static attributes via dir,how would instance xmletreecelementtreeelement python python r jun gcc based apple inc build llvm build darwin xmletreecelementtree import element obj element aaa obj element aaa xbde dirobj copy deepcopy reduce append clear extend find findall findtext get getchildren getiterator insert items iter iterfind itertext keys makeelement remove set objtag aaa,2 yes structure works find example useful i organize smaller app engine app ├── appyaml ├── confpy ├── mainpy ├── modelpy ├── static │â â ├── gif │â â ├── gif │â â ├── gif │â â ├── gif │â â ├── animgif │â â ├── maincss │â â ├── mainjs └── templates ├── basehtml ├── errorhtml ├── infohtml ├── uploadhtml ├── userhtml └── welcomehtml,python new i got problems organize files codes i want something like views indexhtml django files controlers mainpy models greetingpy i take classe exemple google app engine website libs xxxpy lib tools classes static js css images and the real problem files tree correct python environment,1 htmlparser standard library import htmlparser text ampldquo amprdquo ampmiddot parserhtmlparserhtmlparser descparserunescapetext printdesc “ ” â· if want single statement could course deschtmlparserhtmlparserunescapetext might advantage need call unescape one place general chaining calls like makes harder identify exceptions occur note htmlparserunescape unescape html entities defined htmlentitydefsnamescodepoint plus ampapos edit htmlparserunescape returns different characters posted to get exactly characters might use xmlsaxsaxutils text ampldquo amprdquo ampmiddot import xmlsaxsaxutils saxutils printsaxutilsunescapetext ampldquo amprdquo ampmiddot note saxutilsunescape also replaces amplt ampgt ampamp if wish replace ampldquo amprdquo ampmiddot i use aix answer,i trying junk characters string using following statement desc stringreplacedesc ampldquo desc stringreplacedesc amprdquo desc stringreplacedesc ampmiddot can i write statements single statement atlease st two statements single statement i use thirdparty libraries project edit unutbu my string looks like this ampldquo teststring amprdquo i want replace unicode appropriate html whole string unicode values after using code import htmlparser text ampldquo amprdquo ampmiddot parserhtmlparserhtmlparser descparserunescapetext i getting html equivalents string but i want replace appropriate values keeping everything original string i expect put this teststring i want replace unicode appropriate html whole string unicode values,2 the first two together using regular expressions desc resub amprldquo desc if foresee many patterns could put dictionary apply loop patterns amprldquo ampmiddot pattern repl patternsitems desc resubpattern repl desc like original code scale well longer desc since scans string multiple times here extensible version scans string import subs rdquo ldquo middot def replmatchobj return subsgetmatchobjgroup matchobjgroup desc sdf sdfs ampldquo sdf sd ampldquo skdfh ampmiddot sdf ampnonsub jk print resub amp repl desc,i trying junk characters string using following statement desc stringreplacedesc ampldquo desc stringreplacedesc amprdquo desc stringreplacedesc ampmiddot can i write statements single statement atlease st two statements single statement i use thirdparty libraries project edit unutbu my string looks like this ampldquo teststring amprdquo i want replace unicode appropriate html whole string unicode values after using code import htmlparser text ampldquo amprdquo ampmiddot parserhtmlparserhtmlparser descparserunescapetext i getting html equivalents string but i want replace appropriate values keeping everything original string i expect put this teststring i want replace unicode appropriate html whole string unicode values,2 did read flask docs testing you use following selfapppost pathtorequest datadictvar data var data selfappget pathtorequest,i would like fake request parameters unit testing how i achieve flask thanks,3 most installation requires sudo python setuppy install otherwise able write installation directories i pretty sure unless root got error python setuppy install,i wrote function python then i wanted make module install ubuntu here i created setuppy along functionpy file built distribution file using python setuppy sdist then installed python setuppy install all going fine but later i wanted use module importing code i got import error importerror no module named ps i searched google find particular answer detailed answer much appreciated,3 this in nphstacka out array if performance issue following place in,i numpy array i want retrieve elements except certain index for example consider following array i specify index resultant,1 you use boostpythonpickle save data python i limited experience pickling suite work provided override appropriate pickling methods classes derived python see answer question,in c i following two classes i expose using boost python struct foo empty struct foocontainer i use boostsharedptr compatibility boostpython vectorboostsharedptrfoo foos in python side i might create special type foo actually something instead empty class add foocontainer class usefulfoo def initself b selfa selfb b x useful add x foocontainer back c side foocontainer foos know care python the application runs data foo objects changes then i decide i want save state program i load later time but problem foocontainer know much foo objects even know come python i want pollute foocontainer data really belong singleresponsibility principle do advice i organize application saving loading data well loading fresh data ie state i saved past done clear way,1 anew npdeletea index wish remove axis zero case using d array see numpydelete,i numpy array i want retrieve elements except certain index for example consider following array i specify index resultant,3 like resizing removing elements numpy array slow operation especially large arrays since requires allocating space copying data original array new array it avoided possible often avoid working masked array instead for example consider array import numpy np nparray printa printasum we mask value index perform summation ignores masked elements npmaarraya maskfalse amask true printa printasum masked arrays also support many operations besides sum if really need also possible remove masked elements using compressed method printacompressed mentioned avoid possible,i numpy array i want retrieve elements except certain index for example consider following array i specify index resultant,3 cdata part xml html browser ignores treats tags would tags ignoring ones recognise paying attention i think alternative use amplt etc convert tags editing convert back saving,i trying display xml tags mixed plain text web page i python script obtains data database i simplified problem program usrlocalbinpython print contenttype texthtmlcharsetutfnn print htmlbody startcdatathis xml tag xmlend bodyhtml i expecting display following startthis xml tag xmlend in ie chrome however displays following start tag end when i look html source page ie i see following htmlbody startcdatathis xml tagxmlend bodyhtml in chrome i see looking source seems cdatathis xml part green considered comment i particularly want keep text instead converting amplt via javascript i access elements allowing people edit separate textarea converting would save converted resulting problems processing i could convert back saving seems like wrong approach any idea i wrong thanks advance grant,1 def openfilefilename opens file samples return base encoded streams feel free use code helpful backend import backend sampledir backendconfigsamplesdir file openospathjoinsampledir filename r stream fileread encodedstream basebencodestream return encodedstream,i need i using ajax transfer file hence i get image file base encoded string i would like convert nicely filestorage object i use flaskuploads library nicely any idea i thanks,1 i think orm solution problem performance by default orms tend less efficient row sql might fetch data going use eg select need one field although sqlalchemy allows finegrained control sql generated now implement caching mechanism depending application could use simple dictionary memory specialized system memcached redis to keep cached data relatively fresh poll source regular intervals might ok application tolerate little delay otherwise need application write access db notify application cache system update occurs edit since seem control app b already got cache system app a simplest way solve problem probably create callback app a app b call expire cached items both apps need agree convention identify cached items,i application needs interface another app database i read access write currently i using sql statements via pyodbc grab rows using python manipulate data since i cache anything quite costly i thinking using orm solve problem the question i use orm like sql alchemy would smart enough pick changes database eg sql alchemy accesses table retrieves row if row got modified outside sql alchemy would smart enough pick edit to clear i one application simply reporting tool lets call app a i another application handles various financial transactions called app b a access b database retrieve transactions generates various reports there hundreds thousands transactions we currently caching info manually python need updated report refresh cache if get rid cache sql queries combined calculations becomes unscalable,1 it source view converting decimal browser handling entities converting relevant nonascii characters it possible little generous terms converting entities terminating the server almost certainly serving seeing source view,while i checking rss feed browser i see fonts è£ ï¼Œé ä¸Šè¶ çŸ­è¿·ä½ è£™ï¼Œå¤ªè¿‡æš´éœ²ï¼Œä¹Ÿå¾ˆä¸å¾—ä½“ã€‚å¤§ä¸“å­¦ç”Ÿçš„éšæ€§æ‰“æ‰®ï¼Œåˆ°åº•æ˜¯é‚‹é¢ï¼Œè¿˜æ˜¯æ–°æ—¶å°šå‘¢ï¼Ÿè¿™ä¸€æœŸçš„â€é’æ˜¥å¼€è®²â€œï¼Œomyè®°è€ æ¥åˆ°æ­¦å‰ç­è®©æ”¿åºœä¸­å­¦çš„å­¦ç”Ÿï¼Œä¸€èµ·è®¨è®ºè¿™ä¸ªè¯é¢˜ã€‚ä¸€åå­¦ç”Ÿè¯´ï¼Œç©¿ç€æ‰“æ‰®å¾—ä½“ï¼Œæ˜¯å¯¹åˆ«äººã€å¯¹è‡ªå·±çš„å°Šé‡ã€‚å¦ä¸€åå­¦ but source code view converted decimal ampampampampampampampampampampampampampampampampampampampampampamp ampampampampampampampampampampampampampampampampampampampampampampampamp ampampampampamp is due localization content file saved different encoding i see file saved using utf edit i trying parse rss feed using python but parsing i getting decimal values actual charecters,1 for reason tool created feed decided convert characters unicode code point string representation odd indeed author tool answer,while i checking rss feed browser i see fonts è£ ï¼Œé ä¸Šè¶ çŸ­è¿·ä½ è£™ï¼Œå¤ªè¿‡æš´éœ²ï¼Œä¹Ÿå¾ˆä¸å¾—ä½“ã€‚å¤§ä¸“å­¦ç”Ÿçš„éšæ€§æ‰“æ‰®ï¼Œåˆ°åº•æ˜¯é‚‹é¢ï¼Œè¿˜æ˜¯æ–°æ—¶å°šå‘¢ï¼Ÿè¿™ä¸€æœŸçš„â€é’æ˜¥å¼€è®²â€œï¼Œomyè®°è€ æ¥åˆ°æ­¦å‰ç­è®©æ”¿åºœä¸­å­¦çš„å­¦ç”Ÿï¼Œä¸€èµ·è®¨è®ºè¿™ä¸ªè¯é¢˜ã€‚ä¸€åå­¦ç”Ÿè¯´ï¼Œç©¿ç€æ‰“æ‰®å¾—ä½“ï¼Œæ˜¯å¯¹åˆ«äººã€å¯¹è‡ªå·±çš„å°Šé‡ã€‚å¦ä¸€åå­¦ but source code view converted decimal ampampampampampampampampampampampampampampampampampampampampampamp ampampampampampampampampampampampampampampampampampampampampampampampamp ampampampampamp is due localization content file saved different encoding i see file saved using utf edit i trying parse rss feed using python but parsing i getting decimal values actual charecters,1 aren stored html entities author page httptltitspsuedusuggestionsinternationalbylanguagethaicharthtml,while i checking rss feed browser i see fonts è£ ï¼Œé ä¸Šè¶ çŸ­è¿·ä½ è£™ï¼Œå¤ªè¿‡æš´éœ²ï¼Œä¹Ÿå¾ˆä¸å¾—ä½“ã€‚å¤§ä¸“å­¦ç”Ÿçš„éšæ€§æ‰“æ‰®ï¼Œåˆ°åº•æ˜¯é‚‹é¢ï¼Œè¿˜æ˜¯æ–°æ—¶å°šå‘¢ï¼Ÿè¿™ä¸€æœŸçš„â€é’æ˜¥å¼€è®²â€œï¼Œomyè®°è€ æ¥åˆ°æ­¦å‰ç­è®©æ”¿åºœä¸­å­¦çš„å­¦ç”Ÿï¼Œä¸€èµ·è®¨è®ºè¿™ä¸ªè¯é¢˜ã€‚ä¸€åå­¦ç”Ÿè¯´ï¼Œç©¿ç€æ‰“æ‰®å¾—ä½“ï¼Œæ˜¯å¯¹åˆ«äººã€å¯¹è‡ªå·±çš„å°Šé‡ã€‚å¦ä¸€åå­¦ but source code view converted decimal ampampampampampampampampampampampampampampampampampampampampampamp ampampampampampampampampampampampampampampampampampampampampampampampamp ampampampampamp is due localization content file saved different encoding i see file saved using utf edit i trying parse rss feed using python but parsing i getting decimal values actual charecters,1 i would need new variable word count participant i could manipulate later no would need counter python else use defaultdictint mapping persons word counts collections import counter collections import defaultdict wordsperperson counter wordsperperson defaultdictint ln inputfile person text lnsplit wordsperpersonperson lentextsplit now wordsperperson p contains number words p assuming textsplit good enough tokenizer purposes linguists disagree definition word always going get approximation,i starting learn python i trying write program would import text file count total number words count number words specific paragraph said participant described p p etc exclude words ie p etc word count print paragraphs separately thanks james hurford i got code like words none open datatxt f words freadsplit totalwords lenwords print total words totalwords inpara false paratype none paragraph list word words p word p word p word inpara false inpara true paratype word else print words paragraph paratype lenparagraph print joinparagraph del paragraph paratype word else paragraphappendword else inpara true print words last paragraph paratype lenparagraph print joinparagraph else print no words my text file looks like p bla bla bla p bla bla bla bla p bla bla p bla the next part i need summing words participant i print i know returnreuse i would need new variable word count participant i could manipulate later addition summing words said participant eg pall sum words paragraph is way count etc two words any ideas solve,3 no verbose flag prints file list stderr otherwise stdout wrote tar file what use verbose flag ps small scripts i think shell scripts efficient,trying create backup script using ssh called subprocesspopen module next checks stderr contains anything writes error log file detects first output part stderr def server bpath mntbackupserveraddressusrlocalbin rpath usrlocalbin bpath mntbackupserveraddressproject rpath varwwwproject cmd ssh q rootserveraddress tar zcf rpath bpathusrlocalbintargz cmd ssh q rootserveraddress tar zcf rpath bpathprojecttargz exec subprocesspopencmdshelltruestdoutsubprocesspipe stderrsubprocesspipe stdoutstderr execcommunicate stderr logwritet stderr n else logwritet backup usrlocalbin serveraddress completen exec subprocesspopencmd shelltruestdoutsubprocesspipestderrsubprocesspipe stdoutstderr execcommunicate stderr logwritet stderr n else logwritet backup varwwwproject serveraddress completen log file septemberpm tar removing leading member names think picked first line thought part stderr ideas fix research tar fixed using ssh q rootccelinsvcs tar zcfp rpath bpathusrlocalbintargz new error test stderr disabled ssh remote host ssh rootserveraddress ssh connect host serveraddress port no route host stderr catch error idea,1 simple string operation mywords xxx yyy zzz allx mystring x mywords if word boundaries relevant e want match zzz ozzzy import allresearchrb reescapeword rb mystring word mywords,i looking expression match strings list words like xxx yyy zzz the strings need contain three words need order eg following strings matched yyy string words “zzz string words “xxx string words “yyy””xxx””zzz” string words,2 you advised redefine root logger way describe in general use root logger directly small scripts larger applications best practice use logger logginggetloggername module use logging make calls loggerinfo etc if want log file add file handler root logger you using eg name main loggingbasicconfigfilename experimentallog filemode w main whatever main entry point called via configuration file update when i say advised i mean answer while may run problems scenario good practice overwrite module attribute designed overwritten for example root logger instance different class part public api references logging machinery would still point old value either facts could lead hardtodebug problems since logging package allows number ways achieving seem want seemingly logging file rather console use mechanisms provided,at current project thousand code lines looks like logginginfoblablabla i want change lines i would change log behavior my idea changing root logger experimental logger configured inifile loggers keys experimental formatterdetailed format asctimesnameslevelnames moduleslinenod messages handlerlogfile class filehandler args experimentallog formatter detailed loggerexperimental level debug qualname experimental handlers logfile propagate now setting new root logger done piece code loggingconfigfileconfigpathtologgerconfig loggingroot logginggetlogger experimental is redefining root logger safe maybe convenient way i tried use google looked stackoverflow questions i find answer,3 i author twython sadly oauth less ideal method authenticating well anything outside web browser while possible could figure hacky method make work concerned user experience may want request xauth permission twitter httpsdevtwittercomdocsauth it still oauth internal twython pieces fine while twython outright support xauth due twitter stance advocating using i definitely open taking patch two enough people need another option would oob authentication requires users getting entering pin generally great ux,i downloaded twython source code compiled system i developing desktop app rather webapp thus i see use djangooauth implementation little project this asked twythonpy selfrequesttokenurl httptwittercomoauthrequesttoken selfaccesstokenurl httptwittercomoauthaccesstoken selfauthorizeurl httptwittercomoauthauthorize selfauthenticateurl httptwittercomoauthauthenticate selftwittertoken twittertoken selftwittersecret twittersecret selfoauthtoken oauthtoken selfoauthsecret oauthtokensecret selfcallbackurl callbackurl the problem i know twittersecret twittertoken in twitter dev registering app i got customer key secret also got twitter key secret my callbackurl none and twitter forced mention website i gave localhost address got accepted now i know move forward oauth authentication what i next,1 well anything webrelated start wsgi application def appenviron startresponse calendar getprocessedfile startresponse ok contenttype texticalendar charsetutf contentdisposition inline filenamecalendarics yield calendar then deploy use handler eg plain cgi would import wsgiref wsgirefcgihandlerrunapp see httpwwwwsgiorg materials wsgi,hi i need process remote ical file another server server hand back requesting user so i need fetch file could urllib process file regex question hand back specific header main problem i know php header contenttype textcalendar charsetutf header contentdisposition inline filenamecalendarics echo ical exit but thing python,1 since textn follows b already found use xpath following axis domxpath btext pointnfollowingnode,how get text tag found example usrbinenv python import lxmlhtml html bpointb text br bpointb text br bpointnb textn bpointnb textnbr dom lxmlhtmldocumentfromstringhtml el domxpath btextpointn print el tag el text pointn found get text textn,2 ok let try in import pickle in numlist person in outfile openlogtxt wb in pickledumpnumlist outfile in outfileclose in infile openlogtxt rb in pickleloadinfile out person as see i got back exactly i started numlist the thing changed compared code i close outfile reopening make sure buffers get flushed,i dictionary list value numlist person i pickle outfile openlogtxt wb pickledumpnumlist outfile i unpickle infile openlogtxt rb pickleloadinfile how i convert binary data back original format dictionary variable name key list two itemsa variable number number calltime time value,1 another way el domxpath btextpointn print eltail,how get text tag found example usrbinenv python import lxmlhtml html bpointb text br bpointb text br bpointnb textn bpointnb textnbr dom lxmlhtmldocumentfromstringhtml el domxpath btextpointn print el tag el text pointn found get text textn,2 the problem might form defined urls loaded django reverselazy feature would solve problem you could implement project see changeset alternatively could set widget forms init method instead then reverse call happens form created urls loaded class workformformsform subcategory formschoicefield requiredtrue label subcategory helptext which subcategory suits work best def initself args kwargs superworkform selfinitargs kwargs selffields subcategory widgetdependantchoicewidget defaultvalue select category first datasourceurlreverse worksjsoncategories dependson categoryid,i trying use django reverse function definition django form custom widget getting error improperlyconfigured the included urlconf urls patterns here code class workformformsform category formschoicefield requiredtrue label category helptext select appropriate category work subcategory formschoicefield widgetdependantchoicewidget defaultvalue select category first datasourceurlreverse worksjsoncategories datasourceurl works way dependson categoryid requiredtrue label subcategory helptext which subcategory suits work best i pretty sure worksurls configured properly since pages work expected is reason i cannot use reverse form definition does something code runs is way fix choice hardcode url here full error dump environment request method get request url httpworksaddcategoryampsubcategory django version prealpha python version installed applications djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles djangocontribadmin djangocontribadmindocs socialauth sorlthumbnail helpers users works debugtoolbar installed middleware djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewaretransactiontransactionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware debugtoolbarmiddlewaredebugtoolbarmiddleware traceback file usrlocallibpythondistpackagesdjangocorehandlersbasepy getresponse response middlewaremethodrequest file usrlocallibpythondistpackagesdjangomiddlewarecommonpy processrequest isvalidpathrequestpathinfo urlconf file usrlocallibpythondistpackagesdjangomiddlewarecommonpy isvalidpath urlresolversresolvepath urlconf file usrlocallibpythondistpackagesdjangocoreurlresolverspy resolve return getresolverurlconfresolvepath file usrlocallibpythondistpackagesdjangocoreurlresolverspy resolve pattern selfurlpatterns file usrlocallibpythondistpackagesdjangocoreurlresolverspy urlpatterns patterns getattrselfurlconfmodule urlpatterns selfurlconfmodule file usrlocallibpythondistpackagesdjangocoreurlresolverspy urlconfmodule selfurlconfmodule importmoduleselfurlconfname file usrlocallibpythondistpackagesdjangoutilsimportlibpy importmodule importname file varwwwmegeniustrunkurlspy module urlr works include worksurls file usrlocallibpythondistpackagesdjangoconfurlsinitpy include urlconfmodule importmoduleurlconfmodule file usrlocallibpythondistpackagesdjangoutilsimportlibpy importmodule importname file varwwwmegeniustrunkworksurlspy module worksviews import file varwwwmegeniustrunkworksviewspy module worksforms import workform file varwwwmegeniustrunkworksformspy module class workformformsform file varwwwmegeniustrunkworksformspy workform datasourceurlreverse worksjsoncategories file usrlocallibpythondistpackagesdjangocoreurlresolverspy reverse prefix resolverreverseview args kwargs file usrlocallibpythondistpackagesdjangocoreurlresolverspy reverse possibilities selfreversedictgetlistlookupview file usrlocallibpythondistpackagesdjangocoreurlresolverspy reversedict selfpopulate file usrlocallibpythondistpackagesdjangocoreurlresolverspy populate pattern reversedselfurlpatterns file usrlocallibpythondistpackagesdjangocoreurlresolverspy urlpatterns raise improperlyconfiguredthe included urlconf patterns selfurlconfname exception type improperlyconfigured worksadd exception value the included urlconf urls patterns,3 timetime twodaysago number seconds two days filecreation twodaysago print file two days old,i want check file older certain amount time eg days i managed get file creation time way import ospath time filecreation ospathgetctimefile file timectimeospathgetctimefile mon aug how i check older days i work linux cross platform solution would better cheers,3 you use collectionscounter class collections import counter combined counter counter listcombinedelements it functions multiset unordered collection element appear multiple times the operator gives union multisets element appears maxapperancesincounter appearancesincounter times this class added python,i need unite two lists pythonwhere duplicates existand one set resulting list contain many max listsan example might clarify operator ideas,3 convert arrays dictionaries akey count create new dictionary rules ckey agetkey bgetkey akey bkey you need iterate keys b dicts expand dictionary result value key,i need unite two lists pythonwhere duplicates existand one set resulting list contain many max listsan example might clarify operator ideas,1 why use lists first place that data looks like dict then simple keys setakeysbkeys vals maxagetn bgetn n keys dictzipkeys vals print result,i need unite two lists pythonwhere duplicates existand one set resulting list contain many max listsan example might clarify operator ideas,1 use python imaging library pil imresize see example geometrical transforms httpeffbotorgimagingbookintroductionhtm,i googled resizing images python i found nothing helpful python solution problem i need complicated image processing resizing function run python please give advises thanks,1 in settingspy file variable called databases it dict one keys default maps another dict this subdict key name path sqlite database this example project mine currentdir usersbrandizzidocumentssoftwarenetunong databases default engine djangodbbackendssqlite name currentdir databasedb the path user password host port you easily retrieve value using django shell accessible running command python managepy shell just follow steps import settings settingsdatabases default name usersbrandizzidocumentssoftwarenetunongdatabasedb if returned value relative path use ospathabspath find absolute one import ospath ospathabspathsettingsdatabases default name usersbrandizzidocumentssoftwarenetunongdatabasedb,i got python installed sqlite included sqlite db file path created managepy syncdb i mac,3 in nativeinitpy include scripts import another,is way create virtual import path python my directory structure like native scripts somepy anotherpy other unrelated dirs the root directory program executed atm i add nativescripts search path i import another instead nativescripts import another i like able like native import import nativeanother is way achieve related questions making virtual package available via sysmodules,2 why move somepy anotherpy native directory everything just works people returning source code later confused things importable update thanks comments usefully clarified problem in case i generally put functions classes i might want import inside say nativesome i easily get but i get script code script code — thin shim interprets arguments starts everything running passing main go function parameters — put inside scripts directory that keeps externalinterface code cleanly separate code might want import means try fool python modules several places,is way create virtual import path python my directory structure like native scripts somepy anotherpy other unrelated dirs the root directory program executed atm i add nativescripts search path i import another instead nativescripts import another i like able like native import import nativeanother is way achieve related questions making virtual package available via sysmodules,1 looks like suds actually throwing incorrect error type plugin file sentry able handle sentry tries call sentry object raised exception i guess expects attributeerror returned suds raises oldstyle exception see httpsfedorahostedorgsudsbrowsertrunksudspluginpyl maybe patch raise attributeerror may best solution others,when using suds django app alongside sentry error logging i hit problem suds raises error sentry tries handle fails horribly causes server wed sep error unable process log entry plugin domain sentry invalid wed sep error traceback recent call last wed sep error file optenvsxxxxlibpythonsitepackagessentryclientmodelspy line sentryexceptionhandler wed sep error messageid getclientcreatefromexceptionextra wed sep error file optenvsxxxxlibpythonsitepackagessentryclientbasepy line createfromexception wed sep error frames varmapshorten reportergettracebackframes wed sep error file optenvsxxxxlibpythonsitepackagessentryhelperspy line varmap wed sep error ret varmapfunc f context f var wed sep error file optenvsxxxxlibpythonsitepackagessentryhelperspy line varmap wed sep error ret dictk varmapfunc v context k v variteritems wed sep error file optenvsxxxxlibpythonsitepackagessentryhelperspy line genexpr wed sep error ret dictk varmapfunc v context k v variteritems wed sep error file optenvsxxxxlibpythonsitepackagessentryhelperspy line varmap wed sep error ret varmapfunc f context f var wed sep error file optenvsxxxxlibpythonsitepackagessentryhelperspy line varmap wed sep error ret varmapfunc f context f var wed sep error file optenvsxxxxlibpythonsitepackagessentryhelperspy line varmap wed sep error ret funcvar wed sep error file optenvsxxxxlibpythonsitepackagessentryhelperspy line shorten wed sep error var transformvar wed sep error file optenvsxxxxlibpythonsitepackagessentryhelperspy line transform wed sep error callablegetattrvalue sentry none wed sep error file optenvsxxxxlibpythonsitepackagessudspluginpy line getattr wed sep error raise exception plugin domain invalid name wed sep error exception plugin domain sentry invalid seems like sentry suds play well,2 inside init could always selflocalparam selfbigparametergroupsmallparametergroupparam,i python class contains several nested parameter groups class myclassobject code set parameters def somefunctionself print selfbigparametergroupsmallparametergroupparam print selfbigparametergroupsmallparametergroupparam print selfbigparametergroupsmallparametergroupparam i want reduce code needed access parameters what i place top somefunction access parameters simply names param param param and i place somewhere myclass apply shortcut methods somefunction,1 first allow say zip encryption weak obsolete you rely need strong security this proved many papers google says popular known plaintext attack pkzip stream cipher eli biham paul c kocher second gae works libraries pure python probably use chilkat c library third zip file encryptiondecryption pure python going slow hell probably cpu problems gae perhaps look another way regards,i problem encrypt compressed blobs type zip because reasons i cannot use chilkat module zipfile module provides decryption i know use encrypt zips key could please give suggestions problem could solved ideal solution would look something like blobinfo blobstoreblobinfoall lets say want read first blob find blobreader blobstoreblobreaderblobinfokey file zipfilezipfileblobreader r data filereadfilenamelist output stringiostringio outfile zipfilezipfileoutput w outfilewritestrfilenamelist data outfilesetpassword testpass would nice module could set pass like setpassword works decryption outfileclose outputstream filesblobstorecreatemimetype applicationzip blobinfouploadedfilename filenamelistsplit zip filesopenoutputstream f fwriteoutputgetvalue filesfinalizeoutputstream,1 i would start function spg selfbigparametergroupsmallparametergroup use abbreviation you could define abbreviations like init i suppose wanted use everywhere self front,i python class contains several nested parameter groups class myclassobject code set parameters def somefunctionself print selfbigparametergroupsmallparametergroupparam print selfbigparametergroupsmallparametergroupparam print selfbigparametergroupsmallparametergroupparam i want reduce code needed access parameters what i place top somefunction access parameters simply names param param param and i place somewhere myclass apply shortcut methods somefunction,3 i figured answer simply logging string looks like hexadecimal format xxx xx hexadecimal code byte ascii substitutions certain easilyprinted characters xpngrnxanxxxrihdrxxx xxxxdxxxxxxcbxenxxxxxcidathrxcxkxaxxsnb xxbnxaxbjx xxxxbfaxxfcxvxbxxxcjxxxcuxbxdxaxxztxxxdfxdpxcxaexfbampxcxfxdxbdxdbxboxexxbkxcxexbdxexfxeckxbxffjxxfdaxcfxxaxxdbxexcxfexxfxxfxxecxxbaxaaxeyxxxbxaxxexcxbxbxfdxxxeexafzxxbxbizrxxafxxxafxcxxxfxbcmxbxvxbdxfjxcxdxdxd xfxpcxaaxxexxfctexexdyxbxbpxxxcxekxxyxxdxrxxexxefxaaxbcxxebxdrexexabxfxxcfxxbxfbxbxxexexfxadxaxxaxrbxxdcxxxftxfxfxetbxaixdxbxxxxcxcvixddsxxcqjxabplkxcyxaxxfxrxxckxexatxfxebxdenxdxexbxnxcdxcazxexddxaxexaxxexafxfxatxfxebxdixxcnxcxxxbxadxaxdjxxxdexbxaxbxxbwxecxbwxbtexxxcxadyxxcxfxafhxdxoxfdazxxxxfxccixdxfbxfxacxxaxcxcpxexxaxexfxexcdxxxxeaxdixxfxfxebxxexaixxfcxfampxcaxbxaaxcbyznxaxbauxertxbfxxx xasxxxxiendxaebx the replicated objective c reading image nsdata getting description list digit hexadecimalformatted byte values after could loop byte decide represent based value nsdata data nsdata datawithcontentsoffilensbundle mainbundle pathforresourceanimage oftypejpg nsstring hexformatstring data describe hexformatstring hexformatstring stringbytrimmingcharactersinsetnscharacterset charactersetwithcharactersinstring stringbyreplacingoccurrencesofstring withstring nsmutablestring newstring nsmutablestring string int x xhexformatstring length x nsstring component hexformatstring substringwithrangensmakerangex int value sscanfcomponent cstringusingencodingnsasciistringencoding x ampvalue value ampamp value value ampamp value value ampamp value value value ampamp value newstring appendformatc charvalue else newstring appendformat component uppercasestring,say i python code somestring filefilenamejpgread how i replicate line code objective c ios i trying convert jpg string eventual url encoding i pass tumblr api i tried base encoding convert image string initially seem get valid response tumblr i also tried nsutfencoding attempts return nil strings see why i someone tumblr posted python example submit multiple photos photoset response thread process appears start converting images strings using fileread the api unfortunately take simple ‘multipartformdata’ request ‘applicationxwwwformurlencoded’ format what sort encoding python using read i replicate objective c iphone i tried following nsstring utfstring nsstring stringwithcontentsoffilensbundle mainbundle pathforresourcefilename oftypejpg encodingnsutfstringencoding erroramperror this gives nil string error the operation couldn’t completed using base encoding gives string tumblr api accept url encoding i assume python read though i could missing step the tubmlr api responds statusmsgbad requestresponseerrorserror uploading photo there similar question stackoverflow uploading photos photosets tumblr question specific posted python code,1 one way create properties property def paramself return selfbigparametergroupsmallparametergroupparam property def paramself return selfbigparametergroupsmallparametergroupparam property def paramself return selfbigparametergroupsmallparametergroupparam another robust less explicit way would override getattr method like def getattrself name import p recompile param pmatchname return getattrselfbigparametergroupsmallparametergroup name else return supermyclass selfgetattrname this work property matches format specified regex param number both methods allow call selfparam etc retriving if want set attributes need also create setter paramsetter def paramself value print called setter selfbigparametergroupsmallparametergroupparam value or complement getattr def setattrself name value import p recompile param pmatchname return setattrselfbigparametergroupsmallparametergroup name value else return supermyclass selfsetattrname value haven tested may typos concept work,i python class contains several nested parameter groups class myclassobject code set parameters def somefunctionself print selfbigparametergroupsmallparametergroupparam print selfbigparametergroupsmallparametergroupparam print selfbigparametergroupsmallparametergroupparam i want reduce code needed access parameters what i place top somefunction access parameters simply names param param param and i place somewhere myclass apply shortcut methods somefunction,1 it looks never passing data template in code base template td user name td that middle line basically says get value data key call argument user name it seems passing data template try find obviously the result uses special value called undefined since undefined value callable error raised to fix need pass data template least needs callable object value for example def myfuncx return x print agetreport tablebodyhtml data myfunc,i files basetablehtml tablebodyhtml basetablehtml block namebodytable table cellspacing cellpadding border width block namebodytabletbody tbody block nameinnerbodytabletbody tr block namebodytableth block tr block namebodytablebody block block tbody block table block table body inherited basetablehtml tablebodyhtml inherit filebasetablehtml block namebodytableth td user name td block block namebodytablebody block inherit when try render gives error basetablehtml renderbodycontext pageargs basetablehtml renderbodytablecontext pageargs basetablehtml renderbodytabletbodycontext pageargs basetablehtml renderinnerbodytabletbodycontext pageargs tablebody renderbodytablethcontext pageargs typeerror undefined object callable code coding utf import os makotemplate import template makolookup import templatelookup makoruntime import context cstringio import stringio import tempfile import subprocess class mytemplateobject class get report template object def initself selflookup templatelookupdirectories def servertemplateself templatename return selflookupgettemplatetemplatename def getreportself filename datanone rtype txt get output given report data data selfservertemplatefilename buf stringio ctx contextbuf data trendercontextctx reportfilename ospathjoin tempfilegettempdir testhtml reportfile openreportfilename w reportfilewritebufgetvalue reportfileclose rtype txt reportpopen subprocesspopen links reportfilename dump stdinsubprocesspipe stdoutsubprocesspipe stderrsubprocesspipe stdout stderr reportpopencommunicate return stdout name main mytemplate print agetreport tablebodyhtml vimexpandtabsmartindenttabstopsofttabstopshiftwidth,1 chmod roottestpy roottestpy rootclasswatchlog amp work,this crontab file looks like root usrbinpython roottestpy rootclasswatchlog amp this python script looks like usrbinpython print hello the cronjob creates log file but empty i also pretty certain python file executed appreciate help i playing past hrs luck,1 change root filename last line ospathjoinroot filename seen two lines earlier,the script recursively go rootpath directory find files mp extension print list files directory structure then move files destdir directory the problem i run trying move files new directory only files rootpath directory moved new destination files subdirectories rootpath causes errors volumesvoigtkampfftemptestleveltestmp volumesvoigtkampfftemptestdestinationlevelstestmp traceback recent call last file volumeshomefoldersidmodesktopscriptslibrarypythonrecursivefindpy line module shutilmoverootfilename destdir filename file libraryframeworkspythonframeworkversionslibpythonshutilpy line move copysrc realdst file libraryframeworkspythonframeworkversionslibpythonshutilpy line copy copyfilesrc dst file libraryframeworkspythonframeworkversionslibpythonshutilpy line copyfile opensrc rb fsrc ioerror errno no file directory volumesvoigtkampfftemptestdestinationlevelstestmp script import fnmatch import os import shutil rootpath volumesvoigtkampfftemptest destdir volumesvoigtkampfftemptest matches root dirnames filenames oswalkrootpath filename fnmatchfilterfilenames mp matchesappendospathjoinroot filename printospathjoinroot filename shutilmoverootfilename destdir filename,1 congratulations you already found ospathjoin you even use print call so use move shutilmoveospathjoinroot filename ospathjoindestdir filename but take care overwrite anything destdir,the script recursively go rootpath directory find files mp extension print list files directory structure then move files destdir directory the problem i run trying move files new directory only files rootpath directory moved new destination files subdirectories rootpath causes errors volumesvoigtkampfftemptestleveltestmp volumesvoigtkampfftemptestdestinationlevelstestmp traceback recent call last file volumeshomefoldersidmodesktopscriptslibrarypythonrecursivefindpy line module shutilmoverootfilename destdir filename file libraryframeworkspythonframeworkversionslibpythonshutilpy line move copysrc realdst file libraryframeworkspythonframeworkversionslibpythonshutilpy line copy copyfilesrc dst file libraryframeworkspythonframeworkversionslibpythonshutilpy line copyfile opensrc rb fsrc ioerror errno no file directory volumesvoigtkampfftemptestdestinationlevelstestmp script import fnmatch import os import shutil rootpath volumesvoigtkampfftemptest destdir volumesvoigtkampfftemptest matches root dirnames filenames oswalkrootpath filename fnmatchfilterfilenames mp matchesappendospathjoinroot filename printospathjoinroot filename shutilmoverootfilename destdir filename,3 ok looks like actually problem django instead related test runner djangosanetesting flushing seems broken way for i better solution using djangonose test runner,i dealing annoying problem trying run dj tests project postgresql backend it starts running tests first db flush happen fails strange error error database dbname flushed possible reasons the database running configured correctly at least one expected database tables exist the sql invalid hint look output djangoadminpy sqlflush that sql command able run the full error cannot truncate tablename pending trigger events if i run output sqlflush pgadmin runs fine any ideas welcome possible causes update ok looks like actually problem django instead related test runner djangosanetesting with default dj test runner djangonose test runner works,1 i suggest use urlparse parsing urls in urlparse import urlparse in urlparse httpwwwstackoverflowcomquestionsanswershelp netloc out wwwstackoverflowcom netloc includes port number present eg wwwstackoverflowcom want port number use hostname instead,i trying create regular expression match third instance url ie website name recorded nothing else so httpwwwstackoverflowcomquestionsanswershelp put regex httpwwwstackoverflowcom i playing come baseurl resubr r url reduce link http obvious i need match third instance anyone explain i would thanks,3 urlparse would work since originally asked regexes try positive match instead negative substitution match rematchr url baseurl matchgroup this grab http https ftp everything first httpwwwtutorialspointcompythonpythonregexpressionshtm,i trying create regular expression match third instance url ie website name recorded nothing else so httpwwwstackoverflowcomquestionsanswershelp put regex httpwwwstackoverflowcom i playing come baseurl resubr r url reduce link http obvious i need match third instance anyone explain i would thanks,2 you using numpyhistogramdd say method proposed jozzas work what flatten three d arrays combine array dimensions xdimydimzdim pass histogramdd the fact original data d red herring since spatial information irrelevant calculating histogram here example using random data channel cubes import numpy n approximate largest cube size works laptop fill channel cubes random bit integers r numpyrandomrandint sizennnastypenumpyuint g numpyrandomrandint sizennnastypenumpyuint b numpyrandomrandint sizennnastypenumpyuint reorder data suitable histogramming data numpyvstackrflat gflat bflatastypenumpyuintt destroy originals save space delr delg delb size histogram cube hist edges numpyhistogramdd data binsm range check worked assert histsum n failed conserve pixels this use lot memory would expect histogramdd seems using bit floats work even though sending bit integers,i got xd arrays red green blue channels d rgb image what elegant way numpy create histogram volume input channels the operation would equivalent assume r g b d arrays output d array filled zeros x xdim ydim z zdim output rxyz gxyz bxyz this code slow large images can numpy improve efficiency algorithm,3 it seems pass least arguments in documentation module see arguments needs add method abc foaf knows def triple case need two context quoted addself triple context quoted i found information addself subject predicate object context quotedfalse adds given statement specific context model the quoted argument interpreted formulaaware stores indicate statement quotedhypothetical it error specify context quoted argument true it also error quoted argument true store formulaaware,whenever i try add triple store using following code gives following error could please help regard thanks advance store pluginget iomemory store storeaddabc foaf knows def error traceback recent call last file cpythoninternetcodepy line module storeaddabc foaf knows def typeerror add takes least arguments given,1 for rms i think clearest numpy import mean sqrt square arange arange for example rms sqrtmeansquarea the code reads like say rootmeansquare,can anyone direct section numpy manual get functions accomplish root mean square calculations know accomplished using npmean npabs built curious offense anyone explain complications matrix arrays following case u matrixtbynor u say t cross n ue another matrixtbyn i define k numpy array uind still matrix following fashion k nparrayuind i print k type k ipython displays following k array you see double square brackets makes multidim guess gives shape n i assign array defined way l npzerosn shape n perhaps n something like l k error matrix dimensions incompatible is way accomplish vector assignment i intend please tell l k defeats purpose i get different errors program i know reasons if need i may attach piece code writing loop dumb way i using time i hope i able explain problems i facing regards,3 personally i situations creating test cases although would could integration test cases unit test cases so usually workflow would regular test cases diff actual output expected output although probably separate source folder run often unittest cases the bad part main remember run entry point probably forget later project grows many files least test case calls main,i quickly explain exactly i mean i working project using python i multiple modules segments work let say example i module called parserpy module function parsefile main module mainpy calls order parse files as right i using main method inside parserpy name main linelist parsefilesysargv outfile opensysargv w rangelenlinelist outfilewritelinelistigetstringtrue it important exactly parsing important part call first argument input file parsing second argument output file parsing so i essentially i using batch file validate results parser typical input output baseline system echo set test source input output baseline directories set testdircd set srcdircdpyprosrc set indircdinput set outdircdoutput set basedircdbaseline parserpy main method base unit testing parsing echo begin parser testing cd indirparser for g in psma do srcdirparserpy g outdirparserg echo parser testing complete cd testdir cprogram fileswinmergewinmergeuexe outdir basedir as see diffs results baseline anything changed programmer knows longer valid requirements wrong is anything wrong method i would easy my plan continue many modules i valid make sense way well suite pyunit tests inside pydev,1 edit i saw actual question answered how profile python script sure use profilepy import profile def myfunction bla bla bla profilerun myfunction see also profilers tips performance edit above example one function you profile run script commandline cprofile python cprofile myscriptpy your programscript could look also like following profiling always run def myfunction range printi def myotherfunction range printi def main main program run several days range myfunction myotherfunction name main profilerun main execute program show profiling results afterwards,i python program running many days memory usage increase much however program becomes slower slower is tool utility list function calls long take complete something like guppyheapy cpu usage,1 you use getsavefilenameandfilter method filename filter qtguiqfiledialoggetsavefilenameandfilterself save file filestypes in pyside however getsavefilenameandfilter exist getsavefilename already behaves way i sure whether also case pyqt api version default python,about pyqt i prefer use static method getsavefilename qfiledialog user sees windowsmac native dialog my problem user type file extension save file name say selecting image type save file i way checking see type file wanted save how i create dialog save files filter know filter user chose for example filestypes gml gmlpickle pickleyaml yml file qtguiqfiledialoggetsavefilenameself save file filestypes with var file i file path i sure whats format user chose so i wanna know could i get extension files type chosen user is away get selectedfilter using method thanks lot,2 yes shared objects get serialized pickle protocol even handle circular references from documentation the pickle module keeps track objects already serialized later references object won’t serialized marshal doesn’t this implications recursive objects object sharing recursive objects objects contain references these handled marshal fact attempting marshal recursive objects crash python interpreter object sharing happens multiple references object different places object hierarchy serialized pickle stores objects ensures references point master copy shared objects remain shared important mutable objects,if i objects b reference object obj happens i pickle restore objects will pickled data know b referenced object restore everything accordingly two get two different mdash initially equal mdash objects,3 if keys catdict numeric strings use print datedictintitem otherwise i uncertain need see declaration catdict looks like if using lists want idx val enumeratecatlist print datelistidx,sorry poor title basically i want access list item based another list item catlist john james jack datelist item catlist item typelist calendar item typelist connector print datelistitem it last line i want achieve essentially print value datelist corresponds value catlist any ideas thanks edit my catdict amp datedict list keys values,1 looking github appears djangoeav active development if working want expect change data model need apply south south works fine managing apps others definitely use south apps building modifying but stable library i rarely bother,i starting new django project usually put south installed apps then need kind eav store fields model found app exactly want djangoeav httpsgithubcommvpdevdjangoeav but facing problem south complains know work djangoeav cannot freeze field eavattributeslug field class eavfieldseavslugfield cannot freeze field eavattributedatatype field class eavfieldseavdatatypefield south cannot introspect fields probably custom fields if worked removed models parser often broke things to fix read httpsouthaeracodeorgwikimyfieldsdontwork i reading httpsouthaeracodeorgdocscustomfieldshtml trying solve problem without giving two projects anyone could help thanks,1 as aix points pickle understands multiple references object within single pickling that pickle always pickles single object if object references within references properly shared unpickled object but call pickle twice pickle two objects shared references objects preserved properly the object exist twice,if i objects b reference object obj happens i pickle restore objects will pickled data know b referenced object restore everything accordingly two get two different mdash initially equal mdash objects,3 i sure produce error fix change usrlocalbindjangoadminpy shebang usrbinenv python actually install django virtualenv djangoadminpy shebang set python interpreter virtualenv script created usrlocalbin instead created virtualenvpathbin along activate virtualenv python interpreter confuse unless moved,i googled hell solutions i found seem solve problems mine i created project virtual environment usersuserdocumentsprojectsproject using virtualenv installed django later i deleted project installed django system outside virtual environment now i trying run djangoadminpy startproject mysite however i receiving error message bash usrlocalbindjangoadminpy usersuserdocumentsprojectsprojectbinpython bad interpreter no file directory i found way i make work setting project virtual environment i django installed how i fix,3 from comments question curve wellbehaved could use something like ternary search the problem handle inconvenient behavior approach zero so start zero define new function g function f gx fx search starting x small value doubling otherwise increasing interval size contains minimum to need know limit f argument approaches infinity equivalent limit g argument goes zero if evaluated explicitly i try numerical approximation see comments answer points consider increase interval size especially steve jessop,i interesting problem i faced function takes long time compute value based index call takesalongtimeindex the values returned function guaranteed global minimum guarantees index associated close zero since takesalongtime takes arbitrarily large positive integers index there unique constraints begin binary search i need way create finite interval search exact minimum my first thought check increasingly large intervals starting zero something like def findintervalwithminimum start end intervalsize minimumininterval checkminimuminstart end minimumininterval intervalsize intervalsize start end end start intervalsize minimumininterval checkminimuminstart end return start end this would seem work fine additional detail really throws things takesalongtime requires exponentially time compute value indexes approach zero since checkminimumin would require multiple calls takesalongtime i would like avoid starting zero so question given minimum could anywhere infinity reasonable way run backwards or good heuristic use avoid checking low indices necessary i love language agnostic solution however i writing python python specific approach i take well,1 what version gtk using this link seems indicate threading bug fixed,does somebody knows error means fatal python error pyevalrestorethread null tstate in application i destroy main window error printed i using multiples threads run differents jobs time i really dont ideia if someone ever lived problem please help below code show reproduce error i tried make smallest code i could usrbinenv python import gtk import threading import sys class testthreadingthread a subclass threadingthread kill method def initself args keywords threadingthreadinitself args keywords gtkgdkthreadsinit selfkilled false def startself start thread selfrunbackup selfrun selfrun selfrun force thread install trace threadingthreadstartself def runself hacked run function installs trace syssettraceselfglobaltrace selfrunbackup selfrun selfrunbackup def globaltraceself frame arg call return selflocaltrace else return none def localtraceself frame arg selfkilled line raise systemexit return selflocaltrace def killself selfkilled true class windowgtkwindow main window def initself create main window children superwindow selfinit selfconnect destroy gtkmainquit button gtkbuttonclick close window buttonconnectclicked selfonitemrun selfaddbutton selfshowall def onitemrunself widget test tstart name main window window gtkgdkthreadsenter gtkmain gtkgdkthreadsleave thanks lot,1 sounds like thing pick large number big enough takesalongtime take long acceptable start two threads one starts looking towards positive infinity range containing minimum another one starts looking towards zero range containing minimum because exponential time increase might well infinity far searching concerned whichever thread finds result cancel one but unless want take advantage multiple cpu cores start two threads start exactly two threads start one per core just alternate work side given basic strategy need tune rate approach the faster approach fewer steps find minimum really side bigger range left binary searched average overshoot towards zero if performance curve reciprocalexponential presumably want overshoot little possible approach slowly it might even task computationally infeasible exponential often means impossible obviously i say anything initial large number is hundred tolerable is million graham number if even know likely acceptable performance could find running parallel either via threads via dovetailing set calculations takesalongtime different indexes one completes again guarantee computationally feasible every single index fits memory computer takes least billion years stuck practice even though solution theory,i interesting problem i faced function takes long time compute value based index call takesalongtimeindex the values returned function guaranteed global minimum guarantees index associated close zero since takesalongtime takes arbitrarily large positive integers index there unique constraints begin binary search i need way create finite interval search exact minimum my first thought check increasingly large intervals starting zero something like def findintervalwithminimum start end intervalsize minimumininterval checkminimuminstart end minimumininterval intervalsize intervalsize start end end start intervalsize minimumininterval checkminimuminstart end return start end this would seem work fine additional detail really throws things takesalongtime requires exponentially time compute value indexes approach zero since checkminimumin would require multiple calls takesalongtime i would like avoid starting zero so question given minimum could anywhere infinity reasonable way run backwards or good heuristic use avoid checking low indices necessary i love language agnostic solution however i writing python python specific approach i take well,1 how import numpy np npzeros nparray j nparray k nparray ijk npvstackijkt hedge nphistogramddijkbinsashape h,i interested multidimensional case increment numpy array repeated indices i ndimensional array set n index arrays values i want increment the index arrays might repeated entries without repeats solution arangereshape array j array k array aijk with repeats ex jarray i unable make numpy increment replicates,1 for accessing template probably noticed django let use underscore prefixes access attributes templates thus easiest way access verbose name given object without create model method model would create template tag registersimpletag def getverbosenameobject return objectmetaverbosename unrelated bug template trying access meta attribute queryset instead object so title line instead look something like objsfirst obj div classtitle getverbosename obj div endwith,i need display several models name amp objects template here view def contentsrequest lists contents objects modelobjectsall modelobjectsall modelobjectsall modelobjectsall return rendertoresponse contentcontentshtml objs contextinstancerequestcontextrequest and template objs objects div classcontent div classtitle objsmetaverbosename div ul obj objs li obj li endfor ul div endfor of course objsmetaverbosename work is way access verbose name without create function model assign value view model,3 to pedantic probably good hardcode either path separator maybe would best mypath ospathjoin cs ossep sourcedir mypath ospathjoin c ossep sourcedir,i trying learn python making program output script i want use ospathjoin pretty confused according docs i say ospathjoin c sourcedir i get csourcedir according docs normal right but i use copytree command python output desired way example import shutil src ospathjoin c src dst ospathjoin c dst shutilcopytreesrc dst here error code i get windowserror error the system cannot find path specified csrc if i wrap ospathjoin ospathnormpath i get error if ospathjoin used way i confused purpose according pages suggested stack overflow slashes used joinmdashthat correct i assume,3 setting background thread pygtk difficult,is way block pygtk performing expensive operation i know threading would work would take lot code setup thanks,2 first create function use testing def somecode try import cstringio stringio print got cstringio except importerror import stringio print got stringio somecode got cstringio now explained hook import function import builtin originalimport builtinimport def importhookname args kwargs name cstringio raise importerror test case module import failure else return originalimportname args kwargs builtinimport importhook somecode got stringio after test case set back builtinimport originalimport,given code like somemodpy try import cstringio stringio except importerror import stringio how one test fallback branch use case trying achieve coverage agreed bit silly goal complications code runs testsomemodpy import somemod mocking importerror python covers complicated,1 make try make,i trouble running make command debian command line install python i untarred download pythonorg ran configure appeared worked fine unfortunately i type make i get following error make no file directory not sure occurs i like get updated version python continue learning language thanks help andy,1 foolist fooobjectsfilterparamsselectrelated job the rest code would remain f foolist fbar would use cached objects,context foo class foreignkey field pointing bar object several foo may refer bar many one i need reference several fields foo object foreignkey barfield barfield seems time i runs separate query as result referencing fields take forever is way get bar objects single query or better way speed foolist fooobjectsfilterparams takes sec returns k objects result f foolist part takes seconds due huge number queries bar fbar foo contains foreignkey reference bar class resultappend field ffield barfield barbarfield barfield barbarfield way even worse barfield fbarbarfield barfield fbarbarfield,2 yes use selectrelated method queryset httpsdocsdjangoprojectcomendevrefmodelsquerysetsdjangodbmodelsqueryquerysetselectrelated joins initial query so case something like foolist fooobjectsfilterparamsselectrelated if deep chain linked models may worth also limiting depth get bar objects additional links beyond like selectrelateddepth,context foo class foreignkey field pointing bar object several foo may refer bar many one i need reference several fields foo object foreignkey barfield barfield seems time i runs separate query as result referencing fields take forever is way get bar objects single query or better way speed foolist fooobjectsfilterparams takes sec returns k objects result f foolist part takes seconds due huge number queries bar fbar foo contains foreignkey reference bar class resultappend field ffield barfield barbarfield barfield barbarfield way even worse barfield fbarbarfield barfield fbarbarfield,1 on design pattern support there proposition also puts design patterns crude metric gaps programming language it would interesting read counterpoint suggestion design patterns constraints supported language httpwwwosconcomosconpublicscheduledetail,i experienced developer done lot heavy duty work delphi c c years i always adhered closely guidelines structured programming oop loosely coupled modular designs etc since languages i used builtin ways enforcing concepts access control static types interface abstract class support etc i rely structure code now i doodling python months i impressed many wonderful features i sorely miss builtin constraints make easy keep code modularized organized and unfortunately i see awful lot spaghetti code written python even respectable sources i single anyone i books written major league pythonistas examples replete designs better put antidesigns make shudder it seems python easy use also easy abuse i try discipline i code python i find takes lot extra work implement often i set adhere constraints simply based memory design help language and since compile time checking doubly difficult often discover design flaw actually run segment code so i looking specific information examples better still book well structured python designs design techniques best implement encapsulation indirection loosely coupled designs etc bad design imo prominent python book author obfuscation def populatelistself selecteddisknone selected none bundling coupling selflistwidgetclear disk selfdisksinorder item qlistwidgetitemqstring l argdisknameargdiskownerargdiskcountry argdiskteu selflistwidgetadditemitem bundling coupling selecteddisk none selecteddisk iddisk selected item selected none selectedsetselectedtrue selflistwidgetsetcurrentitemselected,1 you need anything sqlalchemy,i storing filenames filepaths mysql retrieving database using like expression requires i escape allowed filename chars collide mysql special chars i happy simply use python stringreplace method wondering standard builtin method sanitizing filepaths sqlalchemy dealing filepaths mysql general edit a little information i need solution osagnostic established it need implemented sa i accept procedure encoding works saving i need list chars need escaped smart choice escape char,1 i find takes lot extra work implement compile code adheres constraints simply based memory design help language writing code compiling some ide offer help language offers help and since compile time checking never seems help find ordinary logic bugs doubly difficult often discover design flaw actually run segment code python designs design techniques best implement encapsulation by encapsulating in languages like java c encapsulation grown mean uses private stuff place in python simply supported we all adults here you still encapsulation like every language without word private however python offers properties decorators overrides getattribute implement various kinds encapsulation techniques indirection by referencing objects i clear specific problems perhaps passed wrongtype argument function the way avoid read docstrings wrote loosely coupled designs etc by dependency injection again python works like every language respect loose coupling you investigate use docstrings heavily you might want use httpsphinxpocooorg generate nice documentation docstrings you also use python builtin help function read docstrings wrote wrote code,i experienced developer done lot heavy duty work delphi c c years i always adhered closely guidelines structured programming oop loosely coupled modular designs etc since languages i used builtin ways enforcing concepts access control static types interface abstract class support etc i rely structure code now i doodling python months i impressed many wonderful features i sorely miss builtin constraints make easy keep code modularized organized and unfortunately i see awful lot spaghetti code written python even respectable sources i single anyone i books written major league pythonistas examples replete designs better put antidesigns make shudder it seems python easy use also easy abuse i try discipline i code python i find takes lot extra work implement often i set adhere constraints simply based memory design help language and since compile time checking doubly difficult often discover design flaw actually run segment code so i looking specific information examples better still book well structured python designs design techniques best implement encapsulation indirection loosely coupled designs etc bad design imo prominent python book author obfuscation def populatelistself selecteddisknone selected none bundling coupling selflistwidgetclear disk selfdisksinorder item qlistwidgetitemqstring l argdisknameargdiskownerargdiskcountry argdiskteu selflistwidgetadditemitem bundling coupling selecteddisk none selecteddisk iddisk selected item selected none selectedsetselectedtrue selflistwidgetsetcurrentitemselected,1 i like rocket web server particular written python it also api creating kinds servers i able adapt xmlrpc server minimal amount effort,what wsgi servers available python pep,1 you need tell jquery jsonp actually script it call function json data json data it said invalid json jquery trying parse function call ajax url httpwwwurltomydomaincom datatype jsonp success functionjson consolelog success consolelogjson error functionxyz xresponsetext wrong consolelogx consolelogy consolelogz datatype jsonp automatically adds callback url needed you also use getjson requires add callback getjson httpwwwurltomydomaincomcallback functionjson consolelog success consolelogjson you use callback jquery automatially replace second dynamic name callback function,i currently puling data external xml file converting json via pythondjango the problem i encountering i pull json jquery i getting error invalid json however i put json validator jsonformatter i told json valid python code def testrequest tree lxmletreeparsehttpsomedomaincom deals treexpathpagedealsdeal dealsinfo deal deals thisvalue iddealfindidtext totaldealcountdealfindtotaldealcounttext offerdealfindoffertext linkdealfindlinktext merchantnamedealfindmerchantnametext salepricedealfindsalepricetext productvaluedealfindproductvaluetext dealsinfoappendthisvalue jsondeals deals simplejsondumpsdealsinfo ifcallback requestgetkeys callback requestgetcallback else callback none ifcallback response httpresponsess callback simplejsondumpsdealsinfo mimetypeapplicationjson else response httpresponsejsondeals mimetypeapplicationjson return response the returned json mycallbackproductvalue totaldealcount merchantname joes door knobs offer deal link httpsomelinkcom saleprice id productvalue totaldealcount merchantname bob pizza offer deal link httpsomelinkcom saleprice id my jquery code ajax url httpwwwurltomydomaincomcallbackmycallback data datatype json success functionjson consolelog success consolelogjson error functionxyz xresponsetext wrong consolelogx consolelogy consolelogz any help would appreciated thanks,2 i think problem code code working fine shared socket when accept sa ocket evread must get client socket free control main socket must write you use code similar following one try clientsocket address sockaccept except socketerror err err errnoeagain sysexcclear return raise coreeventcoreevread clientsocketfileno callback coreeventcoreevwrite clientsocketfileno callback coreeventcoreevread coreevwrite clientsocketfileno callback after set read write events socket,the problem happened proxy program considering gk i use gevent program i use lowlevel geventcore run function before i change program multiple processes everything ok but i changed problem appears i find problem process no accept socket events process no stop dispatch and i add sleep event came surprise but i lower sleep time problem showed the problem bothered weeks still nothing could someone help i use event like coreinit selfentssend coreeventcoreevwriteselfconnfileno selfsersendselfconnselfbody selfentssendadd coredispatch,1 adminspy class myregisteredtouradminadminmodeladmin def querysetself request qs tourobjectsfilteractionuserrequestuser return qs adminsiteregistertourmyregisteredtouradmin,i django model like class tourmodelsmodel namemodelscharfieldmaxlength countmodelssmallintegerfield priceunitcodemodelsforeignkeypriceunit pricemodelscharfieldmaxlength descriptionmodelstextfield actiondatemodelscharfieldmaxlength actionusermodelsforeignkeyuser when user logs admin site i would want user see tour instances created tour instances actionuser equal id loggedin user how i filter changelist based loggedin users,1 key value mydictiteritems this iterate dictionary storing key key value value see docs,basically i dictionary i want transform list lists component list consisting key value dictionary the reason i i iterate new list loop something key value if easier way i open suggestions,3 iterate dictionary keys values key value diteritems something,basically i dictionary i want transform list lists component list consisting key value dictionary the reason i i iterate new list loop something key value if easier way i open suggestions,2 when type configure runs executable script current directory labeled called configure make executable file usually located somewhere like usrbin uses file directory run bunch commands depending whether files date when type make shell program handles commands sends output terminal go looking directories path environment variable find executable file called make run first one finds but type make actually telling try run executable file current directory called make it uses approach searching path variable whenever put command you use anywhere could use normal directory specify directory example usrbin usrbin similarly use specify directory usrbinbinbinlib usrlib so running configure script located generates socalled makefile run system wide version make located ever typing make uses makefile build package also use command find command run enter command example make apologies condescending i going completism also i may overused code tags,i trouble running make command debian command line install python i untarred download pythonorg ran configure appeared worked fine unfortunately i type make i get following error make no file directory not sure occurs i like get updated version python continue learning language thanks help andy,1 for c something called ecwin look httpcodegooglecompduktosourcebrowsetrunksrcecwincpp maybe hard make python bindings i sure hope helps anyhow,i looking way using windows task bar features specifically progressbar jump lists python application uses qt ui the questions i seen so years old either say qt yet next version since released point qgoodies i prefer use cost reasons does anyone know qt python binding either pyqt pyside interact windows taskbar i using python x qt i upgrade needed i move python x yet,1 there number ways optimize approach answer specific question rather duplicate handler could add get parameter link check constructing query class useradminpagewebapprequesthandler def getself orderby selfrequestget order query ownerall queryfilterowner user orderby queryorderownertag elif orderby date queryorderdate hrefyourpageurlorderdateorder tags recenta,i table useradminpage tags listed alpha order code i want add link change order date i know i change queryorderownertag queryorderdate i need create new handler i understand link question marks thanks class useradminpagewebapprequesthandler def getself tags table query ownerall queryfilterowner user queryorderownertag w queryfetch usertaglist item w usertaglistappenditemownertag uniquetags sortedffusertaglist holding table start selfresponseoutwrite table border cellpadding cellspacing tr td tags table start selfresponseoutwritetable border tr th colspantagsbr link sort recent hreforder tags recentath tr tag uniquetags selfresponseoutwrite tr tda hreftagtagssatd tr tag tag selfresponseoutwritetable holding table first column end selfresponseoutwritetd holding table second column start selfresponseoutwritetd styleverticalaligntop updated code as per kevin p s answer class useradminpagewebapprequesthandler def getself orderby selfrequestgetorder tags table query ownerall queryfilterowner user orderby queryorderownertag elif orderby date queryorderdate w queryfetch usertaglist item w usertaglistappenditemownertag uniquetags ffusertaglist holding table start selfresponseoutwrite table border cellpadding cellspacing tr td tags table start i put link i click table drawn block draws tag table i understand i draw table orderdate selfresponseoutwritetable border tr th colspantagsbr hreftagorderdatespan idsmallmost recentspanath tr tag uniquetags selfresponseoutwrite tr tda hreftagtagssatd tr tag tag selfresponseoutwritetable,2 here import string module import sysimp mycode mymodule impnewmodule mymodule exec mycode mymoduledict access module attributes functions classes etc mymodulea to ignore next attempt import add module sys sysmodules mymodule mymodule,in python something like import module using string filename assign namespace variable local namespace x importstr i wondering related function take take string python code instead path file python code return namespace variable for example str x importstrstr print xa output i realize i could write string file use import i like skip intermediate file possible the reason i experimenting metaprogramming python seems like good solution i,2 i facing nearly problem end i sticked boostpython however option boostpython swig if use swig also write much boilerplate code boostpython,i project mine written c progressed stage i require embedded programming language i chosen python several reasons playing around revealing api dynamicallyloaded python module it works well i think i stick python foreseeable future i question though i spending lot time adding function python api i providing i looking framework alleviates much repetition the framework seems mentioned time time boostpython while i nothing boostpython fact i probably use near future project i unfortunately cannot use boostrelated libraries are decent frameworks i particularly fancy writing neither i wish continue use straight python c api thanks,2 how trying connect import socket socketsocketsocketafinet socketsockstream result sconnectex result print socket open sclose,in translating scripts bash i encountering many uses netstat find one services listening while i know i use subprocesscall even popen i would rather use pythonic solution i leveraging unix environment operating from i read socket module something i seen anything checks listening ports it could understanding simple trick far i know connect socket write something lets know connection failed but necessarily i found something specifically checks port see listening any ideas,3 you could either try connecting port question emulate netstat doing latter osspecific on linux examine procnettcp it looks like sl localaddress remaddress st txqueue rxqueue tr tmwhen retrnsmt uid timeout inode c a fffffa cc a fffff f a fffff a fffff f a ffffda a ffffedcc a a ffffedc bc a ffffcca c a fffffe you looking lines a st status column the numbers colon localaddress c cc etc tcp port numbers hex listening processes,in translating scripts bash i encountering many uses netstat find one services listening while i know i use subprocesscall even popen i would rather use pythonic solution i leveraging unix environment operating from i read socket module something i seen anything checks listening ports it could understanding simple trick far i know connect socket write something lets know connection failed but necessarily i found something specifically checks port see listening any ideas,1 in past accomplish i read portion socket data memory read buffer rnrn sequence encountered could use state machine simply use stringfind function once reach sequence know headers read parsing headers read entire content length you may need prepared read response include contentlength header since responses contain if run buffer seeing sequence simply read data socket buffer continue processing i post c example would like look,i trying code python http library learn sockets http protocol my question recvbytestoread using socket i get header contentlength information continue recieving page content isn purpose contentlength header thanks advance,1 def fookwargs pass foo foo bar,from external file i generate following dictionary mydict foo bar given function takes kwargs argument generate keywordargs dictionary,3 your misunderstanding seems come importing string module well naming variable string you need import module use find could name variable something else need import module something else the type str string find work like you mean stringfindch index want variable named string strfindstring ch index want variable named string really want access class type str reason you call find string searching pass string find manually unless accessing find class type find first manually passed argument string search followed start end indexes since appear searching whole string omitted,i bit trouble understanding happening when i run following def findinstringstring ch count index index lenstring stringfindstring ch index return true findinstring asdfasdf here i get typeerror slice indices must integers none index method however running interpreter like index stringfind asdfasdf index return true it returns true so i understanding stringfind getting passed integer starting index function any advice appreciated edit for whatever reason function works importing string perhaps much coffee,1 you make foo objects properties moo objects server side f b zipfoo bar ffoosbar b context foo foo this especially clean second list properties first typically case users userobjectsall user users userbestfriend findbestfriendforuseruser context users users,i want list iteration django templates foo foo bar moo moo loo b zipfoo moo print b django code b zipfoo moo b endfor i get error i try file basepythonlibversionsthirdpartydjangodjangotemplatedefaulttagspy line dofor raise templatesyntaxerror statements either four five words tokencontents how i accomplish,1 now i also method capturing exceptions i want log text file use logging httpdocspythonorglibrarylogginghtml the problem already solved no work,this little bit strange question i bunch automation scripts using sikulijython want run parent script regression purposes now i also method capturing exceptions i want log text file so currently works master script specific test script specific test script etc ever many scripts i talking friend mine recommended script handles errors parent script opens file makes file location global variable child scripts append file basically i need anything special python make possible master script basically touching file scripts use here example parent script code handle errors open file executes scripts dirpath dirnames filenames oswalkcdirectorytothescripts filename f f filenames fendswithpy directoryappendospathjoindirpath filename entry directory execfileentry,1 on linux use strace see netstat ln reading parsing various values proc filesystem strace netstat ln amp grep proc openprocnettcp ordonly openprocnettcp ordonly openprocnetudp ordonly openprocnetudp ordonly openprocnetraw ordonly openprocnetraw ordonly openprocnetunix ordonly openprocnetipxsocket ordonly enoent no file directory openprocnetipx ordonly enoent no file directory openprocnetax ordonly enoent no file directory openprocnetx ordonly enoent no file directory openprocnetx ordonly enoent no file directory openprocnetnr ordonly enoent no file directory so read files python extract data need cat procnettcp sl localaddress remaddress st txqueue rxqueue tr tmwhen retrnsmt uid timeout inode a a f a dbac dbb dbacd edabb e dbacda edabb dbacd edabb the listening sockets remote address the addressport pairs hex see how match procnettcp entry opened socket you could cross reference procfd for example sshd running laptop cat varrunsshdpid sudo ls l procfd total lrwx root root devnull lrwx root root devnull lrwx root root devnull lrwx root root socket lrwx root root socket socket corresponds inode listed second row procnettcp so get information proc may end reinventing netstat lntp,in translating scripts bash i encountering many uses netstat find one services listening while i know i use subprocesscall even popen i would rather use pythonic solution i leveraging unix environment operating from i read socket module something i seen anything checks listening ports it could understanding simple trick far i know connect socket write something lets know connection failed but necessarily i found something specifically checks port see listening any ideas,1 why yield f use val hnext,suppose simple generator python like update def fself customfunctionarglist yield customfunctionarglist yield customfunctionarglist yield i call f another script like hf true try hnext sleep except keyboardinterrupt todo tell last line f executed is way i todo section knowing last line f executed keyboardinterrupt occurred,1 you use enumerate count def f yield yield step value enumeratef try timesleep except keyboardinterrupt printstep step holds number last executed function example yield yield value value course none or explicit using verbose indication def f yield first function finished yield almost done message f try timesleep except keyboardinterrupt printmessage,suppose simple generator python like update def fself customfunctionarglist yield customfunctionarglist yield customfunctionarglist yield i call f another script like hf true try hnext sleep except keyboardinterrupt todo tell last line f executed is way i todo section knowing last line f executed keyboardinterrupt occurred,2 are trying run windows python cygwin i problem python cygwin fails import site python cmd works it looks like need make sure run pythonhome pythonpath cygwin aw make windows paths also python seems using incorrect paths i think i need install python cygwin get working,i trying install python first time i downloaded following installer python website python windows installer windows binary include source i ran installer selected all users fine i installed python default location cpython next test python installed correctly i navigated python directory ran python command windows cmd prompt it returns following error importerror no module named site when i python v i get following installing zipimport hook import zipimport builtin installed zipimport hook importerror no module named site clear builtin clear syspath clear sysargv clear sysps clear sysps clear sysexitfunc clear sysexctype clear sysexcvalue clear sysexctraceback clear syslasttype clear syslastvalue clear syslasttraceback clear syspathhooks clear syspathimportercache clear sysmetapath clear sysflags clear sysfloatinfo restore sysstdin restore sysstdout restore sysstderr cleanup main cleanup zipimport cleanup signal cleanup exceptions cleanup warnings cleanup sys cleanup builtin cleanup ints unfreed ints cleanup floats when i dir cpythonlibsitepy i get following cusersmimminitodir cpythonlibsitepy volume drive c label volume serial number daba directory cpythonlib sitepy files bytes dirs bytes free any ideas,2 import sys def strtoobjastr strtoobj scipystatsstats returns associated module strtoobj scipystatsstatschisquare returns associated function print processing astr try return globalsastr except keyerror try importastr modsysmodulesastr return mod except importerror modulebasenameastrrpartition module modstrtoobjmodule return getattrmodbasename else raise,given string form packagemoduleclass simple way python get class object directly assuming module yet imported if cleanest way separate packagemodule part class part import module get class,2 that pretty broad question among sparse coding dictionary learning nonnegative factorization plenty methods many still new yet exist dominant piece python software universally accepted these research areas recent focus i primarily use python i decided write simple versions matching pursuit nmf nonnegative ls ksvd i might recommend specific purposes difficult implement modify just get used numpy scipy numpylinalg that said publicly available python tools need search specifically for instance matching pursuit python yields results for convex optimization formulations could use cvx really easy use may find fast enough,i looking library implements common sparse coding dictionary learning algorithms python interface suggestion,1 try something like def importobjpath pathparts pathsplit obj importjoinpathparts pathremainder listreversedpathparts pathremainder obj getattrobj pathremainderpop return obj this work anything getattr module eg module level functions constants forth,given string form packagemoduleclass simple way python get class object directly assuming module yet imported if cleanest way separate packagemodule part class part import module get class,2 the length give recv maximum target there guarantee recv wait len bytes received return soon read data the man page recv says the receive calls normally return data available requested amount rather waiting receipt full amount requested if need read given number bytes need call recv loop concatenate returned packets read enough,i echo server c test client python the server limited read buffer eg bytes when client send bytes first read write back client read i tested server telnet i got back string input even longer bytes however python client work data initialized bytes data len socksetblocking socksenddata recvdata sockrecvlen ifrecvdata data print recvdataencode hex print len print dataencode hex this client receive first bytes server writes back the server log show two writes python output looks like recvdata sent data i sure happening how come blocking recv returns less data asked,3 some hints each node check encapsulate data got dfs like stack start pushing start state you pop stack push back nodes follow node popped since ultimately trying find path node data must hold location path took get,i working assignment found ai course page berkley website fun i need write depthfirst search pacman game find paththe problem pacman gets stuck i paste code first make i saying clear import util class searchproblem this class outlines structure search problem implement methods objectoriented terminology abstract class you need change anything class ever def getstartstateself returns start state search problem utilraisenotdefined def isgoalstateself state state search state returns true state valid goal state utilraisenotdefined def getsuccessorsself state state search state for given state return list triples successor action stepcost successor successor current state action action required get stepcost incremental cost expanding successor utilraisenotdefined def getcostofactionsself actions actions a list actions take this method returns total cost particular sequence actions the sequence must composed legal moves utilraisenotdefined def tinymazesearchproblem returns sequence moves solves tinymaze for maze sequence moves incorrect use tinymaze game import directions directionssouth w directionswest return sswswwsw def depthfirstsearchproblem search deepest nodes search tree first p your search algorithm needs return list actions reaches goal make sure implement graph search algorithm fig to get started might want try simple commands understand search problem passed print start problemgetstartstate print is start goal problemisgoalstateproblemgetstartstate print start successors problemgetsuccessorsproblemgetstartstate your code here start problemgetstartstate item start openitem state closed path problemisgoalstateopen true return state else open visit openpop closedappendvisit state pathappendstatepop problemisgoalstatevisit true print closed return path else successors problemgetsuccessorsvisit index successors ititerindex dataitnext data closed openappenddata stateappenditnext else print path now read code dfs see open list contains points i visit expanded the path file contains direction set pacman the problem arises i face condition successors i get unvisited pacman takes path leads dead end needs backtrace my open finds solution i able find way provide directions backtracing path list if go httpinsteecsberkeleyeducsspprojectssearchsearchhtml download zip paste code searchpy dfs search understand problem,2 type exit capital e alternatively start ipython ipython noconfirmexit or newer versions ipython ipython noconfirmexit,it really irritating every time i type exit i get prompted confirmation exit course i want exit otherwise i would written exit is way override ipython default behaviour make exit without prompt,3 you two variables one keep track person speaking keep paragraphs persons speaking for storing paragraphs associating paragraph belongs use dict person key list paragraphs person said associated key paradict dict paratype none word words p word p word p word extract part want leaving paratype word create dict list lists contain paragraph person uses paratype paradict paradictparatype list paradictparatypeappendlist else append word last list list lists paradictparatypeappendword from sum number words spoken thus person paralist paradictitems countslist list para paralist countslistappendlenpara print person spoke sumcountslist words,i starting learn python i trying write program would import text file count total number words count number words specific paragraph said participant described p p etc exclude words ie p etc word count print paragraphs separately thanks james hurford i got code like words none open datatxt f words freadsplit totalwords lenwords print total words totalwords inpara false paratype none paragraph list word words p word p word p word inpara false inpara true paratype word else print words paragraph paratype lenparagraph print joinparagraph del paragraph paratype word else paragraphappendword else inpara true print words last paragraph paratype lenparagraph print joinparagraph else print no words my text file looks like p bla bla bla p bla bla bla bla p bla bla p bla the next part i need summing words participant i print i know returnreuse i would need new variable word count participant i could manipulate later addition summing words said participant eg pall sum words paragraph is way count etc two words any ideas solve,1 yes it possible execute external python script you use simpleserver example receives ajax request page calls subprocess osstartfile launch script in fact call function within server return result eg json page use javascript handle,so i searching topic quite i unable find whether possible i suspect i need sure what i i building fancy web app uses xml xsl javascript however i need transformation text file convert proper xml file to i use python script what i need i working make easy possible use app gets kind destroyed user execute terminal script anything i need graphical ide python i time learn make one i would love entire app would work within web environment much intuitive user then really easy way would use firefox ide example choosing file transformed launching python script what i require i need compatibility firefox but course system capable install python firefox work well the user would happily install programs long interest app what i know is possible execute external python script if security reasons i imagine way user allow maybe installation plugin maybe httpmozexmozdevorg i looking thanks gerard,1 your problem sounds like perfect fit posixipc sysvipc modules expose either posix sysv apis shared memory semaphores message queues the feature matrix includes excellent advice picking amongst modules provides the problem anonymous mmap areas cannot easily share processes filebacked easy actually need file anything else feels silly you could use clonevm flag clone system call c i want try using language interpreter probably makes assumptions memory safety it little dangerous even c maintenance programmers five years might also shocked clonevm behavior but sysv newer posix shared memory mappings allow even unrelated processes attach detach shared memory identifier need share identifier processes create mappings processes consume mappings manipulate data within mappings available processes simultaneously without additional parsing overhead the shmopen function returns int used file descriptor later calls ftruncate mmap processes use shared memory segment without file created filesystem memory persist even processes using exited a little strange unix perhaps flexible,how i give child processes access data shared memory data available child processes spawned using multiprocessingprocess i aware multiprocessingsharedctypesrawarray i figure give child processes access rawarray created processes already started the data generated parent process amount data known advance if gil i using threading instead make task little simpler using noncpython implementation option looking hood muliprocessingsharedctypes looks like shared ctype objects allocated using mmap ed memory so question really boils can child process access anonymously mapped memory mmap called parent child process spawned that somewhat vein asked question except case caller mmap parent process child process solved i created version rawarray uses shmopen hood the resulting shared ctypes array shared process long identifier tag matches see answer details example,2 as page loading asynchronous wait loadfinished signal trying save then retrieve page content webpagecurrentframetohtml returns python unicode string write file codecs module pysideqtcore import pysideqtgui import pysideqtwebkit import import sys import codecs class downloaderqobject to emitted every items downloaded done signal def initself urllist parent none superdownloader selfinitparent selfurllist urllist selfcounter as probably need display page use qwebpage instead qwebview selfpage qwebpageself selfpageloadfinishedconnectselfsave selfstartnext def currenturlself return selfurllistselfcounter def currentfilenameself return selfurllistselfcounter def startnextself print downloading sselfcurrenturl selfpagemainframeloadselfcurrenturl def saveself ok ok data selfpagemainframetohtml codecsopenselfcurrentfilename encodingutf modew f fwritedata print saving sselfcurrenturl selfcurrentfilename else print error downloading snskippingselfcurrenturl selfcounter selfcounter lenselfurllist selfstartnext else selfdoneemit urllist httpnewsgooglecom googlehtml httpwwwstackoverflowcomstackhtml httpwwwimdbcom imdbhtml app qapplicationsysargv downloader downloaderurllist quit done downloaderdoneconnectappquit to view pages web qwebview to prevent user action would interrupt current page loading websetdisabledtrue websetpagedownloaderpage webshow sysexitappexec,what best simplest way save webpage displayed qwebview file pyqtqtcore import pyqtqtwebkit import pyqtqtgui import pyqtqtscript import import sys import time currentfile testhtm app qapplicationsysargv web qwebview webloadqurlhttpnewsgooglecom webshow data webpagecurrentframedocumentelementtoinnerxml opencurrentfilewwritedata sysexitappexec,3 numpyarrayv v vals lensetv lenv mind still loops behind scenes you avoid but work fine even millions rows,i n array numpy values vals numpyarray vals array i like remove rows array duplicate value for example result array duplicatesremoved array i sure efficiently numpy without looping array could quite large anyone know i could,2 this option import numpy vals numpyarray vals vals vals vals vals vals vals numpydeletevals numpywherea axis,i n array numpy values vals numpyarray vals array i like remove rows array duplicate value for example result array duplicatesremoved array i sure efficiently numpy without looping array could quite large anyone know i could,3 right relying fact keys typically generate sequence always case add date property model date dbdatetimepropertyautonowaddtrue also fix get parameter consistent here hrefuseradminpageorderxyzspan idsmallmost recentspana elif orderby xyz queryorderdate,see previous question i updated code per kevin p answer i able sort newest tag top my comments queryorderdate do know date minus sign works work without minus sign model class ownerdbmodel owner dbuserproperty ownertag dbstringproperty tagvalue dbintegerproperty url dbstringproperty handler draws tag table class useradminpagewebapprequesthandler def getself orderby selfrequestgetorder tags table query ownerall queryfilterowner user orderby queryorderownertag date minus sign table sorted correctly i remove minus signs i get propertyerror invalid property name date elif orderby date queryorderdate w queryfetch usertaglist item w usertaglistappenditemownertag uniquetags sortedffusertaglist uniquetags ffusertaglist holding table start selfresponseoutwrite table border cellpadding cellspacing tr td tags table start selfresponseoutwritetable border tr th colspantagsbr hrefuseradminpageorderdatespan idsmallmost recentspanath tr tag uniquetags selfresponseoutwrite tr tda hreftagtagssatd tr tag tag selfresponseoutwritetable,2 identical marcelo i think using numpyunique instead set may get across exactly shooting numpyarrayv v vals lennumpyuniquev lenv,i n array numpy values vals numpyarray vals array i like remove rows array duplicate value for example result array duplicatesremoved array i sure efficiently numpy without looping array could quite large anyone know i could,1 the easiest way use pip generate requirements file a requirements file basically file contains list python packages want install already installed case file generated pip versions to generate requirements file go original virtualenv run pip freeze requirementstxt this generate requirementstxt file if open file favorite text editor see something like django fabric etc now edit line says djangoxx say django whatever version want install new virtualenv lastly activate new virtualenv run pip install r requirementstxt and pip automatically download install python modules listed requirementstxt file whatever versions specified,i existing environment virtualenv lot packages old django version what i want duplicate environment i another environment i install newer django version keeping packages already environment,3 def fself sleep yield sleep yield sleep yield hf true try hnext except keyboardinterrupt stacktrace sysexcinfo first traceback points function exception caught stacktrace stacktracetbnext pointing happened case lineno stacktracetblineno line number del stacktrace get rid circular references i moved call sleep f works exception happens inside f,suppose simple generator python like update def fself customfunctionarglist yield customfunctionarglist yield customfunctionarglist yield i call f another script like hf true try hnext sleep except keyboardinterrupt todo tell last line f executed is way i todo section knowing last line f executed keyboardinterrupt occurred,1 note error message line break usrbinpython clarifies message this suggests operating system seeking file usrbinpython usrbinpythonnewline most likely copied python file windows system style linebreaks binsh expecting see script you solve problem converting windowsstyle newlines python script file following command dosunix homesomeuserpublichtmlxmlfeedcronjobwodpy if dosunix available system list alternative methods effect change,need urgent help regard trying run python script via cron job cpanel web hosting server using cpanel version build cron job set successfully ececuting file file failed following error recieved email binsh homesomeuserpublichtmlxmlfeedcronjobwodpy usrbinpython bad interpreter no file directory done far placed cronjobwodpy publichtmlxmlfeedcronjobwodpy permission code added usrbinpython top script added appache handler called cgiscript extensions cgi py pl still script working could get right path python interpreter solution problem please help,2 oslistdir provides base names absolute paths you need ospathjoinpath infile instead infile may still relative path fine needed absolute path feed ospathabspath,i wish read incoming xml files specific name eg datetime naming extract values perform particular tasks i step files trouble opening reading what i works import os path directory listing oslistdirpath infile listing print infile but i add following try read files errors saying no file directory file openinfile r thank,2 you join directory path filename using ospathjoinpath infile also use path without path directory something like not optimized small change code import os path directory listing oslistdirpath infile listing print infile fileabs ospathjoinpath infile file openfileabs r,i wish read incoming xml files specific name eg datetime naming extract values perform particular tasks i step files trouble opening reading what i works import os path directory listing oslistdirpath infile listing print infile but i add following try read files errors saying no file directory file openinfile r thank,1 you need provide path file file openospathjoinpathinfile r,i wish read incoming xml files specific name eg datetime naming extract values perform particular tasks i step files trouble opening reading what i works import os path directory listing oslistdirpath infile listing print infile but i add following try read files errors saying no file directory file openinfile r thank,2 if want know line number debugging purposes cpython use hgiframeflineno this line executed next indexed i sure works python implementations cpython hf true try hnext sleep except keyboardinterrupt print hgiframeflineno flineno line executed next if want know debugging purposes remi enumerate solution far cleaner,suppose simple generator python like update def fself customfunctionarglist yield customfunctionarglist yield customfunctionarglist yield i call f another script like hf true try hnext sleep except keyboardinterrupt todo tell last line f executed is way i todo section knowing last line f executed keyboardinterrupt occurred,1 docs cheese shop use requires keyword,i build new python lib i seeking information concerning packaging python i understand setuppy script controls everything i wonder deal external libraries svn instance how download automatically given version repository using setuppy,1 debugging simply change line words wordsstripsplit words wordsstripsplit print words see comes i mention couple things if literal userid file try process take kindly trying convert integer and unusual line n i would probably write n if indicate comment end seeing xxxxxx xxxxxxx i checking input file binary nontextual data you never end binary information reading text trimmingsplitting and state digits seem spaces hex dump file find really it may utf unicode string example,i text file contains entry like useridproductidscore i wrote program read sorry indendetion bit messed def generatesyntheticdatafilename datadict rowdict innerdict try key range count myfile openfilename c del innerdictleninnerdict line myfile c line strline n lenline print n n n c print c entries read far words linereplace words linereplace words wordsstripsplit print userid words userid int words get error movieid int words rating float words print userid userid productid movieid rating rating print words words wordsreplace innerdict datadictsetdefaultuserid innerdictmovieid rating datadictuserid innerdict innerdict except ioerror errnostrerror print io error formaterrnostrerror finally myfileclose print total ratings read filefilename c return datadict but get error valueerror invalid literal int base funny thing working fine reading format data file actually posting question i noticed something weird the entry number spacein like space space space space space space but text file looks fine copy pasting shows nature anyways clue whats going thanks,1 pep extensive discussion might wanna take look,in python functions created using def lambda dict attribute dynamically add attributes having dict every function memory cost an empty dict uses bytes cpython adding attributes function particularly common thing use custom object call method cases need function nonstandard attributes since adding custom attributes function common use case dict memory cost python functions dict,3 import sys f opensysargvr contents fread fclose print contents better import sys opensysargv r f contents fread print contents,how i read file python command line so let say texttxt file i want python prefixerpy texttxt would i read text file prefixerpy,3 in python functions created using def lambda dict attribute dynamically add attributes well yes objects having dict every function memory cost an empty dict uses bytes cpython it bytes not really matters sake discussion if really needed save every byte using python in program uses lot memory functions normally represent tiny fraction number objects overhead really important imo much worried fact costing bytes per floatingpoint value switch double float of course way worry use numpy adding attributes function particularly common thing if come javacc world i imagine must seem horribly messy but people come perljavascript world even rather different direction maybe something like scheme haskell pretty elegant so basically i would say answer,in python functions created using def lambda dict attribute dynamically add attributes having dict every function memory cost an empty dict uses bytes cpython adding attributes function particularly common thing use custom object call method cases need function nonstandard attributes since adding custom attributes function common use case dict memory cost python functions dict,2 keys must unique using keys means two values associated when creating dictionary setting key correspond value so first abc kfc but continually overriding keys give different values in end latest values keys kept type tag,thevalues u abc u kfc u listproperty u models u new u newer u note u order u tag u test u type thekeys dictzipthekeys thevalues u type u tag can give clue type tag taken i trying sort thevalues thekeys i noticed switching order thevalues thekeys works dictzipthevalues thekeys u abc u models u note u tag u kfc u newer u listproperty u test u new u type u order thanks,2 because dictionary definition unique keys otherwise would know value return look key the dict constructor iterates keyvalue pairs assigns value corresponding key dictionary overwriting previous value keys already present,thevalues u abc u kfc u listproperty u models u new u newer u note u order u tag u test u type thekeys dictzipthekeys thevalues u type u tag can give clue type tag taken i trying sort thevalues thekeys i noticed switching order thevalues thekeys works dictzipthevalues thekeys u abc u models u note u tag u kfc u newer u listproperty u test u new u type u order thanks,1 as others said keys must unique in order get around must use dictionary x x sortedzipthekeys thevalues keyoperatoritemgetter u abc u listproperty u new u newer u note u order u test u type u kfc u models u tag,thevalues u abc u kfc u listproperty u models u new u newer u note u order u tag u test u type thekeys dictzipthekeys thevalues u type u tag can give clue type tag taken i trying sort thevalues thekeys i noticed switching order thevalues thekeys works dictzipthevalues thekeys u abc u models u note u tag u kfc u newer u listproperty u test u new u type u order thanks,2 return ends function yield creates generator spits one value time def numberlistitems number item items yield strnumber item number number itemlines n joinnumberlist red orange yellow green alternatively return list def numberlistitems indexeditems number item items indexeditemsappendstrnumber item number number return indexeditems itemlines n joinnumberlist red orange yellow green use enumerate itemlines n joinstrx x enumerate red orange yellow green in case n joinstrx x iterable takes something like list turns item string like print joins string together newline like multiple print statements,if i print function def numberlistitems number item items printnumber item number number numberlist red orange yellow green i get red orange yellow green i change print function return function i get red i need return function work exactly like print function i need change code rewritethankspls make response simple understandable straight forward possiblecheers,3 on split use collectionscounter collections import counter numstring numcount counternumstringsplit pre collections import defaultdict numstring numcount defaultdictint num numstringsplit numcountnum if want use count numstring numlist numstringsplit numcount dictnum numlistcountnum num setnumlist omn rather on iterates list numbers unique number,i long string numbers seperated commas i search count number occurences numbers accurately digit numbers if i number sequences like i want count many times number appears i really get however counting i getting does anyone know make code match only whole strings thanks def mostfreqnumstring import json maxnum count list count maxnum listcount count numstring array numbers count topten count maxnum listcountnumstringcountstrcount topten toptenjsondumps count listcount sortkeystrue indent count responsegenerator topten return httpresponseresponsegenerator,3 the spaces thay seeing appear nuls x there chance file encoded utf utfle utfbe if oneoff file open notepad save ansi unicode unicode bigendian if however need process need knowdetect encoding to find print repropenyourfiletxt rbread compare srtart output following ucode u sfx le be enc utf sfx print enc reprucodeencodeenc utf xffxfexxxxxx utfle xxxxxx utfbe xxxxxx you make detector good enough purposes inspecting first bytes pseudocode fb xffxfexff utf elif fb x utfle elif fb x utfbe else cp utf whatever else prevalent neck woods you could avoid hardcoding fallback encoding import locale localegetpreferredencoding cp your linereading code look like rawbytes openmyfile rbread enc detectencodingrawbytes line rawbytesdecodeencsplitlines whatever oh lines unicode objects gives problem ask another question,i text file contains entry like useridproductidscore i wrote program read sorry indendetion bit messed def generatesyntheticdatafilename datadict rowdict innerdict try key range count myfile openfilename c del innerdictleninnerdict line myfile c line strline n lenline print n n n c print c entries read far words linereplace words linereplace words wordsstripsplit print userid words userid int words get error movieid int words rating float words print userid userid productid movieid rating rating print words words wordsreplace innerdict datadictsetdefaultuserid innerdictmovieid rating datadictuserid innerdict innerdict except ioerror errnostrerror print io error formaterrnostrerror finally myfileclose print total ratings read filefilename c return datadict but get error valueerror invalid literal int base funny thing working fine reading format data file actually posting question i noticed something weird the entry number spacein like space space space space space space but text file looks fine copy pasting shows nature anyways clue whats going thanks,2 read httpsdocsdjangoprojectcomendevtopicstesting django testing as i know better use unittest doctest shipped django several improvements djangospecific testing like form field output testing database features hovewer essential want continue using nose think missed django environment setup djangotestutils import setuptestenvironment setuptestenvironment this lines needed run tests outside managepy test upd yeah previous thought wrong so i digged sources nose nosegae i think check hardenedmoduleshook definition nose version cause trunk nose i found following class hardenedmoduleshookobject def initself moduledict impmoduleimp osmoduleos dummythreadmoduledummythread picklemodulepickle that gives following nosegae plugin begin method executed selfinstallhookdevappserverhardenedmoduleshook called declares mixedhook class creates instance like selfhook hooksysmodules selfpath there hardenedmoduleshookinit called second argument mystic path however nose argument imp module default that makes exception got sf path desc selfimpfindmoduletop none attributeerror str object attribute findmodule so i think might problem nosegae,i trying get started using nosegae however i run issue i seem get pass even simplest cases using django running without withoutsandbox flag following tests fail def testimportdjango import django def testimportdjangohttp import djangohttp traceback recent call last file cpythonlibsitepackagesnosepyeggnosecasepy line runtest selftestselfarg file cusersuserdesktoptddgaemyprojtestspy line testimportd jango import django file cpythonlibsitepackagesnosegaepyeggnosegaepy line findmodule return superhookmixin selffindmodulefullname path file cprogram files xgooglegoogleappenginegoogleappenginetoolsde vappserverpy line decorate return funcself args kwargs file cprogram files xgooglegoogleappenginegoogleappenginetoolsde vappserverpy line findmodule searchpath file cprogram files xgooglegoogleappenginegoogleappenginetoolsde vappserverpy line decorate return funcself args kwargs file cprogram files xgooglegoogleappenginegoogleappenginetoolsde vappserverpy line findmodulerestricted result selffindpathhooksubmodule submodulefullname pathentry file cprogram files xgooglegoogleappenginegoogleappenginetoolsde vappserverpy line findpathhook return selfimpfindmodulesubmodule pathentry howevere i use withoutsandbox least first test passes myprojteststestimportdjango ok myprojteststestimportdjangohttp error error myprojteststestimportdjangohttp traceback recent call last file cpythonlibsitepackagesnosepyeggnosecasepy line runtest selftestselfarg file cusersuserdesktoptddgaemyprojtestspy line testimportd jangohttp import djangohttp file cprogram files xgooglegoogleappenginelibdjangodjangohtt pinitpy line module modpythonutil import parseqsl file cpythonlibsitepackagesnosegaepyeggnosegaepy line findmodule modpath selffindmodpathfullname file cpythonlibsitepackagesnosegaepyeggnosegaepy line findmodpath sf path desc selfimpfindmoduletop none attributeerror str object attribute findmodule has anyone encountered know i go past edit it seems issue recursive imports def testimportpdb import pdb pdbsettrace part stack trace file cpythonlibpdbpy line init import readline notice import init djangohttp also part stack trace,1 your approach problem unconventional but ignoring issue simply code given qputqueuedcall twitter q twittergetstatus opcomplete clearly possible following workflow occur a thread constructed started queuedcallinit it put queue q however queue completes logic inserting item independent thread already finished work attempted call qtaskdone which causes error taskdone called object safely put queue how done you insert threads queues queues hold data threads process so instead create queue insert jobs want done eg functions args want callback you create start worker threads a worker thread calls qget get function invoke invokes calls qtaskdone let queue know item handled,my apologies longish post front hopefully give enough context solution i tried create utility function take number old classmethod stick multithreaded queue class queuedcallthreadingthread def initself name queue fn args cb threadingthreadinitself selfname name selfcb cb selffn fn selfqueue queue selfargs args selfdaemon true selfstart def runself r selffnselfargs selfargs none else selffn selfcb none selfcbselfname r selfqueuetaskdone here calling code looks like within class data def opcompletename r dataname r q queuequeue socketsetdefaulttimeout qputqueuedcall twitter q twittergetstatus opcomplete qputqueuedcall soanswers q stackexchangegetanswers apistackoverflowcom opcomplete qputqueuedcall souser q stackexchangegetuserinfo apistackoverflowcom opcomplete qputqueuedcall panswers q stackexchangegetanswers apiprogrammersstackexchangecom opcomplete qputqueuedcall puser q stackexchangegetuserinfo apiprogrammersstackexchangecom opcomplete qputqueuedcall fbimage q facebookgetlatestpicture none opcomplete qjoin return data the problem i running seems work every time fresh server restart fails every second third request error valueerror taskdone called many times this error presents random thread every second third request rather difficult nail exactly problem anyone ideas andor suggestions thanks edit i added print effort debug quick dirty rather logging one print statement print running thread selfname first line run another right calling taskdone print thread done selfname the output successful request running thread twitter running thread soanswers running thread souser running thread panswers thread done twitter thread done souser running thread puser thread done soanswers running thread fbimage thread done panswers thread done puser thread done fbimage the output unsuccessful request running thread twitter running thread soanswers thread done twitter thread done soanswers running thread souser thread done souser running thread panswers thread done panswers exception thread panswers traceback recent call last file usrlibpythonthreadingpy line bootstrapinner selfrun file homedemiansrcwwwprojectsdemianbrechtdemianbrechtdemianbrechthelperspy line run selfqueuetaskdone file usrlibpythonqueuepy line taskdone raise valueerror taskdone called many times valueerror taskdone called many times running thread puser thread done puser running thread fbimage thread done fbimage,3 i may misunderstanding i sure using queue correctly from brief survey docs looks like idea use put method put work queue another thread call get get work work call taskdone finished what code appears put instances queuedcall queue nothing ever get queue queuedcall instances also passed reference queue inserted work know intrinsically get queue call taskdone if reading correct call get method somewhere else i see i believe i understand problem the issue queuedcall instances created put queue act creating one starts work another thread if thread finishes work calls taskdone main thread managed put queuedcall queue get error see i think works run first time accident the gil helps lot likely queuedcall thread actually gain gil begin running immediately the fact actually care queue counter also helps appear work matter queuedcall hit queue yet long empty queuedcall taskdone another element queue time element calls taskdone one hopefully queue marked done and adding sleep also makes new threads wait bit giving main thread time make sure actually queue masks problem well also note far i tell quick fiddling interactive shell queue actually still full end never actually get anything it received number taskdone messages equal number things put join works i think need radically redesign way queuedcall class works use different synchronisation primitive queue a queue designed used queue work worker threads already exist starting thread within constructor object put queue really good fit,my apologies longish post front hopefully give enough context solution i tried create utility function take number old classmethod stick multithreaded queue class queuedcallthreadingthread def initself name queue fn args cb threadingthreadinitself selfname name selfcb cb selffn fn selfqueue queue selfargs args selfdaemon true selfstart def runself r selffnselfargs selfargs none else selffn selfcb none selfcbselfname r selfqueuetaskdone here calling code looks like within class data def opcompletename r dataname r q queuequeue socketsetdefaulttimeout qputqueuedcall twitter q twittergetstatus opcomplete qputqueuedcall soanswers q stackexchangegetanswers apistackoverflowcom opcomplete qputqueuedcall souser q stackexchangegetuserinfo apistackoverflowcom opcomplete qputqueuedcall panswers q stackexchangegetanswers apiprogrammersstackexchangecom opcomplete qputqueuedcall puser q stackexchangegetuserinfo apiprogrammersstackexchangecom opcomplete qputqueuedcall fbimage q facebookgetlatestpicture none opcomplete qjoin return data the problem i running seems work every time fresh server restart fails every second third request error valueerror taskdone called many times this error presents random thread every second third request rather difficult nail exactly problem anyone ideas andor suggestions thanks edit i added print effort debug quick dirty rather logging one print statement print running thread selfname first line run another right calling taskdone print thread done selfname the output successful request running thread twitter running thread soanswers running thread souser running thread panswers thread done twitter thread done souser running thread puser thread done soanswers running thread fbimage thread done panswers thread done puser thread done fbimage the output unsuccessful request running thread twitter running thread soanswers thread done twitter thread done soanswers running thread souser thread done souser running thread panswers thread done panswers exception thread panswers traceback recent call last file usrlibpythonthreadingpy line bootstrapinner selfrun file homedemiansrcwwwprojectsdemianbrechtdemianbrechtdemianbrechthelperspy line run selfqueuetaskdone file usrlibpythonqueuepy line taskdone raise valueerror taskdone called many times valueerror taskdone called many times running thread puser thread done puser running thread fbimage thread done fbimage,1 the best solution kind tasks using uwsgi spooler if want run tasks specific interval use timer decorator let spooler hard work uwsgidecorators import execute thetask every seconds spooler timer target spooler def thetasksignum dothelongtask,i running flask webapp running behind uwsgi processes a part code involves pinging remote resource seeing modified ifmodifiedsince updating local copy resource webserver modified that update also sends email diff i concerned takes long time causing user requests time sending email is python threading library right way tackle spawn thread send email will interfere uwsgi processes thanks help side note i also bit concerned uwsgi processes bumping heads try update resource local copy i wonder threading module lock capabilities right thing look problem well edit to clarify primary concern email task part code execution it takes long time runs returntemplate call therefore holding response user is python threading library right way tackle problem given flaskuwsgi environment,3 you contactfirstname contactlastname django know need,getting error exception value could parse remainder contactlastname contactfirstname contactlastname i trouble displaying list names name link my modelspy code class contactmodelsmodel firstname modelscharfieldfirst name maxlength lastname modelscharfieldlast name maxlength def unicodeself return u selffirstname selflastname my viewspy code djangohttp import httpresponse pkmodels import contact djangotemplate import context loader djangoshortcuts import rendertoresponse def indexrequest contactlist contactobjectsall return rendertoresponse pkindexhtml contactlist contactlist my indexhtml template contactlist ul contact contactlist lia hrefpkl contactid contactfirstname contactlastname ali endfor ul else pno contacts availablep endif,2 that looks like quotedprintable encoding base there module python standard library called quopri able convert text,how i recover text corrupted base encoding eg f danea danã§a i tried python get right,1 if want convert string whitespace chars import resubr r t h e e x w h i w n r e p l c e the text i want replace or want remove single whitespace replace whitespaces one resubr r a b c d ab c d,example t h e e x w h i w n r e p l c e i want result like the text i want replace i tried shell sed echo t h e e x w h i w n r e p l c e sed r sazazsgsed g successfully i know replace python could anybody help,3 just kicks nonregex solution using string operations text t h e e x w h i w n r e p l c e textreplace replace replace the text i want replace per comment i changed null character,example t h e e x w h i w n r e p l c e i want result like the text i want replace i tried shell sed echo t h e e x w h i w n r e p l c e sed r sazazsgsed g successfully i know replace python could anybody help,2 def removeprefixtext prefix return textlenprefix textstartswithprefix else text couldn resist one line requires python,i simple python code searches files string eg pathcpath whereby cpath may vary the current code def findpath ifile lines open ifile readlines line lines linestartswith path return order get line content path what simple way get string text path is simple method without closures reflection esoteric things,3 this parse instance method class method instead try parserparse… possibly emailmessagefromfile emailmessagefromstring,i getting following error calling builtin function parse email python txt parserparserparsefd headersonlyfalse and error got typeerror parse takes least arguments given can anybody tell way solve problem,3 as gmail based api working labels thing adding dest label deleting src label import imaplib obj imaplibimapssl imapgmailcom objlogin username password objselectsrcfoldername typ data objuid store msguid xgmlabels destifoldername typ data objuid store msguid xgmlabels srcfoldername,i want able move email gmail inbox another folder using python i using imaplib figure,2 thanks buddy i tryed code errorso i changed work well class touradminadminmodeladmin def querysetself request qs supertouradmin selfquerysetrequest requestuserissuperuser return qs return qsfilteractionusercoderequestuser adminsiteregistertourtouradmin i put code others may problem,i django model like class tourmodelsmodel namemodelscharfieldmaxlength countmodelssmallintegerfield priceunitcodemodelsforeignkeypriceunit pricemodelscharfieldmaxlength descriptionmodelstextfield actiondatemodelscharfieldmaxlength actionusermodelsforeignkeyuser when user logs admin site i would want user see tour instances created tour instances actionuser equal id loggedin user how i filter changelist based loggedin users,2 i created httpscodedjangoprojectcomwikisplitsettingssettinginheritancewithhierarchy preferred solution allows inheritance common file deployment environment,when install new django application addmodify settingspy module for project i trying make module python subpackage create module application settings initpy basepy adminpy feincmspy the problem i confronted merge settingspy attributes installedapps example tuple values getting values different submodules thanks ok i asked wrong question got right answer though my question get attributes submodules merge django import settings expects everything,1 if try make server independent app instance mind replacing uwsgi gunicorn later i would recommend using celery here first steps httpdocsceleryprojectorgenlatestgettingstartedfirststepswithceleryhtml,i running flask webapp running behind uwsgi processes a part code involves pinging remote resource seeing modified ifmodifiedsince updating local copy resource webserver modified that update also sends email diff i concerned takes long time causing user requests time sending email is python threading library right way tackle spawn thread send email will interfere uwsgi processes thanks help side note i also bit concerned uwsgi processes bumping heads try update resource local copy i wonder threading module lock capabilities right thing look problem well edit to clarify primary concern email task part code execution it takes long time runs returntemplate call therefore holding response user is python threading library right way tackle problem given flaskuwsgi environment,1 can simply copy existing virtual env directory new one update new django,i existing environment virtualenv lot packages old django version what i want duplicate environment i another environment i install newer django version keeping packages already environment,1 for logilabcommoncompat module buried inside egg logilabpylintinstallerpyegg sitepackages folder having logilabcommon egg installed removing pylintinstaller egg got pylint working eclipse i found via ipython like in import logilabcommoncompat in logilabcommoncompat import builtins importerror traceback recent call last cusersriodocumentsmceditpymclevelipython console module importerror cannot import name builtins in logilabcommoncompatfile out cpythonlibsitepackageslogilabpylintinstallerpyegglogilabcommoncompatpyc,maybe someone clue one google logilaborg archives every source i tried determine solution turned empty i trying get pylint running pydev eclipse python windows right i happy simply running pylin i used easyinstall install pylint dependancies that seemed work fine however i try run cpythonscriptspylintbat i get following traceback recent call last file cpythonscriptspylint line module pkgresourcesrunscript pylint pylint file cpythonlibsitepackagespkgresourcespy line runscript selfrequirerequiresrunscriptscriptname ns file cpythonlibsitepackagespkgresourcespy line runscript execfilescriptfilename namespace namespace file cpythonlibsitepackagespylintpyeggegginfoscriptspylint line module pylint import lint file cpythonlibsitepackagespylintpyeggpylintlintpy line module pylintcheckers import utils file cpythonlibsitepackagespylintpyeggpylintcheckersinitpy line module logilabastngutils import astwalker file cpythonlibsitepackageslogilabastngpyegglogilabastnginitpy line module logilabastngnodes import file cpythonlibsitepackageslogilabastngpyegglogilabastngnodespy line module logilabastngnodeclasses import arguments assattr assert assign file cpythonlibsitepackageslogilabastngpyegglogilabastngnodeclassespy line module logilabastngbases import nodeng statement instance inferencecontext file cpythonlibsitepackageslogilabastngpyegglogilabastngbasespy line module logilabcommoncompat import builtins importerror cannot import name builtins i mucked around looked basedpy i clue problem my shell path includes cpythoncpythonscripts does something libto or python compatibility note i installed pylint using easyinstall pylint logilabcommon latest thanks,1 possibly set time or number seconds sleep earlier overshadowing time module but would usually give attributeerror int object attribute sleep i sure there problem import datetime import time you must assigned something else time provided code else would getting typeerror float required calling timesleeptime so post code,i trying import time module able use timesleepsecs functionality the problem i think might fact i also imported datetime might messing import datetime import time code utilizing datetime timesleepseconds the error i getting attributeerror function object attribute time,1 you almost certainly defined variable function called time try renaming,i trying import time module able use timesleepsecs functionality the problem i think might fact i also imported datetime might messing import datetime import time code utilizing datetime timesleepseconds the error i getting attributeerror function object attribute time,3 mpsplt this works fabulously example import os ossystemmpsplt inputfilemp,i mp files want slice samples giving start end time library function does anyone know python library suits,3 the simplestquickest way would use python ossystem call ssh command system httpdocspythonorglibraryoshtmlhighlightsystemossystem eg works ubuntu import os ossystem usrbinssh localhost ls la runs ls la ssh localhost you need provide proper commandline options ssh set ssh keys connect securely without password remote host executing commands check httpwwwgloadedeusshwithkeys google info ssh keys,hi i want know establish ssh connection python jython run script file remotly another machine i sure platform machine want run script please provide sample code well i wont mind going scripting language well,1 you might want take look fabric fabric python library commandline tool streamlining use ssh application deployment systems administration tasks it provides basic suite operations executing local remote shell commands normally via sudo uploadingdownloading files well auxiliary functionality prompting running user input aborting execution,hi i want know establish ssh connection python jython run script file remotly another machine i sure platform machine want run script please provide sample code well i wont mind going scripting language well,1 you try execnet provide api execute arbitrary python code remote machine i use linux machines work windows linux,hi i want know establish ssh connection python jython run script file remotly another machine i sure platform machine want run script please provide sample code well i wont mind going scripting language well,1 as alternative joining directory path filename answers use glob module this also handy directories might contain nonxml files want process import glob infile globglob directoryxml print infile,i wish read incoming xml files specific name eg datetime naming extract values perform particular tasks i step files trouble opening reading what i works import os path directory listing oslistdirpath infile listing print infile but i add following try read files errors saying no file directory file openinfile r thank,2 selenium maybe it allows automate actual browser firefox ie safari using python amongst languages it meant testing websites seems usable scraping well disclaimer never used,does python screen scraping libraries offer javascript support i using pycurl simple html requests java htmlunit complicated requests requiring javascript support ideally i would like able everything python i come across libraries would allow do exist,2 although would classified ocr many box python machine learning libraries may useful ocr especially labelled examples digits take look httpscikitlearnsourceforgenetstableautoexamplesplotdigitsclassificationhtml may need,i following problem a range images assigned numbers soon appear i made several attempts ocr images failed is simpler solution if i take certain position screen coordinates always process pixels function map number manually output function soon specific pixel pattern found i get result how would i python maybe pil best us,1 if actually using python firefox rather server side written python although webserver course running locally i would guess pythonext used pyxpcomext need,so i searching topic quite i unable find whether possible i suspect i need sure what i i building fancy web app uses xml xsl javascript however i need transformation text file convert proper xml file to i use python script what i need i working make easy possible use app gets kind destroyed user execute terminal script anything i need graphical ide python i time learn make one i would love entire app would work within web environment much intuitive user then really easy way would use firefox ide example choosing file transformed launching python script what i require i need compatibility firefox but course system capable install python firefox work well the user would happily install programs long interest app what i know is possible execute external python script if security reasons i imagine way user allow maybe installation plugin maybe httpmozexmozdevorg i looking thanks gerard,1 as workaround create stand alone program using openmp qt frontend program make communicate using tcp socket something familiar dll another option point isolate different modules one module fails know part fails one whole big program hard find one wild pointer,i developing python application uses cextension module i also developed the extension module heavy number crunching makes use openmp i recently adding gui components python application using pyqt however i show window application crashes window fully drawn the window shows shortly i able track problem when i compile numbercrunching cextension without openmp support window shows fine everything works i guess something threading stuff openmp qt has anyone ever made similar observation,1 many thanks brandon craig rhodes tracing detailed post i removed offending line astng code available hg repository logilabastng and i confirm fixes op pb,i running lint follows python pylintlint mtestpy code import mcrypto def f mcryptorsanewpubkeyaspemciphernonesplitn the lint output ends exception attributeerror shutdown module threading usrlibpythonsitepackagesmcryptopylinuxxeggmcryptothreadingpyc ignored this code works fine run actually minimal test case full version work the exception ignored bitten considers failure stops step i tried adding mcryptothreadinginit mcryptothreadingcleanup around definition function fix problem how i prevent problem occurring i using mcrypto pylint python also tried debian lenny x,2 this possible accurately i answered similar question dependency testing python,how one get finds location dynamically imported modules python script python understanding dynamically run time load modules be using import modulename using exec x import either using impfindmodulemodulename imploadmoduleparam param param param knowing i want get dependencies python file this would include getting least i tried dynamically loaded modules loaded either using hard coded string objects returned functionmethod for normal import modulename x import either manual scanning code use modulefinder so i want copy one python script dependencies including custom dynamically loaded modules i,1 the xmletreeelementtreeelement object dict xmletreeelementtree import element obj element aaa objdict attrib tag aaa children the dict dictionary currently defined attributes dir calls dir may overrided,how would instance xmletreecelementtreeelement python python r jun gcc based apple inc build llvm build darwin xmletreecelementtree import element obj element aaa obj element aaa xbde dirobj copy deepcopy reduce append clear extend find findall findtext get getchildren getiterator insert items iter iterfind itertext keys makeelement remove set objtag aaa,1 you nature programming language means cannot predict code executed without actually executing so way telling modules could included this confused userinput consider importsysargv there lot theoretical information first problem normally described halting problem second obviously done,how one get finds location dynamically imported modules python script python understanding dynamically run time load modules be using import modulename using exec x import either using impfindmodulemodulename imploadmoduleparam param param param knowing i want get dependencies python file this would include getting least i tried dynamically loaded modules loaded either using hard coded string objects returned functionmethod for normal import modulename x import either manual scanning code use modulefinder so i want copy one python script dependencies including custom dynamically loaded modules i,2 e yet supported pylint afaik e c c e shoult cc i sure pylint special case parameters allows lack space e e supported afaik e c configure length pylintrc w w w supported afaik it would nice could report wanted features httpwwwlogilaborgprojectpylint,searching answer pylint mailing list brings interesting results pylint known customizable i guess possible the reason i would like pylint check compliance pep pydev much better support pylint pep it easier one tool checks use two i also asked question pylint mailing list httpthreadgmaneorggmanecomppythonlogilab example diagnostic messages pep i get pylint e whitespace e missing whitespace around operator e spaces around keyword parameter equals e expected blank line found e many blank lines e line long characters w trailing whitespace w newline end file w blank line contains whitespace,3 from theoretical perspective never know exactly whatwhere modules imported from practical perspective simply want know modules check modulefile attribute run script python v find files modules loaded this give every module could possibly loaded get modules mostly sane code see also how i find location python module sources,how one get finds location dynamically imported modules python script python understanding dynamically run time load modules be using import modulename using exec x import either using impfindmodulemodulename imploadmoduleparam param param param knowing i want get dependencies python file this would include getting least i tried dynamically loaded modules loaded either using hard coded string objects returned functionmethod for normal import modulename x import either manual scanning code use modulefinder so i want copy one python script dependencies including custom dynamically loaded modules i,1 i think found one possible solution httpsouthaeracodeorgdocscustomfieldshtmlfieldnamepatterns next model put southmodelsinspector import addignoredfields addignoredfieldseavfieldseavdatatypefield addignoredfieldseavfieldseavslugfield works,i starting new django project usually put south installed apps then need kind eav store fields model found app exactly want djangoeav httpsgithubcommvpdevdjangoeav but facing problem south complains know work djangoeav cannot freeze field eavattributeslug field class eavfieldseavslugfield cannot freeze field eavattributedatatype field class eavfieldseavdatatypefield south cannot introspect fields probably custom fields if worked removed models parser often broke things to fix read httpsouthaeracodeorgwikimyfieldsdontwork i reading httpsouthaeracodeorgdocscustomfieldshtml trying solve problem without giving two projects anyone could help thanks,1 no extend append pop modify object inplace without returning anything the list objects mutable objects modified without need recreate one in case l lextend l if change type l assume another object let call class foo would expect return value something like foo foo foomodifyobjecthere modifications won expect something like foo object modified nothing returned method,this i python shell extend i pressed enter nothing came i tried something else l l extend pressed enter nothing came none true does mean i cannot something like extend,3 you always,this i python shell extend i pressed enter nothing came i tried something else l l extend pressed enter nothing came none true does mean i cannot something like extend,1 httpdocspythonorgreferencecompoundstmtshtmlthetrystatement the optional else clause executed control flows end try clause currently control “flows end” except case exception execution return continue break statement,i came across strange behavior python i could find information python help se def dividex print entering divide try return xy except print error else print error finally print exit print divide print divide output entering divide exit entering divide error exit none it seems python go inside else block value returned try however always go finally block i really understand can someone help logic thanks,3 just idea i sure work you could write module contains wrapper builtinimport this wrapper would save reference old import assign function builtinimport following whenever called get current stacktrace work calling function maybe information globals parameter import enough get module calling functions store name module get imported redirect call real import after done call application python magicmodule yourapppy the magic module must store information somewhere retrieve later,how one get finds location dynamically imported modules python script python understanding dynamically run time load modules be using import modulename using exec x import either using impfindmodulemodulename imploadmoduleparam param param param knowing i want get dependencies python file this would include getting least i tried dynamically loaded modules loaded either using hard coded string objects returned functionmethod for normal import modulename x import either manual scanning code use modulefinder so i want copy one python script dependencies including custom dynamically loaded modules i,1 have tried use absolute path syspathappendospathabspathospathdirnametestpath,i sure simple solve i staring long i staring straight past solution any tipshintssuggestionssolutions appreciated i trying add unittests app engine app i using testrunnerpy example httpcodegooglecomappenginedocspythontoolslocalunittestinghtml bottom page this works fine i put unittest file named testlibpy root app myapp however i want move tests separate subdirectory named tests within app now i need import modules app however since working directory unittest file one level deeper sees actual modules app engine app i tried adding initpy tests added following code import os import sys syspathappendospathdirnameosgetcwd i hoped would find current working directory go one level add syspath i would able import utillib unittest file testlibpy however i run testrunnerpy i still get error importerror no module named utillib i trying import module called lib within subdirectory called util within root myapp my directory structure follows testrunnerpy myapp initpy util initpy libpy tests initpy file import mentioned testlibpy i also tried adding import root app testrunner returns error def mainsdkpath testpath syspathappendospathdirnametestpath this line i added testrunner syspathinsert sdkpath import devappserver devappserverfixsyspath suite unittestloadertestloaderdiscovertestpath unittesttexttestrunnerverbosityrunsuite and i calling test following command testrunnerpy sdkgoogleappengine myapptests any suggestions i missing,1 return ends function returns whatever want return so go course finally always executed,i came across strange behavior python i could find information python help se def dividex print entering divide try return xy except print error else print error finally print exit print divide print divide output entering divide exit entering divide error exit none it seems python go inside else block value returned try however always go finally block i really understand can someone help logic thanks,1 the reason behaviour return inside try when exception occurs finally except blocks execute return in opposite case exception occurs else runs except this works expected def dividex print entering divide result try result xy except print error else print error finally print exit return result print divide print divide,i came across strange behavior python i could find information python help se def dividex print entering divide try return xy except print error else print error finally print exit print divide print divide output entering divide exit entering divide error exit none it seems python go inside else block value returned try however always go finally block i really understand can someone help logic thanks,3 the else block executed left function got chance however finally block always executed unless yank power cord something like consider thought experiment please real code def whoops try return true finally return false see returns whoops false if find confusing alone some languages like c actively prevent placing return statement finally clause,i came across strange behavior python i could find information python help se def dividex print entering divide try return xy except print error else print error finally print exit print divide print divide output entering divide exit entering divide error exit none it seems python go inside else block value returned try however always go finally block i really understand can someone help logic thanks,3 the description part fasta standard you use regex parse import desc fbgn typegene locscaffoldcomplement fields dictrefindallr w desc fields type gene fields length,i fasta file first sequence mentioned long description i need pick specific description fields used following code whole description get string bio import seqio record seqioparsegenetempfasta fasta idrecordid descrecorddescription print desc is easy way get description fields using biopython libraries array picking specific fields without taking description string spiting string code output python r sep gcc red hat localhostlocaldomain standard fbgn typegene locscaffoldcomplement idfbgn namedvirgj dbxrefflybaseannotationidsgjflybasefbgngleanrdvirgleanrentrezgenegbproteinedwflyminefbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgn mdbedaecaffdb length releaser speciesdvir locscaffoldcomplement one sequences fasta file fbgn typegene locscaffoldcomplement idfbgn namedvirgj dbxrefflybaseannotationidsgjflybasefbgngleanrdvirgleanrentrezgenegbproteinedwflyminefbgnorthodbarthropodsnvorthodbarthropodslhorthodbarthropodsiscworthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodsfbgnorthodbarthropodscpijorthodbarthropodsgborthodbarthropodsagaporthodbarthropodsaaelorthodbarthropodspborthodbarthropodsphumorthodbarthropodsglean mdcbecaccecdf length releaser speciesdvir atgcgtctgcgacgccgctggcatcggcggatgcggcgtacaattgagaa aatctatcgccttaaaatgcaatcgcgccgcaagttggtttacttagccg tatttggagcactatgcgtaatattctggctggctggacagcagttgctg acgacttcgaatggtcactacagtagctactacggcgaaacgcattgtgc gcccattgatgccgtatacacctgggtaaatggttcggatccggatttta ttgagtccattagacgctacgatgccagctacgatccgtcgcgcttcgac,3 i think noop string asdf print pack a string n would give asdf since means take many possible never reason pad imho throw away whole line re update the pack function still serves purpose except maybe implicitely converting nonstring arguments strings here would python i took liberty change order parameters i use parameter packing like string packing import hmac hashlib def getsignkey data msg joinstritem item data h hmacnewkey msg hashlibsha return hhexdigestupper php print getsign foo httpexamplecom fooexamplecom blah fafadcfdbcdbcfedcccbcafdfb python in getsign blah foo httpexamplecom fooexamplecom out fafadcfdbcdbcfedcccbcafdfb,i need convert php function python i even know space padded binary string pack a string python structpack probably used i end can somebody help explain behaviour thanks update this whole code i need implement python until i never heard pack i trying understand exactly i python function getsignpid id desc price url email pwd bhash pack a pid id desc price url email bpwd pack a pwd sign strtoupperhashhmac sha bhash bpwd false return sign,1 the assert trick seem work pydev still supposed however another trick i tried work following class fooobject def initself bar selfbar bar tricking pydev selfbar selfbar bar raise exceptionbar null in cases looks pretty hacky i would love cleaner way things documentation annotation whatever,is way help pydev code completion telling type variable with pdt use phpdoclike syntax purpose var myvar myclass myvar myfunction pdt able figure myvar myclass object but till i cannot figure python,2 import numpy np nparray numneighbor index rangelena left aindexnumneighbor right aindexnumneighborindex printindexleftright yields array dtypeint array array array array array array array array array array array array array array array array array array array dtypeint the reason aindexnumneighborindex work indexnumneighbor slicing rules given sij if j negative index relative end string lens lens j substituted the slice j defined sequence items index k k j if j greater lens use lens if omitted none use if j omitted none use lens if greater equal j slice empty so index aindexnumneighborindex,i want get neighbors certain element numpy array lets consider following example numpyarray so i want specify position want get three neighbors sides it done index numneighbor left aindexnumneighborindex right anumneighbornumneighborindex the code take care boundaries i want get neighbours within boundaries array for consider following example index left neighbor one element thanks lot,2 left amaxindexnumneighborindex,i want get neighbors certain element numpy array lets consider following example numpyarray so i want specify position want get three neighbors sides it done index numneighbor left aindexnumneighborindex right anumneighbornumneighborindex the code take care boundaries i want get neighbours within boundaries array for consider following example index left neighbor one element thanks lot,3 var myarray b c alertmyarrayindexof b alertmyarrayindexof dd element found receive,if i list python i check whether given value using operator mylist b c mylist true mylist false if i array javascript eg var myarray b c can i check whether value similar way python’s operator i need loop array,3 import numpy np import itertools adict b c bdict c printlistitertoolschainfromiterable itertoolsproductvalue bdictkey keyvalue adictiteritems key bdict,i two hash tables form dictionaries the keys map features list occurrences said features adict b c bdict c what i need list ideally numpy array contains combinations occurrences two matching features so case result since point supposed run fast possible large dicts i hoping use comprehensions since understood cython but gotten itertoolsproductvalue adictkey keyvalue bdictitems itertoolsproduct object xa itertoolsproduct object xab thanks help,2 both options perfectly fine note writing singlethreaded program way easier unless tight performance requirements timing constraints forgo threads favor faster development less bugs,i working program logs memory usage server the server multiple instances running program logging i trying figure would optimal options assuming two instances single thread program handles instance one one time delay seconds double thread handling one instance time delay second any suggestions,1 i thinking leave parent process parsing file containing directories use child processes fetch files a directory name the parent parses list provides directory name child right the child reads files inside directory since parent would need obtain data create childs would blocking architecture parent read file call childs um the child read files inside directory up says child read files it silly parent read lot data push children i like send one childs list containing directories results well this different now want parent read directory name read batch file names send file names child okay that less silly reading data now names so parent continues parsing file childs work time find keyword okay but totally missing opportunity parallel processing read multprocessing module carefully what want two queues two kinds workers your application build two queues it build source process pool get batch worker processes pool get files worker processes source this process basically function reads original file containing directories and puts directory name get batch queue get batch this pool processes each process function gets entry get batch queue this directory name it reads directory enqueues tuple file names get files queue get files this pool processes each process function gets entry get files queue this tuple files it opens reads files godknowswhat the idea multiprocessing module use pools workers get tasks queue put results another queue these workers run time,i script parses file containing directories file opened read searching keyword since number file growing i like enable multiprocessing reduce amount time requested complete job i thinking leave parent process parsing file containing directories use child processes fetch files since parent would need obtain data create childs would blocking architecture parent read file call childs i like send one childs list containing directories results so parent continues parsing file childs work time find keyword how could i something like if need explanations please ask i tell thanks,2 you cannot pack grid place widgets canvas expect scroll instead must use createwindow method,i really hard time trying achieve decdent gui layout tkinter i aiming layout left get layout right i feel completely lost different layout managers this code far tkinter import class scrolledcanvas def initself master width height labelmaster texttop master framepacksidetop selfcontrolframemaster selfcontrolpacksidebottom fillx padx labelselfcontrol textbottom master framepack selfgrid framemaster bd bgred selfcanvas canvasmaster reliefsunken borderwidth scrollregion c c c c selfvscroll scrollbarmaster commandselfcanvasyview selfcanvasconfigureyscrollcommandselfvscrollset selfgridpackexpandyes fillboth padx pady selfgridrowconfigure weight minsize selfgridcolumnconfigure weight minsize selfcanvasgridpadx inselfgrid pady row column rowspan columnspan sticky news selfvscrollgridpadx inselfgrid pady row column rowspan columnspan sticky news selfoldfill none selfcanvas selffillcanvasselfcanvas def fillcanvasself thecanvas range frame framethecanvas labelframe texttext inner frame ipacksidetop buttonframe textbutton ipacksideleft buttonframe textbutton ipacksideleft framepack return thecanvas name main root tk scroll scrolledcanvasroot rootmainloop for reason scrollregion expands full size making scrollbar actions obsolete this code bases scrollbar example canvas filled rectangles everything scrolls really nice i probably missed something fundamental resizing components seem completely ignore fixed width height i looking help get example work tkinter i know layout technologies i know modules offer scrollable widgets box but unless completely unavoidable i really like stick example cost least nights far,2 the problem v local variable when goes scope ie init finishes executing v getting garbagecollected change v selfv problem goes away why see problem ttk entry widget standard one i know i guess one sensitive garbage collector perhaps importing libraries somehow triggers garbage collector sooner regardless even stock widgets would eventually sort problem v always eventually get garbagecollected,the following python code label entry field correctly initialized string junk example but second import line uncommented replace old entry widget new themed widget label entry fields initialized any clue themed widget initialization broken tkinter import tkinterttk import class myapp def initself root v stringvar vsetjunk label labelroot textvariablev labelpack textentry entryroot textvariablev textentrypack root tk roottitlemyapp app myapproot rootmainloop,3 changing process name cannot done plain python pydaemon python you need clevel library like pysetproctitle then simply add following main method try import setproctitle setproctitlesetproctitle myawesomeprogram except pass ignore errors since cosmetic,i using pydaemon httpwwwpythonorgdevpepspep make friendly daemon how i give name default called python i want something meaningful,2 the binary mo files gettext could decompiled using msgunfmt httpwwwgnuorgsoftwaregettextmanualgettexthtmlmsgunfmtinvocation,after djangoadminpy compilemessages my djangopo file became empty all translations gone the compiled djangomo file still i copy djangopo github day old is way decompile djangomo get last added translations,1 your installed python py file marked executable sudo chmod ax usrbinpython fix,cpanel using python verion script need least installed python added usrbinpython line top script point newly installed python getting following error cron job runs binsh homesommeuserpublichtmlxmlfeedcronjobwodpy usrbinpython bad interpreter permission denied permissions error folder cpanel recognising interpreter permission error check permission folder means read write execute problem,1 this work please update question specific error text test call optprogramsomethinglookup search bob,following advice given how call external command python i experimenting using call function call external command however command i need call called correctly like parameters passed this call function passing parameters around eg test call optprogramsomethinglookup search bob the search part must passed command lookup without characters surrounding i tried different permutations call function varying levels quotes spaces lack commas etc the second statement bob must within quotes is clean way example return value test atm error search bob valid command,3 if cumret array use numpysumcumret axis get rowsum numpysumcumret axis generate test whole array then use numpyselect apply conditions if put print row statement beginning loop notice integer rather numpy array that causing error btw need looping perform operation another consideration happens first row what considered previous row edit after reading comments i think want something like import numpy cumret numpyarray b cumret c numpycumprodb axis no looping required need check condition rows zero,i new using numpy class i problems manipulating contents array here code finance equation apply element array row cumret col row sumrow rowcol prevrowcolrowcol else rowcol cumretrowcol rowcol prevrow row see changed contents row cumret print row now i getting error saying array indices used must integer boolean type i get row value also array index array object so correct syntax method i supposed use thank advance the cumret array ndarray floats array i want modify here short snippet output and occurring traceback recent call last file qstkpy line module cumretrowcol rowcol indexerror arrays used indices must integer boolean type,2 import yaml class foldedunicodeunicode pass class literalunicodeunicode pass def foldedunicoderepresenterdumper data return dumperrepresentscalaru tagyamlorgstr data style def literalunicoderepresenterdumper data return dumperrepresentscalaru tagyamlorgstr data style yamladdrepresenterfoldedunicode foldedunicoderepresenter yamladdrepresenterliteralunicode literalunicoderepresenter data literal literalunicode u hjw n n yn n y n n n folded foldedunicode u it removes ordinary curses equipped items heavy permanent curses unaffectedn print yamldumpdata the result folded it removes ordinary curses equipped items heavy permanent curses unaffected literal hjw y y for completeness one also str implementations i going lazy,i like able dump dictionary containing long strings i like block style readability for example foo block literal bar folded block pyyaml supports loading documents style i seem find way dump documents way am i missing something,3 i probably ran behaviour today yes correct assuming related django handles data the django admin makes changes manytomany field separately changing actual object remember mm saved different database table in case i select anything manytomany field admin site would translate clearoperation manytomany relation everything savemethod immediately removed clear same thing stuff i postsave signal handler the solution separate manytomanyfield inline automatically get saved empty modifying object,i experiencing weird problem i hope someone may able shed light i overriding save method model add values manytomanyfield running super my problem i saving django admin values seems get added relationship empty if however i managepy shell works without problem i put two print statements produce exact output regardless i running via django admin via shell class storemodelsmodel holidays modelsmanytomanyfieldstoreholiday blanktrue copyholidaysfrom modelsforeignkey store blanktrue nulltrue def saveself print before save selfholidaysall superstore selfsave selfcopyholidays print after save selfholidaysall def copyholidaysself selfpk selfcopyholidaysfrom selfholidaysclear h selfcopyholidaysfromholidaysall selfholidaysadd h this output print statements before save after save storeholiday mar chuck norris birthday closed does anyone suggestions might causing edit all manual changes mm relationship save seems discarded django saving admin interface is related processes form,1 probably looking next rawinput message messageasdf joinchrordc c bteg notes use rawinput need get string input user ord convert character integer chr vise versa c syntax generator expression it also used list comprehension,want take string character make ordinal value value myinputinputmessage mylist listmyinput convert list order take character character mylist mylistcharacterordmylistcharacter printcharacter the problem ordmylistcharacter thank,2 instead character mylist mylistcharacterordmylistcharacter character list index therefore invalid probably want mylist ordcharacter character mylist or counter,want take string character make ordinal value value myinputinputmessage mylist listmyinput convert list order take character character mylist mylistcharacterordmylistcharacter printcharacter the problem ordmylistcharacter thank,1 three problems first mixing list indices list elements second convert back character i assuming want characters numbers third adding existing value one way rangelenmylist mylisti chrordmylisti another way character enumeratemylist mylisti chrordcharacter,want take string character make ordinal value value myinputinputmessage mylist listmyinput convert list order take character character mylist mylistcharacterordmylistcharacter printcharacter the problem ordmylistcharacter thank,1 assuming bit channels tuple integers rgb thought single number base r g b thus convert arrays rgb single array color values use npbincount produce desired histogram import numpy np def usingbincountrgb rrravelastype int ggravelastype int bbravelastype int outputnpzerosbasebasebasedtype int resultnpbincountrbasegbaseb outputlenresultresult outputoutputreshapebasebasebase return output def usinghistogramddrgb data npvstackrflat gflat bflatastypenpuintt delr delg delb hist edges nphistogramdd data binsbase rangebasebasebase return hist nprandomseed n base r nprandomrandintbase sizennnastypenpuint g nprandomrandintbase sizennnastypenpuint b nprandomrandintbase sizennnastypenpuint name main bhistusingbincountrgb hhistusinghistogramddrgb assert npallclosebhisthhist these timeit results suggest usingbincount faster usinghistogramdd perhaps histogramdd built handling floats bins ranges bincount solely counting integers python mtimeit import test testusingbincounttestrtestgtestb loops best sec per loop python mtimeit import test testusinghistogramddtestrtestgtestb loops best sec per loop,i got xd arrays red green blue channels d rgb image what elegant way numpy create histogram volume input channels the operation would equivalent assume r g b d arrays output d array filled zeros x xdim ydim z zdim output rxyz gxyz bxyz this code slow large images can numpy improve efficiency algorithm,2 osextsep defined importing ospathextsep but right ospathsplitext always uses regardless ospathextsep from ospy ospath import curdir pardir sep pathsep defpath extsep altsep devnull from ntpathpy becomes ospath extsep def getdotpath isinstancepath bytes return b else return instead return extsep comment source def splitextp return genericpathsplitextp getsepp getaltsepp getdotp also genericpathpy def getdotpath isinstancepath bytes return b else return so ospath fact define extension separator twice now probably matter going change anytime soon supported platforms anyway but way violates dry principle,in python ospathsplitext using extension separator instead osextsep,3 from qt documentation qwidgetwindowflags note this function calls setparent changing flags window causing widget hidden you must call show make widget visible so add selfshow selfsetwindowflags fine,i attempting add full screen option qt using pyqt application if user hits f goal maximize window i problems removing window title bar though normally i something like selfsetwindowflagsqtcoreqtcustomizewindowhint init title bar would display expected behavior however i launch qt application wait user press f like def keypresseventself event eventkey qtcoreqtkeyf selfdofullscreencheck def dofullscreencheckself selfmaximizedflg false selfmaximizewindow def maximizewindowself selfsetwindowflagsqtcoreqtcustomizewindowhint screen qtguiqdesktopwidgetscreengeometry selfsetgeometryscreen selfmaximizedflg true having marked line maximizewindow outside init seems make window completely vanish the application still running seen task manager i switch back using alttab task manager how i change window flags fly,1 it looks like oneor two collections duplicate elements so creating sets gives sets less number elements try lensetnatean lensetnwrongpea see,please take look following snippet ipython in lennetean out in lennwrongpea out in lensetintersectionsetnwrongpea setnetean out in lensetnwrongpea setnetean out in lensetnetean setnwrongpea out i going crazy since two lists elements common based intersection answers possible returns shouldn have i forgotten something set theory thanks,3 i recall problem kind turned accessing requestrawpostdata prevented requestpost dict subsequently populated post params what happens remove loggingdebug line,the following code works fine django fails django requestpost empty although form data posted correctly server def commitformrequest loggingdebugstrdatetimedatetimenow commit data requestrawpostdata purchase purchaseobjectsgettransactionidrequestpost transactionid breaks requestpost empty stuff return httpresponsegood mimetypetextplain why work i see error,1 you trying connect foursquare api v but disable as part of the apiv sunset oauth v has been diabled see httpdeveloperfoursquarecom apparently example using outdated,i trying query foursquare api obtain userspecific information venue centric information i successfully able get venue centric data however i clueless user centric information i tried following link however requesttoken url returns nothing it would great someone could point where i possibly going wrong also suggest right approach approach completely wrong edit here modified code snippet language python get a request token consumeroauthconsumerkeynntbsprbcvjmwcdpnweloloqlxaaqwhwlbilx secretrvmpguqcmflxmedjkkmzdzfbnyyvvbkgvxznwnmdvm requesttokenurl httpfoursquarecomoauthrequesttoken client oauthclientconsumer resp content clientrequestrequesttokenurl get requesttoken dicturlparseparseqslcontent print request tokens requesttokenkeys token oauthtokenrequesttoken oauthtoken requesttoken oauthtokensecret create a signed consumer request set api endpoint url httpapifoursquarecomvauthexchange set base oauth parameters along parameters required api call params oauthversion oauthnonce oauthgeneratenonce oauthtimestamp inttimetime fsusername myfoursquare username fspassword myfoursquarepassword oauthtoken requesttoken oauthtoken oauthconsumerkey consumerkey req oauthrequestmethodget urlurl parametersparams sign request signaturemethod oauthsignaturemethodhmacsha reqsignrequestsignaturemethod consumer token make auth request test httpapifoursquarecomvtestjson resp content clientrequesttest get print resp print content prints ok i get following error i run code request tokens traceback recent call last file testingfourpy line module token oauthtokenrequesttoken oauthtoken requesttoken oauthtokensecret keyerror oauthtoken from i make request tokens returned empty idea could happening secondedit this error i get i try print respcontent i know i calling wrong url clearly substituting ouath oauth helping status contentlength expires thu sep utc server nginx connection keepalive pragma nocache cachecontrol nocache private nostore date thu sep gmt contenttype textplain charsetutf as part of the apiv sunset oauth v has been diabled see httpdeveloperfoursquarecom request tokens traceback recent call last file testingfourpy line module token oauthtokenrequesttoken oauthtoken requesttoken oauthtokensecret keyerror oauthtoken thank time,1 you able parse message walk parts using code so answer however first need add contenttype multipartalternative boundarycbsmsmainboundary beginning message preserve full original message i believe code works after adding two lines mimemessageintextfiletxt i ran testpy import os import sys import mimetypes import email msg emailmessagefromfileopensysargv ipart enumeratemsgwalk partgetcontentmaintype multipart continue ext mimetypesguessextensionpartgetcontenttype filename partds ext filenameospathjoin settingsmediaroot filename printfilename openfilename wb fp fpwritepartgetpayloaddecodetrue way testpy mimemessageintextfiletxt received partxml partjpe partksh,i mime message stored textplain file looks like httppastebincomspwwcll the mime message supposed multipart message how i parse python i tried emailmessagefromstring still encoded textplain thus i use email library parse my code looks like f opensettingsmediaroot rawtxt r msg emailmessagefromstringfread part msgwalk partgetcontentmaintype multipart continue ext mimetypesguessextensionpartgetcontenttype filename partds ext fp opensettingsmediaroot filename wb fpwritepartgetpayloaddecodetrue fpclose i would grateful help,1 i think could use corpusbased dependency parser instead grammarbased one nltk provides doing corpusbased dependency parsing even small amount text python ideal performancewise so nltk provide wrapper maltparser corpus based dependency parser you might find question rdf sentences relevant,going nltk book clear generate dependency tree given sentence the relevant section book subchapter dependency grammar gives example figure show parse sentence come relationships maybe i missing something fundamental nlp edit i want something similar stanford parser given sentence i shot elephant sleep return something like nsubjshot i detelephant dobjshot elephant prepshot posssleep pobjin sleep,3 you check see email field changed checking whether validate previous email addresses your clean method would changed def cleanemailself prevent duplicate email addresses email selfchangeddata selfmetamodelallfilter email selfcleaneddata email count raise formsvalidationerror duplicate entry selfcleaneddata email return selfcleaneddata email,i trying validate uniqueness email address datastore the problem allow editupdate entry eg i want change displayname see modelspy i submitting form build using djangoforms datastore entry prefilled i already know key datastore entry formsuserforminstancedbgetdbkeykey after submitting form using post method i get details datastore associate submitted form entry dbgetdbkeyselfrequestget key data formsuserformdataselfrequestpost instanceentry dataisvalid the form validates using following form class formspy django import forms googleappengineextdb import djangoforms import models class userformdjangoformsmodelform class meta model modelsauthorizedusers def cleanemailself prevent duplicate email addresses selfmetamodelallfilter email selfcleaneddata email count raise formsvalidationerror duplicate entry selfcleaneddata email return selfcleaneddata email using following model modelspy class authorizedusersdbmodel base model class storing user permissions email dbstringproperty displayname dbstringproperty any suggestions i missing how i prevent raising validationerror updating entry keep mind i want prevent adding new datastore entry email address thanks advance help,1 the answer highlighter fools reader i compiled code instructions generated highlight needed handle error cases return value related array assignment indeed change code read def foonumpyndarraydouble ndim arr none cdef int cdef double elem xrange elem arri arri elem return add the highlight would last line assignment you speed code using cythonboundscheck import numpy cimport numpy cimport cython cythonboundscheckfalse def foonumpyndarraydouble ndim arr none cdef int cdef double elem xrange elem arri arri elem return,i trying speed python code cython i making use cython option see i improve things my understanding generated html file highlighted lines ones python functions called correct in following trivial function i declared numpy array argument arr using buffer syntax i thought allows indexing operations take place purely c without call python functions however cython version highlights line i set value element arr though one read one elements why happen is efficient way accessing numpy array elements import numpy cimport numpy def foonumpyndarraydouble ndim arr none cdef int cdef double elem xrange elem arri highlighted arri elem highlighted edit also mode buffer argument interact numpy assuming i changed order argument numpyarray default always safe use mode c does actually make difference performance edit delnan comment arri also gets highlighted i split first place see part operation causing issue if i turn bounds checking simplify things makes difference gets highlighted generated c code ctpyx cdef int cdef double elem xrange elem arri arri elem pyxt pyxt pyxt pyxvi pyxt ctpyx cdef double elem xrange elem arri arri elem pyxt pyxvi pyxvelem pyxbufptrstridedddouble pyxbstructarrbuf pyxt pyxbstridearr ctpyx xrange elem arri arri elem pyxt pyxvi pyxbufptrstridedddouble pyxbstructarrbuf pyxt pyxbstridearr pyxvelem,2 disclaimer i author question i eventually used posixipc module create version rawarray i used mainly posixipcsharedmemory calls shmopen hood my implementation shmemrawarray exposes functionality rawarray required two additional parameters tag uniquely identify shared memory region create flag determine created new shared memory segment attach existing one here copy anyone interested httpsgistgithubcom shmemrawarraytypecodeortype sizeorinitializer tag createtrue usage notes the first two args typecodeortype sizeorinitializer work rawarray the shared array accessible process long tag matches the shared memory segment unlinked origin object returned shmemrawarray createtrue deleted creating shared array using tag currently exists raise existentialerror accessing shared array using tag exist one unlinked also raise existentialerror a sscce short self contained compilable example showing action usrbinenv python import ctypes import multiprocessing random import random randint shmemctypes import shmemrawarray class pointctypesstructure fields x ctypescdouble ctypescdouble def workerq get access ctypes array shared parent count tag qget shareddata shmemrawarraypoint count tag false procname multiprocessingcurrentprocessname print procname f f dx dy shareddata name main procs np multiprocessingcpucount queue multiprocessingqueue spawn child processes xrangenp p multiprocessingprocesstargetworker argsqueue procsappendp pstart create unique tag shmem segment tag stackoverflowd multiprocessingcurrentprocesspid random number points random data count randint combineddata pointxrandom yrandom xrangecount create ctypes array shared memory using shmemrawarray able use multiprocssingsharectypesrawarray children already spawned shareddata shmemrawarraypoint combineddata tag give children info needed access ctypes array p procs queueputcount tag print parent f f dx dy shareddata p procs pjoin running results following output mehome shmemtestpy parent process process process process,how i give child processes access data shared memory data available child processes spawned using multiprocessingprocess i aware multiprocessingsharedctypesrawarray i figure give child processes access rawarray created processes already started the data generated parent process amount data known advance if gil i using threading instead make task little simpler using noncpython implementation option looking hood muliprocessingsharedctypes looks like shared ctype objects allocated using mmap ed memory so question really boils can child process access anonymously mapped memory mmap called parent child process spawned that somewhat vein asked question except case caller mmap parent process child process solved i created version rawarray uses shmopen hood the resulting shared ctypes array shared process long identifier tag matches see answer details example,2 in subprocesspy line file descriptor duplicated via osdup for reason i suspect operating system limiting number subprocesses andor number file descriptors available application however i understand osdup raisethrow exception case try find operating system limit stay limit for unixbased systems probably use python resource module though i never used httpdocspythonorglibraryresourcehtml,i python application uses threads follows create tasks queue queue module create threads pass queue object put tasks queue around tasks total each thread takes task runs linux commands using popencommunicate mutexes critical sections queue management thread pool library tested already couple smaller projects reason think sth spoiled everything works fine i couple thousand tasks however i case threads hang gdb shows stuck python subprocesspy execute child line means osfork called gdb gdb pystack optpythoncurrentlibpythonsubprocesspy executechild optpythoncurrentlibpythonsubprocesspy init homeolibsuptoolschelocheckscheckutilsosutilscmdutilspy shcmd homeolibsuptoolschelochecksliblistlibworkerspy workerfunction homeolibsuptoolschelocheckscheckutilspoolsthpoolpy run optpythoncurrentlibpythonthreadingpy bootstrapinner optpythoncurrentlibpythonthreadingpy bootstrap my ulimit shows core file size blocks c unlimited data seg size kbytes unlimited file size blocks f unlimited pending signals max locked memory kbytes l max memory size kbytes unlimited open files n pipe size bytes p posix message queues bytes q stack size kbytes cpu time seconds unlimited max user processes u virtual memory kbytes v unlimited file locks x unlimited top also show anything suspicious least cpus us sy niid wa hi si st mem k total k used k free k buffers swap k total k used k free k cached do ideas threads hang not threads hang finished properly tasks available thank help zbigniew,1 the problem line patternfindallrow f you using statement it requires object enter exit methods but patternfindall returns list tries store exit method find raises error just use f patternfindallrow instead,i tried rewrite csvreading code able run multiple cores python i tried use pool object multiprocessing i adapted working examples already worked another part project i ran error message i found hard decipher troubleshoot what good way troubleshoot thanks the error traceback recent call last file parsernodotsparallelpy line module mgppl csvgraphr file parsernodotsparallelpy line csvgraph nodechunks file libraryframeworkspythonframeworkversionslibpythonmultiprocessingpoolpy line map return selfmapasyncfunc iterable chunksizeget file libraryframeworkspythonframeworkversionslibpythonmultiprocessingpoolpy line get raise selfvalue attributeerror exit the relevant code import csv import time import datetime import operator import itemgetter multiprocessing import pool import itertools def chunksln divide list nodes l n chunks lc iterl x tupleitertoolsislicelcn x return yield x def csvnodesr strptime timestrptime mktime timemktime l ppl set pattern recompilerazazn row r patternfindallrow f cell intf id intf st mktimestrptimef dmy ed mktimestrptimef dmy collect list lappendidcellst ed collect separate sets ppladdid return lppl def csvgraphsource mgnxmultigraph remember i use integers edge attributes save space dic start end p pool nodedivisor lenppool nodechunks listchunkssourceintlensourceintnodedivisor numchunks lennodechunks pedgelists pmapcsvnodes nodechunks ppl set l pedgelists llappendl pplupdatel mgaddedgesfromll return mgppl open userslaszlosandordropboxpeersprisonspythoncodetenustesttxt r source r sourcereadlines mgppl csvgraphr,3 sounds like need update syspath point wherever nltk lives check importing external module ironpython,i using visual studio i ironpython console project c console project this ironpython script works fine i run import nltk def simple baconipsumfile open baconipsumtxt r baconipsumcorpus baconipsumfileread tokens nltkwordtokenizebaconipsumcorpus text nltktexttokens print text here c console program work fine using ironpythonhosting namespace ironnltkcsharpconsole class program static void mainstring args var ipy pythoncreateruntime dynamic test ipyusefilecpathtoprogrampy testsimple i get importexception no module named nltk what i missing,2 i lost plot the answer simply c b c npsumcaxis c npsumcaxis one line c npsumnpsumabaxisaxis,how i calculate product without loop i think i need use numpytensordot i seem set correctly here loop version import numpy np nprandomrand b nprandomrand c npzerosashape rangecshape j rangecshape cij npsumaij bij the result numpy array c shape,2 create multiple handlers one output file infolog debuglog etc add filter handler allows specific level for example import logging set loggers handlers class levelfilterloggingfilter def initself level selflevel level def filterself record return recordlevelno selflevel debuglogfilehandleraddfilterlevelfilterloggingdebug infologfilehandleraddfilterlevelfilterlogginginfo,i looked tutorials python logging class didnt see anything would let make multiple logs different levels output in end i would like three logs timestampdebuglog debug level timestampinfolog info level timestamperrorlog error level is way one script generate multiple log files input update so implementing robert suggestion i small issue probably due fully understanding done code here code scriptrunpy import os import logging logger logginggetloggerexceptionslogger debuglogfilehandler loggingfilehandlerdebuglog errorlogfilehandler loggingfilehandlererrorlog formatter loggingformatter asctimes levelnames messages errorlogfilehandlersetformatterformatter debuglogfilehandlersetformatterformatter loggeraddhandlerdebuglogfilehandler loggeraddhandlererrorlogfilehandler class levelfilterloggingfilter def initself level selflevel level def filterself record return recordlevelno selflevel debuglogfilehandleraddfilterlevelfilterloggingdebug errorlogfilehandleraddfilterlevelfilterloggingerror directory dirpath dirnames filenames oswalkpathtoscripts filename f f filenames fendswithpy directoryappendospathjoindirpath filename entry directory execfileentry lists x lists loggererrorlists lists elif lists loggerdebuglists lists example running import sys def scripttest print def scriptttest mundohungry global x x thetests test test test thetests try test xappendtestname ok except error strsysexcinfo xappendtestnameerror now issue running scriptrunpy throw errors run errorlog debuglog created errorlog populated entries idea update so i realized nothing logged lower warning even remove filters debuglogfilehandlersetlevelloggingdebug seem matter if i set actual log command loggerwarning higher print logs of course i uncomment debuglogfilehandleraddfilterlevelfilterloggingdebug i get log activity debuglog im tempted make log level seems like really bad idea case anyoneanything else uses code final update well i stupid forgot set logger log debug level events since default logging class log anything warning wasnt logging debug information i send final thanks shoutout robert filter,3 on side things interested multithreading python mfc if python consider multiprocess python gil issue httpwwwdabeazcompythonunderstandinggilpdf httpwikipythonorgmoinglobalinterpreterlock if windows i help little bit memory if tell help better edit if mfc question might want add tag,currently i accessing mfc c dll using python script everything works well far my next step continuously access dll carry various operations simultaneously i feel multithreading good option could guys suggest good links learn multithreading implement application thanks advance,1 running following command setuppy correct issue python setuppy register ideally would want run register command alongside upload i usually use minimum three commands releasing package sdist register upload the following make typical release pypi python setuppy sdist register upload the rest post brief explanation commands the sdist command one build commands build source distribution you likely familiar already since uploaded zip file a similar command bdist builds binary distributions the distribution package metadata sent separate built distribute the setuptools upload command upload project builds eg myprojectzip the register command used update metadata information the register command sends pkginfo egginfo pypi format understands,i betaversion package pypi the metainformation eg home page categories etc setuppy appeared project pypi page later i updated project the thing i changed setuppy version number update as always never trust someone says i changed setuptools distutils cargo cult programming i copied another project done sorry but next version project pypi page metainformation i trying work i broke i find pypi rather taxing get right i sure this time i used python fairly fresh install windows previously i used python x i almost certainly used different commandline upload this time seemed need signing pgp installed i recall needing last time where i look see metainformation setuppy file longer uploaded,2 i managed get timeouts working http requests selfrfilesocksettimeout hope helps,in python script i trying run web server server basehttpserverhttpserver requesthandler i request handler class class requesthandlerbasehttpserverbasehttprequesthandler def dogetself doing some stuff now i always wait data catch doget i want implement timeout operation i want web server close lets say seconds i able implement please suggest i implement auto shut operation web server scenario thanks tara singh,1 you might try restructuring code use session sqlalchemyormsessionmaker def transactionself callback session sqlalchemyormscopedsessionsession try result callbacksession except sessionrollback raise else sessioncommit finally sessionclose return result then transaction goes function like def updatetxnpk newvalue def txnsession obj sessionquerymyclassfilterbyidpkone objfield newvalue sessionaddobj return txn transactionupdatetxn abc handling commitrollback logic one place relying function scope scope unit work may reduce complexity application eliminate bugs found yet,i database committing problem sqlalchemy here scenario i list records added table once records added table i need get inserted records id another insert second table i operation single session the code structure given i allowed give code creates session object loop records list inserted sessionaddobj sessioncommit get objid sessionaddobj obj id obj sessioncommit last record data getting committed properly multiple records could one please help correct issue,2 one problems aa bb lists numpyarray you aa nparray bb nparray the second thing i notice get second element subarray need aa aa third vec function return something print the final issue vec function operate integers arrays pass slices function complete arrays the corrected version returns expected output import numpy np aa nparray bb nparray def veca b return b func npvectorizevec print funcbb aa note edits op post make answer seem bit odd,editi sort brush example i clean code well my question i pass subarray numpyvectorized function specifically example i figure use numpyvectorize numpyfrompyfunc vectorize commands takes array argument let think easy example i understand basic example i use numpyvectorize i asking example aa bb and i want vectorize function adds second element subarray aa bb in example i want return array but code like doesnt work def vecbsub asub return bsub asub func npvectorizevec func bb aa similar thing numpyfrompyfunc luck my question i past list subarrays numpyvectorized function let subarray argument function,3 in gae uploading file synonymous writing blobstore need work googleappengineext import blobstore uploadfiles selfgetuploads file blobinfo uploadfiles blobreader blobstoreblobreaderblobinfokey messageattachments blobinfofilenameblobreaderread once done always delete blob blobstoreblobinfogetblobinfokey blobdelete,my attempt emailing form gets error message how i process file post request i need write blobstore email template form methodpost actionformurl nameupload enctypemultipartformdata table bordertrtd colspan div classlabelform div divinput typehidden idlng namelng size maxlength value div div classlabelform div divinput typehidden idlat namelat size maxlength value input typehidden idplace nameplace size maxlength value div tdtd rowspan tdtr field form trtd div classlabelform styledisplay block label trans type problem label div tdtd label select namesubject idsubject option value trans problems ads trans problems ads option option value trans advertising trans advertising option option value trans images trans images option option value trans our rules advertising trans our rules advertising option option value trans technical problems trans technical problems option option value trans other trans other option select div tdtr trtd div classfieldwrapper formnameerrors label foridsubject filter capfirst trans name endfilter labeltdtd div input typetext idname namename value usernickname user currentusernameescape endif user currentuser ifequal twittername none else twittername endifequal endif size maxlength div iderrname styledisplay none span classwarning iderrmsgnamespan div divtdtr divtrtd div classfieldwrapper formemailerrors label foridsender trans email address labeltdtd formemail tdtr divtrtd valigntop div classfieldwrapper formtexterrors label foridmessage trans text labeltdtd formtext tdtr div div trtd tdtd input typefile namefile br trans if problem images upload br input typesubmit valuesubmit tdtrtable code class contactfileuploadhandlerblobstorehandlersblobstoreuploadhandlerto doattachment def postself message mailemailmessagesender adminappspotappidcom subjectselfrequestpostget subject attachments test selfrequestpostget file fileread messagebody ns ns nhttpcom selfrequestpostget name selfrequestpostget email selfrequestpostget text messageto infocom messagesend selfredirect customerservicehtm,1 note this answer modified according larry code previous solution extended fieldsbigintegerfield better extend fieldsautofield i problem solved following code djangodbmodels import fields southmodelsinspector import addintrospectionrules class bigautofieldfieldsautofield def dbtypeself connection mysql connectionclassmodule return bigint autoincrement return superbigautofield selfdbtypeconnection addintrospectionrules myappfieldsbigautofield apparently working fine south migrations,i currently building project involves lot collective intelligence every user visiting web site gets created unique profile data later used calculate best matches users by default django creates int id field handle models primary keys i concerned overflown quickly ie b devices visiting page without prior cookie set how i change represented bigint mysql long inside django i found i could following httpdocsdjangoprojectcomendevrefmodelsfieldsbigintegerfield class myprofilemodelsmodel id bigintegerfieldprimarykeytrue but way make autoincrement like usual id fields additionally i make unsigned i get space fill thanks,3 you check statpassingcompletions empty string you could use player players playerstats playerstatobjectsfilterplayeridplayerpk nstat enumerateplayerstats n statpassingcompletions n passingcompletions something meaningful passingcompletions intstatpassingcompletions elif statpassingcompletions n passingcompletions intstatpassingcompletions else pass case statpassingcompletions empty string statsappendplayerfirstname playerlastname playerteam passingcompletions,i trying convert string int i keep running total would like able output django template def statsrequest stats players playerobjectsall player players playerstats playerstatobjectsfilterplayeridplayerpk nstat enumerateplayerstats n passingcompletions statpassingcompletions else passingcompletions statpassingcompletions statsappendplayerfirstname playerlastname playerteam passingcompletions return rendertoresponse prepsstatshtml stats stats i tried adding int around statpassingcompletions throws error invalid literal int base so i used isdigit method make sure strings digits trying converted like player players playerstats playerstatobjectsfilterplayeridplayerpk nstat enumerateplayerstats n statpassingcompletionsisdigit passingcompletions intstatpassingcompletions else statpassingcompletionsisdigit passingcompletions intstatpassingcompletions statsappendplayerfirstname playerlastname playerteam passingcompletions i get error caught typeerror rendering int object iterable model structure class playerstatmodelsmodel player modelsforeignkeyplayer weeknum modelscharfield maxlength choices sep nd sep th sep th sep rd sep th nov nd nov th nov th nov st nov th dec th dec th blank true nulltrue rushingattempts modelscharfield maxlength verbosename rushing attempts blanktrue rushingyards modelscharfield maxlength verbosename rushing yards blanktrue rushingtouchdowns modelscharfield maxlength verbosename rushing touchdowns blanktrue passingcompletions modelscharfield maxlength verbosename passing completions blanktrue passingattempts modelscharfield maxlength verbosename passing attempts blanktrue passingyards modelscharfield maxlength verbosename passing yards blanktrue passingtouchdowns modelscharfield maxlength verbosename passing touchdowns blanktrue receptions modelscharfield maxlength verbosename receptions blanktrue receivingyards modelscharfield maxlength verbosename receiving yards blanktrue receivingtouchdowns modelscharfield maxlength verbosename receiving touchdowns blanktrue any help would appreciated thanks,1 i sometimes use stupid trick int somestring adding zero front string guaranties least string now sure may extract digits somestring regular expression,i trying convert string int i keep running total would like able output django template def statsrequest stats players playerobjectsall player players playerstats playerstatobjectsfilterplayeridplayerpk nstat enumerateplayerstats n passingcompletions statpassingcompletions else passingcompletions statpassingcompletions statsappendplayerfirstname playerlastname playerteam passingcompletions return rendertoresponse prepsstatshtml stats stats i tried adding int around statpassingcompletions throws error invalid literal int base so i used isdigit method make sure strings digits trying converted like player players playerstats playerstatobjectsfilterplayeridplayerpk nstat enumerateplayerstats n statpassingcompletionsisdigit passingcompletions intstatpassingcompletions else statpassingcompletionsisdigit passingcompletions intstatpassingcompletions statsappendplayerfirstname playerlastname playerteam passingcompletions i get error caught typeerror rendering int object iterable model structure class playerstatmodelsmodel player modelsforeignkeyplayer weeknum modelscharfield maxlength choices sep nd sep th sep th sep rd sep th nov nd nov th nov th nov st nov th dec th dec th blank true nulltrue rushingattempts modelscharfield maxlength verbosename rushing attempts blanktrue rushingyards modelscharfield maxlength verbosename rushing yards blanktrue rushingtouchdowns modelscharfield maxlength verbosename rushing touchdowns blanktrue passingcompletions modelscharfield maxlength verbosename passing completions blanktrue passingattempts modelscharfield maxlength verbosename passing attempts blanktrue passingyards modelscharfield maxlength verbosename passing yards blanktrue passingtouchdowns modelscharfield maxlength verbosename passing touchdowns blanktrue receptions modelscharfield maxlength verbosename receptions blanktrue receivingyards modelscharfield maxlength verbosename receiving yards blanktrue receivingtouchdowns modelscharfield maxlength verbosename receiving touchdowns blanktrue any help would appreciated thanks,3 x local script function visible outer scope if put code inside script top level file work,i following script run script sequentially directory import os directory dirpath dirnames filenames oswalkpathtoscripts filename f f filenames fendswithpy directoryappendospathjoindirpath filename entry directory execfileentry print x scripts look like def script x script ran return x script when print x called says x defined i curious way return values parent script access data,1 i curious way return values parent script access data this define functions return values script include function def main various bits script except import return x name main x main print x works used elsewhere script import script print scriptmain that way one script uses another,i following script run script sequentially directory import os directory dirpath dirnames filenames oswalkpathtoscripts filename f f filenames fendswithpy directoryappendospathjoindirpath filename entry directory execfileentry print x scripts look like def script x script ran return x script when print x called says x defined i curious way return values parent script access data,3 you memcacheset inside loop that lot unnecessary traffic memcache service do loop further way coded need establishing size foostab foo foos foostabappendfoo idiomatically foostab foo foo foos that save separate count,hello i want know appengine env things i usefull because i know page slow class foodbmodel id dbstringpropertymultilinetrue name dbstringpropertymultilinetrue date dbdatetimepropertyautonowaddtrue description dbtextproperty carac dbstringpropertymultilinetrue class foospagewebapprequesthandler def getself foos memcachegetallfoos foos none foos fooall size foocount else size lenfoo foostab rangesize foostabinsertifoosi memcachesetallfoos foostab templatevalues foos foos path ospathjoinospathdirnamefile templates fooshtml selfresponseoutwritetemplaterenderpath templatevalues,3 i found code google converts numpy array cvmat c using boostpython link,i looking wrap c class implements algorithm i wrote using opencv i aware python wrappers opencv whole i need wrap code uses opencv this seems logical lower level algorithm fast compiled c code i free call python build system around my class actually quite simple main methods void train stdvectorcvmat void save void load bool detect cvmat this essentially majority i need wrap the problem i know best go i looked ctypes swig boost python pyplusplus i successful date i keep encountering issues wrap opencv object cvmat from python i using numpy arrays i know i need conversion code numpy array cvmat i register i feel like someone else must tried something like one point help much appreciated just reiterate goal wrap c class uses opencv python library i use algorithm python i think i conversion somewhat figured help opencv source i still work python okay i working code linked post conversion numpy cvmat i still encountering problems i going post code hopefully someone knowledgeable i help for example simple class fooh include opencvcorecorehpp class foo public foo foo cvmat image void bar cvmat foocpp include fooh foofoo foofoo void foobar cvmat image cvcanny image image cvimwriteimagepng image and i attempted wrap class using boostpython bits code link wrapfoocpp include boostpythonhpp include numpyarrayobjecth include opencvcorecorehpp include fooh using namespace cv namespace bp boostpython wrapper functions void barfooamp f bpobject np converter functions cvmat convertnumpymatbpobject np wrapper functions void barfooamp f bpobject np mat img convertnumpymatnp fbarimg return boost python class boostpythonmodulelib bpclassfoofoo defbar bar converters cvmat convertnumpymatbpobject np mat numpytomatnpptrm return the numpytomat function panocv library playing around official opencv source i know function also degree the full file function i wrote this code compiles bjam fine i import python crashes the error libfooso undefined symbol zncvmatdeallocateev i tried number different things i get work help appreciated,1 you use locals argument execfile write scripts like def runscript retvalue return retvalue scriptret runscript and main script scriptlocals dict execfilepathtoscript dict scriptlocals printscriptlocalsscriptret,i following script run script sequentially directory import os directory dirpath dirnames filenames oswalkpathtoscripts filename f f filenames fendswithpy directoryappendospathjoindirpath filename entry directory execfileentry print x scripts look like def script x script ran return x script when print x called says x defined i curious way return values parent script access data,2 same problem i tracked cvload cascade i os x opencv python here dump exception type excbadaccess sigsegv exception codes kerninvalidaddress x crashed thread dispatch queue comapplemainthread thread crashed dispatch queue comapplemainthread libopencvobjdetectdylib xb cvrttiimplcvhogdescriptorisinstancevoid const libopencvcoredylib xbf cvtypeof cvso xbae pycvloadobject object object orgpythonpython xbd pyevalevalframeex orgpythonpython xbaf pyevalevalcodeex orgpythonpython xbc pyevalevalcode orgpythonpython xdeae pyrunfileexflags orgpythonpython xded pyrunsimplefileexflags orgpythonpython xeec pymain orgpythonpython xf x i hunted around found httpscoderosorgtracopencvticket seems indicate due opencv able find file so double check datahaarcascadeshaarcascadefrontalfacealtxml exists relative executing,i recently installed opencv v ubuntu machine using instructions given httpwwwsamontabcomwebinstallingopencvinubuntu im able run sample c programs sample python programs but running python facedetectpy imgjpg giving segmentation fault what could causing problem fix below code facedetectpy usrbinpython this program demonstration face object detection using haarlike features the program finds faces camera image video stream displays red box around original c implementation python implementation roman stanchak james bowman import sys import cv optparse import optionparser parameters haar detection from api the default parameters scalefactor minneighbors flags tuned accurate yet slow object detection for faster operation real video images settings scalefactor minneighbors flagscvhaardocannypruning minsizeminimum possible face size minsize imagescale haarscale minneighbors haarflags def detectanddrawimg cascade allocate temporary images gray cvcreateimageimgwidthimgheight smallimg cvcreateimagecvroundimgwidth imagescale cvround imgheight imagescale convert color input image grayscale cvcvtcolorimg gray cvcvbgrgray scale input image faster processing cvresizegray smallimg cvcvinterlinear cvequalizehistsmallimg smallimg ifcascade cvgettickcount faces cvhaardetectobjectssmallimg cascade cvcreatememstorage haarscale minneighbors haarflags minsize cvgettickcount print detection time gms tcvgettickfrequency faces x w h n faces input cvhaardetectobjects resized scale bounding box face convert two cvpoints pt intx imagescale inty imagescale pt intx w imagescale inty h imagescale cvrectangleimg pt pt cvrgb cvshowimageresult img name main parser optionparserusage usage prog options filenamecameraindex parseraddoptionc cascade actionstore destcascade typestr helphaar cascade file default default default datahaarcascadeshaarcascadefrontalfacealtxml options args parserparseargs cascade cvloadoptionscascade lenargs parserprinthelp sysexit inputname args inputnameisdigit capture cvcreatecameracaptureintinputname else capture none cvnamedwindowresult capture framecopy none true frame cvqueryframecapture frame cvwaitkey break framecopy framecopy cvcreateimageframewidthframeheight cvipldepthu framenchannels frameorigin cviplorigintl cvcopyframe framecopy else cvflipframe framecopy detectanddrawframecopy cascade cvwaitkey break else image cvloadimageinputname detectanddrawimage cascade cvwaitkey cvdestroywindowresult please help thank you,1 this may satisfying solution using case expression instead order fields sqlalchemyormqueryalphabettable filteralphabettableletteringack orderbysqlalchemysqlexpressioncasealphabettableletter g alphabettableletter alphabettableletter c alphabettableletter k,i trying sort sqlalchemy orm object field specific order values neither ascending descending if i query mysql would look like select letter from alphabettable where letter g c k order by fields letter g c k output letter g c k for sqlalchemy i trying things along lines sessionqueryalphabettablefilteralphabettableletterin g c k orderbyalphabettableletterin g c k which work ideas it small onetime constant list i could create table order join seems like bit much,3 most likely python executable path given child process try changing command line include full path python executable process p rexeccmd c cpathtopython pythontestpy,i trying run python script java i troubles i using command bellow execute python script inside folder called python java project runtime r runtimegetruntime process p rexeccmd c python pythontestpy the script write something text file screen execution throught rexec work nothing recorded neither written screen pwaitfor returns meaning work properly works terminal though i tried place python script root folder project see error could caused path mistake i success either how i get work my so windows python script testpy i trying run import sys import os def main f open pythontesttxt w fwrite it works fflush fclose print it works name main main,3 the problem one uses in operator must parentheses apsec cursorexecute select remediationticket from remediation where issuekey in sqlitecursor object x cursorexecute select remediationticket from remediation where issuekey in tfetchall u show check in multiple values apsec apsec cursorexecute select remediationticket from remediation where issuekey in lent sqlitecursor object x cursorexecute select remediationticket from remediation where issuekey in lent tfetchall u u u u u u u u u my call dbquery modified allow multiple qvalue qvaluetuple incidents qvaluetuple tickets dbqueryqselect remediationticket qtable remediation qwhere issuekey qwhereoperator in qvalue qvaluetuple also dbquery method must modified following rows cursorexecute select from where qselect qtable qwhere qwhereoperator lenqvalue qvaluefetchall,code print select from where qselect qtable qwhere qwhereoperator qvalue rows cursorexecute select from where qselect qtable qwhere qwhereoperator qvaluefetchall result select ticket from mytable where issuekey in apsec traceback recent call last file codepy line validate tovalidate dbqueryqselect ticket qtable mytable qwhere issuekey qwhereoperator in qvalue incidentquerylist file codepy line dbquery rows cursorexecute select from where qselect qtable qwhere qwhereoperator qvaluefetchall sqliteoperationalerror near syntax error when i perform exact query directly sqlite file firefox sqlite manager i receive proper response without error select ticket from mytable where issuekey in apsec update trying without substitutions still receiving error test cursorexecute select ticket from mytable where issuekey in apsec fetchall traceback recent call last file stdin line module sqliteoperationalerror near syntax error update trying without dbapi’s parameter substitution still error apsec cursorexecute select ticket from mytable where issuekey in traceback recent call last file stdin line module sqliteoperationalerror near syntax error update why in operator referenced tablename cursorexecute select ticket from mytable where issuekey in apsec traceback recent call last file stdin line module sqliteoperationalerror table apsec update fixed strange tablename issue cursorexecute select remediationticket from remediation where issuekey in apsec sqlitecursor object x cursorexecute select remediationticket from remediation where issuekey in apsec fetchall u update cannot write solution yet due less reputation the problem use in operator must parentheses cursorexecute select remediationticket from remediation where issuekey in apsec sqlitecursor object x cursorexecute select remediationticket from remediation where issuekey in apsec fetchall u therefore dbquery method must modified following rows cursorexecute select from where qselect qtable qwhere qwhereoperator qvaluefetchall,2 lxml elementtree quite similar the elementtree portion lxml documentation site fact points elementtree documentation you might try working elementtree tutorials examples bottom overview page since elementtree part python distribution tends widely documented easily googled once grok extend lmlx magic initial found elementtree need for example lxml maintains parent relationships every element elementtree you add parent relationships elementtree easy example start that i learned,first thing first i know many questions regarding python lxml stackoverflow already i read right i looking comprehensive answer question i html conversion i need grammatically parse html content changes href img this simplified version i right openfilename r infile inputs infileread mytree fromstringinputs parse etree html content breadcrumb mytreegetelementbyidbreadcrumb list elements matching id breadcrumbcontent breadcrumbtextcontentstrip text content bread crumb h mytreexpath h another way get elements xpath hcontent htextcontentstrip get text content gettail mytreecssselect tableresults tr td span br get list elements using css select so basically i know moment is ways get elementsattributes using lxml i know may best way bear new whole thing following i want i img srcimagesmacmailgif alt width height br hrefhttpwwwsomeurlcomfaqgeneralfaqhtml targetblankgeneral faqs pagea they nested inside elements like div p whatsoever what i want programatically look elements image i want extract src manipulation set src something else example srcimagessomethingjpg srcsomethingimagesjpg thing href want change make point place other i also want remove elements tree simplify example head titlesomething goes heretitle head div p idsomep some content p div i would want remove head node div would able get p idsomep ways grab parent element also way remove elements case look head remove head look idsomep get parent delete thank update i already found solution already finished coding using lxmletree i post answer soon stackoverflow allows i truly hope answer question would help people deal html parsing,1 if want unblock udp read another thread send datagram rgds martin,this looks like duplicate how i abort socketrecv another thread python since i want abort recvfrom thread udp tcp can solved poll selectselect,3 you aware user model already firstname lastname fields right also misstyped lastname lastfield i would advise extend form provided djangoregistration making new form adds new fields you also save first name last name directly user model get form djangoregistration registrationforms import registrationform class myregistrationformregistrationform firstname modelscharfieldmaxlength labelu first name lastfield modelscharfieldmaxlength labelu last name pincode modelscharfieldmaxlength labelu pincode def saveself args kwargs newuser supermyregistrationform selfsaveargs kwargs put user model instead profile save user newuserfirstname selfcleaneddata firstname newuserlastname selfcleaneddata lastname newusersave get profile fields information gender selfcleaneddata gender pincode selfcleaneddata pincode create new profile user information userprofileuser newuser gender gender pincode pincodesave return user model return newuser,am trying create registration form extending djangoregistration app using django profile i created model form profile i checked django shell generating fields for profile fields using modelform now i struck bring djangoregistration profile fields together following code developed modelpy class userprofilemodelsmodel this class would define extra fields required user registring site this model used django profile application genderchoices m male f female links user model one one relationship user modelsonetoonefielduser other fields thats required registration firstname modelscharfield first name maxlength null false lastfield modelscharfield last name maxlength gender modelscharfield gender maxlength choicesgenderchoices null false dob modelsdatefield date birth null false country modelsonetoonefieldcountry usertype modelsonetoonefieldusertype address modelscharfield street address line maxlength null false address modelscharfield street address line maxlength city modelscharfield city maxlength null false state modelscharfield stateprovince maxlength null false pincode modelscharfield pincode maxlength createdon modelsdatetimefield updatedon modelsdatetimefieldautonowtrue formspy class userregistrationformregistrationform modelform resolves metaclass conflict metaclass classmaker class meta model userprofile fields firstname lastfield gender dob country usertype address address city state pincode now mix djangoregistration app custom app i gone lots sites links figure including djangoregistration amp djangoprofile using custom form sure move forward especially since using modelform instead update th sept i made changes suggested vascop i updated template file viewpy created following code def registerrequest requestmethod post form userregistrationformrequestpost formisvalid userregistrationformsave else form userregistrationform return rendertoresponse registrationregistrationformhtml form form contextinstancerequestcontextrequest after following change form correctly getting rendered problem data getting saved please help update th sept userregistrationformsave changed formsave the updated code viewspy follows def registerrequest requestmethod post form userregistrationformrequestpost formisvalid formsave else form userregistrationform return rendertoresponse registrationregistrationformhtml form form contextinstancerequestcontextrequest even update user getting saved instead i getting error super object attribute save i see save method registrationform class so save data please help,1 so several issues first discovered parentheses part syntax in clause you must include secondly command work fine long qvalue contains single value but in really use multiple commaseparated values simply case might well use instead in if try pass commaseparated list values single parameter qvalue work sqlite treat entire commaseparated list single value match in case must build list commaseparated question marks insert sql string formatting then must create python list values pass list supply one value per question mark,code print select from where qselect qtable qwhere qwhereoperator qvalue rows cursorexecute select from where qselect qtable qwhere qwhereoperator qvaluefetchall result select ticket from mytable where issuekey in apsec traceback recent call last file codepy line validate tovalidate dbqueryqselect ticket qtable mytable qwhere issuekey qwhereoperator in qvalue incidentquerylist file codepy line dbquery rows cursorexecute select from where qselect qtable qwhere qwhereoperator qvaluefetchall sqliteoperationalerror near syntax error when i perform exact query directly sqlite file firefox sqlite manager i receive proper response without error select ticket from mytable where issuekey in apsec update trying without substitutions still receiving error test cursorexecute select ticket from mytable where issuekey in apsec fetchall traceback recent call last file stdin line module sqliteoperationalerror near syntax error update trying without dbapi’s parameter substitution still error apsec cursorexecute select ticket from mytable where issuekey in traceback recent call last file stdin line module sqliteoperationalerror near syntax error update why in operator referenced tablename cursorexecute select ticket from mytable where issuekey in apsec traceback recent call last file stdin line module sqliteoperationalerror table apsec update fixed strange tablename issue cursorexecute select remediationticket from remediation where issuekey in apsec sqlitecursor object x cursorexecute select remediationticket from remediation where issuekey in apsec fetchall u update cannot write solution yet due less reputation the problem use in operator must parentheses cursorexecute select remediationticket from remediation where issuekey in apsec sqlitecursor object x cursorexecute select remediationticket from remediation where issuekey in apsec fetchall u therefore dbquery method must modified following rows cursorexecute select from where qselect qtable qwhere qwhereoperator qvaluefetchall,2 i exact problem today brand new system i tracked cause seems pydev refuses pick messages pylint released july reverting previous version pylint seems solved problem for involved removing everything python libsitepackages directory related pylint running python setuppy install directory i extracted pylint without deleting files sitepackages directory first kept using new version but steps messages started showing pydev expected you check pylint version pylint version shell prompt shows good go,i pylint installed works fine command line set within pydev eclipse pylint triggered ok i edit files outputting eclipse console but pylint warnings appear marks editor margin way compiler warnings errors newlygenerated warnings appear problems view either old ones showing disappear i resave relevant module i know possible i working previously i set ticking unticking redirect pylint output console seem make difference,2 add dictionary context using templaterenderlocalvars use functions note mako fast engine create python module maktemplate file render may try makotemplate import template mytemplate templatefilename docsmytmpltxt moduledirectory tmpmakomodules print mytemplaterender check content py files tmpmakomodules,i using pyramid mako templating it possible define semianonymous function within mako block i know done modulelevel block means function access local scope templating meaning i pass every bit variable i need example template variableinlocalscope blah blah blah def myfunction headername variableinlocalscopeupper return headername foo this throw nameerror saying headername defined the way around code like def myfunctioninputvariable return inputvariableupper myfunctionvariableinlocalscope this works variables function gets quite unweildy i must also reimport helper functions available template modulelevelblock is way around i something completely stupid,2 the formatting makes little tricky since names spaces make csv difficult use one way get around use first column get location width columns interested using regex you try something like import email emails print email lines emailsplit n name researchr names lines rei price researchr offerings lines rei line lines n linenamestartnameendstrip p linepricestartpriceendstrip print n p print this assumes emails list entry email here output cusip name original current cashflow collat offering d gsaa a fcf ac ahm gac spr snr oa gsaa a ahm gac name of cf cpn fico cal walb notes offer csmc a l fltas lxs h a l ss csmc a lxs h a cusip name bid x off size ce wal arm cflw kaa sami ar a x mm poa sspt haq sami ar a x mm poa srmez sami ar a sami ar a,i created text file multiple email messages each three tuples written text file different email message sender cusip name original current cashflow collat offering d gsaa a fcf ac ahm gac spr snr oa name of cf cpn fico cal walb notes offer csmc a l fltas lxs h a l ss cusip name bid x off size ce wal arm cflw kaa sami ar a x mm poa sspt haq sami ar a x mm poa srmez by name i need way pull price info price info data words offering offer off this process replicated whole text file extracted data name price written excel file via xlwt notice format price data varies tuple,2 if python need use rawinput def funcaddnum num rawinputyour city print return num num input causes whatever type evaluated python expression end whateveryoutyped so variable named whateveryoutyped get nameerror with rawinput saves whatever type string end whateveryoutyped points string want,i wrote function python prompts user give two numbers adds it also prompts user enter city prints for reason i run shell i get name defined i enter city def funcaddnum num inputyour city print return num num,2 not problem although program respect amount resources allocated queuing system may considerably less realized i believe lsf oslevel hooks enforce compliance probably in past i seen handled wrapper script one sets program job simultaneously appropriate settings launches,i access linux cluster resources allocated using lsf i think common tool comes scali httpwwwscalicomworkloadmanagementhighperformancecomputing in interactive queue i asked got maximum number cores but i check many cpus python multiprocessing module see number number physical cores node i allocated it looks like multiprocessing module problems respecting bounds lsf shouldwould impose is problem lsf python lsandoriliadaccess peersprisons bsub is n q interact sh job submitted queue interact waiting dispatch starting heroint sh python python r jun gcc linux type help copyright credits license information import multiprocessing multiprocessingcpucount,1 import numpy np a nparray b nparray def ismembera b tf npindab newer versions numpy tf nparrayi b u npuniqueatf index nparraynpwhereb else zipatf return tf index tfixismemberab printtf true false false true true printix printatf printbixtf,i racking brain solution along lines older question i trying find python code pattern replicates indices result for example a b tf ix ismemberab atf ans bixtf ans what allows array c ordered way b i appropriately insert values c new array d ordered way a i mapping data lot i would love work various data types like strings datetimes particular it seems numpy ind get half way i also open pythonic ideas well dtf cixtf thank,3 it basically fetches httpwwwowsneweggcomstoreseggmenus dumps contents string response parses json using jsonloads puts data then iterate contents data build html list using lxml the list look like ul lia hrefstorestoreidstoretitleali ul where storeid storetitle ids titles fetched parsed url references urllib json lxml,i trying port bit python code java httpwwwbemashernetarchives scroll bottom code but everything dynamically typed i difficulty porting i need able use java implementation pythons json right i using gson httpcodegooglecompgooglegson i open anything neither gson fromjson signatures public t t fromjsonstring json classt classoft throws jsonparseexception public t t fromjsonstring json type typeoft throws jsonsyntaxexception match pythons data jsonloadsresponse this json i trying read httpwwwowsneweggcomstoreseggcategories how would i go getting class type json read all examples i seen know thanks,2 def productiterables equivalent itertoolsproduct versions not build intermediate results omitted repeat option product abcd xy ax ay bx by cx cy dx dy niters leniterables lstlenths lstremaining xrangeniters leniterablesi lstlenthsinsert lstremaininginsert lstremaining nproducts lstremainingpop p xrangenproducts lstvals xrangeniters j plstremainingilstlenthsi lstvalsappenditerablesij yield tuplelstvals,i list tuples eg a want generate permutations one item tuple i number tuples tuple number elements and i use itertoolsproduct python,3 since third party libraries option code done python builtin elementtree xmletree import elementtree etree document etreeparseopen yourexamplexmlrdf root documentgetroot nspurl httppurlorgrss nsrdf httpwwwworgrdfsyntaxns item rootfindall sitem nspurl print itemattribget sabout nsrdf print itemfind sdescription nspurltext print,given following data rdfrdf xmlnshttppurlorgrss xmlnsrdfhttpwwwworgrdfsyntaxns xmlnsslashhttppurlorgrssmodulesslash xmlnsdchttppurlorgdcelements channel rdfabouthttpwwwgmanewstv titlegmanewstvtitle description gma newstv bring latest news gma news teams highlights favorite shows subscribe stay uptodate gma newstvdescription linkhttpwwwgmanewstvlink channel item rdfabouthttpwwwgmanewstvstoryworldmagnitudequakehitschileancoastnodamage dcformattexthtmldcformat dcdatetdcdate dcsourcehttpwwwgmanewstvstoryworldmagnitudequakehitschileancoastnodamage dcsource titlecdatamagnitude quake hits chilean coast damagetitle linkhttpwwwgmanewstvstoryworldmagnitudequakehitschileancoastnodamage link descriptioncdatasantiago a magnitude quake hit coast central chile early wednesday state emergency office said reports damagedescription item item rdfabouthttpwwwgmanewstvstorynationhouseminorityblamespnoysadvisersforlegalsetbacks dcformattexthtmldcformat dcdatetdcdate dcsourcehttpwwwgmanewstvstorynationhouseminorityblamespnoysadvisersforlegalsetbacks dcsource titlecdatahouse minority blames pnoy advisers legal setbacks title linkhttpwwwgmanewstvstorynationhouseminorityblamespnoysadvisersforlegalsetbacks link descriptioncdatamembers opposition house representatives wednesday blamed president benigno aquino iii advisers various legal setbacksampquot suffered administration advised consider replacing advisersdescription item item rdfabouthttpwwwgmanewstvstorynationexshariajudgeothersmaytestifyinpollfraudprobe dcformattexthtmldcformat dcdatetdcdate dcsourcehttpwwwgmanewstvstorynationexshariajudgeothersmaytestifyinpollfraudprobe dcsource titlecdataexshari judge others may testify poll fraud probetitle linkhttpwwwgmanewstvstorynationexshariajudgeothersmaytestifyinpollfraudprobe link descriptioncdatathe former shari court judge claimed helped gloria macapagalarroyo cheat presidential elections least others may serve witnesses joint investigation commission elections department justice alleged poll fraud comelec chief sixto brillantes jr said wednesdaydescription item rdfrdf now i want get details elements inside item tag this trivial i new python i quite sure i going parse rdf extract item inside edit i use third partie libraries script going run embeded system,1 convert bytes littleendian byte ordering applies data types greater byte so convert list bytes littleendian you need understand list bytes a bit integer bytes if bytes data you could unpack bit integers if data ascii text endianness matter read exact ascii text file bigendian littleendian machines here example demonstrating structpack structunpack usrbinenv python import struct bit unsigned integer base base xaabbccdd u xaabbccdd print u u xx u big endian xaa xbb xcc xdd ube structpack i u bx byte byte structunpack b ube print big endian packed xx x x bx assert bx xaa xbb xcc xdd little endian xdd xcc xbb xaa ule structpack i u lx byte byte structunpack b ule print little endian packed xx x x lx assert lx xdd xcc xbb xaa bit unsigned integer base base xaabbccddeeff u xaabbccddeeffl print u u xx u big endian xaa xbb xcc xdd xee xff x x ube structpack q u bx byte byte structunpack b ube print big endian packed xx x x bx assert bx xaa xbb xcc xdd xee xff x x little endian x x xff xee xdd xcc xbb xaa ule structpack q u lx byte byte structunpack b ule print little endian packed xx x x lx assert lx x x xff xee xdd xcc xbb xaa check documentation info httpdocspythonorglibrarystructhtmlformatstrings,i base encoded data experiment so i trying stepwise retrieve bytes base encoding decode convert bytes littleendian decompress bytes zlib convert byte array float array example dnlqnpkoyxqjekdrbrufksczbenxezrfaothmzeoqrcrfcqkryeunewxjjrofbsuscveevdtvrkpvtluwnelrhxzksbbwpefvyrifdeeskohhenidrinfusyybeccrgkqgrcrreuerouahutbwoderkymrnsvkkrvupjeukwurolksqrzevaurpbtweqfcvebnkra what i tried far import os import base import struct decodebasedecodestring dnlqnpkoyxqjekdrbrufksczbenxezrfaothmzeoqrcrfcqkryeunewxjjrofbsuscveevdtvrkpvtluwnelrhxzksbbwpefvyrifdeeskohhenidrinfusyybeccrgkqgrcrreuerouahutbwoderkymrnsvkkrvupjeukwurolksqrzevaurpbtweqfcvebnkra tmpsizelendecode now i trying convert byte little endian i want following operation python though i trying figure taking much time thanks,1 i know backendagnostic way definitely possible common backends eg wx tkagg etc import matplotlib matplotlibusewx pylab import figure plot thismanager getcurrentfigmanager thismanagerwindowsetposition show per tim comment section might wanna switch thismanagerwindowwmgeometry instead for tkagg change thismanagerwindowwmgeometry so i think exhaust backends capable imposing certain one option,i writing simple python application uses matplotlib display figures screen the number figures generated based user input changes throughout application life the user ability issue plot command generate new figure window selected data series in order improve user experience i would like provide another command would programmatically arrange open figure windows convenient arrangement eg tile across available screen space i believe found apis allow adjust size figure window pixels success finding way set absolute position screen is way without delving details whatever backend use i would like backendagnostic way i avoid relying upon implementation details might change future,3 in init set selfstore in addtoback selfstoreselfendindex value if first operation circular array pass value turns the problem obvious empty list index indexes you need add item list different way i going tell exactly part homework figure,i project create circular array class language i using python i new classes python reading webpages chapters books i think i understanding work however i need help i figured i would come wonderful teachers so our class must able implement several operations insert front insert back insert index remove front remove back remove index i started coding running problems i sure syntax even right here i far class circular def initself selfstore selfcapacity lenselfstore selfsize selfstartindex selfendindex def decrementindexself index index index selfstore selfstore selfcapacity def incrementindexself index index index selfcapacity index index selfcapacity def addtobackself value selfstoreselfendindex value selfendindex incrementindexselfendindex selfsize def addtofrontself value selfsize addtobackself value else selfstartindex decrementindexselfstartindex selfstoreselfstartindex value selfsize i stopped start testing functions primarily addtofront addtoback upon testing idle using c circular caddtoback i get index errorand i sure that problem i gotten stuck need help moving forward i posting i need help want learn i lazy tried researching problem thanks already so,1 you recreate virtual environment ubuntu the virtual env python binary different different system,i recently made django project using virtualenv mac that mac broke i saved files i want work project using linux computer i difficulty running virtual environment ubuntu does even make sense try use virtual env made mac os ubuntu thanks,1 it appears data actually compressed read data floats either loop using structunpackfrom one big structure using structunpack import base import struct encoded dnlqnp bnkra decode string data basestandardbdecodeencoded ensure enough data bit floats assert lendata determine many floats count lendata unpack data floats result structunpack f formatcount one big structure count floats data results returned tuple if data compressed decompress import zlib decompressed zlibdecompressdata,i base encoded data experiment so i trying stepwise retrieve bytes base encoding decode convert bytes littleendian decompress bytes zlib convert byte array float array example dnlqnpkoyxqjekdrbrufksczbenxezrfaothmzeoqrcrfcqkryeunewxjjrofbsuscveevdtvrkpvtluwnelrhxzksbbwpefvyrifdeeskohhenidrinfusyybeccrgkqgrcrreuerouahutbwoderkymrnsvkkrvupjeukwurolksqrzevaurpbtweqfcvebnkra what i tried far import os import base import struct decodebasedecodestring dnlqnpkoyxqjekdrbrufksczbenxezrfaothmzeoqrcrfcqkryeunewxjjrofbsuscveevdtvrkpvtluwnelrhxzksbbwpefvyrifdeeskohhenidrinfusyybeccrgkqgrcrreuerouahutbwoderkymrnsvkkrvupjeukwurolksqrzevaurpbtweqfcvebnkra tmpsizelendecode now i trying convert byte little endian i want following operation python though i trying figure taking much time thanks,2 there good chance need issue two commits one main reasons using sqlalchemy sessions understands objects interrelate order inserts way data gets properly inserted correctly represents desired structure this works principally relationship construct here simple example sqlalchemy import sqlalchemyorm import sqlalchemyextdeclarative import declarativebase base declarativebase class abase tablename atable id columninteger primarykeytrue class bbase tablename btable id columninteger primarykeytrue aid columninteger foreignkeyaid relationshipa mya a myb b myba mya the important part declaring relationship a b ba to take best advantage important express relationship instances relationship property let sqlalchemy take care setting aid column engine createenginesqlitememory basemetadatacreateallengine engineecho true session sessionmakerengine session session sessionaddmya sessionaddmyb sessioncommit with echotrue output looks bit like info sqlalchemyenginebaseenginexed begin implicit info sqlalchemyenginebaseenginexed insert into atable default values info sqlalchemyenginebaseenginexed info sqlalchemyenginebaseenginexed insert into btable aid values info sqlalchemyenginebaseenginexed info sqlalchemyenginebaseenginexed commit notice mya object inserted sqlalchemy reads assigned primary key uses insert myb,i database committing problem sqlalchemy here scenario i list records added table once records added table i need get inserted records id another insert second table i operation single session the code structure given i allowed give code creates session object loop records list inserted sessionaddobj sessioncommit get objid sessionaddobj obj id obj sessioncommit last record data getting committed properly multiple records could one please help correct issue,3 have tried lxml lxmlhtml import builder e lxmlhtml import usedoctest html ehtml ehead elinkrelstylesheet hrefgreatcss typetextcss etitlebest page ever ebody eheclassheading top news epworld news page stylefontsize ah text way lxmlhtmlfromstringp parsed fragment p print lxmlhtmltostringhtml outputs html head link hrefgreatcss relstylesheet typetextcss titlebest page evertitle head body h classheadingtop newsh p stylefontsize world news pagep ah text way p parsed fragment p body html,i seen people ask question but looking specific i need module works python html new like html potentially css going extract info text file database write html file what think best task i new python dont time play around different modules need get best one xd i looked markuppy htmltags think thank much i forgot could also show install module without root access requires one tt,1 i know answer trying helpful the bh code r padjust bh lpl lp number pvalues orderp decreasing true reverse sort pvalues ro ordero pmin cumminni poro n also number pvalues,i list pvalues i would like calculate adjust pvalues multiple comparisons fdr in r i use pval readcsvmyfiletxtheaderfsept pval pval fdr padjustpval method bh printlengthpvalfdr writetablecbindpval fdrpvalfdrtxtrownamesfseptquotef how i implement code python here feable attempt python help google pvaluelist e e pvalues pvaluelst vr pvalue v pvaluelist padjust rr padjust rfloatvectorpvaluelstmethod bh v padjust print v the code throws attributeerror float object attribute r error can anyone help point problem thanks advance help,1 if want extract specific number lines specific line matches you may well simply read array readlines loop find match take next n lines array also could use loop along readline preferable files get large the following straightforward fix code i think necessarily best overall implementation i suggest following tips unless good reasons want get job done asap hook crook newlines rangelenlinelist mylines linelistisplit researchr w arrayofxsdstring l linelistii newlinesappendl print newlines should want i interpreted requirements properly this says take next one line next lines including th line match append newlines cannot append whole list list becomes single index list adding have fun good luck,trying write python script extract lines file the file text file dump python suds output i want strip characters except words numbers i want n etc characters find section starts arrayofxsdstring remove next line item result grab remaining lines create dictionary based unique number fifth line using number key remaining lines values pardon ignorance i explaining pythonic terminology output results file data file list arrayofxsdstring item abcd wordy type stuff stuff etc arrayofxsdstring item abcd wordy type stuff stuff etc arrayofxsdstring item abcd wordy type stuff stuff etc i tried recompile poor attempt code import string f open datatxt rb linelist line f line recompile w linesub stringprintable linelistappendline print linelist newlines line linelist mylines linesplit researchr w arrayofxsdstring newlinesappendnextlinelist range print newlines i python newbie found results google stackoverflow extract specific number lines finding specific text any help appreciated please ignore code i taking shots dark here i like see results abcdwordy type stuffmore stuff etc abcdwordy type stuffmore stuff etc abcdwordy type stuffmore stuff etc i hope helps trying interpret flawed code,1 according link provided note session’s state still preflush ie ‘new’ ‘dirty’ ‘deleted’ lists still show preflush state well history settings instance attributes this means able get access dirty objects sessiondirty list you note first parameter event callback current session object as second part use sqlalchemyormattributesgethistory function figure columns changed it returns history object given attribute contains haschanges method if trying listen changes specific class attributes consider using attribute events instead,i using sqlalchemy i would like postprocessing occur sessionflush namely i need access instances involved flush iterate the flush call update database instances involved also store data ldap database i would like sqlalchemy trigger update ldap database calling instance method i figured i using afterflushsession flushcontext event detailed i get list update instances on side note i determine columns changed dirty instance i able find instance whole dirty individual properties,2 several suggestions code stripping nonalphanumeric characters totally unnecessary timewasting need whatsoever build linelist are aware simply use plain old stringfindarrayofxsdstring research strip characters except words numbers i want n etc characters find section starts arrayofxsdstring remove next line item result then regex already covered w anyway but following reassignment line overwrites line read line f line recompile w overwrites line read linesub stringprintable here version reads file directly also handles multiple matches open datatxt r f thedict found linenoline enumeratef found linefind arrayofxsdstring found lineno entries continue grab following lines linenofound entry linestrip entriesappendentry create dict key line linenofound key entriespop thedictkey entries print key joinentries commaseparated quotes break want end first match found process multiple matches and output exactly wanted joinentries abcdwordy type stuffmore stuff etc abcdwordy type stuffmore stuff etc abcdwordy type stuffmore stuff etc,trying write python script extract lines file the file text file dump python suds output i want strip characters except words numbers i want n etc characters find section starts arrayofxsdstring remove next line item result grab remaining lines create dictionary based unique number fifth line using number key remaining lines values pardon ignorance i explaining pythonic terminology output results file data file list arrayofxsdstring item abcd wordy type stuff stuff etc arrayofxsdstring item abcd wordy type stuff stuff etc arrayofxsdstring item abcd wordy type stuff stuff etc i tried recompile poor attempt code import string f open datatxt rb linelist line f line recompile w linesub stringprintable linelistappendline print linelist newlines line linelist mylines linesplit researchr w arrayofxsdstring newlinesappendnextlinelist range print newlines i python newbie found results google stackoverflow extract specific number lines finding specific text any help appreciated please ignore code i taking shots dark here i like see results abcdwordy type stuffmore stuff etc abcdwordy type stuffmore stuff etc abcdwordy type stuffmore stuff etc i hope helps trying interpret flawed code,1 recording recordings li href recordinguri mp recordingdatecreated recordingduration sec li endfor you need add underscore datecreated you find list attributes recording object,here first post i working python web app recording phone calls i able access clientrecordingsuri i able access recordingsdatecreated dateupdated code recording recordings lia href recordinguri mp recordingdatecreated recordingduration secali endfor uri duration valid python attributes anyone know call datecreated attribute is possible python module,1 as reading full entity anyway second way least slower first one probably faster less api calls,appengine docs note queries return keys faster cost less cpu queries return full entities which two desired way fetch iterate number objects data store querykeys personallkeysonlytrue querykeysfilter name personname querykeysorderkey people dbgetquerykeys p people read properties person object print pname vs query personall queryfilter name personname queryorderkey p people read properties person object print pname,1 it django thing implemented python things in python get dictionary keyword arguments passed function method def funcargs kwargs printkwargs funca b b from simply iterate dictionary keys split interpret however wants in case takes last part interprets icontains caseinsensitive contains,in django make database queries like following modelobjectsfilternameicontains bob the question working cover is double underscore django thing python thing is single variable named nameicontains sort attributeaccess syntax in former case filter method parse variable name determine searching model table name contains somewhere string bob,3 a keyonly query gives keys entity properties in first example p name also key order implicit if want properties entity keyonly query want going query entity there way present get less properties factor data modeling here third alternative may may find readable it perform equivalently second fragment people persongqlwhere name personname person people print personname whether use approach second snippet querying directly entities going faster querying keys fetching entities correspond keys,appengine docs note queries return keys faster cost less cpu queries return full entities which two desired way fetch iterate number objects data store querykeys personallkeysonlytrue querykeysfilter name personname querykeysorderkey people dbgetquerykeys p people read properties person object print pname vs query personall queryfilter name personname queryorderkey p people read properties person object print pname,1 first belief namespace going help avoid key collisions time take step back a key consists entity kind namespace name id parents entity might it perfectly valid two different entity kinds name id so say lookupthingy matching created member specifying unique name key going collide anything else as challenge equivalent spellcheck unparented lookup table within transaction possible keep lookup table code or think analogy closer need one motivates need lookup within transaction,my python high replication datastore application requires large lookup table entries i need able supply code method return value associated code none association for example table held acceptable english words i would want function return true word found false none otherwise my current implementation create one parentless entity table entry entity contain associated data i set datastore key entity lookup code i put entities namespace prevent key conflicts essential question then i simply call getbykeyname code i get associated data the problem i access entities transaction i trying span entity groups so going back example let say i wanted spellcheck words used chat session i could access messages chat i give common ancestor i access word table entries parentless it imperative i able reference table transactions note lookup table fixed changes rarely again matches spellcheck example one solution might load words chat session one transaction spellcheck saving results start second transaction would spellcheck saved results but would inefficient chat session might added transactions this seems like clumsy solution ideally i like tell gae lookup table immutable i able query without complaining spanning entity groups transaction i see way however storing table entries memcache tempting problems it large amount data troublesome gae boots memcache entry i able reload transaction does anyone know suitable implementation large global lookup tables please understand i looking spellcheck web service anything like i using word lookup example make question clear i hoping general solution sort large lookup tables,1 as aside using xrange instead range usually faster are absolutely certain memory disk machine runs job good since data ranges hundreds gigabytes question seeing hardwarebased corruption even machine seems run stably without crashing singlebit memory errors pretty common data densities if hardware marginal sort behavior i expect are disks running checksummed raided format zfs favorite are using ecc memory do see errors hot day do see errors machine transferring network how long operation take run do see errors towards end,i encountering errors csv files i writing python necessary format i team depends csvs in nonpatterned way errors creeping across hundreds g files for example extra columns row extra row eroneous inputs certain rows missing colums i rerun script twice second run errors absent i need way ensure files written properly here code i using i know efficient i knew fashion i wanted post i sample inputs representative actual data i working output npzeros example iso alb sex m year npones postenv nprepeat postcause nprepeat postpop nprepeat outsheet npzerosoutputshape outputshape dtype s outsheet iso outsheet sex outsheet nparraypostyear dtype s outsheet nparraypostage dtype s outsheet nparraypostcause dtype s outsheet nparraypostenv dtype s outsheet nparraypostpop dtype s outsheet nparrayoutput dtype s outsheetoutsheet nan firstrow draw stri rangeoutputshape firstrowinsert population firstrowinsert envelope firstrowinsert cause firstrowinsert age firstrowinsert year firstrowinsert sex firstrowinsert iso outfile open filename w writer csvwriteroutfile writerwriterowfirstrow writerwriterowsoutsheet outfileclose errors even included random numeric values first column alb extra set rows observation observation missing columns postwriting,2 according hadoop the definitive guide hadoop sets job configuration parameters environment variables streaming programs however replaces nonalphanumeric character underscores make sure valid names the following python expression illustrates retrieve value mapredjobid property within python streaming script osenvironmapredjobid you also set environment variables streaming process launched mapreduce applying cmdenv option streaming launcher program variable wish set for example following sets magicparameter environment variable cmdenv magicparameterabracadabra,i able find name input file mapper class using filesplit writing program java is corresponding way i write program python using streaming i found following hadoop streaming document apache see configured parameters during execution streaming job names mapred parameters transformed the dots become underscores for example mapredjobid becomes mapredjobid mapredjar becomes mapredjar in code use parameter names underscores but i still cant understand make use inside mapper any help highly appreciated thanks,3 rename script you hiding real gasp module benubuntu python homebendocumentspythongasppy when gasp import trying import called gasppy,using interpreter mode gasp import runs i place script i copying straight chapter how think like computer scientist learning python heading gasp script gasp import begingraphics circle line box updatewhen keypressed endgraphics terminal benubuntu python homebendocumentspythongasppy traceback recent call last file homebendocumentspythongasppy line module gasp import file homebendocumentspythongasppy line module begingraphics nameerror name begingraphics defined,1 that memory leak means garbage collector run yet and even garbage collector run odds good kind memory pooling going processexplorer good debugging tool especially memory,does python ctypes known memory leak i working python script code like snippet using ctypes reason causing memory leak the true example test leak caused calling function it run windows python import ctypes def hi class cctypesstructure fields f ctypescuint class cctypesstructure fields g c true testhi the leak tested using processexplorer keeps looping python keeps taking memory it seems require two structure subclasses one classes multiple one using operator i sure condition basic even del test added loop still leaks memory any ideas might causing edit because someone suggested might garbagecollected yet edited version garbagecollect still appears leak memory import gc import ctypes def hi class cctypesstructure fields f ctypescuint class cctypesstructure fields g c true testhi testgccollect,1 since specify file handle give process executing methods involved file object to work around could write output pipe read like ofid gzipopenfiltsortfile wb sort subprocesspopenargssort shelltrue stdinsubprocesspipe stdoutsubprocesspipe ofidwritelinessortstdout ofidclose,i trying stream data subprocess gzip write file the following works i wonder possible use python native gzip library instead fid gzipopenselfipfile rb input data ofid openfiltsortfile wb output file sort subprocesspopenargssort gzip c shelltrue stdinsubprocesspipe stdoutofid set pipe processlinesfid sortstdin filtfid pump data pipe the question how i instead gzip package python used i mostly curious know following gives text files instead compressed binary version odd fid gzipopenselfipfile rb ofid gzipopenfiltsortfile wb sort subprocesspopenargssort shelltrue stdinsubprocesspipe stdoutofid processlinesfid sortstdin filtfid,1 subprocess writes ofidfileno gzip returns fd underlying file object def filenoself invoke underlying file object fileno method return selffileobjfileno to enable compression use gzip methods directly import gzip subprocess import popen pipe threading import thread def finput output line iterinputreadline outputwriteline p popensort bufsize stdinpipe stdoutpipe threadtargetf argspstdout gzipopen outgz wb start cafebabe pstdinwritesn pstdinclose example python gzipsubprocesspy ampamp od c outgz ampamp zcat outgz b b e n u k j j t l j j k b b c e e f,i trying stream data subprocess gzip write file the following works i wonder possible use python native gzip library instead fid gzipopenselfipfile rb input data ofid openfiltsortfile wb output file sort subprocesspopenargssort gzip c shelltrue stdinsubprocesspipe stdoutofid set pipe processlinesfid sortstdin filtfid pump data pipe the question how i instead gzip package python used i mostly curious know following gives text files instead compressed binary version odd fid gzipopenselfipfile rb ofid gzipopenfiltsortfile wb sort subprocesspopenargssort shelltrue stdinsubprocesspipe stdoutofid processlinesfid sortstdin filtfid,2 not clients implement xep xhtmlim recommends trying figure side speaks xhtml see section also mandates use normal body element message bodyhibody html xmlns httpjabberorgprotocolxhtmlim body xmlns httpwwwworgxhtml p style fontweightbold hip body html message it likely jitsi implement xep able pick plain text version note when receiving xhtml im make sure read security considerations if careful filter elements attributes styles explicitly allowed sender attack quite easily,anyone know message formatted way would send properly via xmpp users running pidgin fail send users running jitsi there error message accompany failure message tofancypantsthesrv html xmlnshttpjabberorgprotocolxhtmlim body xmlnshttpwwwworgxhtml hrefhttpwwwgooglecomlink testa body html message i also interested alternative ways constructing html message maybe one work jitsi thanks,1 if wish sure getting r also indicate wish use function r package stats rpyrobjectspackages import importr rpyrobjectsvectors import floatvector stats importr stats padjust statspadjustfloatvectorpvaluelist method bh,i list pvalues i would like calculate adjust pvalues multiple comparisons fdr in r i use pval readcsvmyfiletxtheaderfsept pval pval fdr padjustpval method bh printlengthpvalfdr writetablecbindpval fdrpvalfdrtxtrownamesfseptquotef how i implement code python here feable attempt python help google pvaluelist e e pvalues pvaluelst vr pvalue v pvaluelist padjust rr padjust rfloatvectorpvaluelstmethod bh v padjust print v the code throws attributeerror float object attribute r error can anyone help point problem thanks advance help,3 if i understand correctly want state beast alternate uintmax the type initial value probably historical reasons once interface used sticks difficult change afterwards if need value initially uintmax call eventfd argument write uintmax immediately propagate file descriptor anybody else int ev eventfd writeev ampuintt const uintmax sizeofuintt well add error checking code,question eventfd new system call available linux since the call signature int eventfdunsigned int initval int flags i making use call constructing new light saber lock class usable polling loop the python lock object starts unblocked state my use eventfd requires initial value nonzero if value internally uintt the object contains unsigned bit integer uintt counter maintained kernel initial value argument type unsigned int overt detail if i use nonzero values unlocked state lock releases done writing multiple releases without intervening acquires erroneous need fail this requires writing fail event object contains nonzero value in default mode event object add values posted uinttxfffffffffffffffe blocking write calls to detect situation i nonblocking write pushes value maximum triggering circumstance if addition would cause counter value exceed maximum write either blocks read performed file descriptor fails error eagain file descriptor made non‐ blocking,1 the script leak running gcsetdebuggcdebugleak shows created structure types collectable gcgarbage remains empty every loop iterations uncollectable objects running script time linux system show steady increase memory consumption,does python ctypes known memory leak i working python script code like snippet using ctypes reason causing memory leak the true example test leak caused calling function it run windows python import ctypes def hi class cctypesstructure fields f ctypescuint class cctypesstructure fields g c true testhi the leak tested using processexplorer keeps looping python keeps taking memory it seems require two structure subclasses one classes multiple one using operator i sure condition basic even del test added loop still leaks memory any ideas might causing edit because someone suggested might garbagecollected yet edited version garbagecollect still appears leak memory import gc import ctypes def hi class cctypesstructure fields f ctypescuint class cctypesstructure fields g c true testhi testgccollect,1 i stumbled upon issue saw question found solution you wait widget realized eg like def printstylewidget style widgetgetstyle range print gdkcolortorgbstylebgi gdkcolortorgb lambda gc gcred gcgreen gcblue widget gtkhbox example widgetconnect realize printstyle,i use pygtk i want get colors widget example bg color i run code gdkcolortorgb lambda gc gcred gcgreen gcblue widget gtkhbox example style widgetgetstyle range print gdkcolortorgbstylebgi but give colors current gtk themestyle it seems default gtk theme current theme dark code gives light colors i use archlinux pygtk gtk,1 no html elements support one value per input element know nothing python lists if want save list values html create list hidden html inputs name attribute you later get list values formgetvaluekey key value name attribute,in python cgi possible pass python list hidden text input field how i retrieve values using cgi form later thanks help def testinputanswer answer b according abc statefile fin filemap r line finreadlines funappendlinestripsplit finclose print braction traversalt answer idval enumerateanswer id firstfunval else secondandonfunval print brform actioncgibinbulpy methodpostinput typehidden namenxtans valuesanswerinput typetext namenxtv valueinput typesubmit valuenext state clickformbrbr,1 congratulations choosing python working dicom scipy numpymatplotlib clan much better dealing huge amounts volume data matlab least gnu octave experience trivia load display code using gdcm python bindings convertnumpypy gdcm examples matplotlib usrbinenv python import gdcm import convertnumpy import numpy np import matplotlibpyplot plt def loaddicomimagefilename readergdcmimagereader readersetfilenamefilename readerread gdcmimagereadergetimage return convertnumpygdcmtonumpygdcmimage imageloaddicomimage mydicomfiledcm pltgray pltimshowimage pltshow note if dicom data contains padding values significantly outside image airbone range might confuse imshow autoscaling use vmaxvmin parameters call specify range actually want see implement windowlevelling code trivial numpy,i trying create app viewing analyzing dicom slices i done app matlab matlab enough tools build really nice gui d picture bad so i trying use itk vtk build app xcode long period time without success one day i found xcodeproject pythondicomdocument project written python read show dicom image i read tutorial python cocoa i still understand project works file pythondicomdocumentdocumentpy foundation import appkit import iidicom import import objc import dicom import numpy import image class pythondicomdocumentdocumentnsdocument imageview objciboutlet imageview def initself self superpythondicomdocumentdocument selfinit selfimage none return self def windownibnameself return upythondicomdocumentdocument def windowcontrollerdidloadnibself acontroller superpythondicomdocumentdocument selfwindowcontrollerdidloadnibacontroller selfimage selfimageviewsetimagescalingnsscaletofit selfimageviewsetimageselfimage def dataoftypeerrorself typename outerror return none def readfromdataoftypeerrorself data typename outerror return no def readfromurloftypeerrorself absoluteurl typename outerror absoluteurlisfileurl slice iidcmsliceallocinitwithdicomfilesliceabsoluteurlpath dicomimage slicesliceasnsimagecontexttrue none dicomimage selfimage dicomimage selfimage dicomimage return true none return false none file mainm import pythonpythonh import cocoacocoah int mainint argc char argv nsautoreleasepool pool nsautoreleasepool alloc init nsbundle mainbundle nsbundle mainbundle nsstring resourcepath mainbundle resourcepath nsarray pythonpatharray nsarray arraywithobjects resourcepath resourcepath stringbyappendingpathcomponentpyobjc systemlibraryframeworkspythonframeworkversionscurrentextraslibpython nil setenvpythonpath pythonpatharray componentsjoinedbystring utfstring nsarray possiblemainextensions nsarray arraywithobjects py pyc pyo nil nsstring mainfilepath nil nsstring possiblemainextension possiblemainextensions mainfilepath mainbundle pathforresource main oftype possiblemainextension mainfilepath nil break mainfilepath nsexception raise nsinternalinconsistencyexception format sd main failed find mainpypycpyo file application wrapper resources directory file line pysetprogramnameusrbinpython pyinitialize pysyssetargvargc char argv const char mainfilepathptr mainfilepath utfstring file mainfile fopenmainfilepathptr r int result pyrunsimplefilemainfile char mainfilepath lastpathcomponent utfstring result nsexception raise nsinternalinconsistencyexception format sd main pyrunsimplefile failed file see console errors file line mainfilepath pool drain return result so i want translate matlab code reading dcm directory uigetdir command finder window appear user choose folder dcm files filefolder directory path folder saved variable filefolder diroutput dirfullfilefilefolder dcm choose files dcm specified folder save names filenames diroutputname names charfilenames numframes numelfilenames count number files folder numframes volumei dicomreadfullfilefilefoldernamesi create d array dicom pixel data end could anyone please tell run code reading dcm files xcode using python i heard python matlab similar,1 you mixing dpkt library parsing creating packets pypcap python wrapper libpcap to specify interface listen use pcappcapname ppp to deserialize ppp packets use dpktpppppppkt,it dpktethernetethernetpkt ethernet interface ppp interface,2 python usespace application cannot possibly determine filesystem type first place that might work albeit slow simple setups inevitably fails presence changing hard soft links various filesystems fat mounted fuse unionfs therefore filesystem filenames containing specific character remove character manually,in short i trying use distutilsdirutilcopytree copy data ext fs usb thumbdrive formatted using fat the filenames tend long contain interesting characters python stripsescapes fine ext however upon using copytree list illegal characters suddenly grows gets thrown onto fat thumbdrive python escape results ioerror errno invalid mode wb filename u mediausbdatasomeweirdfilewithdotsetcsatellite obviously mode wb fine resulting illegal character short rewriting copytree escaping filename way easily tell python working different filesystem type,1 no python know underlying filesystem it also escape anything filename — job — happens valid character ext filesystems,in short i trying use distutilsdirutilcopytree copy data ext fs usb thumbdrive formatted using fat the filenames tend long contain interesting characters python stripsescapes fine ext however upon using copytree list illegal characters suddenly grows gets thrown onto fat thumbdrive python escape results ioerror errno invalid mode wb filename u mediausbdatasomeweirdfilewithdotsetcsatellite obviously mode wb fine resulting illegal character short rewriting copytree escaping filename way easily tell python working different filesystem type,1 the problem first loop current always none therefore second loop body never executed even case found false,can someone please tell add function working adds first rest thankyou class frequencyobject stores letterfrequency pair f frequency c fletter c ffrequency f c def initself letter frequency selfletter letter selffrequency frequency selfnext none def reprself return selfletter selffrequency class sortedfrequencylistobject stores collection frequency objects sorted linked list items sorted highest frequency lowest def initself selfhead none def addself letter frequency adds given letterfrequency combination frequency object list if given letter already list given frequency added frequency f sortedfrequencylist fadd f fadd b f b fadd c f c b fadd b f b c current selfhead found false prev none selfhead none selfhead frequencyletter frequency else current none currentletter letter currentfrequency currentfrequency frequency found true prev current current currentnext found false current none currentfrequency frequency currentnext frequencyletter frequency elif currentfrequency frequency temp prev prev frequencyletter frequency current temp prev current current currentnext,1 assuming read javascript look javascript file httpcommonswikimediaorgwindexphptitlemediawikistockphotojsampactionrawampctypetextjavascript you see javascript order get info look getauthorattribution getlicense you port python using beautifulsoup parse html,since i counldn find api function common wikimedia get alicense image thing left fetch webpage parse for image nice popup wikimedia lists attribution field i need for example page httpcommonswikimediaorgwikifilebradpittcannesjpg link right saying use file web when clicking i see attribution field i need using python i fetch webpage initiate javascript call open pop order retrieve text inside attribution field thanks meir,1 use poison pill technique upon receipt pill special message program must handle die the way ok something elegant implement kind communication killing script main program for start look standard library interprocess communication networking,i python program uses multiple daemon threads i want stop program outside preferably another python script i tried kill pid shell test work multithreaded scripts one way would make program check file every nseconds flag termination i sure better way i note i like stop program cleanly message outside form exception would ideal i think edit here example i moment try open myproglck w close true timesleep try open myproglck close except ioerror raise keyboardinterrupt except keyboardinterrupt print myprogram terminated deleting file myproglck cause script stop is example bad way,1 i interested see done using tools using selenium rc lxml done like import selenium selseleniumseleniumlocalhostfirefox file selstart selopen httpcommonswikimediaorgwikifileabradpittcannesjpg selclick acontainstitleuse file web printselgetvalue inputidstockphotoattribution selstop yields georges biard ccbysa wwwcreativecommonsorglicensesbysa via wikimedia commons,since i counldn find api function common wikimedia get alicense image thing left fetch webpage parse for image nice popup wikimedia lists attribution field i need for example page httpcommonswikimediaorgwikifilebradpittcannesjpg link right saying use file web when clicking i see attribution field i need using python i fetch webpage initiate javascript call open pop order retrieve text inside attribution field thanks meir,1 you use locals get local symbol table dict use get variable value ie picklevel lockpickinglevelmaxxp lockpickinglevelmaxxp lockpickinglevelmaxxp localslockpickingleveldmaxxp picklevel,i like using lot if statements here i playing around right world use lot if statements get done first variables picklevel lockpickinglevelmaxxp lockpickinglevelmaxxp lockpickinglevelmaxxp now get picking lock a successful pick happens random number anything current lockpicking skill level max xp divided chosen so level anything level anything level anything here would look if statements x randomrandint picklevel x range lockpickinglevelmaxxp print you failed pick lock elif picklevel x range lockpickinglevelmaxxp etcetc what i like determine xp based value picklevel bunch if statements asking question it would go something like using grave accents like bash x range lockpickinglevelpicklevelmaxxp this way i avoid if statements code automatically become lockpickinglevelmaxxp lockpickinglevelmaxxp lockpickinglevelmaxxp based whatever picklevel value it since i done bash scripts though memory works may bit also i know python version basically using repr is way i i stuck writing ugly if statements place i suppose i could use dict lockpickingmaxxp x range lockpickingmaxxppicklevel i know exactly i setting skill database although probably end json file i love json thank much time i look forward learning idea,1 whenever feel need add numbers variables probably use list picklevel lockpickinglevels test randomrandint test lockpickinglevelspicklevel print failed else,i like using lot if statements here i playing around right world use lot if statements get done first variables picklevel lockpickinglevelmaxxp lockpickinglevelmaxxp lockpickinglevelmaxxp now get picking lock a successful pick happens random number anything current lockpicking skill level max xp divided chosen so level anything level anything level anything here would look if statements x randomrandint picklevel x range lockpickinglevelmaxxp print you failed pick lock elif picklevel x range lockpickinglevelmaxxp etcetc what i like determine xp based value picklevel bunch if statements asking question it would go something like using grave accents like bash x range lockpickinglevelpicklevelmaxxp this way i avoid if statements code automatically become lockpickinglevelmaxxp lockpickinglevelmaxxp lockpickinglevelmaxxp based whatever picklevel value it since i done bash scripts though memory works may bit also i know python version basically using repr is way i i stuck writing ugly if statements place i suppose i could use dict lockpickingmaxxp x range lockpickingmaxxppicklevel i know exactly i setting skill database although probably end json file i love json thank much time i look forward learning idea,1 don repeat use data structures instead individual objects much possible lockpickingmaxxp x randomrandint x lockpickingmaxxppicklevel print you failed pick lock of course probably skills game might want something like maxxp lockpicking trapsearching skill lockpicking x randomrandint x maxxpskilllevelskill print you failed pick lock,i like using lot if statements here i playing around right world use lot if statements get done first variables picklevel lockpickinglevelmaxxp lockpickinglevelmaxxp lockpickinglevelmaxxp now get picking lock a successful pick happens random number anything current lockpicking skill level max xp divided chosen so level anything level anything level anything here would look if statements x randomrandint picklevel x range lockpickinglevelmaxxp print you failed pick lock elif picklevel x range lockpickinglevelmaxxp etcetc what i like determine xp based value picklevel bunch if statements asking question it would go something like using grave accents like bash x range lockpickinglevelpicklevelmaxxp this way i avoid if statements code automatically become lockpickinglevelmaxxp lockpickinglevelmaxxp lockpickinglevelmaxxp based whatever picklevel value it since i done bash scripts though memory works may bit also i know python version basically using repr is way i i stuck writing ugly if statements place i suppose i could use dict lockpickingmaxxp x range lockpickingmaxxppicklevel i know exactly i setting skill database although probably end json file i love json thank much time i look forward learning idea,2 you overlooked fact integers try f instead,i reading csv file extracting piece data line x floatnode i printx i get correct value exact value found cell eg but i try pass x variable following print node version lond x output node version lon of course i want value what i overlooked thanks advance,2 you want replace f problem solved see httpdocspythonorgreleaselibtypesseqstringshtml for bonus points aware put together long format strings still readable using dictionaries you read r option i used call repr function variable know inserted exactly seen printed debugging string tagname ididvalr typetagtyper foobarr print stringformat idval var tagtype var bar var,i reading csv file extracting piece data line x floatnode i printx i get correct value exact value found cell eg but i try pass x variable following print node version lond x output node version lon of course i want value what i overlooked thanks advance,1 you using wrong format flag integers use f floats,i reading csv file extracting piece data line x floatnode i printx i get correct value exact value found cell eg but i try pass x variable following print node version lond x output node version lon of course i want value what i overlooked thanks advance,1 defining explicit getters setters bad practice python instead use properties class thingobject newstyle class def initself whatever selfwhatever whatever property def whateverself return selfwhatever insert complicated calculation so instead preplanning using get methods introduce property actually need advanced behavior earlier,i question puzzling recently best way retrieve attributes outside let say i class class thing def initself whatever selfwhatever whatever x thing foo now i know i want retrieve whatever attribute i xwhatever i habit probably i come oo languages define methods retrieve class attributes needed use insted retrieve directly like class thing def initself whatever selfwhatever whatever def getwhateverself return selfwhatever in little experience i found using approach make things easier mantain long term i edit structure data attributes i edit specific method but since i really python veteran i love know i doin right approaches better pythonic thoughts,3 phihag right idea mentions answer explicit the first step simply use attribute directly class thingobject def initself whatever selfwhatever whatever thing assert twhatever later find need make whatever attribute sophisticated turn property class thingobject def initself whatever selfwhatever whatever property def whateverself return somethingcomplicatedselfwhatever thing assert twhatever this way calling code change nice clean api object,i question puzzling recently best way retrieve attributes outside let say i class class thing def initself whatever selfwhatever whatever x thing foo now i know i want retrieve whatever attribute i xwhatever i habit probably i come oo languages define methods retrieve class attributes needed use insted retrieve directly like class thing def initself whatever selfwhatever whatever def getwhateverself return selfwhatever in little experience i found using approach make things easier mantain long term i edit structure data attributes i edit specific method but since i really python veteran i love know i doin right approaches better pythonic thoughts,3 using unutbu answer i converted use selenium webdriver rather older seleniumrc import codecs import lxmlhtml lh selenium import webdriver browser webdriverfirefox browserget httpcommonswikimediaorgwikifileabradpittcannesjpg content browserpagesource browserquit doc lhfromstringcontent elt docxpath spanacontainstitleuse filetext print elt output web wiki,since i counldn find api function common wikimedia get alicense image thing left fetch webpage parse for image nice popup wikimedia lists attribution field i need for example page httpcommonswikimediaorgwikifilebradpittcannesjpg link right saying use file web when clicking i see attribution field i need using python i fetch webpage initiate javascript call open pop order retrieve text inside attribution field thanks meir,2 you use decode unicode decode input string representation example iso utf get unicode object you use u indicate string treated unicode fact result object unicode type foo u å‚ã³dåº fooclass type unicode use encode encode input string using example utf encoding choice get str object foo u å‚ã³dåº fooclass type unicode bar fooencode utf barclass type str read article unicode python get better idea stringunicodestring encoding mess,i from iran and i use persian character when i use u decode encode unicode,1 via python interpreter import flask flaskversion if flask installed via pip easyinstall always use pip freeze command,what easiest way determine version flask installed,3 when serve content web browser need tell encoding file ideally send contenttype http header response something like textplain charsetutf utf replaced whatever encoding actually using utf your browser may also need set use unicodeaware font displaying text files uses font necessary glyphs obviously display,i txt files included turkish characters i prepared html code wanna include texts txt files the processes successful html files made python character problemsspecial characters seems like � i tried add u strings python code work txt files made python actually blog entries i got using urrlib moreover character problems thank answers,1 unfortunately case setup tools masking error setuppy caused bad version string tvrenamrinitpy i picked error installing manually python setuppy install clean virtualenv something environment must affecting things,i trying install program via pip pypi usual command pip install tvrenamr however i getting error downloadingunpacking tvrenamr running setuppy egginfo package tvrenamr usage tvr options filefolder c error option eggbase complete output command python setuppy egginfo usage tvr options filefolder c error option eggbase command python setuppy egginfo failed error code storing complete log usersgeorgepippiplog it since i checked i used able pip install code previous versions i put pypi however i updated latest pip sure would cause things break so pip running python setuppy egginfo seems tvrenamr called least option parser class imported my setuppy ospath import dirname join setuptools import setup findpackages tvrenamr import getversion def freadfname return openjoindirnamefile fnameread setup name tvrenamr version getversion description rename tv show files using online databases longdescription fread readmemarkdown author george hickman authoremail georgeghickmancouk url httpgithubcomghickmantvrenamr license mit packages findpackagesexclude tests entrypoints consolescripts tvr tvrenamrtvrenamrrun classifiers environment console intended audience end usersdesktop license osi approved mit license operating system macos operating system microsoft windows operating system posix linux programming language python topic multimedia topic utilities natural language english installrequires lxml pyyaml tvrenamrinitpy version def getversion return joinmapstr version my thoughts getting tvrenamr options either findpackages entrypoints option way importing tvrenamrpy thus optionspy all versions tvrenamr uploaded pypi python setuppy sdist upload i really stumped problem help much appreciated edit i run python setuppy egginfo errors,1 change field type ratingglobal numeric type either float integer need varchar personally i would change rating fields integer i find need float drop key id primary key already indexed videoidratingglobalwebsiteid watch integer length references eg videoid videoid may run numbers these sizes i suggest following step solution replace query create temporary table ratingstats enginememory select videoid sumtagrating as tagratingsum from userrating ur join videotag vt on vtid urtagid and uruserid group by videoid order by null select vid tagratingsumratingglobal as score from video v join ratingstats rs on rsvideoid vid where vwebsiteid and vratingglobal and vid not in order by score desc limit for latter query perform really fast could incorporate primary key video table fields websiteid ratingglobal perhaps websiteid enough though you also use another table statistics precalculate dynamically based user loginaction frequency i guessing show cached data instead showing live results much difference,i building video recommendation site think pandora music videos python mysql i three tables db video table videos data change columns create table video id int not null autoincrement websiteid smallint unsigned default ratingglobal varchar default title varchar default null thumburl text primary key id key websites websiteid key id id using btree engineinnodb autoincrement default charsetutf videotag table tags attributes associated video doesn change create table videotag id int not null autoincrement videoid mediumint unsigned default tagid mediumint unsigned default primary key id key videoid videoid key tagid tagid engineinnodb autoincrement default charsetutf userrating table good bad ratings user given tag data always changing create table userrating id int not null autoincrement userid smallint unsigned default tagid int unsigned default tagrating float default primary key id key video tagid key userid userid using btree engineinnodb autoincrement default charsetutf based user preferences i want score unwatched video try predict like best this resulted following massive query takes seconds complete videos select videotagvideoid sumuserratingtagrating videoratingglobal score from videotag join userrating on userratingtagid videotagtagid join video on videoid videotagvideoid where userratinguserid and videowebsiteid and ratingglobal and videoid not in group by videoid order by score desc limit i desperately need make efficient i looking advice best direction some ideas i considered rework db table structure sure b offload grouping aggregation python figured way join three tables actually faster c store nonchanging tables memory try speed computation time earlier tinkering yielded gains yet how would recommend making efficient thanks per request comments explain select shows id selecttype table type possiblekeys key keylen ref rows extra simple userrating ref videouserid userid const using using temporary using filesort simple videotag ref videoidtagid tagid dbuserratingtagid using simple video eqref primarywebsitesid primary dbvideotagvideoid using,1 use multiline string str rrow id posttypeid parentid creationdatet score viewcount bodypan explicit cast double as long string span multiple lines also use alternative quote character str r row id posttypeid parentid kinds quotes inside string escape quotes ned batchelder noted use raw string anymore str row id posttypeid parentid,i need use long string testing regular expression however test string always altered inside quotation marks leads whole string seperetaed several parts included string thus error occurred strrrow id posttypeid parentid n creationdatetn score viewcount bodypan explicit cast double would pleae tell tackle thanks lot,1 it generally difficult delete large categories keys a better approach site generation number associated start generation use generation number cache keys site when make fundamental change time want invalidate entire cache site increment site generation number now cache accesses misses everything cached anew all old data still cache discarded ages accessed this scheme extremely efficient since require finding touching old data it also generalized class cache contents persite,one common pattern caching django use current site id cache key order essence namespace keys the problem i i love able delete values cache namespace eg delete cache values site made fundamental change the current pattern dealing send signals place etc i used siteid cache key example common pattern others may recognize way i using cache custom multitenant application makes problem even profound question is cache backend andor pattern works well deleting objects namespaced way pseudonamespaced way extraordinarily expensive ie looping possible cache keys given namespace deleting cache i would prefer use memecached open solution works well plugin,1 it looks like relies windows api ahk probably wrapper given parameters site referencing silly use case eg hwnd generally suggests windows api structtypethings i highly doubt plug play anything given somewhat unusual goal specific windows if want make implementation likely get lot help tim golden website anyone done i imagine httptimgoldenmeukpythonwmiindexhtml mark hammond core python windows modules also reasonable search words somehow still relatively little documentation directly i imagine book much help otherwise make calls ahk make requires reading msdn you effort would greatly reduced given know roughly want ahk script but still annoying you might find grayhat python early chapters useful want see examples implement windows api calls making struct calling functions etc i found helpful materials come directly pythonwindows groups undoubtedly bit head best luck,is way use python get list icons system tray lower right hand corner associated processes executables here thread using ahk httpwwwautohotkeycomforumtopichtml relies heavily ahk note i interested windows xp thanks,1 actually yes check difference getattribute getattr method you assign new value instance field getattribute except setattr explicitly prohibits try python prompt class aobject pass agetattribute myfunc agetattr myfunc if setattr allow something like solution proposed check module copy magically copying attributes,i trying modify getattribute method instance may already know getattirbute readonly attribute python edit appereantly objects others what i mind create new object like def createnewinstaceoldinstance class tempoldinstanceclass def initselfargskwargs since copy already inited instance pass def getattributeselfattr stuff newinstance temp magically copy attrs oldinstance newinstance return newinstance is kind thing possible i particular problem i want know,1 you want run python script cgi script first create cgi script abcsh like binsh echo http ok echo contenttype textplain echo abcpy amp make sure chmod x abcsh stick abcsh abcpy cgibin directory then able visit examplecomcgibinabcsh run python script,i found python script task i know i execute script server parameter local machine i command line if script address wwwaaacomabcpy i execute parameters browser else,1 from question i really understand inspect ran possible escape output like object e or escape things inside template using foo raw raw endraw,i started building first flask app currently simply returns output inspect objects inside table tags the problem instead html i expect template engine messes layout creating new tags i guess parses dict curly brackets,3 ok i inadvertently trying cprofile parallel run cluster i simply test runs offline the code runs fine profiling breaks always parallel scripts it related cluster lsf sorry,i trying parallelize work runs mac pyton mac os gives following error linux cluster i run i got cores access python the error messages continue i break execution manually exception thread thread traceback recent call last file nswpythonlibpythonthreadingpy line bootstrapinner selfrun file nswpythonlibpythonthreadingpy line run selftargetselfargs selfkwargs file nswpythonlibpythonmultiprocessingpoolpy line handletasks puttask picklepicklingerror can pickle class function attribute lookup builtinsfunction failed process poolworker process poolworker traceback recent call last traceback recent call last file nswpythonlibpythonmultiprocessingprocesspy line bootstrap file nswpythonlibpythonmultiprocessingprocesspy line bootstrap process poolworker traceback recent call last file nswpythonlibpythonmultiprocessingprocesspy line bootstrap process poolworker traceback recent call last file nswpythonlibpythonmultiprocessingprocesspy line bootstrap selfrun file nswpythonlibpythonmultiprocessingprocesspy line run selftargetselfargs selfkwargs file nswpythonlibpythonmultiprocessingpoolpy line worker process poolworker traceback recent call last file nswpythonlibpythonmultiprocessingprocesspy line bootstrap selfrun file nswpythonlibpythonmultiprocessingprocesspy line run selftargetselfargs selfkwargs file nswpythonlibpythonmultiprocessingpoolpy line worker of course reference part code i see call multiprocessingpool result errors esp poolworkers numbers higher processes thanks thoughts import csv import networkx nx import time import shutil import datetime import pydot import os import import logging operator import itemgetter import numpy np multiprocessing import pool import itertools dictionary edge attributes projected graph overlaplength overlapstart overlapend cell level def chunksln divide list nodes l n chunks lc iterl x tupleitertoolsislicelcn x return yield x def overlapsgbunbrs l v nbrs mutualcell setbu amp setbv uspell bgetedgedataumutualcellvalues ustart uspell uend uspell vspell bgetedgedatavmutualcellvalues vstart vspell vend vspell uend vstart vend ustart ostart maxustartvstart oend minuendvend olen oendostart ocell mutualcell v gu ostart edict edict guvvalues lappenduv olen ostart oend ocell return l def pmapargtuple pool multiprocess accepts functions one argument this function uses tuple argument return overlapsargtupleargtupleargtupleargtuple def timeoverlapprojectedgraphparallelb nodes gnxmultigraph gaddnodesfromnbnoden n nodes addedgesfrom nxmultigraphaddedgesfrom getedgedata nxmultigraphgetedgedata p poolprocesses nodedivisor lenppool u nodes unbrs setbu nbrs setn nbr unbrs n bnbr setu iterate subsets neighbors parallelize nodechunks listchunksnbrsintlennbrsintnodedivisor numchunks lennodechunks pedgelists pmappmap zipgnumchunks bnumchunks unumchunks nodechunks l pedgelists llextendl gaddedgesfromll compile long list add edges long list single step return g,1 you missing hidden submitlogin argument have tried import urllib urllib url httpblahcommemberindexbv values submit login email someemailgmailcom password somepassword data urlliburlencodevalues req urllibrequesturl data response urlliburlopenreq thepage responseread,i looking grab form data needs passed along specific website submit below htmlform i need simulate i working hours seem get anything work i want work google app engine any help would nice form methodpost actionmemberindexbv table cellspacing cellpadding border width tr td alignleft hmember loginhinput typehidden namesubmit valuelogin br td tr tr td alignleft stylecolor bc emailbr input typetext nameemail stylewidth px td tr tr td alignleft stylecolor bc passwordbr input typepassword namepassword stylewidth px td tr td input typeimage classformelementimagebutton srcresourcesdefaultimagesbtnlogingif stylewidth px height px td tr tr td alignleft div stylelineheight em hrefjoin stylecolor bc fontweight bold textdecoration underline joinabr hrefmemberforgot stylecolor bc fontweight bold textdecoration underlineforgot passwordainput typehidden namelastplace valuefbr trouble logging hrefcookieproblemsbvclick herea help div td tr table form currently i trying use code access working i pretty new maybe i missing import urllib urllib url httpblahcommemberindexbv values email someemailgmailcom password somepassword data urlliburlencodevalues req urllibrequesturl data response urlliburlopenreq thepage responseread,1 this general issue understanding closures python default variables local innermost function assigned implicit assignment tocheck becomes local variable connected failed as tocheck main function never changed in python x nonlocal tocheck top connected failed would make expect here example accomplish thing using mutation x import itertools def main ip port tocheck counter itertoolscountnext twistedinternet import reactor def connectedwhathappened print sysstdout successfully connected whathappenedwhathappened return counter def failedreason print sysstderr connection failed reason return counter def checkedcount print sysstdout connections left check tocheck count count tocheck reactorstop rangetotal checkconnip striport daddcallbacksconnectedfailed daddbothchecked reactorrun,aim to try tcp connection list server print connection successful prompted password problem it seems statement tocheck callbacknamed connected errbacknamed failed never gets executed even though print statements functions twistedinternet import protocol defer import sys class myprotoprotocolprotocol got def datareceivedselfdata print data selfgot data password data selftransportloseconnection def connectionlostselfreason print selfgot password selfgot selffactorysuccessand prompted password else selffactorysuccessbut prompted password class myfactoryprotocolclientfactory protocol myproto def initselfdeferredhost selfdeferred deferred selfhost host print trying connection host def successselfaskpass selfdeferred none selfdeferred selfdeferred none dcallbackselfhostaskpass def clientconnectionfailedself connector reason selfdeferred none selfdeferred selfdeferred none derrbackreason def checkconnhost port twistedinternet import reactor deferdeferred factory myfactorydhost reactorconnecttcphostportfactory return def main ip port total tocheck total twistedinternet import reactor def connectedwhathappened print sysstdout successfully connected whathappenedwhathappened tocheck def failedreason print sysstderr connection failed reason tocheck def checked print sysstdout connections left check tocheck tocheck reactorstop rangetotal checkconnip striport daddcallbacksconnectedfailed daddbothchecked reactorrun name main main output trying connection trying connection successfully connected prompted password connections left check successfully connected prompted password connections left check successfully connected prompted password connections left check successfully connected prompted password connections left check similar output successfully connected prompted password connections left check number connection left check decreasing remains,3 no nothing truly private python if know method name get i think might come clever hack would hack no functionality exists language,pep states emphasis mine we use term private since attribute really private python without generally unnecessary amount work i guess refers defining actual class language exposing public members interpreter is way achieve true privateness python i asking curiosity,2 note this private sense ccjava type private close for class prefix variable this cause python name mangle accidentally call outside class for example class testobject def initself selfnumber test print anumber name error on hand really private you access number print atestnumber but prevent accidental mistakes private used anyway if prefixed someone uses code fault code breaks later warned,pep states emphasis mine we use term private since attribute really private python without generally unnecessary amount work i guess refers defining actual class language exposing public members interpreter is way achieve true privateness python i asking curiosity,1 is login page rd party site if may simply posting form inputs for example i tried login page one sites a simple post request work case may login page accessing well for starters login form may hidden csrf token value send posting login request this means first get login page parse resulting html csrf token value the server may also require session cookie login request i using requests module handle getpost beautifulsoup parse data import requests import zlib beautifulsoup import beautifulsoup first get login page response requestsget httpswwwsitecom content zipped need unzip html zlibdecompressresponseread zlibmaxwbits parse html csrf token soup beautifulsouphtml csrftoken soupfindname input id csrftoken value submit login data including csrf token original cookie data response requestspost httpswwwsitecomlogin csrftoken csrftoken username username password ckrit cookiesresponsecookies loginresult zlibdecompressresponseread zlibmaxwbits print loginresult i cannot say gae allow least might helpful figuring may require particular case also carl points submit input used trigger post include in particular example required,i looking grab form data needs passed along specific website submit below htmlform i need simulate i working hours seem get anything work i want work google app engine any help would nice form methodpost actionmemberindexbv table cellspacing cellpadding border width tr td alignleft hmember loginhinput typehidden namesubmit valuelogin br td tr tr td alignleft stylecolor bc emailbr input typetext nameemail stylewidth px td tr tr td alignleft stylecolor bc passwordbr input typepassword namepassword stylewidth px td tr td input typeimage classformelementimagebutton srcresourcesdefaultimagesbtnlogingif stylewidth px height px td tr tr td alignleft div stylelineheight em hrefjoin stylecolor bc fontweight bold textdecoration underline joinabr hrefmemberforgot stylecolor bc fontweight bold textdecoration underlineforgot passwordainput typehidden namelastplace valuefbr trouble logging hrefcookieproblemsbvclick herea help div td tr table form currently i trying use code access working i pretty new maybe i missing import urllib urllib url httpblahcommemberindexbv values email someemailgmailcom password somepassword data urlliburlencodevalues req urllibrequesturl data response urlliburlopenreq thepage responseread,1 python urllib indeed leaks file descriptor httpsbugspypyorgissue,i using urllib load files ftp httpservers some servers support one connection per ip the problem urllib close connection instantly look exampleprogram urllib import urlopen time import sleep url ftpuserpasshostbigfileext def loadfileurl f urlopenurl loaded true data fread data break loaded lendata fclose sleep print loaded formatloaded loadfileurl loadfileurl the code loads two files two files ftpserver supports connection this print following log loaded traceback recent call last file conectiontestpy line module loadfileurl file conectiontestpy line loadfile f urlopenurl file usrlibpythonurllibpy line urlopen return openeropenurl data timeout file usrlibpythonurllibpy line open response selfopenreq data file usrlibpythonurllibpy line open open req file usrlibpythonurllibpy line callchain result funcargs file usrlibpythonurllibpy line ftpopen fw selfconnectftpuser passwd host port dirs reqtimeout file usrlibpythonurllibpy line connectftp fw ftpwrapperuser passwd host port dirs timeout file usrlibpythonurllibpy line init selfinit file usrlibpythonurllibpy line init selfftpconnectselfhost selfport selftimeout file usrlibpythonftplibpy line connect selfwelcome selfgetresp file usrlibpythonftplibpy line getresp raise errortemp resp urlliburlerror urlopen error ftp error there many connections internet address so first file loaded second fails first connection closed but use sleep fclose error occurr loaded loaded is way force close connection second download would fail,2 this python ba f,i try write formulas python luck i errors code i know calculation gives incorrect result i guess i something wrong implementation formulas import math lat lon b mathradianslat l mathradianslon h pi mathpi b f ba f ba f e da df one second radians dx dy dz sin mathsin cos mathcos rn mathsqrte mathsinb rm aee sinb vc rmhsinm db dxsinbcosl dysinl dzcosb darn esinbcosbadfrmabrnbasinbcosbvc dl dx sinl dy cosl rn h cosb sinm db pi b b dl pi l print print b,3 pythonexe compilercuminterpreter file comes python implementation package it runs code written using python language you run python code installed system i suggest go download python implementation here os try running program earlier,okay months ago guy built program company using python the program ran fine sudden work the error message says find pythonpythonexe i trying figure file came python installation something built programmer sorry dumb question,2 this formula errors db dxsinbcosl dysinl dzcosb darn esinbcosbadfrmabrnbasinbcosbvc it db dxsinbcosl dysinbsinl dzcosb darn esinbcosba dfrmabrnbasinbcosb vc,i try write formulas python luck i errors code i know calculation gives incorrect result i guess i something wrong implementation formulas import math lat lon b mathradianslat l mathradianslon h pi mathpi b f ba f ba f e da df one second radians dx dy dz sin mathsin cos mathcos rn mathsqrte mathsinb rm aee sinb vc rmhsinm db dxsinbcosl dysinl dzcosb darn esinbcosbadfrmabrnbasinbcosbvc dl dx sinl dy cosl rn h cosb sinm db pi b b dl pi l print print b,2 just goes every character line code something like coding utf import sys data opensysargv line l data line char listunicodel utf char try sencode ascii except print non ascii character lines chars linechar,while making app engine app i suddenly ran error shows every couple requests runwsgiappapplication file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebapputilpy line runwsgiapp runbarewsgiappaddwsgimiddlewareapplication file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebapputilpy line runbarewsgiapp data result file homeubuntuprogramsgooglegoogleappenginegoogleappengineextappstatsrecordingpy line appstatswsgiwrapper result appenviron appstatsstartresponse file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlerhandleexceptione selfdebug file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebappwebapppy line handleexception selferror file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebappwebapppy line error selfresponseclear file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebappwebapppy line clear selfoutseek file usrlibpythonstringiopy line seek selfbuf joinselfbuflist unicodedecodeerror ascii codec decode byte xd position ordinal range i really idea could happens i use specific function impossible track string i it possible byte character like etc another language how i find byte possibly ones i running gae python ubuntu thanks updated this code i ended using codecs import bomutf os import listdir path p path def looppathp times fname listdirp filepath pathjoinp fname pathisdirfilepath return looppathfilepath times fnamesplit py continue f openfilepath r ln line f print line bomutf ln line bomutf line line col c listline ordc raise exception found linec line column ln col filepath col ln fclose looppathp,2 when i translated utf files latin latex i similar problems i wanted list evil unicode characters files it probably even need i used unicodeerrors def fortexexc import unicodedata exceptions global unicodeerrors isinstanceexc exceptionsunicodeencodeerror raise typeerrordon know handle r exc l print sysstderr unicode reprexcobjectmaxexcstartexcend c excobjectexcstartexcend uname unicodedatanamec uxx ordc lappenduname key reprc unicodeerrorshaskeykey unicodeerrorskey uname else unicodeerrorskey return ugptastaturs u joinl excend def main codecsregistererrorfortex fortex fileout codecsopenfilepath w defaultcharset fortex print unicodeerros helpful here matching excerpt python doc codecsregistererrorname errorhandler register error handling function errorhandler name name errorhandler called encoding decoding case error name specified errors parameter for encoding errorhandler called unicodeencodeerror instance contains information location error the error handler must either raise different exception return tuple replacement unencodable part input position encoding continue the encoder encode replacement continue encoding original input specified position negative position values treated relative end input string if resulting position bound indexerror raised,while making app engine app i suddenly ran error shows every couple requests runwsgiappapplication file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebapputilpy line runwsgiapp runbarewsgiappaddwsgimiddlewareapplication file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebapputilpy line runbarewsgiapp data result file homeubuntuprogramsgooglegoogleappenginegoogleappengineextappstatsrecordingpy line appstatswsgiwrapper result appenviron appstatsstartresponse file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlerhandleexceptione selfdebug file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebappwebapppy line handleexception selferror file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebappwebapppy line error selfresponseclear file homeubuntuprogramsgooglegoogleappenginegoogleappengineextwebappwebapppy line clear selfoutseek file usrlibpythonstringiopy line seek selfbuf joinselfbuflist unicodedecodeerror ascii codec decode byte xd position ordinal range i really idea could happens i use specific function impossible track string i it possible byte character like etc another language how i find byte possibly ones i running gae python ubuntu thanks updated this code i ended using codecs import bomutf os import listdir path p path def looppathp times fname listdirp filepath pathjoinp fname pathisdirfilepath return looppathfilepath times fnamesplit py continue f openfilepath r ln line f print line bomutf ln line bomutf line line col c listline ordc raise exception found linec line column ln col filepath col ln fclose looppathp,1 the recommendation use informative class names sw it much better use full words capcase see pep,i writing extension tkinter conflicted naming style i use new attributes i going add this first naming style giving new attributes prefix sw import tkinter tk class new tkbutton object def init self par tkbuttoninitself par attrnames attr attr attr attr name attrnames newname sw name setattrself newname none root tktk new newroot newpack newswattr rootmainloop for second naming style i made new attributes attributes sw class then i made instance sw attribute new class import tkinter tk class sw object def init self attrnames attr attr attr attr name attrnames setattrself name none class new tkbutton object def init self par tkbuttoninitself par selfsw sw root tktk new newroot newpack newswattr rootmainloop,1 definitely python yes people say python productive without reason some answers mention recompile i give details python one layer abstraction c think express designs less code your program might run fast sure express faster code want the common case launch application load files setup environment open dialog there notice button working now point people close application bind one slot one signal start application load files setup python write code fire dialog whole application i know type task i time qt python gives something c introspection you explore running program pull information components runtime qt gives partially you moc layer meta properties meta information attached qt objects all parts python program introspected many people debugging python code trying understand works addicted good reason,trying dive qt big time done large project yet currently using python i thinking really better language use terms programmer productivity in comparisons languages python obvious answer mess memory management however qt i sure it provides enough added features c i tell line python code roughly equal line c code time excluding additional things like class definitions structure components qt nearly memory management long stick classes provides equivalents nice containers would find python i always preferred statically typed languages gotten python bandwagon various reasons if programmer productivity similar c however i may jump back way benefits efficient code fewer dependencies users install thoughts,3 it stable yet trunk specify ul divs style rather table style radio widget i think would dbpaymentbpaystepselectiontypewidget lambda f v sqlformwidgetsradiowidgetf v style divs you also create custom widget described end section book when say want innerhtml different value radio button talking label next radio button for isinset validator takes labels argument list labels associated options set,i trying display field radio button group customised form i want place radio button different row table the problem i use formcustomselectiontype widget wrapped unwanted tr td tags is way add radio button my form extend layouthtml formcustombegin table tr td formcustomselectiontypetd td formcustomwidgetbillerlisttd tr tr td formcustomwidgetselectiontypetd td formcustomwidgetbillercodetd tr table formcustomend example happening html source code table tr td trtdinput nameselectiontype typeradio valuefrom biller list from biller listtdtrtd tr table my model dbdefinetable paymentbpaystep field selectiontype liststring field billerlist dbbiller notnulltrue field billercode field billername dbpaymentbpaystepselectiontyperequires isinset from biller list search biller code search biller name dbpaymentbpaystepselectiontypewidget sqlformwidgetsradiowidget,1 run issue files able solve i sure generated like example they trailing data end ignored windows z failing python zipfile this code solve issue def fixbadzipfilezipfile f openzipfile rb data fread pos datafind xxbxx end central directory signature pos selflogtruncating file location strpos fseekpos size zip end central directory record ftruncate fclose else raise error file truncated,i came problem trying decompress zip file zipfileiszipfilemyfile always returns false even though unix command unzip handles fine also trying zipfilezipfilepathfilehandletopath i get error file command returns zip archive data least v extract using less file shows pkzip iseries pkware length method size cmpr date time crc name defls ceee myfiletxt file any ideas i go around issue it would nice i could make python zipfile work since i already unit tests i drop i switch running subprocesscallunzip,3 i found short time ago httpcodegooglecompnmrgluesourcebrowsetrunknmrglueanalysisleastsqboundpy it uses parameter transformation impose box constraints it also calculates adjusted covariance matrix parameter estimates bsd licensed i tried yet,i using optimizeleastsq fit data i would like constrain fitting parameters certain range is possible define bounds using optimizeleastsq bounds implemented optimizefminslsqp i prefer use optimizeleastsq,2 here little example tkinter import root tk class windowdraggable def initself label selflabel label labelbind buttonpress selfstartmove labelbind buttonrelease selfstopmove labelbind bmotion selfonmotion def startmoveself event selfx eventx selfy eventy def stopmoveself event selfx none selfy none def onmotionselfevent x eventxroot selfx selflabelwinforootx selflabelwinforootx eventyroot selfy selflabelwinforooty selflabelwinforooty rootgeometryss x label labelroot text drag windowdraggablelabel labelpack rootmainloop you almost right compensate offset within label note example compensate window border you use specific tools figure example works perfectly using overrideredirect my guess coming another programming language i give tips i python end statements valid syntax reason method names either consistently looklikethis looklikethis variables need declared if want create instance variable init definitely outside method unless want class variable,first current code essential parts class windowdraggable x def initselflabel labelbind buttonpress selfstartmove labelbind buttonrelease selfstopmove labelbind bmotion selfonmotion def startmoveselfevent selfx eventx selfy eventy def stopmoveselfevent selfx none selfy none def onmotionselfevent deltax eventx selfx deltay eventy selfy selfx rootwinfox deltax selfy rootwinfoy deltay rootgeometrysxs selfxselfy root window root tk this i assign class label windowdraggablelabel all imports tkinter import pil import image imagetk import sys import what i trying accomplish make window draggable handle case label i really describe behaves move window simply following mouse please bear i total newcomer python any help appreciated a rewrite class okay i know really badly written,1 python style guide thing follow readable sensible thing that said suggest follow project styles official python styles use python styles something new python already namespacing feature language imports prefixes entirely needed in situation using prefixes bad means break whole ducktyping ideology python ideas object orientation you require user know using attributes added class originally concern make class work avoid extra stuff important know it object they use without caring implementation,i writing extension tkinter conflicted naming style i use new attributes i going add this first naming style giving new attributes prefix sw import tkinter tk class new tkbutton object def init self par tkbuttoninitself par attrnames attr attr attr attr name attrnames newname sw name setattrself newname none root tktk new newroot newpack newswattr rootmainloop for second naming style i made new attributes attributes sw class then i made instance sw attribute new class import tkinter tk class sw object def init self attrnames attr attr attr attr name attrnames setattrself name none class new tkbutton object def init self par tkbuttoninitself par selfsw sw root tktk new newroot newpack newswattr rootmainloop,2 when i i made list i needed embedded python application work i remember worked pythondll pythonxxdll work without external files visual c runtime dlls require sidebyside manifest see pd wiki page work if want import something need ship anything depends that means either pick part python standard libraries want pick there way need python standard libraries but i want live without os key ones but decision,my delphi program uses pythondelphi python script uses standard libs when deploying program i want entire python installation must work pythondll what minimal set necessary files the document pythondelphi dated clear thanks help,1 the struct module supports byte order specifiers format string httpdocspythonorglibrarystructhtmlbyteordersizeandalignment,i code i want host network float values amp u usrbinenv python import socket import sys struct x intsysargv intsysargv z sockethtonsintsysargv floatsysargv i want sockethtonf something similar htonl u floatsysargv sysstdoutwritestructpack bbhff xyztu note values arguments another text file i get values like pythonpy cat argsfile somewhere i really beginner python help really appreciated thank,1 you might find httpslmfitgithubiolmfitpy useful it allows upper lower bounds variable allows algebraic constraints parameters,i using optimizeleastsq fit data i would like constrain fitting parameters certain range is possible define bounds using optimizeleastsq bounds implemented optimizefminslsqp i prefer use optimizeleastsq,1 you cannot hide your program needs access hacker simply use tool like debugger virtual machine modified python implementation heshe really wants know api key i think necessary hide google maps api key anyway web page also source code api use you refer documentation page obtained key see private key,i using api key python code i looking distribute this api key google maps are security issues regards distributing api key best hide,1 it necessary google api key tied domain referrer checked used you read works relevant part note key httpwwwmygooglemapssitecom accepted site accessed using address it accepted site accessed ip address eg http hostname aliased wwwmygooglemapssitecom using dns cname record their version api require key httpcodegooglecomapismapsdocumentationjavascript,i using api key python code i looking distribute this api key google maps are security issues regards distributing api key best hide,3 most web frameworks try onestopshop webapplication needs varying degrees tight loose coupling that said python python web framework much stop using way just pick framework suits needs use existing libraries need a concrete answer require concrete question form how i x existing y z framework this happens i tried error message,i looking graceful way taking nonweb project based either sqlobject sqlalchemy overlay decent webframework i looked turbogears even though looks like something i could use models seems defined inside turbogears framework i want core functionality models code presenting layer turgbogears separated i need something take models already existing codebase help presenting data without much hassle,1 if want running total available want iterate league twice def pythagleague totalrunsscored team scores leagueiteritems stuff totalrunsscored scores stuff runs scored teams point print league running total runs scored f totalrunsscored outside loop total runs scored league last one loop print league total runs scored f totalrunsscored remember inside loop talking single team need sum get runs scored team instead need add runs scored previous teams scores previous iterations loop,i working python i list teams following dictionary nl phillies braves mets the first value list amount runs scored team second amount runs team given i using code determine pythagorean winning percentage team i would also like able function calculate total number runs scored allowed group whole right i using pythagleague team scores leagueiteritems runsscored floatscores runsallowed floatscores winpercentage runsscoredrunsscoredrunsallowed totalrunsscored sumscores team league print f team winpercentage print f league total totalrunsscored i sure exactly going sum function instead getting one value i getting different value iteration team winpercentage value ideally function would return one value sum runs scored team dictionary thanks help,2 the reason xterminalemulator spawns new process exits know executed command actually finishes to work around solution would modify command add another command notifies since apparently xterminalemulator ever executes one command use shell chain probably best way one would ossystem xterminalemulator installing new packages e sh c sudo tlmgr install touch tmpinstallcompleted packagesstring ospathexiststmpinstallcompleted timesleep osremovetmpinstallcompleted,edit final code goes something like warning command need escaped def spawninnewterminalcommand creates lock file lock openlockpath w lockwritecurrently performing task separate terminal lockclose adds line command remove lock file command rm lockpath executes command new terminal process subprocesspopen xterminalemulator e sh c formatcommand stdoutsubprocesspipe processwait let us proceed lock file removed bash command ospathexistslockpath timesleep original question i writing simple wrapper installs missing packages fly finally running lualatex it mostly works near end i run command sudo tlmgr install string packages furthermore guarantee latex editor allow user input i call new terminal enter sudo password i mostly figured either process subprocesspopen shlexsplit xterminalemulator installing new packages e sudo tlmgr install packagesstring stdoutsubprocesspipe retcode processwait ossystem xterminalemulator installing new packages e sudo tlmgr install packagesstring the problem line wait spawned terminal process done in fact continues next line running actual lualatex immediately user even enter password download packages from i understand sudo child process finishes right away is way make sure tlmgr process finishes continuing,2 do idea modules depend lxml if could simply check modules setuppy files check installrequires package creators include version number well eg installrequires djangomodeldict nexus djangojsonfield from httpsgithubcomdisqusgargoyleblobmastersetuppy you may also want look something like modulefinder i think simply checking setuppy much easier case,when i run pip install i get dependencies installed including transitive dependencies problem two modules depend two different versions lxml how i figure requiring pip tool,1 ols function takes entire independent data set second argument try olsy x x x though i suspect may need wrap numpy arrays x numpyndarray lenx x numpyarrayx x numpyarrayx x numpyarrayx olsy x,i using olspy code downloaded scipy cookbook download first paragraph bold ols i need understand rather using random data ols function multiple linear regression i specific dependent variable three explanatory variables every time i try put variables place random variables gives error typeerror constructor takes arguments can anyone help is possible here copy ols code i trying use along variables i trying input future import division scipy import c ones dot stats diff scipylinalg import inv solve det numpy import log pi sqrt square diagonal numpyrandom import randn seed import time class ols author vincent nijs email vnijs kelloggnorthwesternedu last modified mon jan cst dependencies see import statement top file doc class multivariate regression using ols input dependent variable yvarnm string variable label x independent variables note constant added default xvarnm string list variable labels independent variables output there values returned class summary provides printed output all measures accessed follows step create ols instance passing data class olsyxyvarnm xvarnm x x x x step get specific metrics to print coefficients print mb to print coefficients pvalues print mp tuition x research development x onenone parents x def initselfyxyvarnm xvarnm initializing ols class selfy selfx conesxshapex selfyvarnm yvarnm isinstancexvarnmlist selfxvarnm const listxvarnm else selfxvarnm const xvarnm estimate model using ols selfestimate def estimateself estimating coefficients basic stats selfinvxx invdotselfxtselfx xy dotselfxtselfy selfb dotselfinvxxxy estimate coefficients selfnobs selfyshape number observations selfncoef selfxshape number coef selfdfe selfnobs selfncoef degrees freedom error selfdfr selfncoef degrees freedom regression selfe selfy dotselfxselfb residuals selfsse dotselfeselfeselfdfe sse selfse sqrtdiagonalselfsseselfinvxx coef standard errors selft selfb selfse coef tstatistics selfp statstcdfabsselft selfdfe coef pvalues selfr selfevarselfyvar model rsquared selfradj selfrselfnobsselfnobsselfncoef adjusted rsquare selff selfrselfdfr selfrselfdfe model fstatistic selffpv statsfcdfselff selfdfr selfdfe fstatistic pvalue def dwself calculates durbinwaston statistic de diffselfe dw dotdede dotselfeselfe return dw def omniself omnibus test normality return statsnormaltestselfe def jbself calculate residual skewness kurtosis jb test normality calculate residual skewness kurtosis skew statsskewselfe kurtosis statskurtosisselfe calculate jarquebera test normality jb selfnobs squareskew squarekurtosis jbpv statschicdfjb return jb jbpv skew kurtosis def llself calculate model loglikelihood two information criteria model loglikelihood aic bic criterion values selfnobslogpi selfnobslogdotselfeselfeselfnobs aic llselfnobs selfncoefselfnobs bic llselfnobs selfncoeflogselfnobsselfnobs return aic bic def summaryself printing model output screen local time amp date timelocaltime extra stats aic bic selfll jb jbpv skew kurtosis selfjb omni omnipv selfomni printing output screen print n print dependent variable selfyvarnm print method least squares print date timestrftimea b yt print time timestrftimehmst print obs f selfnobs print variables f selfncoef print print variable coefficient std error tstatistic prob print rangelenselfxvarnm print f f f f tupleselfxvarnmiselfbiselfseiselftiselfpi print print models stats residual stats print print rsquared f durbinwatson stat f tupleselfr selfdw print adjusted rsquared f omnibus stat f tupleselfradj omni print fstatistic f probomnibus stat f tupleselff omnipv print prob fstatistic f jb stat f tupleselffpv jb print log likelihood f probjb f tuplell jbpv print aic criterion f skew f tupleaic skew print bic criterion f kurtosis f tuplebic kurtosis print name main testing ols class intercept added default olsyxyvarnm xvarnm x x x msummary,1 for kind thing might look pyramid it flexible enforce particular group components template database engine etc you could use either sqlobject sqlalchemy configure needs fortunately also well documented there pyramid recipes setting sqlalchemy well couple frameworks built top pyramid add preconfigured defaults include sqlalchemy akhet kufu,i looking graceful way taking nonweb project based either sqlobject sqlalchemy overlay decent webframework i looked turbogears even though looks like something i could use models seems defined inside turbogears framework i want core functionality models code presenting layer turgbogears separated i need something take models already existing codebase help presenting data without much hassle,2 not sure tags mean d match transportation openair azaz match last word noun ppoldpddpengdpdddpendazaz,i trying match word noun last group regex so far i tags motocykl mutka motorcycle bike moped transportation openair noun print research ppoldpddpengdpddpendd tagsgroup end all i get string last group transportation openair noun i need get noun update i forgot mention noun showing last word strings i running regex for example tags dåºwig crane noun construction vehicle tags trycykl tricycle child noun transportation any ideas single regex,1 it seems installed mysql python current version mysqlpython version supported mysql however try installing via activepython if install activepython default path open terminal run optactivepythonbinpypm install mysqlpython i similar case mysql python fedora platform worked well,reason i unable install mysqlpython package neither virtualenv main python install os x i getting following output downloadingunpacking mysqlpython running setuppy egginfo package mysqlpython warning files found matching manifest warning files found matching changelog warning files found matching gpl installing collected packages mysqlpython running setuppy install mysqlpython building mysql extension gcc fnostrictaliasing fnocommon dynamic dndebug g fwrapv os wall wstrictprototypes denabledtrace arch arch ppc arch x pipe dversioninfo final dversion iusrlocalcellarmysqlinclude isystemlibraryframeworkspythonframeworkversionsincludepython c mysqlc buildtempmacosxuniversalmysqlo g in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeofsizet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning havewcscoll redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpyconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeoftimet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition usrlibexecgccpowerpcappledarwinas assembler usrbinlibexecgccdarwinppcas usrbinlocallibexecgccdarwinppcas architecture ppc installed installed assemblers usrbinlibexecgccdarwinxas architecture x usrbinlibexecgccdarwinias architecture in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeofsizet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning havewcscoll redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpyconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeoftimet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition mysqlc fatal error error writing broken pipe compilation terminated in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeofsizet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning havewcscoll redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpyconfigh warning location previous definition lipo open input file varfoldersoooqsngeksdwcajzfbmktitmpccnabtsout no file directory error command gcc failed exit status complete output command usersjmalinasitesvirtualenvsmuckrackbinpython c import setuptoolsfile usersjmalinasitesvirtualenvsmuckrackbuildmysqlpythonsetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record varfoldersoooqsngeksdwcajzfbmktitmppipiobfrecordinstallrecordtxt installheaders usersjmalinasitesvirtualenvsmuckrackbinincludesitepython running install running build running buildpy copying mysqldbreleasepy buildlibmacosxuniversalmysqldb running buildext building mysql extension gcc fnostrictaliasing fnocommon dynamic dndebug g fwrapv os wall wstrictprototypes denabledtrace arch arch ppc arch x pipe dversioninfo final dversion iusrlocalcellarmysqlinclude isystemlibraryframeworkspythonframeworkversionsincludepython c mysqlc buildtempmacosxuniversalmysqlo g in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeofsizet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning havewcscoll redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpyconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeoftimet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition usrlibexecgccpowerpcappledarwinas assembler usrbinlibexecgccdarwinppcas usrbinlocallibexecgccdarwinppcas architecture ppc installed installed assemblers usrbinlibexecgccdarwinxas architecture x usrbinlibexecgccdarwinias architecture in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeofsizet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning havewcscoll redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpyconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeoftimet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition mysqlc fatal error error writing broken pipe compilation terminated in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning sizeofsizet redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpymacconfigh warning location previous definition in file included mysqlc usrlocalcellarmysqlincludemyconfigh warning havewcscoll redefined in file included systemlibraryframeworkspythonframeworkversionsincludepythonpythonh pymemcompath mysqlc systemlibraryframeworkspythonframeworkversionsincludepythonpyconfigh warning location previous definition lipo open input file varfoldersoooqsngeksdwcajzfbmktitmpccnabtsout no file directory error command gcc failed exit status command usersjmalinasitesvirtualenvsmuckrackbinpython c import setuptoolsfile usersjmalinasitesvirtualenvsmuckrackbuildmysqlpythonsetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record varfoldersoooqsngeksdwcajzfbmktitmppipiobfrecordinstallrecordtxt installheaders usersjmalinasitesvirtualenvsmuckrackbinincludesitepython failed error code,2 is taglist property list strings i gonna assume trying search tags i would use comma delimited list input instead space delimited also sure f try selfresponseoutwrite form namesearchform actionsearchhandler methodgetbr input typetext namesearchstring size input typesubmit valuesearch tags form handler class searchhandlerwebapprequesthandler def getself searchstring selfrequestgetsearchstring none searchstring raise exceptionmissing param tags tstrip searchstringsplit tags query mainall queryfiltertaglist in tags queryordertotalvalue handle results edit case make request method get instead post,i want change search results url searchhandler searchhandlersearchstringsearch string i redirect search results page how i this search form search selfresponseoutwrite form namesearchform actionsearchhandler methodpostbr input typetext namesearchstring size input typesubmit valuesearch tags form searchhandler class searchhandlerwebapprequesthandler def postself filternone fstriplistselfrequestgetsearchstringsplit n lens n query mainall queryfiltertaglist queryordertotalvalue fdisplayquery self update thanks mattotodd below solution according answer i changed form like searchstring selfresponseoutwrite form namesearchform actionsearchhandlersearchstrings methodget br input typetext namesearchstring size input typesubmit valuesearch tags form searchstring,1 this solution simple way getting class enumeration defined list annoying integer assignments enumerationpy import new def createclassname names return newclassobj classname object dicty x x enumeratenames examplepy import enumeration colors enumerationcreate colors red orange yellow green blue violet,i mainly c developer i currently working project python how i represent equivalent enum python,2 just fun two ways these assume strictly space every character want t h e e x w h i w n r e p l c e import pat recompiler joinrefindallpat the text i want replace even easier using string slicing the text i want replace,example t h e e x w h i w n r e p l c e i want result like the text i want replace i tried shell sed echo t h e e x w h i w n r e p l c e sed r sazazsgsed g successfully i know replace python could anybody help,1 from example looks like would simple building list just call function like crazyfunction abc edit just tested console def printfirstlst print lst printfirst hello h printfirst hello hello,i looking python way take string pass function list like word abc result crazyfunctioncastword crazyfunction receive list like word abc instead string the goal cast function parameter instead assignment call,1 anything domain name map whatever person configuring domain wants there guarantee url ending html refers real file filesystem somewhere return valid html anything else you arbitrarily decide count def directory part filename whatever floats boat choice equally correct,i actually using php crawling done programming languages it bit difficult cater lot situations please help look problem please give suggestion whether i going right direction what i know current url address i get list links href frame src what i current url address i firstly get root url example httpwwwabccomdef i get httpwwwabccom first this cater situation hreffffhtml i know root url first secondly i need get url directory current url little difficult i still idea get done perfectly for example httpwwwabccomdefxyzhtm url directory httpwwwabccomdef this cater situation hrefxyzhtml the problem i facing get current url directory for example current url httpwwwabccomdef i actually know def directory file if def file url directory would httpwwwabccom but def directory url directory would httpwwwabccomdef you say last would directory but point view i crawling webpage i really ensure webpage builder add end directory url a directory url perfect valid example def directory httpwwwabccomdef would probably stands httpwwwabccomdefindexhtml since hard know whether httpwwwabccomdef directory script file hard make full url relative href hrefxyzhtml am i complicating problem is solution there situations example href means anchor i append end current url is correct valid current url situation meaning valid situation current url httpwwwabccomdef def directory httpwwwabccomdefxyz converted httpwwwabccomdefindexhtmlxyz and hrefjavascript hrefvbscript etc i ignore and hrefxyz image file exe file anything valid html i ignore thanks the question might little messy i hope i explained clearly,2 if httpwwwabccomdef directory web server usually redirect httpwwwabccomdef order avoid confusing client you simply need notice redirect use urlparseurljoin appropriate function languageofchoice fuse two components together either case browser would,i actually using php crawling done programming languages it bit difficult cater lot situations please help look problem please give suggestion whether i going right direction what i know current url address i get list links href frame src what i current url address i firstly get root url example httpwwwabccomdef i get httpwwwabccom first this cater situation hreffffhtml i know root url first secondly i need get url directory current url little difficult i still idea get done perfectly for example httpwwwabccomdefxyzhtm url directory httpwwwabccomdef this cater situation hrefxyzhtml the problem i facing get current url directory for example current url httpwwwabccomdef i actually know def directory file if def file url directory would httpwwwabccom but def directory url directory would httpwwwabccomdef you say last would directory but point view i crawling webpage i really ensure webpage builder add end directory url a directory url perfect valid example def directory httpwwwabccomdef would probably stands httpwwwabccomdefindexhtml since hard know whether httpwwwabccomdef directory script file hard make full url relative href hrefxyzhtml am i complicating problem is solution there situations example href means anchor i append end current url is correct valid current url situation meaning valid situation current url httpwwwabccomdef def directory httpwwwabccomdefxyz converted httpwwwabccomdefindexhtmlxyz and hrefjavascript hrefvbscript etc i ignore and hrefxyz image file exe file anything valid html i ignore thanks the question might little messy i hope i explained clearly,1 update pythonpath include directory,the way im currently importing functions putting py files sitepackages directory calling using following command idle myfile import i cannot find sitepackages directory inside python ubuntu i need another way import thanks,1 webbrowseropen expecting character buffer fetchmany returns list so webbrowseropenx trick,i trying make app similar stumbleupon using python back end personal project from database i retrieve website name i open website webbrowseropenhttpwwwwebsitecom sounds pretty straight forward right problem when i try open website webbrowseropenwebsitecom returns following error file fetchallpy line module webbrowseropenx file usrlibpythonwebbrowserpy line open browseropenurl new autoraise file usrlibpythonwebbrowserpy line open arg selfargs typeerror expected character buffer object here code import sqlite import webbrowser conn sqliteconnectwebsitessqlite cur conncursor curexecuteselect website from column x curfetchmany webbrowseropenx edit okay thanks reply i receiving error showing url error stating file homeuseru httpbbccouk no file directory what going,1 you may get answer someone familiar pyramid problem pyramidrequest depends zopedeprecation installedavailable you elaborate much i tried installing zope using help be sure running pyramid python installation if case zopedeprecation package installed what get python c import zopedeprecation print import zopedeprecation,i trying build application using newish pyramid framework i new pyramid idea zope importance become apparent i followed basic tutorial i try run application i get traceback traceback recent call last file taskspy line module pyramidconfig import configurator file optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagespyramidpyeggpyramidinitpy line module pyramidrequest import request file optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagespyramidpyeggpyramidrequestpy line module zopedeprecation import deprecate importerror no module named deprecation i tried install pyramid using setuptools sudo easyinstall pyramid which among lot output included searching zopedeprecation reading httppypipythonorgsimplezopedeprecation best match zopedeprecation downloading httppypipythonorgpackagessourcezzopedeprecationzopedeprecationtargzmdedbaabeebfb processing zopedeprecationtargz running zopedeprecationsetuppy q bdistegg distdir tmpeasyinstallzilyjzopedeprecationeggdisttmpygfsor adding zopedeprecation easyinstallpth file which i thought cover i also tried installing zope via macports sudo port install zope sudo port install pyzopeinterface i also tried run sudo port load zope running script help i also tried downloading source httppypipythonorgpypizopeinterface building manually directory any ideas i wrong edit one guess setuptools installing zope components system default python framework enthought distribution default python environment one macports installed perhaps macports zope module components zopedeprecate,1 i would prefer import sys print running idle idlelibrun sysmodules else out idle,just title says i want write script behaves differently depending whether running inside console window idle is object exists running idle i check an environment variable i using python windows edit the answers given far work but i looking official way one look like hack if someone comes one i accept answer otherwise days i accept earliest answer thanks everyone,3 gstreamer uses gobject framework need run gobjectmainloop start message flow pipeline import gobject import gst pipeline gstparselaunch filesrc locationtestflac flacdec lame filesink locationtestmp pipelinesetstategststateplaying gobjectthreadsinit gobjectmainlooprun in second example also need run mainloop link pipeline elements eg elementlinkmany you connected source sink actual pipeline filesrc filesink here corrected code import gobject import gst converter gstpipeline converter source gstelementfactorymake filesrc filesource sourcesetproperty location testflac decoder gstelementfactorymake flacdec decoder encoder gstelementfactorymake lame encoder sink gstelementfactorymake filesink sink sinksetproperty location testmp converteraddsource decoder encoder sink gstelementlinkmanysource decoder encoder sink convertersetstategststateplaying gobjectthreadsinit gobjectmainlooprun,here command i trying replicate gstlaunch filesrc locationtestflac flacdec lame filesink locationtestmp when i run command works beautifully i tried replicate using pythong bindings luck i get errors either scripts work expected when i run script i get empty mp file import gst pipeline gstparselaunch filesrc locationtestflac flacdec lame filesink locationtestmp pipelinesetstategststateplaying when i run script i get corrupt mp file import gst converter gstpipeline converter source gstelementfactorymake filesrc filesource sourcesetproperty location testflac decoder gstelementfactorymake flacdec decoder encoder gstelementfactorymake lame encoder sink gstelementfactorymake filesink sink sinksetproperty location testmp converteraddsource decoder encoder sink sourcelinksink convertersetstategststateplaying anyone know i wrong,3 how import xmldomminidom minidom dom minidomparse testxml data dct domgetelementsbytagname dict keysdctgetelementsbytagname key keynextsibling integer string date element text node keynextsiblingfirstchild text node none valskeynextsiblingfirstchild key keys drill text inside keys vals keyskeyfirstchilddata key keys valsvaldata val else none val vals datadictzipkeysvals data track id printdata location break yields filelocalhostdmymusicenglishsongssecondstomarskingsandqueensmp,dict keykey dict keytrack idkeyintegerinteger keynamekeystringkings and queensstring keyartistkeystring seconds to marsstring keyalbum artistkeystring seconds marsstring keycomposerkeystringjared letostring keyalbumkeystringthis is warstring keygenrekeystringpopstring keykindkeystringmpeg audio filestring keysizekeyintegerinteger keytotal timekeyintegerinteger keytrack numberkeyintegerinteger keyyearkeyintegerinteger keydate modifiedkeydatetzdate keydate addedkeydatetzdate keybit ratekeyintegerinteger keysample ratekeyintegerinteger keycommentskeystring f ea a string keyplay countkeyintegerinteger keyplay datekeyintegerinteger keyplay date utckeydatetzdate keypersistent idkeystringbbdefcacstring keytrack typekeystringfilestring keylocationkeystringfilelocalhostdmymusicenglishsongssecondstomarskingsandqueensmpstring keyfile folder countkeyintegerinteger keylibrary folder countkeyintegerinteger dict i want use xmldomminidom package parse file selfdom xmldomminidomparseselffile selfname selfdomgetelementsbytagname dict print selfnamefirstchilddata this code seem work basically i want check value second child dict track i want get location track is way get dict node satisfies conditions,2 it could case something pyqt thread unsafe may could try using zeromq inproc ipc example,i developing python application uses cextension module i also developed the extension module heavy number crunching makes use openmp i recently adding gui components python application using pyqt however i show window application crashes window fully drawn the window shows shortly i able track problem when i compile numbercrunching cextension without openmp support window shows fine everything works i guess something threading stuff openmp qt has anyone ever made similar observation,1 to avoid split call twice every line i suggest following solution def parselogfname openfname f samples linestrip line freadlines linestartswith ints mapint linesplit line samples currents x x ints temperatures x x ints return currents temperatures,my file looks like a matrix i would like create list column one list correspond first element row mapping current second element maps temperature as shown better way make code look fancier def parselogfname f openfname r samples freadlines samples filterlambda x xstartswith samples printsamples current maplambda x intxsplit samples printcurrent temperature maplambda x intxsplit samples printtemperature return current temperature,1 this simple version would imo reasonable megabytes log file try minimize memory usage computing time parsing def parselogfname data mapint xsplit x openfname x return current current temp data temp current temp data,my file looks like a matrix i would like create list column one list correspond first element row mapping current second element maps temperature as shown better way make code look fancier def parselogfname f openfname r samples freadlines samples filterlambda x xstartswith samples printsamples current maplambda x intxsplit samples printcurrent temperature maplambda x intxsplit samples printtemperature return current temperature,1 pay attention naming variables if global integer fishmove method name two almost certainly interfere unexpected way try renaming method movefish sth,i project python pygtk i using following code create motion animation gtkimage inside gtkfixed def fishmove global fishmove fishmove fishmove fishmove fixedhabmovefish fishmove gobjecttimeoutadd fishmove however program comes without throwing errors image move what going btw fishmove starts,1 you could use comet solution like ape project this kind project designed send realtime data browser make use modern browsers web sockets feature,i need develop realtime recent activity feed django ajax longpolling i wondering best strategy serverside pseudocode def recentactivitypostsave notifyview view newactivity sleep return httpresponsenewactivity the first thing comes mind querying db every second not feasible other options using cache notification service using specialized tool like celery i rather seems like overkill what best way go,1 if read recv waiting one connection if multiple connections create multiple processes threads waste system resource with select poll epoll monitor multiple connections one thread get notified data available call read recv corresponding connection it may block infinitely block given time block depending arguments,i threaded asynchronous networking experiment python using udp i like understand polling select python module i never used cc what i kind understand little select block watching resource what purpose polling,3 this reimport module new import sys del sysmodules mymodule import mymodule,many python modules preserve internal state without defining classes eg logging maintains several loggers accessible via getlogger how test module using standard unittest tools i would like various tests inside testcase class reimport moduleundertest time loses context can done,2 import unittest import sys class testunittesttestcase def teardownself try del sysmodules logging except keyerror pass def testloggingself import logging loggingfoo def testloggingself import logging printloggingfoo name main unittestsysargvinsert verbose unittestmainargv unittestsysargv testpy testtestlogging passes testlogging maintest ok testpy testtestlogging testlogging maintest error since internal state logging reset,many python modules preserve internal state without defining classes eg logging maintains several loggers accessible via getlogger how test module using standard unittest tools i would like various tests inside testcase class reimport moduleundertest time loses context can done,3 finally solved and easy way as httpsdocsdjangoprojectcomendevtopicsindeployment says put locale files different localizations so i copy locale files djangoconf template folder this line pyexe setuppy copy compilation templates pyexedatafiles addpathtree templates the last thing set locale path settings file localepaths templateslocale,i compiled django application exe using pyexe but i idea make django translation work i mean built translation translation files there languagecode set settings file i also tried importing djangoutilstranslation djangoconflocalepl pyexe options includes i also tried i manage import lcmessage files djangoconflocalepl using datafiles pyexe setup i think lcmessage files main problem i know put compilation is possible change pyexe compiled project language how import language files my pyexe setup files similar httpmisunderstandingswordpresscomdjangodesktopapp edit i post code lines i trying import translation util djangoutilstranslation djangoconflocalepl i also tried djangoutilstranslationtransnull djangoutilstranslationtransreal djangoutilstranslationinit djangoconflocaleplinit djangoconflocaleplformats but i though matter in buildbdistwinamdwinexecollectdjango folders conflocale utilstranslation proper files but course lcmessage folder i try import using pyexedatafiles addpathtree pythonpath libsitepackagesdjangoconflocalepl as i checked finds files folder nothing my setup file long i put sourcepod httpwwwsourcepodcomfcmpkn maybe i forgot include something i idea could,1 i’m sure i understand question completely easy solution probably dictitems fees status pending,if i list keyvalue pair i get value key i working code snippet items fees status pending timeout hostel status pending timeout print itemsi itemskeys status pending timeout status pending timeout i expecting get timeout i know line wrong timeout itemsgeti put transaction item queue specific timeout period transactionqueuei block timeout def transactionqueueitem blockfalse timeout return queueputitem block timeout thanks helping i answer hours writing so answer key value itemsiteritems val value print formatval val status pending timeout status pending timeout thanks vincent vande vyvre,1 i want draw attention doppelganger answer question i error situation you trying import functionclass x module called say strategypy unfortunately also created python package directory called strategy words got directory called strategy least single file directory strategy called initpy root folder strategypy contains functionclass called x strategy initpy you forget fact created python package directory try import class function defined file strategypy root directory like strategy import x what get python error importerror cannot import name x error the actual problem doppelganger notes python interpretor gives precedence package directory created searches filemodule named x package directory ignores actual module strategypy functionclass x therein actually looking this exactly expect want read documentation python packages change mind halfway along like i may end scratching head,i seen many similar errors i see solution applies particular problem i trying use akismet module pythonpath i start interactive interpreter i run akismet import akismet docstring says i get following error akismet import akismet traceback recent call last file stdin line module importerror cannot import name akismet,3 declare dtype object nparraygf gf gf gf gf gf gf gf gfdtype object then type elements array gf for example typea class maingf,in cryptography project i deal gf arithmetic operations essentially sum operation field gf normal xor operation product operation ab ab mod mx you skip mathematics part my job inverse matrix x gf this difficult tedious reimplement every matrix operations hand i would like make use functionality inverse matrix numpy i able make numpy use operations items matrix say instead performing adding items using i want perform xor whenever operation used i created class customer type call gf the code found class gffloat def initself value selfvalue value def addself b isinstanceb gf return gfopsaddselfvalue bvalue else return gfopsaddselfvalue b rsub isub sub radd iadd add def mulself b isinstanceb gf return gfopsmulselfvalue bvalue else return gfopsmulselfvalue b rmul imul mul def divself b return selfmulselfinvb rdiv idiv div def invself return gfopsinvselfvalue def floatself return self and i create matrix gf items using arraygf gf gf gf gf gf gf gf gf it appears float cast function used rest touched please help make operation overriding work thanks lot edit performing basic matrix operation already ok if somebody could make work matrix inversion i would really appreciate thanks,1 sipdeletepage kill page object stopping execution delete reference page python del page you might also want check subclassing webpage reimplementing shouldinterruptjavascript perhaps killing page executes,webviewcrashpy import sys pyqtqtgui import pyqtqtcore import pyqtqtwebkit import app qapplicationsysargv view qwebview viewsettingssetattributeqwebsettingsjavascriptenabled true viewloadqurl infiniteloophtml viewshow appexec infiniteloophtml script whiletrue documentwrite infinite loop script i want fix python code without touching javascript can i kill javascript somehow edit both files local,1 note call package package distribution a distribution contain zero modules modules packages that means onetoone mapping distributions packages i sure way detect modules packages installed distribution actually installing introspect filesystem changes newly added packages modules pth files,i wonder reliable consistant way get python package import name namespace for example package djangohaystack import name haystack package ipython import name ipython so far i know pypi store information i checked pypixmlrpc i also tried automate download package extract dig egginfo packages folder any help appreciated used goodmanner gadget,1 almost you shift a half number digits shift of course efficient base power since shifting base example done multiplications edit well ok multiply shifts additions but ever much simpler power if using python greater counting bits easy introduced intbitlength method for versions python count bits copying a shifting right this done olog n time n digits sort binary search method shift many bits many etc,i want implement karatsuba split multiplication python however writing numbers form acxd x power base let xbm close sqrta how i supposed find x i even use division multiplication should i count number digits shift a left half number digits thanks,2 i feeling django cache versioning support new django it allows set systemwide variable version cache explicitly set creating record cachesetmykey true version with method need update cache simply version clear,one common pattern caching django use current site id cache key order essence namespace keys the problem i i love able delete values cache namespace eg delete cache values site made fundamental change the current pattern dealing send signals place etc i used siteid cache key example common pattern others may recognize way i using cache custom multitenant application makes problem even profound question is cache backend andor pattern works well deleting objects namespaced way pseudonamespaced way extraordinarily expensive ie looping possible cache keys given namespace deleting cache i would prefer use memecached open solution works well plugin,1 yes thumbnail method needed one thing mentioned posts topic size must either list tuple so resize maximum dimension pixels would call imagethumbnail imageantialias see also post subject how i resize image using pil maintain aspect ratio,does pil resize exact dimensions i give matter or try keep aspect ratio i give something like imageantialias argument,1 you already accepted answer since i started writing what tom said python x get n intbitlength directly in python x get n ologa time binarysearch like here x code calculates let base exponent x n ie x n first get n binarysearch shifting really needed n one unnecessary last iteration then know n getting xcd easy still using division def karatsubaforman binarysearch karatsuba form using binary shifts first search n loga step n step c a n print nd stepd cd nstepc c n step else n step more concisely could say n nstep c else nstep step then take x n ëœ sqrta ndiv n find karatsuba form c a ndiv x ndiv a c ndiv return xcd,i want implement karatsuba split multiplication python however writing numbers form acxd x power base let xbm close sqrta how i supposed find x i even use division multiplication should i count number digits shift a left half number digits thanks,2 you reading bytes data,i newbie objectoriented design i try incorporate python function init function works i asked earlier here code import struct import urllib import stringio class wallpaper def initself url selfurl url selfcontenttype selfheight selfwidth image urlliburlopenselfurl data strimageread datastartswith selfcontenttype imagejpeg jpeg stringiostringiodata jpegread b jpegread try b ordb xda ordb xff b jpegread ordb xff b jpegread ordb xc ordb xc jpegread h w structunpackhh jpegread break else jpegreadintstructunpackh jpegread b jpegread selfwidth intw selfheight inth except structerror pass except valueerror pass x wallpaper httpiimgurcomrapwxjpg print xurl xcontenttypet xheightt xwidth the problem i cannot initialize height width properties equal where problem edit i found problem solution thanks hints one question approach proper far oop rules concerned should i compute widthheight init create method eg size,2 it difficult determine problem simply ignore exceptions except structerror pass except valueerror pass at least print error messages except structerror exc print strexc except valueerror exc print strexc this way able debug code thus solve problem of course i assume indentation correct actual code,i newbie objectoriented design i try incorporate python function init function works i asked earlier here code import struct import urllib import stringio class wallpaper def initself url selfurl url selfcontenttype selfheight selfwidth image urlliburlopenselfurl data strimageread datastartswith selfcontenttype imagejpeg jpeg stringiostringiodata jpegread b jpegread try b ordb xda ordb xff b jpegread ordb xff b jpegread ordb xc ordb xc jpegread h w structunpackhh jpegread break else jpegreadintstructunpackh jpegread b jpegread selfwidth intw selfheight inth except structerror pass except valueerror pass x wallpaper httpiimgurcomrapwxjpg print xurl xcontenttypet xheightt xwidth the problem i cannot initialize height width properties equal where problem edit i found problem solution thanks hints one question approach proper far oop rules concerned should i compute widthheight init create method eg size,1 if condition ordb xc ordb xc true first iteration outer break loop assigning selfwidth selfheight maybe meant indent two assignments one level less code,i newbie objectoriented design i try incorporate python function init function works i asked earlier here code import struct import urllib import stringio class wallpaper def initself url selfurl url selfcontenttype selfheight selfwidth image urlliburlopenselfurl data strimageread datastartswith selfcontenttype imagejpeg jpeg stringiostringiodata jpegread b jpegread try b ordb xda ordb xff b jpegread ordb xff b jpegread ordb xc ordb xc jpegread h w structunpackhh jpegread break else jpegreadintstructunpackh jpegread b jpegread selfwidth intw selfheight inth except structerror pass except valueerror pass x wallpaper httpiimgurcomrapwxjpg print xurl xcontenttypet xheightt xwidth the problem i cannot initialize height width properties equal where problem edit i found problem solution thanks hints one question approach proper far oop rules concerned should i compute widthheight init create method eg size,1 does seem sensible way organizing classes yes seems remember lineitem ispartof account account part journal there inheritance relationships around collection accounts journal collection lineitem account the issue i see naming you say class lineitem later lineitem transaction maybe give moment thought why name transaction would need yo clarify class named transaction anyway needs application change time grow time probably need worry adapt future needs instead requirements clear your second question i adding method look transactions runtime specified startdate enddate the best way might store startdate enddate somewhere modify account change methods receive startdate enddate parameters examine lineitem dates totaling listing linetimes are approaches i considering pay attention fact used word transaction you must store date attribute lineitem objects i think sensible approach if want change lookup methods constantly order track possible attributes search consider creating options class store search parameters storing attributes need future hope helps,i writing expense tracking program at moment i three class lineitem stores attributes individual transactions methods format transaction output payee amount date etc each lineitem one transaction account collection lineitems methods add lineitem list lineitems determine value lineitems etc journal collection accounts methods add new account list accounts format list accounts etc does seem sensible way organizing classes i adding method look transactions runtime specified startdate enddate the best way might store startdate enddate somewhere modify account change methods receive startdate enddate parameters examine lineitem dates totaling listing linetimes are approaches i considering edit method accounts implement date check selflineitems list lineitems startdate enddate set runtime may set may set def getlineitemsself startdate enddate startdate enddate lineitem selflineitems startdate lineitemdate enddate yield lineitem else lineitem selflineitems yield lineitem,1 paramvaluesget used since already used paramvalues read value ie instead paramvaluesgetparamvaluesgroupphones use paramvaluesgroupphones you use get instead addition want default value case key exist case necessary,i trying create list input corresponding values accessing global nested dictionary here code import sys paramvalues vowels aa ae ah ao eh er ey ih iy uh uw consonants b ch dh dx f g hh jh k l n ng p r sh th v w z zh diphthong aw ao uw ay ao ih ow aa oy ih print usage python copy phonemefile def coartphonemefile function generating parameter values global list phonemelist opensyllabifiedphonemestxt r pfile line pfile l linesplit phoneme l nextphoneme diphthonggetphoneme nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgetparamvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgetparamvaluesgroupphones phoneme nextphoneme print new list print n joinstrl l phonemelist the input file syllabifiedphonemestxt following contents aa ih k l eh k aa n ih g eh l v ae n ih k aa p l ay k the ifelse statement right far i see i got following error traceback recent call last file copy line module coartsyllabifiedphonemestxt file copy line coart phonemelistappendphones paramvaluesgetparamvaluesgroupphones typeerror unhashable type list i changed ifelse statement following got rid error nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgroupphones phoneme nextphoneme but i got output huge list i presume program iterates dict many times prints whole dict instead displaying values given input could someone point i wrong thank,1 here paramvaluesgetparamvalues vowels aa but problem paramvalues vowels aa returns list trying get value map using list unhashable use key map i believe trying get paramvalues vowels aa returns try python console find error check what dictionary key strings dictionary keys mydict doghund rhinocerosnashorn integers dictionary keys the following dictionary somewhat redundantly maps prime numbers rank eg first prime number primenums floating point numbers dictionary keys well mydict pi e mydict pi’ lists cannot dictionary keys mydict wontwork traceback recent call last file stdin line module typeerror unhashable type list more info ok first try iterating dict using following code k v dictitems k key v value pass it make code cleaner maybe solve problem,i trying create list input corresponding values accessing global nested dictionary here code import sys paramvalues vowels aa ae ah ao eh er ey ih iy uh uw consonants b ch dh dx f g hh jh k l n ng p r sh th v w z zh diphthong aw ao uw ay ao ih ow aa oy ih print usage python copy phonemefile def coartphonemefile function generating parameter values global list phonemelist opensyllabifiedphonemestxt r pfile line pfile l linesplit phoneme l nextphoneme diphthonggetphoneme nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgetparamvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgetparamvaluesgroupphones phoneme nextphoneme print new list print n joinstrl l phonemelist the input file syllabifiedphonemestxt following contents aa ih k l eh k aa n ih g eh l v ae n ih k aa p l ay k the ifelse statement right far i see i got following error traceback recent call last file copy line module coartsyllabifiedphonemestxt file copy line coart phonemelistappendphones paramvaluesgetparamvaluesgroupphones typeerror unhashable type list i changed ifelse statement following got rid error nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgroupphones phoneme nextphoneme but i got output huge list i presume program iterates dict many times prints whole dict instead displaying values given input could someone point i wrong thank,1 try something like it much simpler much efficient i think import sys paramvalues aa ae ah ao eh er ey ih iy uh uw b ch dh dx f g hh jh k l n ng p r sh th v w z zh diphthong aw ao uw ay ao ih ow aa oy ih phonemelist opensyllabifiedphonemestxt r pfile line pfile l linesplit phoneme l phoneme nextphoneme diphthonggetphoneme nextphoneme none exploring dict paramvalues extracting nested dict phonemelistappendphoneme paramvaluesphoneme else phonemelistextendphoneme paramvaluesphoneme phoneme nextphoneme print new list print n joinstrl l phonemelist if need consonantvowel information better storing somewhere else storing complicates code much note i took function testing purposes obviously put back code,i trying create list input corresponding values accessing global nested dictionary here code import sys paramvalues vowels aa ae ah ao eh er ey ih iy uh uw consonants b ch dh dx f g hh jh k l n ng p r sh th v w z zh diphthong aw ao uw ay ao ih ow aa oy ih print usage python copy phonemefile def coartphonemefile function generating parameter values global list phonemelist opensyllabifiedphonemestxt r pfile line pfile l linesplit phoneme l nextphoneme diphthonggetphoneme nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgetparamvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgetparamvaluesgroupphones phoneme nextphoneme print new list print n joinstrl l phonemelist the input file syllabifiedphonemestxt following contents aa ih k l eh k aa n ih g eh l v ae n ih k aa p l ay k the ifelse statement right far i see i got following error traceback recent call last file copy line module coartsyllabifiedphonemestxt file copy line coart phonemelistappendphones paramvaluesgetparamvaluesgroupphones typeerror unhashable type list i changed ifelse statement following got rid error nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgroupphones phoneme nextphoneme but i got output huge list i presume program iterates dict many times prints whole dict instead displaying values given input could someone point i wrong thank,1 this reply current new code version snippet nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgroupphones phoneme nextphoneme if i understand correctly goal i think want written nextphonemes diphthonggetphoneme phoneme nextphoneme nextphonemes exploring dict paramvalues extracting nested dict groupval paramvaluesitervalues groupval refers values associated vowels consonants nextphoneme groupval phonemelistappendnextphoneme groupvalnextphoneme break once found next phoneme need look,i trying create list input corresponding values accessing global nested dictionary here code import sys paramvalues vowels aa ae ah ao eh er ey ih iy uh uw consonants b ch dh dx f g hh jh k l n ng p r sh th v w z zh diphthong aw ao uw ay ao ih ow aa oy ih print usage python copy phonemefile def coartphonemefile function generating parameter values global list phonemelist opensyllabifiedphonemestxt r pfile line pfile l linesplit phoneme l nextphoneme diphthonggetphoneme nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgetparamvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgetparamvaluesgroupphones phoneme nextphoneme print new list print n joinstrl l phonemelist the input file syllabifiedphonemestxt following contents aa ih k l eh k aa n ih g eh l v ae n ih k aa p l ay k the ifelse statement right far i see i got following error traceback recent call last file copy line module coartsyllabifiedphonemestxt file copy line coart phonemelistappendphones paramvaluesgetparamvaluesgroupphones typeerror unhashable type list i changed ifelse statement following got rid error nextphoneme none exploring dict paramvalues extracting nested dict group paramvalueskeys group refers vowels consonants iterate nested dict phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistappendphones paramvaluesgroupphones else group paramvalueskeys group refers vowels consonants phones paramvaluesgroupkeys phones refers phonemes present inside group phonemelistextendphones paramvaluesgroupphones phoneme nextphoneme but i got output huge list i presume program iterates dict many times prints whole dict instead displaying values given input could someone point i wrong thank,1 if attempting combine figures ie make image you use import matplotlibpyplot plt pltfigure pltimshowim cmapcmbone pltimshowim cmapcmjetalpha pltshow issue colorbars relative colormap call imshow import matplotlibpyplot plt pltfigure pltimshowim cmapcmbone cbar pltcolorbarorientation horizontal cbarsetlabel title unit pltimshowim cmapcmjetalpha cbar pltcolorbar cbarsetlabel title unit pltshow,i want display images using different color maps different figures following code displays image two different windows color map import scipymisc pylab import scipymiscimread lenajpg figure image meanaaxis imshowimage i call show one window displayed gray change default colormap gray figure imshowimage show i wondering anyone please help thanks lot,1 you say line giving error using python gives float result use integer,when i try make shape using variables i keep getting error message typeerror integer argument expected got float import pygameview import pygame sys pygamelocals import import random pygameinit barrel pygameimageloadimagesbarrelgif barrelcreate barrelx screengetheight barrelgetheight barrely screengetwidth barrelgetwidth barrelexist explosiondelay running barrelexist barrelcreate barrely barrelx randomrandint barrelexist barrelexist barrely barrely barrely barrelexist explosiondelay pygamedrawcirclescreen barrelx barrely explosiondelay explosiondelay explosiondelay explosiondelay the explosiondelay barrel shot,1 you getset active row currentindex setcurrentindex functions find qtreeview qitemselectionmodel latter returned qtreeviewselectionmodel and despite name qitemselectionmodel handles view current item view selection independently,is way get change active row qtreeview qtreewidget by active i mean row focus highlight selected row in paint event i use qstylestatehasfocus get active row seem work elsewhere,2 i something like unfortunately easy way the best i could come render form parse result beautifulsoup get values inputs selects something like beautifulsoup import beautifulsoup myform myform renderedform myformasp soup beautifulsouprenderedform values input soupfindall input value inputget value value valuesinput name value select soupfindall select selected selectfindselected selected selected valuesselect name selected value,i writing tests forms django these forms change quite often i trying avoid hardcoding form parameters tests every time form would change i modify tests well i quite forms nature i mainly testing information stored properly correct tables without really bothering form field using django testclient way i could fetch page form post back default form field values filed i googled around avail an help guys thanks,1 barrely barrely barrely must float point line i think pygamedrawcirclescreen intbarrelx intbarrely round variables integers function requires,when i try make shape using variables i keep getting error message typeerror integer argument expected got float import pygameview import pygame sys pygamelocals import import random pygameinit barrel pygameimageloadimagesbarrelgif barrelcreate barrelx screengetheight barrelgetheight barrely screengetwidth barrelgetwidth barrelexist explosiondelay running barrelexist barrelcreate barrely barrelx randomrandint barrelexist barrelexist barrely barrely barrely barrelexist explosiondelay pygamedrawcirclescreen barrelx barrely explosiondelay explosiondelay explosiondelay explosiondelay the explosiondelay barrel shot,3 okay i nailed i followed advice set custom error message validation so i code def initself args kwargs superinternapplicationform selfinitargs kwargs field selffieldsvalues fielderrormessages required set required field validation message fields when error different invalid noninteger django looked dictionary i supplied—and guess keyerror because message invalid fault so fix fielderrormessages required invalid that number sir possibly error message keys,i code view def addinternrequest requestmethod post form internapplicationformrequestpost formisvalid formsave form internapplicationform else form internapplicationform return rendertoresponse applicationhtml form form contextinstance requestcontextrequest the form modelform underlying model contains integerfield when i post form empty value validation message displayed fine when i post form noninteger value i get keyerror invalid it kind surprises code seems crash isvalid call i assumed safe ie return false problem crash how i fix stacktrace django version python version file usrlocallibpythondistpackagesdjangopyeggdjangocorehandlersbasepy getresponse response callbackrequest callbackargs callbackkwargs file homedanwwwintsbackendviewspy addintern formisvalid file usrlocallibpythondistpackagesdjangopyeggdjangoformsformspy isvalid return selfisbound boolselferrors file usrlocallibpythondistpackagesdjangopyeggdjangoformsformspy geterrors selffullclean file usrlocallibpythondistpackagesdjangopyeggdjangoformsformspy fullclean selfcleanfields file usrlocallibpythondistpackagesdjangopyeggdjangoformsformspy cleanfields value fieldcleanvalue file usrlocallibpythondistpackagesdjangopyeggdjangoformsfieldspy clean value selftopythonvalue file usrlocallibpythondistpackagesdjangopyeggdjangoformsfieldspy topython raise validationerrorselferrormessages invalid exception type keyerror exception value invalid,2 i solved i needed add line return true end function here fixed code it works def fishmove global fishmove fishmove fishmove fishmove fixedhabmovefish fishmove return true gobjecttimeoutadd fishmove,i project python pygtk i using following code create motion animation gtkimage inside gtkfixed def fishmove global fishmove fishmove fishmove fishmove fixedhabmovefish fishmove gobjecttimeoutadd fishmove however program comes without throwing errors image move what going btw fishmove starts,1 if multiple processorscores could take look multiprocessing module running simulations time might bit expensive though you probably run simulations rate one per core time you could use queue module work process pool here mini sample could look like tested multiprocessing import process queue def runsimulationsimulations results simulationsqsize simulationparams simulationsget run simulation resultsputsimulationresult simulationstaskdone name main simulationstorun queue simulationstorunput simulation parameters go dict add simulations one per line could done loop list dicts results queue range number processes want run p processtargetrunsimulation argssimulationstorun results pstart simulationstorunjoin results shoud results queue httpdocspythonorglibrarymultiprocessinghtml,i large set simple simulations i need run i wondering done simultaneously let describe situation i draws prevalence diseases draws corresponding disability weights diseases bad disease scalefor agegroups the simulation i need determine given set prevalences many people would different combinations diseases here input data would look like diseases future import division import numpy np diseasenumber nparray age nparray prevalence nprandomuniform disabilityweight nprandomuniform a simulation single draw would look something like age draw prevdraw prevalenceage disabilitydraw disabilityweightage simulation nprandombinomial prevdraw prevdrawshape then calculate disability weight attributable disease given comorbidity multiple diseases i following set denominator sum present disability weights use disability weight given disease numerator for disease denom npsumdisabilitydrawsimulaiton denomdenom numerator disabilitydrawsimulation adjusteddw npsumnumeratordenom i would need adjusted dw calculation seperately disease is way simulations simultaneously any help appreciated i fairly new python descriptions helpful,2 tuple unpacking b print print b print next and function function,i still python newb i working pyneurgen neural network tutorial i fully understand loop used create input data works instance position target populationgenpopulation pos floatposition allinputsappendrandomrandom pos factor alltargetsappendtarget what loop iterating exactly i come across use comma function loop thanks advance help,2 the function populationgen returning list tuples unpacked automatically variable names using syntax so basically getting something like following return value function pos target pos target given example loop first iteration variables position target values position pos target target in second iteration position pos target target,i still python newb i working pyneurgen neural network tutorial i fully understand loop used create input data works instance position target populationgenpopulation pos floatposition allinputsappendrandomrandom pos factor alltargetsappendtarget what loop iterating exactly i come across use comma function loop thanks advance help,3 the function either returns sequence serves something called generator spits successive elements sequence caller iterate this question concerning yield keyword thorough discussion work as comma since function apparently returns twotuple commaseparated list names convenient way name individual elements tuple without unpack,i still python newb i working pyneurgen neural network tutorial i fully understand loop used create input data works instance position target populationgenpopulation pos floatposition allinputsappendrandomrandom pos factor alltargetsappendtarget what loop iterating exactly i come across use comma function loop thanks advance help,2 it called tuple unpacking the populationgen generator function yields tuples containing exactly two elements in python assign several variables tuples like b so loop directly put two tuple values current iteration item two variables position target,i still python newb i working pyneurgen neural network tutorial i fully understand loop used create input data works instance position target populationgenpopulation pos floatposition allinputsappendrandomrandom pos factor alltargetsappendtarget what loop iterating exactly i come across use comma function loop thanks advance help,1 answer question code def parityx k x k k amp return k benefit depending bit length number faster eg takes usec takes usec loop depends number ones ie population count number number bits,is xor bit reduction operand function python i problem write reason write every script already builtin rxamp xrange rrxiamp,2 basically asking number x even odd asking parity x the solution gave indeed naive solution horribly inefficient compared methods here site excellent solutions bitrelated problems bit twiddling hacks the solutions given c hard translate python,is xor bit reduction operand function python i problem write reason write every script already builtin rxamp xrange rrxiamp,1 if mind using external module could use bitstring count method if want concise python expression try r summapint formatx b amp,is xor bit reduction operand function python i problem write reason write every script already builtin rxamp xrange rrxiamp,1 try call flush stdout print import sys sysstdoutflush or use command line option u force stdin stdout stderr totally unbuffered,i recently switched os using newer python on old system i used able print instantaneously for instance suppose i computationally intense loop range huge calculation print code completed iteration would print however current system python seems cache stdout terminal blank several minutes prints short succession then minutes prints how i make python print soon reaches print statement,2 strptime inverse strftime datetimedatetimestrptimefebruary bmonth,is way convert string containing month name integer dependent current locale i know somedatestrftimeb convert date time object string containing month name according current locale way go backwards,3 i see two separate problems keeping track python modules need project keeping track dynamic libraries need python modules project for first problem i found buildout good help althought takes litle grasp in case i would start creating directory new project i would go directory download bootstrappy wget httppythondistributeorgbootstrappy i would create buildoutcfg file buildout parts qrproject python eggs pyqrencode qrproject recipe zcrecipescripts eggs buildouteggs entrypoints qrprojectqrprojectmodulerun extrapaths buildoutdirectory this simple way creating interpreter access eggs modules project uses python recipe zcrecipescripts interpreter python eggs buildouteggs extrapaths buildoutdirectory in buildoutcfg i referencing module qrprojectmodule entrypoints qrproject this create binqrproject runs function run module qrprojectmodule so i also create file qrprojectmodulepy import qrencode def run print entry point qrproject happily imports qrencode module now time run bootstrappy python binary want use python bootstrappy then run generated binbuildout binbuildout this create two additional binaries bin directory binqrproject binpython the former project main binary it created automatically time run buildout modules eggs want loaded the second simply convenient way get python prompt modules eggs loaded easy debugging the fine thing binbuildout automatically install python eggs eggs case pyqrencode specified dependencies actually probably get compilation error step run binbuildout this need address problem all dynamic libraries available system on linux usually best get help packaging system i going assume using debian derivate ubuntu the pyqrencode web site specifies need libqrencode library pyqrencode work so i used package manager search aptcache search libqrencode libqrencodedev qr code encoding library development libqrencode qr code encoding library qrencode qr code encoder png image in case i want dev package installs linkable libraries header files required compile python cmodules also dependency system package manager make sure i install libqrencodedev i also get libqrencode required runtime ie compilation module so i install package sudo aptget install libqrencodedev once completed rerun binbuildout pyqrencode module hopefully compile install successfully now try run binqrproject binqrproject entry point qrproject happily imports qrencode module success so summary use buildout automatically download install python moduleseggs need project use system package manager install dynamic c libraries required python modules use be aware many cases already packaged versions python modules available package system for example pil available installing pythonimaging package ubuntu in case need install via buildout need worry libraries available package manager install dependencies required module run doing via buildout however make easier distribute project make run systems,due lack support libraries i want use i moved python development windows linux development i spent day messing getting nowhere dependencies the question whenever i pick linux i usually run kind dependency issue usually development libraries whether installed via aptget easyinstall pip i waste days simple tasks spending longer getting libraries work writing code where i learn strategy dealing kind issues rather aimlessly googling someone come across problem an example just one example i wanted generate qr codes so i thought i use githubcombitlypyqrencode based pyqrcodesourceforgenet supposedly without java dependencies there others pyqrnative githubcomarachnidpyqrencode one seemed like best bet needs so i found package pypi thought using would make life easier i perhaps made life difficult using virtualenv keep things neat tidy myenvmatubuntumyenv binpip install pyqrencode downloadingunpacking pyqrencode downloading pyqrencodetargz running setuppy egginfo package pyqrencode installing collected packages pyqrencode running setuppy install pyqrencode building qrencode extension gcc pthread fnostrictaliasing dndebug g fwrapv o wall wstrictprototypes fpic iusrincludepython c qrencodec buildtemplinuxiqrencodeo gcc pthread shared wlo wlbsymbolicfunctions wlbsymbolicfunctions buildtemplinuxiqrencodeo lqrencode buildliblinuxiqrencodeso successfully installed pyqrencode cleaning i guess i probably sudo aptget install libqrencodedev point prior so i tried run test script myenvmatubuntumyenv python testqrpy traceback recent call last file testqrpy line module qrencode import encoder file qrencodepyx line init qrencode qrencodec importerror no module named imageops well investigations revealed imageops appears part pil myenvmatubuntumyenv pip install pil downloadingunpacking pil downloading piltargz kb kb downloaded operation cancelled user storing complete log homematpippiplog myenvmatubuntumyenv binpip install pil downloadingunpacking pil downloading piltargz kb kb downloaded running setuppy egginfo package pil warning valid package name please use onlyseparated package names setuppy installing collected packages pil running setuppy install pil warning valid package name please use onlyseparated package names setuppy building imaging extension gcc building imagingmath extension gcc pil setup summary version platform linux r apr gcc tkinter support available jpeg support available zlib pngzip support available freetype support available littlecms support available to add missing option make sure required library set corresponding root variable setuppy script to check build run selftestpy script successfully installed pil cleaning hmm pil installed picked libraries i installed sudo aptget install libjpeg libjpegdev libpngdev zlibg zlibgdev earlier i sure tell pip feed library locations setuppy googling suggests variety ideas i tried none seem help much send round circles ubuntu installing pil virtualenv pip suggests using pillow package instead let try myenvmatubuntumyenv pip install pillow downloadingunpacking pillow downloading pillowzip kb kb downloaded running setuppy egginfo package pillow installing collected packages pillow running setuppy install pillow building imaging extension gcc setup summary pillow pil version platform linux r apr gcc tkinter support available jpeg support available zlib pngzip support available freetype support available littlecms support available to add missing option make sure required library set corresponding root variable setuppy script to check build run selftestpy script successfully installed pillow cleaning well seem jpeg png support time yay myenvmatubuntumyenv python testqrpy traceback recent call last file testqrpy line module qrencode import encoder file qrencodepyx line init qrencode qrencodec importerror no module named imageops still imageops though now i stumped imageops missing pillow different problem also pil,3 two somewhat easy ways x ytt xreshape numpy broadcasting powerful feature exactly want automatically expects last axis axes arrays shape first axes thus need transpose work the second option treated placeholder array size reduces typing,i encountering annoying shape mismatch issue i working arrays length one width one for example import numpy np x npones npones xy valueerror shape mismatch objects cannot broadcast single shape the simple solution yxreshapexshape however i often end subsetting one column array designate reshape is way avoid,3 import new printasfunction python x future import printfunction put statement top scriptmodule this allows replace new print function def prints end n filesysstdout filewrites end fileflush the advantage way script work upgrade one day python x ps i try printasfunction might flush default ps might also interested progressbar example,i recently switched os using newer python on old system i used able print instantaneously for instance suppose i computationally intense loop range huge calculation print code completed iteration would print however current system python seems cache stdout terminal blank several minutes prints short succession then minutes prints how i make python print soon reaches print statement,1 import numpy np nparray foo,this homework simply example complex problem right i take arrays create vectors use equation vectors inputs everything works fine but wondering i could skip vector creation use array slicing samething import numpy np npasarraylista npfloat x npasarraya npfloat npasarraya npfloat foo xyy print foo,3 the definition percentile i usually see expects result value supplied list p percent values found to get use simpler function def percentilen p find percentile list values parameter n a list values n must sorted parameter p a float value return the percentile values n introundp lenn return nn a b print percentilea p print percentilea p print percentileb p print percentileb p if would rather get value supplied list p percent values found use simple modification def percentilen p n introundp lenn n return nn else return,is convenient way calculate percentiles sequence singledimensional numpy array i looking something similar excel percentile function i looked numpy statistics reference find all i could find median th percentile something specific,3 if talk classes queue module following api way detect queue contains given object,a producer thread queries data store puts objects queue each consumer threads pull object shared queue long call external service when call returns consumer marks object completed my problem i basically wait queue empty producer add else i risk getting duplicates sent edit someone asked good question irc i figured i would add answer the question why producers produce duplicates the answer basically producer produces duplicates track sending state object sent unsent is way i check duplicates queue,1 every linear reccurence equation solve directly in fibonacci case equation fn fn fn f f the solution fn sqrt sqrtn sqrt sqrtn use direct formula for get look linear reccurence equation solving eg because floating point errors round result nearest integer,i recently programming question preinterview certain company the questions create django app test driven course display fibonacci sequence world the app take index number display resulting fibonacci sequence additionally page shows recent generated sequences also fibonacci bit impatient doesn’t want wait around forever make sure take steps make sure webserver runs efficiently i came following djangoviewsgenericsimple import directtotemplate djangohttp import http largestsequence largest latest def fibn calculate nth fibonacci sequence global largest n largest n largest next largestsequencelargest largestsequencelargest print appending next largestsequenceappendnext largest return largestsequence else return largestsequencen def latestrequest results n latest result fibn resultsappendnresult return directtotemplaterequest latesthtml results results def indexrequest requestmethodpost try nintrequestpostget n except return http result fibn lenlatest latestpop latestinsertn else result none return directtotemplaterequest basehtml result result the latest view nd version st version work consistently the original version stored result index latest latest originally list fib sequences lists instead list recent values n i guess main question bad store largest fib sequence generated runtime viewspy file i know persistent instructions never really gave details things done what guys think would approached problem thanks guys,2 from python x print bla bla end also used python putting future import printfunction top scriptmodule python console progressbar example import time status generator def rangewithstatustotal iterate total show progress console n ntotal done n todo totaln formatdonetodo todo n n r prints end yield n n example use status generator rangewithstatus timesleep,basically i want opposite guy hehe httpstackoverflowcomquestionspythonscriptprintnewlineeachtimetoshellratherthanupdateexistingline i program telling far along somelist bunch stuff print ilensomelist percent complete so lensomelist i get last line printed times i want print one line keep updating line i know i know probably lamest question read day i figure four words i need put google get answer update i tried mvds suggestion seemed right the new code print percentcomplete r percent complete string i abstracting first time i trying literal the result runs program print anything program prints percent complete one one line without carriage return comma half mvds suggestion prints nothing end and prints percent complete percent complete percent complete percent complete and so new issue comma print program finished with carriage return comma behaves exact neither,3 so thanks hints thomas k amp ed i managed complete exercise quite annoyed straightforward i look directions north south east west right verbs go stop kill eat stops nouns door bear princess cabinet def scanthewords thewords thewordssplit sentence thewords directions sentenceappend direction elif verbs sentenceappend verb elif stops sentenceappend stop elif nouns sentenceappend noun elif iisdigit sentenceappend number convertnumberi else sentenceappend error return sentence def convertnumbers try return ints except valueerror return none,i currently going lpthw i excercise first time i hit brick wall here first part test case i given nosetools import ex import lexicon def testdirection assertequallexiconscannorth direction north result lexiconscannorth south east assertequalresult direction north direction south direction east this question asked i noticed current solution far pretty identical answer provided robbyt yet still work def scanthewords directions direction north direction south direction east thewords thewordssplit sentence thewords directions sentenceappend direction else sentenceappend error return sentence so question after taking input thewords i search list tuples correctly return specific tuple part thanks advance sort answers advice really stuck one,1 it seems like really problem duplicate objects queue want make sure processing per object if i suggest consumer threads use set keep track objects sseen if object set add process set ignore duplicate if longrunning system instead set use ordereddict track seen objects then time time clean oldest entries ordereddict,a producer thread queries data store puts objects queue each consumer threads pull object shared queue long call external service when call returns consumer marks object completed my problem i basically wait queue empty producer add else i risk getting duplicates sent edit someone asked good question irc i figured i would add answer the question why producers produce duplicates the answer basically producer produces duplicates track sending state object sent unsent is way i check duplicates queue,1 you missing two things first need sort loop construct condition or var list and need way shortcircuit loop start top user types nonnumeric value for want read continue statement putting together might get something like while true add randomrandint add randomrandint answer stradd add question what add add print question print answer userin rawinput userinisdigit false print type number start top loop continue elif userin answer print awesome else print sorry incorrect print play yn rawinput break note infinite loop true exits hits break statement in closing i highly recommend learn python hard way good introduction programming python,i trying figure best way loop simple math quiz program best meaning neatest simplest method i get two random numbers sum prompt user enter evaluate input ideally get new numbers want play ask question prompt valid answerbut i seem wrap head around go import random sys import exit add randomrandint add randomrandint answer stradd add question what add add print question print answer userin rawinput userinisdigit false print type number i want ask question prompt answer elif userin answer print awesome else print sorry incorrect print play yn rawinput pass play game else exit,1 there two basic kinds loops python loops loops you would use loop loop list sequence something specific number times would use know many times need something which seems better suited problem,i trying figure best way loop simple math quiz program best meaning neatest simplest method i get two random numbers sum prompt user enter evaluate input ideally get new numbers want play ask question prompt valid answerbut i seem wrap head around go import random sys import exit add randomrandint add randomrandint answer stradd add question what add add print question print answer userin rawinput userinisdigit false print type number i want ask question prompt answer elif userin answer print awesome else print sorry incorrect print play yn rawinput pass play game else exit,1 you use datastore admin httpsdevelopersgooglecomappenginedocsadminconsoledatastoreadmindeletingentitiesinbulk,i would like wipe data specific kind google app engine what best way i wrote delete script hack since much data timeout hundred records,3 the overall convention mvc frameworks like django place much logic possible models this serves lot purposes it binds logic data good thing makes easy look one place code data manipulation methods allows run methods models directly without relying views makes testing simpler gives really clean api use templates eg objectpricewithtax opposed rendering different views different behaviors for project layout try keep code works models modelspy file try avoid using actionspy helperspy unless really need if long amounts code appropriate put modelspy maybe implementing algorithms something convention use helperspy there lot stuff later keep app hierarchy clean organized basic gist,it design problem let assume kind model django class paymentmodelsmodel purchase foreignkeyfieldpurchase netprice decimalfield isaccepted booleanfield def setacceptself logic touch purchase send emails etc def pricewithtaxself return netprice tax we also another file called actionspy implement others actions our problem determine kind methods placed modelspy actionspy do know common approach guide something like i want use existing solutions much possible thanks,3 you trying format instance method selflen length returned instance method when try formatselflen calls repr instance referred self creating recursion you need use format selflen lenself selflen,code supposed implent len magic method following code def lenself sqlalchemy import func selflen sessionqueryfunccountquestionidscalar return intselflen def reprself selfrepr traffic theory question current number questionsformatselflen return selfrepr i get upper lines keep repeating long list terminate following line file cpythondirfilepy line repr selfrepr traffic theory question current number questionsformatselflen runtimeerror maximum recursion depth exceeded getting str object i stress i getting error calling repr class method i call lenq q class instance working i get right answer clues,1 the documentation includes information use virtualenv install pyramid it recommended use virtualenv way system packages already installed main python weird interactions pyramid requirements,i trying build application using newish pyramid framework i new pyramid idea zope importance become apparent i followed basic tutorial i try run application i get traceback traceback recent call last file taskspy line module pyramidconfig import configurator file optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagespyramidpyeggpyramidinitpy line module pyramidrequest import request file optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagespyramidpyeggpyramidrequestpy line module zopedeprecation import deprecate importerror no module named deprecation i tried install pyramid using setuptools sudo easyinstall pyramid which among lot output included searching zopedeprecation reading httppypipythonorgsimplezopedeprecation best match zopedeprecation downloading httppypipythonorgpackagessourcezzopedeprecationzopedeprecationtargzmdedbaabeebfb processing zopedeprecationtargz running zopedeprecationsetuppy q bdistegg distdir tmpeasyinstallzilyjzopedeprecationeggdisttmpygfsor adding zopedeprecation easyinstallpth file which i thought cover i also tried installing zope via macports sudo port install zope sudo port install pyzopeinterface i also tried run sudo port load zope running script help i also tried downloading source httppypipythonorgpypizopeinterface building manually directory any ideas i wrong edit one guess setuptools installing zope components system default python framework enthought distribution default python environment one macports installed perhaps macports zope module components zopedeprecate,2 in matlab cell arrays containers heterogeneous data types matrices elements must type numeric doubles characters matrices rectangular shapes thus store strings d matrix row must length padded spaces this notion applies multidimensional matrices well the matlab equivalent python lists cell arrays python x str x maltab x int str x edit here example show difference python import numpy import scipyio list hello world scipyiosavemat filemat mdict list list list numpyarraylist dtypenumpyobject scipyiosavemat filemat mdict list list matlab load filemat load filemat whos list list name size bytes class attributes list x char list x cell now access strings list ans hello list ans hello note matrix case strings spacepadded strings length could use strtrim,this code python creates cell strings matfile data strings numpyemptydtypenumpyobject datastrings numpyappend datastrings some string scipyiosavemat outputmatfile data in matlab i get cell strings strings ans some string how could i get ordinary matrix for instance strings char some strings ans some edit if i run following code i get misunderstood array mangling python list hello world scipyiosavematoutputmatfile mdict list list matlab list list hlo wrd,2 i guess i little late party forgive shameless plug please check dabble ab framework it works quite nicely web frameworks using classbased views supports filesystem mongodb storage generates results,there several ab split testing modulesplugins rails httpgithubcompaulmarssevenminuteabs httpwwwbingocardcreatorcomabingo httpvanitylabnotesorg etc is anything similar python,1 despite wellknow formula computation o fails large numbers ie i would next fibonacci thing def fibn complexity ologn n return n b c b b c b c b c c c c return b and lastes numbers i would create model djangodb import models class fibonaccimodelsmodel parameter modelsintegerfieldprimarykeytrue result modelscharfieldmaxlength time modelsdatetimefield and view i would models import fibonacci def indexrequest result none requestmethodpost try nintrequestpostget n except return http try result fibonacciobjectsgetpkn resulttime datetimenow except doesnotexist result strfibn result fibonaccin result datetimenow resultsave return directtotemplaterequest basehtml result resultresult using models retrive last n entries pretty simple,i recently programming question preinterview certain company the questions create django app test driven course display fibonacci sequence world the app take index number display resulting fibonacci sequence additionally page shows recent generated sequences also fibonacci bit impatient doesn’t want wait around forever make sure take steps make sure webserver runs efficiently i came following djangoviewsgenericsimple import directtotemplate djangohttp import http largestsequence largest latest def fibn calculate nth fibonacci sequence global largest n largest n largest next largestsequencelargest largestsequencelargest print appending next largestsequenceappendnext largest return largestsequence else return largestsequencen def latestrequest results n latest result fibn resultsappendnresult return directtotemplaterequest latesthtml results results def indexrequest requestmethodpost try nintrequestpostget n except return http result fibn lenlatest latestpop latestinsertn else result none return directtotemplaterequest basehtml result result the latest view nd version st version work consistently the original version stored result index latest latest originally list fib sequences lists instead list recent values n i guess main question bad store largest fib sequence generated runtime viewspy file i know persistent instructions never really gave details things done what guys think would approached problem thanks guys,2 there one instance function stored inside class the function gets called reference class instance first argument traditionally called self so three equivalent ways call add method function x myobj myobjaddx pass reference x explicitly xadd method call implicitly passes reference x x overloaded operator implicitly passes reference x also python type signature function part function name the add method get one declared in python would simply write code make one function different jobs might want for example wanted add convert string integer make x return would like class myobjobject see note def initself b selfb b def addself return selfb intother see note def aaddself return myobja note it best declare class inheriting object in python x class inherit object whether declare way python x get oldstyle class unless declare object class name note bother check type argument try coerce int value this duck typing action now string coerced integer anything successfully coerced int work sometimes make one function multiple jobs may need extra arguments you make optional need specify every time call function you read python tutorial one place httpdiveintopythonnetpowerofintrospectionoptionalargumentshtml finally python need explicitly use myobja refer class variable if use member function get usual name resolution rules look global namespace object namespace special you could also get class variable like def aaddself cls typeself cls set class return clsa but work newstyle class inherits object,in java objects instantiated complete copy functions class linked this one reasons spring framework successful spring helps cut memory java vm uses create many temporary data objects service objects served spring singletons effectively carry functions i wondering true python it seems like but means mess dict object changing function copies class right for example class myobj def initself b selfb b def addself c return selfb c if i create array myobj one instantiation add one,3 change date datereplacetzinfouserstimezone date userstimezonelocalizedate localize adjusts daylight savings time replace see docs info,i requirement convert date local time stamp utc back local time stamp strangely converting back local utc python decides pdt instead original pst post converted date gained hour can someone explain going i wrong datetime import datetime pytz import timezone import pytz dateformat ymd hms zz def printformatteddt formatteddate dtstrftimedateformat print dttzinfo formatteddate convert strings datetime date datetimenow printformatteddate get user timezone pofile table userstimezone timezoneuspacific set parsed date timezone date datereplacetzinfouserstimezone date dateastimezoneuserstimezone printformatteddate create utc timezone utctimezone timezone utc date dateastimezoneutctimezone printformatteddate convert back user local timezone date dateastimezoneuserstimezone printformatteddate and output none uspacific pst utc utc uspacific pdt,3 your question already answered article referred karatsuba basic step works base b recursive algorithm efficient equal n rounded n number digits valueofdigit b some perspective might help you allowed required use elementary operations like numberofdigits divmoddigitx digitx b school arithmetic b required example know divmod produces when implementing large number arithmetic computer usual make b largest power support elementary multiplication operation conveniently for example cpython implementation bit machine b chosen ie product digitx digity hi product lo product amp xfff works without overflow without concern sign bit i sure trying achieve implementation python uses b numbers represented python ints whose implementation c already uses karatsuba algorithm multiplying numbers large enough make worthwhile it speed as learning exercise might like try representing number list digits base b input parameter,i want implement karatsuba split multiplication python however writing numbers form acxd x power base let xbm close sqrta how i supposed find x i even use division multiplication should i count number digits shift a left half number digits thanks,1 use urlparse library import urlparse urlparseurljoinhttpwwwfoocomstuffmikedochtmlbobdochtml httpwwwfoocomstuffbobdochtml,i looking way fully qualify url using python i current page url httpwwwfoocomstuffmikedochtml i href hrefbobdochtml what i need build httpwwwfoocomstuffbobdochtml does python libraries parse paths like i looked around docs urllib urllib find anything like thanks,3 java create new function instance in fact java function objects begin python hand first class functions getting function object instance class wraps class function simple object called bound method when bound method invoked underlaying class function called instance object first argument you could say given object class obj def fself print self obj f bound method hood happens import types func objdict f get raw function f typesmethodtypefunc obj create bound method as see instance obj func obj remain thing different instance used try bound method objf mainobj instance xcad objf unbound method objf equivalent objfo,in java objects instantiated complete copy functions class linked this one reasons spring framework successful spring helps cut memory java vm uses create many temporary data objects service objects served spring singletons effectively carry functions i wondering true python it seems like but means mess dict object changing function copies class right for example class myobj def initself b selfb b def addself c return selfb c if i create array myobj one instantiation add one,2 you able use tag function get name node xmletree import elementtree et path ccoolxml et etparse path root etgetroot roottag root print i root,my question follows another stackoverflow question how get root node xml file python xmletree import elementtree et path ccoolxml et etparse path root etgetroot when i extract print root tag i receive element root xabcd i want check root tag certain title i pull tag name if i try root root print something work i assume i need convert root text something like i new python,2 in situations best solution rely socalled user site location see pep details running pip install user packagename below manual way original answer need read solution works with easyinstall easyinstall prefixhomelocal packagename install homelocallibpythonxysitepackages local folder typical name many people use course may specify folder permissions write you need manually create homelocallibpythonxysitepackages add pythonpath environment variable otherwise easyinstall complain btw run command find correct value xy if using easyinstall look prefix option install scripts let specify one with pip use pip install installoptionprefixhomelocal packagename,i taking university classes given instructional account school account i ssh work i want run computationally intensive numpy matplotlib scipy code machine i cannot install modules i system administrator how i installation,3 root instance element class any object tag attribute just use roottag given say question produce string root,my question follows another stackoverflow question how get root node xml file python xmletree import elementtree et path ccoolxml et etparse path root etgetroot when i extract print root tag i receive element root xabcd i want check root tag certain title i pull tag name if i try root root print something work i assume i need convert root text something like i new python,1 you need import regular expression module code import recompile titletitle,i new python very new i copied following tutorial usrbinpython import urllib import urlopen beautifulsoup import beautifulsoup webpage urlopen httpfeedshuffingtonpostcomhuffingtonpostlatestnews read patfindertitle recompile titletitle patfinderlink recompile link relhref findpattitle refindallpatfindertitlewebpage findpatlink refindallpatfinderlinkwebpage listiterator listiterator range listiterator print findpattitlei print findpatlinki print n i get error traceback recent call last file testpy line module patfindertitle recompile titletitle nameerror name defined what i wrong edit i added import get following file scriptsprodtestpy line module findpattitle refindallpatfindertitlewebpage file usrlibpythonrepy line findall return compilepattern flagsfindallstring typeerror expected string buffer,3 just fun another version sven marnach answer r sumordch ch formatx b amp this works ascii thus unicode the reason works ordinal value x bit least significant bit position ordinal value x bit if going bitwiseand least significant bit anyway work well using int coerce bit value this twice fast but dan d answer even faster computing parity numbers xrange best three trials sven marnach answer seconds answer seconds dan d answer seconds and trials larger numbers compute dan d answer would win larger margin,is xor bit reduction operand function python i problem write reason write every script already builtin rxamp xrange rrxiamp,1 try module i think equivalent modulo sideeffects string import string one match refinditerrthisss string print matchgroup,i trying learn python quite understand syntax what equivalent string one whilestringthisssg print n prints one,3 as others noted i assume typo since would get syntax error but testing floats equality floats almost never equal imprecision generally test see two floats within small difference traditionally called epsilon try abswinpercentage observed print etc,working python i would like able input number return sets values x complete equation winpercentage observed def rlogobserved z floatobserved x range x winpercentage floatxfloatxfloatyfloatxfloatyfloatxfloaty winpercentage observed print z floatx floaty when i run function i get nothing no errors values either i tried without floats x i think needs winpercentage float the frustrating part i code basically thing works fine def solvenumnuggets numtwenties range numnuggets numnines range numnuggets numtwenties numsixes numnuggets numtwenties numnines totnuggets numtwenties numnines numsixes totnuggets numnuggets print numsixes numnines numtwenties i know kind newbie question i wits end,3 the heapify method transforms list inplace this means alters list returned modified list as agf mentions heapify returns none protect mistake therefore lst heapifylst typelst see lst heapified see library reference info,i b heapify i typeb it says nonetype instead list type anyone know i wrong,2 currently webpage reference function i suspect left read,i new python very new i copied following tutorial usrbinpython import urllib import urlopen beautifulsoup import beautifulsoup webpage urlopen httpfeedshuffingtonpostcomhuffingtonpostlatestnews read patfindertitle recompile titletitle patfinderlink recompile link relhref findpattitle refindallpatfindertitlewebpage findpatlink refindallpatfinderlinkwebpage listiterator listiterator range listiterator print findpattitlei print findpatlinki print n i get error traceback recent call last file testpy line module patfindertitle recompile titletitle nameerror name defined what i wrong edit i added import get following file scriptsprodtestpy line module findpattitle refindallpatfindertitlewebpage file usrlibpythonrepy line findall return compilepattern flagsfindallstring typeerror expected string buffer,1 this exactly answerbut note using dig look hostnames way say urlopen dig strictly dns query tool whereas system may configured look host information multiple source local hosts file nis ldap etc when type urlliburlopenhttpgooglecom your operating may check several sources on linux system exactly gets checked controlled hosts entry etcnsswitchconf you would use getent tool check hostname looks manner similar urlopen getent hosts googlecom your questions mention os using make explicitly exactly changed first second examples edit file change setting preferences dialog if linux including resolvconf changes well nsswitchconf might help diagnose things if linux specifying os may lead useful answers,i trying troubleshoot problem urlliburlopen it seem make use regular dns server below result several attempts open various urls first using google public dns second using router gridley defined etchosts file python default jun gcc linux import urllib urlliburlopenhttpgridley addinfourl whose fp socketfileobject object xbfec urlliburlopenhttpgooglecom addinfourl whose fp socketfileobject object xc python default jun gcc linux import urllib urlliburlopenhttpgridley addinfourl whose fp socketfileobject object xbec urlliburlopenhttpgooglecom traceback recent call last file stdin line module file usrlibpythonurllibpy line urlopen return openeropenurl data timeout file usrlibpythonurllibpy line open response selfopenreq data file usrlibpythonurllibpy line open open req file usrlibpythonurllibpy line callchain result funcargs file usrlibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlibpythonurllibpy line doopen raise urlerrorerr urlliburlerror urlopen error errno no address associated hostname however querying googlecom dig shows definitely work dig googlecom global options cmd got answer header opcode query status noerror id flags qr rd ra query answer authority additional question section googlecom in a answer section googlecom in a googlecom in a googlecom in a googlecom in a googlecom in a query time msec server when sun sep msg size rcvd ipv caused problems completely what heck going,1 heapify mutates list passed like lsort import heapq l heapqheapifyl l,i b heapify i typeb it says nonetype instead list type anyone know i wrong,1 i tried reading redis docs settings mention easy but sound like plan good idea the hashing describe designed save memory small values the values still stored completely memory it sounds like reducing overhead appear many times example string added many sets your string meet criteria i strongly doubt save memory using scheme you course benchmark see,i trying encode data big string actually memory efficient way redis side according redis docs claimed use hashes possible declares two configuration parameters the hashmaxzipmapentries i understood well denotes many keys every hash key must i right the hashmaxzipmapvalue denotes maximum length value does refer field value actually and length bytes characters my thought split string somehow fixed length quantities play well parameters store values the fields sequence numbers ensure consistent decoding edit i benchmarked extensively seems encoding string hash yields better memory consumption here benchmarking script import redis random sys def newdb db redisredishost localhost port db dbflushall return db def dbinfodb return used memory dbinfousedmemoryhuman def randomstringlen letters abcdefghijklmnopqrstuvwxyz return joinlettersrandomrandintlenletters rangelen def chunkastr size lenastr size yield astrsize astr astrsize lenastr yield astr def encodeasdictastr size dod cnt chunkastrsize dodcnt cnt return dod dbnewdb r randomstring print size string bytes sysgetsizeofr print default redis memory consumption dbinfodb dictchunk print print benchmarking n dbnewdb dbsetakey r print string dbinfodb print dbnewdb dbhmsetakey encodeasdictrdictchunk print dict stored value dbinfodb print results machine bit redis instance size string bytes default redis memory consumption used memory k benchmarking string used memory m dict stored value used memory m i asking efficient way store string hash playing parameters i mentioned so firstly i must aware mean then i benchmark see gain edit am i idiot the benchmarking correct confirmed one big string if i repeat many big strings storing big strings definite winner i think reason i got results one string lies redis internals,2 maybe take look documentation modelfields datefield the option autonow could searching you also use datetimefield it updates datetime time saving model so option set datetimefield sufficent retrieve datarecord save set time right,how i equivalent sql django update table set timestampnow where particularly i want set datetime field using server builtin function get system time server database running time client machine i know execute raw sql directly i looking portable solution since databases different functions getting current datetime edit people mentioned autonow param this updates datetime every modification i want update datetime certain occasions,1 problem related added space semicolon typed scripts directory easyinstall work removed space ie cpython cpythonscripts work,i python installed cpython i pyqt installed httpwwwriverbankcomputingcoukstaticdownloadspyqtpyqtpygplexe i added path path cpythoncpythonscripts when i type command cmdexe however easyinstall cheetah i get error cusersrichardeasyinstall cheetah easyinstall recognized internal external command operable program batch file cusersrichard any help in windows xp worked,1 as jker said want automatic update timestamp use autonow option eg datemodified modelsdatetimefieldautonowtrue or want manually simple assignment python datetimenow datetime import datetime objdatemodified datetimenow,how i equivalent sql django update table set timestampnow where particularly i want set datetime field using server builtin function get system time server database running time client machine i know execute raw sql directly i looking portable solution since databases different functions getting current datetime edit people mentioned autonow param this updates datetime every modification i want update datetime certain occasions,3 django explicitly avoids providing front end widgets like aspnet gridviews rails scaffolding if want regular template gotta roll list table tr th foo th th bar th tr item list tditemfootd tditembartd empty td colspanno itemstd endfor table endif however want provide admins quick ways editview data use django admin site make sure djangocontribadmin installedapps setting trivial example create adminpy app djangocontrib import admin myprojectmyappmodels import author adminsiteregisterauthor,i new django i got models data i want display table format i used using gridviews aspnet i looking alternative is best way using template iteration tags sort tutorials online showing examples,2 maybe using httppypipythonorgpypiscikitsstatsmodels easier features import numpy np import scikitsstatsmodelsapi sm tuition x research development x onenone parents x x npcolumnstackxxx stack explanatory variables array x smaddconstantx prependtrue add constant res smolsyxfit create model fit print resparams print resbse print ressummary,i using olspy code downloaded scipy cookbook download first paragraph bold ols i need understand rather using random data ols function multiple linear regression i specific dependent variable three explanatory variables every time i try put variables place random variables gives error typeerror constructor takes arguments can anyone help is possible here copy ols code i trying use along variables i trying input future import division scipy import c ones dot stats diff scipylinalg import inv solve det numpy import log pi sqrt square diagonal numpyrandom import randn seed import time class ols author vincent nijs email vnijs kelloggnorthwesternedu last modified mon jan cst dependencies see import statement top file doc class multivariate regression using ols input dependent variable yvarnm string variable label x independent variables note constant added default xvarnm string list variable labels independent variables output there values returned class summary provides printed output all measures accessed follows step create ols instance passing data class olsyxyvarnm xvarnm x x x x step get specific metrics to print coefficients print mb to print coefficients pvalues print mp tuition x research development x onenone parents x def initselfyxyvarnm xvarnm initializing ols class selfy selfx conesxshapex selfyvarnm yvarnm isinstancexvarnmlist selfxvarnm const listxvarnm else selfxvarnm const xvarnm estimate model using ols selfestimate def estimateself estimating coefficients basic stats selfinvxx invdotselfxtselfx xy dotselfxtselfy selfb dotselfinvxxxy estimate coefficients selfnobs selfyshape number observations selfncoef selfxshape number coef selfdfe selfnobs selfncoef degrees freedom error selfdfr selfncoef degrees freedom regression selfe selfy dotselfxselfb residuals selfsse dotselfeselfeselfdfe sse selfse sqrtdiagonalselfsseselfinvxx coef standard errors selft selfb selfse coef tstatistics selfp statstcdfabsselft selfdfe coef pvalues selfr selfevarselfyvar model rsquared selfradj selfrselfnobsselfnobsselfncoef adjusted rsquare selff selfrselfdfr selfrselfdfe model fstatistic selffpv statsfcdfselff selfdfr selfdfe fstatistic pvalue def dwself calculates durbinwaston statistic de diffselfe dw dotdede dotselfeselfe return dw def omniself omnibus test normality return statsnormaltestselfe def jbself calculate residual skewness kurtosis jb test normality calculate residual skewness kurtosis skew statsskewselfe kurtosis statskurtosisselfe calculate jarquebera test normality jb selfnobs squareskew squarekurtosis jbpv statschicdfjb return jb jbpv skew kurtosis def llself calculate model loglikelihood two information criteria model loglikelihood aic bic criterion values selfnobslogpi selfnobslogdotselfeselfeselfnobs aic llselfnobs selfncoefselfnobs bic llselfnobs selfncoeflogselfnobsselfnobs return aic bic def summaryself printing model output screen local time amp date timelocaltime extra stats aic bic selfll jb jbpv skew kurtosis selfjb omni omnipv selfomni printing output screen print n print dependent variable selfyvarnm print method least squares print date timestrftimea b yt print time timestrftimehmst print obs f selfnobs print variables f selfncoef print print variable coefficient std error tstatistic prob print rangelenselfxvarnm print f f f f tupleselfxvarnmiselfbiselfseiselftiselfpi print print models stats residual stats print print rsquared f durbinwatson stat f tupleselfr selfdw print adjusted rsquared f omnibus stat f tupleselfradj omni print fstatistic f probomnibus stat f tupleselff omnipv print prob fstatistic f jb stat f tupleselffpv jb print log likelihood f probjb f tuplell jbpv print aic criterion f skew f tupleaic skew print bic criterion f kurtosis f tuplebic kurtosis print name main testing ols class intercept added default olsyxyvarnm xvarnm x x x msummary,2 first might beneficial make one list tuples example newlisti firstlisti secondlisti that way change ensure always operating items firstlist secondlist secondly assuming relations entries lists use function operate one given value spawn thread handle value consider indices rangelennewlist results r poolmapasyncyourfunction indices callbackresultsappend rwait wait results this give want,here simplest multi threading example i found far import multiprocessing import subprocess def calculatevalue return value name main pool multiprocessingpoolnone tasks range results r poolmapasynccalculate tasks callbackresultsappend rwait wait results print results i two lists one index access elements list the ith position first list related ith position second i use dict lists ordered what i something like xrangelenfirstlist something firstlisti secondlisti so using example i think make function sort like global variables firstlist secondlist firstlist secondlist none none initialize lists function loop inside increment def function stuff but makes shared resource i sure safe it also seems design lending well multithreaded approach i sure fix here working example i wanted edit image want use import multiprocessing import subprocess shlex links httpwwwexamplecomimagejpg use url names stri jpg range def downloadi command wget o namesi linksi print command args shlexsplitcommand return subprocesscallargs shellfalse name main pool multiprocessingpoolnone tasks range r poolmapasyncdownload tasks rwait wait results,1 there seem couple questions i try answer paraphrased versions make clear i responding what sort overhead associated method attributes instances compared classes in python almost kinds container local variables class attributes references objects when define function function value created variable initialized reference function if function scope class definition python adds class attributes still reference original function so real way overhead function beyond cost references furthermore attributes class associated indirectly object class attribute number attributes class carries extra cost instances can i modify methods one instance class can i modify methods instances attributes object object dict already noticed goes attributes type also object resolving attributes python takes fairly consistent search pattern first checks descriptors class checks instance dict class dict picks first finds a fairly obvious example might look like class fooobject bar apples myfoo foo yourfoo foo yourfoobar bananas myfooclassbar oranges yourfoobar still bananas there extra gotcha methods though when get class attribute happens function python dynamically turns instancemethod binds self parameter instance took attribute class this effect happens attribute taken class instance if want modify instance new method take care turning function instance method you use typesmethodtype opinion case handled functoolspartial import functools def mymethodself something clever myfoobaz functoolspartialmymethod myfoo one instantiation add one it long way getting actual question but summarize function add method occurs single reference dict myobj there may many instances instancemethod wraps function method fact one time lookup python always creates new one,in java objects instantiated complete copy functions class linked this one reasons spring framework successful spring helps cut memory java vm uses create many temporary data objects service objects served spring singletons effectively carry functions i wondering true python it seems like but means mess dict object changing function copies class right for example class myobj def initself b selfb b def addself c return selfb c if i create array myobj one instantiation add one,1 if try fit data instance memory if fit instance memory options available you store data resource file upload app changes infrequently access disk this assumes build data structure permits easy disk lookups effectively implementing readonly disk based table likewise big fit static resource could take approach store data blobstore if data absolutely must datastore may need emulate readmodifywrite transactions add revision property records to modify fetch record outside transaction perform required changes inside transaction fetch check revision value if changed increment revision record store datastore note underlying rpc layer theoretically support multiple independent transactions nontransactional operations apis currently expose way access within transaction short horrible i mean really horrible hacks unfortunately one final option you could run backend provisioned memory exposing spellcheckservice make urlfetch calls frontends remember inmemory always going much much faster diskbased option,my python high replication datastore application requires large lookup table entries i need able supply code method return value associated code none association for example table held acceptable english words i would want function return true word found false none otherwise my current implementation create one parentless entity table entry entity contain associated data i set datastore key entity lookup code i put entities namespace prevent key conflicts essential question then i simply call getbykeyname code i get associated data the problem i access entities transaction i trying span entity groups so going back example let say i wanted spellcheck words used chat session i could access messages chat i give common ancestor i access word table entries parentless it imperative i able reference table transactions note lookup table fixed changes rarely again matches spellcheck example one solution might load words chat session one transaction spellcheck saving results start second transaction would spellcheck saved results but would inefficient chat session might added transactions this seems like clumsy solution ideally i like tell gae lookup table immutable i able query without complaining spanning entity groups transaction i see way however storing table entries memcache tempting problems it large amount data troublesome gae boots memcache entry i able reload transaction does anyone know suitable implementation large global lookup tables please understand i looking spellcheck web service anything like i using word lookup example make question clear i hoping general solution sort large lookup tables,1 a regular query performs essentially operations first snippet inside single rpc if need entities efficient ask ask keys fetch entities one thing watch efficiencywise iterating query objects when underlying rpc layer fetches results datastore batches resulting lot unnecessary rpcs if know many results need call fetch query like results personallfilter name joe fetch execute single rpc appstats excellent tool discovering diagnosing sorts performance issues,appengine docs note queries return keys faster cost less cpu queries return full entities which two desired way fetch iterate number objects data store querykeys personallkeysonlytrue querykeysfilter name personname querykeysorderkey people dbgetquerykeys p people read properties person object print pname vs query personall queryfilter name personname queryorderkey p people read properties person object print pname,1 this block code foos memcachegetallfoos foos none foos fooall size foocount else size lenfoo foostab rangesize foostabinsertifoosi memcachesetallfoos foostab can replaced much simpler code foos memcachegetallfoos foos foos fooallfetch at foos memcachesetallfoos foos specifically avoids unnecessary call count issues expensive rpc something find anyway fetch result single fetch call instead iterating results fetching batches calls memcache set fetch list first place,hello i want know appengine env things i usefull because i know page slow class foodbmodel id dbstringpropertymultilinetrue name dbstringpropertymultilinetrue date dbdatetimepropertyautonowaddtrue description dbtextproperty carac dbstringpropertymultilinetrue class foospagewebapprequesthandler def getself foos memcachegetallfoos foos none foos fooall size foocount else size lenfoo foostab rangesize foostabinsertifoosi memcachesetallfoos foostab templatevalues foos foos path ospathjoinospathdirnamefile templates fooshtml selfresponseoutwritetemplaterenderpath templatevalues,1 you pass object want invoke instance method you pass class want invoke class method the classic example using super class methods factory methods want superclass factory methods called class baseobject classmethod def makecls args kwargs printbasemakes start args kwargs printbasemake end class foobase classmethod def makecls args kwargs printfoomakes start args kwargs superfoo clsmakeargs kwargs printfoomake end class barbase classmethod def makecls args kwargs printbarmakes start args kwargs superbar clsmakeargs kwargs printbarmake end class foobarfoobar classmethod def makecls args kwargs printfoobarmakes start args kwargs superfoobar clsmakeargs kwargs printfoobarmake end fb foobarmake c invoking superclass class methods python realworld example,super args supertype objoftypeorsubclassoftype i understand use super nd arg objoftype but i understand matter nd arg subclass anyone show,1 python different relative cost operations instead garbage collection uses reference counting means releasing objects expensive java using singletons speedup good design opinion makes interdependencies different parts system on hand design benefits dependency injection clearer code better encapsulation apply also python exists frameworks python dependency injection framework,this question focused dao mvc messaging component frameworks spring known core as i understand spring earlier advantage managed component lifecycle providing singleton factory creates objects configuration file read startup the singleton factory creates service beans upon request singletons this one big wins spring uses less memory lot less garbage collection jvm data objects hand still created destroyed often singletons why dependency injection big advantages python languages or used,1 does help cherrypy digest basic authentication tutorial internet archive copy i cherypy application uses ldap module interact ldap auth system seems app needs manage usrpasswds within you could probably put registered userpasswords encrypted database table tweak scheme outlined blog,i going develop web application based cherrypy it app public users register login afterwards usual stuff other frameworks like rails django contain sophisticated code regarding security encrypted salted passwords prevention session hijacking is something like already available cherrypy i found simple solutions far,1 if want datetime foreign server ie one hosting django application going peg manually datatime use you could use sql command like select something ssh like ssh userhost date,how i equivalent sql django update table set timestampnow where particularly i want set datetime field using server builtin function get system time server database running time client machine i know execute raw sql directly i looking portable solution since databases different functions getting current datetime edit people mentioned autonow param this updates datetime every modification i want update datetime certain occasions,1 see documentation httpcodegooglecomwebajaxcrawlingdocsgettingstartedhtml and specifically parts relating escapedfragment,i need google indexes full url anchor part httpexamplecom user enters httpexamplecom then click reference address page changes httpexamplecom something happens page reload if user types address httpexamplecom directly address line browser presses enter corresponding page loads it may differencies httpexamplecom looks like user done action clicking in case google index httpexamplecom independent resource how provide behavior we javascript backend language,1 import line open logfilelog match researchr line match print matchgroup else match researchr line match print matchgroup else print no match line linestrip,i set strings log file i need parse timestamp user found user timestamp exception xyzsecurityplugin global error low memory i want capture text last currently i using r n captures string till eol please bear mind may colons used string i need capture till last colon used eol also colons string take eol ending sequence thanks edit better examples tpprocessor error springsecuritygrailsdaoimpl user found sspm tpprocessor error transactionjdbctransaction jdbc commit failed tpprocessor error errorsgrailsexceptionresolver exception occurred processing request post webappuserindex parameters runtime exception,1 r trick this works greedy check python documentation particular,i set strings log file i need parse timestamp user found user timestamp exception xyzsecurityplugin global error low memory i want capture text last currently i using r n captures string till eol please bear mind may colons used string i need capture till last colon used eol also colons string take eol ending sequence thanks edit better examples tpprocessor error springsecuritygrailsdaoimpl user found sspm tpprocessor error transactionjdbctransaction jdbc commit failed tpprocessor error errorsgrailsexceptionresolver exception occurred processing request post webappuserindex parameters runtime exception,1 make sure openmp number crunching extension free race conditions avoid updating windows gui operations multiple threads use pragma omp single pragma omp master kind stuff if variablecallback python code make sure threads finished supposed changing variable making callback the threads qt thread openmp completely different threads pose problems,i developing python application uses cextension module i also developed the extension module heavy number crunching makes use openmp i recently adding gui components python application using pyqt however i show window application crashes window fully drawn the window shows shortly i able track problem when i compile numbercrunching cextension without openmp support window shows fine everything works i guess something threading stuff openmp qt has anyone ever made similar observation,1 try it matches last current line if colon match therefore r recompile result rsearchmystring result match resultgroup else match n this said colon match eol meant colon match eol single regex r recompile,i set strings log file i need parse timestamp user found user timestamp exception xyzsecurityplugin global error low memory i want capture text last currently i using r n captures string till eol please bear mind may colons used string i need capture till last colon used eol also colons string take eol ending sequence thanks edit better examples tpprocessor error springsecuritygrailsdaoimpl user found sspm tpprocessor error transactionjdbctransaction jdbc commit failed tpprocessor error errorsgrailsexceptionresolver exception occurred processing request post webappuserindex parameters runtime exception,1 try look redis memory usage article find good comparison various data types memory consumption,i trying encode data big string actually memory efficient way redis side according redis docs claimed use hashes possible declares two configuration parameters the hashmaxzipmapentries i understood well denotes many keys every hash key must i right the hashmaxzipmapvalue denotes maximum length value does refer field value actually and length bytes characters my thought split string somehow fixed length quantities play well parameters store values the fields sequence numbers ensure consistent decoding edit i benchmarked extensively seems encoding string hash yields better memory consumption here benchmarking script import redis random sys def newdb db redisredishost localhost port db dbflushall return db def dbinfodb return used memory dbinfousedmemoryhuman def randomstringlen letters abcdefghijklmnopqrstuvwxyz return joinlettersrandomrandintlenletters rangelen def chunkastr size lenastr size yield astrsize astr astrsize lenastr yield astr def encodeasdictastr size dod cnt chunkastrsize dodcnt cnt return dod dbnewdb r randomstring print size string bytes sysgetsizeofr print default redis memory consumption dbinfodb dictchunk print print benchmarking n dbnewdb dbsetakey r print string dbinfodb print dbnewdb dbhmsetakey encodeasdictrdictchunk print dict stored value dbinfodb print results machine bit redis instance size string bytes default redis memory consumption used memory k benchmarking string used memory m dict stored value used memory m i asking efficient way store string hash playing parameters i mentioned so firstly i must aware mean then i benchmark see gain edit am i idiot the benchmarking correct confirmed one big string if i repeat many big strings storing big strings definite winner i think reason i got results one string lies redis internals,1 take look gnu radio httpgnuradioorgredmineprojectsgnuradiowiki gnu radio project software much possible radio signal transmission reception because radio already uses phase shift keying gnu radio guys already solved problem gnu radio already python project and complicated dsp stuff written c speed wrapped use python here page discussing project using differential binary phase shift keying dbpsk differential quadrature phase shift keying dqpsk transmit binary data example jpeg image python source code available download httpwwwwueceufleduprojectssoftwareradio i see project mit license gnu radio gpl may problem you need figure use gnu radio without needing make project derived work thus forcing change license it possible make standalone sending daemon standalone receiving daemon whose source code would gpl mit code connect socket something by way one searches found clear explanation bpsk works httpcnxorgcontentmlatest good luck,i currently working code transmit messagesfilesand data lasers using audio transformation my current code uses hexlify function binascii module python convert data binary emits tone different tone this theory works albeit fastest way encodedecode testing proves errors tones generated spot ie emitting hz turn hz receiving end huge issue i set boundaries receiving end lower higher real problem i emit tone played computer receiving end may read multiple times read based rate samples incoming audio i tried play tones speed samples iffy in i couple successful runs using short messages unreliable inaccurate due mentioned issues i looked solution looks like could involve bpsk binary phase shift keying although i sure implement any suggestions code samples would appreciated my code project found main files i working binary decoding encoding i expert python please pardon anything i said wrong code best if overlooked something basic thanks,3 chameleon takes syntax zope pagetemplates unfortunately support pluralization,how pluralization chameleon templates i manage find examples documentation for example could output span carspan span carsspan,1 you use winreg module windows first find path registry eg starting regeditexe using find function then query path i find home directory r key winregopenkeywinreghkeylocalmachine softwarercorer value winregqueryvalueexkey installpath added if familiar windows regstry look httpenwikipediaorgwikiwindowsregistry,a python program needs find installation location openofficeorg installed windows xp computer what best way,2 from theoretic point view there algorithm arbitrary program it like halting problem you inspect used modules check granted thread safe but general way check byte code module thread safety,well initial thing mind make sure pydispatcher pubsub threadsafe pubsub might little tricky complex figure pydispatcher seems simple realize then i started wonder figure python module threadsafe any heuristics,1 have tried inline formsets,this models class affiliationmodelsmodel submission modelsforeignkeysubmission relatedname submissionaffiliations name modelscharfieldmaxlength department modelscharfieldmaxlength city modelscharfieldmaxlength country modelscharfieldmaxlength sequenceno modelscharfield sequence no maxlength default class authormodelsmodel submission modelsforeignkeysubmission relatedname submissionauthors salutation modelscharfieldmaxlength lastname modelscharfieldmaxlength firstname modelscharfieldmaxlength email modelscharfieldmaxlength presentingpaperflag modelsbooleanfieldpresenting paper sequenceno modelscharfield sequence no maxlength choices sqno default affiliations modelsmanytomanyfieldaffiliation authoraffiliation class authoraffiliationmodelsmodel submission modelsforeignkeysubmission author modelsforeignkeyauthor affiliation modelsforeignkeyaffiliation the relation affiliation author mm there affiliations field author class there author affiliation authoraffiliation class when i go django admin add author shown like please focus red oval httpncupanhcombsdacdadefbfefscreenshotatpng i like make thing form could anybody show this current form httpncupanhcombsdbedcedaffscreenshotatpng thanks sorry english,1 if need speed numpy help really fast based atlas blas lapack i know use c if lot calculations find way store results case something crash moreover maybe find way optimize using cache otherwise try using several computer using libs like mpi anyway consider points order able scalable depending calculations cost python could good choice c if calculations could done using third library really matter but agree obrok avoid mix languages try keep simple possible for memory maybe using cache could good thing cut calculations smaller part looking numpyscipy functions could help,i working quite big project the program multiple tasks time hundreds complicated calculations second the program working as i proffessionnal programmer i know memory cpu handled kind program i request help the program different functions week weekend i know two languages pretty well python c i need application fast calculations i think c handle quickly the program work i might think python written project several little scripts call eachother multiples tasks working permanently would work better big c code how write best way i thinking writing pseudocode like during week function huge code functions call datetime friday datetime friday function functionclose during weekend function different code functions call datetime sunday datetime sunday function functionclose what best approach problem it quite large question kind advice welcomed thanks edit question program quite complicated hundreds functions calculations i want fastest lowest memory consuming how write best,1 must use either charsc wordscountc or charsc,im trying split string letters dictionary automatically adds value every letter present the problem code adds value every keyfor example input aasf dict f whats wrong word rawinputwrite letters chars c word charsc ccountc c chars charsc print chars,1 if put items import brackets use one line everything want import without escaping newlines,python two ways import something module mymodule import classone classtwo classthree mymodule import classone classtwo classthree i cannot find note probably i trying hard enough python documentation i want know significant difference two ways importing,3 beautifulsoup excels parsing extracting data badly formatted htmlxml broken html ambiguous uses set rules interpret tags may want see section parsing html docs ends example sounds similar situation if know wrong tags understand rules beautifulsoup uses may able augment html slightly perhaps remove move certain tags make beautifulsoup return output want if post short example someone might able give specific help update examples for example consider example given docs linked beautifulsoup import beautifulsoup html html form table tdinput nameinputrow cell trtdrow cell form tdrow cell brthisbr sure long cell body html print beautifulsouphtmlprettify the table tag closed form ensure table properly nested within form leaving last td hanging if understand problem get correct closing tab table removing form parsing html htmlreplaceform soup beautifulsouphtml print soupprettify html table td input nameinput row cell td tr td row cell td td row cell br this sure long cell td tr table html if form tag is important still add parsing for example newform tagsoup form create form element souphtmlinsert newform insert form child html newforminsert souptableextract move table form print soupprettify html form table td input nameinput row cell td tr td row cell td td row cell br this sure long cell td tr table form html,i automatically translate content html pages different language i extract text nodes different html pages sometimes badly written i possibility edit htmls by using beautifulsoup extract texts easily replace translation i display html operation html beautifulsoupsourcehtml sometimes broken beautifulsoup automatically closes tags instance table tag closed wrong place is way prevent beautifulsoup closing tags for instance input html tabletrtdsome texttdtable closing tr missing soup beautufulsouphtml get tabletrtdsome texttdtrtable want get html input is possible,2 you go struct module pack values byte string example import struct type status varid value b hello buffer structpack bbhs type status varid value buffer b xxxxhelloxxxxxxxxxxx alternatively use ctypesstructure define class representing structure it advantage easier use python code take account alignment padding issues resolve perhaps struct,i porting simple bluetooth app sends magic packet lcap protocol bluetooth device i problem converting struct object c python equivalent in c command types define cfgbttypesetreq x define cfgbttypesetres x define cfgbttypegetreq x define cfgbttypegetres x varid types define cfgvaridtuint x define cfgvaridtuint x define cfgvaridtstring x typedef struct uintt type status uintt varid uintt value attributepacked cfgbtframe static cfgbtframe c app used like set ctype cfgbttypegetreq cvarid strtolargv null cstatus memsetcvalue send frame writes ampc sizeofc can point construct packetstuctlike structure using python i know i probably need use ctypes create empty class get together,2 python r apr collections import counter counter count letters sentence counter e n c h l r u,im trying split string letters dictionary automatically adds value every letter present the problem code adds value every keyfor example input aasf dict f whats wrong word rawinputwrite letters chars c word charsc ccountc c chars charsc print chars,2 how gformat gformat gformat gformat however since significant digits also include integer part also get gformat gformat e,i function expects two cutoff values called mindf maxdf either may int denote absolute frequency cutoff float denote relative frequency now i want add checks give appropriate warning messages without much clutter this works maxdf mindf raise valueerror neither maxdf mindf may maxdf mindf float warning contains i rather say i tried f turns int values floats well displays how i switch type get right format do i need build format string passing operator update i need something works python since minimum version i targeting,2 if already directory contains files want rename need give absolute path filename filenames osrenamefilename filenamereplace,i writing simple python script rename files directory replace spaces file name hyphens i following crashing osrename import os path osgetcwd filenames oslistdirpath filename filenames osrenameospathjoinpath filename ospathjoinpath filenamereplace gives error console traceback recent call last file stdin line module oserror errno no file directory any ideas happening,3 keep simple def formatdfdf isinstancedf int long return df elif isinstancedf float return f df else return strdf fallback case raise valueerror neither maxdf mindf may formatdfmaxdf formatdfmindf,i function expects two cutoff values called mindf maxdf either may int denote absolute frequency cutoff float denote relative frequency now i want add checks give appropriate warning messages without much clutter this works maxdf mindf raise valueerror neither maxdf mindf may maxdf mindf float warning contains i rather say i tried f turns int values floats well displays how i switch type get right format do i need build format string passing operator update i need something works python since minimum version i targeting,3 i think syntax wrong call ospathjoin items joining supplied two distinct arguments separated comma this works fine python default jun msc v bit intel win type help copyright credits license information import os path osgetcwd filenames oslistdirpath filename filenames osrenameospathjoinpath filename ospathjoinpath filenamereplace,i writing simple python script rename files directory replace spaces file name hyphens i following crashing osrename import os path osgetcwd filenames oslistdirpath filename filenames osrenameospathjoinpath filename ospathjoinpath filenamereplace gives error console traceback recent call last file stdin line module oserror errno no file directory any ideas happening,3 the first solutions comes mind ospathrelpath imageshtml ospathdirname faqindexhtml imageshtml of course requires url parsing domain name comparison path rewriting case readding query fragment edit complete version import urlparse import posixpath def relativeurldestination source udest urlparseurlsplitdestination usrc urlparseurlsplitsource uc urlparseurlunsplitudesttuple range uc urlparseurlunsplitusrctuple range uc uc this different domain return destination relpath posixpathrelpathudestpath posixpathdirnameusrcpath return urlparseurlunsplit relpath udestquery udestfragment then relativeurl httpwwwexamplecomimageshtml httpwwwexamplecomfaqindexhtml imageshtml relativeurl httpwwwexamplecomimageshtmlmyqueryampstringherefragment httpwwwexamplecomfaqindexhtml imageshtmlmyqueryampstringherefragment relativeurl httpwwwexamplecomimageshtml httpwwwexamplecomfaqindexhtml httpwwwexamplecomimageshtml relativeurl httpswwwexamplecomimageshtml httpwwwexamplecomfaqindexhtml httpswwwexamplecomimageshtml edit using posixpath implementation ospath make work windows,is builtin function get url like imageshtml given base url like httpwwwexamplecomfaqindexhtml target url httpwwwexamplecomimageshtml i checked urlparse module what i want counterpart urljoin function,2 you could use urlparseurlparse find paths posixpath version ospathrelname find relative path warning this works linux may windows import urlparse import sys import posixpath def relurltargetbase baseurlparseurlparsebase targeturlparseurlparsetarget basenetloc targetnetloc raise valueerror target base netlocs match basedir posixpathdirnamebasepath target targetpath return posixpathrelpathtargetstartbasedir tests httpwwwexamplecomimageshtml httpwwwexamplecomfaqindexhtml imageshtml httpgooglecom httpgooglecom httpgooglecom httpgooglecom httpgooglecom httpgooglecom httpgooglecom httpgooglecom httpgooglecomindexhtml httpgooglecom indexhtml httpgooglecomindexhtml httpgooglecomindexhtml indexhtml targetbaseanswer tests try resultrelurltargetbase except valueerror err print trbr e formatttargetbbaseeerr else resultanswer print trbr pass formatttargetbbase else print trbr rr ar format ttargetbbaserresultaanswer,is builtin function get url like imageshtml given base url like httpwwwexamplecomfaqindexhtml target url httpwwwexamplecomimageshtml i checked urlparse module what i want counterpart urljoin function,3 if use distutils setuppy script commandline options forcing installation destination see httpdocspythonorginstallindexhtmlalternateinstallation if problem repeats setup distutils configuration file see httpdocspythonorginstallindexhtmlinstconfigfiles setting pythonpath variable described tihos post,i taking university classes given instructional account school account i ssh work i want run computationally intensive numpy matplotlib scipy code machine i cannot install modules i system administrator how i installation,3 the favored method use newaxis x numpynewaxis it readable efficient,i encountering annoying shape mismatch issue i working arrays length one width one for example import numpy np x npones npones xy valueerror shape mismatch objects cannot broadcast single shape the simple solution yxreshapexshape however i often end subsetting one column array designate reshape is way avoid,2 after digging django sources i found class domaincreateviewcreateview creates domain formclass domainform templatename customercreatedomainshtml successurl reverselazy managedomains methoddecoratorloginrequired methoddecoratoronlymanagersallowed def dispatchself args kwargs the dispatcher return superdomaincreateview selfdispatchargs kwargs def formvalidself form validate save form company selfrequestusergetprofilecompany selfobject formsavecompany return supermodelformmixin selfformvalidform class domaindeleteviewdeleteview deletes domain model domain templatename customerdeletedomainshtml successurl reverselazy managedomains methoddecoratorloginrequired methoddecoratoronlymanagersallowed def dispatchself args kwargs the dispatcher return superdomaindeleteview selfdispatchargs kwargs,i using django generic crud views quite things project i like begin migrating new style classbased generic crud views django i finds docs help could use little help converting functionbased views here snippet views def createdomainsrequest args kwargs return createobjectrequestrequest formclassdomainform templatename customercreatedomainshtml postsaveredirectreverse managedomains def deletedomainsrequest objectid args kwargs return deleteobjectrequestrequest objectidobjectid modeldomain templatename customerdeletedomainshtml postdeleteredirectreverse managedomains i guess i using createview first one deleteview next one this i come far class domaincreateviewcreateview formclass domainform templatename createdomainshtml successurl managedomains class domaindeleteeviewcreateview model domain templatename deletedomainshtml successurl managedomains pkurlkwarg objectid could one show rewrite classbased view a little jump start would great help i confident i could take thanks,1 apachemodwsgi required each mounted web application modwsgi run distinct sub interpreter process using different code bases better still use daemon mode modwsgi delegate web application distinct process risk interfering,i stuck desperate is possible serve multiple python web applications multiple different domains using virtualhost cherrypy hmm wait i answer yes possible with virtual host dispatcher possible require i need use instances application different versions this means i need somehow split namespace python import applications example i application myapp two versions i got two domains appcom appcom when i access appcom i would like get application myapp version when i access appcom myapp version i using virtualhostdispatcher cherrypy problem i use import methods myapp version myapp version loaded python use already imported module module cache yes possible wrap import clean python module cache everytime use top level application object instantiation seems quite unclean and i think also inefficient so recommend i thinking using apache cherrypy using modwsgi seems solve import problem becuase still one python process apps togetger maybe i thinking whole problem completely wrong i need rethink i opened every idea tip only limitation want use python anything else still opened discussion thank every response,1 if upside imagedata imagedata if swapped left right imagedata imagedata and transposed flipped diagonal imagedata imagedatat if dimensions color alpha flipping done imagedata imagedata imagedata imagedata placeholder something i know implemented feature numpy,i reading image disk i converting numpy array imimageopeninfile imdata scipymiscfromimageim image mirrored like stored disk how read correct order thanks lot,1 shell ps cp output format specifier ps p pid cp from python see psutilprocessgetcpupercent,i trying calculate percentage cpu used particular process using pythonshell far nothing i looked lot questions none could help any suggestions,1 ps pid cp pid cp if process looking might running user etc use ps eo pid cp show processes system instead default selfowned ones if know specific process id could ps p cp noheading process id want result get character string rightaligned potentially digit number,i trying calculate percentage cpu used particular process using pythonshell far nothing i looked lot questions none could help any suggestions,2 use yield return streaming actual uploaded file size you check yield cherrypy httpwwwcherrypyorgwikireturnvsyield this one cases yield fits,i simplistic cherrypy web application running windows successfully allows upload multiple files the application save anything special uploaded files moment however i want testing first anyways html snippet includes lines form idmyform actiondoupload enctypemultipartformdata methodpost input typefile idfiles namefiles multiple input typesubmit idbutton form the corresponding cherrypy dispatcher lines code removed begins cherrypyexpose def douploadself kwargs try filesuploaded f kwargs files selfperformactualuploadf filesuploaded filesuploaded filesuploaded selfperformactualuploadkwargs files except keyerror pass the selfperformactualupload method simple loop counts number bytes read prints total i used logging features i dump output windows command prompt size true try data ffileread data break size lendata except attributeerror size print total bytes transferred formatsize what i discovered output selfperformactualupload generated files uploaded transfer what i want monitor amount bytes transit i update html field either growing progress bar everchanging numeric total i trawled google searches stumbled upon thread httpoldnabblecomfileuploadstatsincptdhtml talks tracking file upload stats cherrypy version http framework i understand uploadstats continuously called something like jquery post ask cherrypy latest upload statistics i also realise i need create fieldstorage object one overridden makefile method what i cannot figure however successfully instantiate fieldstorage object i tried following lines code doupload dispatcher lchdrs key val cherrypyrequestheadersitems lchdrskeylower val formfields fieldstoragefpcherrypyrequestrfile headerslchdrs environ requestmethod post keepblankvaluestrue receive error message valueerror cherrypywsgiserverknownlengthrfile object x return bytes got str knownlengthrfile wrapper around filelike object i tried convert str bytes work so i total loss proceed point admittedly knowledge python cherrypy quite limited moment is someone help again i trying adapt code fragments httpoldnabblecomfileuploadstatsincptdhtml cherrypy web application there also questions surrounding whole ajax interaction ie calling uploadstats receiving json entity parsing i reserve another time thanks,1 try getattrselfui variablenamefunction see info getattr,i strings variables names must initially strings due file io the variables correspond variable names pyqt widgets embed two classes i need strings able converted actual variable names use functions kind like int string number here code showing class madness first file class uimainwindowobject def setupuiself mainwindow selfvariablename qwidgetwhatever second file firstfile import uimainwindow class startqtguiqmainwindow def initself parent none qtguiqwidgetinitself parent selfui uimainwindow selfuisetupuiself def resetdropboxesself x variablename selfuixfunction some might recognise format python code generated pyuic qt designer the last two lines second file trouble i get error message uimainwindow attribute x i idea go except attempt eval i tried things x selfuievalvariablename this prompted errors uimainwindow attribute eval x evalvariablename variablename defined x variablename evalselfuixfunction uimainwindow attribute x i could use help matter i feel eval gets step closer using nested classes inhibits halp details python windows bit idle pyqt qt designer,3 another possible solution use debugtoolbarpanels setting config file disable requestvars panel causing issue appmain stuff debugtoolbarpanels pyramiddebugtoolbarpanelsversionsversiondebugpanel pyramiddebugtoolbarpanelssettingssettingsdebugpanel pyramiddebugtoolbarpanelsheadersheaderdebugpanel pyramiddebugtoolbarpanelsrequestvarsrequestvarsdebugpanel pyramiddebugtoolbarpanelsrenderingsrenderingsdebugpanel pyramiddebugtoolbarpanelsloggerloggingpanel pyramiddebugtoolbarpanelsperformanceperformancedebugpanel pyramiddebugtoolbarpanelsroutesroutesdebugpanel pyramiddebugtoolbarpanelssqlasqladebugpanel,goal i try integrate mongo db pyramid basic application background appliation created book httpsdocspylonsprojectorgprojectspyramidnarrprojecthtmlcreatingtheproject using basic command paste create pyramidstarter i followed cookbook article httpsdocspylonsprojectorgprojectspyramidcookbookdevmongohtml problem it seems ever i add mongodb connection request i got internal server error i tried several articles seems i must start debug system has anybody found easy solution exception helps expert exception happened processing request traceback recent call last file virtualenvlibsitepackagespastepyeggpastehttpserverpy line processrequestinthread selffinishrequestrequest clientaddress file cpythonlibsocketserverpy line finishrequest selfrequesthandlerclassrequest clientaddress self file cpythonlibsocketserverpy line init selfhandle file virtualenvlibsitepackagespastepyeggpastehttpserverpy line handle basehttprequesthandlerhandleself file cpythonlibbasehttpserverpy line handle selfhandleonerequest file cpythonlibsitepackagespyramiddebugtoolbarpyeggpyramiddebugtoolbarpanelsinitpy line render return rendertemplatename vars requestrequest file virtualenvlibsitepackagespyramidapyeggpyramidrendererspy line render return helperrendervalue none requestrequest file virtualenvlibsitepackagespyramidapyeggpyramidrendererspy line render result renderervalue systemvalues file cpythonlibsitepackagespyramidjinjapyeggpyramidjinjainitpy line call return selftemplaterendersystem file cpythonlibsitepackagesjinjapyeggjinjaenvironmentpy line render return selfenvironmenthandleexceptionexcinfo true file cpythonlibsitepackagespyramiddebugtoolbarpyeggpyramiddebugtoolbarpanelstemplatesrequestvarsjinja line toplevel template code td valueescape td file virtualenvlibsitepackagesmarkupsafepyeggmarkupsafenativepy line escape return shtml file virtualenvlibsitepackagespymongopywinamdeggpymongocollectionpy line call selfname typeerror collection object callable if meant call html method database object failing method exists,1 do happen perl pip lying around somewhere sounds like problem described httpsgithubcommikeperdidegitbusterissues to check windows command prompt execute cwhere pip this potentially output following cstrawberryperlbinpip cstrawberryperlbinpipbat if problem unistall strawberry perl use full path python pip,i installed pip windows downloading httppypipythonorgpackagessourceppippiptargzmdecfffdfedcad running python setuppy install installation went fine errors but i tried installing selenium package gives following error pip install u selenium unknown option u unknown unsupported command install where i making mistake,3 you checking presence entire list keys character list rather checking key individually you must iterate keys individually check presence k chars k ordlistalist print yes else print no if want print words consist solely letters character list may use following approach word ordlistalist filterlambda char char chars word print word,i would like compare input lettersdictionary listtextfile words print words matching inputed letters what i done wrongi know print yes nofunction finds matching word moment what best way create function way def ordlistalist fil openordtxt r words filreadlines list w words w wstrip listappendw return list chars word rawinputwrite letters w word w wlower w chars charsw else charsw charskeys ordlistalist print yes else print no,1 charskeys list charskeys ordlistalist never true what want match letter counts word list so i suggest charsum sumcharsvalues word wordlist lenword charsum allwordcountc charsc c chars print yes word word edit if want words match least letter counts ie word match input two change edit since want exact matches easiest solution would count number chars make sure word length,i would like compare input lettersdictionary listtextfile words print words matching inputed letters what i done wrongi know print yes nofunction finds matching word moment what best way create function way def ordlistalist fil openordtxt r words filreadlines list w words w wstrip listappendw return list chars word rawinputwrite letters w word w wlower w chars charsw else charsw charskeys ordlistalist print yes else print no,1 i think tool pyscxml needs closer look this project uses wc definition state chart xml scxml state machine notation control abstraction scxml provides generic statemachine based execution environment based ccxml harel state tables currently scxml working draft chances quite high getting wc recommendation soon it th draft another interesting point highlight apache commons project aimed creating maintaining java scxml engine capable executing state machine defined using scxml document abstracting environment interfaces and certain tools supporting technology emerge future scxml leaving draftstatus,related so question c statemachine design could so folks share community python statemachine design techniques update at moment i going engine based following class trackinfohandlerobject def initself selfstatebegin selfacc event callbacks def startelementself name attrs selfdispatchstartelement name attrs def charactersself ch selfaccch def endelementself name selfdispatchendelement selfacc selfacc def missingstateself event raise handlerexceptionmissing states selfstate def dispatchself event methodnamestselfstate getattrself methodname selfmissingstateevent state related callbacks but i sure tons ways going whilst leveraging python dynamic nature eg dynamic dispatching update i design techniques engine receives events dispatches based state machine,1 if want pack struct value one byte unsigned uintt end string one character probably looking format b instead c c converts character string useful b converts integer structpack b and yes x x the struct class also conveniently handle endianness communication uses,i want take integer hex string representation eg i want pass get x get xff i tried structpack c chokes anything since wants take single character string,3 use sets chars setrawinputwrite letters word ordlistanone ifsetword chars print yes word btw argument list ordlista unnecessary used i would also advise using name list general hides builtin type list update i read comment jellybean post if every letter used obviously use sets,i would like compare input lettersdictionary listtextfile words print words matching inputed letters what i done wrongi know print yes nofunction finds matching word moment what best way create function way def ordlistalist fil openordtxt r words filreadlines list w words w wstrip listappendw return list chars word rawinputwrite letters w word w wlower w chars charsw else charsw charskeys ordlistalist print yes else print no,1 try launch server u yourmodulename yourdbname,i process trying upgrade module written openerp although works fine local machine local openerp server it gives error i try update files via svn staged server the error states trying insert record db actually update insertion i worried remove record postgres db directly though think might trick i also removed existing files i svn update staged server may might pit fall quite sure let know guys think best solution problem below error messages show openerp server restarted svn update the server stops never ends but soon i revert files remove update server works like charm module abc loading objects oetest infoinitmodule abcregistering objects oetest infoinitmodule abc creating updating database tables oetest debugsqlbad query insert into irmodeldata namedateinitdateupdatemodulemodelresid values e modelabc e abc e irmodel oetest debugsql modelabc u abc irmodel oetest debugsqlduplicate key value violates unique constraint irmodeldatamodulenameuniq regards gayan,1 in response first issue regarding frequency looking decoder i see sample rate chunk size if reading right means fft size that would put fft bin size hz have tried zero pad fft zeropadding fft change frequency give better resolution i see using quadratic interpolation improve frequency estimate i used technique i familiar improvement get maybe balance zeropadding quadratic interpolation get better frequency accuracy also depending hardware transmission receiving frequency error might result different clocks driving ad one clocks exactly hz something like might affect frequency see fft output,i currently working code transmit messagesfilesand data lasers using audio transformation my current code uses hexlify function binascii module python convert data binary emits tone different tone this theory works albeit fastest way encodedecode testing proves errors tones generated spot ie emitting hz turn hz receiving end huge issue i set boundaries receiving end lower higher real problem i emit tone played computer receiving end may read multiple times read based rate samples incoming audio i tried play tones speed samples iffy in i couple successful runs using short messages unreliable inaccurate due mentioned issues i looked solution looks like could involve bpsk binary phase shift keying although i sure implement any suggestions code samples would appreciated my code project found main files i working binary decoding encoding i expert python please pardon anything i said wrong code best if overlooked something basic thanks,2 this bug python fixed httphgpythonorglookupr it possible use mime libraries nonemail transports sensible things happen,i need generate multipartmime message send response http request hitting either bug limitation python email package the problem using python messageasstring call generates string n rather crlf line endings message mimemultipart image images f imageopen rb img mimeimagefread encoderencodeorbit messageattachimg messageasstring there seem way persuade use mime standard crlf the generator class seems able what people done get round,1 from python release notes overriding new method new static method class method i initially thought would class method i added classmethod primitive unfortunately class methods upcalls work right case i make static method explicit class first argument since new static method supernew returns static method there binding cls first argument case all arguments need supplied explicitly,as i learned i use super way superclass objofclassorsubclassofclass code goes case class aobject def initself print a init class ba def initself print b init superb selfinit ok i invoke a init successfully case class aobject classmethod def foocls print a foo class bobject classmethod def foocls print b foo superb clsfoo ok i invoke a foo successfully case class aobject def newcls print a new return supera clsnewcls class ba def newcls print b new return superb clsnew oops error question in case i use super successfully without specifying obj cls operate but i new because case i use super way i got error but i use way superb clsnewcls no error,3 straight documentation commit used commit current transaction it always issues flush beforehand flush remaining state database,does anybody know main difference sessioncommit sessionflush sqlalchemy,2 here relevant quotes documentation flush when session used default configuration flush step nearly always done transparently specifically flush occurs individual query issued well within commit call transaction committed commit commit used commit current transaction it always issues flush beforehand flush remaining state database independent “autoflush” setting if transaction present raises error note default behavior session “transaction” always present behavior disabled setting autocommittrue in autocommit mode transaction initiated calling begin method,does anybody know main difference sessioncommit sessionflush sqlalchemy,3 i guessing documentation seams like register service first maybe show us bit code help better,i using envisage workbance i want get service handler in tcpsendchanged function i get services in plugin selfapplicationgetservice i reach updated this view class mclidarguiview hastraits traitsuiview view vgroup hgroup item lidarlist showlabel false editor tabulareditor showtitles false selected selected editable false multiselect true adapter lidaradapter item lidarscommand hgroup item handlertcpsend showlabel false editor buttoneditor label tcpsend id forwindlidarapigiuview resizable true handler mclidaractions lidarlist lidarobject lidarname no connected lidar lidarscommand handler class mclidaractions handler tcpsend event def objectupdatedchanged self info print info pass def tcpsendchanged self print info,1 i trying thing customtreectrl support tristate check boxes when create root selfroot selftreeaddrootroot nodecttype child node child selftreeappenditemparentchildcttype returns generictreeitem object change attribute isstate true selfrootsetstatetrue childsetstatetrue,as per title possible by tristate i mean parent node checked children checked unchecked children unchecked greyfilled children checked i used previously c cannot find equivalent controlimplementation wxpython,1 assuming index pairs stored numpy array indices shape n n fairly large probably best avoid python loop c numpyr acumsumindices sums c c,suppose i array a i series index pairs b b bn i want obtain sums elements pairs ie sumaab sumaab sumaab in terms runtime efficient way thanks,3 cleanercleanercall safeattrsonly parameter when set true attributes cleandefssafeattrs preserved you remove attributes changing cleandefssafeattrs just sure change back done import lxmlhtmlclean clean code tr idctlcontentadmanagementpreviewdetailviewdivnova classextended styledisplay none safeattrs cleandefssafeattrs cleaner cleancleanersafeattrsonlytrue safeattrsfrozenset cleansed cleanercleanhtmlcode printcleansed yields trtr,how i remove certain attributes id style class etc html code i thought i could use lxmlhtmlclean module turned i remove style attributes cleanstyletruecleanhtmlcode i prefer use regular expressions task attributes could change what i would like lxmlhtmlclean import cleaner code tr idctlcontentadmanagementpreviewdetailviewdivnova classextended styledisplay none cleaner cleanerstyletrue idtrue classtrue cleaned cleanercleanhtmlcode print cleaned tr thanks advance,3 the following arr nparraykv kv datadictiteritems dtype date o high f low f if wish use arr recarray could use arr arrviewnprecarray this enable reference fields name eg arrdate,i python dict object key datetimedate object values tuple objects datadict datetimedate datetimedate datetimedate datetimedate datetimedate datetimedate i want convert numpy array object format dtype date o high low i could store disk later work learn numpy matplotlib as matter fact i thought use format looking matplotlib examples httpmatplotlibsourceforgenetusersrecipeshtml find way get,3 how import copy def createarraymutabledims obj lendims return copydeepcopyobj else return createarraymutabledims obj xrangedims class cobject pass print createarraymutable c this creates xx array unique instances c the solution still recursive i think recursion pretty good fit problem,i want create multidimensional array initialize copies mutable object this i far import copy def createarraydimensions dimensions copydeepcopydimensions dimensionsreverse dimensions del dimensions dimensions copydeepcopya ranged return def createarraymutabledimensions obj createarraydimensions def setx isinstancex list e x sete else rangelenx xi copydeepcopyobj seta return i wonder better way without copies recursion,1 actually efficient way store large string large string anything else adds overhead the optimizations mention dealing lots short strings empty space strings become issue performance storing large string may good small strings due need find contiguous blocks store unlikely actually affect anything,i trying encode data big string actually memory efficient way redis side according redis docs claimed use hashes possible declares two configuration parameters the hashmaxzipmapentries i understood well denotes many keys every hash key must i right the hashmaxzipmapvalue denotes maximum length value does refer field value actually and length bytes characters my thought split string somehow fixed length quantities play well parameters store values the fields sequence numbers ensure consistent decoding edit i benchmarked extensively seems encoding string hash yields better memory consumption here benchmarking script import redis random sys def newdb db redisredishost localhost port db dbflushall return db def dbinfodb return used memory dbinfousedmemoryhuman def randomstringlen letters abcdefghijklmnopqrstuvwxyz return joinlettersrandomrandintlenletters rangelen def chunkastr size lenastr size yield astrsize astr astrsize lenastr yield astr def encodeasdictastr size dod cnt chunkastrsize dodcnt cnt return dod dbnewdb r randomstring print size string bytes sysgetsizeofr print default redis memory consumption dbinfodb dictchunk print print benchmarking n dbnewdb dbsetakey r print string dbinfodb print dbnewdb dbhmsetakey encodeasdictrdictchunk print dict stored value dbinfodb print results machine bit redis instance size string bytes default redis memory consumption used memory k benchmarking string used memory m dict stored value used memory m i asking efficient way store string hash playing parameters i mentioned so firstly i must aware mean then i benchmark see gain edit am i idiot the benchmarking correct confirmed one big string if i repeat many big strings storing big strings definite winner i think reason i got results one string lies redis internals,3 using sophisticated fibonacci number test could use def isfibonaccin phi mathsqrt phi n return n absrounda n this probably efficient way determine whether number fibonacci number probably intended solution homework i included answer future reference,i would like ask i retrieve list fibo list check whether input value user inside fibo list b num sysmaxint fibo b b ab num b ab print it fibonacci number break else print it fibonacci number break thank,3 possibly efficient solution using close formula efficient see sven answer def fibs ab yield yield b true ab bab yield b n intrawinputplease enter number fib fibs n fib print number fibonacci number break fib n print number fibonacci number break the fibs generator gives list fibonacci numbers you go list every number check equal one user entered case done bigger one user entered also case done i hope useful least understand python generators,i would like ask i retrieve list fibo list check whether input value user inside fibo list b num sysmaxint fibo b b ab num b ab print it fibonacci number break else print it fibonacci number break thank,1 to thing use sitecustomizepy usercustomizepy file syspath modifications source python docs create sitecustomizepy file libsitepackages directory python installation imported time python interpreter launched,currently trying reference library code i top python file import sys syspathappend ccodemylibrary mylibrary import mylibrary then mylibrary part syspath long session active if i start new file i remember include syspathappend i feel like must much better way how i make mylibrary available every python script windows machine without use syspathappend time,2 probably heavy use string variables involves lot dynamic memory allocations try accepting parameters lpctstr assign string variables inside function lpctstrs pass parameters strcstr,have annoying problem code probably i something wrong python implementation much faster c implementation problems iterating hkeyclassesroot takes lot ram i assume c implementation uses lots variables fixed it also slow much slower python implantation code fixed the code even slower trying iterate hkeyclassesroot fixed new questions thanks nam nguyen understood causing leaks code directly effecting execution time code fixed one come c implementation runs fast python implementation c implementation include iostream include windowsh include stdioh include tcharh include string using namespace std define maxkeylength int recurseopenregexhkey hkey string subkey string search nothing dword sum tchar csubkeymaxkeylength dword nsubkeys dword pathlength maxpath tchar storekeynamemaxkeylength dword keylength hkey hkey hkey somehow need reassign hkey otherwise pass function bigger tough const char ccsearch searchcstr const char ccsubkey subkey ccsubkey subkeycstr copysubkeybegin subkeyendcsubkey convert string tchar regopenkeyexhkey ccsubkey keyread amphkey errorsuccess regqueryinfokeyhkey csubkey amppathlength nullampnsubkeys null null null null null null null errorsuccess sum nsubkeys dword subkeyindex subkeyindex nsubkeys subkeyindex keylength maxkeylength regenumkeyexhkey subkeyindex storekeyname ampkeylength null null null null errorsuccess string skeyname storekeyname convert tchar string explicitly subkey skeyname subkey skeyname sum recurseopenregexhkey skeyname regclosekeyhkey now closing right key return sum int main cout sum keys recurseopenregexhkeylocalmachine return python implementation import winreg def recurseregistrysearchkey keysearch subkey subkeypath x key winregopenkeykey subkey winregqueryinfokeykey x items rangex try subkey winregenumkeykey items keysearchlower subkeylower keysearch printsubkeypath subkey x recurseregistrysearchkey keysearch subkey subkeypath subkeypath subkey except windowserror pass return x printsum keys formatrecurseregistrysearchwinreghkeyclassesroot,1 there leak resource code you open hkey close hkey note difference case k k on side note store opened registry key hkey and happens hkey passed parameter shared among calls recurseopenregex that somehow need reassign hkey basically i advise immediately clean code bugs like hard spot code difficult read once done i believe find easier debugtrace,have annoying problem code probably i something wrong python implementation much faster c implementation problems iterating hkeyclassesroot takes lot ram i assume c implementation uses lots variables fixed it also slow much slower python implantation code fixed the code even slower trying iterate hkeyclassesroot fixed new questions thanks nam nguyen understood causing leaks code directly effecting execution time code fixed one come c implementation runs fast python implementation c implementation include iostream include windowsh include stdioh include tcharh include string using namespace std define maxkeylength int recurseopenregexhkey hkey string subkey string search nothing dword sum tchar csubkeymaxkeylength dword nsubkeys dword pathlength maxpath tchar storekeynamemaxkeylength dword keylength hkey hkey hkey somehow need reassign hkey otherwise pass function bigger tough const char ccsearch searchcstr const char ccsubkey subkey ccsubkey subkeycstr copysubkeybegin subkeyendcsubkey convert string tchar regopenkeyexhkey ccsubkey keyread amphkey errorsuccess regqueryinfokeyhkey csubkey amppathlength nullampnsubkeys null null null null null null null errorsuccess sum nsubkeys dword subkeyindex subkeyindex nsubkeys subkeyindex keylength maxkeylength regenumkeyexhkey subkeyindex storekeyname ampkeylength null null null null errorsuccess string skeyname storekeyname convert tchar string explicitly subkey skeyname subkey skeyname sum recurseopenregexhkey skeyname regclosekeyhkey now closing right key return sum int main cout sum keys recurseopenregexhkeylocalmachine return python implementation import winreg def recurseregistrysearchkey keysearch subkey subkeypath x key winregopenkeykey subkey winregqueryinfokeykey x items rangex try subkey winregenumkeykey items keysearchlower subkeylower keysearch printsubkeypath subkey x recurseregistrysearchkey keysearch subkey subkeypath subkeypath subkey except windowserror pass return x printsum keys formatrecurseregistrysearchwinreghkeyclassesroot,2 if library use throughout code install package properly either install sitepackages directory specific certain projects use virtualenv install within relevant virtualenvs,currently trying reference library code i top python file import sys syspathappend ccodemylibrary mylibrary import mylibrary then mylibrary part syspath long session active if i start new file i remember include syspathappend i feel like must much better way how i make mylibrary available every python script windows machine without use syspathappend time,2 i error trying install existing directory already easyinstall libpython i put link libpython libpython i saying fix right fix rather i pointing another reason might get error,i need run code linux machine python preinstalled i sudoers list machine i built python subdirectory home directory then i attempted use virtualenv first time got pythonpython virtualenvvirtualenvpy env new python executable envbinpython could find platform dependent libraries execprefix consider setting pythonhome prefixexecprefix installing setuptools complete output command appsusersdspitzerenvbinpython c python bootstrap setuptoo appsusersdspitzervirtualenegg could find platform dependent libraries execprefix consider setting pythonhome prefixexecprefix import site failed use v traceback traceback recent call last file string line module importerror no module named md installing setuptoolsdone traceback recent call last file virtualenvvirtualenvpy line module main file virtualenvvirtualenvpy line main usedistributeoptionsusedistribute file virtualenvvirtualenvpy line createenvironment installsetuptoolspyexecutable unzipunzipsetuptools file virtualenvvirtualenvpy line installsetuptools installreqpyexecutable unzip file virtualenvvirtualenvpy line installreq cwdcwd file virtualenvvirtualenvpy line callsubprocess cmddesc procreturncode oserror command appsusersdspitzerenvbinpython c python bootstrap setuptoo appsusersdspitzervirtualenegg failed error code should i setting pythonhome value i intentionally named env env lack better name not knowing i ignore errors i tried installing nose env cd nose ls authors doc lgpltxt noseegginfo selftestpy bin examples manifestin nosetests setupcfg build functionaltests news pkginfo setuppy changelog installrpmsh nose readmetxt unittests envbinpython setuppy install could find platform dependent libraries execprefix consider setting pythonhome prefixexecprefix traceback recent call last file setuppy line module nose import version version file appsusersdspitzernosenoseinitpy line module nosecore import collector main run runexit runmodule file appsusersdspitzernosenosecorepy line module future import generators importerror no module named future any advice,1 i generate random numbers python list then use set get uniques l setl set now may generate numbers get least unique ones truncate list i tried import random l range lappend randomrandom print lensetl gave set length there dups within generated random,i generating somewhere around rows random data around columns i need values unique the solid way i could think would query random generation make sure exist yet adds hundreds thousands queries the alternative would creating unique constraint table i would need way counting many duplicates fail i recreate rows i need know i generate exactly many random rows specified something retries new generation insert fails is way or i missing approach together,1 the logical place tryexcept would place offending calculation takes place def gener try yield except zerodivisionerror pass,is way python continue iterating exception throwed iteratorgenerator like code way skip zerodivisionerror continue looping gener without modyfying run function def gener yield def run gener print run script try run except zerodivisionerror print magick put,3 one possible solution wrapping problem code try except block def gener try divresult except zerodivisionerror divresult none yield divresult,is way python continue iterating exception throwed iteratorgenerator like code way skip zerodivisionerror continue looping gener without modyfying run function def gener yield def run gener print run script try run except zerodivisionerror print magick put,1 i also problem webserver but root problem webserver single thread answer one request so process one request cannot answer another url i asked urllib,in python i use urllib urllib open external urls google however i hitting issues opening localhost urls i python simplehttpserver running port i browse successfully using httplocalhost python simplehttpserver it also worth noting i running ubuntu cntlm running handle authentication corporate web proxy therefore wget actually work localhost either i think urllib issue test script testurllibpy import urllib print opening google google urlliburlopenhttpwwwgooglecom print googleread print google opened print opening localhost localhost urlliburlopenhttplocalhost print localhostread print localhost opened output testurllibpy opening google doctype htmlhtmlheadmeta httpequivcontenttype contenttexthtml charsetiso google opened opening localhost traceback recent call last file testurllibpy line module localhost urlliburlopenhttplocalhost file usrlibpythonurllibpy line urlopen return openeropenurl data timeout file usrlibpythonurllibpy line open response methreq response file usrlibpythonurllibpy line httpresponse http request response code msg hdrs file usrlibpythonurllibpy line error result selfcallchainargs file usrlibpythonurllibpy line callchain result funcargs file usrlibpythonurllibpy line httperror return selfparentopennew timeoutreqtimeout file usrlibpythonurllibpy line open response selfopenreq data file usrlibpythonurllibpy line open open req file usrlibpythonurllibpy line callchain result funcargs file usrlibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlibpythonurllibpy line doopen r hgetresponse file usrlibpythonhttplibpy line getresponse responsebegin file usrlibpythonhttplibpy line begin version status reason selfreadstatus file usrlibpythonhttplibpy line readstatus raise badstatuslineline httplibbadstatusline solution the problem indeed i using cntlm behind corporate web proxy specifics caused problem i sure the solution use proxyhandler proxysupport urllibproxyhandler opener urllibbuildopenerproxysupport print openeropenhttplocalhostread thanks loki pointing,1 for current purposes i satisfied solution i create separate config file cherrypy application i using class cherrypy parsing file cherrypylibreprconf import config settings configospathjoinconfpath settingscfg also python standard module handling config files named configparser this question also quite irrelevant serving multiple cherrypy applications i thought quite difficult cherrypy server i decided use cherrypy wsgi server behind appache solves problem explicitly,i trying use cherrypy virtualhost dispatcher serving multiple different applications my idea separate configuration file application i kinda lost if i use virtualhost dispatcher applications namespace example section database connection occur or can please help,1 first dictionary it list second way print values iterable dictionaries lists included loop errors error errors error endfor endif in view could use something like u joinerrors transform list single string use code like django template,i got dictionary containing form errors namely u phonealreadyregistered u emailalreadyregistered how i access values dictionary print strings screen this piece html code i using errors errorsvalues endif,1 leave templatedirs alone affects admin problem anyways the way override admin page include associated template default django admin templates yourprojecttemplatesadmin directory make necessary modifications see documentation httpsdocsdjangoprojectcomenrefcontribadminoverridingadmintemplates,in django run admin interface well customized admin index page my template dirs followed templatedirs projectpath templates and adminmediaprefix admin if comment line functions would work put uncommented admin interface shows specified file what run simultaneously thanks advance,1 simply add path pythonpath environment variable to go control panel system advanced environment variable user variables sections check already pythonpath if yes select click edit click new add paths pythonpath separated,currently trying reference library code i top python file import sys syspathappend ccodemylibrary mylibrary import mylibrary then mylibrary part syspath long session active if i start new file i remember include syspathappend i feel like must much better way how i make mylibrary available every python script windows machine without use syspathappend time,3 in python care order content assertitemsequalactualiterable expectediterable method care order content assertsequenceequalactualiterable expectediterable method in python assertitemsequal method named assertcountequal,is decent way unittest check equality contents two iterable objects i using lot tuples lists numpy arrays i usually want test contents type currently i simply casting type selfassertequal tuple selfnumpydata tuple selfreferencelist i used list comprehension ago selfassertequal x x zipselfnumpydata selfreferencelist but solution seems bit inferior typecast prints single values fails also fail different lengths reference data due zipfunction,3 you always add assertion methods testcase class def assertsequenceequalself selfassertequaltupleit tupleit take look defined httphgpythonorgcpythonfilecafbdlibunittestcasepyl,is decent way unittest check equality contents two iterable objects i using lot tuples lists numpy arrays i usually want test contents type currently i simply casting type selfassertequal tuple selfnumpydata tuple selfreferencelist i used list comprehension ago selfassertequal x x zipselfnumpydata selfreferencelist but solution seems bit inferior typecast prints single values fails also fail different lengths reference data due zipfunction,3 did forgot clientloadsystemhostkeys this example docs client sshclient clientloadsystemhostkeys clientconnect sshexamplecom stdin stdout stderr clientexeccommand ls l and use try block like try telnet except telnet false telnet false try ssh,i new python i writing script telenet device ip cases ssh usernamedeviceip telnet faiils for telnet ip work perfectly but ssh admin code fails i get error try bloc like socketerror ssh device i want ssh devices enter else block telnet ip fails try block in mainpy file try telnet module call tn telnetmodtelnetusername password device break else ssh module call ssh sshmodsshusername password device in telnetmod file code works import telnetlib def telnetuservarpasswordvar device tn tn telnetlibtelnetdevice python version and higher tnreaduntilusername tnwriteuservar r passwordvar tnreaduntilpassword tnwritepasswordvar r return tn in sshmod file code fails sure code import paramiko def sshuservarpasswordvar device ssh ssh paramikosshclient sshconnectdevice usernameuservarpasswordpasswordvar return ssh,1 no main saves status bar updates conducted using database connection part transaction i see two options avoid you either create separate database connection save status bar updates using don save status bar updates database instead use cache store as long use database cache backend ideally use memcached work fine my preferred option would second one you need delve django internals get database connection could likely end fragile messy,i function i save large number models thousands time takes several minutes i written progress bar display progress user the progress bar works polling url javascript looking requestsession value see state first call one saving the problem first call within transactioncommitonsuccess decorator i using database backed sessions i try force requestsessionsave instead immediately committing appended ongoing transaction this results progress bar updated saves complete thus rendering useless my question i sure i already know answer commit statements within transaction without whole lot ie i need commit requestsessionsave whilst leaving others many thanks alex,1 doncallisto got right jiracat run method takes three arguments logger jiraenv args first one supposed logger object passing string so error reports string loggers error attribute means your comment command line subprocesspopen python jira jiraservercom catall jira calling run method arguments have look bottom jirapy see sysargv edit having read code following python replicate command line call it bit complicated misses exception handling logic jirapy could get flaky i test import jira import os com jiracommands logger jirasetuplogging jiraenv home osenviron home commandname cat myargs jira server httpjiraservercom rpcsoapjirasoapservicevwsdl class options pass options options you might want set optionsuser optionspassword jirasoap jiraclientserver jirastartloginoptions jiraenv commandname com logger comruncommandname logger jiraenv myargs,i couple classes jirapy providing sample class jiracommand name default aliases summary summary usage mandatory commands none def initself commands selfcommands commands def dispatchself logger jiraenv args return exit code whole process lenargs args help h loggerinfo aliastext firstalias true selfaliases firstalias lenselfaliases aliastext alias else aliastext aliases firstalias false else aliastext firstalias aliastext loggerinfos ss selfname selfsummary aliastext selfusage opts else opts options loggerinfo loggerinfousage ss sysargv selfname selfmandatory opts loggerinfoselfusage return results selfrunlogger jiraenv args results return selfrenderlogger jiraenv args results else return def runself logger jiraenv args return nonzero object success return def renderself logger jiraenv args results return success return second class file jirapy class jiracatjiracommand name cat summary show fields issue usage issue key issue identifier eg ca def runself logger jiraenv args global soap auth lenargs loggererrorselfusage return issuekey args try jiraenv fieldnames soapservicegetfieldsforeditauth issuekey except exception e in case edit permission jiraenv fieldnames try return soapservicegetissueauth issuekey except exception e loggererrordecodee def renderself logger jiraenv args results for available field names see variables srcjavacomatlassianjirarpcsoapbeansremoteissuejava fields jiraenv fieldnames f key summary reporter assignee description environment project votes loggerinfogetnamef fields encoderesultsf loggerinfo type getnameresults type jiraenv types loggerinfo status getnameresults status jiraenv statuses loggerinfo priority getnameresults priority jiraenv priorities loggerinfo resolution getnameresults resolution jiraenv resolutions f created updated duedate loggerinfogetnamef fields datestrresultsf f results components loggerinfogetname components fields encodef name f results affectsversions loggerinfogetname versions fields encodef name f results fixversions loggerinfo fix versions encodef name todo bug jira api attachmentnames returned loggerinfostrresults attachmentnames todo restrict fields shown f results customfieldvalues fieldname strf customfieldid v f values loggerinfogetnamefieldname fields encodev return now jiracat using jiracommand argument how use jiracat get live results tried jira import jiracommand dirjiracommand doc init module aliases commands dispatch mandatory name render run summary usage jcmd jiracommandhttpjiraservercom jira import jiracat dirjiracat doc init module aliases commands dispatch mandatory name render run summary usage jc jiracatjcmd print jc jirajiracat instance xd jcruns cat qa traceback recent call last file stdin line module file jirapy line run loggererrorselfusage attributeerror str object attribute error,1 you examine search path modules import sys print njoinsyspath but argparse odd standard library,i trying run python script linux ssh secure shell command line environment i trying import argparse library gives error importerror no module named argparse i think python environment linux shell using argparse library i think i fix fix i find directories libraries used python environment copy argparse library i find directory located i would appreciate help finding directory i suppose i could include argparse library directory python script i would much rather argparse library place python libraries,1 datetimenow returns naive local datetime to convert kuala lumpur time first need make timezoneaware datetime convert kuala lumpur timezone the easiest way timezone conversions use pytz import pytz import datetime dt kualalumpurpytztimezone asiakualalumpur localtzpytztimezone europelondon here naive datetime dtdatetimenow use localize make datetime timezone aware nowlocaltzlocalizenow printnow use astimezone convert another timezone nowinkualalumpurnowastimezonekualalumpur printnowinkualalumpur due daylight savings time uk dst kuala lumpur time difference currently hours,on system i set current time zone clock kuala lumpur singapore utc puts clock forward eight hours course in python i using code get current timedate datetime import datetime datetimetuple datetimenow i using method i need individual parts including microsecond however always returns regular time eight hours front based selected time zone is another method,1 one possible solution using redis remote dictionary server redis fast powerful stable keyvalue storage used many projects stackoverflow also uses redis i recently start using redis current project creating user ratings my personal opinion redis simple fast stable it also pretty command line client i like on website i use synchronous redis package server uses twisted requires asynchronous approach fortunately thirdparty module txredis allows easily interact redis database using twisted i problems however txredis connection pool problem implement manually needed,i looking keyvalue database implementation working twisted asynchronous mode the one idea i using twisted memcache api memcachedb is solution,2 i think confusing two separate issues you could processing many individual tasks individual task could inefficient you may know problem clear question to track many tasks processed i suggest look celerymon if particular appears often would expect investigate getting called profiling whole celery probably helpful get lots code control as say also means problem running production i suggest look adding profiling code directly task definition you use cprofilerun func layer indirection celery code run task profiled if generate unique filename pass second parameter run directory full profile data inspect taskbytask basis use pstatsadd combine multiple task runs together finally pertask profiling means also turn profiling using setting project code either globally task rather needing modify init scripts server,as i see top utility celery procecess consume lot cpu time so i want profile i manually developer machine like python cprofile testdate ymdtprof managepy celeryd b but accurate timings i need profile production machine on machine fedora celery launched init scripts eg service celeryd start i figured scripts eventually call managepy celerydmulti eventually so question i tell celerydmulti start celery profiling enabled in case means add cprofile outprof options python any help much appreciated,3 the easiest way i know explain show using echotrue sessionflush begin implicit insert into users username password values alice none sessioncommit commit flush causes data sent database commit causes commit tells database keep data sent as others stated commit also cause flush occur needed,does anybody know main difference sessioncommit sessionflush sqlalchemy,2 you appear using bitonly python possibly one downloaded pythonorg they built gcc ppc archs compatibility multiple os x versions when building c extension module python distutils attempt use compiler version options python build because gcc support ppc architecture longer included xcode os x use bitonly builds need build extension modules either install bitbit version python current pythonorg use applesupplied system pythons usrbinpython defaults,i tying build pil mac os x i getting error running build running buildpy running buildext using frameworks systemlibraryframeworks building imaging extension gcc fnostrictaliasing fnocommon dynamic arch ppc arch g o dndebug g o dhavelibz isystemlibraryframeworkstclframeworkheaders isystemlibraryframeworkstkframeworkheaders ilibimaging ioptlocalinclude ilibraryframeworkspythonframeworkversionsinclude iusrinclude ilibraryframeworkspythonframeworkversionsincludepython c imagingc buildtempmacosxfatimagingo unable execute gcc no file directory error command gcc failed exit status i latest xcode installed gcc exist gcc i know trying use gcc,1 you could use beautifulsoup htmlstr input typehidden autocompleteoff idpostformid namepostformid valuedaebbecdcaebeaf input typehidden namefbdtsg valueaqcysohu autocompleteoff beautifulsoup import beautifulsoup soup beautifulsouphtmlstr n name n value n soupfindall input u postformid u daebbecdcaebeaf u fbdtsg u aqcysohu,i trying get input values html doc want parse values hidden input fields for example i parse value snippet using python input typehidden autocompleteoff idpostformid namepostformid valuedaebbecdcaebeaf input typehidden namefbdtsg valueaqcysohu autocompleteoff and output python function return something like postformid daebbecdcaebeaf fbdtsg aqcysohu,3 you want use listfilter the property looking listdisplay the documentation offers example create column behaves like boolean display in short something like create method class def isactivatedself selfbar something return true return false add boolean method attribute directly isactivated method isactivatedboolean true add method field listdisplay class myadminmodeladmin listdisplay name isactivated you notice column name probably is activated something like if want column heading change use shortdescription method attribute isactivatedshortdescription activated,in django admin field booleanfield nullbooleanfield django display pretty icon instead true false now i really booleanfield model i property fior i like display icons i try django screams someadminlistfilter refers isactivated refer field is possible display nice little icons field without hacking django much thanks,3 going mathematica definition small function job season delta taste def sameqpram pram delta typepram typepram pram pram return true try abspram pram delta return true except exception pass return false,how i achieve effect operator python for example i want false true,1 imshow much faster pcolor returns polycollection going fairly slow million elements whereas imshow image note indexing pcolor slightly different imshow though may need worry depending used pcolor also often going pcolor imshow one wants set interpolationnearest imshow large images may matter either,i want plot d array roughly x values corresponding color scale so i used matplotlibpcolor reason super slow gets dimensions like minutes plot what reason would converting float values int help are alternatives pcolor pylab import datagenfromtxt datatxt autostriptrue casesensitivetrue pcolordatacmap hot colorbar show datatxt containing array the loading process take seconds main computing time definitely used both pcolor show function roughly maybe secs,3 or lxml import lxmlhtml htmlstr input typehidden autocompleteoff idpostformid namepostformid valuedaebbecdcaebeaf input typehidden namefbdtsg valueaqcysohu autocompleteoff parse string turn tree elements htmltree lxmlhtmlfromstringhtmlstr iterate input element tree print relevant attributes inputel htmltreexpath input name inputelattrib name value inputelattrib value print name value gives postformid daebbecdcaebeaf fbdtsg aqcysohu,i trying get input values html doc want parse values hidden input fields for example i parse value snippet using python input typehidden autocompleteoff idpostformid namepostformid valuedaebbecdcaebeaf input typehidden namefbdtsg valueaqcysohu autocompleteoff and output python function return something like postformid daebbecdcaebeaf fbdtsg aqcysohu,2 mercurial keyword extension probably want it supports revision format pretty much exactly,i application i want print box revisionversion mercurial suppose revision deadbeef know in old times cvs could use something like revision substitute automatically what best practice mercurial,1 l l b c e f x xy zipll b c e f or sumx x zipll b c e f import itertools listitertoolschainx x zipll b c e f we also without zip li li xrangeminlenl lenl b c e f x li x enumeratel assuming lenl lenl b c e f deals different lengths lx ly ll lllenllenl shortcut ifelse x lyi x enumeratelx some benchmarks here benchmarks answers provided far it looks like popular answer x xy zipll pretty much par hammar map solution on hand alternative solutions i given proven rubbish however fastest solutions seems ones uses list comprehension without zip mehome setuplxx x xrangelxx x xrange mehome raises indexerror lenl lenl mehome python timeit setup x li x enumeratel loops best msec per loop mehome deals length inconsistencies mehome python timeit setup lxlylllllenllenlx lyi x enumeratelx loops best msec per loop mehome almost fast easier read mehome python timeit setup li li xrangeminlenllenl loops best msec per loop mehome python timeit setup lx xy zipll loops best msec per loop mehome python timeit setup lmaplistadd l l loops best msec per loop mehome python timeit setup lsumx x zipll loops best msec per loop mehome python timeit setupimport itertools llistitertoolschainx x zipll loops best msec per loop zac suggestion really quick comparing apples oranges since list extension inplace l instead creating third list so l longer needed great solution mehome python timeit setup index x enumeratel xextendlindex loops best msec per loop however l kept intact performance would sub par include deepcopy mehome python timeit setupfrom copy import deepcopy ldeepcopyl index x enumeratel xextendlindex loops best msec per loop,i two lists lists equivalent numbers items the two lists look like l l b c e f i looking create one list looks like lmerge b c e f i attempting use zip something like list list zipl l lmerge list list what best way combine two lists lists thanks advance,3 l l b c e f lmerge x x zipl l b c e f,i two lists lists equivalent numbers items the two lists look like l l b c e f i looking create one list looks like lmerge b c e f i attempting use zip something like list list zipl l lmerge list list what best way combine two lists lists thanks advance,1 index x enumeratel xextendlindex,i two lists lists equivalent numbers items the two lists look like l l b c e f i looking create one list looks like lmerge b c e f i attempting use zip something like list list zipl l lmerge list list what best way combine two lists lists thanks advance,1 you want combine sublists plus operator iterate list comprehension lmerge zipl l,i two lists lists equivalent numbers items the two lists look like l l b c e f i looking create one list looks like lmerge b c e f i attempting use zip something like list list zipl l lmerge list list what best way combine two lists lists thanks advance,2 use stringsplit break required parts,i folder containing books various formats pdf djvu dvi follow format name book authoran identifier indicating searchable notfiletype i want make list books format xyzt x name book author etc my problem i file oslistdir homeusernamebooks file string thus immutable i cannot change,1 that problem since want change you want extract pieces new strings one simple way might something like top filesplit name top fields topsplit author fields searchable fields filetype fields mybooksappendname author searchable filetype this builds flat list mybooks could course something clever,i folder containing books various formats pdf djvu dvi follow format name book authoran identifier indicating searchable notfiletype i want make list books format xyzt x name book author etc my problem i file oslistdir homeusernamebooks file string thus immutable i cannot change,1 file string thus immutable i cannot change so what want change you want parse pieces different punctuation marks you want create new strings existing string nothing changes you split partition get much job done immutability string totally irrelevant,i folder containing books various formats pdf djvu dvi follow format name book authoran identifier indicating searchable notfiletype i want make list books format xyzt x name book author etc my problem i file oslistdir homeusernamebooks file string thus immutable i cannot change,1 maplistadd l l b c e f,i two lists lists equivalent numbers items the two lists look like l l b c e f i looking create one list looks like lmerge b c e f i attempting use zip something like list list zipl l lmerge list list what best way combine two lists lists thanks advance,3 strings immutable mean create tuple need string something like work def filetotuplefile titleauthor searchable ext filersplit title author titleauthorrsplit return title author searchable ext you use variety ways convert file list list tuples couple options booklist mapfiletotuple oslistdir homeusernamebooks booklist filetotuplef f oslistdir homeusernamebooks strrsplit maxsplit param used fail titles contain period dash authors contain period example filetotuple narnia the silver chair cs lewispdf narnia the silver chair cs lewis pdf,i folder containing books various formats pdf djvu dvi follow format name book authoran identifier indicating searchable notfiletype i want make list books format xyzt x name book author etc my problem i file oslistdir homeusernamebooks file string thus immutable i cannot change,2 south migrates apps order appear installedapps tuple settingspy so make sure appb comes appa settingspy work,i recently begun using south migrations django project all going well recently i ran peculiar issue i two apps project say appa appb a model appa foreign key model appb when i trying build system i ran syndb created auth south tables then i ran migrate threw errors when tried creating model appa referenced model appb model appb migratedcreated yet therefore error in order resolve i manually migrate appb first appa am something wrong how south supposed know migration order across apps thanks,3 newstyle classes selfclass attribute available in xcompatible python classes newstyle before x use class aobject declare newstyle,this question similar pertains static methods in python i reference class generically static way like phps quotselfquot keyword how refer class generically instance method eg usrbinpython class b c def initself printab generic explicitly refer classmethod def instancemethodcls printclsb generic instance method,2 for oldstyle classes code python x code class inheriting object use class property def initself printselfclassb python x oldstyle class for newstyle classes code python code use type def initself printselfclassb class works newstyle class printtypeselfb internally type uses class property,this question similar pertains static methods in python i reference class generically static way like phps quotselfquot keyword how refer class generically instance method eg usrbinpython class b c def initself printab generic explicitly refer classmethod def instancemethodcls printclsb generic instance method,1 quoting ã‰ric araujo python bug distutils warning in packagingdistutils recommended idiom looks like setupcfg metadata descriptionfile readmewhatever sdist include file you also write description setupcfg directly readme file included extrafiles field so basically ignore warning distutils missing readmetxt also distutils supposedly emit warning i tested could try upgrading,python packaging tools expect readme file named readme readmetxt but follow convention github displays plain text project page pretty unlike beautiful html version named readmerst is technique make pypi github happy readme,1 you wanting change string fact immutable irrelavent you still make new items here small function tested even want def booktupleinfo bookauthor searchable ext inforsplit book author bookauthorrsplit return book author searchable ext booklist filename oslistdir homeusernamebooks booklistappendbooktuplefilename the first split uses rsplit splits two times case periods title author name starts end case periods title author name the second split max split reasons,i folder containing books various formats pdf djvu dvi follow format name book authoran identifier indicating searchable notfiletype i want make list books format xyzt x name book author etc my problem i file oslistdir homeusernamebooks file string thus immutable i cannot change,1 append end print statement print newline exit loop add additional print move next row j range print pxpypz print assuming rows number columns get number columns using lenrowsplit also definitely shorten code quite bit i sure purpose j following equivalent j range xp yp zp mapfloat posnisplitjj xc yc zc mapfloat posnisplitjj,i following file i trying manipulate the file contains numbers i trying write program subtract rows print results file my program dtesttxt name input file the name program makedistancepy math import posnfile opendtesttxtr posn posnfilereadlines posnfileclose range lenposn j range j xp floatposnisplit yp floatposnisplit zp floatposnisplit xc floatposnisplit yc floatposnisplit zc floatposnisplit else xp floatposnisplitj yp floatposnisplitj zp floatposnisplitj xc floatposnisplitj yc floatposnisplitj zc floatposnisplitj px fabsxcxp py fabsycyp pz fabszczp print pxpypz the program calculating values correctly i try call program write output file mpipython makedistancepy distancedat the output file distancedat contains columns contain how i tell program shift columns print step j for j program output first columns j program output second columns forth finally len function gives number rows input file function gives number columns file thanks,3 what marshal module according benchmarks significantly faster pickle however make sure read understand warnings top documentation also make sure use cpickle if try — significantly faster pickle alternatively since data fairly simple could write using pyrex if want go route msgpack serializer would good starting point,i writing python program runs rather slow phone well platforms reading data phone pickle takes seconds simplejson significantly slower the phone runs python the data various lists dictionaries group classes i convert json format relatively quickly the bulk time seems pickle json processing reading writing json pickle file much faster using pickle json the program read entire dataset write periodically i suppose i could create way translate data text see faster reinventing wheel seldom worthwhile endeavor what storage alternatives might make sense,2 mysqldb python interface mysql mysql and apparently mysqldb needs command mysqlconfig need install first can confirm install mysql running mysql shell that give response mysql command found which linux distribution using mysql prepackaged linux distributions for example debian ubuntu installing mysql easy sudo aptget install mysqlserver mysqlconfig different package installed assuming debian ubuntu sudo aptget install libmysqlclientdev using mariadb drop replacement mysql run sudo aptget install libmariadbclientdev,i trying get python script run linux server i connected via ssh the script uses mysqldb i components i need i try install mysqldb via setuptools like python setuppy install i get following error report related mysqlconfig command sh mysqlconfig command found traceback recent call last file setuppy line module metadata options getconfig file usrlibpythonmysqlpythonsetupposixpy line getconfig libs mysqlconfiglibsr file usrlibpythonmysqlpythonsetupposixpy line mysqlconfig raise environmenterrors found mysqlconfigpath environmenterror mysqlconfig found has anyone else encountered error resolve itwhat i successfully install mysqldb,3 i typically handle adding extern destroy object function i pass pointer back delete cpp someclass createobj return new someclass void destroyobjsomeclass pobj delete pobj pobj null h extern c someclass createobj void destroyobjsomeclass py class someobj def initself selfsolib cdllloadlibrarypathso createobj selfsolibcreateobj createobjrestype pointerclong selfobjref createobj stuff selfobjref def delself selfsolibdestroyobjselfobjref,i using ctypes extending c functions mydll python ctypes import cdll libx cdllloadlibrarydmytestprojectdebugmydlldll py file class methods call functions mydll ctypes class mytestclass def initselfid libamytestclassindllnewrestype ctypescvoidp selfobj libamytestclassindllnewid corresponding c function mytestclassindllnew defined mydll extern c declspecdllexport void mytestclassindllnewchar id ptestobject new cmytestclassindllcstringid return void ptestobject note i using new instantiate object vc dll returning pointer i set restype function py file ctypescvoidp the script i execute contains following testob mytestclass works fine testob obtain used call methods internally call c functions mydll however object created using new mydll returned mytestclassindllnew function how object destroyed somewhere need use delete ptestobject destructor called cleanup memory deallocated,2 i say i fully understand motivation insisting single query i think best bet two simple queries select id from statustable where value this gives id entry exists case skip step insert into statustablevalue values returning id this give id newly created entry lastly although i verified whether problem fetchone across commit looks slightly suspect,my postgres query query insert into statustablevalue select where not exists select id value from statustable where value returning id status status cursorpostgresexecutequery connpostgrescommit statusid cursorpostgresfetchone print statusid strstatusid i need get freshly inserted status value id doesnt exist select id already exist returning id choked query entirely i remove atleast get selective insertion working any clues get statusid in another instance i upsertinsert exist update otherwise here i need inserted updated row id no i using stored procedures first question thanks advance,3 it exactly clear looking consider things w match word contain letters numbers underscores unicode wordlike characters using raw string dealing python regex preferred escape backslashes this means need prefix every regex pattern r like r otherwise match literal backslash need use when doubt check library docs another source regex,i need find function definitions like function param param param i using following regular expression python sss something like refindallssssourcecodestring give function names working please suggest improvements regular expression i new regular expressions,1 the following code gqlquery statements works item itemset itemjokeid itemjokeid itemposition itemput item itemset itemjokeid itemjokeid itemposition itemput currentid deck range similarids dbgqlquery select from itemset where jokeid and position in currentid deckfetch item similarids logginginfos itemjokeid itemposition it returns info mainpy info mainpy,here query currentid deck range similarids dbgqlquery select from itemset where jokeid and position in currentid deckfetch here model class itemsetdbmodel jokeid dbintegerproperty jokeid dbintegerproperty position dbintegerproperty when i execute query googleappengine data viewer i get results what i missing,1 instead appending contentnav go parent contentdiv insert new div particular index to find index use contentdivindexcontentnav gives index contentnav within contentdiv adding one gives desired index import lxmletree et content div idcontents div idcontentnav something goes div p contents p div tree etfromstringcontent parserethtmlparser contentnav treefinddivid contentnav contentdiv contentnavgetparent contentdivinsertcontentdivindexcontentnav etxmldiv style clear div printettostringtree yields htmlbodydiv idcontents div idcontentnav something goes div div styleclear bothp contents p divbodyhtml,i following html markup div idcontents div idcontentnav something goes div p contents p div to fix css issue i want append div tag div styleclearbothdiv contentnav div like div idcontents div idcontentnav something goes div div styleclearbothdiv p contents p div i way import lxmletree tree lxmletreefromstringinputstring parserlxmletreehtmlparser contentnav treefinddivid contentnav contentnavappendlxmletreexmldiv style clear div but append new div right contentnav div inside div idcontentnav something goes div styleclearbothdiv div is way add div middle contentnav div p like inside contents thanks,3 your main function setup code working properly i sure set one way get working def main run main program root tk gui bouncygui guipack rootmainloop,i full time student taking first class python this strange working longer showing buttons labels entry fields i sure something i removed added i loss any ideas all suggestions appreciated tkinter import import tkfont import tkmessagebox class bouncyguiframe the gui used interface bouncy calculation chapter section def initself frameinitself establish base frame selfmastertitlecalculate bounciness ball selfmasterrowconfigure weight selfmastercolumnconfigure weight selfmastergrid selfmasterresizable establish components capturing height selfheightlabel labelself text height initial drop justify left selfheightlabelgridrow column selfheightvar doublevar selfheightentry entryself textvariable selfheightvar justify center selfheightentrygridrow column establish bounciness index selfbouncyindex labelself text bounciness index justify left selfbouncyindexgridrow column selfbouncyvar doublevar selfbouncyentry entryself textvariable selfbouncyvar justify center selfbouncyentrygridrow column selfbouncyvarset establish number allowable bounces selfnumberbounces labelself text number bounces justify left selfnumberbouncesgridrow column selfnumberbouncesvar intvar selfnumberbouncesentry entryself textvariable selfnumberbouncesvar justify center selfnumberbouncesentrygridrow column establish field response selfanswer labelself text distance travelled justify left selfanswergridrow column selfanswervar doublevar selfanswerfont tkfontfontweightbold size selfanswerentry entryself textvariable selfanswervar justify center font selfanswerfont selfanswerentrygridrow column selfanswerentryconfigstate disabled bg green create frame hold buttons selfbuttonframe frameself selfbuttonframegridrow column columnspan create reset button selfbuttonreset buttonselfbuttonframe text reset command selfreset width padx pady selfbuttonresetgridrow column selfbuttonresetconfigstate disabled create calculate button selfbuttoncalc buttonselfbuttonframe text calculate command selfcalculate width padx pady selfbuttoncalcgridrow column selfbuttoncalcconfigstate normal def resetself allow screen reset fresh data entry selfheightvarset selfnumberbouncesvarset selfanswervarset selfbuttoncalcconfigstate normal selfbuttonresetconfigstate disabled selfnumberbouncesentryconfigstate normal selfbouncyentryconfigstate normal selfheightentryconfigstate normal def calculateself calculate bounciness update gui selfvaliddatatypes selfanswervarsetcomputedistanceselfheightvarget selfbouncyvarget selfnumberbouncesvarget selfnumberbouncesentryconfigstate disabled selfbouncyentryconfigstate disabled selfheightentryconfigstate disabled selfbuttoncalcconfigstate disabled selfbuttonresetconfigstate normal def validdatatypesself themessage selfisintselfnumberbouncesvarget true themessage please reenter integer value number bouncesn elif selfisfloatselfbouncyvarget true themessage please reenter float value bounciness indexn elif selfisfloatselfheightvarget true themessage please reenter float value initial height lenmessage tkmessageboxshowerrormessage message parent self return false else return true def isintself value test ensure value entered integer try x intvalue except valueerror if return false return false integer return true return true def isfloatself value test ensure value entered float value try x floatvalue except valueerror if return false return false if float return true return true def computedistanceheight index bounces compute distance travelled total x rangebounces total height height index total height return total def main run main program bouncyguimainloop main,1 the argparse module added python httpdocspythonorglibraryargparsehtml prior common way handle commandline arguments probably getopt httpdocspythonorglibrarygetopthtml of course always handle commandline manually simply looking sysargv however getopt good abstraction layer argparse even better if truly need argparse older environments debatable google code project maintaining include project httpcodegooglecompargparse,i trying run python script linux ssh secure shell command line environment i trying import argparse library gives error importerror no module named argparse i think python environment linux shell using argparse library i think i fix fix i find directories libraries used python environment copy argparse library i find directory located i would appreciate help finding directory i suppose i could include argparse library directory python script i would much rather argparse library place python libraries,3 on serverside clearly need socket server this server creates new thread every incoming client connection once connection established client thread instantiated communication require additional thread business parallel listening socket communication synchronous in case asynchronous communication need python provides excellent asynchronous socket handler,i trying figure make server accept multiple clients one time while i need client able send receive data server time would make threaded server and thread listening data and another thread sending information client then client side need use threads sendget info,1 the count indeed foiling to see create second identical query apply saved cursor see happens by way key order implicit,i thought i understood concept cursors queries based httpcodegooglecomappenginedocspythondatastorequeryclasshtml apparently based i code i items datastore i want iterate small batch sizes query eventall queryorderkey batchsize expecting return st items results queryfetchlimitbatchsize logginginfocount results querycount lenresults reports count results item results print item print items expected move next batch block cursor querycursor querywithcursorcursor results queryfetchlimitbatchsize logginginfocount results querycount lenresults reports count results expecting move item how i iterate entities batches does querycursor return cursor end st batchsize start block,1 if display header coming back server server simply cut it may request bad unlikely it may exceeded bandwidth restrictions it may requests appear ddos attack happening frequently,posterencode import multipartencode posterstreaminghttp import registeropeners def picscrazystrint registeropeners datagen headers multipartencodeimagefile openstr rb request urllibrequesthttpwwwpicscrazycomprocessphp datagen headers str filename int another flag the code upload file image hosting website i using poster poster post requests the program stops request statement gives error i cant understand error whether problem network program below traceback error traceback recent call last file cdocuments settingsadministratordesktopfor exbiirespy line module picscrazyfname file cdocuments settingsadministratordesktopfor exbiirespy line picscrazy printurlliburlopenrequestread file cpythonliburllibpy line urlopen return openeropenurl data file cpythonliburllibpy line open response selfopenreq data file cpythonliburllibpy line open open req file cpythonliburllibpy line callchain result funcargs file cpythonlibposterstreaminghttppy line httpopen return selfdoopenstreaminghttpconnection req file cpythonliburllibpy line doopen raise urlerrorerr urlerror urlopen error connection reset peer,1 if asking inject code running python process want httpsfedorahostedorgpyrasite,i seen sites talking injecting dll httpwwwcodeprojectcomkbdlldllinjectiontutorialaspx i struggling get exe work helptips would appreciated the best way i know explain runpe execute exe memory does help,1 you could using single table inheritance however two columns different tables exactly trying possible unique constraint across tables if single table inheritance option probably want either enforce uniqueness python abandon sqlalchemy inheritance use foreign key link foo bar parametric you could foreign key name then unique constraint name prop,a top class called parametric used create objects parameters associated class parametricobject def initself name selfname name selfpars class fooparametric def initself name prop selfprop prop parametricinitself name class barparametric def initself name prop selfprop prop parametricinitself name i use sqlalchemy orm engine i want impose unique constraint ensures combination name prop unique given class eg one instance foo called myfoo prop value say myprop i see reference name column parametric foo table uniqueconstraint section is uniqueness something imposed via foreign key directives,1 if following python database api spec could use cursor curs conncursor cursexecute select bigtable use cursfetchone cursfetchmanychunksize,i query result set million rows i need processing row code currently query connquerysql results querygetresult row results blah i sure i imagine getresult pulling entire result set is case i imagine way pull chunks result set across wire needed i immediately see something like pg module docs is possible pgdb module instead approach my concerns memory application machine i rather load millions rows memory i help is even worth worrying,1 you could two separate fields model one html one bbcode make html one show admin interface using exclude property modeladmin class admins see edit bbcode field you get html content overriding model save method place bbcodehtml function something along lines def saveself args kwargs selfhtml bbcodehtmlselfbbcode supermymodel selfsaveargs kwargs documentation customizing admin interface httpsdocsdjangoprojectcomendevrefcontribadmin,i writing django website i want use built admin interface allow admins edit content so learn html i want able format content using simple bbcode tags i written pair functions convert bbcode html markup call htmlbbcode bbcodehtml basically i need following pass html database htmlbbcode bbcode diplayed admin editing forms pass bbcode admin form bbcodehtml admin presses save goes database able retrieve content html actually going form part webpage i cannot find anywhere pass input admin interface custom function saving result database vice versa can anyone point right direction,1 use asynchronous socket example server could found client code no direct hassle threads depending needs probably need asynchronous client,i trying figure make server accept multiple clients one time while i need client able send receive data server time would make threaded server and thread listening data and another thread sending information client then client side need use threads sendget info,1 if want b c merged c b collections import defaultdict dict defaultdictlist dictupdateitem item item list item list dictitemappenditem want merged c dict dictitem item item list dict item list key item key dict dictkey dictkey item you using item keys use datatype fits in case dictionary mapping this works average linear time omn n lengths lists any solution using nested loops similar omn if really need data back list list key value key value dictiteritems,i two lists lists ie expired test active test well andrew alexander john smith lets call list list i want merge list list only note pseudocode trying figure program python x list x list i sure write by merge i mean pseudocode listx listx listx x list x list output desired expired test andrew alexander active test john smith the critical point x going match perfectly,1 use async io there dozen async io socket libs python here brief benchmark i also tested gevent eventlet asyncore twisted pyev pycurl tornado twsited stable slow also easy start gevent eventlet libevent easy start fast code looks like blocking issues forking pycurl libcurl fast easy ok flags magic example http pyev libev must understand almost like polling tornado polling python fast enough think stable also easy start asyncore really fast use uglyugly don use threads python unless really know python threads really big friends unless version must new gil,i trying figure make server accept multiple clients one time while i need client able send receive data server time would make threaded server and thread listening data and another thread sending information client then client side need use threads sendget info,2 using agf idea employing collectionsdefaultdict omn n lengths lists import collections import itertools x expired test active test andrew alexander john smith resultcollectionsdefaultdictlist item itertoolschainxy resultitemappenditem resultlistitertoolschainfromiterablevalue value resultvalues printresult yields expired test andrew alexander active test john smith in comments op says desired output expired test andrew alexander active test john smith different desired output posted original question then import collections import itertools x expired test active test andrew alexander john smith result item itertoolschainxy resultsetdefaultitemitemextenditem resultresultvalues printresult this one times i found using setdefault convenient collectionsdefaultdict,i two lists lists ie expired test active test well andrew alexander john smith lets call list list i want merge list list only note pseudocode trying figure program python x list x list i sure write by merge i mean pseudocode listx listx listx x list x list output desired expired test andrew alexander active test john smith the critical point x going match perfectly,1 you need use numpy read whole file know many columns use awkward comma end print statement use list subscripting use mathfabs explicitly close file try untested opendtesttxt r posnfile previous none line posnfile current floatx x linesplit previous delta absc p c p zipcurrent previous print joinstrd delta previous current,i following file i trying manipulate the file contains numbers i trying write program subtract rows print results file my program dtesttxt name input file the name program makedistancepy math import posnfile opendtesttxtr posn posnfilereadlines posnfileclose range lenposn j range j xp floatposnisplit yp floatposnisplit zp floatposnisplit xc floatposnisplit yc floatposnisplit zc floatposnisplit else xp floatposnisplitj yp floatposnisplitj zp floatposnisplitj xc floatposnisplitj yc floatposnisplitj zc floatposnisplitj px fabsxcxp py fabsycyp pz fabszczp print pxpypz the program calculating values correctly i try call program write output file mpipython makedistancepy distancedat the output file distancedat contains columns contain how i tell program shift columns print step j for j program output first columns j program output second columns forth finally len function gives number rows input file function gives number columns file thanks,1 are trying add mixin class class defined if could inject mixin way def injectclassmixin def injectclasscls return typeclsnamemixinclsbasesdictclsdict return injectclass class mixinobject def mixself print mix injectclassmixin class fooobject def fooself print foo class goofoo def gooself print goo googoo goomix goofoo googoo prints mix foo goo if want generality injectclass could make specialized class decorator mixes decorator def decoratecls class decoratorobject def decoself print deco return typeclsnamedecoratorclsbasesdictclsdict decorate class fooobject def fooself print foo result,i trying decorate class another class i also want inherit decorated class i get errors here code class decorator def initself decorated pass decorator class foo pass class goofoo pass the error i get i try subclass foo traceback recent call last nbspnbspnbspfile testpy line nbspnbspnbspnbspnbspnbspclass goofoo typeerror init takes exactly positional arguments given by adding another init function decorator def initself args arg args printarg i get following output class mainfoo goo maindecorator object xb module main what parameters i using inside decorator,1 sysexit raises systemexit seeing as inherit exception the exception inherits baseexception instead standarderror exception accidentally caught code catches exception this allows exception properly propagate cause interpreter exit,i script containing section similar python import sys listid cow prev cow try listidprev print formatlistidprev sysexit except print exception occurred exiting error sysexit i noticed though printing line also logs exception if remove tryexcept block interpreter shows error if catch specific error like valueerror except block executed import sys listid cow prev cow try listidprev print formatlistidprev sysexit except exception k print exception occurred exiting error exception print kargs sysexit the except block executed process finishes return code so exception exception hierarchy import sys listid cow prev cow try listidprev print formatlistidprev sysexit except baseexception k print exception occurred exiting error exception print kargs sysexit produces cow cow exception occurred exiting error exception and process finishes exit code why except block executed,3 sysexit simply raises systemexit that exits program when catch exceptions also catch systemexit,i script containing section similar python import sys listid cow prev cow try listidprev print formatlistidprev sysexit except print exception occurred exiting error sysexit i noticed though printing line also logs exception if remove tryexcept block interpreter shows error if catch specific error like valueerror except block executed import sys listid cow prev cow try listidprev print formatlistidprev sysexit except exception k print exception occurred exiting error exception print kargs sysexit the except block executed process finishes return code so exception exception hierarchy import sys listid cow prev cow try listidprev print formatlistidprev sysexit except baseexception k print exception occurred exiting error exception print kargs sysexit produces cow cow exception occurred exiting error exception and process finishes exit code why except block executed,2 in addition answers systemexit inherit exception python exception hierarchy httpdocspythonorglibraryexceptionshtml,i script containing section similar python import sys listid cow prev cow try listidprev print formatlistidprev sysexit except print exception occurred exiting error sysexit i noticed though printing line also logs exception if remove tryexcept block interpreter shows error if catch specific error like valueerror except block executed import sys listid cow prev cow try listidprev print formatlistidprev sysexit except exception k print exception occurred exiting error exception print kargs sysexit the except block executed process finishes return code so exception exception hierarchy import sys listid cow prev cow try listidprev print formatlistidprev sysexit except baseexception k print exception occurred exiting error exception print kargs sysexit produces cow cow exception occurred exiting error exception and process finishes exit code why except block executed,1 in method call need explicitly specify self just call selfproductndnd desired behavior class methods always extra self first argument refer self inside method body note also unlike languages java many self common good practice name first argument could call however like use,so i learning use classes python i creating simple program perform arithmetic operations rational numbers i creating class called arithmeticoperations in class i main function definition prompts user numerator denominator rational numbers performs either sum difference product quotient based choice user the operations performed separate function right i created main function product function i run i get error says typeerror product takes exactly arguments given i sure something simple i new classes bit trouble debugging here current program class arithmeticoperations given numbers u v side design pattern def productselfn nd selfnumerator nn selfdenominator dd print n n selfnumerator selfdenominator def mainself n input enter numerator fraction input enter denominator fraction n input enter numerator fraction input enter denominator fraction print add n subtractn multiplyn divide question input choose operation question operation selfsumselfndnd elif question operation selfdifferenceselfndnd elif question operation selfproductselfndnd elif question operation selfquotientselfndnd else print invalid choice ao arithmeticoperations aomain,3 don use threads it confusing tkinter mainloop for second window create toplevel window your code minimal modifications tkinter import import thread needed class app def initself master print master def creatnew recommend making instance method admintoplevel changed tk toplevel lablabeladmintext workes labpack adminminsizewidth height adminmaxsizewidth height adminconfigurebg light green adminmainloop call mainloop entire app def need define function lalabelmastertext lapack bubuttonmastertext clicks commandcreatnew removed lambdathread bupack need code placed function admin tk adminminsizewidth height adminmaxsizewidth height app appadmin adminmainloop,run code click button tkinter import import thread class app def initself master print master def creatnew admintk lablabeladmintext workes labpack adminminsizewidth height adminmaxsizewidth height adminconfigurebg light green adminmainloop def lalabelmastertext lapack bubuttonmastertext clicks commandlambda threadstartnewthreadcreatnew bupack admin tk adminminsizewidth height adminmaxsizewidth height app appadmin adminmainloop get second tkinter window white blank screen makes programs respond ideas,2 i think want set hasdeletepermissionself objnone that allow decide cannot delete entire inline,i using tabularinlines administrate manytomany relationships django admin when conditions met i want make inline read to achieve i override getreadonlyfields method basemodeladmin this works like charm problem read fields still deleteable checkbox deletion still still works of course i could set candelete field tabularinline false prevents deletion also read cases my question how i set tabularinline i prohibit deletion read fields enable fields readwriteable edit i use django solution also works would perfect,1 here rough stab depending nature digmoreobjects may need adjust condition import time results true mark timetime newobjs digmoreobjectsobj elapsed timetime mark resultsappendnewobjs elapsed count threshhold objs elapsed results count lenobjs digmoreobjects returns one time threshhold elapsed threshhold count break,this question could answered languageagnostic fashion i using python fyi i running infinite loop needs terminate last minute new objects discovered eg true newobjs digmoreobjectsobj less newobjs discovered last minute break edit the question how i implement line less newobjs discovered last minute,1 general tip don try build strings accretively like myoutput myoutput word instead make myoutput list append word list end single join myoutput joinmyoutput see texttomessage code example using join right way build strings delaying creation string useful processing lists substrings pleasant splitting unsplitting strings add spaces carriage returns study generators they easy understand help lot processing text like import textwrap keywordlist stuff things junk keywordlist crap def texttomessagetext result word textsplit word keywordlist word keywordlist result yield joinresult result yield word else resultappendword result yield joinresult def formatmessagesmessages title text num message messages message keywordlist title text elif message keywordlist title newtext line textwrapwrapmessagewidth yield datantl formatnnumttitlelline num text stuff random text things random text random text stuff junk crazy randomness crap random stuff i cant believe random line formatmessagestexttomessagetext printline,firt thing i like say place helped i could ever repay i like say thanks helped past i trying devide text specific style message it formated like datatextstuff random text datatextthings random text datatextsome random text stuff datatextjunk crazy randomness datatextcrap random stuff i cant believe random i code shown combines text adding space words adds string named text looks like stuff random text things random text random text stuff junk crazy randomness crap random stuff i cant believe random i need formated like datatextstuff datatextsome random text datatextthings datatextsome random text datatextsome random text stuff datatextjunk datatextcrazy randomness datanewtextcrap datanewtextsuch random stuff i cant believe random the line numbers easy i done well carraige returns what i need grab crap change part says text newtext my code scans string looking keywords adds line adds text followed next keyword line etc here code i far combines text one line adds string currentsegmentmovenext data text text currentsegmentfieldvalue keywordlist stuff things junk keywordlist crap splits words search textlist textsplit searches first keywords stops unwanted one word textlist word keywordlist myoutput myoutput word elif word keywordlist break else myoutput myoutput word searches unwanted keywords leaving output blank reaches wanted keyword word textlist word keywordlist myoutput elif word keywordlist myoutput myoutput word n else myoutput myoutput word myoutput formatted back way i want deviding text less character lines maxlength mywrappedoutput wrapmyoutputmaxlength mywrappedoutput wrapmyoutputmaxlength myoutputlist mywrappedoutputsplit n myoutputlist mywrappedoutputsplit n phrase myoutputlist phrase setid output output data strsetid text else setid output output data strsetid text phrase phrase myoutputlist phrase setid output output data strsetid newtext else setid output output data strsetid newtext phrase populates fields i need value output then i format myoutput myoutput adding word newtext goes this code runs line looking keyword puts keyword carraige return once gets keywordlist stops drops rest text starts next loop my problem code gives datatextstuff datatextsome random text datatextthings datatextsome random text datatextsome random text stuff datatextjunk datatextcrazy randomness datanewtextcrazy randomness datanewtextcrap datanewtextsuch random stuff i cant believe random it grabbing text keywordlist adding newtext section i know way make groups keyword text i unclear impliment any help would much appreciated thanks this i get work keywordlist stuff things junk keywordlist crap def texttomessagetext result word textsplit word keywordlist word keywordlist result yield joinresult result yield word else resultappendword result yield joinresult def formatmessagesmessages title text message messages message keywordlist title text elif message keywordlist title newtext mywrappedoutput wrapmessagemaxlength myoutputlist mywrappedoutputsplit n line myoutputlist line yield title else yield title line line formatmessagestexttomessagetext line setid output data strsetid else setid output data strsetid line needed instead printline value output,1 usually following pattern used handle situation python first rename beautifulsoup module something else eg mybeautifulsoup then try import beautifulsoup standard except importerror import mybeautifulsoup beautifulsoup internal distribution,i want use module eg beautifulsoup python code i usually add top file beautifulsoup import beautifulsoup however i distribute module i writing others may beautifulsoup i include directory structure like mode lastwritetime length name pm beautifulsoup pm myscriptpy now modified myscriptpy file look like top reference local copy beautifulsoup beautifulsoupbeautifulsoup import beautifulsoup cdata but developer uses library already beautifulsoup installed machine i want modify myscriptpy checks see beautifulsoup already installed use standard module otherwise use included one using pseudopython fbeautifulsoupisinstalled beautifulsoup import beautifulsoup cdata else beautifulsoupbeautifulsoup import beautifulsoup cdata is possible if,3 have looked scipysparse there point reinventing wheel sparse matricies fairly standard thing in example i using x matrix easier printing multiplication a x matrix problem though this much faster multiplying two dense arrays assuming majority elements import scipysparse import numpy np make result reproducible nprandomseed def generaterandomsparsearraynrows ncols numdense generate random sparse array nonzero portions nprandomrandint nrows numdense j nprandomrandint ncols numdense data nprandomrandomnumdense datadata datadata ij npvstackij return scipysparsecoomatrixdata ij shapenrows ncols a generaterandomsparsearray b generaterandomsparsearray c a b print ctodense this yields,i want multiply sparse matrix a matrix b elements to reduce complexity matrix multiplication i ignore items go ahead add column without multiplication item subs the discussion random projection algorithm pseudo code now i go ahead implement trick i wonder i use numpy multiplication functions faster does anyone knows optimised matrix multiplication matrices or suggest something speed process since i matrix x,3 i issue netbeans would die opening i could fix revert back,i went tools plugins then chose install three python items show after installation i choose restart netbeans option but instead restarting netbeans closed and opening any ideas fix i normally develop java netbeans install i using mac osx i see takers let ask is way revert new plugin install,1 the reason string would double backslashes convert single backslashes raw string check built edit okay actual code posted double backslashes the problem happening strdictkeys putting kinds backslashes you need another way building value string i mention passing arguments sql wrapper separately one string risk sql injection attacks way here way build strings without extra backslashes finalvalueslist joinfieldsvaluelistvalues,i using python scripts send hundreds thousands insert queries sql server belonging another system an example inserts insert into importdata isbnorissnorurl filename pdflocations processed values pintohirespdf icollect process datalicensing schemes processing data preparation originalusqseptemberoctober pintohirespdf the file path string assigned global pdflocations icollect process datalicensing schemes processing data preparation originalusqseptemberoctober and added dictionary consisting namevalue pairs match field value data insert query these converted strings data finalheaderlist strfieldsvaluelistkeysreplacereplacereplace finalvalueslist strfieldsvaluelistvaluesreplacereplacereplace which added final insert string insertquery insert into values formattablefinalheaderlistfinalvaluelist which sent sql server groups the double backslash goes database double backslash rather magically converting single backslash i apparently allowed use forward slash alternative is alternative method getting desired single backslash end or administrators sql server instance make change end many thanks,1 when call myclass decorated right actually calling class calling function that function calls class cls instances caches returns cached instance in words reason myclass call class directly work expected long returns instance class,code goes first def singletoncls instances def getinstance cls instances instancescls cls return instancescls return getinstance singleton class a ok code implementation singleton i saw implementation another post i understand singleton function returns function a class how work,1 a class end the class a gets created replaced function singleton returns so end a ends function but since call class create object ends working pretty much way but isinstance work ps probably use singleton in python almost always wrong choice,code goes first def singletoncls instances def getinstance cls instances instancescls cls return instancescls return getinstance singleton class a ok code implementation singleton i saw implementation another post i understand singleton function returns function a class how work,1 it takes keyword arguments variables urlfor add variablefoo,half flask routes requires variable say variableadd variableremove how i create links locations urlfor takes one argument function route i add arguments,3 note need consider whether want methods base classes inherited overridden included result the dir inspectgetmembers operations include base class methods use dict attribute,i want iterate methods class handle class instance objects differently based methods present how i get list class methods also see how i list methods python module looping python ironpython object methods finding methods object how i look inside python object how do i perform introspection object python x how get complete list object’s methods attributes finding functions available class instance python,3 you could use boolean array index data import numpy np import datetime dt datesdtdatedttimedeltadaysi range valuesrange datanparrayzipdatesvaluesdtype dates object value f data dates dtdate amp data dates dtdate boolean array length data true dates september printdata value data dates dtdate amp data dates dtdate,i numpy array data dtype date o value f date object python datetimedate object consists days one year value object value data corresponding date how i return value data let say september,2 try changing pdflocations icollect process datalicensing schemes processing data preparation originalusqseptemberoctober pdflocations ricollect process datalicensing schemes processing data preparation originalusqseptemberoctober notice raw r indicator edit trying use ugly beast approach finalvalueslist joinfieldsvaluelistvaluesreplacer thus forcing string double backslashes of course i first try replacing insertquery insert into values formattablefinalheaderlistfinalvaluelist insertquery insert into valuess tablefinalheaderlistfinalvaluelist completely sure ugly approach would needed,i using python scripts send hundreds thousands insert queries sql server belonging another system an example inserts insert into importdata isbnorissnorurl filename pdflocations processed values pintohirespdf icollect process datalicensing schemes processing data preparation originalusqseptemberoctober pintohirespdf the file path string assigned global pdflocations icollect process datalicensing schemes processing data preparation originalusqseptemberoctober and added dictionary consisting namevalue pairs match field value data insert query these converted strings data finalheaderlist strfieldsvaluelistkeysreplacereplacereplace finalvalueslist strfieldsvaluelistvaluesreplacereplacereplace which added final insert string insertquery insert into values formattablefinalheaderlistfinalvaluelist which sent sql server groups the double backslash goes database double backslash rather magically converting single backslash i apparently allowed use forward slash alternative is alternative method getting desired single backslash end or administrators sql server instance make change end many thanks,1 at start candidates loops product equals base then loop another loop products at end loop increment product base so product goes multiple base you remove values product remove multiples base number basically program set product base candidate multiple base referred product remove product candidates set base new value reset product new base,this homework lesson gives answer already i trouble putting words answer line code calculate primes result candidates range base product base candidates product product candidates candidatesremoveproduct product product base resultappendbase base candidates product base del candidates resultappendbase print result this version the sieve erastothenes this explanation given new things example… the builtin function range actually returns list used like lists it includes first index last a list used logic variable if empty true — empty false thus candidates means “while list named candidates empty” simply “while still candidates” you write someelement somelist check element list you write somelistremovesomeelement remove someelement somelist you append element list using somelistappendsomething actually use somelist somelistsomething efficient you get element list giving position number first element strangely element brackets name list thus somelist fourth element list somelist more you delete variables using keyword del it also used delete elements list thus del somelist deletes first element somelist if list deletion would afterwards before going explaining mysteries indexing list elements i give brief explanation example this version ancient algorithm called “the sieve erastothenes” something close it considers set case list candidate numbers systematically removes numbers known primes how know because products two numbers we start list candidates containing numbers — know prime actually may may depending ask wanted primes actually list candidates also candidate since first base we also list called result times contains updated results far to begin list contains number we also variable called base for iteration “round” algorithm remove numbers multible base number always smallest candidates after iteration know smallest number left prime since numbers products smaller ones removed — get therefore add result set new base number remove candidate list won’t process when candidate list empty result list contain primes clever huh what i understand say remove numbers multiple base number where line code can someone explain line line program i newb trying understand mechanics line code thanks assistance,1 i try answer parameters question this code decorator class foo pass equivalent class foo pass foo decoratorfoo this means foo ends instance decorator class instead class when try use instance base class goo python determine metaclass used create new class in case use fooclass equals decorator then call metaclass name bases dict arguments expect return new class this end arguments decoratorinit more found httpwwwpythonorgdownloadreleasesdescrintrometaclasses particularly when class statement executed part,i trying decorate class another class i also want inherit decorated class i get errors here code class decorator def initself decorated pass decorator class foo pass class goofoo pass the error i get i try subclass foo traceback recent call last nbspnbspnbspfile testpy line nbspnbspnbspnbspnbspnbspclass goofoo typeerror init takes exactly positional arguments given by adding another init function decorator def initself args arg args printarg i get following output class mainfoo goo maindecorator object xb module main what parameters i using inside decorator,3 the problem you dividing two integers python using integer division in integer division quotient rounded for example would equal works equal still rounded instead use float division like,in code highly simplified i get zerodivisionerror float division any value one gives errors other times gives error how i fix import math def top return mathsqrtt top topt print top,3 in addition cheeken answer put following top modules future import division doing make division operator work way want ie always perform close approximation true mathematical division the default behaviour division operator performs truncating integer division arguments happen bound integers inherited c eventually realised great fit dynamically typed language like python in python longer happens in python modules i almost always import division future i get caught accidentally passing integers division operation i expect truncate it worth noting future import statements first thing module i think comments docstring nothing else it really normal import statement even though looks like one actually changes way python interpreter reads code wait runtime exectuted like normal import statement also remember import future magic effects future import,in code highly simplified i get zerodivisionerror float division any value one gives errors other times gives error how i fix import math def top return mathsqrtt top topt print top,3 that way works it perfectly fine if additional rules excluding dictionary words may want include filters well likelihood randomly generating dictionary word setup extremely small,i interested creating simple high cryptographic quality random password generator is better way import os random string length chars stringasciiletters stringdigits amp randomseed osurandom print joinrandomchoicechars rangelength,1 xkcd great explanation think strong passwords to anyone understands information theory security infuriating argument someone possibly involving mixed case i sincerely apologize randall munroe and understand math behind illustration explaining try writing anything cryptographically secure just put mouse step away keyboard,i interested creating simple high cryptographic quality random password generator is better way import os random string length chars stringasciiletters stringdigits amp randomseed osurandom print joinrandomchoicechars rangelength,3 i pyhook example site httpfadedblueskycomusingpyhooktoblockwindowskey i originally wrote block keys game written using pygame you able easily adapt windows programs,how i even applicationexe focused window for example like windows d shortcut works everywhere i want alt function alt another one,1 it occurred forgot supply django project settings you fix supplying,input djangodb import models idlethe result throw exception named settings cannot imported environment variable djangosettingsmodule undefined exception occur fix,2 that code path loading script file specified appyaml it expects find bit clean ascii finding something else any chance python script specified script appears tingpy got garbled,i trying upgrade i downloaded new version download page i click browse button launcher i get ascii error does anyone know going this error traceback recent call last file cprogram files xgooglegoogleappenginegoogleappenginetoolsdevappserverpy line handlerequest selfdispatchdispatcher selfrfile outfile envdict file cprogram files xgooglegoogleappenginegoogleappenginetoolsdevappserverpy line dispatch baseenvdictenvdict file cprogram files xgooglegoogleappenginegoogleappenginetoolsdevappserverpy line dispatch baseenvdictbaseenvdict file cprogram files xgooglegoogleappenginegoogleappenginetoolsdevappserverpy line dispatch selfmoduledict file cprogram files xgooglegoogleappenginegoogleappenginetoolsdevappserverpy line executecgi resetmodules execscripthandlerpath cgipath hook file cprogram files xgooglegoogleappenginegoogleappenginetoolsdevappserverpy line executeorimportscript handlerpath cgipath importhook file cprogram files xgooglegoogleappenginegoogleappenginetoolsdevappserverpy line loadtargetmodule raise syntaxerrorerror syntaxerror ascii codec decode byte xef position ordinal range please see httpwwwpythonorgpepspephtml details tingpy,1 in absence batch operations much reduce wallclock times batch operations pretty essential reducing wallclock time app engine distributed platform rpcs really under current billing model cpu milliseconds reported datastore reflect cost operation rather actual time took way billing resources under new billing model billed explicitly datastore operations instead,i testing google app engine djangononrel free quota it seems database operations datastore hideously slow take example simplified function processing request takes multipartformdata xml blobs parses inserts database def postrequest fields cgifieldstoragerequest transactioncommitonsuccess xmlblob fieldsgetlist xmlblob blobobject parsexmlxmlblob blobobjectsave blobobject five fields type charfield for ca blobs kb xml altogether function takes seconds return uses apicpums cpu time equivalent amount work ghz intel x processor could time i pretty sure would take seconds insert rows database x processor available without saving objects database parsing xml throwing away result request takes merely milliseconds so google app engine really slow i save even dozen entities datastore normal request i missing something and course even i would inserts backend using task queue would still cost hundreds times would seem acceptable edit i found default gae two index writes per property entity most properties indexed question i set properties unindexed djangononrel i still feel though even index writes database operation taking ridiculous amount time,2 just two days ago kragen javier sitaker posted program httplistscanonicalorgpipermailkragenhacksseptemberhtml gone try httpsgithubcomjesterpmbinblobmastermkpasswd generate random memorizable password httpxkcdcom example run kragen inexorabledevelinexorablemisc mkpasspy your password learned damage saved residential stages that equivalent bit key that password would take e cpuyears crack inexpensive celeron e assuming offline attack mscache hash worst password hashing algorithm common use slightly worse even simple md the common passwordhashing algorithm days freebsd’s iterated md cracking hash would take e cpuyears but modern gpu crack times fast iterated md would fall e gpuyears that gpu costs us per day run cracking password would cost use i started using password generated way place printable asciicharacter random password equally strong munroe assertion passwords much easier memorize correct however still problem many fewer bits entropy per character instead lot redundancy password attacks ssh timingchannel attack song wagner tian herbivore attack i learned bram cohen bagdad cafã© wee hours one morning years ago keyboard audio recording attacks much better chance capturing enough information make password attackable my countermeasure herbivore attack works well character password extremely annoying new password type password halfsecond delay characters timing channel carry much information actual characters used additionally lower length character password inherently gives herbivore approach much less information chew other possible countermeasures include using emacs shellmode prompts locally password recognizes password prompt sends whole password copying pasting password somewhere else as expect password also takes little longer type seconds instead seconds usrbinpython coding utf import random itertools os sys def mainargv try nwords intargv except indexerror return usageargv try nbits intargv except indexerror nbits filename ospathjoinosenviron home devel wordlist wordlist readfilefilename nbits lenwordlist nbits sysstderrwriter contains words dn filename lenwordlist nbits return displaypasswordgeneratepasswordnwords wordlist nwords nbits return def usageargv p sysstderrwrite pusage nwords nbitsn argv pgenerates password nwords words nbits bitsn pof entropy choosing words first entries inn phomedevelwordlist format asn phttpcanonicalorgkragenswwordlist text filen pwith one word per line preceded frequency frequentn pwords firstn pnrecommendedn p n argv p n argv return def readfilefilename nbits return linesplit line itertoolsisliceopenfilename nbits def generatepasswordnwords wordlist choice randomsystemrandomchoice return joinchoicewordlist ii rangenwords def displaypasswordpassword nwords nbits print your password password entropy nwords nbits print that equivalent dbit key entropy print my celeron e httparkintelcomproductsintelceleronprocessorekcacheghzmhzfsb released january running bit mode john test httpwwwopenwallcomjohn reports md operations per second i’m pretty sure that’s singlecore number i don’t think john multithreaded dualcore processor yearsentropy print that password would take g cpuyears crack print inexpensive celeron e print assuming offline attack mscache hash print worst password hashing algorithm common use print slightly worse even simple md print yearsentropy print the common passwordhashing algorithm days freebsd’s print iterated md cracking hash would take g cpuyears print as happens machines use drepper’s shabased hashing algorithm developed replace one mentioned i assuming it’s least slow mdcrypt httpsenbitcoinitwikimininghardwarecomparison says core duo u mhashs bitcoin ghz clock one thread the celeron machine i benchmarked basically core duo smaller cache i’m going assume could probably mhashs all common passwordhashing algorithms ones mentioned others implemented john bcrypt scrypt use little memory i believe scale gpus comparably sha used bitcoin the mininghardware comparison says radeon card mhashs us print but modern gpu crack times fast print iterated md would fall g gpuyears print suppose depreciate video card moore’s law ie halving value every months that loss value every day us that’s ⢠per day us per gpuyear if someone wanted password quickly possible could distribute cracking job across network millions cards the cards additionally use watts power â¢kwh works ⢠per day if assume additional overhead that’s usday usgpuyear costperday costpercrack costperday print that gpu costs usf per day run costperday print cracking password would cost usg costpercrack def yearsentropy cryptspersecond return floatentropy cryptspersecond name main sysexitmainsysargv,i interested creating simple high cryptographic quality random password generator is better way import os random string length chars stringasciiletters stringdigits amp randomseed osurandom print joinrandomchoicechars rangelength,3 another stackoverflow page came rescue pythonldap os x python the final solution pip install pythonldap noting people facing cygwin use post,i trying install basic ldap python module cygwin the following failing easyinstall ldap searching ldap no local packages download links found ldap i using cherrypy app running fine ubuntu planning port cygwin i run app win lapop i could install djangospecific module djangoauthldap tried import ldap seem initialize method basic ldap module ps i forgot mention trying pythonldap easyinstall pythonldap fails due compilation errors modulesconstantsc in function ldapinitconstants modulesconstantsc error ldapoptdiagnosticmessage undeclared first use function modulesconstantsc note undeclared identifier reported function appears modulesconstantsc error ldapcontrolrelax undeclared first use function error setup script exited error command gcc failed exit status,3 you trust python pseudo random number generator generating password it necessarily cryptographically random you seeding pseudo random number generator osurandom good start but depend python generator a better choice would randomsystemrandom class takes random numbers source urandom according python documentation good enough cryptographic use the systemrandom class gives everything main random class need worry pseudorandomness example code using randomsystemrandom python import random string length chars stringasciiletters stringdigits amp rnd randomsystemrandom print joinrndchoicechars rangelength note your mileage may vary python documentation says randomsystemrandom availability varies operating system,i interested creating simple high cryptographic quality random password generator is better way import os random string length chars stringasciiletters stringdigits amp randomseed osurandom print joinrandomchoicechars rangelength,1 the python manual says equal precedence httpdocspythonorgreferenceexpressionshtmlsummary thus evaluated left right default also chaining consider the expression put true actually evaluated true course false if know chaining allows something like python mean expect greater less,python manual said operator lower precendence comparsion operators true true true true false true traceback recent call last file pyshell line module true typeerror argument type bool iterable,3 i would suggest using environment variable like myprojectsettings so running task jenkins overwrite default path whatever put settings file jenkins the option case want copy settings file buildmachine hand would making settingspy default fake keys add repo local settings file real keys overwrites options eg settingspy file secretkey fake stuff try settingslocal import except importerror pass,i started using jenkins today entirely possible i missed something docs i currently jenkins set run unit tests local git repo via plugin i set environment correctly least seemingly working condition run small snag i single settingspy file i excluded git repo contains keys i using app i want include file git repo i planning os ing project i done anyone using project would need keys i realize may best way done small personal project i concerned the problem git management jenkins pick i like able copy single file source directory jenkins build directory prior running tests is way i tried using copy slave plugin seems like file i want would first manually need copied created workspaceusercontent am i missing something,1 it nothing precedence in python relational operators chain containment considered relational operator therefore true true false since true equal,python manual said operator lower precendence comparsion operators true true true true false true traceback recent call last file pyshell line module true typeerror argument type bool iterable,2 chaining allows write x z mean x z look interaction false true false true false true false true false true false false so example true equivalent true,python manual said operator lower precendence comparsion operators true true true true false true traceback recent call last file pyshell line module true typeerror argument type bool iterable,1 the time module used need time particular record like lets say seperate tablefile transactions day would need time however time datatype usually used store time difference points time this also done using datetime dealing time particular day time module used datetime used store particular data time record like rental agency the due date would datetime datatype,i know datetime provides dates time what use time module differences this might seem naive i trying figure differences used examples would appreciated differences concerning timezones would especially interest thanks,1 considering comment i need able generate passwords secure ones i would come head seems want use program generate passwords rather writing exercise it preferable use existing implementation make mistake output might compromised read random number generator attacks particular wellknown rng bug debian exposed people ssl private keys so instead consider using pwgen it provides several options choose depending plan use passwords,i interested creating simple high cryptographic quality random password generator is better way import os random string length chars stringasciiletters stringdigits amp randomseed osurandom print joinrandomchoicechars rangelength,2 time module principally working unix time stamps expressed floating point number taken seconds since unix epoch datetime module support many operations provides object oriented set types also limited support time zones,i know datetime provides dates time what use time module differences this might seem naive i trying figure differences used examples would appreciated differences concerning timezones would especially interest thanks,3 try jsonloadscheckinjson instead jsonloadrequestpost notice extra,i using django receive process push notifications foursquare realtime api each checkin pushed post request server containing single parameter named checkin i trying grab value checkin parameter convert python dict however calling jsonloads always results following error nameerror name true defined i know json valid i must something wrong the code import json def pushrequest requestissecure checkinjson requestpost checkin checkin jsonloadrequestpost the body post request checkin id efebceeac createdat type checkin timezone americanewyork user id firstname jimmy lastname foursquare photo httpsfoursquarecomimgblankboypng gender male homecity new york ny relationship self venue id abecfafbe name foursquare hq contact twitter foursquare location address east village lat lng city new york state ny postalcode country usa categories id bfdddd name tech startup pluralname tech startups shortname tech startup icon httpsfoursquarecomimgcategoriesbuildingdefaultpng parents professional amp other places offices primary true verified true stats checkinscount userscount tipcount url httpfoursquarecom,2 this expect elif change it looks like intend something like elif change change python also supports elif change however next run floating point rounding problems various kinds i suggest first convert input number integer number cents perform calculations cents avoid floating point numbers dealing money,updated new code bottom page answer so cs class make program user input less change returned least amount coins bills cent pieces for part program well except run xx eg python va jun gcc apple inc build dot darwin type copyright credits license information restart amount due amount return quaters return dimes return nickels return program completely skips dimes section straight nickels providing solution least amount quarters dimes end also i really skilled loops much i know would possible lot shorter code cleaning code advice would nice well thanks help optionalpy calculating least amount change return bill amount due due inputamount duen amount exit program due print please enter number lower exit amount less exit program due print please enter number greater exit subtract amount else change due print amount returnn f change amount change change print no change return passes expression previous met pass elif change setting q dividing change q change maaking q integer quaters intq print quaters return r quaters subtracting quaters chane change change quaters change pass elif change change dimes intd print dimes return r dimes change change dimes change pass elif change n change nickels intn print nickels return r nickels change change nickels change pennies change print pennies return r pennies elif change p change print pennies return f p,1 use nltk import nltk yourstring your words words w w yourstringsplit freqdist nltkfreqdistwords tokens freqdistkeys frequent mostfrequent tokens least frequent leastfrequent tokens,i looking simple script find frequencies words given document probably using portable stemmer is library simple script process,1 as far i tell reference item using itemtext allitems qcomboboxnameitemtexti rangeqcomboboxnamecount,i a lot qcomboboxes certain point i need fetch every item particular qcombobox iterate although i could list items correspond items qcombobox i rather get straight widget huge amount qcomboboxes many items is functions methods eg qcomboboxnameallitems i looked class reference find anything relevant i thought messy methods i like like iterating qcombobox changing index getting item etc python idle windows pyqt,3 there changes could make clean code one might fix problem first pass absolutely nothing it usually used placeholder loop function filled later also conditions elif statements mutually exclusive statements follow change print no change return passes expression previous met pass elif change setting q dividing change q change maaking q integer quaters intq print quaters return r quaters subtracting quaters chane change change quaters rewritten change setting q dividing change q change making q integer quaters intq print quaters return r quaters subtracting quaters change change change quaters elif statement also statement change testing whether change to make want statement rewritten change in addition using floating point numbers often lead rounding errors to avoid errors i would suggest either representing money integer number cents multiply numbers problem use something fixed point numbers like python decimal module,updated new code bottom page answer so cs class make program user input less change returned least amount coins bills cent pieces for part program well except run xx eg python va jun gcc apple inc build dot darwin type copyright credits license information restart amount due amount return quaters return dimes return nickels return program completely skips dimes section straight nickels providing solution least amount quarters dimes end also i really skilled loops much i know would possible lot shorter code cleaning code advice would nice well thanks help optionalpy calculating least amount change return bill amount due due inputamount duen amount exit program due print please enter number lower exit amount less exit program due print please enter number greater exit subtract amount else change due print amount returnn f change amount change change print no change return passes expression previous met pass elif change setting q dividing change q change maaking q integer quaters intq print quaters return r quaters subtracting quaters chane change change quaters change pass elif change change dimes intd print dimes return r dimes change change dimes change pass elif change n change nickels intn print nickels return r nickels change change nickels change pennies change print pennies return r pennies elif change p change print pennies return f p,2 add empty print end printmultiples outside loop,the output code quite similar exactly supposed the code def printmultiplesn printni end n printmultiplesn n the output whereas like how code modified,1 if interested timezones consider use pytz,i know datetime provides dates time what use time module differences this might seem naive i trying figure differences used examples would appreciated differences concerning timezones would especially interest thanks,2 the difficult thing passwords make strong enough still able remember if password meant remembered human really password you use python osurandom good for practical purpose even cryptography output osurandom indistinguishable true alea then use seed random less good one noncryptographic prng output may exhibit structure register statistical measurement tool might exploited intelligent attacker you work osurandom along to make things simple choose alphabet length eg letters uppercase lowercase digits two extra punctuation characters then password character get one byte osurandom reduce value modulo unbiased divides use result index chars array with alphabet length get bits entropy per character thus characters get bits entropy this ultimately strong cases already strong could defeated budget counted months billions dollars mere millions,i interested creating simple high cryptographic quality random password generator is better way import os random string length chars stringasciiletters stringdigits amp randomseed osurandom print joinrandomchoicechars rangelength,3 one approach would pass custom defined filter def myfiltertxt return whatever i want selfbody myfilter,is possible get rendered body content within mako template what i mean i display body using selfbody i want something first,1 this explained httpssouthreadthedocsioenlatestdependencieshtml migrations apps nice ‘n start writing large project lot apps realise foreign key relationships apps working order migrations would need applied app painful luckily also problem south dependency system inside migration declare depends another app run certain migration first example app “forum” depends “accounts” app created user profile table forummigrationspostpy class migration dependson accounts adduserprofile def forwardsself then try migrate beyond post forum app first make sure accounts migrated least adduserprofile migrate dependencies also work reverse south knows undo adduserprofile migration undone post migration you multiple dependencies sorts wacky structures however two rules no circular dependencies two migrations depending no upwards dependencies app can’t make post forum app depend room app either directly dependency chain,i recently begun using south migrations django project all going well recently i ran peculiar issue i two apps project say appa appb a model appa foreign key model appb when i trying build system i ran syndb created auth south tables then i ran migrate threw errors when tried creating model appa referenced model appb model appb migratedcreated yet therefore error in order resolve i manually migrate appb first appa am something wrong how south supposed know migration order across apps thanks,3 apparently i looking capture function from docs the way buffer output def mako callable using builtin capture function this function performs operation similar buffering operation except specified caller results capturesomedef results or case body captureselfbody etc,is possible get rendered body content within mako template what i mean i display body using selfbody i want something first,1 try following line sumitem price item list,is simple way getting total price fruits list dictionaries python name apple price name banana price name grapes price,3 your regex fundamentally wrong sss mean match least one nonwhitespace bracket series nonwhitespace or series whitspace or comma closing bracket i think meant use raw strings r escape sssssss see regexr you find name function capturing group brackets around first s the optional whitespaces but regex simple i sure find functions fail nested brackets find stuff,i need find function definitions like function param param param i using following regular expression python sss something like refindallssssourcecodestring give function names working please suggest improvements regular expression i new regular expressions,1 the syntax tuples abc if want dictionary multiple values list value red you may want also consider named tuples even classes this allow name fields instead accessing index make code clear structured i read around i think way i found use nested lists i type storage billion recordsand i need search i thought maybe nested anything might slow if billion records probably persisting data example database you likely run memory try keep data memory,i new python still learning i wondering standard best practice storing one key value tuple here example i value called red value i need divide number say i need store values red name number times divides remainder there values similar need included well red results blue green etc numbers different label i read around i think way i found use nested lists i type storage billion records i need search i thought maybe nested anything might slow i tried create something like red correct syntax i considering adding delimiter key value splitting sure efficient red parse letter i wondering better ways store nested tuples solution i using python,2 use tuple for example red,i new python still learning i wondering standard best practice storing one key value tuple here example i value called red value i need divide number say i need store values red name number times divides remainder there values similar need included well red results blue green etc numbers different label i read around i think way i found use nested lists i type storage billion records i need search i thought maybe nested anything might slow i tried create something like red correct syntax i considering adding delimiter key value splitting sure efficient red parse letter i wondering better ways store nested tuples solution i using python,1 r pmediaidd scangoscannerviewsdownload maybe try instead this example named groups in python regular expressions syntax named regular expression groups ppattern name name group pattern pattern match,i url like httpgagandeepdesk i filtering urlspy file sending one parameters function urlspy filter looks like urlr scangoscannerviewsdownload and function looks like def downloadrequest mediaid media mediaobjectsgetidintmediaid print media return httpresponsefileiterwrapperopenmediapath i getting error many values unpack line media mediaobjectsgetidintmediaid i also tried running function standalone without request object running perfectly fine so i confused i done wrong environment request method get request url httpgagandeepdesk django version python version installed applications haystack scanner djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles djangocontribadmin installed middleware djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware traceback file cpythonlibsitepackagesdjangocorehandlersbasepy getresponse response callbackrequest callbackargs callbackkwargs file cusersgagasingdesktopideasscangoscangoscannerviewspy download media mediaobjectsgetidintmediaid file cpythonlibsitepackagesdjangodbmodelsmanagerpy get return selfgetquerysetgetargs kwargs file cpythonlibsitepackagesdjangodbmodelsquerypy get clone selffilterargs kwargs file cpythonlibsitepackagesdjangodbmodelsquerypy filter return selffilterorexcludefalse args kwargs file cpythonlibsitepackagesdjangodbmodelsquerypy filterorexclude clonequeryaddqqargs kwargs file cpythonlibsitepackagesdjangodbmodelssqlquerypy addq canreuseusedaliases forcehavingforcehaving file cpythonlibsitepackagesdjangodbmodelssqlquerypy addfilter arg value filterexpr exception type valueerror exception value many values unpack,2 note best answer simply use numpylogaddexplogalogb why exactly compare log this equal numpyinf case come log mathexpinflogb logb which reduces logb this call always give warning message extremely slow i could come oneliner however need really measure see actually faster it use one complex calculation function instead two use recursion happening still hidden maybe optimized fabs maximum def logaddlogalogb return numpylogaddexpnumpyfabslogbloga numpymaximumlogalogb edit i quick timeit following results your original version took my version took i removed compare log version came i edited code keep logaddexp also worked recursive went updated code could also switch recursive call inline updated formula made little difference timing tests def logaddloga logb loga logb return logaddlogb loga return numpylogaddexplogblogaloga edit as pv noted comments could actually numpylogaddexploga logb comes calculating logexplogaexplogb course equal logab i timed machine went so come bad,given loga logb i want compute logab numerically stable way i wrote little function def logaddlogalogb loga log return logb logalogb return logaddlogbloga return log mathexplogbloga loga i wrote program far timeconsuming piece code obviously i could try optimize eliminate recursive call instance do know standard math numpy function computing logab loga logb if know simple way make single c hook function it complicated function uses floats i said taking majority runtime thanks advance numerical methods ninja,3 i think csv module python help extract file data first convert spreadsheet csv format save csv command appropriate delimiter try code snippet import csv fileptr open filenamecsv r fields range total number columns file header filedata csvdictreaderfileptr fields delimiter data filedata print data data dict format first line would headerselse column data database query code processing hope helpful,i using sqlite python script extract data client spreadsheet my client planning add spreadsheet sqlite code generate columns based headers i extract first line how i this naive attempt import sqlite conn sqliteconnect foosql c conncursor line file line firstline below line question cexecute create table exists bar linetuple else cexecute insert bar values linetuple,1 it looks like want grid evaluate function case use numpyogrid open numpymgrid fleshed import numpy mygrid numpymgridslice,i trying run parameters space parameter function study numerical behavior trying anything complex i searching efficient way my function takes float values given dim numpy array input what i tried initially first i created function takes arrays generate array combinations values two arrays numpy import def combab c j b cappendrij return c then i used reduce apply copies array def combsam return reducecombam and i evaluate function like values combsnparange val values print fval this works waaaay slow i know space parameters huge slow i sampled million points example took seconds create array values do know efficient way numpy i modify way function f takes arguments necessary,3 i know app seems quite simple i think necessary modify use djangoregistration case create form ask email password create corresponding user the username may generated slug email address look following snippet allowing authenticate email address httpdjangosnippetsorgsnippets,i found djangoregistration app seems complex i trying i want users simply enter email username password automatically registered no activations confirmations hacker news style does anyone know simplest way implement would is something preexisting know i find anything i somehow modify djangoregistration build,1 i suspecting looking collision detection andor response algorithms you might find question answer almost exactly scenario for good explanation underlying physics math i find old articles chris hecker useful,i trying simulate following balls moving area fixed dimensions whenever two balls come proximity range say i want event triggered my idea utilize movement trace different properties guide movement balls study balls come contact can someone suggest good way,1 edit since answer accepted i edited make clear view new information defined comments unless use autocommittrue transaction started automatically therefore need call sessionbegin explicitly,i table mysql engine innodb system configuration mysql version mysql ver distrib redhatlinuxgnu x using readline python version python file testpy sqlalchemy import createengine engine createengine mysqltesttestlocalhosttest echotrue sqlalchemyextdeclarative import declarativebase base declarativebase sqlalchemy import column integer string class userbase tablename users id columninteger primarykeytrue name columnstringlength fullname columnstringlength password columnstringlength def initself name fullname password selfname name selffullname fullname selfpassword password def reprself return user selfname selffullname selfpassword basemetadatacreateallengine sqlalchemyorm import sessionmaker session sessionmakerbindengine sessionsession sessionbeginnested eduser user ed ed jones edspassword sessionaddeduser sessioncommit after i get console info sqlalchemyenginebaseengine select database info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine show variables like characterset info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine show variables like lowercasetablenames info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine show collation info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine show variables like sqlmode info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine describe users info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine begin implicit info sqlalchemyenginebaseengine savepoint sasavepoint info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine insert into users name fullname password values info sqlalchemyenginebaseengine ed ed jones edspassword info sqlalchemyenginebaseengine release savepoint sasavepoint info sqlalchemyenginebaseengine then check database entry get mysql test p mysql use test database changed mysql select users empty set sec then wondering entry db i check log found savepoint sasavepoint release savepoint sasavepoint commit statement so add one extra commit file last lines sessionbeginnested eduser user ed ed jones edspassword sessionaddeduser sessioncommit sessioncommit then log chenged info sqlalchemyenginebaseengine begin implicit info sqlalchemyenginebaseengine savepoint sasavepoint info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine insert into users name fullname password values info sqlalchemyenginebaseengine ed ed jones edspassword info sqlalchemyenginebaseengine release savepoint sasavepoint info sqlalchemyenginebaseengine info sqlalchemyenginebaseengine commit now get line database mysql use test database changed mysql select users id name fullname password ed ed jones edspassword row set sec so meaning commit times start savepoint behavior beginnested sqlalchemy,1 finally found solution written wrongly documentation doc adminpy add code cade admin calss orderadmin def getformself request objnone kwargs form superorderadminselfgetformrequestobjkwargs autoselectfieldscheckcanaddformselfmodelrequestuser return form,installed djangoajaxselect app wonderful app autocomplete option adding form adminpy button add new object attached snapshot example found code splitting value written hooking clean method override case want add button def cleanself value value lookup getlookupselfchannel objs lookupgetobjects value objs return objs else firstname surname valuesplit gender selfchannelsplit newskater skaternamefirstname surnamesurname gendergender return newskater else selfrequired raise formsvalidationerrorselferrormessages required return none,1 what django use urlvalidator see url valid could use validations present djangocore edit for example lets say validate django official website url httpswwwdjangoprojectcom exists code would simply look like djangocorevalidators import urlvalidator djangocoreexceptions import validationerror myurlvalidator urlvalidatorverifyexiststrue creates urlvalidator object verifyexists myurl httpswwwdjangoprojectcom url verified check url valid try myurlvalidatormyurl except validationerror valid fix custom stuff rescue customstuff,i url fields defined model follows image modelsurlfieldmaxlength verifyexiststrue blanktrue image modelsurlfieldmaxlength verifyexiststrue blanktrue image modelsurlfieldmaxlength verifyexiststrue blanktrue my question way i test whether verifyexists returns true false take action depending output,3 perform http query see result ok you easily pycurl sample documentation import pycurl c pycurlcurl csetoptpycurlurl httpexamplecom csetoptpycurlfollowlocation cperform print cgetinfopycurlhttpcode,i wordpress self hosted blog last week after updating wordpress site working fine but i would like check frequently next couple days is possible write program i schedule please give suggestions i thinking python language program i open language,1 you test website simple httpconnection send options request answer ok site otherwise check http error codes import httplib connection httplibhttpconnectionyourhost portprobably connectionrequestoptions response connectiongetresponse responsestatus httplibok responsereason ok print down else print up,i wordpress self hosted blog last week after updating wordpress site working fine but i would like check frequently next couple days is possible write program i schedule please give suggestions i thinking python language program i open language,2 oetest debugsqlduplicate key value violates unique constraint irmodeldatamodulenameuniq in irmodeldata sqlconstraint defined unique record name error comes code says you duplicate record name per knowledge kind error could occur duplicate record id dataxml file note check either noupdatetrue dataxml file,i process trying upgrade module written openerp although works fine local machine local openerp server it gives error i try update files via svn staged server the error states trying insert record db actually update insertion i worried remove record postgres db directly though think might trick i also removed existing files i svn update staged server may might pit fall quite sure let know guys think best solution problem below error messages show openerp server restarted svn update the server stops never ends but soon i revert files remove update server works like charm module abc loading objects oetest infoinitmodule abcregistering objects oetest infoinitmodule abc creating updating database tables oetest debugsqlbad query insert into irmodeldata namedateinitdateupdatemodulemodelresid values e modelabc e abc e irmodel oetest debugsql modelabc u abc irmodel oetest debugsqlduplicate key value violates unique constraint irmodeldatamodulenameuniq regards gayan,2 to answer question problem precision as rocksportrocker points two popular estimators standard deviation matlab std available standard uses different one used python try stdz instead stdz za zrepmatmeanz repmatstdzza sprintf f za leads za matlab read rockspotrocker answer two results appropriate want,i know basic data types float types floatdouble hold numbers exactly in porting code matlab python numpy i however found significant differences calculations i think going back precision take following code znormalizing dimensional vector first two elements nonzero value matlab z repmat zz za zrepmatmeanz repmatstdz za python numpy import zerosmeanstd z zeros z z za z meanz stdz print za besides formatting shows bit digits python huge difference imho both python matlab using bit data type afaik python uses numpyfloat matlab double why difference huge which one correct,3 maybe difference comes mean std calls compare first there several definitions std use sqaure root n sumxi meanx others use n sumxi meanx instead from mathematical point formulas estimators variance normal distributed random variable the distribution two parameters sigma mu if know mu exactly optimal estimator sigma n sumxi mu if estimate mu data using mu meanxi optimal estimator sigma n sumxi meanx,i know basic data types float types floatdouble hold numbers exactly in porting code matlab python numpy i however found significant differences calculations i think going back precision take following code znormalizing dimensional vector first two elements nonzero value matlab z repmat zz za zrepmatmeanz repmatstdz za python numpy import zerosmeanstd z zeros z z za z meanz stdz print za besides formatting shows bit digits python huge difference imho both python matlab using bit data type afaik python uses numpyfloat matlab double why difference huge which one correct,3 here example calling super beware need inherit object inorder make super works class eobject def initself print enter e print leave e class fe def initself print enter f superf selfinit print leave f f f,i following classes forwindlidarapiapi import mclidarguiplugin class mclidaractions handler tcpsend event def objectupdatedchanged self info print info pass def tcpsendchanged self print click forwindlidarapiactionsapi import mclidaractions class mcudpactions mclidaractions def objectupdatedchanged self info pass def tcpsendchanged self print click udp when i click button mclidaractions tcpsendchanged function called i extend function i want take action mcudpactions well in case if i click button printed click i want print click udp well,1 this nothing multiple models inserts the issue obvious set nested statements one return right deeply nested bit what happens post form valid form p valid django expects view return response circumstances need return matter happens,i going mad trying figure problem i form multiple models basically someone writes story puts username username associated story it pretty basicapparently django aside searching hours find something helps essentially multiple sql inserts seems impossible i get error failed return httpresponseobject even though i verified indentation here view def submitstoryrequest requestmethod post f requestpostcopy sdata author f username authorform p storyformsdata aisvalid asave pisvalid psave return httpresponseredirect thanks here models class authormodelsmodel username modelscharfieldmaxlength uniquetrue email modelsemailfield firstname modelscharfieldmaxlength lastname modelscharfieldmaxlength class storymodelsmodel title modelscharfieldmaxlength text modelscharfieldmaxlength date modelsdatefield likes modelsintegerfield dislikes modelsintegerfield views modelsintegerfield author modelsforeignkey author thanks advance i changed django php thinking would simpler multiple form submission plain irritating,1 you use asserttrue purpose selfasserttruemyint myint or using python comparison chaining idiom selfasserttrue myint,in unit testing i currently i need pass test variable lies two boundary conditions something like def mytestself myint selfassertbetweenmyint would pass test or myint lied outside range would fail i looked list assert methods python documentation work one would give sort functionality thanks,3 u pk u u quantity u u name u mm aliminum sheet u size u x u pk u u quantity u u name u mm aliminum sheet u size u x evals print typed this good way persisting objects try save using model class,how would convert object iterate u pk u u quantity u u name u mm aliminum sheet u size u x u pk u u quantity u u name u mm aliminum sheet u size u x this data saved charfield django model now i need iterate template,1 don use jsonfield example implementation see store content valid json rather stringified dict,how would convert object iterate u pk u u quantity u u name u mm aliminum sheet u size u x u pk u u quantity u u name u mm aliminum sheet u size u x this data saved charfield django model now i need iterate template,1 probably forgot create index foreignkey somecolumn resulting mysql needing perform full table scan find data you see running explain explain select column from table where foreignkey and somecolumn val,i using time profiler optimizing python script it turns mysql queries taking lot time python scripts there total queries these mysql queries take secs reported cprofile following complete script footprint mysql query respective query time secs python cprofile time myscriptpy mysql queries select column from table where foreignkey and somecolumn val select column from table where foreignkey and somecolumn val select column from table where foreignkey and somecolumn val function calls primitive calls cpu seconds ordered internal time ncalls tottime percall cumtime percall filenamelinenofunction method query mysqlconnection objects method execute psycopgpsycopgcursor objects method commit psycopgpsycopgconnection objects posixpathpyjoin posixlstat textfilepyreadline psycopgpsycopgconnect initpymodule connectionspyinit posixpathpyrealpath method storeresult mysqlconnection objects can anyone help figure reason thanks,2 i wonder would handle registration like the usual way handle registration write user info database inactive label attached user send email user if user confirms registration switch user active if want write database write cache like memcache redis user confirms registration get user info cache write database,i working tornado mongodb i would like send confirmation email user creates account application for moment i use simple xhtml page form i send information mongodb database using tornado i would like intermediate step sends email user inserting data database i would like know could i send email insert user account user receives email confirms registration,2 to phrase another way i inherit module override modify parts yes import module you use stuff module override stuff script you also create derived module call module module import which imports everything you use stuff module override stuff new module module other scripts import module and get stuff module modified overrides module,is possible copy module make changes copy to phrase another way i inherit module override modify parts,2 when inherent instance really strange way using metaclass normally class objects instances type in case class b inherits instance foo this exactly would happen defined class foo metaclass inherited so speculation happening python processing base classes reverse mro order class c works first parent class processed foo whose class type this means metaclass d must type subclass thereof then foo processed whose class foo subclass type everything fine class d fails first parent class processed foo sets constraint d metaclass foo subclass then foo comes along whose class type subclass foo that complete guess could try see python documentation metaclasses requires multiply inherit two classes different metaclasses metaclasses involved subtype relationship put particular order,i messing around dark arts python something i like help understanding given class foo ways i attempted inherit class afoo mdash works unsurprizingly class bfoo mdash works provided foo appropriate new method i provided class cfoo foo mdash works conditions b class dfoo foo mdash gives famous metaclass error traceback recent call last nbspnbspnbspfile testpy line nbspnbspnbspnbspnbspnbspnbspnbspclass dfoo foo typeerror metaclass conflict metaclass derived class must nonstrict subclass metaclasses bases what exactly causes conflict when i inherit foo foo instance first class second works i inherit foo foo class first instance second,3 as indicated comment could problem encryption mode using zip create zip file using aes i get error with zypcrypto encryption works ok pycrust the flakiest python shell python r jun msc v bit amd win type help copyright credits license information import zipfile psw abcd zipcrypto encryption path cusersjoaquindesktopzipcryptozip zip zipfilezipfilepath r zipsetpasswordpsw zipextractallcpython zipclose aes encryption path cusersjoaquindesktopaeszip zip zipfilezipfilepath r zipsetpasswordpsw zipextractallcpython traceback recent call last file input line module file cpythonlibzipfilepy line extractall selfextractzipinfo path pwd file cpythonlibzipfilepy line extract return selfextractmembermember path pwd file cpythonlibzipfilepy line extractmember source selfopenmember pwdpwd file cpythonlibzipfilepy line open raise runtimeerrorbad password file name runtimeerror bad password file zipfilezipinfo object xb this problem zipfile supporting traditional pkware encryption method reported feature request python,i trying implement simple script extracting zip files password protected i created simple zip file testzip password containing text files txt txt wrote script import zipfile password zip zipfilezipfiletestzip r zipsetpasswordpassword zipextractall zipclose getting following runtime error traceback recent call last file testpy line module zipextractall file usrlibpythonzipfilepy line extractall selfextractzipinfo path pwd file usrlibpythonzipfilepy line extract return selfextractmembermember path pwd file usrlibpythonzipfilepy line extractmember source selfopenmember pwdpwd file usrlibpythonzipfilepy line open raise runtimeerrorbad password file name runtimeerror bad password file zipfilezipinfo object xffa i tried iterating using zipnamelist extract method specifying exact parameters follows zipextractfilename pathpath pwdpassword luck i know security issue extractall complete code verification prior extracting process trying figure wrong thanks help advance,3 never considered using builtin ftplib,i looking alternative ftputil library should work python would nice archlinux repos is,1 the issue unittest runner replaces sysstdout sysstderr testing starts streamhandler still writing original sysstdout if assign current sysstdout handler work see code import sys import unittest import logging logger logginggetlogger loggerlevel loggingdebug streamhandler loggingstreamhandlersysstdout loggeraddhandlerstreamhandler class testcaseunittesttestcase def testsimplemsgself streamhandlerstream sysstdout printaa logginggetloggerinfobb although better approach would addingremoving handler test import sys import unittest import logging logger logginggetlogger loggerlevel loggingdebug class testcaseunittesttestcase def testsimplemsgself streamhandler loggingstreamhandlersysstdout loggeraddhandlerstreamhandler try printaa logginggetloggerinfobb finally loggerremovehandlerstreamhandler,i using pydev development unittesting python application as unittesting everything works great behalf fact content logged logging logger captured captured output pydev i already forward everything logged standard output like import sys logger logginggetlogger loggerlevel loggingdebug loggeraddhandlerloggingstreamhandlersysstdout nevertheless captured output display stuff logged loggers here example unittestscript testpy import sys import unittest import logging logger logginggetlogger loggerlevel loggingdebug loggeraddhandlerloggingstreamhandlersysstdout class testcaseunittesttestcase def testsimplemsgself printaa logginggetloggerinfobb the console output finding files done importing test modules done testsimplemsg itflowleveltestshltestcase aa root info bb bb ok ran test ok but captured output test captured output aa does anybody knows capture everything logged logginglogger execution test,3 nothing wrong you done correct thing if want use nonascii characters code need tell python encoding using this nothing django unicode,i getting error syntaxerror nonascii character xe file pointed formspy file chinese characters i put coding utf start formspy file would work i thought django handles everything unicode what wrong,3 agree eryksun amp joaquin z l slt testzip grep method show compress method used z p memzipcrypto testzip txt txt create python zipfile compatible zip z p memaes testzip txt txt create aes encrypted zip reference httpdocsbugacocomzipmanualswitchesmethodhtm,i trying implement simple script extracting zip files password protected i created simple zip file testzip password containing text files txt txt wrote script import zipfile password zip zipfilezipfiletestzip r zipsetpasswordpassword zipextractall zipclose getting following runtime error traceback recent call last file testpy line module zipextractall file usrlibpythonzipfilepy line extractall selfextractzipinfo path pwd file usrlibpythonzipfilepy line extract return selfextractmembermember path pwd file usrlibpythonzipfilepy line extractmember source selfopenmember pwdpwd file usrlibpythonzipfilepy line open raise runtimeerrorbad password file name runtimeerror bad password file zipfilezipinfo object xffa i tried iterating using zipnamelist extract method specifying exact parameters follows zipextractfilename pathpath pwdpassword luck i know security issue extractall complete code verification prior extracting process trying figure wrong thanks help advance,2 an object instantiation class think class like blueprint car ford make cars objects based rules information enclosed blueprint,i selfthaught python user kind i read much deepen knowledge python today i encountered text saying classes objects so i wondering difference objects classes python i tought classes objects case author used phrase classes objects i confused,1 these two closely related terms object oriented programming the standard meaning object instance class,i selfthaught python user kind i read much deepen knowledge python today i encountered text saying classes objects so i wondering difference objects classes python i tought classes objects case author used phrase classes objects i confused,3 yes classes functions modules basically everything python objects the difference lies types class fooobject pass print typefoo print typefoo to see objects check attributes print dirfoo print dirfoo,i selfthaught python user kind i read much deepen knowledge python today i encountered text saying classes objects so i wondering difference objects classes python i tought classes objects case author used phrase classes objects i confused,1 one use following code read config original code taken httpmarkpasctypepadcomblogloadingsshconfigsettingsforfabrichtml fabricapi import envhosts servername def annotatehostswithsshconfiginfo ospath import expanduser paramikoconfig import sshconfig def hostinfohost config hive configlookuphost hostname hive host hive hostname user hive host ss hive user host port hive host ss host hive port return host try configfile fileexpanduser sshconfig except ioerror pass else config sshconfig configparseconfigfile keys configlookuphostget identityfile none host envhosts envkeyfilename expanduserkey key keys key none envhosts hostinfohost config host envhosts role rolehosts envroledefsitems envroledefsrole hostinfohost config host rolehosts annotatehostswithsshconfiginfo,i trouble fabric recognizing hosts i sshconfig my fabfilepy follows fabricapi import run env envhosts lulu def whoami run whoami running fab whoami gives lulu run whoami fatal error name lookup failed lulu the name lulu sshconfig like host lulu hostname port identityfile sshlulukey my first thought solving adding something like lulululu etchosts i mac i also pass identity file fabric i rather keep authentication ie sshconfig separate deployment ie fabfilepy as well incidentally try connect host hosts file fabriccontribprojectsrsyncproject seem acknowledge ports hostsenv ie use hostsenv lulu call rsyncproject seems try connecting lulu is reason fabric recognize lulu name,2 have read httpcodegooglecompmodwsgiwikiintegrationwithdjango i suspect problem would solved used modwsgi daemon mode ie via wsgidaemonprocess,i two django applications appsystem testapp running separate folders enabled apache virtual host setting see conf file end one application displays page root domain one seems always work fine i go url go second application fails first time complaining find database table despite fact i see debug page loading right settings if i refresh page testapp works fine continues i go back page appssytem if i go back testapp i must refresh page both applications using sqlite authentication removing authentication sqlite references settings file appsystem seem make difference the reason i done way idea application displays root page admin pages unique urls list django application installed display links click i also suspect may session related i go directly testapp another browser works fine even first instance because i give django app value sessioncookiename seem helped does anyone idea problem may virtualhost serveradmin webmasterlocalhost documentroot appwwwroot rewriteengine on root box show system index list installed apps rewriterule appsystemsystemindex pt directory options followsymlinks allowoverride none directory directory appwwwroot order allowdeny allow directory errorlog varlogapacheerrorlog possible values include debug info notice warn error crit alert emerg loglevel warn customlog varlogapacheaccesslog combined include etcapacheinstalledapps gets pulled include alias testappstatic testappstatic alias testapplogs varlogtestapp wsgiscriptaliasmatch testapp testappdjangowsgi directory testapp order allowdeny allow directory directory varlogtestapp order allowdeny allow directory location testapplogs sethandler none options indexes location location testapplstatic sethandler none options indexes options includes addoutputfilter includes html location end included file wsgi docs advise trailing slash wsgiscriptalias appsystem appsysdjangowsgi virtualhost,1 this impossible use class decorator metaclass instead decorator syntax class fooobject dec def barself pass means class fooobject def barself pass bar decbar class definition processed execute body gather definitions wrap class object ie decoration done class comes existence,when i create decorator class method always receives method type function however i play around things bit i get back bound methods class testobject def saveself print save called def funcself print func called and typetestfunc type instancemethod typetestfunc type instancemethod what i would ultimately like create class method decorator also decorates method class how would i go,2 this loggerspecific behaviour never mutate insertremove elements list currently iterating if need make copy in case testloggerhandlers trick,i playing python logging system i noticed strange behavior removing handlers logger object loop namely loop removes one handler additional call removehandler removes last handler smoothly no error messages issued calls this test code import logging import sys loggingbasicconfig dbg logginggetlogger dbg dbgsetlevelloggingdebug testlogger logginggetlogger mylogger sh loggingstreamhandlersysstdout fh loggingfilehandler mylogfilelog dbgdebug adding handlers handlers lentestloggerhandlers testloggeraddhandlerfh testloggeraddhandlersh dbgdebug removing handlers lentestloggerhandlers strtestloggerhandlers h testloggerhandlers dbgdebug removing handler strh testloggerremovehandlerh dbgdebug go lentestloggerhandlers here i expect that no handler will remain dbgdebug removing handlers lentestloggerhandlers strtestloggerhandlers lentestloggerhandlers why happening testloggerremovehandlertestloggerhandlers dbgdebug manually removing last handler handlers lentestloggerhandlers i expect end loop handlers remain testlogger object however last call removehandler apparently fails seen output nevertheless additional call function removes handler expected here output debugdbgbefore adding handlers handlers debugdbgbefore removing handlers loggingfilehandler instance xf loggingstreamhandler instance xb debugdbgremoving handler loggingfilehandler instance xf debugdbg go debugdbgafter removing handlers loggingstreamhandler instance xb debugdbgafter manually removing last handler handlers more interestingly i replace original loop following one loop works expected handlers remain testlogger object end loop here modified loop lentestloggerhandlers h testloggerhandlers dbgdebug removing handler strh testloggerremovehandlerh dbgdebug go lentestloggerhandlers what explains behaviour is bug i missing something,3 in cases clever build new list newlist dd dd mylist dd newdict this typical functional programming style avoids side effects imagine use solution function method in cases need modified list internal purposes modifying input parameter dangerous,i trying remove dictionary list already exists seem working can anyone see i wrong advise i newdict value value key somekey newdict mylist mylistremovenewdict newlist list dictionaries newdict definitely,1 if newdict definitely mylist mylistremovenewdict trick ie need newdict mylist slows,i trying remove dictionary list already exists seem working can anyone see i wrong advise i newdict value value key somekey newdict mylist mylistremovenewdict newlist list dictionaries newdict definitely,3 try following config location mediaadmin alias optpythonlibpythonsitepackagesdjangocontribadminmedia expires max addheader cachecontrol public i changed path djangocontribadminmedia i guess admin media files folder normal hint mediaroot adminmediaprefix sould absolute,i currently testing moving apache modwsgi nginx fastcgi i prepared whole installation currently testing centos box runs django in old apache configuration i alias setup media also one called mediaadmin which displayed alias media wwwdjangotestomumedia directory wwwdjangotestomumedia alias mediaadmin optpythonlibpythonsitepackagesdjangocontribadminmedia directory optpythonlibpythonsitepackagesdjangocontribadminmedia how i get type setup nginx configuration currently snippet i even restarting nginx still see admin side resolving correct css images etc server location media root wwwdjangotestomu location mediaadmin root optpythonlibpythonsitepackagesdjangocontribadmin my settingspy basepath ospathdirnameospathabspathfile baseurl mediaroot smedia basepath mediaurl smedia baseurl adminmediaprefix smediaadmin baseurl,2 mylist value value key somekey z z x x newdict value value key somekey newdict z z x x differ matched element mylist typeelement typesdicttype matched differ check dictionary keys match elementviewkeys newdictviewkeys check dictionary values match key elementkeys elementkey newdictkey differ matched differ mylistremovenewdict print mylist it worked dictionaries,i trying remove dictionary list already exists seem working can anyone see i wrong advise i newdict value value key somekey newdict mylist mylistremovenewdict newlist list dictionaries newdict definitely,2 try running virtualenv modwsgi,i two django applications appsystem testapp running separate folders enabled apache virtual host setting see conf file end one application displays page root domain one seems always work fine i go url go second application fails first time complaining find database table despite fact i see debug page loading right settings if i refresh page testapp works fine continues i go back page appssytem if i go back testapp i must refresh page both applications using sqlite authentication removing authentication sqlite references settings file appsystem seem make difference the reason i done way idea application displays root page admin pages unique urls list django application installed display links click i also suspect may session related i go directly testapp another browser works fine even first instance because i give django app value sessioncookiename seem helped does anyone idea problem may virtualhost serveradmin webmasterlocalhost documentroot appwwwroot rewriteengine on root box show system index list installed apps rewriterule appsystemsystemindex pt directory options followsymlinks allowoverride none directory directory appwwwroot order allowdeny allow directory errorlog varlogapacheerrorlog possible values include debug info notice warn error crit alert emerg loglevel warn customlog varlogapacheaccesslog combined include etcapacheinstalledapps gets pulled include alias testappstatic testappstatic alias testapplogs varlogtestapp wsgiscriptaliasmatch testapp testappdjangowsgi directory testapp order allowdeny allow directory directory varlogtestapp order allowdeny allow directory location testapplogs sethandler none options indexes location location testapplstatic sethandler none options indexes options includes addoutputfilter includes html location end included file wsgi docs advise trailing slash wsgiscriptalias appsystem appsysdjangowsgi virtualhost,1 try requests simple powerful module based urllib docs,when would someone use httplib urllib what differences i think i ready urllib uses httplib i planning make app need make http request far i used httplibhttpconnection python requests reading urllib i see i use request whats benefit one,3 it depens order stuff happens if take normal method following happens class testobject def saveself print save called def funcself print func called testdictfunc function func xbe testfunc unbound method testfunc should what happens well look f testdictfunc fgetnone test f function func xbe unbound method testfunc the first original function object second one method object created actual method call furthermore instance test tfunc bound method testfunc maintest object xbab fgett test bound method testfunc maintest object xbab so happens attribute access now question the reason happens original function present class dict the method object creation happens access,when i create decorator class method always receives method type function however i play around things bit i get back bound methods class testobject def saveself print save called def funcself print func called and typetestfunc type instancemethod typetestfunc type instancemethod what i would ultimately like create class method decorator also decorates method class how would i go,1 pyramid support shutdown event however python atexit event runs interpreter shutdown httpdocspythonorglibraryatexithtml import atexit atexitregister def goodbye print you leaving python sector,pyramid supports applicationcreated event however i find applicationdestroyed applicationshutdown event is possible execute function upon shutdown do i choice go stack ie i using gevent inside uwsgi it might possible get gevent uwsgi run shutdown code certainly pretty,1 i got working i used customtreectrl tree list control multi inheritance listctrl checklistctrlmixin report like list check boxes i share code anyone interested,i looking create window two panels collapsible folder browser left panel list files right panel contained selected folder left similar nautilus older windows explorer both folders left files right need check box beside users make selection mix folders files across whole file system i look around found similarish builtin bits wx like genericdirctrl i get started i wanted ask anyone come across something like available better starting point genericdirctrl,1 matrixs joinf transformmatrix tested edit tested,def createsvgstyletransformationmatrixself transformmatrix return matrixf f f f f ftransformmatrixtransformmatrixtransformmatrixtransformmatrixtransformmatrixtransformmatrix as substitutions list sequence i hoping neater way anybody got ideas,2 if lentransformmatrix use return matrixf f f f f f tupletransformmatrix,def createsvgstyletransformationmatrixself transformmatrix return matrixf f f f f ftransformmatrixtransformmatrixtransformmatrixtransformmatrixtransformmatrixtransformmatrix as substitutions list sequence i hoping neater way anybody got ideas,3 you know pythonpath order know one thing actually want know vncbrowser coming instead printing python path following import vncbrowser vncone import mysitevncbrowser vnctwo print vnconefile print vnctwofile and see two different paths file system then start figuring this wild guess i think vncone installed somewhere python path vnctwo resides source code edit wrong guess further random remark also make import statement testspy simpler using models import instead xxxmodels import,i put unit tests mysitevncbrowsertestspy i run cd mysite python managepy test vncbrowser in testspy i import model classes vncbrowsermodels import project stack integerd doubled test insertion integerd custom field type test like class insertiontesttestcase def teststackinsertionself stack stitle example stack simagebase httpfoobar sdimension integerdx z sresolution doubledx z ssave selfassertequalsid however i run tests python managepy test vncbrowser i find check isinstancevalue integerd modelspy source failing it seems modelspy file bare reference integerd defined earlier file full name vncbrowsermodelsintegerd object passed test full name mysitevncbrowsermodelsintegerd the relevant code modelspy debugging statements class integerdobject elided class integerdfieldmodelsfield def topythonself value integerd print sysstderr value type value typevalue print sysstderr new integerd instance typea isinstancevalue integerd print sysstderr isinstance check worked return value print sysstderr isinstance check failed produces output newlines spaces added clarity value vncbrowsermodelsintegerd object xbbf type class vncbrowsermodelsintegerd new integerd instance class mysitevncbrowsermodelsintegerd isinstance check failed i make test work changing import testspy mysitevncbrowsermodels import project stack integerd doubled i see mysite qualification required testspy file it seem required elsewhere django source i sure i missing something obvious perhaps someone explain i even sure mysite import works fact since i print syspath statement includes path homemarkfoomysite homemarkfoo my current working directory homemarkfoomysite i run python managepy test vncbrowser as requested layout project follows ── mysite ├── custompostgresqlpsycopg │â â ├── basepy │â â └── initpy ├── initpy ├── managepy ├── settingspy ├── urlspy └── vncbrowser ├── initpy ├── modelspy ├── tablessql ├── testspy └── viewspy all initpy files listed empty i using python django i using python virtualenv i print njoinsyspath start testspy i get homemarkfoomysite homemarkfooenvlibpythonsitepackagesdistributepyegg homemarkfooenvlibpython homemarkfooenvlibpythonplatlinux homemarkfooenvlibpythonlibtk homemarkfooenvlibpythonlibold homemarkfooenvlibpythonlibdynload usrlibpython usrlibpython usrlibpythonplatlinux usrlibpythonlibtk usrlibpythonlibtk homemarkfooenvlibpythonsitepackages update suggested lbp answer i tried adding following top testspy import vncbrowser vncone import mysitevncbrowser vnctwo print vncone vnconefile print vnctwo vnctwofile produced output vncone homemarkfoomysitevncbrowserinitpyc vnctwo homemarkfoomysitemysitevncbrowserinitpyc,1 unfortunately argparse quite flexible enough the best make arg arg optional using nargs check whether given needed the internal help action implemented printing help message exiting program soon h help encountered command line you could write similar action something like class myactionargparseaction def callself parser values namespace optionstring print whatever parserexit warning untested code there definite downsides latter approac though the help message unconditionally show arg arg compulsory arguments and parsing command line simply stops encountering l list ignoring arguments this behaviour quite acceptable help less desirable options,i trying make argparse ignore fact two normally required positional arguments evaluated optional argument l specified basically i trying replicate behavior help specify h missing required arguments ignored example code parser argparseargumentparserdescriptionfoo bar baz parseraddargument arg help arg positional argument parseraddargument arg help arg positional argument parseraddargument l list dest list help optional argument prints stuff options args parserparseargs optionslist print i list stuff and course i run i get error arguments i tried different things like nargs get anything working this question quite similar answered any help appreciated thanks,3 alternatively use strformat method version preferred string interpolation python x return matrixf f f f f fformattransformmatrix the instructs python interpreter unpack arguments list tuple,def createsvgstyletransformationmatrixself transformmatrix return matrixf f f f f ftransformmatrixtransformmatrixtransformmatrixtransformmatrixtransformmatrixtransformmatrix as substitutions list sequence i hoping neater way anybody got ideas,3 matrixformat joinmapstr transformmatrix i think simplier matrix joinmapstr transformmatrix string concatenation problem three small strings avoid using large number big strings,def createsvgstyletransformationmatrixself transformmatrix return matrixf f f f f ftransformmatrixtransformmatrixtransformmatrixtransformmatrixtransformmatrixtransformmatrix as substitutions list sequence i hoping neater way anybody got ideas,2 yes metacall call productclassinit case may to quote documentation example defining custom call method metaclass allows custom behavior class called eg always creating new instance that page also mentions scenario metaclass call may return instance different class ie productclass example in scenario would clearly inappropriate call productclassinit automatically,say i got metaclass class metatype def callcls args print meta call args class productclassobject metaclass meta def initself args print productclass init args p productclass output follows meta call question why productclass init triggered just meta call update now i add new productclass class productclassobject metaclass meta def newcls args print productclass new args return superproductclass clsnewcls args def initself args print productclass init args p productclass is meta call responsibility call productclass new init,2 that weird direct way delete items qlistwidget try listwidget selflistdialogcontentlist model listwidgetmodel selecteditem listwidgetselecteditems qindex listwidgetindexfromitemselecteditem print removing modeldataqindextostring modelremoverowqindexrow,i qlistwidget i need remove items from i researched generally unpleasant thing i read tonne solutions none applicable specific scenario at moment i actual item widgets deal values index this i obtain items needed removed via selecteditems here code itemselect listselflistdialogcontentlistselecteditems x range lenitemselect print selflistdialogcontentlistremoveitemwidgetitemselectx this nothing however it raise error selected items removed the methods i seen removing items require either index name item neither i i actual widgets how i remove am i missing something i using python pyqt idle windows,1 i get figure i comment axtransdata transform definition import numpy np import matplotlibpyplot plt import matplotlibpatches patches import matplotlib mpl matplotlibcollections import patchcollection fig pltfigure ax figaddsubplot myangles mycolors mypatches color angle zip mycolorsmyangles r patchesrectangle colorcolor alpha r patchesrectangle mpltransformsaffinedrotatedegangle axtransdata rsettransformt axaddpatchr mypatchesappendr pltxlim pltylim pltgridtrue collection patchcollectionmypatches cmapmplcmjet alpha collectionsetarraynparraymycolors axaddcollectioncollection figsavefig withouttransdatapng pltshow,i want apply different transformations patch including rotating changing fill color hier piece code already inspired matplotlib rotating patch import numpy np import matplotlibpyplot plt import matplotlibpatches patches import matplotlib mpl matplotlibcollections import patchcollection fig pltfigure ax figaddsubplot myangles mycolors mypatches color angle zip mycolorsmyangles r patchesrectangle colorcolor alpha r patchesrectangle mpltransformsaffinedrotatedegangle axtransdata rsettransformt axaddpatchr mypatchesappendr pltxlim pltylim pltgridtrue collection patchcollectionmypatches cmapmplcmjet alpha collectionsetarraynparraymycolors axaddcollectioncollection pltshow unfortunatly transformation lost i get loop if i add patch ax inside loop everything fine but i end colors collected loop applied later advices kind highly appreciated cheers armel,1 there difference oop extending method overriding metaclass meta called overriding defined call method call parent call behavior want extend call method calling parent method class metatype def callcls args print meta call args return supermeta clscallargs,say i got metaclass class metatype def callcls args print meta call args class productclassobject metaclass meta def initself args print productclass init args p productclass output follows meta call question why productclass init triggered just meta call update now i add new productclass class productclassobject metaclass meta def newcls args print productclass new args return superproductclass clsnewcls args def initself args print productclass init args p productclass is meta call responsibility call productclass new init,3 set default value nargs positional arguments check manually code latitude longitude set listmethods mode parser argparseargumentparser parseraddargument lat helplatitudedefaultnone nargs parseraddargument lon helplongitudedefaultnone nargs parseraddargument method helpcalculation method default add defaultadd parseraddargument listmethods helplist available methods actionstoretrue args varsparserparseargs args listmethods args lat none args lon none print error arguments sysargv exit args listmethods print list methods else print normal script execution gives testpy listmethods list methods testpy testpy error arguments testpy normal script execution,i question regarding python argparse is possible optional argument require positional arguments example parseraddargument lat helplatitude parseraddargument lon helplongitude parseraddargument method helpcalculation method default add defaultadd parseraddargument listmethods helplist available methods actionstoretrue the normal command line would testpy testpy method sub but soon i call script testpy listmethods list available methods i get error arguments how i use argparse optional argument listmethods without positional arguments lat lon,2 check site httpallseeingicomasihttprequest it actually want send postget values form action page page httptestcomformphp following form form namelogin methodpost actionactionphp input nameusernamebr input namepasswordbr input typesubmit form use code perform form nsurl url nsurl urlwithstringhttptestcomactionphp asiformdatarequest request asiformdatarequest alloc initwithurlurl autorelease request setpostvalueadmin forkeyusername request setpostvalue forkeypassword request startsynchronous,i code python quite simple mechanize go url click submit button mechanize import parseresponse urlopen urljoin response urlopenhttpwwwsomesitecomsomepage forms parseresponseresponse backwardscompatfalse form forms print urlopenformclickread now question is librarysimple method objectivec i seen less similar examples nsurl quite big since i bunch diferent sites look like simple thing go torugh dozens code lines one debug everything easy way like mechanize regards bruno,1 takeitem work selecteditem selflistdialogcontentlistselecteditems selflistdialogcontentlisttakeitemselflistdialogcontentlistrowselecteditem,i qlistwidget i need remove items from i researched generally unpleasant thing i read tonne solutions none applicable specific scenario at moment i actual item widgets deal values index this i obtain items needed removed via selecteditems here code itemselect listselflistdialogcontentlistselecteditems x range lenitemselect print selflistdialogcontentlistremoveitemwidgetitemselectx this nothing however it raise error selected items removed the methods i seen removing items require either index name item neither i i actual widgets how i remove am i missing something i using python pyqt idle windows,3 mainline lazyboy supports cassandra i recommend using pycassa instead pycassa maintained datastax fully supports latest cassandra features if must use lazyboy fork supports cassandra compatible development look active last update may,hey stackoverflow comm i trying write cassandra database something going wrong some datas i using python ubuntu cassandra lazyboy while i want write cassandra i get traceback recent call last file homekqprotoworkspaceindexersrcdatabasepy line module wsave file usrlocallibpythondistpackageslazyboypyegglazyboyrecordpy line save selfsaveinternalselfkey changes consistency file usrlocallibpythondistpackageslazyboypyegglazyboyrecordpy line saveinternal key changes changed consistency file usrlocallibpythondistpackageslazyboypyegglazyboyconnectionpy line inner raise ex attributeerror client object attribute batchinsert this actual source lazyboy import lazyboykey import key connectionaddpool indexer localhost class indexxkey def initself args kwargs keyinitself indexer indexx key class wordrecordrecord required word docid count def initself args kwargs recordrecordinitself args kwargs selfkey indexx w word print wkey data word test docid docidtest count wupdatedata wupdatedataitems wupdatedata k data wk datak w worddata print w print wismodified wsave any ideas i wrong,1 import subprocess sub process subpopenls colorsalways stdoutsubpipe stderrsubpipe output errors processcommunicate now data want output including ansi escape sequences,what i need following python script spawn say ls colorsalways linux command read output the important part i need output keep ansi escape sequences colors later translate sequences html i heard python pty module i could find useful example usage internet module documentation quite comprehensive i appreciate someone could guide way accomplishing task,1 an inline formset required example i use i needed submit several stories given author also things i change models title modelscharfieldmaxlength text modelscharfieldmaxlength a textfield might appropriate least text part i would resolve like create authorform use existing storyform view so logic would following authorform authorformrequestpost authorformisvalid author authorformsave storyform storyformrequestpost storyformisvalid story storyformsavecommitfalse storyauthor author storysave the instance parameter let use specify already existing model form eg want update already existing database entry,i sorry ask two questions similar topics one day noobishness django completely taken basically i two models class storymodelsmodel title modelscharfieldmaxlength text modelscharfieldmaxlength date modelsdatefielddefaultdatetimedatetoday editablefalse likes modelsintegerfielddefault dislikes modelsintegerfielddefault views modelsintegerfielddefault author modelsforeignkey author relatednameusername class authormodelsmodel username modelscharfieldmaxlength uniquetrue email modelsemailfieldblanktrue firstname modelscharfieldmaxlength blanktrue lastname modelscharfieldmaxlength blanktrue idea someone submits story name goes author table pretty simple stuff my problem creating form allow user submit story name i tried inlineformset luck i find way perform i know simple and sql statement behind scenes here form models storyauthorformset inlineformsetfactoryauthor story class storyformmodelform class meta model story exclude date views likes dislikes author view def submitstoryrequest requestmethod post form storyformrequestpost formisvalid watch nest part aware author bit author formsavecommitfalse story storyauthorformsetrequestpost instanceauthor authorformsetisvalid storysave authorformsetsave return httpresponseredirect thanks else form storyform authorformset storyauthorformsetinstanceauthor return rendertoresponse submitsubmitstoryhtml locals contextinstancerequestcontextrequest i realise probably simple solution i missedbut i stumped ideas would greatly greatly appreciatedso much i free clojure erlang programming anybody needs,1 when say using python command window i guessing mean idle if rather try type command run script already created file use file open open file press f run good luck,i starting fresh python trying execute code python command window i wrote file desktoppracticenewpy lunched python command window i type cusersuserdesktoppracticenewpy gives syntaxerror invalid syntax executing cmd worked python window didnt any help edit put compiled code directory use import runs compiled directory execute edit file contains simple print statement nd sytax error free,1 the python command window expecting python commands try typing import system print if want run code another file need use import its easier start directory case import new work however already new module python library easiest thing rename file something else,i starting fresh python trying execute code python command window i wrote file desktoppracticenewpy lunched python command window i type cusersuserdesktoppracticenewpy gives syntaxerror invalid syntax executing cmd worked python window didnt any help edit put compiled code directory use import runs compiled directory execute edit file contains simple print statement nd sytax error free,1 everything explained httpdocspythonorgfaqwindowshtmlhowdoirunapythonprogramunderwindows the main point launch python shell its like live programming try type print hello world if want launch file run cmd python cusersuserdesktoppracticenewpy update if want run file within python shell answered how execute file within python interpreter,i starting fresh python trying execute code python command window i wrote file desktoppracticenewpy lunched python command window i type cusersuserdesktoppracticenewpy gives syntaxerror invalid syntax executing cmd worked python window didnt any help edit put compiled code directory use import runs compiled directory execute edit file contains simple print statement nd sytax error free,2 assuming connection oriented socket no you close old one create new socket,the program connects server connection closed server i try reconnect says socketerror errno bad file descriptor if i close socket client try reconnect says socketerror errno transport endpoint already connected is way reconnect broken pipe without creating new socket import socket host port socketsocketsocketafinet socketsockstream def loop try print srecv except socketerror sclose connect def connect sconnecthost port loop connect,3 i know problems specific diacritics python the following works uå‚ uåºdåºbå‚o true edit uå‚ uåºdåºblo false the matching exact if diacriticsinsensitive matching want specify question see fredrik answer edit yes string literals containing nonascii chars need specify encoding source file something like work coding utf,i testing python certain string contains something follows substr str dosomething the problem substr contains letter diacritics non usual characters how would recommend tests letters thank,1 the way data framed hybi hybi really hixie significantly changed the new frame format described diagram also data sent client server data masked the mask first bytes frame payload decoded encoded actually place using simple algorithm datai datai xor maskj mod the mask key different every frame getting different payload every time even though sending data if client receiving data sent chances framing data right also note chrome firefox yet support binary data opcode needs denote text utf frame,i using websocket python javascriptand handshake protocol google chrome draft hybi i guess google chrome changed protocol draft hybi recently so today i updated handshake code websocket succefully created opened on onopen event javascript i send simple text message vizws new websocketws vizwsonopen function vizwssendtestn my server python receives data however encoded somehow i get simple text testn i sent def recvdataself client count try data clientrecvcount except return false print data print datadecode utf ignore return datadecode utf ignore the prints return ã¼ã ãu┬â¯ã©ã¦â•‘â–„ u and always different sent text always testn also server receives data client receiving data sent server i read hybi uses binaries am i missing data conversion code i sorry i really new websockets protocols messing head,1 use triple quotes trip le quoted ag quoted keep mind python repr string backslashes mean actually added slashes string may showing special characters escaped using example python tutorial len isn said len isn said even though second string appears one character shorter backslash actually length backslash escape single quote single quoted string another example c isn said sysstdoutwritec isn said if let python format string see string changed python trying display unambiguously see tutorial section strings,hi i trying string contains single double quotation python the reason i need expression use input external batch command however python always automatically corrects i wonder way put double quotation single quotation together thanks,3 use triplequoted strings this string contains types quote so,hi i trying string contains single double quotation python the reason i need expression use input external batch command however python always automatically corrects i wonder way put double quotation single quotation together thanks,2 class myhandlerhandler def initself application traits handlerinitself traits selfapplication application,i using envisage workbance i want get service handler in tcpsendchanged function i get services in plugin selfapplicationgetservice i reach updated this view class mclidarguiview hastraits traitsuiview view vgroup hgroup item lidarlist showlabel false editor tabulareditor showtitles false selected selected editable false multiselect true adapter lidaradapter item lidarscommand hgroup item handlertcpsend showlabel false editor buttoneditor label tcpsend id forwindlidarapigiuview resizable true handler mclidaractions lidarlist lidarobject lidarname no connected lidar lidarscommand handler class mclidaractions handler tcpsend event def objectupdatedchanged self info print info pass def tcpsendchanged self print info,1 i issue the thing i found make image public save later use itemimageurlsplit get url,i writing client side image uploader library python i need upload image amazon s return public url image i using boto however i share secret key correct way as alternative i use browser upload using amazon post request give access image public url how i solve conundrum,1 edit the right tool shutilmove shutilmovepathpaths datadata assuming pathpaths absolute directory want rename datadata absolute directory name want rename the destination directory must already exist work the two locations need filesystem old answer use osrenames instead osrename it recursively create needed directories,i trying write little application takes value file named datadat renames folder contains file value the py script runs another folder allows user define path to give better idea user defined path must like mac usersuserdesktopfolder folder contain datadat that little part source code looks like try data open datadat read datadata data pathpaths pathrsplit basepath joinpathpaths chdirbasepath pathpaths datadata renamepathpaths datadata rawinput folder name corrected thank quit else print folder name already correct thank quit except indexerror rawinput error quit well works raise exception folder contains one file actually folder contain datadat folders that give problems traceback recent call last file usersuserdesktopexamplepy line module renamepathpaths datadata oserror errno directory empty just prevent happens way fix thanks,3 i using ffmpeg subprocess module python extract video thumbnails seems ffmpeg pretty much anything once install ffmpeg trim first second video like ffmpeg samplemov ss trimmov so using subprocess module python import subprocess seconds string subprocesscall ffmpeg inputfilename ss seconds outputfilename take first second for specific frames flags like vframes dframes i actually used documentation ffmpeg there also pyffmpeg python wrapper ffmpeg but i used,i would like trim cut frames beginning end video variety different formats save trimmed video are libraries suggestions thanks,2 it much easier use shutil,i trying write little application takes value file named datadat renames folder contains file value the py script runs another folder allows user define path to give better idea user defined path must like mac usersuserdesktopfolder folder contain datadat that little part source code looks like try data open datadat read datadata data pathpaths pathrsplit basepath joinpathpaths chdirbasepath pathpaths datadata renamepathpaths datadata rawinput folder name corrected thank quit else print folder name already correct thank quit except indexerror rawinput error quit well works raise exception folder contains one file actually folder contain datadat folders that give problems traceback recent call last file usersuserdesktopexamplepy line module renamepathpaths datadata oserror errno directory empty just prevent happens way fix thanks,1 something like might trick just create inttimer object call stamp whenever receive packet it start want might need change clean old stamps etc otherwise selftimestamps grow grow you could use selftimestamps work average times etc packets import time class inttimer def initself selftimestamps def stampself selftimestamps last selftimestamps else last false timetime selftimestampsappendnow last return time since last packet return last else return this quite simple answer asking complicated question say,i debugging code i need write python script read data sent serial port bluetooth calculate time elapsed successive packeti know read data serial port i issues calculating time packet any suggestions would helpful thanks,1 why use python time module calculate time diff if need beter precision implement timer using select system call but better solution use something like portmon,i debugging code i need write python script read data sent serial port bluetooth calculate time elapsed successive packeti know read data serial port i issues calculating time packet any suggestions would helpful thanks,1 loginauthentication to make django authenticate using emailpassword instead usernamepassword need add settingspy authenticationbackends myprojectmyauthenticationbackend this authentication backend needs able authenticate user based emailpassword a good email authentication backend found httpdjangosnippetsorgsnippets user registration normally registration form ask user email password however django auth user model requires every user username one way handle adding username upon saving registration modelform generate random username since using anyways you need check manually email user entered already registered system i also written blog post back complete notes email authentication it also includes sample emailpassword registration form httpwwwxaironnetdjangoemailonlyauthentication,i found djangoregistration app seems complex i trying i want users simply enter email username password automatically registered no activations confirmations hacker news style does anyone know simplest way implement would is something preexisting know i find anything i somehow modify djangoregistration build,2 generally speaking addresses always clean especially data coming straight users consider everyone standard address there po boxes rural routes suites tons variations street types road street circle court etc etc plus abbreviations spaces street names hypens house numbers complexity addresses easy underestimate mix potential nonus addresses complexity goes exponentially this giant function tries make sense least far us post concerned httpcodepadorgpktdudl i function kicking around may need tweaking elaboration if nothing else give idea task one faced trying make user address data sane this also makes tempting split house number street name street type separate fields if accuracy parsing addresses critical system design might want consider real estate systems example would need level granularity data if use case critically rely ability accurately parse data i would suggest presenting user extra fields just take address give try clean anticipate inconsistencies rest system design,i trying separate street names street numbers patterns street namestreet number street namestreet number street namestreet numbera streeta namestreet numbera what regex get street name regex get street number php python note the number always street name i guess shorten thanks,1 i would suggest best way determine number starts hit digit thus would use pregmatch dds address match examples bubbletown bubbletown circleta circle bloomfield avenue bloomfield avenue quibbit ave quibbit ave singletownabc singletown abc it probably best consider want edge cases handled write unit test test regex function,i trying separate street names street numbers patterns street namestreet number street namestreet number street namestreet numbera streeta namestreet numbera what regex get street name regex get street number php python note the number always street name i guess shorten thanks,1 i assuming tried userbinpython work it worked setting pycharm ide then provide following path python interpreter path systemlibraryframeworkspythonframeworkversionsbin course path might slightly different,i mac osx lion i installed eclipse eclipse java ee ide web developers version indigo release build id and i installed python plugins following instructions httpwwwrosehulmaneduclasscsseresourceseclipseeclipsepythonconfigurationhtm now according instructions i need set python executable path eclipse preference now i know mac comes version python installed and whereis python terminal reveals usrbin but file python exe i new mac one week i completely new python less one day thanks,1 generally speaking you need escape data inserted mysql query the python library provides access mysql provide escaping function escape data automatically using prepared statements the reason string data needs escaped quotes break sql statement used enter data,how i insert piece html code containing mysql database it easy simply escape backslash i looking solutions all solutions i found depended programming language php like example the programming language i using python i prefer general mysql solution the piece code i want insert could eg look like tr td widthimg alt srcimagesstoriespng height width td td widthmp std td widthogg std tr random code neccessarly senseful working thanks advance,1 the django serializer know handle mongoengine objects you likely write json encoder map simple dictionary class myencoderjsonjsonencoder def encodeobjectself obj return id unicodeobjid otherproperty objotherproperty def defaultself obj hasattrobj iter return selfencodeobjectx x obj else return selfencodeobjectobj call like import json import myencoder jsonstring jsondumpsmodelobjectsall clsmyencoder,how i dump data queryset mongo documents json file using python i tried use django serializer work fields accessed django way accessed mongo model models jsonserializerserializemodelobjectsall indent streamoutputfilemongo i also tried use python json encodedecoder import json model mongomodels outputfilemongowritejsondumpsmodelobjectsall i get exception file usrlibpythonjsoninitpy line dumps return defaultencoderencodeobj file usrlibpythonjsonencoderpy line encode chunks selfiterencodeo oneshottrue file usrlibpythonjsonencoderpy line iterencode return iterencodeo file usrlibpythonjsonencoderpy line default raise typeerrorrepro json serializable typeerror mongomodela mongomodela object json serializable,1 it sounds like probability density estimation problem scipystats import gaussiankde occurences values range kde gaussiankdemapfloat occurences p kdevalues p psump print px f sump also see httpjpktdblogspotcomusinggaussiankerneldensityhtml,introduction i list values ranging eg etc continuous distribution problem based distribution i would like calculate pvalue probability seeing greater values given value for example see pvalue would approaching pvalue higher numbers would tending i know i right determine probabilities i think i need fit data theoretical distribution suitable describe data i assume kind goodness fit test needed determine best model is way implement analysis python scipy numpy could present examples thank,1 here really simple solution works like normal python static variables def statickwargs def wrapf key value kwargsitems setattrf key value return f return wrap example usage statica def foox fooa return xfooa foo foo foo this closely matches normal way python static variables def foox fooa return xfooa fooa,i like create decorator like i seem think implementation works i starting think possible thought i would ask guys first i realize various ways create static variables python i find ways ugly i really like use syntax possible staticx def f x print x f prints f prints i care implementation static long hackity long works like i created version allows functionvarname syntax gets cumbersome pretty quickly longer function variable names def staticassignments def decoratefunc var val assignmentsitems setattrfunc var val return func return decorate various things i thought get work changing f decorated function callable class somehow storing static vars self transparently modifying globals f inside decorator somehow inserting global x statements code f changing f generator bind variables hand execute f code directly,3 i think twisted simply uses os resolver answer questions much os,if i use twisted endpoint api make series connections host twisted cache dns lookup requests if honour dns record ttl my implementation fairly vanilla i instantiate sslclientendpoint host port etc life program i use make several connections,1 refer flask api document flaskurlfor other sample snippets usage linking js css template script src urlfor static filename jqueryminjs script link relstylesheet typetextcss href urlfor static filename stylecss,half flask routes requires variable say variableadd variableremove how i create links locations urlfor takes one argument function route i add arguments,3 funny ask i bit surprised different use django documentation earlier today def uppercasenameobj return objfirstname objlastnameupper uppercasenameshortdescription name another occurrence method attribute attribute assigned function object class personadminadminmodeladmin listdisplay uppercasename so means essentially function definitions type object a familiar way saying might def myfunc return myvalue myfunc object type function local scope observe typemyfunc type function course call call myfunc myfunc myvalue myfunccall myvalue myfunc also normal object define attributes myfuncsomeattribute somevalue myfuncisafunction true myfunctakesargs false so question bit idea python objects way everything python object now useful suppose want collect use metadata set functions methods writing operator import attrgetter def addx return x def subtractx return x def getattributevalueobj attr return attrgetterattrobj addtakesargs true addnumberofargs addtypeofargs int int addusesblackmagic false subtracttakesargs true subtractnumberofargs subtracttypeofargs int int subtractusesblackmagic false getattributevaluetakesargs true getattributevaluenumberofargs getattributevaluetypeofargs object str getattributevalueusesblackmagic true you could use method attributes useful way def performfunctionchecksfunctionlist afunc functionlist getattrafunc takesargs print function takes args unusual afuncname getattrafunc numberofargs print function takes args afuncname afuncnumberofargs getattrafunc typeofargs print function takes args afuncname lenafunctypeofargs joinstritem item afunctypeofargs getattrafunc usesblackmagic print oh function uses black magic afuncname performfunctionchecksadd subtract getattributevalue prints function add takes args unusual function add takes args function add takes args type int type int function subtract takes args unusual function subtract takes args function subtract takes args type int type int function getattributevalue takes args unusual function getattributevalue takes args function getattributevalue takes args type object type str oh function getattributevalue uses black magic now course illustrative purposes actually trying type introspection functions objects probably want use inspect module rather adding bizarro metadata httpdocspythonorglibraryinspecthtml for information topic i recommend post httpwwwcafepycomarticlepythontypesandobjectspythontypesandobjectshtml edit sorry i address implementation allows method attributes callable addendum your example bit red herring discussion what going someone using property decorator decorate method make look like property aka attribute consider example let define simple class class foo normal attribute anattribute value method decorate property decorator property def whatkindself return strselfclassname instances foo class attribute whatkind bar foo bar instance foo baranattribute value finally decorated method barwhatkind foo note call whatkind return value i think property decorator automatically call call author post making look django adding plain old attribute class fact shortdescription votestoday actually methods here information property decoratorfunction builtin btw need import httpadamgomaausblogaugthepythonpropertybuiltin edit fixed couple markup problems typo,under documentation modeladminlistdisplay describes ways configure methodfunction usage display admin list view adminorderfield describes field model use ordering method allowtags allows html displayed rather escaped shortdescription sets label column boolean determines field treated boolean field display it describes method attributes addendum just found methodfunction attributes used template filters issafe used marking template filter safe needsautoescape used deal autoescaping data what method attributes django even python or really cases clarification just clear i talking specifically in following code class foomodelsmodel name modelscharfieldmaxlength color modelscharfieldmaxlength age modelspositiveintegerfield def isadultself return age isadultboolean true isadultshortdescription over def colorednameself return span stylecolor ssspan selfcolor selfname colorednameallowtags true colorednameshortdesciption name colorednameadminorderfield name the method attributes i talking isadultboolean isadultshortdescription colorednameallowtags colorednameshortdescription colorednameadminorderfield if need details please read linked documentation addendum looks like partially covered pep function attributes the pep points mailing list post lists potential use cases function attributes i need associate javastyle type declaration method recognized based type java method dispatch how would instances i need associate grammar rule python method method invoked parser recognizes syntactic construct input data i need associate idl declaration method com interface definition generated source file i need associate xpath pattern string python method method invoked tree walker discovers particular pattern xml dom i need associate multiple forms documentation method they optimized different ides environments languages here implementation allows method attributes callable djangocontribadmin import modeladmin datetimedatetime import class profileadminmodeladmin listdisplay votestoday class votestoday def callself modeladmin obj today nowreplacehour minute second microsecond return objvotesetfiltercreatedgtetoday property def shortdescriptionself return votes today nowstrftime b property def votestodayself hasattrself votestoday selfvotestoday selfvotestoday return selfvotestoday,3 you check byte order mark start srt file test encoding however probably work files required attribute specified utf files anyways a check performed teststr b xffxfeotherdata teststr b xffxfe print utf little endian elif teststr b xfexff print utf big endian what probably want simply open file decode whatever pull file unicode deal unicode representation ready print encode back see talk information code samples might relevant,i wish able read srt file python these files found httpwwwopensubtitlesorg with info httpenwikipediaorgwikisubrip subrip supports encoding ascii unicode example if i understand correctly i need specify decoder use i use pythons read function so i right saying i need know file encoded order make judgement if i establish file i hundred files different sources language support ultimately i would prefer i could convert files utf encoding start but files might obscure encoding i know please help barry,1 try changing connection localhost instead loaclhost,i code import socket sck socketsocketsocketafinet socketsockstream sck socketsocketsocketafinet socketsockstream sckconnect loaclhost and i error traceback recent call last file pyshell line module sckconnect localhost socketerror errno no connection could made target machine actively refused please helpe where error how i repair,2 try httpdocspythonorglibraryospathhtmlospathexpanduser import ospath subprocesscallospathexpandusersrcrankrank outputtxt,i want call program multiple times python code save output program text file my first problem right calling code i redirect different directory call rank outputtxt this im trying thecommand srcrankrank outputtxt ossystemthecommand im getting parsing error parsing error line unknown error im running python mac os im sure problem i also tried using subprocess subprocesscallsrcrankrank outputtxt this find directory i feeling im using subprocess incorrectly i dont know wrong ossystem,1 name program first argument subprocesspopen must contain pass string shell processing like always using parameterized queries sql protects one string injection attacks eg instead outputtext one rm rf system version would run rank run rm rf subprocesspopen would rank open file named rm rf one expand calling ospathexpanduser subprocesspopenospathexpanduser srcrankrank outputtxt although possible turn shell processing passing shelltrue recommended aforementioned reason,i want call program multiple times python code save output program text file my first problem right calling code i redirect different directory call rank outputtxt this im trying thecommand srcrankrank outputtxt ossystemthecommand im getting parsing error parsing error line unknown error im running python mac os im sure problem i also tried using subprocess subprocesscallsrcrankrank outputtxt this find directory i feeling im using subprocess incorrectly i dont know wrong ossystem,3 your code error match spelling localhost port number error message due server listening port cut paste exact code error message next time,i code import socket sck socketsocketsocketafinet socketsockstream sck socketsocketsocketafinet socketsockstream sckconnect loaclhost and i error traceback recent call last file pyshell line module sckconnect localhost socketerror errno no connection could made target machine actively refused please helpe where error how i repair,1 use threadingevent timesleep interrupt class memmonthreadingthread def initself threadingthreadinitself selfkeeprunning true selfmaxmem selfinterrupt threadingevent def runself loop run call set interrupt selfinterruptisset selfmaxmem maxselfmaxmem ckmem either sleep seconds timeout interrupted interrupt set selfinterruptwait mem memmon memrun later set interrupt halt second sleep end loop meminterruptset,forgive dumb question i new threading i running thread finish i change keeprunning status like class memmonthreadingthread def initself threadingthreadinitself selfkeeprunning true selfmaxmem def runself selfkeeprunning selfmaxmem maxselfmaxmem ckmem timesleep but due sleep call i often wait join other creating faster loop checks keeprunning often anything i join thread instantaneously for example overriding del join,2 i error well downgrading unixodbc fixes note i get pyobdc build i fairly troubled state newer releases odbc tools unix freetds problematic well,i get following error trying simple query i figure changed here example sqlalchemy elixir class class songentity usingoptionstablename tbsongs autoloadtrue usingtableoptionsschema apra the database connection ok classes construct ok i dirsong see correct columns however simple query work here query class resulting output songs songqueryall traceback recent call last file stdin line module file usrlibpythonsitepackagessqlalchemyormquerypy line return listself file usrlibpythonsitepackagessqlalchemyormquerypy line iter return selfexecuteandinstancescontext file usrlibpythonsitepackagessqlalchemyormquerypy line executeandinstances result connexecutequerycontextstatement selfparams file usrlibpythonsitepackagessqlalchemyenginebasepy line execute params file usrlibpythonsitepackagessqlalchemyenginebasepy line executeclauseelement compiledsql distilledparams file usrlibpythonsitepackagessqlalchemyenginebasepy line executecontext context file usrlibpythonsitepackagessqlalchemyenginebasepy line executecontext context file usrlibpythonsitepackagessqlalchemyenginedefaultpy line doexecute cursorexecutestatement parameters sqlalchemyexcdbapierror error im im unixodbcdriver managerdriver support function sqlcolattribute select tbsongsidsong as apratbsongsidsong tbsongsalbum as apratbsongsalbum tbsongstitle as apratbsongstitle tbsongscomposer as apratbsongscomposer tbsongsperformer as apratbsongsperformer tbsongstracknumber as apratbsongstracknumber tbsongsduration as apratbsongsduration tbsongsrecordlabel as apratbsongsrecordlabel tbsongsnotes as apratbsongsnotes tbsongsclass as apratbsongsclass tbsongssongid as apratbsongssongid tbsongsdeleted as apratbsongsdeleted nfrom apratbsongs as tbsongs setup details bit arch linux python sqlalchemy elixir freetds unixodbc etcodbcinstini odbc drivers tds installed tds driver usrliblibtdsodbcso setup usrliblibtdsodbcso etcodbcini odbc trace dbname driver tds trace no server xxxxxxxxdbname database dbname port,1 dbpedia content rdf format the dumps download dbpedia large dataset rdf handling amount data need use triple store technology for dbpedia need one native triple stores i recommend use either virtuoso store i personally prefer store once triple store set dbpedia you use sparql query dbpedia rdf triples there python libraries help store virtuoso give results back json easily get without libraries some simple urllib script like def queryqeprf applicationjson try params query q params urlliburlencodeparams opener urllibbuildopenerurllibhttphandler request urllibrequestepr params requestaddheader accept f requestgetmethod lambda get url openeropenrequest return urlread except exception e tracebackprintexcfilesysstdout raise e help run sparql instance q select birthplace httpdbpediaorgresourceclaudemonet httpdbpediaorgpropertybirthplace birthplace print queryqhttpdbpediaorgsparql head link vars birthplace results distinct false ordered true bindings birthplace type literal xmllang en value paris france i hope gives idea start,i writing python script extract entity names collection thousands news articles countries languages i would like make use amazing dbpedia structured knwoledge say example look names artists egypt names companies canada if information sql form i would problem i would prefer download dbpedia content use offline ideas needed query locally python,3 here implementation singletons all decorate class get singleton use instance method here example singleton class foo def initself print foo created f foo error get instance singleton f fooinstance good being explicit line python zen g fooinstance returns already created instance print f g true and code class singleton a nonthreadsafe helper class ease implementing singletons this used decorator metaclass class singleton the decorated class define one init function takes self argument other restrictions apply decorated class to get singleton instance use instance method trying use call result typeerror raised limitations the decorated class cannot inherited def initself decorated selfdecorated decorated def instanceself returns singleton instance upon first call creates new instance decorated class calls init method on subsequent calls already created instance returned try return selfinstance except attributeerror selfinstance selfdecorated return selfinstance def callself raise typeerror singletons must accessed instance def instancecheckself inst return isinstanceinst selfdecorated,this question discussion whether singleton design pattern desirable antipattern religious wars discuss pattern best implemented python way pythonic in instance i define pythonic mean follows principle least astonishment i multiple classes would become singletons usecase logger important i wish clutter several classes added gumph i simply inherit decorate best methods method a decorator def singletonclass instances def getinstanceargs kwargs class instances instancesclass classargs kwargs return instancesclass return getinstance singleton class myclassbaseclass pass pros decorators additive way often intuitive multiple inheritance cons while objects created using myclass would true singleton objects myclass function class cannot call class methods also myclass n myclass typen n ampamp ampamp n method a base class class singletonobject instance none def newclass args kwargs isinstanceclassinstance class classinstance objectnewclass args kwargs return classinstance class myclasssingleton baseclass pass pros it true class cons multiple inheritance eugh new could overwritten inheritance second base class one think necessary method a metaclass class singletontype instances def callcls args kwargs cls clsinstances clsinstancescls supersingleton clscallargs kwargs return clsinstancescls python class myclassbaseclass metaclass singleton python class myclassbaseclass metaclasssingleton pass pros it true class automagically covers inheritance uses metaclass proper purpose made aware cons are method decorator returning class name def singletonclass class classwclass instance none def newclass args kwargs classwinstance none classwinstance superclassw classnewclass args kwargs classwinstancesealed false return classwinstance def initself args kwargs selfsealed return superclassw selfinitargs kwargs selfsealed true classwname classname return classw singleton class myclassbaseclass pass pros it true class automagically covers inheritance cons is overhead creating new class here creating two classes class wish make singleton while fine case i worry might scale of course matter debate whether aught easy scale pattern what point sealed attribute can call methods name base classes using super recurse this means customize new subclass class needs call init,1 this uses simple fast encryption scheme bytes objects for python strings unicode print function def obfuscatebyt use function directions input output bytes objects mask b keyword lmask lenmask return bytesc maski lmask c enumeratebyt def tests data obfuscatesencode printlens lendata data newdata obfuscatedatadecode printnewdata simplestring just plain ascii unicodestring sensei nhiragana letter senhiragana letter n nhiragana letter senhiragana letter i testsimplestring testunicodestring python version for python mask keyword nmask ordc c mask lmask lenmask def obfuscates use function directions input output python strings ascii return joinchrordc nmaski lmask c enumerates def tests data obfuscatesencode utf print lens lendata reprdata newdata obfuscatedatadecode utf print newdata simplestring u just plain ascii unicodestring u sensei nhiragana letter senhiragana letter n nhiragana letter senhiragana letter i testsimplestring testunicodestring,i need obfuscate lines unicode text slow may want extract ideally would done built python module small addon library string length less original unobfuscation fast possible i tried various character swaps xor routines slow base hex encoding increase size considerably to date efficient method i found compressing zlib lowest setting is better way,2 you subclassing wrong thing missing enter method you probably want class contextshelfshelveshelve def enterself return self def exitself exctype excvalue exctrace selfclose because adding methods changing init signature adding extra steps reason need redefine init the base class init called automatically,i using python builtin shelve module manage simple dictionaries the problem i i want use shelveopenfilename f i try claims dbfilenameshelf attribute exit so i guessing easiest way wrap another class add exit function wrapper i tried class wrappershelvedbfilenameshelf def exitself selfclose def initself filename writebackfalse shelvedbfilenameshelfinitself filename flag c protocolnone writebackfalse but i tried instantiate wrapper like wrapped wrapperfilename tells i giving invalid argument error requested traceback recent call last file input line module file input line init file cpythonlibshelvepy line init shelfinitself anydbmopenfilename flag protocol writeback file cpythonlibanydbmpy line open return modopenfile flag mode file cpythonlibdbhashpy line open return bsddbhashopenfile flag mode file cpythonlibbsddbinitpy line hashopen dopenfile dbdbhash flags mode dbinvalidargerror invalid argument,1 don subclass python comes tool automatically calling close contextlibclosing contextlib import closing closingshelveopenfilename f block automatically call close method object returned shelveopenfilename end block,i using python builtin shelve module manage simple dictionaries the problem i i want use shelveopenfilename f i try claims dbfilenameshelf attribute exit so i guessing easiest way wrap another class add exit function wrapper i tried class wrappershelvedbfilenameshelf def exitself selfclose def initself filename writebackfalse shelvedbfilenameshelfinitself filename flag c protocolnone writebackfalse but i tried instantiate wrapper like wrapped wrapperfilename tells i giving invalid argument error requested traceback recent call last file input line module file input line init file cpythonlibshelvepy line init shelfinitself anydbmopenfilename flag protocol writeback file cpythonlibanydbmpy line open return modopenfile flag mode file cpythonlibdbhashpy line open return bsddbhashopenfile flag mode file cpythonlibbsddbinitpy line hashopen dopenfile dbdbhash flags mode dbinvalidargerror invalid argument,3 how old rot trick x string xencode rot fbzr fgevat ydecode rot u string for unicode string x u 國碼 print x 國碼 xencode unicodeescape encode rot print hohop print ydecode rot decode unicodeescape 國碼,i need obfuscate lines unicode text slow may want extract ideally would done built python module small addon library string length less original unobfuscation fast possible i tried various character swaps xor routines slow base hex encoding increase size considerably to date efficient method i found compressing zlib lowest setting is better way,3 i modified recipe make work classmethod here code import copyreg import types def picklemethodmethod funcname methodimfuncname obj methodimself cls methodimclass funcnamestartswith funcnameendswith deal mangled names clsname clsnamelstrip funcname ss clsname funcname return unpicklemethod funcname obj cls def unpicklemethodfuncname obj cls obj funcname objdict cls obj obj none funcname classmethod cls clsmro try func clsdictfuncname except keyerror pass else break return funcgetobj cls copyregpickletypesmethodtype picklemethod unpicklemethod,i met pickling error dealing multiprocessing multiprocessing import pool def testfuncx return x class test classmethod def funccls x return x def mprunn func args return poolnmapfunc args name main args range print mprun testfunc args print mprun testfunc args exception thread thread traceback recent call last file usrlibpythonthreadingpy line bootstrapinner selfrun file usrlibpythonthreadingpy line run selftargetselfargs selfkwargs file usrlibpythonmultiprocessingpoolpy line handletasks puttask picklingerror can pickle type instancemethod attribute lookup builtininstancemethod failed and i found useful thread solution perfect self style instancemethod i got problem applying recipe classmethod def picklemethodmethod funcname methodimfuncname obj methodimself cls methodimclass return unpicklemethod funcname obj cls def unpicklemethodfuncname obj cls try cls clsmro try func clsdictfuncname except keyerror pass else break except attributeerror func clsdictfuncname return funcgetobj cls copyregpicklemethodtype picklemethod unpicklemethod newfunc pickleloadspickledumpstestfunc traceback recent call last file testpy line module newfunc pickleloadspickledumpstestfunc file usrlibpythonpicklepy line dumps picklerfile protocoldumpobj file usrlibpythonpicklepy line dump selfsaveobj file usrlibpythonpicklepy line save selfsavereduceobjobj rv file usrlibpythonpicklepy line savereduce saveargs file usrlibpythonpicklepy line save fself obj call unbound method explicit self file usrlibpythonpicklepy line savetuple saveelement file usrlibpythonpicklepy line save fself obj call unbound method explicit self file usrlibpythonpicklepy line saveglobal obj module name picklepicklingerror can pickle type classobj found builtinclassobj any ways alter lines get work classmethod,2 you integer variable named id masking builtin function id that messing cprofile rename id variable cprofile work fine,following script runs great python myscriptpy when i try profile code using cprofile like python cprofile time myscriptpy python cprofile myscriptpy i get following error traceback recent call last file systemlibraryframeworkspythonframeworkversionslibpythonrunpypy line runmoduleasmain main fname loader pkgname file systemlibraryframeworkspythonframeworkversionslibpythonrunpypy line runcode exec code runglobals file systemlibraryframeworkspythonframeworkversionslibpythoncprofilepy line module main file systemlibraryframeworkspythonframeworkversionslibpythoncprofilepy line main run execfiler sysargv optionsoutfile optionssort file systemlibraryframeworkspythonframeworkversionslibpythoncprofilepy line run result profprintstatssort file systemlibraryframeworkspythonframeworkversionslibpythoncprofilepy line printstats pstatsstatsselfstripdirssortstatssortprintstats file systemlibraryframeworkspythonframeworkversionslibpythonpstatspy line init selfinitarg file systemlibraryframeworkspythonframeworkversionslibpythonpstatspy line init selfloadstatsarg file systemlibraryframeworkspythonframeworkversionslibpythonpstatspy line loadstats argcreatestats file systemlibraryframeworkspythonframeworkversionslibpythoncprofilepy line createstats selfsnapshotstats file systemlibraryframeworkspythonframeworkversionslibpythoncprofilepy line snapshotstats callersdictsidentrycode callers typeerror int object callable my script runs successfully cases except chokes cprofile latter case i know something really petty cant nail please help resolve thanks,3 i hazarding guess one ec instance node attempts rpc call ec instance node node returns internal ip address instead reference httpalesticcomecelasticipinternal quote this last option uses littleknown feature elastic ip address system implemented amazon ec when ec instance queries external dns name elastic ip ec dns server returns internal ip address instance elastic ip address currently assigned and examples illustrates dig returns different values comparing scenario use machine outside amazon ping ec instance versus use ec instance ping another ec instance this permanent external dns name elastic ip address matter many times change instance assigned if query dns name outside ec resolve external ip address shown dig short eccomputeamazonawscom however query dns name inside ec instance resolve internal ip address instance currently assigned dig short eccomputeamazonawscom,i trying create simple clientserver application using thrift going run ec the example i created works awesome localhost i try make rpc call across two different machines ec separately allocated elastic ip addresses work following error raceback recent call last file socialqclientpy line module transportopen file usrlocallibpythondistpackagesthrifttransportttransportpy line open return selftransopen file usrlocallibpythondistpackagesthrifttransporttsocketpy line open raise ttransportexceptiontypettransportexceptionnotopen messagemessage thrifttransportttransportttransportexception could connect myelasticip i security group set port machines tcp i tried udp also fix what i wrong update,2 solution the tls simulated stacklessgreenlet using current tasklet object retrieved call stacklessgetcurrent store additional data solution if tasklet support add extra fields global weakkeydictionary instance weakref key tasklet value represents tls,i starting stackless python whole new amazing world i usually use regular threads normally threadlocal storage tls useful feature need not share memory threads so i wondering stackless python something similar a way store local memory python object given tasklet is possible thanks advance f,1 searching so python utf windows brings first result question getting python print utf windows xp console describes problem printing utf windows python,let say utestuuuu uuuuuuaueubueubue if i try print directly print traceback recent call last file stdin line module unicodeencodeerror cp codec encode character u u position illegal multibyte sequence so i change console utf within python otherwise understand input import winconsole winconsolesetconsoleoutputcp winconsolesetconsolecp and output string encoded utf python know chcp utf known bug print sencode utf testø§ù„ù„ù‡ ø£ùƒø¨ø±çˆ†ç™ºð¾ð»ð¾ð»ð¾traceback recent call last file stdin line module ioerror errno error as see prints successfully hits newline throws ioerror the following workaround works def safeprintstr try print strencode utf except pass print safeprints testø§ù„ù„ù‡ ø£ùƒø¨ø±çˆ†ç™ºð¾ð»ð¾ð»ð¾ but must better way any suggestions,2 ok i found solution i would love see elegant one data numpyemptyshape dtype start date s n int creates dimensional array single element gets element this makes accessing elements work strings numerical indices data start date contains space flexible namedtuple data data it would nice way directly constructing data without first create array one element extracting element since typedata type numpyvoid i sure numpy constructor could called… docstring numpyvoid,is possible create numpy object behaves much like collectionsnamedtuple sense elements accessed like data data start date slight generalization possible namedtuple i tried use complex data type data numpyemptyshapetuple dtype start date s n int this creates dimensional value kind namedtuple type almost works data start date data array dtype start date s n however element access work array dimensional data traceback recent call last file ipythoninputedb line module data indexerror arrays indexed is way obtaining desired behavior described item assignment string index numpy object,1 you something like using numpyrec module what need record class module i know directly create instance class one indrect way first create recarray single entry numpyrecarray namesstart date n formatss astart date if figure create instance record directly please let know,is possible create numpy object behaves much like collectionsnamedtuple sense elements accessed like data data start date slight generalization possible namedtuple i tried use complex data type data numpyemptyshapetuple dtype start date s n int this creates dimensional value kind namedtuple type almost works data start date data array dtype start date s n however element access work array dimensional data traceback recent call last file ipythoninputedb line module data indexerror arrays indexed is way obtaining desired behavior described item assignment string index numpy object,2 your code work exactly typed def foomylist barfirst mylist def barvals print joinvals fooab print firstab,given function funcargs list i unpack list i pass contents separate arguments i know i functhelist i actually want pass along another object besides contents list something like funcsomeobj thelist how i,2 it also useful formfieldashidden,i django form regexfield similar normal text input field in view certain conditions i want hide user trying keep form similar possible what best way turn field hiddeninput field i know i set attributes field form fieldname fieldwidgetattr readonly readonly i set desired initial value forminitial fieldname mydesiredvalue however change form widget what bestmost djangoyleast hacky way make field input typehidden field,3 so exact match letters little tricky instead creating permutations checking one merely sort words alphabetical order using python builtin sorted function doc compare result the trick realizing looking anagram letters for example terse reset anagrams sort turn eerst even looking exact matches still use trick make optimizations as rest program look basic tutorials reading text file python i sure able get rest good luck,hi question python im rookie text file contains list words around alphabetical order like small dictionary line word textfile make programme asks user nine letters programme supposed rerange letters find words textfile match set nine letters im kind stuck coding programme would like assistance please done nian rawinput type nine letters filename dictionarytxt fil openfilename r lines filread tx linesstrip nian b nian c nian nian e nian f nian g nian h nian nian w lines b c e f g h lines print w,1 here take depending average inmates per cell might improve performance if better way get cells eg node properties replace cells n n bnodes n nodes i assuming nodes list inmates itertools import combinations def timeoverlapprojectedgraphparallelb nodes gnxmultigraph gaddnodesfromnbnoden n nodes cells n n bnodes n nodes cell cells uv combinationsbcell uspell bgetedgedataucellvalues ustart uspell uend uspell vspell bgetedgedatavcellvalues vstart vspell vend vspell uend vstart vend ustart ostart maxustartvstart oend minuendvend olen oendostart ocell cell v gu ostart edict edict guvvalues gaddedgeuv olen ostart oend ocell return g,using networkx module i network analysis python i need project bipartite graph inmates linked cell input graph b code subgraph linking cellmates overlapping spell cell using input set nodes defining inmatenodes graph b generating output graph g i need special algorithm come optimal matching i need collect links satisfy conditions thus so posts i found really apply but my current code blowing ram swap cpuwise i give data please let know see ways streamline code layers loops i sure knowledge networkx necessary details labeling edge attributes relevant thanks def timeoverlapprojectedgraphparallelb nodes gnxmultigraph gaddnodesfromnbnoden n nodes u nodes unbrs setbu nbrs setn nbr unbrs n bnbr setu v nbrs mutualcell setbu amp setbv uspell bgetedgedataumutualcellvalues ustart uspell uend uspell vspell bgetedgedatavmutualcellvalues vstart vspell vend vspell uend vstart vend ustart ostart maxustartvstart oend minuendvend olen oendostart ocell mutualcell v gu ostart edict edict guvvalues gaddedgesfromuv olen ostart oend ocell return g,1 httpwwwpipinstallerorgenlatestothertoolshtmlpipcomparedtoeasyinstall pip doesn’t everything easyinstall specifically it cannot install eggs it installs source,i working windows i created python egg using distutils now i try install egg virtual environment using pip using following command then i create virtual environment myvirtualenv i activate using activatebat execute following command pip install pathtomylocalfoldereggname this creates copy egg myvirtualenvbuild directory i following error ioerror errno no file directory pathofmyvirtualenvbuildpyeqdrsetuppy do know pip looking setuppy file should i include egg,3 the answer going depend language source files written recall python function definitions prefixed def suffixed expanding stema answer try python sdef sssssss this match python function definitions the match beginning end line respectively find function defs line usually python,i need find function definitions like function param param param i using following regular expression python sss something like refindallssssourcecodestring give function names working please suggest improvements regular expression i new regular expressions,1 rather trying use embed link go directly google api get images static graphics here link google maps static image api looks like pass longlat parameters url normal embeddable one for example httpmapsgoogleapiscommapsapistaticmapcenterampsizexampzoomampsensorfalse gives x streetlevel overview centered coordinates give seems porto alegre brazil now use urlopen pil ned suggests cstringio import stringio import image import urllib url httpmapsgoogleapiscommapsapistaticmapcenterampsizexampzoomampsensorfalse buffer stringiourlliburlopenurlread image imageopenbuffer,i noticed google maps page get embed link put inside iframe load map browser news the image size adjusted large i interested getting som big images single pngs more specifically i would like define rectangular area bounding box upperright lowerleft coordinates get corresponding image appropriate zoom factor but question how i use python get pixel content map image object my rationale browser get render image content python capable edit content html file shows sample map iframe width height frameborder scrollingyes marginheight marginwidth srchttpmapsgooglecombrmapshlptbrampampllampampspnampampzampampoutputembed edit i suggested ned batchelder read content urlliburlopen call using src address taken iframe the result lot javascript code i think google maps javascript api so question lingers could i useful stuff stuff python order get map image edit link appears contain pretty relevant info google maps tiles maps httpwwwcodeprojectcomkbscrapbookgooglemapaspx also httpeconymorgukgmaphowitworkshtm,3 the information looking descriptor howto guide to support method calls functions include get method binding methods attribute access this means functions nondata descriptors return bound unbound methods depending whether invoked object class in pure python works like class functionobject def getself obj objtypenone simulate funcdescrget objectsfuncobjectc return typesmethodtypeself obj objtype so really anything strange going get method function object calls typesmethodtype returns result,i know want add method class instance simple assignment like def printvarself method added printselfvar class myclass var c myclass cprintvar printvar indeed would cause printvar behave like normal function self argument typical meaning cprintvar function printvar xeec cprintvar traceback recent call last file pyshell line module cprintvar typeerror printvar takes exactly argument given in order let function considered method ie bind instance i used use code import types cprintvar typesmethodtypeprintvar c cprintvar bound method myclassprintvar mainmyclass object xabac cprintvar i found get may also used purpose cprintvar printvargetc cprintvar bound method myclassprintvar mainmyclass object xabac cprintvar the problem works i understand the documentation get seem help much i appreciate someone could clarify behaviour python interpreter,2 you breaking loop outer loop if anything loop propagate break adding true print attempting locate correct bluetooth gps device address discovereddevices address targetaddress print unable locate bluetooth gps device retrying else print bluetooth gps device located targetaddress break else break continue loop normally continue otherwise break loop well break,i currently trying connect gps bluetooth device my python code worked correctly initially i tried implement code loop whilst device available continue keep looping unfortunately code seems stuck loop repeatedly prints error message unable locate bluetooth gps device retrying i using bluetooth module pybluez here code import bluetooth targetaddress discovereddevices discoverdevices object discover devices bluetooth module true print attempting locate correct bluetooth gps device address discovereddevices address targetaddress print unable locate bluetooth gps device retrying else print bluetooth gps device located targetaddress break move next statement outside loop connection etc as said basically i looking achieve device discovery object start message appear console indicate looking device transmitting specified device address ie should device address i like code present error message relating unable locate device i like continue keep looking on side i would also ultimately like edit code attempting locate device x amount time number x occasions avail i like code end program present error message any guidance thanks,2 the line discovereddevices discoverdevices go inside loop entering loop then replace loop loop limit number attempts and properly exit inner loop jeremy said add else continue break end you may also want wait attempt using sleep iteration outer loop,i currently trying connect gps bluetooth device my python code worked correctly initially i tried implement code loop whilst device available continue keep looping unfortunately code seems stuck loop repeatedly prints error message unable locate bluetooth gps device retrying i using bluetooth module pybluez here code import bluetooth targetaddress discovereddevices discoverdevices object discover devices bluetooth module true print attempting locate correct bluetooth gps device address discovereddevices address targetaddress print unable locate bluetooth gps device retrying else print bluetooth gps device located targetaddress break move next statement outside loop connection etc as said basically i looking achieve device discovery object start message appear console indicate looking device transmitting specified device address ie should device address i like code present error message relating unable locate device i like continue keep looking on side i would also ultimately like edit code attempting locate device x amount time number x occasions avail i like code end program present error message any guidance thanks,3 you could use charade package formerly chardet detect encoding,i wish able read srt file python these files found httpwwwopensubtitlesorg with info httpenwikipediaorgwikisubrip subrip supports encoding ascii unicode example if i understand correctly i need specify decoder use i use pythons read function so i right saying i need know file encoded order make judgement if i establish file i hundred files different sources language support ultimately i would prefer i could convert files utf encoding start but files might obscure encoding i know please help barry,1 the object returned selfrequestgetimg property called filename assuming img file upload course,i upload db coming user request like xfile dbblobselfrequestgetimg how i get filename i request blob solution could applied ok,1 do need permission as need sudo python setuppy install,i directory django project localhost mydjangolist in folder i django application called pk i downloaded djangoregistration unzipped folder mydjangolist i went terminal went djangoregistration folder ran python setuppy install it bunch things spit following error could create usrlocallibpythondistpackagesregistration permission denied the install file says i put folder project i even need install if i properly install,1 in short main process second process share stdin multiprocessing import process queue import sys def subproc print sysstdinfileno name main print sysstdinfileno qproc processtargetsubproc qprocstart qprocjoin run get two different results sysstdinfileno unfortunately solve problem what trying,so i program main process i fire new process object i want read lines stdin append queue object essentially basic system setup command getting process user enter commandsqueries i need get queries subsystems running separate processes my thinking share via multiprocessing queue systems read what i focusing getting commandsqueries basically def subprocq somestr true somestr rawinput somestrlower quit return qputnowaitsomestr name main q queue qproc processtargetsubproc argsq qprocstart qprocjoin point q contain strings entered user the problem i get process process traceback recent call last file usrlibpythonmultiprocessingprocesspy line bootstrap selfrun file usrlibpythonmultiprocessingprocesspy line run selftargetselfargs selfkwargs file homeblahblahblahblahpy line subproc somestr rawinput file randompathhereeclipsepluginsorgpythonpydevpysrcpydevsitecustomizesitecustomizepy line rawinput ret originalrawinputprompt eoferror eof reading line how,2 refindallr requestparams upsell this return list entry contents different group curly braces note work nested braces the make lazy match opposed greedy this means match stop first instead continuing match many characters possible ending last closing brace refindall search string find nonoverlapping matches return group alternatively could use refinditer iterate match objects would need use matchgroup get inside braces this also would need change example matchgroup returns entire match captured group need put number group want,i trying find functionality python similar ruby function scan my goal grab text inbetween two curly braces list if multiple pairs curly braces string i want multiple entries list when i run code match researchr requestparams upsell print matchgroup i match right text however captured includes curly braces i want include text i want include everything curly braces thanks,3 you need add wsgiapplicationgroup directive httpdconf file directory wwwdjangoapache wsgiapplicationgroup global order denyallow allow directory,i using django centos python version using numpy i used viewspy function calculate regression line sample code numpy import def testfuncrequest n tlinspacen parameters b xpolyvalabt add noise xnxrandnn linear regressison polyfit polyfit used orders polys arbrpolyfittxn xrpolyvalarbrt return in browser i call page cannot load but works fine windows default development server comes django could anyone tell mistake code i miss something thanks advanced,1 import refindallr b c b,i trying find functionality python similar ruby function scan my goal grab text inbetween two curly braces list if multiple pairs curly braces string i want multiple entries list when i run code match researchr requestparams upsell print matchgroup i match right text however captured includes curly braces i want include text i want include everything curly braces thanks,1 use group lookbehindsaheads also sure take advice fj jf use either import match researchr asdfasd asdfasdfasdf print matchgroup lookbehindsaheads import match researchr asdfasd asdfasdfasdf print matchgroup,i trying find functionality python similar ruby function scan my goal grab text inbetween two curly braces list if multiple pairs curly braces string i want multiple entries list when i run code match researchr requestparams upsell print matchgroup i match right text however captured includes curly braces i want include text i want include everything curly braces thanks,3 if want install system folder i recommend sudo pip install djangoregistration may need sudo aptget install pythonpip beforehand assuming ubudebian if like put alongside folder instead unzip use another django app that means take look see everything standard places eg projectapppymodelstemplatesetc,i directory django project localhost mydjangolist in folder i django application called pk i downloaded djangoregistration unzipped folder mydjangolist i went terminal went djangoregistration folder ran python setuppy install it bunch things spit following error could create usrlocallibpythondistpackagesregistration permission denied the install file says i put folder project i even need install if i properly install,1 you use separate threads processes tkinter uses single thread process display updates thread used event callbacks if event handler blocks tkinter code execute completes if tkinter thread one calls tkmainloop another thread rest application event handlers running within tkinter thread simply pass messages possibly using queuequeue application event handler,i making programs includes loopsto illustrate number calculatings i use tkinter gui program windows freezing loop finished i want add stop button i want windows freeze how i two things thank,2 if data grid data point point dataloni datalatj dataij use scipyinterpolaterectbivariatespline instead griddata some geographyspecific libraries may offer functionality though,i trying map irregularly gridded dataset raw satellite data associated latitudes longitudes regularly gridded set latitudes longitudes given basemapmakegrid i using matplotlibmlabgriddata mpltoolkitsnatgrid installed below list variables used output whos ipython stats variables variable type datainfo datalat ndarray x elems type float bytes mb datalon ndarray x elems type float bytes mb gridlat ndarray x elems type float bytes mb gridlon ndarray x elems type float bytes mb var ndarray x elems type float bytes mb in varmin out in varmax out in datalatmin out in datalatmax out in datalonmin out in datalonmax out in gridlatmin out in gridlatmax out in gridlonmin out in gridlonmax out datalat datalon orignal data coordinates gridlat gridlon coordinates interpolate var contains actual data using variables i call griddatadatalon datalat var gridlon gridlat taken long minutes complete returns array nan from looking data latitudes longitudes appear correct original coordinates overlapping portion new area data points lying outside new area does anyone suggestions the nan values suggest i something stupid,1 cachemaxhits timeout calls initmaxhits timeout satisfying function argument you could implement decorator via wrapper method detected whether function present if finds function return cache object otherwise return wrapper function used decorator class cacheobject def initself function maxhits timeout selffunction function selfmaxhits maxhits selftimeout timeout selfcache def callself args here code returning correct thing wrap cache allow deferred calling def cachefunctionnone maxhits timeout function return cachefunction else def wrapperfunction return cachefunction maxhits timeout return wrapper cache def doublex return x cachemaxhits timeout def doublex return x,i trying pass optional arguments class decorator python below code i currently class cacheobject def initself function maxhits timeout selffunction function selfmaxhits maxhits selftimeout timeout selfcache def callself args here code returning correct thing cache def doublex return x cachemaxhits timeout def doublex return x the second decorator arguments overwrite default one maxhits timeout init function working i got exception typeerror init takes least arguments given i tried many solutions read articles i still make work any idea resolve thanks,3 cache def double equivalent def double doublecachedouble while cachemaxhits timeout def double equivalent def double double cachemaxhits timeoutdouble cachemaxhits timeoutdouble different semantics cachedouble it unwise try make cache handle use cases you could instead use decorator factory take optional maxhits timeout arguments returns decorator class cacheobject def initself function maxhits timeout selffunction function selfmaxhits maxhits selftimeout timeout selfcache def callself args here code returning correct thing def cachehitsmaxhits timeout def cachefunction return cachefunctionmaxhitstimeout return cache cachehits def doublex return x cachehitsmaxhits timeout def doublex return x ps if class cache methods besides init call probably move code inside cache function eliminate cache altogether,i trying pass optional arguments class decorator python below code i currently class cacheobject def initself function maxhits timeout selffunction function selfmaxhits maxhits selftimeout timeout selfcache def callself args here code returning correct thing cache def doublex return x cachemaxhits timeout def doublex return x the second decorator arguments overwrite default one maxhits timeout init function working i got exception typeerror init takes least arguments given i tried many solutions read articles i still make work any idea resolve thanks,3 fascinating — answers note utterly unreleased unknown language how ever find background screenshot i brighten image gimp see talking the dialect slightly pythonic — uses init object initiation seems something like python loop though used integers — borrows least many constructs languages the … end delimiters ruby from smalltalk ruby method arguments simply listed whitespace separation method name instead delimited punctuation the language reason seems unable handle abc despite order operations lefttoright expressions least since release c around instead odd language makes type abc unless i misunderstand special case lambda functions use parens arrow regular expressions direct support syntax using r for cannot see image clearly snippet showing five features occurs one level deep inside curly braces whose beginning cannot see def initself parent nil superinit parent selfsetlayout qgridlayout transform rnsub br c selflayoutsetrowstretch c c selflayoutsetcolumnstretch c selflayoutaddwidget qlabel transform selftext selflayoutaddlayout sublayout qhboxlayout sublayoutaddwidget qlineedit sublayoutaddwidget qpushbutton …russian text… return sublayout selflayoutaddwidget qlabel transform selffooter end my wild guess language compiles directly c since beneath pretty syntax i see nothing requires dynamic language,on background image find code looks like written extended python dialect processed “python dg” get “normal” python code google results “python dg” query yandexru one page cache briefly mention one example python dg sum map int str seems equivalent summapint str do know i want take look tool find links…,2 you use python module random import random urls formhtml formhtml formhtml formhtml formhtml redirectto randomchoiceurls redirection stuff httpdocspythonorglibraryrandomhtml,so i learning cgi programming python need create forms ask input users use input display results i create five different forms hence different results i want play button result page users click directed one five forms i read lot redirecting case i put url i want random page generated how i thank,1 with lookahead assertion resplitr schange ds change persondomaincom some random text including line breaks change persondomaincom some random text including line breaks change persondomaincomn some random text including line breaks change persondomaincomn some random text including line breaks,i new python regular expressions bear i text looks like change persondomaincom some random text including line breaks change persondomaincom some random text including line breaks now i want use python along regular expression split tuple in end i want tuple contain two elements element change persondomaincom some random text including line breaks element change persondomaincom some random text including line breaks i realize i use regex recognize pattern formed word change space digits text date form text text line break i know could broken i think recognizing things good enough purposes once i come regular expression pattern i use split string tuple strings,2 try removing prepackaged freetds unixodbc pyodbc rebuilding sources using version respectively worked tricky process i covered detail recent thread sqlalchemy group httpgroupsgooglecomgroupsqlalchemybrowsethreadthreadeddd,i get following error trying simple query i figure changed here example sqlalchemy elixir class class songentity usingoptionstablename tbsongs autoloadtrue usingtableoptionsschema apra the database connection ok classes construct ok i dirsong see correct columns however simple query work here query class resulting output songs songqueryall traceback recent call last file stdin line module file usrlibpythonsitepackagessqlalchemyormquerypy line return listself file usrlibpythonsitepackagessqlalchemyormquerypy line iter return selfexecuteandinstancescontext file usrlibpythonsitepackagessqlalchemyormquerypy line executeandinstances result connexecutequerycontextstatement selfparams file usrlibpythonsitepackagessqlalchemyenginebasepy line execute params file usrlibpythonsitepackagessqlalchemyenginebasepy line executeclauseelement compiledsql distilledparams file usrlibpythonsitepackagessqlalchemyenginebasepy line executecontext context file usrlibpythonsitepackagessqlalchemyenginebasepy line executecontext context file usrlibpythonsitepackagessqlalchemyenginedefaultpy line doexecute cursorexecutestatement parameters sqlalchemyexcdbapierror error im im unixodbcdriver managerdriver support function sqlcolattribute select tbsongsidsong as apratbsongsidsong tbsongsalbum as apratbsongsalbum tbsongstitle as apratbsongstitle tbsongscomposer as apratbsongscomposer tbsongsperformer as apratbsongsperformer tbsongstracknumber as apratbsongstracknumber tbsongsduration as apratbsongsduration tbsongsrecordlabel as apratbsongsrecordlabel tbsongsnotes as apratbsongsnotes tbsongsclass as apratbsongsclass tbsongssongid as apratbsongssongid tbsongsdeleted as apratbsongsdeleted nfrom apratbsongs as tbsongs setup details bit arch linux python sqlalchemy elixir freetds unixodbc etcodbcinstini odbc drivers tds installed tds driver usrliblibtdsodbcso setup usrliblibtdsodbcso etcodbcini odbc trace dbname driver tds trace no server xxxxxxxxdbname database dbname port,1 a general solution python iterables specific numpy arrays works linear average time onm n number subarrays number unique subarrays b collections import defaultdict indexmap defaultdictlist row sublist enumeratea b column item enumeratesublist indexmaptupleitemappendrow column repeats dictkey value key value indexmapiteritems lenvalue gives if need doublerowindexes index list stored index simplify loop row b column item enumeratesublist indexmaptupleitemappendcolumn processed b duplicates get numbered row automatically with repeatskeyrownum returning column index row,i large unsorted arrays structured set xyz coordinates i trying find positions identical subarrays common points consisting coordinates example array b array here correct subarray would one identical subarrays possible the correct indexes would b i already implemented pure python method iterating points one array comparing every point array extremely slow my question efficient way find indexes arrays preferably numpy i need arrays calculations perhaps rollingwindow approach,1 after googling python equivalent dbdcsv i found kirbybase that looks though fit bill since i generally use python however i never tried edited add okay taking glance documentation query commands exactly sql lot sqlesque using awk,background sqlite great sql operations data loaded databases many times line work i need selects joins statements files loaded database necessarily worth time loadinginitialization database also random access characteristics sqlite often make operations performed every row database slower question is suite sql type commandsfxns preferably pythonbash need sqlite works raw tab spaced files for instance instead using tables select rows use column numbers example select colcolcol filenametsv colint note i realize lot accomplished awk cut bashjoin etc i wondering something sqlesque,1 fwiw various things wrong configuration why using wsgiscriptaliasmatch directive you replace wsgiscriptalias don use wsgiscriptaliasmatch properly stuff reverse url resolution using sethandler none required that something may needed modpython modwsgi using location directive block apply directives static file resources bad practice you apply specific directories using directory directive instead as pointed others better using daemon mode if worked delegate applications single daemon mode process though may multi process issue ie application handle run multiple processes time if delegated daemon process group may issue running process even case separate sub interpreters,i two django applications appsystem testapp running separate folders enabled apache virtual host setting see conf file end one application displays page root domain one seems always work fine i go url go second application fails first time complaining find database table despite fact i see debug page loading right settings if i refresh page testapp works fine continues i go back page appssytem if i go back testapp i must refresh page both applications using sqlite authentication removing authentication sqlite references settings file appsystem seem make difference the reason i done way idea application displays root page admin pages unique urls list django application installed display links click i also suspect may session related i go directly testapp another browser works fine even first instance because i give django app value sessioncookiename seem helped does anyone idea problem may virtualhost serveradmin webmasterlocalhost documentroot appwwwroot rewriteengine on root box show system index list installed apps rewriterule appsystemsystemindex pt directory options followsymlinks allowoverride none directory directory appwwwroot order allowdeny allow directory errorlog varlogapacheerrorlog possible values include debug info notice warn error crit alert emerg loglevel warn customlog varlogapacheaccesslog combined include etcapacheinstalledapps gets pulled include alias testappstatic testappstatic alias testapplogs varlogtestapp wsgiscriptaliasmatch testapp testappdjangowsgi directory testapp order allowdeny allow directory directory varlogtestapp order allowdeny allow directory location testapplogs sethandler none options indexes location location testapplstatic sethandler none options indexes options includes addoutputfilter includes html location end included file wsgi docs advise trailing slash wsgiscriptalias appsystem appsysdjangowsgi virtualhost,1 it fact provide editdistance method see docs,i writing spell checker using nltk wordnet i wrongly spelt words say belive what i want find words wordnet separated leveshtein edit distance given word does nltk provide methods accomplish how may i put wrongly editdistance method takes arguments like editdistancewordword returns levenshtein distance word word what i want find edit distance word i give every word wordnet,1 you hack something together using csv module list comprehensions import csv reader csvreaderopen datacsv r rows row row reader select data first column actually work asis see edit row row rows row select data second column third column row row rows row row select columns data first column mykey row row row rows row mykey you probably even impressive things python’s functional programming tools although you’re already familiar fp it’s probably big topic learn edit a couple tips if you’re going perform one “query” per script cut intermediate storage data rows example import csv reader csvreaderopen datacsv r result row row reader row banana the csv reader generates output text want treat one column eg integer you’ll for example second third columns integers import csv reader csvreaderopen datacsv r rows row introw introw row reader perform select rows this means first example won’t actually work asis if columns integers invoke functional map function import csv reader csvreaderopen datacsv r rows mapint row row reader,background sqlite great sql operations data loaded databases many times line work i need selects joins statements files loaded database necessarily worth time loadinginitialization database also random access characteristics sqlite often make operations performed every row database slower question is suite sql type commandsfxns preferably pythonbash need sqlite works raw tab spaced files for instance instead using tables select rows use column numbers example select colcolcol filenametsv colint note i realize lot accomplished awk cut bashjoin etc i wondering something sqlesque,1 as explained tutorial at least once dictionary keys unique if want multiple values key fake sequence foo bar,i experience strange issue resulting dict dict django template data hrs ld u pname dn u ts ist u ts act u o date datetimedate id hrs ld u pname dn u ts ist u ts act u ti date datetimedate id hrs ld u pname dn u ts ist u dmin act u poc date datetimedate id hrs ld u pname dn u smgr ist u smgr act u pl date datetimedate id hrs ld u pname dn u smgr ist u ts act u mting date datetimedate id hrs ld u sname dn u holiday ist u holiday act u pl date datetimedate id hrs ld u sname dn u holiday ist u holiday act u pl date datetimedate id hrs ld u sname dn u ts ist u ts act u o date datetimedate id hrs ld u sname dn u pd ist u pd act u lop date datetimedate id using list dict wrote logic results collectionsdefaultdictdict fetch data user fetch ld getid fetch id adata ssss fetch dn fetch ist fetch act fetch hrs row resultsuser row user user dt strfetch date rowdt adata give output results u sname u holidayholidaypl u pdpdlop user u sname u holidayholidaypl u pname u tststi u smgrtsmting user u pname u tstso in general need get output dict dict print date key value instead multiple key values date expected output u sname u holidayholidaypl u tstso u pdpdlop user u sname u holidayholidaypl u pname u tststrickle u tsdminpoc u smgrsmgrpl u smgrtsmting user u pname u techsupporttechsupporto one using template tag hash table template registerfilter def hashobject attr gencontext object object try value templatevariable objects attrresolvegencontext except templatevariabledoesnotexist value return value html table thead thsnoth thnameth dates weekdates thdatesth endfor thead tr fetch dataitems tr td forloopcounter td td fetch td dates weekdates td fetchhashdates td endfor tr endfor table any help really appreciate please let know need information,1 you cannot put try statement list comprehension generators exist complex list processing def cleanlst item lst try itemvideo except videodoesnotexist pass else yield item cleanedlist cleandirtylist,is possible convert following list comprehension cleanedlist item dirtrylist try itemvideo except videodoesnotexist pass else cleanedlistappenditem,3 since based questions using django check actual field cleanedlist item item dirtylist itemvideoid none,is possible convert following list comprehension cleanedlist item dirtrylist try itemvideo except videodoesnotexist pass else cleanedlistappenditem,3 there reason result claimed id fact offer nothing support expectation however noted first library uses wrong value claimed id emphasis mine normalization the end user input must normalized identifier follows â url identifiers must normalized following redirects retrieving content and second url response headers removed get xrdsusernamecataphractmyopenidcom http host wwwmyopenidcom accept applicationxrdsxml http moved permanently location httpcataphractmyopenidcomxrds therefore httpusernamemyopenidcomxrds used,when authenticating openid i afaict supposed use claimed identifier key uniquely identify specific user the problem i either two independent bugs misunderstanding spec when using node openid i would expect two urls result claimedid httpusernamemyopenidcom httpwwwmyopenidcomxrdsusername usernamemyopenidcom however urls result two different claimedids httpusernamemyopenidcom httpwwwmyopenidcomxrdsusername usernamemyopenidcom urls mentioned to verify behaviour i decided check different openid library python openid using two urls i still get two claimedids case different i get httpusernamemyopenidcom httpusernamemyopenidcomxrds so i guess questions i right assuming claimedids used identifiers urls result claimedid,1 i looked around good solution yet find proper solution looking tkinterpy class looks like image del value def delself selfname try selftkcall image delete selfname except tclerror may happen root destroyed pass this means wanted brutal hack could setup photoimage described jtp link photo tkphotoimagefilecmyimagegif widgetimage photo widgetimage photo then could program exited following hack photoname none this would prevent trying clean photoimage delete prevent exception called del method i really recommend unless back wall alternative i continue look i find better solution edit post better one hopefully someone give correct solution,i making tkinter gui nothing except call images course i struggled find decent tkinter documentation along there line code cannot seem asked i want call values dictionary individually print pull image name one next value called i tried dictitervalues dictvalues seem figure anything altogether anyway snippet key ansdictiterkeys using iterkeys function kind xkey root tktk root window created right place roottitle c h e m i s t r y a b c frameanstkframeroot frameansgridrow column stickytknw rangelenansdictx print ansdictxi value ansdictitervalues this important part rangelenvalue pulls value list dictionary named ansdict picref imageopenvaluei jpg calls image file name using pil photo imagetkphotoimagepicref masterroot button tkbuttonframeans compoundtktop imagephoto textstrvaluei nclose bg white pulls button onto image pasted buttongridstickytknw padx pady places button grid buttonimagephoto rootmainloop finally end pulls one two images i get following error tclerror invoke image command application destroyed i figure wrong i move image command somehow i need save destroyed i know code errors i think i figure tclerror i getting i set everything else straight if easier way please tell,1 pyexe done prerequisites dependencies remove additional installuninstall could use msi installer creator,there large python application consists numerous thirdparty packages binary libraries here overview requirements crossplatform currently windows modern linux distributions installing lots say mb binary libraries dlls windows installing thirdparty python packages cannot installed windows using tools like easyinstall installing visual studio redistributable package needed preserving file layout package possible compressed eggs a clear way remove packages libraries distribute test suite pytest case option nosource distribution pyc the application portable least python package installed anywhere using virtualenv what choices should i stick setuptools distribute should i roll custom installer the application developed proprietary provides python api developers i want look feel pythonish hackerish possible,1 use subprocess redirect input output process created,i wanted type command prompt windows net users administrator and returns type password cmd i want type password egpass then type enter pressed how would go ossystem work it goes new cmd time any ideas,2 here class decorator make class multiton def multitoncls instances def getinstanceid id instances instancesid clsid return instancesid return getinstance this slight variant singleton decorator pep then make class multiton use decorator multiton class myobject object def init self arg selfid arg expensive stuff now instantiate myobject id get instance myobject b myobject c myobject b false b c true,i trying create class recreate object input parameters when i try instantiate class parameters used create alreadyexisting object i want new class return pointer alreadycreated expensivelycreated object this i tried far class myobjectobject at first i realize even alreadyinstantiated objects init called instances def newclsx x clsinstanceskeys clsinstancesx objectnewclsx return clsinstancesx def initselfx print something expensive class myobjectobject i tried override existing object init didnt work instances def newclsx x clsinstanceskeys clsinstancesx objectnewclsx else clsinstancesxinit lambda x none return clsinstancesx def initselfx print something expensive class myobjectobject i want ugly instances def newclsx x clsinstanceskeys clsinstancesx objectnewclsx clsinstancesxisnew else clsinstancesxisnew return clsinstancesx def initselfx selfisnew print something expensive this first venture overriding new i convinced i going right way set straight please,3 python normally stores unicode values internally ucs the utf representation utf u character ududf got result that said python builds use ucs builds compatible take look pyunicode this type represents storage type used python internally basis holding unicode ordinals python’s default builds use bit type pyunicode store unicode values internally ucs it also possible build ucs version python recent linux distributions come ucs builds python these builds use bit type pyunicode store unicode data internally ucs on platforms wchart available compatible chosen python unicode build variant pyunicode typedef alias wchart enhance native platform compatibility on platforms pyunicode typedef alias either unsigned short ucs unsigned long ucs,i need step python string one character time simple loop gives utf code units instead str abcuacuufffd ch str code ordch printuxformatcode that prints u u u uac ud udf udbff udffd i wanted u u u uac u ufffd is way get python give sequence unicode code points regardless string actually encoded hood i testing windows i need code work anywhere it needs work python i care python x the best i able come far import codecs str abcuacuufffd bytestr codecsgetencoderutfbestr range lenbytestr code b bytestrii code code b printuxformatcode but i hoping simpler way pedantic nitpicking precise unicode terminology ruthlessly beaten head cluebyfour i think i made clear i please waste space utf technically unicode kind arguments,2 the question title asking something specific lua equivalent getting value array removing that would thetable fill needed local thevalue thetable get value tableremovethetable remove value table the question ask post seems openended,i working project endusers running lua communicating server written python i find way i need lua summary i give program input recipient commandargumentargument sender get output list containing recipient commandargumentargument sender separate items individual variables after i separate commandargumentargument another list separate variables how i python test server searching guy example msglist testsplit recipient msglistpop msg msglistpop id msglistpop cmdarglist cmdsplit cmd cmdarglistpop lencmdarglist argument localsarg strargument argument any advice better ideas would greatly appreciated,1 this nicely implemented series pandas package for example tutorial pandas import import numpy np seriesnprandomrandn index b c e b c e b i playing around days looks like lot offer,is possible create numpy object behaves much like collectionsnamedtuple sense elements accessed like data data start date slight generalization possible namedtuple i tried use complex data type data numpyemptyshapetuple dtype start date s n int this creates dimensional value kind namedtuple type almost works data start date data array dtype start date s n however element access work array dimensional data traceback recent call last file ipythoninputedb line module data indexerror arrays indexed is way obtaining desired behavior described item assignment string index numpy object,2 perhaps pytz normalize method looking import datetime dt import pytz tzpytztimezone europelondon dtdatetime ttzlocalizet dttimedeltahours sumval sumval remains bst printreprsumval datetimedatetime tzinfodsttzinfo europelondon bst dst after normalization sumval gmt sumval tznormalizesumval printreprsumval datetimedatetime tzinfodsttzinfo europelondon gmt std note london dst transition occurs,so i currently line code looks like datetimeselfyear selfmonth selfday selfhour selfminute selfsecond timedeltadaysdaynum hourstimehour minutestimeminute secondstimesecond sumval i would like result take account dst affects might occur i am add hours i would get am due fall back dst i looked using pytz pythondateutil neither seem support least support without separate file contains time zones the kicker times may necessarily time zone current system even past i sure simple way i would expect python nothing seems i need right any ideas,3 if writing java c would implement functions static methods in languages methods part class due design language in python whilst emulate static method absolutely need example python creator guido van rossum argued favour use functions rather methods first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix — prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something isn’t file write method saying thing another way i see ‘len‘ builtin operation i’d hate lose … whilst directly related question challenge sometimes dogmatic stance methods always preferred functions in opinion python using functions better solution creating classes,this really languagespecific i use python explain question my program several nearly selfcontained functions the command line arguments select one functions provide input file name the function executed mainpy import functions def main filename sysargv functionname sysargv function getattrfunctions functionname result functionfilename something result functionpy contains functions def functionfilename i feeling i probably use classes rather functions i wrapped function class but class looks pretty silly instantiated execute constructor exactly old functions then i call certain method retrieve return value new version mainpy import classes def main filename sysargv clsname sysargv cls getattrclasses clsname calculation clsfilename result calculationresult something result classespy import functions class class def initself filename selfresult functionsfunctionfilename def resultself return selfresult functionspy unchanged this seem better i functions is way make code objectoriented useful way,2 there nothing wrong global functions code needed when functions require class normally related class called methods there need add complexity nesting function within class not python anyway,this really languagespecific i use python explain question my program several nearly selfcontained functions the command line arguments select one functions provide input file name the function executed mainpy import functions def main filename sysargv functionname sysargv function getattrfunctions functionname result functionfilename something result functionpy contains functions def functionfilename i feeling i probably use classes rather functions i wrapped function class but class looks pretty silly instantiated execute constructor exactly old functions then i call certain method retrieve return value new version mainpy import classes def main filename sysargv clsname sysargv cls getattrclasses clsname calculation clsfilename result calculationresult something result classespy import functions class class def initself filename selfresult functionsfunctionfilename def resultself return selfresult functionspy unchanged this seem better i functions is way make code objectoriented useful way,1 you printing returned list value python formats brackets quotes to print first element list print lookupgetkey to print elements list separated commas print joinstrx x lookupgetkey print joinmapstr lookupgetkey,sorry already mentioned somewherei find i basically want list item list including quotes bracketswhich i want here data inputdata red blue green organge here class find items either based key value class lookupdict dictionary lookup value key keys value def initself items items list pairlists dictionary dictinitself items def getkeyself value find keys list given value return item item selfitems item value def getvalueself key find value given key return selfkey works fine except brackets print lookupgetkey blue i want output blue i know i via replacing bracketquotes lookupvariablereplace i wondering pythonic way thanks,2 change return item item selfitems item value return nextitem item selfitems item value right returning result list comprehension list instead want return first item returned equivalent generator expression next edit if actually want multiple items use greg answer sounds like thinking getting single key good way if want raise stopiteration error value exist leave if want return something else instead like none return nextitem item selfitems item value none,sorry already mentioned somewherei find i basically want list item list including quotes bracketswhich i want here data inputdata red blue green organge here class find items either based key value class lookupdict dictionary lookup value key keys value def initself items items list pairlists dictionary dictinitself items def getkeyself value find keys list given value return item item selfitems item value def getvalueself key find value given key return selfkey works fine except brackets print lookupgetkey blue i want output blue i know i via replacing bracketquotes lookupvariablereplace i wondering pythonic way thanks,2 if need specify value single define cppdefines must dictionary from scons user manual if cppdefines dictionary values cppdefprefix cppdefsuffix construction variables appended beginning end item dictionary the key dictionary item name defined dictionary item corresponding value value none name defined without explicit value for example i suggest envappendcppdefines blub none value none foo envappendcppdefines blub none value none sometime later envappendcppdefines foo,i like set compiler defines dblub well dfoo currently i envappendcppdefines blub value i would like include third define via foo thus use cppdefines dictionary i later test quite easy envcppdefinesgetfoo everything i attempted leads syntax errors strange errors could one explain strange ways python,2 let look specific case modeling you want associate function several functions string name gets passed sysargv in python convenient way make association strings dict your code might look bit like mainpy import functions functionmap function functionsfunction function functionsfunction function functionsfunction def main filename sysargv result functionmapsysargvfilename something result functionpy contains functions def functionfilename ok enough get rid getattr maybe little some functions probably code common i bet try open file although may now getting closer something might use classes you still treat objects way regular functions defining call method class openfilefunctorobject def initself mode rb selfmode mode def callself filename stuff selffoo filename return openfilename selfmoderead alternately might much say function body you use lambda expression shorten function entry dict mainpy import functions import os functionmap function functionsfunction slurpunviersal functionsopenfilefunctor ru istextfile lambda fn fnlowerendswithtxt ospathisfilefn,this really languagespecific i use python explain question my program several nearly selfcontained functions the command line arguments select one functions provide input file name the function executed mainpy import functions def main filename sysargv functionname sysargv function getattrfunctions functionname result functionfilename something result functionpy contains functions def functionfilename i feeling i probably use classes rather functions i wrapped function class but class looks pretty silly instantiated execute constructor exactly old functions then i call certain method retrieve return value new version mainpy import classes def main filename sysargv clsname sysargv cls getattrclasses clsname calculation clsfilename result calculationresult something result classespy import functions class class def initself filename selfresult functionsfunctionfilename def resultself return selfresult functionspy unchanged this seem better i functions is way make code objectoriented useful way,1 the default settings likely bind localhost publicly available if want cherrypy run public interface direct from discussion i found cherrypyconfigupdate serversockethost pub ip cherrypyquickstart cherrypyconfigupdate serversockethost cherrypyquickstart to bind interfaces,i created python web app using cherrypy deployed local machine when i try view another computer house nothing comes back however i create simple html file deploy python simplehttpserver it visible intranet i stumped app could work locally avalable intranet given connection problem machines i serve content port i used configuration file i using default cherrypy settings,3 this one solved the trouble request get post thus query parameters passed url instead passed post data so case get friends code would look something like url httpsgraphfacebookcommefriends params accesstoken valid accesstoken fields idnamebirthday try con urlliburlopen url urlliburlencodeparams print conread except exception excp print excp hope helps someone,i following code urllib prints http error forbidden i use urllib instead fetch url i see error i get list friends the access token used cases url httpsgraphfacebookcommefriends params accesstoken valid accesstoken fields idnamebirthday req urllibrequesturl dataurlliburlencodeparams try con urlliburlopen req print conread except exception excp print excpread please suggest might wrong,3 if create string unicode object able break character time automatically eg python uabcuacuufffd note u front c print ux ordc i received u u u uac u ufffd python abcuacuufffd c print ux ordc it worked u u u uac u ufffd additionally i found link explains behavior working correctly if string came file etc likely need decoded first update i found insightful explanation the internal unicode representation size compiletime option working wide chars outside bit plane need build python remove limitation use one workarounds page apparently many linux distros already i encountered,i need step python string one character time simple loop gives utf code units instead str abcuacuufffd ch str code ordch printuxformatcode that prints u u u uac ud udf udbff udffd i wanted u u u uac u ufffd is way get python give sequence unicode code points regardless string actually encoded hood i testing windows i need code work anywhere it needs work python i care python x the best i able come far import codecs str abcuacuufffd bytestr codecsgetencoderutfbestr range lenbytestr code b bytestrii code code b printuxformatcode but i hoping simpler way pedantic nitpicking precise unicode terminology ruthlessly beaten head cluebyfour i think i made clear i please waste space utf technically unicode kind arguments,2 you added b c module c module when inside module see added b c added sysmodules imported sys using sysmodules b,i following use case apy import b import c cfun bpy def fun print b cpy def fun bfun python apy work it fails nameerror global name b defined my understanding import python name added sysmodules if case cpy also see module b but apparently case so anyone explain exactly happens module imported thanks,1 the module cpy import b order get working when importing module added globalsdictionary available current script scope use globals print content,i following use case apy import b import c cfun bpy def fun print b cpy def fun bfun python apy work it fails nameerror global name b defined my understanding import python name added sysmodules if case cpy also see module b but apparently case so anyone explain exactly happens module imported thanks,2 working code googleappengineext import db class modulenamedbmodel id dbstringproperty id dbstringproperty id dbdateproperty property dbstringproperty createdate dbdatepropertyautonowaddtrue changedate dbdatepropertyautonowaddtrue isactive dbbooleanproperty modulename plist mproperties p plist print p strplistp thanks clues daniel roseman nick johnson,is possible detect type model property class modulenamedbmodel id dbstringproperty id dbstringproperty id dbstringproperty property dbstringproperty property dbstringproperty createdate dbdatepropertyautonowaddtrue changedate dbdatepropertyautonowaddtrue isactive dbbooleanproperty how i test id int float string i learned far model method called allpropertie returns list properties i created model now i want check property type i make form automatically te correct html input types i change property type html change automatically does make sense i far track michael,1 on python narrow unicode build pythonwin default jul msc v bit intel win portions copyright mark hammond see helpabout pythonwin copyright information import sys sysmaxunicode what discovered utf encoding abcuacuufffd lens c print ux formatordc u u u uac ud udf udbff udffd a way around import struct ssencode utfbe structunpack l formatlenss structunpack l formatlenss print ux formati u u u uac u ufffd update python now works way op expects abcuacuufffd lens c print ux formatordc u u u uac u ufffd,i need step python string one character time simple loop gives utf code units instead str abcuacuufffd ch str code ordch printuxformatcode that prints u u u uac ud udf udbff udffd i wanted u u u uac u ufffd is way get python give sequence unicode code points regardless string actually encoded hood i testing windows i need code work anywhere it needs work python i care python x the best i able come far import codecs str abcuacuufffd bytestr codecsgetencoderutfbestr range lenbytestr code b bytestrii code code b printuxformatcode but i hoping simpler way pedantic nitpicking precise unicode terminology ruthlessly beaten head cluebyfour i think i made clear i please waste space utf technically unicode kind arguments,3 model class names singular this read much better python you associated database table different name using class meta inside model class also default manager objects object you need go trouble django take care mapping ids it creates reverse field destination model foreignkey the name reverse connection name model foreignkey plus set so case employees autogenerated field named expensesset acts manager containing employee expenses the manager methods create delete well so example newexpense employeeobjectsgetname john doe expensesetcreatefoo bar though better keep tabs employee object employee employeeobjectsgetname john doe newexpense employeeexpensesetcreatefoo bar no spaces around used parameter lists note need set employee id way that said us provide foreignkey better name reverse link using relatedname parameter class expensesmodelsmodel employee modelsforeignkeyemployees relatedname expenses employee employeeobjectsgetname john doe newexpense employeeexpensescreatefoo bar btw want get expenses employee three ways one like employee employeeobjectsgetname john doe employeeexpenses employeeexpensesall or oneliner employeeexpenses employeeobjectsgetname john doe expensesall there also employeeexpenses expenseobjectsfilteremployeenamejohn doe the says dereference foreignkey get fields the first way two queries others one get intermediate employee object use later,i new programming databases i question foreignkeys django say i model called expenses foreignkey pointed employees model class employeesmodelsmodel class expensesmodelsmodel employee modelsforeignkeyemployees i see foreignkey field employee id so question practice i employee name accessible form i would get employee id employees table name insert employee id foreign key expenses table like empid employeesobjectgetname john doe newexpense expensesfoo bar employeeid empidemployeeid newexpensessave am i right if correct way,1 characters beyond sysmaxunicode stored internally using utf surrogates yes deal use wide build even wide build also may deal single characters represented combination code points for example print au ã¡ print xe ã¡ the first uses combining accent character second both print you use unicodedatanormalize convert forms,cpython stores unicode strings either utf utf internally depending compile options in utf builds python string slicing iteration len seem work code units code points multibyte characters behave strangely eg cpython sysmaxunicode char u ude lenchar char u uu char u udce according python documentation sysmaxunicode an integer giving largest supported code point unicode character does mean unicode operations guranteed work code points beyond sysmaxunicode if i want work characters outside bmp i either use utf build write portable unicode operations i came across problem how iterate unicode characters python,2 your method workerthreadrun launches subprocess terminates immediately run needs perform polling update workerthreadcompleted subprocess completes,i script workerpy prints unbuffered output form n n constant number iterations loop script make in another script servicecontrollerpy i start number threads starts subprocess using subprocesspopenstdoutsubprocesspipe now main thread servicecontrollerpy i want read output thread workerpy subprocess use calculate estimate time remaining till completion i logic working reads stdout workerpy determines last printed number the problem i figure nonblocking way if i read constant bufsize read end waiting data workers i tried numerous ways including using fcntl select osread etc what best option i post source needed i figured explanation describes problem well enough thanks help edit adding sample code i worker starts subprocess class workerthreadthreadingthread def initself selfcompleted selfprocess none selflock threadingrlock threadingthreadinitself def runself cmd pathtoscript arg arg selfprocess subprocesspopencmd stdoutsubprocesspipe bufsize shellfalse flags fcntlfcntlselfprocessstdout fcntlfgetfl fcntlfcntlselfprocessstdoutfileno fcntlfsetfl flags osononblock def getcompletedself selflockacquire fd selectselectselfprocessstdoutfileno fd selfdata osreadfd try selfcompleted intselfdatasplitn except indexerror pass selflockrelease return selfcompleted i threadmanager class threadmanager def initself selfpool selfrunning selflock threadinglock def cleanpoolself pool worker x x pool xisalive workerjoin poolremoveworker del worker return pool def runself concurrent lenselfrunning lenselfpool selfcleanpoolselfrunning n minmaxconcurrent lenselfrunning lenselfpool n worker selfpooln workerstart selfrunningextendselfpooln del selfpooln timesleep worker selfrunning selfpool workerjoin code run threadmanager threadmanager xrange threadmanagerpoolappendworkerthread threadmanagerrun i stripped log code hopes try pinpoint issue,1 use loginrequired decorator view functions httpsdocsdjangoprojectcomentopicsauthdjangocontribauthdecoratorsloginrequired djangocontribauthdecorators import loginrequired loginrequired def myviewrequest it default redirect users loginurl defined settingspy example here simple example happens user perspective use loginrequired decorator the user types browser url httplocalhostmyview this url view loginrequired user redirect login page httplocalhostloginnextmyview after user logins heshe redirected automatically myview,user getting chance login it redirects page getting error page found request method get request url httppkinvalid using urlconf defined namekeeprurls django tried url patterns order the current url pkinvalid match this viewspy file login page def loginrequest username requestpostget username password requestpostget password user authenticateusernameusername passwordpassword user none userisactive correct password user marked active authloginrequest user redirect success page return httpresponseredirectpkloggedin else show error page return httpresponseredirectpkinvalid,1 assignments functions assigned functions local scope setname assigns name local scope setname outer name unaffected in python x possible assign module global scope using global statement outer local scope python x adds nonlocal statement see pep details interested in example nonlocal could used setname assign outer local scope this blog post discusses variable scoping python nice examples workarounds see example specifically,python script def showname     def getname         return name     def setnamevalue      name value     name     print input parameter name     print global variable sayhello     print change private variable setnamename     print get private variable getname     print private variable name     print input parameter name sayhello hello show jim output input parameter jim global variable hello change private variable none get private variable private variable input parameter jim why doesn’t inner function change value name yet function show get value sayhello i know variable scope problem i want know detail,1 you could either make one class instantiate class aobject def initself selfb bself class bobject def initself selfa a b ab or make one class tell like class aobject def initself b selfb b ba self class bobject def initself will set a later selfa none b b ab,i two classes class aobject def initself b self b b class bobject def initself self i like init like ab b ba but i since b exist ab i a b ba ba but seems unclean is solvable,2 you need threads either client server instead select multiplex io inside single thread,i trying figure make server accept multiple clients one time while i need client able send receive data server time would make threaded server and thread listening data and another thread sending information client then client side need use threads sendget info,1 use deferreds perform calculation asynchronously other way long calculation separate thread started lets say deferrtothread use reactorcallfromthread i assume heavy calculation main loop wrong little example def somelongfoodataarray protocol def sendmsgmsg protocol it actually looks petter classes without pushing protocol protocoltransportwritemsg n chunk enumeratedataarray dosomethingcoolchunk n n twistedinternet import reactor sendmsg safely executed main reactor loop reactorcallfromthreadsendmsg chunks processed protocol somwhere linereceived start long calculation def cbresult selftransportwrite got result formatresult threadsdefertothreadsomelongfoo dataarray self daddcallbackcb thus notify client processing every chunks data finally send result code may little incorrect eg docs upd clarification missed sendline part generally matter call insted transportwrite,i server twisted implementing linereceiver protocol when i call sendline response client message writes line client immediately one would expect but say client asks server lengthy calculation i want server periodically send progress message client when server takes initiative calls sendline without client asked anything seems wait client send message server sending anything how i send message server client immediately without client explicitly ask,1 greedy resubrecompile redotall text even shorter resub text,i want delete comment this regular expression resubrecompile redotall text but text bzzzzzz blabla blibli bloblo blublu result bzzzzzz blublu instead bzzzzzz blibli blublu thanks help,3 i suggest use regex kind stuff there always better solution lxmlhtmlclean your example import lxmlhtmlclean clean cleaner cleancleanercommentstrue cleanercleanhtmlbzzzzzz blabla blibli bloblo blublu bzzzzzz blibli blublu,i want delete comment this regular expression resubrecompile redotall text but text bzzzzzz blabla blibli bloblo blublu result bzzzzzz blublu instead bzzzzzz blibli blublu thanks help,3 you could use slicing hstack in testex nphstacktesttest in testshape out in testexshape out note indexing one test and would delete two elements instead one,i trying remove observation array via indexing what i import numpy np test npones what i want return array test removed th observation ie test and is simple way,1 what problem if eg hgrev variable settings module access rest code via djangoconfsettings proxy like setting if want expose every template easiest way write context processor,i like use working directory mercurial version info within django app by version info i really mean changeset branch tag are plugins techniques i got one way implemented settingspy i found way i like make data available code templates any ideas i aware related techniques write version info file template i looking instead i want version info variable within django app environment ubuntu virtualenv python django mercurial x thanks,1 numpy delete see httpdocsscipyorgdocnumpyreferencegeneratednumpydeletehtml in case numpydeletetest axis but elements deleted place function returns new array without th column,i trying remove observation array via indexing what i import numpy np test npones what i want return array test removed th observation ie test and is simple way,1 you use gstdebuglevel probe problem lets say code file gsttestpy launch like python gsttestpy gstdebuglevel this give better idea whats going try changing value lower noise my gut feeling missing caps you also probably set props,i trying setup gstreamer appsrc video source even trivial program work produces random crashes hangings far could please help spot problem minimal crashing code import gst gtk def needdatasrc needbytes srcemitpushbuffer gstbuffer needbytes def onmessagebus msg print onmessage msg pipeline gstparselaunchappsrc namesrc fakesink src pipelinegetbynamesrc srcconnectneeddata needdata srcsetpropertyblocksize bus pipelinegetbus busaddsignalwatch busconnectmessage onmessage pipelinesetstategststateplaying gtkmain,1 i approach like first get dictionary like file file file file file file then loop file generating sets file etc the compare values sets valfile valfile set file file etc this probably fastest mot elegant solution work,i trying parse large amount configuration files group results separate groups based content i know approach for example say i following data files configtxt ntp ntp configtxt ntp configtxt ntp ntp configtxt ntp the results would sets unique data set configtxt configtxt set configtxt set configtxt i understand glob directory files loop glob results open file time use regex match line the part i understand i could store results compare file set result even entries order match entry wise any help would appreciated thanks,1 collections import defaultdict load data paths configtxt configtxt configtxt configtxt files path paths openpath file line filereadlines get data files filespath frozensetdata example data files configtxt frozenset configtxt frozenset configtxt frozenset configtxt frozenset sets defaultdictlist key value filesitems setsvalueappendkey note need use frozensets immutable hence used dictionary keys as going change fine,i trying parse large amount configuration files group results separate groups based content i know approach for example say i following data files configtxt ntp ntp configtxt ntp configtxt ntp ntp configtxt ntp the results would sets unique data set configtxt configtxt set configtxt set configtxt i understand glob directory files loop glob results open file time use regex match line the part i understand i could store results compare file set result even entries order match entry wise any help would appreciated thanks,1 ethan fakemodule likely better accomplished plain old python just move code directory setup mymodule initpy apipy utilpy mymodulepy where mymodulepy contains current code in initpy mymodule import in apipy explicity import api classes want expose allow call mymoduleapi import import mymodule apiclass import mymodule apiclass etc do utilpy explicity import util classes want expose allow call mymoduleutil import import mymodule utilclass import mymodule utilclass etc so import everything willy nilly help mymodule import import public values api util mymoduleapi import mymoduleutil import breaking code like useful organizing largish module still want able access top level namespace but i would agree brandizzi using mymodule import code using module generally bad idea what gain ease importing lose transparency code using imports,i module split roughly half utility type functions core api functions i need order help useful also specify many functionsclassesetc module external use i also want support mymodule import way get core functionality modules is way,2 filenames r configtxt r configtxt r configtxt r configtxt results filename filenames openfilename r f contents linesplit line f key frozensetcontents resultssetdefaultkey appendfilename,i trying parse large amount configuration files group results separate groups based content i know approach for example say i following data files configtxt ntp ntp configtxt ntp configtxt ntp ntp configtxt ntp the results would sets unique data set configtxt configtxt set configtxt set configtxt i understand glob directory files loop glob results open file time use regex match line the part i understand i could store results compare file set result even entries order match entry wise any help would appreciated thanks,1 you need dictionary mapping contents files filename so read file sort entries build tuple use key if duplicate entries file read contents set first,i trying parse large amount configuration files group results separate groups based content i know approach for example say i following data files configtxt ntp ntp configtxt ntp configtxt ntp ntp configtxt ntp the results would sets unique data set configtxt configtxt set configtxt set configtxt i understand glob directory files loop glob results open file time use regex match line the part i understand i could store results compare file set result even entries order match entry wise any help would appreciated thanks,1 this alternative verbose others may efficient depending couple factors see notes end unless processing large number files large number configuration items i even consider using suggestions performance issue algorithm might help start dictionary configuration strings file set call cf file configuration strings set fc both built glob files to clear cf dictionary keys strings values sets files fc dictionary keys files values sets strings loop file keys fc one data item use cf find files contain item those files need compare here working code structure simulates files system contents cfgdata configtxt configtxt configtxt configtxt build dictionaries on lines configuration data fc dict cf dict file data cfgdataiteritems dataset set item data datasetadditem item cf cfitem set cfitemaddfile fcfile dataset build results list pairs lists results track processed files processed set file data fciteritems file processed continue size lendata equivalencelist get one item data preferably one used smallest list files item none itemfiles data item none item itemfiles lencfitem elif lencfi itemfiles item itemfiles lencfi all files data f must least first item data look files otherfile cfitem otherdata fcotherfile otherdata data equivalencelistappendotherfile no need visit files processedaddotherfile resultsappenddata equivalencelist display results data files results print data files adding note computational complexity this technically ok log nl log m n number files m number unique configuration items k n number groups files content l m average number files compared pairwise l processed files this efficient k n l m,i trying parse large amount configuration files group results separate groups based content i know approach for example say i following data files configtxt ntp ntp configtxt ntp configtxt ntp ntp configtxt ntp the results would sets unique data set configtxt configtxt set configtxt set configtxt i understand glob directory files loop glob results open file time use regex match line the part i understand i could store results compare file set result even entries order match entry wise any help would appreciated thanks,1 i run code i suspect part alternative regexp matches nonempty string starting space case message,i trying create svn precommit hook get regular expression work expected it print false messages look like dev message why i get true python r apr gcc linux type help copyright credits license information import p recompileaz redotall message test message match psearchmessage boolmatch true,1 p recompileaz redotall print psearchtest message none print psearchdev message sresrematch object xebb need need escape,i trying create svn precommit hook get regular expression work expected it print false messages look like dev message why i get true python r apr gcc linux type help copyright credits license information import p recompileaz redotall message test message match psearchmessage boolmatch true,3 the culprit trailing matching message alternative first regex as roman pointed meant match literal escape to see matched print matchgroup message by way faster nonregex way handle lines containing vertical bar would use linesplit line parts linesplit lenparts continue codemesg parts,i trying create svn precommit hook get regular expression work expected it print false messages look like dev message why i get true python r apr gcc linux type help copyright credits license information import p recompileaz redotall message test message match psearchmessage boolmatch true,2 the code kill ichat oriented programs p subprocesspopen pgrep l ichat stdoutsubprocesspipe err pcommunicate line outsplitlines line bytesdecodeline pid intlinesplitnone oskillpid signalsigkill,i trying kill process specifically ichat on command line i use commands ps a grep ichat then kill pid however i exactly sure translate commands python,1 you could try base encoding order serialize image used inside json,i trying serialize one models imagefield the inbuilt serializer seem serialize therefore i thought writing custom serializer could tell i could serialize image use default json serializer django thanks,1 i know django but could way class wantfixupobject def newinstanceself name derivedname cls typeself name none name derivednamereplace return clsname class containerwantfixup def initself namenone selfname name def reprself return container strselfname class willfixupobject def initself cls typeself name clsdict clsdictname look object name isinstanceo wantfixup continue printcalling snewinstance oname name selfdictname onewinstanceoname name class namewillfixup firstname containergiven name lastname container here example code action import autoname n autonamename calling container none newinstance none lastname calling container given name newinstance given name firstname printndict firstname container given name lastname container last name printautonamenamedict module autoname lastname container none firstname container given name doc none the class wantfixup serves two purposes first classes inherit detected using isinstance object instance named test like isinstanceo wantfixup second provided newinstance method function class inherits the class container example container might need fixup note inherits wantfixup the class willfixup contains init method performs fixup classes inherit this simply loops everything class dictionary calls newinstance method function one passing name finally class name inherits willfixup contains two instances container because inherits willfixup method willfixupinit called as see example firstname name attribute set given name lastname set patched name attribute set last name the init function supposed set new class instance as long special wantfixup class instances parent class init method automatically loop set the confusing part instance firstname set instance container name patched actually used store stuff but class name contains instance container used store name class marker init method find the good part magic hidden away base classes the container name classes need inherit cluttered stuff there might slicker way solve problem using metaprogramming httpwwwibmcomdeveloperworkslinuxlibrarylpymetaindexhtml this solution metaclass programming tested working code edit this changed version code the original code intended show general idea actually init name object it hard actually init i changed,see update i even know make short title problem in class i class attributes stringfield class class authorstable id field already present firstname stringfieldmaxlength lastname stringfieldmaxlength stringfield constructor may receive argument called name if given want equal class attribute name firstname lastname example is possible extract name variable created instance going assigned i guess use inspect module i see django each field type except foreignkey manytomanyfield onetoonefield takes optional first positional argument verbose name if verbose name given django automatically create using field attribute name converting underscores spaces in example verbose name person first name firstname modelscharfieldperson first name maxlength in example verbose name first name firstname modelscharfieldmaxlength but find django source code part need update to simplify class field def initself fieldnamenone fieldname fieldname magic determine name printfieldname class table firstname field lastname field running print firstname lastname solution class field def initself namenone selfname name class table firstname field lastname field attrname attr tabledictitems isinstanceattr field attrname none attrname attrname printtablefirstnamename printtablelastnamename,1 an alternative use masked arrays depending application improve speed delete entries andor create new ndarrays afaik pretty expensive operations numpy an example import numpy np test npones mask npzeros mask result npmamaskedarraytest mask the fifth element masked away various operations performed result like methods sum mean more info link i gave if want real ndarray call resultcompressed however perform expensive work allocating new memory copying data masked arrays might benefit particular problem good know exist,i trying remove observation array via indexing what i import numpy np test npones what i want return array test removed th observation ie test and is simple way,1 you misunderstanding f means it means give float columns total display positions radix point perhaps want f instead,i formatting floats follows logfilewriteloadcase f f f f freq amp cutoff endtime penaltyinc stabinc result like loadcase ok loadcase ok loadcase ok loadcase ok loadcase ok i simply want floats right aligned spaces inserted necessary i really basically want table nicely aligned my guess writing f seems ignored i cannot use numpy technical reasons,3 the syntax fieldwidth precision conversiontype so want leave space show decimals try f see python documentation full overview,i formatting floats follows logfilewriteloadcase f f f f freq amp cutoff endtime penaltyinc stabinc result like loadcase ok loadcase ok loadcase ok loadcase ok loadcase ok i simply want floats right aligned spaces inserted necessary i really basically want table nicely aligned my guess writing f seems ignored i cannot use numpy technical reasons,1 chameleon included two babel extraction plugins one python code one xml files pyramid documentation referring chameleon longer includes plugins focuses core functionality template library these two plugins cleaned included new lingua package the pyramid documentation updated reflect since pyramid see pyramid chapter the lingua xml plugin uses expat parse input indeed fail html files use xml notation since i personally feel quite strongly xml notation much better choice i likely chance lingua implementation support nonxml syntax there one exception lingua allow missing namespace declaration,does pyramid pt files support html markup currently tag extractor babel seems want xhtml based input accept html markup thus want use pt files forced write xml ish way,1 you want use csvreader csvexceltab dialect examples csv usage,i problem reading ascii file python here example file httppastebincomctwwppka i tried using numpy genfromtxt data npgenfromtxtexampletxt but way i cannot read dates times properly since datetime objects on hand loadtxt read float values also acceptable could please suggest way properly read kind file,1 you could look script update po files new code it use xgettext msgmerge echo messagespo xgettext needs file need empty find type f iname py xgettext j f msgmerge n existingpo messagespo newpo mv newpo existingpo rm messagespo,i got python project internationalized strings i modified source codes lines strings changed ie pot po files lines strings pointing correct lines so update po pot files new string locations files,3 the format string f says format digits radix point use least characters full string so f f f in case set high enough,i formatting floats follows logfilewriteloadcase f f f f freq amp cutoff endtime penaltyinc stabinc result like loadcase ok loadcase ok loadcase ok loadcase ok loadcase ok i simply want floats right aligned spaces inserted necessary i really basically want table nicely aligned my guess writing f seems ignored i cannot use numpy technical reasons,1 the parameter passed slot function must string types parameters direct call connect slot parameters signal without parameter you use lambda function instead qtcoreqtimersingleshot lambda selfrecallarg,i strange problem here code def methodself arg delaytrue this method class def recallarg selfmethodarg delayfalse return delay print a arg typearg qtcoreqtimersingleshot self qtcoreslotrecallint arg return print b arg typearg so i get console a type int b type int type type in b get a anyone knows wrong how i get arg value instead type this making sense ps i trying something like httpliststrolltechcomqtinterestthreadhtml,3 use dtype option x npgenfromtxtexampletxt dtypenone printx get data the trick specify dtype none numpy automatically recognize strings numbers default dtype float then use datetimestrptime convert strings datetime objects accordingly,i problem reading ascii file python here example file httppastebincomctwwppka i tried using numpy genfromtxt data npgenfromtxtexampletxt but way i cannot read dates times properly since datetime objects on hand loadtxt read float values also acceptable could please suggest way properly read kind file,1 also add set default templates somewhere make usage registration vastly easier think ubernostrums google code last time needed,i directory django project localhost mydjangolist in folder i django application called pk i downloaded djangoregistration unzipped folder mydjangolist i went terminal went djangoregistration folder ran python setuppy install it bunch things spit following error could create usrlocallibpythondistpackagesregistration permission denied the install file says i put folder project i even need install if i properly install,1 how simplejsondumpspdict p listitervalues,i want serialize dictionary json python i str object attribute dict error here code djangoutils import simplejson class personobject person person persona person person persona list listfirst person listsecond person simplejsondumpspdict p list and exception traceback recent call last file basedatahomeappspyideonlineshellpy line post execcompiledcode globals file string line module attributeerror str object attribute dict,3 you using dictionary list list order code work change list eg list listappendperson listappendperson,i want serialize dictionary json python i str object attribute dict error here code djangoutils import simplejson class personobject person person persona person person persona list listfirst person listsecond person simplejsondumpspdict p list and exception traceback recent call last file basedatahomeappspyideonlineshellpy line post execcompiledcode globals file string line module attributeerror str object attribute dict,1 what think pdict p list since list list dictionary p list iterates key values dictionary the keys strings never use names like list dict variables and never lie data type your list variable dictionary call persondict happier,i want serialize dictionary json python i str object attribute dict error here code djangoutils import simplejson class personobject person person persona person person persona list listfirst person listsecond person simplejsondumpspdict p list and exception traceback recent call last file basedatahomeappspyideonlineshellpy line post execcompiledcode globals file string line module attributeerror str object attribute dict,2 your parse function seem belong spider class indent whole function one indention belongs class gets called,i started use scrapy ubuntu facing issue specifically parse function following code execute although terminal shows spider executed closed successfully scrapycontribspiders import crawlspider scrapyselector import htmlxpathselector class mytestspidercrawlspider namegomumbaicom domainname gomumbaicom starturls httpwwwgomumbaicommumbaibusroutephpbusno def parseself response hxs htmlxpathselectorresponse stopnameshxsselect tablecellspacingtrtdatext extract print lenstopnames spider mytestspider the following response terminal rupinrupinlaptopdesktopscrappytestbasetest sudo scrapy crawl gomumbaicom scrapy info scrapy started bot basetest scrapy debug enabled extensions telnetconsole spidercontext webservice corestats memoryusage closespider scrapy debug enabled scheduler middlewares duplicatesfiltermiddleware scrapy debug enabled downloader middlewares httpauthmiddleware downloadtimeoutmiddleware useragentmiddleware retrymiddleware defaultheadersmiddleware redirectmiddleware cookiesmiddleware httpcompressionmiddleware downloaderstats scrapy debug enabled spider middlewares httperrormiddleware offsitemiddleware referermiddleware urllengthmiddleware depthmiddleware scrapy debug enabled item pipelines scrapy debug telnet console listening scrapy debug web service listening gomumbaicom info spider opened gomumbaicom debug crawled get httpwwwgomumbaicommumbaibusroutephpbusno referer none gomumbaicom info closing spider finished gomumbaicom info spider closed finished is part code i missing please advise,1 python cleanedlist filterlambda x hasattrx video dirtylist django you could following dirtylist queryset cleanedlist dirtylistfiltervideoisnullfalse,is possible convert following list comprehension cleanedlist item dirtrylist try itemvideo except videodoesnotexist pass else cleanedlistappenditem,1 use itertoolsgroupby import itertools l lenlistg k kg itertoolsgroupbyl,i list like i want group find length groupso result like any help appreciatedthanks,3 in import itertools in sum gv vg itertoolsgroupbyl out where l input list,i list like i want group find length groupso result like any help appreciatedthanks,1 you add modules want use script other way pass module function argument call modules method the way add builtins better explain post,i following use case apy import b import c cfun bpy def fun print b cpy def fun bfun python apy work it fails nameerror global name b defined my understanding import python name added sysmodules if case cpy also see module b but apparently case so anyone explain exactly happens module imported thanks,1 the solution appeared quite simple at point program lucky spit fatal python error gc object already tracked message became pretty clear call gobjectthreadsinit missing adding call beginning program fixed issue,i trying setup gstreamer appsrc video source even trivial program work produces random crashes hangings far could please help spot problem minimal crashing code import gst gtk def needdatasrc needbytes srcemitpushbuffer gstbuffer needbytes def onmessagebus msg print onmessage msg pipeline gstparselaunchappsrc namesrc fakesink src pipelinegetbynamesrc srcconnectneeddata needdata srcsetpropertyblocksize bus pipelinegetbus busaddsignalwatch busconnectmessage onmessage pipelinesetstategststateplaying gtkmain,2 i novice comes regex take mgroups initially change whatever wish return variable say xlistmgroups note groups group x value else return x edit maybe i get trying achieve as mentioned comment change regex azazaz this basically help joining list mgroups,i following simplified code essence would like def replacetodom value else return mgroup i want edit specific group match object render whole match including edited part the replacetodo function gets called every match using mycompiledregexsubreplacetodo text the text used input mah lalalalalaa mah lalalalalaa expected output mah lalalalalaa mah lalalalalaa the regex looks like azazaz but seems allowed edit match object when try execute code get following typeerror sresrematchamp object support item assignment thanks advance edit using spicavigo solution converting list string strgroups looks u’ ’ ’ u’jsp’ u’do something’ look jsp something,1 at guess mean say vat purchasesvatvat,i seem problem multiplying django i want multiply total purchase including vat vat value unfortunately i got error unsupported operand types decimal vat it looks like program calls vat see views vat rather decimal i sure error unless another way around viewspy purchases purchaseobjectsall vat purchasesvat totalpurchases purchaseobjectsallaggregateprice sum amount totalpurchasesvat totalpurchases price vat modelspy class vatmodelsmodel vat modelsdecimalfieldmaxdigits decimalplaces def unicodeself return unicodeselfvat class purchasemodelsmodel vatperiod modelsforeignkeyvatperiod date modelsdatefield amount modelsdecimalfieldmaxdigits decimalplaces description modelstextfieldmaxlength vat modelsforeignkeyvat def unicodeself return unicodeselfamount,1 purchasesvat yields instance vat model you need use purchasesvatvat get actual value,i seem problem multiplying django i want multiply total purchase including vat vat value unfortunately i got error unsupported operand types decimal vat it looks like program calls vat see views vat rather decimal i sure error unless another way around viewspy purchases purchaseobjectsall vat purchasesvat totalpurchases purchaseobjectsallaggregateprice sum amount totalpurchasesvat totalpurchases price vat modelspy class vatmodelsmodel vat modelsdecimalfieldmaxdigits decimalplaces def unicodeself return unicodeselfvat class purchasemodelsmodel vatperiod modelsforeignkeyvatperiod date modelsdatefield amount modelsdecimalfieldmaxdigits decimalplaces description modelstextfieldmaxlength vat modelsforeignkeyvat def unicodeself return unicodeselfamount,2 this achieved defining parent parser containing common options parentparser argparseargumentparseraddhelpfalse parentparseraddargumentp typeint requiredtrue helpset db parameter parsercreate subparsersaddparsercreate parentsparentparser helpcreate orbix environment parserupdate subparsersaddparserupdate parentsparentparser helpupdate orbix environment,my script defines one main parser multiple subparsers i want apply p argument subparsers so far code looks like parser argparseargumentparserprogmyprog subparsers parseraddsubparserstitleactions parseraddargumentv verbose actionstoretrue destverbose helprun verbose mode parsercreate subparsersaddparser create help create orbix environment parsercreateaddargument p type int required true help set db parameter update parserupdate subparsersaddparser update help update orbix environment parserupdateaddargument p type int required true help set db parameter as see addarument p repeated twice i actually lot subparsers is way loop existing subparsers order avoid repetition for record i using python,3 could try booksobjectsallonly title author date extrawhere library is not null distinct,i query django resulting unique rows contain common values various fields i want consolidate rows common values example assume row returns id library book title author publication date i want know book title author publication date additionally i would like know one library found how using django,1 run code tt option find using tabs spaces inconsistently,how i rectify error unexpected indent python,3 are talking creating plugin system app the usual way directory somewhere designated plugins directory folders loaded plugins you could either hardcode path make configurable using application ui configuration file you manipulate python path runtime app include plugins directory the path available readwrite list syspath use siteaddsitedir,so i following situation i package generated pyapp this structure projects sources located distappcontentsresourceslibpythonmyproject now works fine however i want give possibility developers add code want so going trough folders every time seems rather ugly so i thinking i could try possible get myproject folder top level next distapp create link lib folder similar distutils python setuppy develop but i rather stuck so far i attempted unpackaged project do python setuppy develop project go python sitepackages copy myprojectegglink generated mentioned place edit path actual project accordingly copy myprojectegginfo generated next myproject folder this however seem work i also tried easiest solution i could create macos alias folder work either any suggestions regards bogdan,1 generally speaking convert oids symbolic names use mib viewer component when use pysnmp oneliner api conversion invoked implicitly input oidssymbols however needs performed explicitly output oids possibly values well see following example recipe httppysnmpsourceforgenetexamplesxvarchonelinermanagerwithmibnextgenhtml,i wrote script test well i could use pysnmp one applications i need able mibwalk network elements names like ifdescr output needs reference name i queried pysnmpsmi import builder view error pysnmpentityrfconeliner import cmdgen cmdgen cmdgencommandgenerator mibbuilder buildermibbuilder mibpath mibbuildergetmibpath optpythonmodelsnetworkmibs mibbuildersetmibpathmibpath mibbuilderloadmodules rfc mibview viewmibviewcontrollermibbuilder errorindication errorstatus errorindex varbindtable cmdgennextcmd snmp v cmdgencommunitydata testagent public transport cmdgenudptransporttarget ifdescr print varbindtable problem when i execute code pysnmp correctly recognizes ifdescr local definition rfcpy however pysnmp translating mib oids names like ifdescr output question how i make pysnmp output objectname instances objectnameifdescr instead objectname objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring unit slot port g level objectname octetstring cpu interface unit slot port objectname octetstring link aggregate objectname octetstring link aggregate objectname octetstring link aggregate objectname octetstring link aggregate objectname octetstring link aggregate objectname octetstring link aggregate objectname octetstring link aggregate objectname octetstring link aggregate objectname octetstring vl objectname octetstring vl update the explicit solution based popper answer import string pysnmpsmi import builder view error pysnmpentityrfconeliner import cmdgen collections import namedtuple nt cmdgen cmdgencommandgenerator mibbuilder buildermibbuilder mibpath mibbuildergetmibpath optpythonmodelsnetworkmibs mibbuildersetmibpathmibpath mibbuilderloadmodules rfc mibview viewmibviewcontrollermibbuilder errorindication errorstatus errorindex varbindtable cmdgennextcmd snmp v cmdgencommunitydata testagent public transport cmdgenudptransporttarget ifdescr snmpobject nt snmpobject modname symname index value errorindication print errorindication else errorstatus print sn errorstatusprettyprint varbindtableinterrorindex else varbindtablerow varbindtable oid val varbindtablerow symname modname indices cmdgenmibvaroidtomibname cmdgenmibviewcontroller oid val cmdgenmibvarclonefrommibvalue cmdgenmibviewcontroller modname symname val index intstringjoinmaplambda v vprettyprint indices value valprettyprint print snmpobjectmakemodname symname index value when i run i get snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value unit slot port g level snmpobjectmodname rfcmib symname ifdescr index value cpu interface unit slot port snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value link aggregate snmpobjectmodname rfcmib symname ifdescr index value vl snmpobjectmodname rfcmib symname ifdescr index value vl this answer exact question objectname instances symbolic names however certainly good enough,1 python tools visual studio addin supports cpython ironpython,i would like know use visual studio cpython official pythonorg python interpreter ironpython in particular i interested getting build run commands visual studio working other features color highlighting autocomplete i less concerned also build command made run pyexe similar exe packagers,2 the cleanest way i know use typesstringtypes confused typesstringtype isinstancevar typesstringtypes alternatively isinstancevar basestring documentation types module indicates latter preferred way recent versions python x,i following code def printmylist mylist print tree try f mylist printmylist f except print mylist hoping get output like root branch leaf leaf since string enumerable i get r checking type seems unpythonic would pythonian go,3 the invisble widget idea works but gtkinvisible crashes gtkhbox thing seems empty selfnotebookappendpagegtkhbox gtklabeltitle now i want display stuff inside tab actually i use reparent move widget current tab like class tabgtkhbox def initself child selfchild child selfnotebookappendpagetabmywidget gtklabeltitle def pageselectedself notebook page pagenum box notebookgetnthpagepagenum boxchildreparentbox,i facing problem need tabs pygtk app pretty much like gedit without perchild widget content i’ve come across gtknotebook requires put widget tab i want the reason i one widget would like updates content based tab selected any hints my idea far would add invisible widget tab connect selectpage signal which widget could i use invisible widget betteralternative way achieving goal,1 i use following pythonic approach problem no isinstance calls required therefore even works various custom c string classes i wrapped python i think isinstance based methods would work cases plus op explicitly asked solution involve type checking pythonistas check behavior type the trick involves observation strings unusual property first element onecharacter string onecharacter string f f this works python x def isstrings try return true except pass return false,i following code def printmylist mylist print tree try f mylist printmylist f except print mylist hoping get output like root branch leaf leaf since string enumerable i get r checking type seems unpythonic would pythonian go,1 use python struct module structunpack translate hex string messagequeuereceive tuple strings,i using philip semanchunk posixipc python module read posix message queue a c program i written populates queue struct containing data my python program successfully reads message queue i sure resulting message print msg prints empty string i know msg something i want able read members struct i assuming i need something maybe struct module marshal message something readable has anyone done anything like i read documentation demos using simple types i found examples source c struct google help either also i restricted using python thanks,1 not programmer answer instead paramiko mount directory documents sshfs serve documents local file system httpfusesourceforgenetsshfshtml,ssh server use store files online need make file available download easily using paramiko library connect ssh server python script lists files displays webpage problem dont want download files web server disk dont enough space send clients instead something like read file spit like done php something like python php file upload file salaryreportpdf headerexpires headerlastmodified gmdated m y his gmt headercachecontrol nostore nocache mustrevalidate headercachecontrol postcheck precheck false headerpragma nocache headercontenttype applicationpdf tell file size header contentlength filesizefile set file name header contentdisposition attachment filename basenamefile readfilefile exit script so useless data outputed exit,1 your problem seems related tutorial error report from report alone guess problem line transport tsockettserversocketport when calling tsockettserversocket single argument value treated host identifier hence error getaddrinfo to fix change line transport tsockettserversocketportport,hi i trying write simple thrift server python named pythonserverpy single method returns string learning purposes the server code i following errors thrift python libraries i run server has anyone experienced problem suggest workaround the execution output starting server traceback recent call last file homedaeworkspacebasictestenvironmentvsrcpythonserverpy line module serverserve file usrlibpythonsitepackagesthriftservertserverpy line serve file usrlibpythonsitepackagesthrifttransporttsocketpy line listen file usrlibpythonsitepackagesthrifttransporttsocketpy line resolveaddr typeerror getaddrinfo argument must string none pythonserverjava port import myservice myserv ttypes import thrift files thrifttransport import tsocket thrifttransport import ttransport thriftprotocol import tbinaryprotocol thriftserver import tserver server implementation class myhandler return server message def sendmessageself text print text return in garage set handler implementation handler myhandler processor myservprocessorhandler transport tsockettserversocketport tfactory ttransporttbufferedtransportfactory pfactory tbinaryprotocoltbinaryprotocolfactory set server server tservertthreadedserverprocessor transport tfactory pfactory print starting server serverserve line goes here,3 stat first mode osstatfilenamestmode oschmodfilename mode statsixusr,i want set executable permissions file i created python if i oschmodfile statsixusr existing permissions overwritten how i combine existing permissions file executable permissions,3 it true proper way indicate error constructor raising exception that c objectoriented languages designed exception safety mind destructor called exception thrown constructor object meaning initialization object incomplete this often case scripting languages python for example following code throws attributeerror socketconnect fails class networkinterface def initself address selfsocket socketsocketsocketafinet socketsockstream selfsocketconnectaddress selfstream selfsocketmakefile def delself selfstreamclose selfsocketclose the reason destructor incomplete object called connection attempt failed stream attribute initialized you avoid throwing exceptions constructors i saying difficult write fully exception safe code python some python developers avoid using destructors altogether matter another debate,is considered bad form raise exceptions within init if accepted method throwing error certain class variables initialized none incorrect type,3 to answer question given twocolumn numpy array could b numpyarraydatetimedatetimestrptimes ymdhmsf since comments indicate original array constructed using genfromtxt probably better joining columns text file defining suitable converter see converters argument genfromtxt edit if columns types s s respectively indicated comments minor optimisation code since need explicitly join columns numpyarray dtype s s b numpyarraydatetimedatetimestrptimes ymdhmsf aviews the operation aviews cheap copy data if array really big optimisation might welcome though make huge difference,i numpy ndarray contains two columns one date eg another one time eg how i combine one array datetime objects currently strings numpy array,1 there several differences you append elements list change size â´numpyndarrayâ´ without making full copy lists containt everything numpy arrays elements must type in practice numpy arrays faster vectorial functions mapping functions lists i think modification times issue iteration elements numpy arrays many array related methods â´argminâ´ â´minâ´ â´sortâ´ etc i prefer use numpy arrays i need mathematical operations sum average array multiplication etc list i need iterate items strings files etc,what differences python numpyndarray list datatypes i vague ideas would like get definitive answer size memory speed order access speed order modification place preserving length effects changing length thanks,2 mysql insert elapse mongodb insert elapse mongodb much faster insert mongodb inserts much faster mongodb insert data ram periodically flush data disc mysql select elapse mongodb select elapse slower quering thought you achieve best performance mongodb embedddenormalize data in many situation mongodb allow us avoid joins embeddingdenormalization and inserting data one collectiontable reading back index mongodb supposed faster read speed compare sql database btw in mongodb indexes faster guess work faster mysql,i discovered mongodb months agoand reading post i thought mongodb really faster mysql i decided build bench problem i result post author especially quering database mongodb seems slower myisam tables could look python code may something wrong datetime import datetime import random import mysqldb import pymongo mysqldbmysqldbconnectusermepasswdmypasswddbtestkv cmysqldbcursor connection pymongoconnection mongodb connectiontest kvtab mongodbkvtab nb thelist xrangenb thelistappendstrrandomrandomstrrandomrandom tdatetimenow kv thelist cexecuteinsert into keyvaltab kv values k v dtdatetimenow print mysql insert elapse dt tdatetimenow xrangenb cexecuteselect from keyvaltab where k randomchoicethelist resultcfetchone dtdatetimenow print mysql select elapse dt tdatetimenow kv thelist kvtabinsertkeykvaluev dtdatetimenow print mongodb insert elapse dt kvtabensureindex key tdatetimenow xrangenb resultkvtabfindonekeyrandomchoicethelist dtdatetimenow print mongodb select elapse dt notes mysql mongodb locahost mysql mongodb key column indexed mysql table create table if not exists keyvaltab k varchar not null v varchar not null key kindex k enginemyisam default charsetlatin versions mysql mongodb python pymongo linux ubuntu bits pae hardware desktop core ghz results million insertsselects mysql insert elapse mysql select elapse mongodb insert elapse mongodb much faster insert mongodb select elapse slower quering thought opposite,3 you set enviromnet variable compatlayer process runasinvoker then run executable without uac prompt you use windows api function setenvironmentvariable purpose,i installer i like run script the installer requests uac elevation need elevation i installing user directory is way run installer request uac elevation the script written python i access windows api ctypes changing installer option,2 i made mods indentpythonvim enable full dedent third empty line entered you may able adapt needs diff git apythonvim bpythonvim index cecce apythonvim bpythonvim function getpythonindentlnum if recommend one dedent return indentplnum ampsw endif otherwise trust user return is user trying break function plnum alnum return else otherwise trust user return endif endif if current line begins keyword lines try function getpythonindentlnum return plindent endif double linebreaks means starting new function probably plnum alnum return endif return endfunction,it could useful vim could unindentation automatically i type empty line seems default behavior this would especially useful python could vim configured,1 if date time string exampletxt data file given one column separating whitespace genfromtxt could convert datetime object like import numpy np import datetime dt def mkdatetext return dtdatetimestrptimetext ymdthmsf data npgenfromtxt exampletxt names data num date tuple coli formatii range converters date mkdate dtypenone given exampletxt could form desired numpy array import numpy np import datetime dt import csv def mkdatetext return dtdatetimestrptimetext ymdhmsf def usingcsvfname desc data s num date o coli formatii f range openfname r f readercsvreaderfdelimiter datanparraytuplerowmkdate joinrowrow row reader dtypedesc printmcreportmemory return data merging two columns numpy array slow operation especially array large that merging like resizing requires allocating memory new array copying data original array new one so i think worth trying form correct numpy array directly instead stages forming partially correct array merging two columns by way i tested csv code versus merging two columns forming single array csv faster memory usage import matplotlibcbook mc import numpy np import datetime dt def usinggenfromtxtfname data npgenfromtxtfname dtypenone origdescdatadtypedescr viewdescorigdesc date s origdesc newdescorigdesc date o origdesc newdata npemptydatashape dtypenewdesc fieldsdatadtypenames fieldsfieldsfields field fields newdatafield datafield newdata date npvectorizemkdatedataviewviewdesc date printmcreportmemory return newdata usingcsv exampletxt usinggenfromtxt exampletxt exampletxt exampletxt duplicated times it k lines long python mtimeit import test testusinggenfromtxtexampletxt loops best sec per loop python mtimeit import test testusingcsvexampletxt loops best msec per loop,i numpy ndarray contains two columns one date eg another one time eg how i combine one array datetime objects currently strings numpy array,3 running regular expression means running state machine character doing split constant string means search string much less complicated procedure,in quests optimization i discovered builtin split method faster resplit equivalent a dummy benchmark easily copypasteable import time random def randomstringlen letters abc return joinlettersrandomrandintlenletters rangelen r randomstring pattern recompilera start timetime patternsplitr print resplit timetime start start timetime rsplita print builtin split timetime start why difference,1 resplit expected slower usage regular expressions incurs overhead of course splitting constant string point using resplit,in quests optimization i discovered builtin split method faster resplit equivalent a dummy benchmark easily copypasteable import time random def randomstringlen letters abc return joinlettersrandomrandintlenletters rangelen r randomstring pattern recompilera start timetime patternsplitr print resplit timetime start start timetime rsplita print builtin split timetime start why difference,3 sigh these kind benchmarks i use term loosely case usually break start mysql slower database mongodb one relational database nosql document store they willshould faster functional areas designed cover in case mysql rdbms mongodb overlap big lot people assume it kind broken apples oranges comparison get redis vs mongodb discussions there many variables app functional requirements hardware resources concurrency configuration scalability etc consider benchmark article ends mongodb faster mysql vice versa generalizing results point uselessness if want benchmark first define strict set functional requirements business rules implement efficiently possible persistence solutions the result one faster almost cases faster approach relevant downsides might still make slower solution viable depending requirements all ignoring benchmark simulate sort real world scenario there wont lot apps max throughput inserts without sort threadingconcurrency impacts performance storage solutions significantly finally comparing inserts like little broken mongodb achieve amazing insert throughput fire forget bulk inserts orders magnitude slower fsynced replicated writes the thing mongodb offers choice mysql less so comparison make sense business requirements allow fire forget type writes which boil i hope works biggy tldr stop simple throughput benchmarks they almost always useless,i discovered mongodb months agoand reading post i thought mongodb really faster mysql i decided build bench problem i result post author especially quering database mongodb seems slower myisam tables could look python code may something wrong datetime import datetime import random import mysqldb import pymongo mysqldbmysqldbconnectusermepasswdmypasswddbtestkv cmysqldbcursor connection pymongoconnection mongodb connectiontest kvtab mongodbkvtab nb thelist xrangenb thelistappendstrrandomrandomstrrandomrandom tdatetimenow kv thelist cexecuteinsert into keyvaltab kv values k v dtdatetimenow print mysql insert elapse dt tdatetimenow xrangenb cexecuteselect from keyvaltab where k randomchoicethelist resultcfetchone dtdatetimenow print mysql select elapse dt tdatetimenow kv thelist kvtabinsertkeykvaluev dtdatetimenow print mongodb insert elapse dt kvtabensureindex key tdatetimenow xrangenb resultkvtabfindonekeyrandomchoicethelist dtdatetimenow print mongodb select elapse dt notes mysql mongodb locahost mysql mongodb key column indexed mysql table create table if not exists keyvaltab k varchar not null v varchar not null key kindex k enginemyisam default charsetlatin versions mysql mongodb python pymongo linux ubuntu bits pae hardware desktop core ghz results million insertsselects mysql insert elapse mysql select elapse mongodb insert elapse mongodb much faster insert mongodb select elapse slower quering thought opposite,3 same language class fooobject def initself selfx class barobject def initself foo print foox foo b bara,class foo def initself selfvar class bar def initself print foo var f foo b bar in foo i something produces var set in bar i would like access contents var how i access var class instance f foo within instance b bar basically classes different wxframes so example one window user may putting input data second window uses input data produce output in c i would pointer caller i dont know access caller python,2 something like class foo def initself selfvar class bar def initself foo print foovar f foo b barfoo you able pass around objects python like pass around pointers c,class foo def initself selfvar class bar def initself print foo var f foo b bar in foo i something produces var set in bar i would like access contents var how i access var class instance f foo within instance b bar basically classes different wxframes so example one window user may putting input data second window uses input data produce output in c i would pointer caller i dont know access caller python,1 scipy import optimize special shell prompt starts command email program scipy import optimize special python put modules optimize special namespace scipy either use unqualified import scipy instead,i newbie i need help i installed scipy ubuntu when i ran code scipy import optimize special i get following terminal read varmailscipyoptimize i type python get type scipy import optimize i ran code including scipy optimize i get following name scipy defined,1 there guarantee seemingly identical objects produce identical pickle strings the pickle protocol virtual machine pickle string program virtual machine for given object exist multiple pickle strings programs reconstruct object exactly to take one examples cpickle import dumps hello world dumps hello world dpnininsininsininsininsininss hello world npnininininintpnlpninainainainainat dumpst dpnininsininsininsininsininss hello world nininininintlpninainainainainatpn the two pickle strings differ use p opcode the opcode takes one integer argument function follows name put code p argdecimalnlshort store stack top memo the stack popped the index memo location write given newline terminated decimal string following binput longbinput spaceoptimized versions to cut long story short two pickle strings basically equivalent i tried nail exact cause differences generated opcodes this could well reference counts objects serialized what clear however discrepancies like effect reconstructed object,is anyone able explain comment testlookups code snippet i run code indeed comment sais true however i like understand true ie cpickle outputting different values object depending referenced does anything reference count if kind bug ie pickled deserialized object would abnormally high reference count effect would never get garbage collected,3 httpdocspythonorglibrarypicklehtmlexample import pickle data j b string u unicode string c none selfreflist selfreflistappendselfreflist output open datapkl wb pickle dictionary using protocol pickledumpdata output pickle list using highest protocol available pickledumpselfreflist output outputclose,i recently got assignment i need put dictionary key refers list pickled form the problem i idea pickled form could anyone point right direction good resources help learn concept thanks,2 pickling serialization putting data form stored file retrieved later here docs pickle module httpdocspythonorgreleaselibrarypicklehtml,i recently got assignment i need put dictionary key refers list pickled form the problem i idea pickled form could anyone point right direction good resources help learn concept thanks,3 the pickle module implements fundamental powerful algorithm serializing deserializing python object structure pickling process whereby python object hierarchy converted byte stream unpickling inverse operation whereby byte stream converted back object hierarchy pickling unpickling alternatively known serialization marshalling flattening import pickle data j b string u unicode string c none selfreflist selfreflistappendselfreflist output open datapkl wb pickle dictionary using protocol pickledumpdata output pickle list using highest protocol available pickledumpselfreflist output outputclose to read pickled file import pprint pickle pklfile open datapkl rb data pickleloadpklfile pprintpprintdata data pickleloadpklfile pprintpprintdata pklfileclose source httpsdocspythonorglibrarypicklehtml,i recently got assignment i need put dictionary key refers list pickled form the problem i idea pickled form could anyone point right direction good resources help learn concept thanks,3 while others pointed python documentation pickle module great resource also check chapter serializing python objects dive into python mark pilgrim,i recently got assignment i need put dictionary key refers list pickled form the problem i idea pickled form could anyone point right direction good resources help learn concept thanks,3 pickling python used serialize deserialize python objects like dictionary case i usually use cpickle module much faster pickle module import cpickle pickle def serializeobjectpythonobj return pickledumpspythonobj picklehighestprotocol def deserializeobjectpickledobj return pickleloadspickledobj,i recently got assignment i need put dictionary key refers list pickled form the problem i idea pickled form could anyone point right direction good resources help learn concept thanks,1 one possibility class a def initself nnone n none n selfdata n,class a def initself n selfdata n a print adata print adata b a print adata print desired output in case way provide default argument mutable object list class init class a b affected operation,2 you could try class a def initself nnone ifn none n selfdata n which avoids biggest problem facing list every single object type a,class a def initself n selfdata n a print adata print adata b a print adata print desired output in case way provide default argument mutable object list class init class a b affected operation,3 it wrong look python execution time estimate database quality each request consist least parts request preparing client side request execution server response preparing client side by experience data convertion mongodbpython takes much time mysqlpython also use indexes databases mongodb works good indexes fields use queries talking mysql i think better test performance innodb myisam support transactions foreign keys triggers little bit outdated,i discovered mongodb months agoand reading post i thought mongodb really faster mysql i decided build bench problem i result post author especially quering database mongodb seems slower myisam tables could look python code may something wrong datetime import datetime import random import mysqldb import pymongo mysqldbmysqldbconnectusermepasswdmypasswddbtestkv cmysqldbcursor connection pymongoconnection mongodb connectiontest kvtab mongodbkvtab nb thelist xrangenb thelistappendstrrandomrandomstrrandomrandom tdatetimenow kv thelist cexecuteinsert into keyvaltab kv values k v dtdatetimenow print mysql insert elapse dt tdatetimenow xrangenb cexecuteselect from keyvaltab where k randomchoicethelist resultcfetchone dtdatetimenow print mysql select elapse dt tdatetimenow kv thelist kvtabinsertkeykvaluev dtdatetimenow print mongodb insert elapse dt kvtabensureindex key tdatetimenow xrangenb resultkvtabfindonekeyrandomchoicethelist dtdatetimenow print mongodb select elapse dt notes mysql mongodb locahost mysql mongodb key column indexed mysql table create table if not exists keyvaltab k varchar not null v varchar not null key kindex k enginemyisam default charsetlatin versions mysql mongodb python pymongo linux ubuntu bits pae hardware desktop core ghz results million insertsselects mysql insert elapse mysql select elapse mongodb insert elapse mongodb much faster insert mongodb select elapse slower quering thought opposite,1 it looking reference counts cpickle source pyrefcntargs pyobid pylongfromvoidptrargs goto finally pydictgetitemselfmemo pyobid getself pyobid goto finally res goto finally the pickle protocol deal pickling multiple references object in order prevent duplicating object depickled uses memo the memo basically maps indexes various objects the put p opcode pickle stores current object memo dictionary however single reference object reason store memo impossible need reference one reference thus cpickle code checks reference count little optimization point so yes reference counts but problem the objects unpickled correct reference counts produces slightly shorter pickle reference counts now i know care but really assume pickling object always give result if nothing else i expect dictionaries give problems order keys undefined unless python documentation guarantees pickle time i highly recommend depend,is anyone able explain comment testlookups code snippet i run code indeed comment sais true however i like understand true ie cpickle outputting different values object depending referenced does anything reference count if kind bug ie pickled deserialized object would abnormally high reference count effect would never get garbage collected,2 if i understood correctly problem could class mclidaractions object li tcpsend event def objectupdatedchanged self info print info pass def tcpsendchanged self print click x selfli xtcpsendchanged class mcudpactions mclidaractions def initself selfliappendself def objectupdatedchanged self info pass def tcpsendchanged self print click udp class mcuuuuuuuuuuuuuutpactions mclidaractions def initself selfliappendself def objectupdatedchanged self info pass def tcpsendchanged self print click uuuuuuuuuuuuuutp m mclidaractions print m instance mclidaractions created print executing mtcpsendchanged mtcpsendchanged mcudpactions print na instance mcudpactions created print executing mtcpsendchanged mtcpsendchanged print print executing atcpsendchanged atcpsendchanged b mcudpactions print nb instance mcudpactions created print executing mtcpsendchanged mtcpsendchanged print print executing atcpsendchanged atcpsendchanged print print executing btcpsendchanged btcpsendchanged v mcuuuuuuuuuuuuuutpactions print nv instance mcuuuuuuuuuuuuuutpactions created print executing mtcpsendchanged mtcpsendchanged print print executing atcpsendchanged atcpsendchanged print print executing btcpsendchanged btcpsendchanged print print executing vtcpsendchanged vtcpsendchanged result m instance mclidaractions created executing mtcpsendchanged click instance mcudpactions created executing mtcpsendchanged click click udp executing atcpsendchanged click udp b instance mcudpactions created executing mtcpsendchanged click click udp click udp executing atcpsendchanged click udp executing btcpsendchanged click udp v instance mcuuuuuuuuuuuuuutpactions created executing mtcpsendchanged click click udp click udp click uuuuuuuuuuuuuutp executing atcpsendchanged click udp executing btcpsendchanged click udp executing vtcpsendchanged click uuuuuuuuuuuuuutp but code necessary define function init subclass mcudpactions mcuuuuuuuuuuuuuutpactions base class mclidaractions to avoid appending li put base class class mclidaractions object li tcpsend event def initself selfclass mclidaractions selfliappendself def objectupdatedchanged self info print info pass def tcpsendchanged self print click x selfli xtcpsendchanged class mcudpactions mclidaractions def objectupdatedchanged self info pass def tcpsendchanged self print click udp class mcuuuuuuuuuuuuuutpactions mclidaractions def objectupdatedchanged self info pass def tcpsendchanged self print click uuuuuuuuuuuuuutp result exactly,i following classes forwindlidarapiapi import mclidarguiplugin class mclidaractions handler tcpsend event def objectupdatedchanged self info print info pass def tcpsendchanged self print click forwindlidarapiactionsapi import mclidaractions class mcudpactions mclidaractions def objectupdatedchanged self info pass def tcpsendchanged self print click udp when i click button mclidaractions tcpsendchanged function called i extend function i want take action mcudpactions well in case if i click button printed click i want print click udp well,1 one standard os way handle interrupts enqueue interrupt another kernel thread process this partially applies python i writing code thread checking file see updates i want interrupt main program aware update deals appropriately returns line running interrupted you multiple threads you need interrupt main program simply deal appropriately separate thread the main thread find updates thread dealt appropriately this locks to sure shared state updated correctly you interrupt thread locking resource thread needs you make thread interruptable acquiring locks resources,is method one could use try statement catch error caused raise statement execute code handle flag eg update variables return line code operating flag raised i thinking specifically interrupt handler microcontroller ive described i writing code thread checking file see updates i want interrupt main program aware update deals appropriately returns line running interrupted ideally main program would recognize flag thread regardless execution a try statement would could i return line flag raised thanks paul edit my attempt isr comments albeit looks like pretty straight forward example using locks small test routine bottom demonstrate code import os import threading import time def isrpath interrupt prevmod osstatpathstmtime newmod osstatpathstmtime newmod prevmod print updates waiting begin prevent enter critical code updating while critical code running interrupt print starting updates prevmod newmod print fished updating else print no updates timesleep def funcinterrupt interrupt prevent updates running critical code execute critical code print running crit code timesleep print finished crit code do things interrupt threadinglock path testfiltxt threadingthreadtarget isr args path interrupt threadingthreadtarget func args interrupt tstart tstart create update file timesleep chngfile opentestfiltxtw chngfilewritechanging file chngfileclose timesleep,1 in python call pattern function calls you cannot exceptions exceptions unroll stack always first enclosing except clause microcontrollers interrupts support asynchronous events mechanism also used software interrupts system calls interrupt configured different set protection bits system call allowed user program calling python kind protection levels like software interrupts much use as handling asynchronous events python using signal module may want step lightly also using threads,is method one could use try statement catch error caused raise statement execute code handle flag eg update variables return line code operating flag raised i thinking specifically interrupt handler microcontroller ive described i writing code thread checking file see updates i want interrupt main program aware update deals appropriately returns line running interrupted ideally main program would recognize flag thread regardless execution a try statement would could i return line flag raised thanks paul edit my attempt isr comments albeit looks like pretty straight forward example using locks small test routine bottom demonstrate code import os import threading import time def isrpath interrupt prevmod osstatpathstmtime newmod osstatpathstmtime newmod prevmod print updates waiting begin prevent enter critical code updating while critical code running interrupt print starting updates prevmod newmod print fished updating else print no updates timesleep def funcinterrupt interrupt prevent updates running critical code execute critical code print running crit code timesleep print finished crit code do things interrupt threadinglock path testfiltxt threadingthreadtarget isr args path interrupt threadingthreadtarget func args interrupt tstart tstart create update file timesleep chngfile opentestfiltxtw chngfilewritechanging file chngfileclose timesleep,1 maybe could adapt packagedata idea use datafiles instead wouldn’t require list twistedplugins package uses absolute paths it would still kludge though my tests pure distutils told possible overwrite files another distribution i wanted test poor man’s namespace packages using pkgutilextendpath distutils turns i install spamhaminitpy spamhamsetuppy spameggsinitpy spameggssetuppy directories problem files happily overwritten i think actually undefined behavior distutils trickles setuptools pip pip could imo close wontfix what usual way install twisted plugins dropithere hand,the twisted plugin system preferred way write extensible twisted applications however due way plugin system structured plugins go twistedplugins directory python package writing proper setuppy installing plugins appears nontrivial i seen attempts add twistedplugins packages key distutils setup command since really package bad things happen example initpy helpfully added tools other attempts seem use packagedata instead eg httpbazaarlaunchpadnetglyphdivmodorgtrunkviewheadepsilonepsilonsetuphelperpy also fail weird ways the question anyone successfully written setuppy installing twisted plugins works cases,1 i think point use dailylogfile use pythonloggingobserver redirect log standard lib log twistedpython import log observer logpythonloggingobserver observerstart logmsg selfcolorscolortype msg also might want see example docs httptwistedmatrixcomdocumentscurrentcorehowtologginghtmlauto,i use logging one file different scripts one program cron tasks twisted daemons httpservers data etc if i use default python logging base class import logging import logginghandlers selffname openlogname loggingbasicconfigformatformat filenamelogname handlerlogginghandlersrotatingfilehandler selflog logginggetloggerselfpname selflogsetlevelloglevel loggingwarn selfcolorscolortype msg work normally sending output scripts one file important part default twisted log missing info http requestheaders etc else i use twisted logging twistedpythonlogfile import dailylogfile twistedpython import log twistedapplicationservice import application application applicationfoo logstartloggingdailylogfilefromfullpathlogname print selfcolorscolortype msg works additional data trouble logging different scripts exists looks like cron tasks trouble appears looks like cron tasks switch context output part logging output missing restored of course cron tasks working without twisted reactor using twisted logging what i logging log data printed twistedcron parts app thanks help,1 the problem validate certificate trying unless selfsigned ca bit set you add real ca certificate web site cacertstxt file another alternative something like connect anyway web browser drop certreqs sslcertnone get exception understand could possibly man middle this ssl module issue sslx work,i trying small secure https client learning purposes see mechanics ssl works higher level trying convert simple socket ssl via sslwrapsocket i probably got whole concept backwards sconnecthost port port f open cacertstxt r calist fread fclose ca sslgetservercertificatehost port sslversionsslprotocolsslvsslprotocoltlsv ca calist f open cacertstxt fwriteca fclose sslwrapsockets sslversionsslprotocolsslvsslprotocoltlsv certreqssslcertrequired cacertscacertstxt sdohandshake and call dohandshake get traceback recent call last file ssltestpy line requester sslwrapsockets sslversionsslprotocolsslvsslprotocoltlsv certreqssslcertrequired cacertscacertstxt file cpythonlibsslpy line wrapsocket suppressraggedeofssuppressraggedeofs file cpythonlibsslpy line init selfdohandshake file cpythonlibsslpy line dohandshake selfsslobjdohandshake sslsslerror errno sslc errorssl routinessslgetservercertificatecertificate verify failed i searched around tried find something would close everyone points either pyopenssl twisted prefer could stay libraries mainly later planing bringing sharp production environment allowed use built libraries python any help would greatful,3 you could also reverse dependency put version mylibinitpy parse file setuppy get version parameter use git tag setuppy version command line create tag git tag vpython setuppy version description version is anything complicated want i haven’t understood,situation i python library controlled git bundled distutilssetuptools and i want automatically generate version number based git tags setuppy sdist alike commands library for first task i use git describe alike solutions see how i get version defined setuppy setuptools package and example i tag call setuppy sdist i get mylibtargz mylibabcdtargz i altered code tagging this fine the problem is the problem comes i want version number available library could send useragent http header mylibadcd if i add setuppy version command how i get version defined setuppy setuptools package versionpy generated after tag made since uses tag value but case i need make one commit version tag made make code consistent which turns requires new tag bundling the question is how break circle dependencies generatecommittaggeneratecommittag,3 class checkjira ends line one method then block checkforjiraissuerecord function defined block function defined name main just put block outside whole class definition,here code usrbinenv python import os sys jira subprocess class checkjira def verifycommittextself tags line tags rematch notik line return true elif rematch noreview line return true elif rematchr azazd line validate jira id researchazazdline myargs mgroup result checkjiracheckforjiraissuerecordmyargs result false utilwarns existmyargs else return true return true else return false name main p checkjira committextverified pverifycommittextospopen hg tip template desc committextverified sysexit else print sysstderr obey rules sysexit def checkforjiraissuerecordobject sysstdout osdevnull sysstderr osdevnull try com jiracommands logger jirasetuplogging jiraenv home osenviron home commandcat cat commandlogout logout myargs qa server httpjiramyservercomrpcsoapjirasoapservicevwsdl except exception e sysexit config error class options pass options options optionsuser user optionspassword password try jirasoap jiraclientserver jirastartloginoptions jiraenv commandcat com logger issue comruncommandcat logger jiraenv myargs except exception e print sysexit data error maybe name main shoudl bottom so classes checkjira options checkjira functions verifycommittext checkforjiraissuerecord i pass object argument checkforjiraissuerecord since passing myargs usage not sure call one function another function class error getting traceback recent call last file homeqahooktesthgcheckjirapy line committextverified pverifycommittextospopen hg tip template desc file homeqahooktesthgcheckjirapy line verifycommittext result checkjiracheckforjiraissuerecordmyargs attributeerror class checkjira attribute checkforjiraissuerecord transaction abort rollback completed abort pretxncommitjira hook exited status,1 the splitlongrows command able change behavior from documentation query set internal variable controls whether rows matrix may split displayed terminal window,i would like use octave calculator python script currently i running octave like octave q eval code read stdout interpret results however i running problems matrices reach certain width octave starts output column numerations like ans columns e e e e e columns e e makes interpreting result little harder is way tell octave split printing results,1 employeesobjectsvalueslist engname flattrue that creates flat list engname if want one field per row flat list create list lists employeesobjectsvalueslist engname rank,i tablemodels called employees i would like get rows single field queryset i know i like hope i right even emplist employeesobjectsgetall empnames emplistengname would query database fields using one is better faster way,3 simplest efficient way would run another python executable subprocess import popen popenpython somescriptpy,in windows i think answer question i need create windows service this seems ludicrously heavyweight i trying i trying slap together little prototype manager i going responsible productizing fact may never even be productized might something researchers play around i cgi script receives file upload stores temporary location launches background process serious numbercrunching file then javascript stuff sits around calling cgi scripts check status update page needed all works except damn web server close connection long subrocess running i done searching appears answer unix make daemon i stuck windows right i guess answer make windows service this seems incredibly heavyweight know launch damn process close server connection that really way edit okay found nifty little hack choice guy gives how completely background process perl cgi iis i able modify make even simpler although klugey solution perfect quickanddirty little prototype i trying make so i initially main script subprocesspopenpythonexemyscriptpyargarg which work i described instead i main script emit little bit javascript runs document fully loaded somecraploadlaunchbackgroundprocesspy argfooargbar and launchbackgroundprocesspy subprocesspopen this solution would never scale since still leaves browser connection open entire time background task running but since little thinger i whipping might someday two simultaneous users even i doubt resources concern this allows user see main page get javascript updates even though still http connection hanging open good reason thanks answers if i ever asked productize i take resources profane recommends,1 you close try locationmapindia sortedlocationmapindiaiteritems keylambda x xname result would list dict dict orderless,i python dictionary i want sort according name locationmapindia name andaman amp nicobar islands lat long radius name andhra pradesh lat long radius it come way i expect i tried locationmapindia sortedlocationmapindiaiteritems keylambda x xname the work what i update the following allowed behaved expected thanks help code locationmapindia sortedlocationmapindiaiteritems keylambda x xname template keyvalue locationmapindia option valuekey valuenameoption endfor,3 you use system call using start windows command this way python script wait completion started program,in windows i think answer question i need create windows service this seems ludicrously heavyweight i trying i trying slap together little prototype manager i going responsible productizing fact may never even be productized might something researchers play around i cgi script receives file upload stores temporary location launches background process serious numbercrunching file then javascript stuff sits around calling cgi scripts check status update page needed all works except damn web server close connection long subrocess running i done searching appears answer unix make daemon i stuck windows right i guess answer make windows service this seems incredibly heavyweight know launch damn process close server connection that really way edit okay found nifty little hack choice guy gives how completely background process perl cgi iis i able modify make even simpler although klugey solution perfect quickanddirty little prototype i trying make so i initially main script subprocesspopenpythonexemyscriptpyargarg which work i described instead i main script emit little bit javascript runs document fully loaded somecraploadlaunchbackgroundprocesspy argfooargbar and launchbackgroundprocesspy subprocesspopen this solution would never scale since still leaves browser connection open entire time background task running but since little thinger i whipping might someday two simultaneous users even i doubt resources concern this allows user see main page get javascript updates even though still http connection hanging open good reason thanks answers if i ever asked productize i take resources profane recommends,1 try locationmapindia sortedlocationmapindiaitems keylambda x x name,i python dictionary i want sort according name locationmapindia name andaman amp nicobar islands lat long radius name andhra pradesh lat long radius it come way i expect i tried locationmapindia sortedlocationmapindiaiteritems keylambda x xname the work what i update the following allowed behaved expected thanks help code locationmapindia sortedlocationmapindiaiteritems keylambda x xname template keyvalue locationmapindia option valuekey valuenameoption endfor,1 it bug exactly told you yielding object several times get several references object the reason see three first snippet python go back time change previous output match objects mutated try storing values get calling next explicitly variables check end get result such iterator useful yielded value used iterator advanced another time therefore i generally avoid produces unexpected results trying precompute results also means breaks various useful tricks itertoolstee iterable unpacking,i generator defined like def gen r yield r r yield r r yield r yield three lists one element going gen nexta nexta nexta nexta traceback recent call last file pyshell line module nexta stopiteration now i go make list generator i got listgen that seems yield time last computed value is python bug i missing something,1 when doubt check source code you see python ssplit optimized whitespace inlined but ssplit fixed delimiters for speed tradeoff resplit regular expression based split far flexible resplit onetwot h r e efourth field one two h r e e fourth field onetwot h r e efourth fieldsplit one two h r e e fourth field would require addition step find empty fields resplit onetwot h r e efourth field one two h r e e fourth field try without regex split understandable way that resplit slower ssplit faster amazing,in quests optimization i discovered builtin split method faster resplit equivalent a dummy benchmark easily copypasteable import time random def randomstringlen letters abc return joinlettersrandomrandintlenletters rangelen r randomstring pattern recompilera start timetime patternsplitr print resplit timetime start start timetime rsplita print builtin split timetime start why difference,2 if much experience windows programming wish peruse msdn docs i blame may want try pick copy mark hammond cannonical guide things python windows it somehow never goes outofdate many sorts recurring questions instead launching process everyplatform solution probably better using winprocess module chapter hammond book covers extensively could probably get need downloading pywin ide i think comes bundled windows extensions download pypi looking help docs python windows api here example using api project i working recently it may fact want little adaptation you probably want focus creationflags in particular winprocessdetachedprocess often used execute console programs background many flags available conveniently wrapped however subprocessmswindows susubprocessstartupinfo sudwflags subprocesssubprocessstartfuseshowwindow process subprocesspopen program flag flag bufsize stdoutsubprocesspipe startupinfosu,in windows i think answer question i need create windows service this seems ludicrously heavyweight i trying i trying slap together little prototype manager i going responsible productizing fact may never even be productized might something researchers play around i cgi script receives file upload stores temporary location launches background process serious numbercrunching file then javascript stuff sits around calling cgi scripts check status update page needed all works except damn web server close connection long subrocess running i done searching appears answer unix make daemon i stuck windows right i guess answer make windows service this seems incredibly heavyweight know launch damn process close server connection that really way edit okay found nifty little hack choice guy gives how completely background process perl cgi iis i able modify make even simpler although klugey solution perfect quickanddirty little prototype i trying make so i initially main script subprocesspopenpythonexemyscriptpyargarg which work i described instead i main script emit little bit javascript runs document fully loaded somecraploadlaunchbackgroundprocesspy argfooargbar and launchbackgroundprocesspy subprocesspopen this solution would never scale since still leaves browser connection open entire time background task running but since little thinger i whipping might someday two simultaneous users even i doubt resources concern this allows user see main page get javascript updates even though still http connection hanging open good reason thanks answers if i ever asked productize i take resources profane recommends,1 i familiar plpython throwing error getting printed passed chain would never know i know testing command line try putting print statement except blocks see erroring instead returning,is reason function call would return result create or replace function myfunction input int out result int as result mymoduleobjectinputplpy plpyinfo extramodule result result language plpythonu content mymodule def objectinputplpy import stringio try plan plpyprepareinsert into file values nextval primarysequence returning primarykey integer except plpyerrortracebackformatexc try rv plpyexecuteplan input result rvprimarykey plpyinfo intramodule result result return result except plpyerrortracebackformatexc,1 if using dictionary must order way using correct data structure try list tuples instead,i python dictionary i want sort according name locationmapindia name andaman amp nicobar islands lat long radius name andhra pradesh lat long radius it come way i expect i tried locationmapindia sortedlocationmapindiaiteritems keylambda x xname the work what i update the following allowed behaved expected thanks help code locationmapindia sortedlocationmapindiaiteritems keylambda x xname template keyvalue locationmapindia option valuekey valuenameoption endfor,1 replace import init import mod,first apologies question already asked elsewhere i really searched find anything the situation following in folder mod i files initpy subpy they contain following data initpy print mod subpy import init print sub now let following import mod mod import modsub mod sub but import modsub modinitpy executed it imported already the strange feature exists call import modsub mod mod sub can i change behaviour changing import init this line seems likely wrong,1 use tuple unpacking key valx valy valz dictiteritems often people use key valz dictiteritems interested one item tuple but may cause problem use gettext module multi language applications model sets global function called as tuples immutable able set one item like dkey x you unpack first x z dkey dkey x newy z,let say i python dictionary values tuple eg dict key valx valy valz key valx valy valzkey valx valy valy i want retrieve third value tuple eg valz valz valz example i could using iteritems instance key val dictiteritems valz val however direct approach ideally i like query dictionary key return third value tuple eg dictkey valz instead i currently get dictkey valx valy valz callable any advice,2 just keep indexing d key key dkey,let say i python dictionary values tuple eg dict key valx valy valz key valx valy valzkey valx valy valy i want retrieve third value tuple eg valz valz valz example i could using iteritems instance key val dictiteritems valz val however direct approach ideally i like query dictionary key return third value tuple eg dictkey valz instead i currently get dictkey valx valy valz callable any advice,3 which method using loadmanipulate frame are using pil if i suggest checking python imaging library specifically pil gif page now assuming using pil read gif pretty simple matter determine frame looking seek go specific frame tell return frame looking import image im imageopenanimationgif to iterate entire gif try imseekimtell something im except eoferror pass end sequence otherwise i believe find number frames gif seeking exception eoferror raised,i looking kind method get gif frames number looking google stackoverflow outher sites find rubbish someone know need simple number gif frames,3 you actually inspect going using dictionary sysmodules python decides reload module depending keys dictionary when run import mod creates one entry mod sysmodules when run import modsub call import init python checks whether key modinit sysmodules key imported the bottom line python decides reimport module keys present sysmodules actual module already imported,first apologies question already asked elsewhere i really searched find anything the situation following in folder mod i files initpy subpy they contain following data initpy print mod subpy import init print sub now let following import mod mod import modsub mod sub but import modsub modinitpy executed it imported already the strange feature exists call import modsub mod mod sub can i change behaviour changing import init this line seems likely wrong,3 i use beatbox example query lead email address import beatbox sfusername username sfpassword password sfapitoken api token def getleadrecordsbyemailemail sfclient beatboxpythonclient password strss sfpassword sfapitoken sfclientloginsfusername password leadqry select id email firstname lastname ownerid from lead where email email records sfclientqueryleadqry return records to get data look salesforce api docs view beatbox examples,is library package use python connect salesforce get data,3 i copied script ran looks like call script wrong way python testpy tmp traceback recent call last file testpy line module print ospathisdiroptsinputpath file usrlibpythongenericpathpy line isdir st osstats typeerror coercing unicode need string buffer nonetype found python testpy path tmp true,i trying input path using optparser python unfortunately piece code keeps showing error import optparseos parser optparseoptionparser parseraddoptionppath help prints pathdest inputpath metavar path optsargs parserparseargs print ospathisdiroptsinputpath error traceback recent call last file usersarmeddocumentspythontestpy line print ospathisdiroptsinputpath file libraryframeworkspythonframeworkversionslibpythongenericpathpy line isdir st osstats typeerror coercing unicode need string buffer nonetype found any help much appreciated,1 that error optsinputpath none instead path stringunicode are sure calling script correctly you probably put error checking code case make sure user doesnt put p program crash or change positional argument make required optparse httpdocspythonorglibraryoptparsehtmlwhatarepositionalargumentsfor edit also optparse deprecated new project probably want use argparse,i trying input path using optparser python unfortunately piece code keeps showing error import optparseos parser optparseoptionparser parseraddoptionppath help prints pathdest inputpath metavar path optsargs parserparseargs print ospathisdiroptsinputpath error traceback recent call last file usersarmeddocumentspythontestpy line print ospathisdiroptsinputpath file libraryframeworkspythonframeworkversionslibpythongenericpathpy line isdir st osstats typeerror coercing unicode need string buffer nonetype found any help much appreciated,2 fisher exact test uses hypergeometric distribution the version scipy using uses implementation hypergeometric distribution precise this known problem fixed scipy repository,i noticed fisherexact test scipy returns negative pvalue pvalue extrememly small import scipy sp import scipystats x spstatsfisherexactx e in r using x contingency table matrixc nrow fishertesta pvalue e my question scipy return negative pvalue i use scipy generate correct pvalue thanks help,3 for d plotting general i would advise mayavi it bit daunting first worth effort it certainly much faster matplotlib plotting one shot d data for plotting many times savefig call i sure,i x numpyarray data constantly changed every iteration i take snapshot make movie snapshot surface plot made using matplotlib the problem plotting costs seconds every iteration seconds iterations i program running matlab seconds number iterations the question ways speed matplotlib surface plotting faster plotting tools python here code initializing plot fig pltfigure figclf ax figgcaprojection x nparange fieldsize y nparange fieldsize x y npmeshgridx y loop starttime timetime k xrange ittime timetime field maxvalue field scipyndimageconvolvefield kernel print k calculation timetime ittime seconds ittime timetime axcla axplotsurfacex y fieldreal rstride cstride cmapcmhot linewidth antialiasedfalse axsetzlimd filename outdpng k figsavefigfilename figclf print k plotting timetime ittime seconds print computing timetime starttime seconds,1 if using python superior take look ordereddict using may solve problem ordereddictsortedditems keylambda x x name,i python dictionary i want sort according name locationmapindia name andaman amp nicobar islands lat long radius name andhra pradesh lat long radius it come way i expect i tried locationmapindia sortedlocationmapindiaiteritems keylambda x xname the work what i update the following allowed behaved expected thanks help code locationmapindia sortedlocationmapindiaiteritems keylambda x xname template keyvalue locationmapindia option valuekey valuenameoption endfor,2 you correct mainloop needs called program initialized this necessary start event loop necessary windows draw respond events what break initialization two parts the first creating wait window happens prior starting event loop the second rest initialization happens event loop started you scheduling second phase via method here simple example import tkinter tk import time class sampleapptktk def initself args kwargs initialize tkinter tktkinitself args kwargs hide main window selfwmwithdraw show please wait window selfwait tktoplevelself label tklabelselfwait textplease wait labelpack schedule rest initialization happen event loop started selfafter selfinitphase def initphaseself simulate something timesleep done close wait window show main window selfwaitdestroy selfwmdeiconify app sampleapp appmainloop,i already large tkinter program i init file root tk window defined containing basically text widget things code last call mainloop function everything works i needed call procedure mainloop i wanted raise wait window begin destroyed procedure end i wrote something like msg messageroot text wait seconds msgpack but cannot work since mainloop called yet if i instead msg messageroot text wait seconds msgpack mainloop the program stops first mainloop finish procedure call mainloop used last program line tkinter program works logic driven user clicks interactions etc here i need sequence raise window stuff destroy window mainloop,1 okay i think i figured i using variablecolumn called clean django admin interface method called clean also kind validation it appears kind naming conflict i changed variable name cleaned make sure knows database field use i using legacypreexisting db i added dbcolumn option cleaned modelstextfieldblanktruedbcolumnclean it would nice know clean reserved identifier django least i wasted half day django stuff ostensibly makes database operations easier to fair i started django morning i would found answer stackoverflow would breeze fix if anyone knows better way handle let know,i getting error trying save following model using admin interface modelspy class answermodelsmodel modelstextfieldprimarykeytrue gloss modelstextfieldblanktrue clean modelstextfieldblanktrue count modelsintegerfieldblanktrue p modelsintegerfieldblanktrue def unicodeself return us selfa class meta dbtable u answers error message shows admin interface environment request method post request url httplocalhostadminemotionsansweradd django version prealpha svn python version installed applications djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles djangocontribadmin emoqbrowseremotions installed middleware djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware traceback file homeabebindjangotrunkdjangocorehandlersbasepy getresponse response callbackrequest callbackargs callbackkwargs file homeabebindjangotrunkdjangocontribadminoptionspy wrapper return selfadminsiteadminviewviewargs kwargs file homeabebindjangotrunkdjangoutilsdecoratorspy wrappedview response viewfuncrequest args kwargs file homeabebindjangotrunkdjangoviewsdecoratorscachepy wrappedviewfunc response viewfuncrequest args kwargs file homeabebindjangotrunkdjangocontribadminsitespy inner return viewrequest args kwargs file homeabebindjangotrunkdjangoutilsdecoratorspy wrapper return boundfuncargs kwargs file homeabebindjangotrunkdjangoutilsdecoratorspy wrappedview response viewfuncrequest args kwargs file homeabebindjangotrunkdjangoutilsdecoratorspy boundfunc return funcself args kwargs file homeabebindjangotrunkdjangodbtransactionpy inner return funcargs kwargs file homeabebindjangotrunkdjangocontribadminoptionspy addview formisvalid file homeabebindjangotrunkdjangoformsformspy isvalid return selfisbound boolselferrors file homeabebindjangotrunkdjangoformsformspy geterrors selffullclean file homeabebindjangotrunkdjangoformsformspy fullclean selfpostclean file homeabebindjangotrunkdjangoformsmodelspy postclean selfinstanceclean exception type typeerror adminemotionsansweradd exception value unicode object callable,1 the python library stata interoperability i could find merely provides readonly access dta files the r foreign library however provides function writedta rpy provides python interface r maybe combination tools help,i wondering anyone knows python package allows save numpy arraysrecarrays dta format statistical data analysis software stata this would really speed steps system i,3 the function called throwing exception due following lines sysstdout osdevnull sysstderr osdevnull you assigning string osdevnull file handle anyone writes stdout stder throw exception due type error you try sysstdout openosdevnull sysstderr openosdevnull see works,may seem like basic question difficulty grasping would appreciate help i want able call checkforjiraissuerecord verifycommittext code run get error jira ticket regex matched printing mgroup qa myargs qa transaction abort rollback completed abort pretxncommitjira hook exited status meaning checkforjiraissuerecordmyargs getting called usrbinenv python import os sys jira subprocess def verifycommittexttags line tags rematch notik line return true elif rematch noreview line return true elif rematchr azazd line validate jira id print jira ticket regex matched researchazazdline print printing mgroup print mgroup myargs mgroup print myargs print myargs result checkforjiraissuerecordmyargs print printing result print result result false utilwarns existmyargs print result false else print result false return true return true return true else return false def checkforjiraissuerecordobject sysstdout osdevnull sysstderr osdevnull try com jiracommands logger jirasetuplogging jiraenv home osenviron home commandcat cat commandlogout logout myargs qa server httpjiramyservercomrpcsoapjirasoapservicevwsdl except exception e sysexit config error name main committextverified verifycommittextospopen hg tip template desc committextverified verifycommittextospopen hg log r template desc committextverified sysexit else print sysstderr obey rules sysexit class options pass options options optionsuser username optionspassword password try jirasoap jiraclientserver jirastartloginoptions jiraenv commandcat com logger issue comruncommandcat logger jiraenv myargs except exception e print sysexit data error,1 offending lines sysstdout osdevnull sysstderr osdevnull you must assign sysstdout variable function done supposed change back ie sysstdout err sysstderr your code just befor function exits sysstdout sysstderr err,may seem like basic question difficulty grasping would appreciate help i want able call checkforjiraissuerecord verifycommittext code run get error jira ticket regex matched printing mgroup qa myargs qa transaction abort rollback completed abort pretxncommitjira hook exited status meaning checkforjiraissuerecordmyargs getting called usrbinenv python import os sys jira subprocess def verifycommittexttags line tags rematch notik line return true elif rematch noreview line return true elif rematchr azazd line validate jira id print jira ticket regex matched researchazazdline print printing mgroup print mgroup myargs mgroup print myargs print myargs result checkforjiraissuerecordmyargs print printing result print result result false utilwarns existmyargs print result false else print result false return true return true return true else return false def checkforjiraissuerecordobject sysstdout osdevnull sysstderr osdevnull try com jiracommands logger jirasetuplogging jiraenv home osenviron home commandcat cat commandlogout logout myargs qa server httpjiramyservercomrpcsoapjirasoapservicevwsdl except exception e sysexit config error name main committextverified verifycommittextospopen hg tip template desc committextverified verifycommittextospopen hg log r template desc committextverified sysexit else print sysstderr obey rules sysexit class options pass options options optionsuser username optionspassword password try jirasoap jiraclientserver jirastartloginoptions jiraenv commandcat com logger issue comruncommandcat logger jiraenv myargs except exception e print sysexit data error,1 to avoid zombie processes child must double fork detach controlling process see httpenwikipediaorgwikizombieprocess so need make child process fork careful keep relevant file handles open still communicate,i trying write application allow user start longrunning calculation processes hours example to i use python popen function as long main pylons process works fine everything good i restart pylons process respond requests zombie processes left previous paster launch what could origin workaround problem thanks advance ivan,1 it class solutionsappendlist list def appendlistself list print list selflistappendlist class methods always self reference instance first parameter,i figure i wrong i create nested listof possible solutions problem i created class appends solution list existing solutionssince solution calculated one time this function works fine def appendlistlist print list listappendlist x x x x one one two two appendlistone two print list result one two one two one two one two one two one two one two one two one two one two i take exact function put class i get error saying typeerror appendlist takes exactly argument given here class i call class solutionsappendlist list def appendlistlist print list listappendlist appendlistappendlist one two i sure i making basic error i seem figure since i using function class any suggestionsadvice would great thanks,1 when working class instance special variable self always passed first argument method calls you need modify function declaration accommodate class solutionlist def appendlistself list rest function,i figure i wrong i create nested listof possible solutions problem i created class appends solution list existing solutionssince solution calculated one time this function works fine def appendlistlist print list listappendlist x x x x one one two two appendlistone two print list result one two one two one two one two one two one two one two one two one two one two i take exact function put class i get error saying typeerror appendlist takes exactly argument given here class i call class solutionsappendlist list def appendlistlist print list listappendlist appendlistappendlist one two i sure i making basic error i seem figure since i using function class any suggestionsadvice would great thanks,1 since dealing classes important use instance variables these accessed using self keyword and dealing class methods sure make first argument self so modified class solutionsappendlist def initself selflist def appendlistself list print list selflistappendlist what cool longer need list instance variables selflist are different local variables list pass appendlist method edit ive also added init method called instance solutionsappendlist object created in first reply i overlooked fact self available outside method this edited code thanks david,i figure i wrong i create nested listof possible solutions problem i created class appends solution list existing solutionssince solution calculated one time this function works fine def appendlistlist print list listappendlist x x x x one one two two appendlistone two print list result one two one two one two one two one two one two one two one two one two one two i take exact function put class i get error saying typeerror appendlist takes exactly argument given here class i call class solutionsappendlist list def appendlistlist print list listappendlist appendlistappendlist one two i sure i making basic error i seem figure since i using function class any suggestionsadvice would great thanks,1 how one liner valid lstrip l fh allc acgt c lstrip fh file handle,i would like remove row file contains letter a c g t so tc cy gs ga ct become tc ga ct the files unknown number rows contain patterns letters order in addition i know letters present y s something else how would i go setting program preferably python i already import file read rows thanks,2 you solve simple regular expression list comprehension import data tc cy gs ga ct x x data rematchr acgt x tc ga ct,i would like remove row file contains letter a c g t so tc cy gs ga ct become tc ga ct the files unknown number rows contain patterns letters order in addition i know letters present y s something else how would i go setting program preferably python i already import file read rows thanks,2 send string selfsendlinestrsomevarwhichisanumber,i writing mud python using twisted library i currently trying send integer sendline method via linereceiver module however whenever i try sending integer i get error message running program unhandled error traceback recent call last file cpythonlibsitepackagestwistedpythonlogpy line thlogger return callwithcontextsystem lp func args kw file cpythonlibsitepackagestwistedpythonlogpy line thcontext return contextcallilogcontext newctx func args kw file cpythonlibsitepackagestwistedpythoncontextpy line allwithcontext return selfcurrentcontextcallwithcontextctx func args kw file cpythonlibsitepackagestwistedpythoncontextpy line llwithcontext return funcargskw exception caught file cpythonlibsitepackagestwistedinternetselectreactorpy doreadorwrite getattrselectable method file cpythonlibsitepackagestwistedinternettcppy line ead rval selfprotocoldatareceiveddata file cpythonlibsitepackagestwistedprotocolsbasicpy line datareceived selflinereceivedline file serverpy line linereceived selfsendlinelevel file cpythonlibsitepackagestwistedprotocolsbasicpy line sendline return selftransportwriteline selfdelimiter exceptionstypeerror unsupported operand types int str the line causing error selfsendlinesomevarwhichisanumber,3 don relative import from pep relative imports intrapackage imports highly discouraged put code one super package ie myapp use subpackages client server common code,i folder client code folder server code folder code shared proj client clientpy server serverpy common initpy commonpy how i import commonpy serverpy clientpy,3 the default import method already relative pythonpath the pythonpath default system libraries along folder original source file if run run module current directory gets added pythonpath so entry point program inside proj using import commoncommon work inside serverpy clientpy don relative import it work want,i folder client code folder server code folder code shared proj client clientpy server serverpy common initpy commonpy how i import commonpy serverpy clientpy,2 edit nov years later python x supports proper relative imports avoid anything hacky with method know getting relative import rather absolute import the means go directory common import common as caveat work run python module outside package for example python proj original hacky way this method still commonly used situations actually ever installing package for example popular django users you add common syspath list paths python looks import things import sys os syspathappendospathjoinospathdirnamefile common import common ospathdirnamefile gives directory current python file navigate common directory import common module,i folder client code folder server code folder code shared proj client clientpy server serverpy common initpy commonpy how i import commonpy serverpy clientpy,3 the problem defined dependent columns foreign keys separately really intend course want composite foreign key sqlalchemy responding saying clear way cannot guess foreign key use firstname lastname the solution declaring composite foreign key tad clunky declarative still fairly obvious class bookbase tablename books title columnstring primarykeytrue authorfirstname columnstring authorlastname columnstring tableargs foreignkeyconstraintauthorfirstname authorlastname authorfirstname authorlastname the important thing foreignkey definitions gone individual columns foreignkeyconstraint added tableargs class variable with relationship defined authorbooks works right,i simple model author books find way make firstname lastname composite key use relation any ideas sqlalchemy import createengine foreignkey column string integer sqlalchemyorm import relationship sessionmaker sqlalchemyextdeclarative import declarativebase base declarativebase engine createengine mssqluserpasslibrary engineecho true session sessionmakerengine class authorbase tablename authors firstname columnstring primarykeytrue lastname columnstring primarykeytrue books relationship book backref author class bookbase tablename books title columnstring primarykeytrue authorfirstname columnstring foreignkey authorsfirstname authorlastname columnstring foreignkey authorslastname,3 for record i would encourage different approach search solutions suggested andy t answer yih answer that said answer addresses issue presented question the code present run one answer found stop since finding first answer make solved equal since know solutions change loop condition solved try in response mark comment lead duplicated answers code make sure get different solutions import random def tryparam global solved tryprevsoln opers hotpotato joinparam randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers evalhotpotato hotpotato tryprevsoln solved tryprevsolnappendhotpotato print solution hotpotato else pass solved solved try of course approach assumes solutions if unknown number solutions would know stop thus recommendation another approach finding solutions,i came across fun math problem yesterday solved code i wrote i keyboard interrupt would run forever lol so i changed end condition prints solution stops the problem goes like you numbers order between number must insert either nothing plus sign multiplication sign resulting expression equals write program prints solutions there two import random def tryparam global solved opers hotpotato joinparam randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers evalhotpotato solved print solution hotpotato else pass solved solved try this code prints first solution encounters stops can anyone tell get print solutions stops,1 don use random enumerate possible operator combinations well cut search space bit first couple numbers result larger way result going smaller itertools friend if program finish time if know exactly two solutions return solution try loop till collected two different solutions really elegant,i came across fun math problem yesterday solved code i wrote i keyboard interrupt would run forever lol so i changed end condition prints solution stops the problem goes like you numbers order between number must insert either nothing plus sign multiplication sign resulting expression equals write program prints solutions there two import random def tryparam global solved opers hotpotato joinparam randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers evalhotpotato solved print solution hotpotato else pass solved solved try this code prints first solution encounters stops can anyone tell get print solutions stops,3 store solutions set solutions set each time solution found update set solutionsappendsolution sets nice store duplicates lenset so loop set size greater one lensolved try also shorten code hotpotato joinparam randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers to hotpotato joinparam randomchoiceopers range,i came across fun math problem yesterday solved code i wrote i keyboard interrupt would run forever lol so i changed end condition prints solution stops the problem goes like you numbers order between number must insert either nothing plus sign multiplication sign resulting expression equals write program prints solutions there two import random def tryparam global solved opers hotpotato joinparam randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers evalhotpotato solved print solution hotpotato else pass solved solved try this code prints first solution encounters stops can anyone tell get print solutions stops,2 to receive solutions need completely different approach solve problem check permutations inserted operations how calculate permutations shown httpwwwbearcavecomrandomhackspermutehtml edit example ops def genver lenver return op ops ver veri op veri evalver yield ver j rangei lenver sol genver j yield sol ver veri veri sol gen print solution sol output solution solution,i came across fun math problem yesterday solved code i wrote i keyboard interrupt would run forever lol so i changed end condition prints solution stops the problem goes like you numbers order between number must insert either nothing plus sign multiplication sign resulting expression equals write program prints solutions there two import random def tryparam global solved opers hotpotato joinparam randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers evalhotpotato solved print solution hotpotato else pass solved solved try this code prints first solution encounters stops can anyone tell get print solutions stops,1 if trying write python programs work perforce might find ppython helpful httpwwwperforcecomperforcedoccurrentmanualspscriptpythonhtml,i variable fulltext contains full text i want description new changelist pv there already files default changelist i want use python populate description new changelist based default contents fulltext how done i tried ossytemp change print fulltext but create new change list i know tell p i done editing description,1 yes correct indentation code work you creating new class time function called def checkforjiraissuerecordobject class options pass options options optionsuser user optionspassword password,how i define class options inside checkforjiraissuerecord function def checkforjiraissuerecordobject sysstdout openosdevnull sysstderr openosdevnull class options pass options options optionsuser user optionspassword password try com jiracommands logger jirasetuplogging jiraenv home osenviron home commandcat cat server httpjiraservercomrpcsoapjirasoapservicevwsdl except exception e sysexit config error try jirasoap jiraclientserver jirastartloginoptions jiraenv commandcat com logger issue comruncommandcat logger jiraenv myargs except exception e print sysexit data error name main committextverified verifycommittextospopen hg tip template desc committextverified verifycommittextospopen hg log r template desc committextverified sysexit else print sysstderr obey rules sysexit is possible declare classes within functions python,3 yes although time function called get different class,how i define class options inside checkforjiraissuerecord function def checkforjiraissuerecordobject sysstdout openosdevnull sysstderr openosdevnull class options pass options options optionsuser user optionspassword password try com jiracommands logger jirasetuplogging jiraenv home osenviron home commandcat cat server httpjiraservercomrpcsoapjirasoapservicevwsdl except exception e sysexit config error try jirasoap jiraclientserver jirastartloginoptions jiraenv commandcat com logger issue comruncommandcat logger jiraenv myargs except exception e print sysexit data error name main committextverified verifycommittextospopen hg tip template desc committextverified verifycommittextospopen hg log r template desc committextverified sysexit else print sysstderr obey rules sysexit is possible declare classes within functions python,1 well everybody sorry incomplete sentences overall poor english i wanted make simple read understand someone completely inexperienced sort programming i first day messing stuff eg terminal this result hours googling done one day perhaps someone familiar commands bold wouldn’t mind explaining exactly taking place additionally done terminal macbook pro running mac os lion install macport binary comes installer easy sudo port install pygame sure necessary doesn’t appear cause pygame functional python version stock python lion sudo port select set python python i believe set default python version i also believe downloaded step therefore i think ends necessary step download setuptoolscpytar in folder gasp appears clicking tar place setuppy gasp folder sudo python gaspsetuppy install make sure directory folder gasp sudo port –v install pypygtk takes hour step complete sudo port uninstall pygame step necessary gasp work i simply didn’t want unnecessary stuff computer downloaded second step however step put python computer could install separately i guess way worked lot unnecessary stuff installed step i think it’ll remain even command oh well,i currently trying learn python going how think like computer scientist learning with python i installed python mac osx using idle at end chapter elkner et al refer gasp however instructions work i enter gasp import i get traceback recent call last file pyshell line module gasp import importerror no module named gasp i look around google find outdated methods installation pages gobbledegook i believe i install pyobjc first able accomplish either can anyone please help plain english instructions,1 the solution problem breaking solved but code real problem using random using random algorithm generally bad idea there possibility code lasts century there much simplier faster way using itertools import itertools itertoolsproduct repeat z itertoolsiziplongest fillvalue e joinitertoolschainfromiterablez evale printe there need break two solutions found code already completes seconds,i came across fun math problem yesterday solved code i wrote i keyboard interrupt would run forever lol so i changed end condition prints solution stops the problem goes like you numbers order between number must insert either nothing plus sign multiplication sign resulting expression equals write program prints solutions there two import random def tryparam global solved opers hotpotato joinparam randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers randomchoiceopers evalhotpotato solved print solution hotpotato else pass solved solved try this code prints first solution encounters stops can anyone tell get print solutions stops,3 yes however each time function options becomes separate class not really able write code exploits broken property you instantiate class via function unless explicitly expose global namespace somehow assuming need object attributes ie jira care class interface beyond able user password really need create custom class collections import namedtuple def checkforjiraissuerecordobject options namedtuple options user password user password user password field names user password initialization values this code creates type similar naming options internally bind variable as,how i define class options inside checkforjiraissuerecord function def checkforjiraissuerecordobject sysstdout openosdevnull sysstderr openosdevnull class options pass options options optionsuser user optionspassword password try com jiracommands logger jirasetuplogging jiraenv home osenviron home commandcat cat server httpjiraservercomrpcsoapjirasoapservicevwsdl except exception e sysexit config error try jirasoap jiraclientserver jirastartloginoptions jiraenv commandcat com logger issue comruncommandcat logger jiraenv myargs except exception e print sysexit data error name main committextverified verifycommittextospopen hg tip template desc committextverified verifycommittextospopen hg log r template desc committextverified sysexit else print sysstderr obey rules sysexit is possible declare classes within functions python,1 just parse file gifs pretty simple class giferrorexception pass def getgifnumframesfilename frames openfilename rb f fread gifa gifa raise giferror valid gif file fseek def skipcolortableflags flags amp x fseek flags amp flags ordfread fseek skipcolortableflags true block fread block break block fseek elif block frames fseek skipcolortableordfread fseek else raise giferror unknown block type true l ordfread l break fseekl return frames,i looking kind method get gif frames number looking google stackoverflow outher sites find rubbish someone know need simple number gif frames,3 i new treeview i think i solution this code show values packaged use however like def fullcalc try get list children root node children tvgetchildren child children for odd reason set method actually returns values actually setting something printtvsetchild,i new programming i figure make work i trying figure extract values treeview col function would allow provide simple sum resultdisplay label bottom from i read i need use item method treeview i figure reference properly i tried dumping any value treeview test label using various command configurations none produced anything error basically i want user able hit results button call fullcalc function extract values col add dump sum resultdisplay label using endresult textvariable i way base i appreciate insight give tinker import tkinter tkinter import tkinter import ttk primary window and frame elements root tk roottitle calorie counter entryframe ttkframeroot padding gridcolumn row listframe ttkframeroot padding gridcolumn row resultframe ttkframeroot padding gridcolumn row global variables namevar stringvar calentvar doublevar volentvar doublevar usedentvar doublevar calinvar doublevar uomvar stringvar endresult intvar functions def itemadd try c namevarget c usedentvarget c calinvarget f volentvarget f calentvarget cpv f f tvinserttextc valuesccpvcc except valueerror pass def itemremove try tvdeletetvfocus except valueerror pass def itemupdateargs try calentvarget b volentvarget c b usedentvarget calinvarsetc except valueerror pass def fullcalc try pass except valueerror pass entry frame elements labels namelabel ttklabelentryframe text item name gridcolumn row columnspan calpervollabel ttklabelentryframe text calories volume gridcolumn row columnspan uomlabel ttklabelentryframe text unit measure gridcolumn row columnspan usedlabel ttklabelentryframe text amount used gridcolumn row columnspan incallabel ttklabelentryframe text calories gridcolumn row columnspan variable entrydisplay elements nameentry ttkentryentryframe width textvariablenamevargridcolumn row columnspan calentry ttkentryentryframe width textvariablecalentvargridcolumn row columnspan stickye volentry ttkentryentryframe width textvariablevolentvargridcolumn row columnspan stickyw uomcombo ttkcomboboxentryframe width state readonly textvariableuomvar values grams milliliters teaspoons tablespoons cups gridcolumn row columnspan usedentry ttkentryentryframe width textvariableusedentvargridcolumn row columnspan callabel ttklabelentryframe width textvariablecalinvargridcolumn row columnspan buttons addbutton ttkbuttonentryframe text add item commanditemaddgridcolumn row columnspan stickye removebutton ttkbuttonentryframe text remove item commanditemremovegridcolumn row columnspan stickyw updatebutton ttkbuttonentryframe text calculate commanditemupdategridcolumn row columnspan list frame elements tv ttktreeviewlistframe show headings tvcolumnscol colcolcol tvcolumncolwidth tvcolumncolwidthanchorcenter tvcolumncolwidth tvcolumncolwidth tvheadingcoltextitem tvheadingcoltextcalories per volume tvheadingcoltextvolume used tvheadingcoltextcalories included tvgridcolumn row columnspan result frame elements results ttkbuttonresultframe text calculate total commandfullcalcgridcolumn row resultslabel ttklabelresultframe text total calories gridcolumn row resultsdisplay ttklabelresultframe textvariableendresult program run elements rootmainloop,1 unless number nodesedges large gives bernoulli distribution you get networkx give poisson degree distribution easily import numpy np scipystats import poisson def poissongraphnmu z npzerosn n number nodes rangen zipoissonrvsmu mu expected value gexpecteddegreegraphz return g,i used source code networkx generate random graph poisson degree distribution i change parts codes i need follows import random import networkx import math networkxgeneratorsclassic import emptygraph def gnprandomgraphn p seednone return random graph gnp parameters n int the number nodes p float probability edge creation possible edges nn seed int optional seed random number generator defaultnone my sample z mean degree n number nodes p mathexpzzkmathfactorialk i add k missing this part source gemptygraphn seed none randomseedseed u xrangen v xrangeun randomrandom p gaddedgeuv return g in last part generating edges i understand count degree compare pprobability distribution degreek for looks like generate random number btw but one use domain p compare random number pk,2 it likely lock database threadprocesses trying update record,i send select queries problem i send update insert queries start wait thread respond anymore i sure seems like loop i know must use commit applying changes work here code import psycopg conn psycopgconnectdbname test user postgres host localhost password xx cursor conncursor cursorexecuteupdate recording set rank where id conncommit cursorclose,2 nothing work native list since cannot add methods type defined c you need derive list add method class,i want add method single instance list class example afirst lambda self return self i know work i want something like works like i know good practice i know i whole new class i think possible python figured i aware dynamically add member function instance class python dynamically binding python methods instance correctly binds method names method none work native list thanks,3 finding optimal graph partition nphard problem whatever algorithm going approximation heuristic not surprisingly different clustering algorithms produce wildly different results python implementation newman modularity algorithm modularity also mcl mcode cfinder nemo clusterone,let g graph so g set nodes set links i need find fast way partition graph the graph i working nodes i might soon working equivalent problem another context medicine website development millions nodes so i store links graph matrix mnumpymatnumpyzeroslendatakeyslendatakeys now m holds position st node connected node i make sure m symmetrical mstmts node links mss if i remember well i multiply m m results matrix represents graph connects vertexes reached two steps so i keep multplying m number zeros matrix decrease longer now i list connected components and i need cluster matrix up i pretty satisfied algorithm i think easy elegant reasonably fast i trouble part essentially i need split graph connected components i go nodes see connected but sorting matrix reordering lines but i know possible what follows code far def findzerosm nzeros mflat nzeros return nzeros mnumpymatnumpyzeroslendatakeyslendatakeys datakeys matrixcellsss datakeys ts scipycorrcoefdatatdatasthreashold mst mts nzerosfindzerosm mmm nzerosfindzerosm nzerosnzeros nzerosnzeros mm mmm nzerosfindzerosm edit it suggested i use svd decomposition here simple example problem x graph we shall use since x square matrix easy see clusters import numpy import scipy mnumpymatnumpyzeros m m m m m m m print m usvh numpylinalglinalgsvdm print u print print vh essentially clusters but i still see svn help context,1 what probably making sure works cleanly x passing verifying result works cleanly x that way go hoops redefining range already done,one classes requires assignments completed python exercise i making sure programs work python python using script like binbash run pyunit tests python testpy python testpy one thing i making range work versions piece code import sys backport python range python program run identically versions sysversioninfo range xrange is bad idea edit the reason xrange range work differently python python i want code thing i could way around making python work like python seems stupid since python future here example using range good enough range dosomethingwithi i obviously using list python use insane amount memory,3 translate unreplaced string or replace translated string foo i would like pounds cheese amount,i currently trying implement internationalization application python run error involving string formatting a string marked translatable looks like foo i would like pounds cheese amount running pygettext source tree complains hits line pygettext foobarpy seen unexpected token the resulting messagespot file contain string pygettext done work what way go string formatting gettext,1 you really need fancy regex just use group want researchr this generated number integer group want match number middle known text follow rule r text know text also know,i new regex i starting sort get hang things i string looks like this generated number integer the text i shown around always stay exactly may text either side but number may really one digits i believe i match number folowing text using using integer i write lookbehind part when i try this generated number integer match using regexpalcom tester also would i use python get variable stored int note i want find numbers sandwiched text i shown the string might much longer many numbers,1 try going httplocalhostaccounts slash end that regular django url usually would redirect reason try solve problem make sure works way,i trying setup djangoregistration recognizing urls i get error i visit httplocalhostaccounts page found request method get request url httplocalhostaccounts using urlconf defined namekeeprurls django tried url patterns order pk pkindex admin accounts activatecomplete name registrationactivationcomplete accounts activatepactivationkeyw name registrationactivate accounts register name registrationregister accounts registercomplete name registrationcomplete accounts registerclosed name registrationdisallowed accounts login name authlogin accounts logout name authlogout accounts passwordchange name authpasswordchange accounts passwordchangedone name authpasswordchangedone accounts passwordreset name authpasswordreset accounts passwordresetconfirmpuidbazazptoken name authpasswordresetconfirm accounts passwordresetcomplete name authpasswordresetcomplete accounts passwordresetdone name authpasswordresetdone admin accountsprofile accountspasswordreset accountspasswordresetdone accountspasswordchange accountspasswordchangedone the current url accounts match,1 find minimumarea square encloses points repeatedly subdivide square subsquares going … stop one squares becomes empty it hard prove resulting grid four times coarse optimal solution key insight empty square guaranteed contain least one square grid least twice fine probably constant reduced introducing random translation,given large set tens thousands millions disordered points represented d cartesian vectors good algorithm making regular square grid userdefined spacing encloses points some constraints the grid needs square regular i need able adjust grid spacing length side one squares ideally single variable i want grid minimum size ie every block grid contain least one disordered points every disordered point enclosed block the return value algorithm list coordinates grid points to illustrate d given set points grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes for anyone interested disordered points i working atomic coordinates large protein molecules like get pdb file python preferred solutions although pseudocode also good edit i think first description i needed maybe little fuzzy i added constraints images order clarify things,1 i suggest make kd tree it fastish simple easy implement and wikipedia code class node pass def kdtreepointlist depth pointlist return select axis based depth axis cycles valid values k lenpointlist assumes points dimension axis depth k sort point list choose median pivot element pointlistsortkeylambda point pointaxis median lenpointlist choose median create node construct subtrees node node nodelocation pointlistmedian nodeleftchild kdtreepointlistmedian depth noderightchild kdtreepointlistmedian depth return node you slightly modify though fit within constraints,given large set tens thousands millions disordered points represented d cartesian vectors good algorithm making regular square grid userdefined spacing encloses points some constraints the grid needs square regular i need able adjust grid spacing length side one squares ideally single variable i want grid minimum size ie every block grid contain least one disordered points every disordered point enclosed block the return value algorithm list coordinates grid points to illustrate d given set points grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes for anyone interested disordered points i working atomic coordinates large protein molecules like get pdb file python preferred solutions although pseudocode also good edit i think first description i needed maybe little fuzzy i added constraints images order clarify things,2 how voronoi diagram it generated on log n using fortunes algorithm i know addresses problem voronoi diagrams narural they common nature example wikipedia,given large set tens thousands millions disordered points represented d cartesian vectors good algorithm making regular square grid userdefined spacing encloses points some constraints the grid needs square regular i need able adjust grid spacing length side one squares ideally single variable i want grid minimum size ie every block grid contain least one disordered points every disordered point enclosed block the return value algorithm list coordinates grid points to illustrate d given set points grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes for anyone interested disordered points i working atomic coordinates large protein molecules like get pdb file python preferred solutions although pseudocode also good edit i think first description i needed maybe little fuzzy i added constraints images order clarify things,1 how version disableexistingloggers false formatters standard format asctimes levelnames names messages handlers default level info formatter standard class loggingstreamhandler loggers handlers default level info propagate true djangorequest handlers default level warn propagate false,i like use dictconfig documentation little bit abstract where i find concrete copypasteable example dictionary used dictconfig,3 find appsprojectsreallycool type f grep v e appprojectsreallycoollib e appprojectsreallycoolmodulesappleframeworks xargs wc l cut f awk begintotal total endprint total a notes find important since cut command separate count file name multiline command make sure spaces escaping slashes might need exclude files like svn something also give funny values binary files might want use grep whitelist specific file types interested ie grep e html e css,is quick dirty way either python bash script recursively descend directory count total number lines code we would like able exclude certain directories though for example start appsprojectsreallycoolapp exclude lib frameworks the excluded directories recursive well for example appprojectsreallycoollib should be excluded appprojectsreallycoolmodulesappleframeworks should also be excluded this would really useful utility,2 you would probably want write custom comparator pass sort fact probably need anyway likely getting lexicographical sort order instead intended i presume numerical order for instance know filenames differ digits write comparator extracts digits converts int compares based value taking examples canonical comparator might look something like import def extracts r recompiler dlogdgz rsearchs file intmgroup mgroup return file index intmgroup return file index def comparators return cmpextracts extracts this prefers sort based file number first one index number second one note takes advantage fact using cmp tuples works require,short renamingfixing logging module webservers listsort list entries get placed following order debug main running wwwsitecomloggz debug main running wwwsitecomloggz debug main running wwwsitecomloggz debug main running wwwsitecomloggz debug main running wwwsitecomloggz would sort list get ie entry eithout digit first debug main running wwwsitecomloggz debug main running wwwsitecomloggz debug main running wwwsitecomloggz debug main running wwwsitecomloggz debug main running wwwsitecomloggz thanks,2 found awesome utility cloc httpsgithubcomaldanialcloc here command ran perl clocpl appsprojectsreallycoolapp excludedirlibframeworks and output language files blank comment code php javascript bourne again shell bourne shell html sum,is quick dirty way either python bash script recursively descend directory count total number lines code we would like able exclude certain directories though for example start appsprojectsreallycoolapp exclude lib frameworks the excluded directories recursive well for example appprojectsreallycoollib should be excluded appprojectsreallycoolmodulesappleframeworks should also be excluded this would really useful utility,3 i go easy globals def scriptx z new ns xxfind z new zgeta,i trying combine two functions a i think i b i think i when i use functions separately script works fine when i combine new variable empty string vice any help would appreciated if need full script could arranged function a def stripdomainnamex global ns l xfind ns xl function b def encodeusernamexy global new x new new ygeta function ab def combinedabovescriptxyz global ns global new l xfind ns xl z new new zgeta here simplified version i trying modifications based blender suggestion in end i print aa result which case aa bb encode def stripandencodexyz aa bb xxfind z aa zgeta aaaaaaaaaa stripandencodesbbencode printaa,1 found one spring python databasetemplate,i looking jdbtemplate equivalent python any one saw something similar somewhere,1 it seems likely context entering lastdate longer exists second time reach tag instance perhaps context popped already a sort hackish solution sure insert lastdate highest context lastdate contextdicts contextdicts lastdate date contextdicts lastdate date this kind approach often needed tags writing nested i found incidentally i also found tags sort often hack not say particular case cases,is way maintain state tag calls i need store last item passed tag i created it appeared i could use context seem work here code registersimpletagtakescontexttrue def datedividercontext date lastdate context context lastdate date display new date header context lastdate date return dateheader the problem new date header always created even date passed match date context i guessing i using context wrong is way store last date context better way,1 okay i figured i reinstalled matplotlib source github httpsgithubcommatplotlib instead ordinary python setuppy install i ran makeosx described readmeosx make f makeosx prefixdevjunk pyversion clean fetch deps mplinstallstd and everything works properly,i installing matplotlib use basemap today i install lot stuff make work after installing matplotlib able import i installed basemap i import basemap error mpltoolkitsbasemap import basemap traceback recent call last file line file usrlocalcellarpythonlibpythonsitepackagesmpltoolkitsbasemap init py line matplotlibcollections import linecollection file usrlocalcellarpythonlibpythonsitepackagesmatplotlibcollectionspy line import matplotlibbackendbases backendbases file usrlocalcellarpythonlibpythonsitepackagesmatplotlibbackendbasespy line import matplotlibwidgets widgets file usrlocalcellarpythonlibpythonsitepackagesmatplotlibwidgetspy line lines import lined file usrlocalcellarpythonlibpythonsitepackagesmatplotliblinespy line matplotlibfontmanager import fontproperties file usrlocalcellarpythonlibpythonsitepackagesmatplotlibfontmanagerpy line matplotlib import ftfont importerror dlopenusrlocalcellarpythonlibpythonsitepackagesmatplotlibftfontso symbol found ftattachfile referenced usrlocalcellarpythonlibpythonsitepackagesmatplotlibftfontso expected dynamic lookup so i tried import ftfont python matplotlib import ftfont i got error traceback recent call last file stdin line module importerror dlopenusrlocalcellarpythonlibpythonsitepackagesmatplotlibftfontso symbol found ftattachfile referenced usrlocalcellarpythonlibpythonsitepackagesmatplotlibftfontso expected dynamic lookup any idea i using mac osx python installed homebrew,2 your best bet case use celery this enables create tasks occur background without blocking current request in case save create task updates fields push celery queue return desired response user,i working django application i would like populate several fields within model object first created currently i able save routine model like def saveself args kwargs file fileinfogetfileinfoselffilepath selffilesize selffilesize filefilesize selffileinode selffileinode filefileinode selfduration selfduration fileduration selfframewidth selfframewidth fileimagewidth selfframeheight selfframeheight fileimageheight selfframerate selfframerate filevideoframerate supersourcevideo selfsaveargs kwargs i created function called getfileinfo within separate module called fileinfo this part function looks like def getfileinfosource fstats osstatsource info dict u filesize fstatsstsize u fileinode fstatsstino output subprocesspopen exiftool json source stdoutsubprocesspipe infoupdate jsonloadsoutputcommunicate parsefloatdecimaldecimal return dotdictinfo although works i would like avoid blocking save process retrieval process delayed reason the information needed object creation time could populated shortly thereafter my thought i would alter function accept file path question well primary key object with information i could obtain information update object entry separate operation something like def saveself args kwargs fileinfogetfileinfoselffilepath selfid supersourcevideo selfsaveargs kwargs what i would like help return function prior actual completion i want call function return nothing long called correctly the function continue run however update object end done please let know i need clarify something also thing even something work thanks,1 return totalplayoffprobabilitywp k wp i think meant return playoffprobwp k wp you got error trying treat floating point number function obviously compute edit actually return totalplayoffprobability playoffprobwp k wp as anything totalplayoffprobability calculate if k return value k,working python the following code allows input winning percentage two teams wp wp number wins k determine given two team winning percentages probability team one wins end season playoffprobability def playoffprobwp k wp tprob p floatwp q floatwp n g mathfactorialnmathfactorialkmathfactorialnk prob gpkpnk c range k g mathfactorialnmathfactorialcmathfactorialnc prob gqcqnc tprob prob playoffprobability probtprob print playoffprobability print tprob but would lot easier function could written recursively would perform operation every possible value k return total probability ending season wins i believe given playoffprobability value run function k i tried set equal totalplayoffprobability i tried following code i get typeerror telling float object callable return totalplayoffprobability step i also sure i set recursion appropriately def playoffprobwp k wp tprob totalplayoffprobability p floatwp q floatwp n g mathfactorialnmathfactorialkmathfactorialnk prob gpkpnk c range k g mathfactorialnmathfactorialcmathfactorialnc prob gqcqnc tprob prob playoffprobability probtprob totalplayoffprobability playoffprobability k return totalplayoffprobability else return playoffprobwp k wp any help would greatly appreciated,3 did actually install xcode downloading app store downloads installer then need run installer find installer downloaded applications after run find installnametool installnametool usrbininstallnametool,trying use virutalenv version latest writing post lion yes xcode installed mac app store yet getting error message new python executable supenvbinpython error errno no file directory executing command installnametool change systemlibraryframversionspython executablepathpython supenvbinpython could call installnametool must apple development tools installed traceback recent call last file usrlocalbinvirtualenv line module loadentrypoint virtualenv consolescripts virtualenv file librarypythonsitepackagesvirtualenvpyeggvirtualenvpy line main neverdownloadoptionsneverdownload file librarypythonsitepackagesvirtualenvpyeggvirtualenvpy line createenvironment sitepackagessitepackages clearclear file librarypythonsitepackagesvirtualenvpyeggvirtualenvpy line installpython pyexecutable file librarypythonsitepackagesvirtualenvpyeggvirtualenvpy line callsubprocess cwdcwd envenv file systemlibraryframeworkspythonframeworkversionslibpythonsubprocesspy line init file systemlibraryframeworkspythonframeworkversionslibpythonsubprocesspy line executechild oserror errno no file directory any hints solve problem i guess first would check installnametool present system force virtualenv use thanks advance,2 i know requirements operation takes unacceptable time save acceptable one access i would consider treating filesize duration videoframerate etc lazyloaded properties model assuming longer initial load time decent tradeoff shorter save time there many ways could cache frame rate instance caching framework first time accessed if prefer make something stored database could access frame rate via property calculate values appropriate first time accessed store database theoretically attributes file therefore interface allow changed hence made sync file refer along lines i might something like class mymediafilemodelsmodel file modelsfilefield filesize modelsintegerfieldnulltrue editablefalse duration modelsintegerfieldnulltrue editablefalse etc property def filesizeself selffilesize return selffilesize else selfpopulatefileinfoself return selffilesize def populatefileinfoself thing selffilesize mycalcuatedfilesize etc the logic property easily split general lazyloading property boilerplate need repeated one,i working django application i would like populate several fields within model object first created currently i able save routine model like def saveself args kwargs file fileinfogetfileinfoselffilepath selffilesize selffilesize filefilesize selffileinode selffileinode filefileinode selfduration selfduration fileduration selfframewidth selfframewidth fileimagewidth selfframeheight selfframeheight fileimageheight selfframerate selfframerate filevideoframerate supersourcevideo selfsaveargs kwargs i created function called getfileinfo within separate module called fileinfo this part function looks like def getfileinfosource fstats osstatsource info dict u filesize fstatsstsize u fileinode fstatsstino output subprocesspopen exiftool json source stdoutsubprocesspipe infoupdate jsonloadsoutputcommunicate parsefloatdecimaldecimal return dotdictinfo although works i would like avoid blocking save process retrieval process delayed reason the information needed object creation time could populated shortly thereafter my thought i would alter function accept file path question well primary key object with information i could obtain information update object entry separate operation something like def saveself args kwargs fileinfogetfileinfoselffilepath selfid supersourcevideo selfsaveargs kwargs what i would like help return function prior actual completion i want call function return nothing long called correctly the function continue run however update object end done please let know i need clarify something also thing even something work thanks,1 you use six package provides python compatibility library written one python core developers among features set standard definitions renamed modules functions including xrange range the use six one many recommendations official porting python code python howto included python documentation set,one classes requires assignments completed python exercise i making sure programs work python python using script like binbash run pyunit tests python testpy python testpy one thing i making range work versions piece code import sys backport python range python program run identically versions sysversioninfo range xrange is bad idea edit the reason xrange range work differently python python i want code thing i could way around making python work like python seems stupid since python future here example using range good enough range dosomethingwithi i obviously using list python use insane amount memory,3 based server response defined url accounts root accounts,i trying setup djangoregistration recognizing urls i get error i visit httplocalhostaccounts page found request method get request url httplocalhostaccounts using urlconf defined namekeeprurls django tried url patterns order pk pkindex admin accounts activatecomplete name registrationactivationcomplete accounts activatepactivationkeyw name registrationactivate accounts register name registrationregister accounts registercomplete name registrationcomplete accounts registerclosed name registrationdisallowed accounts login name authlogin accounts logout name authlogout accounts passwordchange name authpasswordchange accounts passwordchangedone name authpasswordchangedone accounts passwordreset name authpasswordreset accounts passwordresetconfirmpuidbazazptoken name authpasswordresetconfirm accounts passwordresetcomplete name authpasswordresetcomplete accounts passwordresetdone name authpasswordresetdone admin accountsprofile accountspasswordreset accountspasswordresetdone accountspasswordchange accountspasswordchangedone the current url accounts match,1 perhaps myargs myargs,let say i myargs qa desired result function i researchazazdline print printing mgroup print mgroup margs mgroup print myargs print margs print typemargs type margs string ie how i convert margs list one element content string,3 you way margs margs,let say i myargs qa desired result function i researchazazdline print printing mgroup print mgroup margs mgroup print myargs print margs print typemargs type margs string ie how i convert margs list one element content string,1 edit working i grabbed complete least complete list html tags w match try fixedstring resubsdoctype aabbracronymaddressappletarea bbasebasefontbdobigblockquotebodybrbutton captioncentercitecodecolcolgroup dddeldfndirdivdldt em fieldsetfontformframeframeset headhhhhhhhrhtml iiframeimginputins kbd labellegendlilink mapmenumeta noframesnoscript objectoloptgroupoption pparampre q ssampscriptselectsmallspanstrikestrongstylesubsup tabletbodytdtextareatfootththeadtitletrtt uul var g bs beautifulsoupfixedstring produces print tr tdlabeltdtdinputtd tr tr tdlabeltdtdinputtd tr print resubsdoctype aabbracronymaddressappletarea bbasebasefontbdobigblockquotebodybrbutton captioncentercitecodecolcolgroup dddeldfndirdivdldt em fieldsetfontformframeframeset headhhhhhhhrhtml iiframeimginputins kbd labellegendlilink mapmenumeta noframesnoscript objectoloptgroupoption pparampre q ssampscriptselectsmallspanstrikestrongstylesubsup tabletbodytdtextareatfootththeadtitletrtt uul var g trtdlabeltdtdinputtd tr tr tdlabeltdtdinputtd tr this one match broken ending tags well endtag resubsdoctypeaabbracronymaddressappletarea bbasebasefontbdobigblockquotebodybrbutton captioncentercitecodecolcolgroup dddeldfndirdivdldt em fieldsetfontformframeframeset headhhhhhhhrhtml iiframeimginputins kbd labellegendlilink mapmenumeta noframesnoscript objectoloptgroupoption pparampre q ssampscriptselectsmallspanstrikestrongstylesubsup tabletbodytdtextareatfootththeadtitletrtt uul var gg,i like know fix broken html tags parsing beautiful soup in following script td needs replaced td how i substitution beautiful soup see beautifulsoup import beautifulsoup tr tdlabeltdtdinputtd tr tr tdlabeltdtdinputtd tr beautifulsoups left right tr afindall tr l r trfindall td leftextendlfindalltexttrue rightextendrfindalltexttrue print left right,1 that pprint print joini,i looked pprint function tried pprint import pprint pprinta but give want is simple way solve,1 add code try import main import pyximport pyximportinstall note pyximport part cython install already,i trying run hadoopy file mainpyx import main failing module found initpy i trying run os x w standard python,3 in order magic happen sample python would need contextsensitive language far i know far django uses modelbase metaclass among tasks set verbose names fields basically metaclass new loops class attributes get attribute names adding options you little direct alter fields directly here python example class fieldobject def initself namenone selfname name def strself selfname return selfname return typeselfname def reprself return ss typeselfname reprselfname class metacontainertype classmethod def dubmetacls name return namereplace capitalize def newcls name bases attrs attr attrs issubclasstypeattrsattr field attrsattrname none attrsattrname metacontainerdubattr return supermetacontainer clsnewcls name bases attrs class containerobject metaclass metacontainer firstname field foo field foobar cntr container cntrfirstname python almost use metaclass class argument rather metaclass property class containerobject metaclassmetacontainer firstname field foo field foobar you write version works metaclasses python creating intermediate base class container using metaclass directly rather metaclass argument metaclass property containerbase metacontainer containerbase object class containercontainerbase firstname field foo field foobar for reason change see pep metaclasses python,see update i even know make short title problem in class i class attributes stringfield class class authorstable id field already present firstname stringfieldmaxlength lastname stringfieldmaxlength stringfield constructor may receive argument called name if given want equal class attribute name firstname lastname example is possible extract name variable created instance going assigned i guess use inspect module i see django each field type except foreignkey manytomanyfield onetoonefield takes optional first positional argument verbose name if verbose name given django automatically create using field attribute name converting underscores spaces in example verbose name person first name firstname modelscharfieldperson first name maxlength in example verbose name first name firstname modelscharfieldmaxlength but find django source code part need update to simplify class field def initself fieldnamenone fieldname fieldname magic determine name printfieldname class table firstname field lastname field running print firstname lastname solution class field def initself namenone selfname name class table firstname field lastname field attrname attr tabledictitems isinstanceattr field attrname none attrname attrname printtablefirstnamename printtablelastnamename,1 docs ref pygamedrawlinesurface color startpos endpos width so need import pygame this makes event handling rect colors simpler now refer sprite rect vs pygamespritesprite pygamerect pygamelocals import pygame import color rect surface def render p p p v p v pygamedrawlinescreen colorwhite p p width note your code simplified using vectors whether numpy euclid code becomes where pos pos velocity vectors pos pos velocity,while running code p selfparticles pos ppos pos ppospvel ppospvel pygamedrawlineselfscreen pcolor pos pos i keep getting error typeerror invalid end position argument so i use print ppos statement see ppos magically works but problem printing makes game run like frames second so i fix error,1 basically tries limit output specific width here example import pprint stuff spam eggs lumberjack knights ni pp pprintprettyprinterwidth pppprintstuff result spam eggs lumberjack knights ni thing change widthsay import pprint stuff spam eggs lumberjack knights ni pp pprintprettyprinterwidth pppprintstuff get spam eggs lumberjack knights ni this modified example python docs httpdocspythonorglibrarypprinthtml for things like i find easier open python interrupter play around see commands react enter,i understand concept clearly could somebody give examples demonstrate concept width pprint python,2 if thing concerned td try mystring resub td td mystring before sending mystring beautifulsoup if broken tags give us examples work,i like know fix broken html tags parsing beautiful soup in following script td needs replaced td how i substitution beautiful soup see beautifulsoup import beautifulsoup tr tdlabeltdtdinputtd tr tr tdlabeltdtdinputtd tr beautifulsoups left right tr afindall tr l r trfindall td leftextendlfindalltexttrue rightextendrfindalltexttrue print left right,1 can put replacement threading module directory make sure directory listed pythonpath want use that mean directory searched default places importing threading python find module stop,question i written replacement threading module python what best method go hooking uses usual threading module standard library the hooking optin per project per executable basis when statement executed import threading i want module loaded instead default note future i may also hook several standard modules solution addresses hooking modules best why i implemented io concurrency via greenlets linux eventfd epoll system calls it works transparently except sysmodules hook replacement socket class looking make hooking nicer consistent,2 add shelltrue argument subprocess calls subprocesscall taskkill f im exenameexe shelltrue or need wait use subprocesspopen rather subprocesscall subprocesspopen taskkill f im exenameexe shelltrue,i wrote statements like ossystemcmd something subprocesscall taskkill f im exenameexe pop console how i stop popping console,3 stuff print continue,i realize title may somewhat confusing i apologize basically code stuff print break now sounds pretty simple right except i really want break loop much i want start so case desired result would iterate break continue iterating how i,3 instead break use continue now i pretty much never use continue i find usually clearer rework code avoid of course really easy example trouble complex example ask one,i realize title may somewhat confusing i apologize basically code stuff print break now sounds pretty simple right except i really want break loop much i want start so case desired result would iterate break continue iterating how i,1 use stringreplace remove words filename then call osrename perform rename newfilename filenamereplace three replace fun osrenamefilename newfilename,i trying figure i could remove certain words file name so file name lolipopthreefunsandi would input three fun would get removed renaming file lolipopsand any ideas start,2 it sounds like using old version app engine sdk you update latest version,if i use following code result urlfetchfetchurlurlgetdevices payload methodurlfetchpost headersheaders deadline i getting error file dworkgaetestpy line get deadline typeerror fetch got unexpected keyword argument deadline but i remove deadline argument works well what wrong,1 edited value want hold node int example showed easy enough node id one children value children value children value children null value children null value,i python binary tree class like class binarytree def initself data leftnone rightnone selfdata data selfleft left selfright right def unicodeself return selfdata i tree traversal function like def treetraversaltree tree nodedata treetraversaltreeleft yield nodedata nodedata treetraversaltreeright yield nodedata i getting stuck generating data format like nested structure id children id children id id tree structure left right,1 how i go class commandobject def executeself canvas raise notimplementederror class drawlinecommandcommand def initself point point selfpoint point selfpoint point def executeself canvas canvasdrawlineselfpoint selfpoint class drawcirclecommandcommand def initself point radius selfpoint point selfradius radius def executeself canvas canvasdrawcircleselfpoint selfradius class undohistoryobject def initself canvas selfcommands selfcanvas canvas def commandself command selfcommandsappendcommand commandexecuteselfcanvas def undoself selfcommandspop throw away last command selfcanvasclear command selfcommands commandexecuteselfcanvas some thoughts trying undo action hard for example would undraw line you need recover used line a simpler approach often revert clean slate reapply commands each command contained single object it store data neccesary command in python need define command class i provide documentation methods i expect command objects implement you may eventually get speed issues reapplying command undo optimization left excersize reader,i read using command pattern one popular ways accomplish doundo functionality in fact i seen possible stack bunch actions reverse order reach given state however i quite sure done python tutorials i read dabble concepts show actual implementation python does anyone know doundo functionality work python for reference naive probably ridden errors code command class drawcommand def initself draw point point selfdraw draw selfpoint point selfpoint point def executedrawingself selfdrawexecuteselfpoint selfpoint def executeundrawingself selfdrawunexecuteselfpoint selfpoint invoker class invokedrawaline def commandself command selfcommand command def clicktodrawself selfcommandexecutedrawing def undoself selfcommandexecuteundrawing receiver class drawaline def executeself point point printdraw line formatpoint point def unexecuteself point point printerase line formatpoint point instantiating follows invokedraw invokedrawaline drawaline drawaline drawcommand drawcommanddrawaline invokedrawcommanddrawcommand invokedrawclicktodraw invokedrawundo output draw line erase line obviously test allow stack several actions undo maybe i completely mistaken i would appreciate help,1 you might try using python metapath hook httpwwwpythonorgdevpepspep it allow add object override part importing process i think able substitute modules standard modules way i sure better patching sysmodules though,question i written replacement threading module python what best method go hooking uses usual threading module standard library the hooking optin per project per executable basis when statement executed import threading i want module loaded instead default note future i may also hook several standard modules solution addresses hooking modules best why i implemented io concurrency via greenlets linux eventfd epoll system calls it works transparently except sysmodules hook replacement socket class looking make hooking nicer consistent,2 for basic renaming hover vim cursor variablemethodetc wish rename type roperename enter from selfexplanatory it asks root path project wish renaming then asks new name then previewconfirm changes if tabcomplete setup vim commandarea look rope features typing ropetab,rope refactoring library python ropevim vim plugin calls rope the idea using ropevim seems great documentation getting started ropevim i followed documentation httpsbitbucketorgagrropevimsrctipreadmetxt i suppose i looking look blog post article link makes make sense alternate recommendations like forget ropevim work well say use instead ropevim,3 here implementation keeping commands list command class drawcommand def initself draw point point selfdraw draw selfpoint point selfpoint point def executedrawingself selfdrawexecuteselfpoint selfpoint invoker class invokedrawlines def initself data selfcommandlist data def addcommandself command selfcommandlistappendcommand def drawself cmd selfcommandlist cmdexecutedrawing def undocommandself command selfcommandlistremovecommand receiver class drawaline def executeself point point printdraw line point point,i read using command pattern one popular ways accomplish doundo functionality in fact i seen possible stack bunch actions reverse order reach given state however i quite sure done python tutorials i read dabble concepts show actual implementation python does anyone know doundo functionality work python for reference naive probably ridden errors code command class drawcommand def initself draw point point selfdraw draw selfpoint point selfpoint point def executedrawingself selfdrawexecuteselfpoint selfpoint def executeundrawingself selfdrawunexecuteselfpoint selfpoint invoker class invokedrawaline def commandself command selfcommand command def clicktodrawself selfcommandexecutedrawing def undoself selfcommandexecuteundrawing receiver class drawaline def executeself point point printdraw line formatpoint point def unexecuteself point point printerase line formatpoint point instantiating follows invokedraw invokedrawaline drawaline drawaline drawcommand drawcommanddrawaline invokedrawcommanddrawcommand invokedrawclicktodraw invokedrawundo output draw line erase line obviously test allow stack several actions undo maybe i completely mistaken i would appreciate help,1 simpler rectcollidepointxy main loop event handling eventtype mousemotion xy eventpos box boxes boxrectcollidepointxy print yay there several collision functions rect sprite see httpwwwpygameorgdocsrefspritehtmlpygamespritespritecollide httpwwwpygameorgdocsrefspritehtml httpwwwpygameorgdocsrefrecthtml,im new pygame right im working sprites my question detect sprite clicked i want something sprite clicked like button thx edited thx stephen in addition way know sprite clicked here sample code boxes pygamespritegroup color location boxesaddupdownboxcolor location example click sprite location program print color location thanks,1 because asking regular square grid userspecified spacing sounds like reasonably straightforward approach work start passing data work minimum maximum coordinate dimension work number steps userspecified spacing required cover distance maximum minimum pass data allocate point cell grid using grid point minimum coordinate specified spacing eg xcell mathfloorxi xmin spacing use dictionary array record number points cell now print coordinates cells least one point you freedom i attempted optimise unless distance minimum maximum coordinate exact multiple grid spacing slop allows slide grid around still contain points moment grid starts position lowest point probably ends highest points room move little dimension as points move cell cell number occupied cells change if consider moves one dimension time work happen reasonably efficiently work distance dimension point maximum coordinate dimension cell sort values as move grid point smallest distance maximum coordinate swap cells first iterate points one one moving sorted order if update counts points cells work shift minimises number occupied cells of course three dimensions worry you could work one time getting reductions number cells this local minimum may global minimum one way look local minima start randomly chosen starting point,given large set tens thousands millions disordered points represented d cartesian vectors good algorithm making regular square grid userdefined spacing encloses points some constraints the grid needs square regular i need able adjust grid spacing length side one squares ideally single variable i want grid minimum size ie every block grid contain least one disordered points every disordered point enclosed block the return value algorithm list coordinates grid points to illustrate d given set points grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes for anyone interested disordered points i working atomic coordinates large protein molecules like get pdb file python preferred solutions although pseudocode also good edit i think first description i needed maybe little fuzzy i added constraints images order clarify things,1 you deleting rect rotate creates you need preserve rect since changes size rotated if want preserve objects location def rotcenterimage angle rotate surface maintaining position loc imagegetrectcenter rotimage defined rotsprite pygametransformrotateimage angle rotspritegetrectcenter loc return rotsprite return tuple surface rect return rotsprite rotspritegetrect,i trying rotate image around center using pygametransformrotate working specifically part hangs rotimage rotimagesubsurfacerotrectcopy i get exception valueerror subsurface rectangle outside surface area here code used rotate image def rotcenterimage angle rotate image keeping center size origrect imagegetrect rotimage pygametransformrotateimage angle rotrect origrectcopy rotrectcenter rotimagegetrectcenter rotimage rotimagesubsurfacerotrectcopy return rotimage,1 the find wc arguments alone solve problem with find specify complex logic like find appsprojectsreallycoolapp type f iname py path lib path frameworks xargs wc l here invert condition command count lines python files lib frameworks directories just dont forget match anything,is quick dirty way either python bash script recursively descend directory count total number lines code we would like able exclude certain directories though for example start appsprojectsreallycoolapp exclude lib frameworks the excluded directories recursive well for example appprojectsreallycoollib should be excluded appprojectsreallycoolmodulesappleframeworks should also be excluded this would really useful utility,3 you could add wrapped attribute partial may already def getself obj objtype support instance methods f functoolspartialselfcall obj fwrapped selffunc return f or could return selffunc instead partial obj none ie accessed class instead instance def getself obj objtype support instance methods obj none return selffunc else return functoolspartialselfcall obj the partial func attribute memoized object call method if call foo instance first argument set instance obj partial see foofooargs then memoizedcall selffuncargs works like poor man bound method for lrucache raymond hettinger python compatible implementations available activestate code recipes there also version least frequently used addition least recently used,normally i would use inspectgetargspec however i get arguments method bound eg i get argument names method foo follows class fooobject memoized def fooself arg arg pass note foofoo memoized object httpwikipythonorgmoinpythondecoratorlibrarymemoize this means really functoolspartial instance how i get original function alternatively obtain arguments somehow if i indicate design flaw pythondecoratorlibrary,1 in experience full solution op problem avoid seeing lambda function message emitted go deeper mylevelnum loggingaddlevelnamemylevelnum mylevelname def logatmyloglevelself message args kws yes logger takes args args selflogmylevelnum message args kws loggerlogatmyloglevel logatmyloglevel i never tried working standalone logger class i think basic idea use log,i like loglevel trace application i think debug sufficient additionally log msg i want how i add custom loglevel python logger i myloggerpy following content import logging property def logobj mylogger logginggetloggerobjclassname return mylogger in code i use following way class exampleclassobject mylogger import log def initself the constructor logger selflogdebuginit runs now i like call selflogtracefoo bar thanks advance help,1 the site object template comes django site model when syncdb defaults automatically examplecom if login django admin interface find sites inside able change examplecom whatever like,the current setup ends substituting examplecom code template i want point localhost without hard coding i change template site linked localhost thank registering account sitedomain to activate registration please visit following page http sitedomain url registrationactivate activationkey this page expire expirationdays day expirationdayspluralize if register account simply delete email bother,3 instead using pyximport build extension modules place python setuppy buildext inplace install inplace development python setuppy develop regular install via python setuppy install for packages almost always want run setup properly configure compilation environment build installation process pyximport good personal scripts using cython speed code eg scientific computing even might need bring libraries build multiple sources in case use pyxbld file set sources includedirs for example say foopyx place build instructions foopyxbld directory for example foopyxbld def makeextmodname pyxfilename distutilsextension import extension return extensionname modname sourcespyxfilename barc includedirs myinclude def makesetupargs return dictscriptargscompilermingw now using foo simple following import pyximport pyximportinstall import foo presuming compilation errors virtually transparent delay first time import module subsequent imports look built extension pyxbld subdirectory homeprofile directory,i trying run hadoopy getting compiling error os x importerror building module failed compileerror command llvmgcc failed exit status n i developerusrbin path running latest version xcode os x lion cython installed via easyinstall full output import pyximport pyximportinstall import hadoopy usersdolanpyxbldtempmacosxintelpyrexhadoopymainc error getdelimh no file directory usersdolanpyxbldtempmacosxintelpyrexhadoopymainc error getdelimh no file directory usersdolanpyxbldtempmacosxintelpyrexhadoopymainc in function ‘pyxfhadoopymainhadoopytaskreadoffsetvaluetext’ usersdolanpyxbldtempmacosxintelpyrexhadoopymainc warning implicit conversion shortens bit value bit value lipo open input file varfoldersbnjpnqnxpvfzhgntcccxexout no file directory traceback recent call last file stdin line module file librarypythonsitepackageshadoopyinitpy line module main import run printdocquit file librarypythonsitepackagescythonpymacosxinteleggpyximportpyximportpy line loadmodule selfpyxbuilddir file librarypythonsitepackagescythonpymacosxinteleggpyximportpyximportpy line loadmodule sopath buildmodulename pyxfilename pyxbuilddir file librarypythonsitepackagescythonpymacosxinteleggpyximportpyximportpy line buildmodule reloadsupportpyxargsreloadsupport file librarypythonsitepackagescythonpymacosxinteleggpyximportpyxbuildpy line pyxtodll distruncommands file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommands selfruncommandcmd file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand cmdobjrun file librarypythonsitepackagescythonpymacosxinteleggcythondistutilsbuildextpy line run buildextbuildextrunself file systemlibraryframeworkspythonframeworkversionslibpythondistutilscommandbuildextpy line run selfbuildextensions file librarypythonsitepackagescythonpymacosxinteleggcythondistutilsbuildextpy line buildextensions selfbuildextensionext file systemlibraryframeworkspythonframeworkversionslibpythondistutilscommandbuildextpy line buildextension dependsextdepends file systemlibraryframeworkspythonframeworkversionslibpythondistutilsccompilerpy line compile selfcompileobj src ext ccargs extrapostargs ppopts file systemlibraryframeworkspythonframeworkversionslibpythondistutilsunixccompilerpy line compile raise compileerror msg importerror building module failed compileerror command llvmgcc failed exit status n,2 you use qt database gui layer if want use sqlalchemy take look camelot update a good introduction qt database gui layer chapter book rapid gui programming python qt,i relatively new database gui programming i want make simple app python allows user access edit database i want viewedit tables specific records plus generate specific reports stored data for example table employees name position allow edit name select position list immediately change database according changes for one employee record output name give selectable list positions also dialog add employees so way create widgets data tables specific records allows output edit data automatic changes database i want reduce need writing methods look changes view reflect model i using pyqt writing gui solutions sql orms like sqlalchemy would fine,1 assuming terminal supports displaying characters iterate list files print individually use python displays unicode lists python default jun msc v bit intel win type help copyright credits license information import os pdf oswalku n f print n ssekã¼nden ssehã¤ndlerpdf also note i used unicode string u path this instructs oswalk return unicode strings opposed byte strings when dealing nonascii filenames good idea in python strings unicode default nonascii characters displayed user instead displayed escape codes python default jul msc v bit intel win type help copyright credits license information import os pdf oswalk printf ssekã¼nden ssehã¤ndlerpdf,file name ssekã¼nden ssehã¤ndlerpdf two unicode char ã¼ã¤ printing file name python interpreter unicode values getting converted respective ascii value guess ssekxnden ssehxndlerpdf want test dir contains pdf file name ssekã¼nden ssehã¤ndlerpdf tried path ctest abc oswalkpath print c ssekxnden ssehxndlerpdf convert ascii chars respective unicode vals want show original name ssekã¼nden ssehã¤ndlerpdf interpreter also writeing file ishow achive i using python windows os thanks,2 abc oswalkpath n c print ndecode utf,file name ssekã¼nden ssehã¤ndlerpdf two unicode char ã¼ã¤ printing file name python interpreter unicode values getting converted respective ascii value guess ssekxnden ssehxndlerpdf want test dir contains pdf file name ssekã¼nden ssehã¤ndlerpdf tried path ctest abc oswalkpath print c ssekxnden ssehxndlerpdf convert ascii chars respective unicode vals want show original name ssekã¼nden ssehã¤ndlerpdf interpreter also writeing file ishow achive i using python windows os thanks,1 use subprocesspopen,i writing test script cs system python and right test client written c it command line based client i want control input get output client python script how could i make thanks,1 use subprocess module follows import subprocess proc subprocesspopencat stdin subprocesspipe stdout subprocesspipe err proccommunicateinput the process ends last call if want input iteratively use procstdinwrite call communicatenone end finish process,i writing test script cs system python and right test client written c it command line based client i want control input get output client python script how could i make thanks,1 i experience grid clustering d implemented example c code httpkunukwordpresscomclusteringgridcluster this handle step handle step you modify code update dspace hope gives ideas the code runs omn number grids n number points,given large set tens thousands millions disordered points represented d cartesian vectors good algorithm making regular square grid userdefined spacing encloses points some constraints the grid needs square regular i need able adjust grid spacing length side one squares ideally single variable i want grid minimum size ie every block grid contain least one disordered points every disordered point enclosed block the return value algorithm list coordinates grid points to illustrate d given set points grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes grid spacing x one possible return value algorithm would coordinates red points dashed lines illustration purposes for anyone interested disordered points i working atomic coordinates large protein molecules like get pdb file python preferred solutions although pseudocode also good edit i think first description i needed maybe little fuzzy i added constraints images order clarify things,1 threading really good choice pygtk just check main loop events expensive loop let thing myoperationrunning code gtkeventspending gtkmainiteration tweak expensive operation run stepbystep using glibidleaddfunction every time main loop something call function make sure function keeps track progress makes one iteration call,is way block pygtk performing expensive operation i know threading would work would take lot code setup thanks,1 as far i know dedicated way python however still use gdbexecutecommand tostringboolean execute cli command python tostring true tell gdb collect output return string cf doc maint print targetstack print layers used internally access inferior you see core local core dump file coredebugging layer active so allinall bit code like gdbexecutemaint print targetstack tostringtrue print local core dump file trick,is way determine whether debugged target core dump live process,1 i little experimenting found numpy specific way solve import numpy np nparangereshape b nparange reshape array b receives entries b b finding common entries c npinda breshapeashape npindb areshapebshape checking common entries exist coordinates indexesc npwherec amp c amp c indexesd npwhered amp amp,i large unsorted arrays structured set xyz coordinates i trying find positions identical subarrays common points consisting coordinates example array b array here correct subarray would one identical subarrays possible the correct indexes would b i already implemented pure python method iterating points one array comparing every point array extremely slow my question efficient way find indexes arrays preferably numpy i need arrays calculations perhaps rollingwindow approach,1 what need make class serializable data structure dictionaries strings i find general way i usually make binarytree implement sort flattening parsing function a good way import json class binarytree def initself data leftnone rightnone selfdata data selfleft left selfright right def flattenself return data selfdata left selfleftflatten selfleft else none right selfrightflatten selfright else none classmethod def fromdictionarycls obj clsddata dhaskeyleft dleft none objleft clsfromdictionarydleft dhaskeyright dright none objright clsfromdictionarydright return obj name main binarytree binarytreefromdictionarydata hello left data yo jsondata jsondumpsbinarytreeflatten print json jsondata binarytreefromjson binarytreefromdictionaryjsonloadsjsondata print binarytreefromjsondata print binarytreefromjsonleftdata,i python binary tree class like class binarytree def initself data leftnone rightnone selfdata data selfleft left selfright right def unicodeself return selfdata i tree traversal function like def treetraversaltree tree nodedata treetraversaltreeleft yield nodedata nodedata treetraversaltreeright yield nodedata i getting stuck generating data format like nested structure id children id children id id tree structure left right,2 since binary calculation problem weird input really area apply pythonic tools like generators list comprehensions itertools def neighborscode n num intcode return num ni rangen if want output sorted ie instead use def neighborssortedcode n num intcode return sortednum rangen,i learning python best way learn language use i thought i make script compares binary words determine ones grey if one bit different flag record number binary code so means example n binary code if i chose first binary code code return results preferably indices my question what best pythonic way mostly i aiming fastest code my reason would better idea optimal way i could compare code would teach far,1 thanks ed gddc i found solution problem turned django shell well turns i set geoslibrarypath cosgeow django settings cosgeowbin calling plain python obviously ignored settings instead relied osown functionality find dll succeeds,i successfully installed geodjango required libraries i set environment variables registry keys yea working windows everything works find command line python djangocontribgisgeos import exit python managepy runserver now server run encounters line code supposed execute says windowserror ntbuaconvexdedsqlexpresseuq error the specified module could found dviewspy module djangocontribgisgeos import cpythonlibsitepackagesdjangocontribgisgeosinitpy module djangocontribgisgeosgeometry import geosgeometry wktregex hexregex cpythonlibsitepackagesdjangocontribgisgeosgeometrypy module djangocontribgisgeoscoordseq import geoscoordseq cpythonlibsitepackagesdjangocontribgisgeoscoordseqpy module djangocontribgisgeoslibgeos import csptr cpythonlibsitepackagesdjangocontribgisgeoslibgeospy module lgeos cdlllibpath cpythonlibctypesinitpy init selfhandle dlopenselfname mode,1 you could take look clonedigger designed detect clones python java code algorithm described,i bunch legacy javascript files looking really similar i like implement copiedpasted code detection tool i unable find description algorithm i already using sonar javascript plugin detect kind code i like finergrained control detection is standard algorithm problem is library perform analysis python java thanks,1 it currently possible install django orm without rest you install whole lot use orm though alternatively might like look one standalone python db wrappersorms the big one sqlalchemy also smaller sqlobject,i starting new python project i love djangolike control database using models sqlite i need django also i want users install dependencies using product are smaller projects deliver djangolike database models possible extract model functionality django include project folder user worry,1 notenodesresplitr details text code text notenodesn else xsl valueof selectn enumeratenotenodes,i wondering anyone come pythonic solution problem i currently trying solve i got source xml file i writing xslt generator the relevant part source xml looks like notes note codeabccode textnote text contentstext note note note notes and i objects anaologous lxmlbuilder import elementmaker this element maker target output namespace trgt elementmakernamespacetargetnamespace xsl elementmakernamespace httpwwwworgxsltransform nsmap xsl httpwwwworgxsltransform this relevant part generator output spec details xpath notesnote node out text code text the aim generate following snippet xslt details object xslforeach selectnotesnote outxslvalueof selectcode xslvalueof selecttextout xslforeach the part i difficulty nicely replacing placeholder text xml nodes i initially tried import text resub xslvalueof select details text xsl foreach trgtnode text selectdetails xpath escapes angle bracket characters even worked i fussy means nicely namespaced elementmakers bypassed i like xslforeach selectnotesnote outampltxslvalueof selectcodeampgt ampltxslvalueof selecttextampgtout xslforeach currently i doesnt feel nice start notenodes match refinditer note textupto notestartmatchstart matchnode selfxsl valueof selectnotematchstartmatchend start matchend notenodesappendtextupto notenodesappendmatchnode textafter notestart notenodesappendtextafter xsl foreach trgtnode notenodes selectdetails xpath is nicer way example split regex list apply function elements matches i overly fussy thanks,1 i think override user model unicode method you create new model like class extendeduseruser inherits djangocontribauthmodelsuser def unicodeself return selffirstname selflastname,trying use filteredselectmultiple widget display list users currently displaying username i tried override labelfrominstance seen seem work get display users full name class usermultiplechoicefieldfilteredselectmultiple custom multiple select feild full name def labelfrominstanceself obj return objgetfullname class ticketformformsform ccto formsmodelmultiplechoicefieldquerysetuserobjectsfilterisactivetrueorderby username widgetusermultiplechoicefieldcc to isstackedtrue,1 i think want use paste mask argument see docs scroll paste pil import image img imageopenbasefile layer imageopenlayerfile file transparent one print layermode rgba imgpastelayer xoff yoff masklayer transparancy layer used mask imgsaveoutfile,i hitting head wall maybe someone help i using pil open png transparent background random black scribbles trying put top another png transparency save third file it comes black end irritating i tell black i tested multiple proposed fixes posts the image opens rgba format still messed also program supposed deal sorts file formats i using pil ironic first format i tried screwy any help would appreciated here code pil import image img imageopenbasefile layer imageopenlayerfile file transparent one print layermode rgba imgpastelayer xoff yoff xoff yoff tests imgsaveoutfile,3 import json data jsondumpsbigstructuregoeshere query update table set json where id returning id cursorpostgresexecutequery data rowid connpostgrescommit,i create json string database values push back database my python code json row cursormysql mainkey row name row value row mainkey n testing name r testing value amp testing json snamesvalues reescapemainkey reescapename reescapevalue json json json print json query update table set json where id returning id json rowid cursorpostgresexecutequery connpostgrescommit insertid cursorpostgresfetchone this code works great malicious characters around however work sprinkled nonalphanumeric values test cases the bad json making db name value name value how sanitize string deserialized json output input,2 on system already string conversion required in typeurlliburlopen httpwwwgooglecom read out type str,i using python i convert output urlliburlopen string data urlliburlopen httpwwwgooglecom read test testone return rendertoresponse homehtml locals homehtml data br test only testone displays browser,1 import urllib data urlliburlopen httpwwwgooglecom read typedata type str it already string,i using python i convert output urlliburlopen string data urlliburlopen httpwwwgooglecom read test testone return rendertoresponse homehtml locals homehtml data br test only testone displays browser,1 you got unprintable character string i get error i append null byte end string print ing show problem import json string uidmethodcheckuserx print string uidmethodcheckuser print reprstring uidmethodcheckuserx jsonloadsstring traceback recent call last file interactive input line module file cpythonlibjsoninitpy line loads return defaultdecoderdecodes file cpythonlibjsondecoderpy line decode raise valueerrorerrmsgextra data end lens valueerror extra data line column line column char print repr string request time see,i got json string i posting python script this example string uidmethodcheckuser in python code i simply call simplejsonloads str str json string request the json string seems fine i print request time intact however i get valueerror extra data line column line column char traceback recent call last file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebappwebapppy line call handlerpostgroups file usersappcontrollerapicontrollerpy line post req simplejsonloads req file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangoutilssimplejsoninitpy line loads return clsencodingencoding kwdecodes file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangoutilssimplejsondecoderpy line decode raise valueerrorerrmsgextra data end lens any ideas may i tried removing new lines tabs slashes string even decoding using decode stringescape,3 from python run bash ossystem ospopen subprocess pass appropriate commandline arguments ossystemr ccygwinbinbash login c bash commands,from windows application written c python i execute arbitrary shell commands my installation cygwin normally launched following bat file echo c chdir ccygwinbin bash login,2 bash accept command args using c flag ccygwinbinbashexe c somecommand combine c exec python ossystem run command,from windows application written c python i execute arbitrary shell commands my installation cygwin normally launched following bat file echo c chdir ccygwinbin bash login,1 i change url wwwexampleorgits worked,i using python i convert output urlliburlopen string data urlliburlopen httpwwwgooglecom read test testone return rendertoresponse homehtml locals homehtml data br test only testone displays browser,1 i think right idea except colors distinguishable pass colormap hsv numbers spread range hsv pltgetcmap hsv hsvfloatilendata using numpy colors hsvnplinspace lenkinds for example import datetime dt import numpy np import matplotlibpyplot plt import matplotlibdates mdates import scipyinterpolate interpolate dates dtdateyear year range listmapmdatesdatenum dates jec pltplotdates jec k markersize newt nplinspacemint maxt newdates mapmdatesnumdate newt kinds cubic quadratic slinear nearest linear zero cmap pltgetcmap jet colors cmapnplinspace lenkinds kind color zipkinds colors newjec interpolateinterpdt jec kindkindnewt pltplotnewt newjec labelstrkind colorcolor pltlegendloc best pltshow,i lot graphs i want plot one plot i started matplotlib find good way generate lot distinguishable colors maybe cycling hsv sv maximum i thinking something like args ixy enumeratedata argsextendxyhsvi plotargs any suggestions,3 you remove comments parsing time parser etreexmlparserremovecommentstrue tree etreeparsexmlfile parserparser or using objectify took hell time find parser objectifymakeparserremovecommentstrue tree objectifyparsexmlfile parserparser,i call following command get following error lxmletreetostringtreegetroot withcommentsfalse valueerror can discard comments cn serialisation i know cn i would appreciate explanation i achieve run foregoing command withcommentsfalse yes i aware i strip comments using regex please offer regular expressions solution background i want transfer xml doc http connection i using lxml python library i running python,3 i familiar webpy framework general web applications need preserve state across multiple requests manage session object the session object separate web user common whole application there session object webpy framework httpwebpyorgdocsapiwebsession it lets decide whether store content session database directly file the code sample diskstore page shows place variable session by way python boolean literals true false true,i want update logfile soon request comes i class variable eventloggingenabled initialised true post function i check value eventloggingenabled now run time i modify value flag false subsequent requests but it remains true during debugging i found request received new object get created handle request pick initialized value ietrue this case functions like getlogenabled class can please suggest work around import web import threading class webserverthreadingthread port eventloggingenabled true def getlogenabledself print stub getlogenabled selfeventloggingenabled def initself threadingthreadinitself logging print initselfeventloggingenabled selfeventloggingfilename uelogslog def runself urls webserver app webapplicationurlsglobals sysargvappendwebserverport apprun def postself print post print stub post logging enabled selfeventloggingenabled,2 the simplest answer still allows pick app want modify code one extra argument includeautocreated djangodbmodels import getapp getmodels app getappappname model getmodelsapp includeautocreatedtrue print modelmetadbtable obviously i got following celope advice read syncdb source thanks documenting exact answer includes app name i wanted possibly others future,how get table names django app i use following code get tables created manytomanyfield djangodbmodels import getapp getmodels app getappappname model getmodelsapp print modelmetadbtable,3 need lambda ii pprinti instead capture current value,code talks pprint import pprint li range liappendlambda pprinti k li k yield thanks ps if i write complete decorator works expected pprint import pprint li range liappendlambda pprinti def closurei def func pprinti return func range liappendclosurei k li k,3 it properly reference thing time list gets populated would value assigned form last item sequence iteration ended seeing,code talks pprint import pprint li range liappendlambda pprinti k li k yield thanks ps if i write complete decorator works expected pprint import pprint li range liappendlambda pprinti def closurei def func pprinti return func range liappendclosurei k li k,2 a simple version based bread first search this code applicable graphs general used binary trees well def printbfslevelsgraphstart queuestart path currlevel levelmembers heightstart childcount print queue queue visnodequeuepop visnode path levelmembers levelmemberschildcount childcount currlevelcurrlevel queuequeuegraphgetvisnode levelmembers levelmemberslevelmembers node graphgetvisnode childcountchildcount heightappendcurrlevelnode pathpathvisnode prevlevelnone vk sortedheight prevlevelv prevlevelnone print n prevlevelv print k return height g printbfslevelsg another version based recursion specific binary tree class bintree node binary tree def initselfvalleftchildnonerightchildnonerootnone selfvalval selfleftchildleftchild selfrightchildrightchild selfrootroot leftchild rightchild selfisexternaltrue def getchildrenselfnode children nodeisexternal return nodeleftchild childrenappendnodeleftchild noderightchild childrenappendnoderightchild return children staticmethod def createtreetuplelist creates binary tree object given tuple list nodes rootnone item treerep root rootbintreeitem rootisexternalfalse nodesitemroot rootrootroot rootleftchildbintreeitemrootroot nodesitemrootleftchild rootrightchildbintreeitemrootroot nodesitemrootrightchild else currentparentnodesitem currentparentisexternalfalse currentparentleftchildbintreeitemrootroot nodesitemcurrentparentleftchild currentparentrightchildbintreeitemrootroot nodesitemcurrentparentrightchild rootnodedictnodes return root def printbfslevelsselflevelsnone levelsnone levelsself nextlevel node levels print nodeval node levels nextlevelextendnodegetchildrennode print n nextlevel nodeprintbfslevelsnextlevel treerep none tree bintreecreatetreetreerep treeprintbfslevels none,to begin question dup one builds taking tree question example how would modify program print rather general i basically looking intuitions efficient way i got method involving appending result list looping a efficient way might store last element level popped print new line afterward ideas,1 in version ply reason occurs related expressions converted docstrings patterns looking source really help line lexpy c recompilepss fnamefdoc reverbose selfreflags i recommend relying something like versions part magic ply works,i using ply noticed strange discrepancy token match stored tlexlexmatch compared srepattern defined usual way module the groupx seem i defined simple lexer illustrate behavior i seeing import plylex lex tokens char def tchart r tvalue tlexerlexmatch return l lexlex i get warning terror ignore now i feed input lexer get token linput hello ltoken i get lextokencharsresrematch object xfbeb i want look match object value so i look groups mgroup h i expect mgroup h i expect mgroup h yet i would expect group compare creating regular expression manually import p recompiler pmatch hello this gives different groups mgroup h i expect mgroup h i expect mgroup gives indexerror group i expect does anyone know discrepancy exists,2 if want use default argument could introduce bugs accidentally called argument use nested lambda pprint import pprint li range liappendlambda x lambda pprintxi k li k this anonymous version closure function,code talks pprint import pprint li range liappendlambda pprinti k li k yield thanks ps if i write complete decorator works expected pprint import pprint li range liappendlambda pprinti def closurei def func pprinti return func range liappendclosurei k li k,2 at present google app engine production servers run python you using python development server well different environment testing production leads scenarios example use syntax valid passes tests fine unexpectedly gives frustrating errors deployed production it noted python runtime production servers currently trusted testers stage available use next months best stay development,hi trying install google app engine windows msi two python version windows one python python python path set environmental variables google app engine detecting python default prerequisite makes google app engine detect python let use python change later,2 ed didn actually need returns syntax instead out suggestion put onto answer and yes i feel like real dummy this beauty others review one work return result added things work nicely key assumption i made result syntax actually finish return within scope calling function doh create or replace function myfunction input int out result int as result mymoduleobjectinputplpy plpyinfo extramodule result result this key bit return result language plpythonu,is reason function call would return result create or replace function myfunction input int out result int as result mymoduleobjectinputplpy plpyinfo extramodule result result language plpythonu content mymodule def objectinputplpy import stringio try plan plpyprepareinsert into file values nextval primarysequence returning primarykey integer except plpyerrortracebackformatexc try rv plpyexecuteplan input result rvprimarykey plpyinfo intramodule result result return result except plpyerrortracebackformatexc,1 you looking combo box widget ttk provides widget httpdocspythonorgdevlibrarytkinterttkhtml httpwwwtkdocscomwidgetscomboboxhtml,how i generate normal selection list like state field html form postal addresses using python tkinter as illustrated listbox widget displays selections large box time reduce height expand list selected the optionmenu widget pops list correctly selected display current value entrylike box closed and entry widget desired appearance associated list values please tell tkinter basic form selection tkinter import class app def initself master frame framemaster framepack items apple banana cherry selflist listboxframe width height item items selflistinsertend item selflistpacksideleft fruit stringvar fruitsetitems selfmenu optionmenuframe fruit items selfmenupacksideleft selfentry entryframe width selfentryinsert items selfentrypacksideleft root tk app approot rootmainloop,1 you surely killing resources just query external web service save uri polled use cache dbthen periodic task collects results ready,i need write bunch tasks every task needs query external web service the web service always replies accepted status points location header uri result polled the time takes web service deliver result vary seconds minute i wondering whats best approach program celery task for i send request start loop till i successfully poll result eg true result pollwebservice result break else timesleep continue rest task while certainly works seems crude also i block celery worker till result polled is better approach,1 what asking called combobox if using old version python use tixcombobox for python beyond use ttkcombobox link points python documentation widget python,how i generate normal selection list like state field html form postal addresses using python tkinter as illustrated listbox widget displays selections large box time reduce height expand list selected the optionmenu widget pops list correctly selected display current value entrylike box closed and entry widget desired appearance associated list values please tell tkinter basic form selection tkinter import class app def initself master frame framemaster framepack items apple banana cherry selflist listboxframe width height item items selflistinsertend item selflistpacksideleft fruit stringvar fruitsetitems selfmenu optionmenuframe fruit items selfmenupacksideleft selfentry entryframe width selfentryinsert items selfentrypacksideleft root tk app approot rootmainloop,1 simple print bell character in python print from bash shell echo note terminals bell disabled in others bell replaced visual bell shape flashing screen background,how i generate audio bell xterm type terminal,3 for simple beep print the control codes listed page characters make terminal perform action,how i generate audio bell xterm type terminal,1 printa python print python see docs,how i generate audio bell xterm type terminal,1 if know locale always en enus enus stated comment need regex locale thestring localestartswith en locale locale locale locale locale thestring code en enus enus codeendswithlocale break else locale found you could add checks data could contain something looked like locale check underscore plus two characters however regex fixed simplified bit recompiler pbasecodeazpextcodeazaz since codes always two characters want you want accept either lower upper case second code it still false positives though,problem getting locale string like menutitleenus menutitleen the locale string would enus the string deal alphanumeric characters underscores like variable names python i tried following regex far recompiler pbasecodeazpextcodeaz working fine strings like menuen menuenus stings like menutitleen menutitleenus working expected extracting en enus maybe someone quick idea solve problem,1 you could try use default value like euamount eusalesaggregateprice sum amount price vat but cleanest way probably test sum returns nothing display kind warning message nt happen,i django app manages vat for instance calculate vat sales european union vat purchasesvatvat eusales saleobjectsfiltercountrytype euamount eusalesaggregateprice sum amount price vat however today i copyied files another machine then i received error unsupported operand types nonetype decimal i realised i getting error euamount value stored yet in overwords vale euamount cannot multiply decimal value here i template euamount is way filter template tag i want say something like value value none null,1 i know enough pyusb deal second issue tkinter one used gui python here sample code found show mouse position mouse moved create hot spot import tkinter tk root tktk def showxyevent xm eventx ym eventy str mouse xd yd xm ym roottitlestr switch color red mouse enters set location range x delta range absxm x delta absym delta frameconfigbg red else frameconfigbg yellow frame tkframeroot bg yellow width height framebindmotion showxy framepack rootmainloop yet seems like cannot change cursor position tkinter see thread workarounds but trying set position within text use widget described so thread tkinter set cursor position to disable mouse could look post adapt code disable mouse instead touchpad post gives interesting keys begin,i make application followings disable given usb mouse move pointer screen given mouses get coordinates mouse pointer change coordinate mouse pointer i tried pyusb never found examples problems any ideas,1 how following def decoratordecorated class decdecorated def callself print decorated call return decoratedcallself return dec decorator class fooobject def callself print original call f foo how i make true print isinstancef foo with code isinstancef foo works f calls decorated method forwards original method the basic idea make sure decorated foo still class also make sure decorated foo subclass original foo ps the purpose entirely clear might metaclasses better way achieve trying,how python isinstance function work internally is anything i alter results like define special function inside class something here use case class decorator def initself decorated selfdecorated decorated def callself return selfdecorated decorator class foo pass f foo how i make true isinstancef foo decorator acts almost like mixin except mixing appropriate is way i make code work i also note isinstance line also gives following error nbspnbspnbspnbspisinstancef foo typeerror isinstance arg must type tuple types,2 the problem foo example class this code decorator class foo pass equivalent class foo pass foo decoratorfoo which means foo instance class decorator because foo clas type isinstance complains,how python isinstance function work internally is anything i alter results like define special function inside class something here use case class decorator def initself decorated selfdecorated decorated def callself return selfdecorated decorator class foo pass f foo how i make true isinstancef foo decorator acts almost like mixin except mixing appropriate is way i make code work i also note isinstance line also gives following error nbspnbspnbspnbspisinstancef foo typeerror isinstance arg must type tuple types,1 you want look filefield fieldfile django docs especially fieldfilesave basically field declared filefield accessed gives instance class fieldfile gives several methods interact underlying file so need selflicensefilesavenewname newcontents newname filename wish assigned newcontents content file note newcontents must instance either djangocorefilesfile djangocorefilesbasecontentfile see given links manual details the two choices boil using file f open pathtofile selflicensefilesavenewname filef using contentfile selflicensefilesavenewname contentfile a string file content,here model what i want generate new file overwrite existing one whenever model instance saved class kittenmodelsmodel clawsize licensefile modelsfilefieldblanktrue uploadto license def saveself args kwargs generate new license file overwriting previous version update file path selflicensefile superrequestselfsaveargs kwargs i see lots documentation upload file but i generate file assign model field django store right place,3 you need share session session identifier probably stored cookie mechanize browser this easy definitely portable browsers want however appears support mechanize sqlite database format firefox uses since version httpsgithubcomjjleemechanizeblobmastermechanizefirefoxcookiejarpy you may want check documentation,i almost working code connect server search but issue code this i following python script i login site construct url search result access search page open browser but issue i facing i getting session expired page but i logged page openmanually browser constructed url giving desired output so question how i keep logged session script active open constructed url browser yield desired output usrbinenv python import urllib urllib cookielib mechanize webbrowser subprocess mechanize import parseresponse urlopen urljoin def main usr sg pwd gk loginurl httpintslafindherenetlogininqactampsitesuperarms searchurl ampneedairyesampneedrailnoampneedtrainnoampneedhotelnoampneedcarnoamporiginrequestregularbookingampmonabbrlistampmonabbrlistampdatelistampdatelistamppickupcityamppickuptimeampdropoffcityampdropofftimeampdispaoptionsampdispadestinationsampchecksurroundingairportsfalseampdoencodedecodeforsurrarptfalseampcheckplusminusdaysnamptriptyperoundtripampitintypeonampdepartlistblrampdestinationlistdelampdateffamptravelmethodlistdepartsamptimelistampdateffamptravelmethodlistdepartsamptimelistampnumpassengersampcabinclassamppricingtypeamppreferredcarrieramppreferredcarrieramppreferredcarrierampuserrequestedwebfarestrue br mechanizebrowser cj cookielibcookiejar brsetcookiejarcj brsethandlerobotsfalse braddheaders useragent mozilla windows nt wow rv gecko firefox bropenloginurl brselectform loginform brform user usr brform pwd pwd brsubmit print brgeturl response urlopenloginurl forms parseresponseresponse backwardscompatfalse form forms token forms token siteid forms siteid site forms site watermark forms watermark transindex forms transindex searchurl httpintslafindherenetpwairavailact site site ampsid ampsiteid siteid ampwatermark watermark amptoken token amptransindex transindex searchurl print searchurl print token print siteid print site print watermark print transindex print form responseread inserting code generate html display overlay htmlstring html head titledirectbook title script typetextjavascript srchttpajaxgoogleapiscomajaxlibsjqueryjqueryminjsscript script typetextjavascript srcfxjqueryfancyboxpackjsscript link relstylesheet typetextcss hreffxjqueryfancyboxcss mediascreen script typetextjavascript documentreadyfunction urllinkfancybox width height autoscale false transitionin fade transitionout fade type iframe script head body onloaddocumentgetelementbyid urllink click div idcontent script typetextjavascript var searchurl searchurl documentwrite idurllink href searchurl script div body html write html file working folder fout opensearchhtml w foutwritehtmlstring foutclose subprocesspopen cprogram filesmozilla firefoxfirefoxexe cpythonmechanizesearchhtml name main main,1 you could pass dict eval locals that allow resolve download upload names keys dict b eval ab globals,i work evaluating log data saved json objects file to facilitate work i created small python scripts filter logged entries according regular expressions print multiple fields event now i like able evaluate simple mathematical operations printing fields this way i could say something like printpy type downloadupload would print type upload download ratio my problem i use eval values actually inside dict is simple solution,1 eval optionally takes globals locals dictionaries you therefore namespace dictfoo bar print eval foobar namespace keep mind eval evil safe executed string cannot trusted it fine helper script though for completness also astliteraleval safer evaluates literals means way give dict,i work evaluating log data saved json objects file to facilitate work i created small python scripts filter logged entries according regular expressions print multiple fields event now i like able evaluate simple mathematical operations printing fields this way i could say something like printpy type downloadupload would print type upload download ratio my problem i use eval values actually inside dict is simple solution,1 yes import random class attributeobject def initself selfvalue def getself selfvalue randomrandom return selfvalue def funcfn return lambda fn att attribute myfunc funcattget print myfunc print myfunc in future please make sure code post free syntax errors actually say,consider following pseudocode class atrributeobject def initself selfvalue def get selfvalue random def funcvar lambda var return var myfunc funcattributeget myfunc myfunc now i call myfunc line i get random value plus one produced get function attribute the problem i call myfunc line i get random value line is anyway i make python initiate get function line produce new random value meir,2 how def myfunc return random,consider following pseudocode class atrributeobject def initself selfvalue def get selfvalue random def funcvar lambda var return var myfunc funcattributeget myfunc myfunc now i call myfunc line i get random value plus one produced get function attribute the problem i call myfunc line i get random value line is anyway i make python initiate get function line produce new random value meir,1 i also experiencing issue however i get error intermittently i found another post referring possible solution helps i get error less fixed issue completely the problem seems exchange server closes connection sending valid response if anyone else add i would greatly appreciate this one driving crazy perhaps may help urllib throwing error url opening properly browser i sure already i needed setup script download messagesxsd typesxsd serviceswsdl locally patch following def setupself patches wsdl file include service tag returns path local wsdl file trans selftransport try makedirsselflocaldir except oserror directory already exists pass download messagsxsd file messagesurl smessagesxsd selfurlprefix open ss selflocaldir messagesxsd w msgxsd msgxsdwritetransgeturlmessagesurl transauthtype download typesxsd file typesurl stypesxsd selfurlprefix open ss selflocaldir typesxsd w typesxsd typesxsdwritetransgeturltypesurl transauthtype modify wsdl add service description serviceurl sexchangeasmx selfurlprefix servicexml wsdlservice nameexchangeservices wsdlport nameexchangeserviceport bindingtnsexchangeservicebinding soapaddress locations wsdlport wsdlservice wsdldefinitions serviceurl localwsdl ss selflocaldir serviceswsdl wsdlxml transgeturlselfwsdl transauthtype openlocalwsdl w wsdl wsdlwritewsdlxmlreplace wsdldefinitions servicexml return localwsdl hopefully point right direction simply talking exchange suds major challenge i found help well sample code provided base project httplistsfedoraprojectorgpipermailsudsseptemberhtml update sending correct soap headers requestserverversion xml version encodingutf soapenvelope soapheader trequestserverversion versionexchange soapheader soapbody soapbody soapenvelope i truncated xml brevity,im trying send email via exchange web services using suds import suds sudsclient import client sudstransporthttps import windowshttpauthenticated url filecserviceswsdl user domainuser password hardtoguess ntlm windowshttpauthenticatedusernameuserpasswordpassword c clienturl transportntlm xml soapenvelope xmlnssoaphttpschemasxmlsoaporgsoapenvelope xmlnsxsihttpwwwworgxmlschemainstance xmlnsxsdhttpwwwworgxmlschema soapbody createitem messagedispositionsendandsavecopy xmlnshttpschemasmicrosoftcomexchangeservicesmessages saveditemfolderid distinguishedfolderid idsentitems xmlnshttpschemasmicrosoftcomexchangeservicestypes saveditemfolderid items message xmlnshttpschemasmicrosoftcomexchangeservicestypes itemclassipmnoteitemclass subjectsent via pythonexchangeewssubject body bodytypetextthis message sent via python exchange ews body torecipients mailbox emailaddressimranazadlocalhostemailaddress mailbox torecipients message items createitem soapbodysoapenvelope attr cservicecreateiteminject msg xml xml soapenvelope xmlnsxsihttpwwwworgxmlschemainstance xmlnsxsdhttpwwwworgxmlschema xmlnssoaphttpschemasxmlsoaporgsoapenvelope xmlnsthttpschemasmicrosoftcomexchangeservicestypes soapbody resolvenames xmlnshttpschemasmicrosoftcomexchangeservicesmessages xmlnsthttpschemasmicrosoftcomexchangeservicestypes returnfullcontactdatatrue unresolvedentryazadiunresolvedentry resolvenames soapbody soapenvelope attr cserviceresolvenamesinject msg print attr i able authenticate fine however i keep getting following error traceback recent call last file soappy line module c clienturl transportntlm file buildbdistwineggsudsclientpy line init file buildbdistwineggsudsreaderpy line open file buildbdistwineggsudswsdlpy line init file buildbdistwineggsudswsdlpy line buildschema file buildbdistwineggsudsxsdschemapy line load file buildbdistwineggsudsxsdschemapy line openimports file buildbdistwineggsudsxsdsxbasicpy line open file buildbdistwineggsudsxsdsxbasicpy line download file buildbdistwineggsudsxsdschemapy line instance file buildbdistwineggsudsxsdschemapy line init file buildbdistwineggsudsxsdschemapy line openimports file buildbdistwineggsudsxsdsxbasicpy line open file buildbdistwineggsudsxsdsxbasicpy line download file buildbdistwineggsudsxsdschemapy line instance file buildbdistwineggsudsxsdschemapy line init file buildbdistwineggsudsxsdschemapy line openimports file buildbdistwineggsudsxsdsxbasicpy line open file buildbdistwineggsudsxsdsxbasicpy line download file buildbdistwineggsudsreaderpy line open file buildbdistwineggsudsreaderpy line download file buildbdistwineggsudstransporthttpspy line open file buildbdistwineggsudstransporthttppy line open file buildbdistwineggsudstransporthttppy line uopen file cpythonliburllibpy line open response selfopenreq data file cpythonliburllibpy line open open req file cpythonliburllibpy line callchain result funcargs file cpythonliburllibpy line httpopen return selfdoopenhttplibhttpconnection req file cpythonliburllibpy line doopen r hgetresponse file cpythonlibhttplibpy line getresponse responsebegin file cpythonlibhttplibpy line begin version status reason selfreadstatus file cpythonlibhttplibpy line readstatus raise badstatuslineline httplibbadstatusline any advice would much appreciated thanks,1 i sure i happy simple class dunderdicthiderobject dict fake dict ddh dunderdicthider ddha ddhb print ddha print ddhdict fake dict the problem class cheating fix class dictunhiderobject pass ddhclass dictunhider print ddha print ddhdict b and this completely fails though class defines slots class doesnthavedictobject slots b dhd doesnthavedict dhda dhdb print dhda dhdclass dictunhider traceback recent call last file stdin line module typeerror class assignment doesnthavedict object layout differs dictunhider,i interested whether way introspect python instance infallibly see dict despite obstacles programmer might thrown way would help debug problems like unintended reference loops dangling resources like open files a simpler example i see keys dict subclass programmer hidden keys behind class the way around manually call dict keys method instead letting inheritance call subclass version method simple example getting real info instance class keyhidingdictdict def keysself return keys khd keyhidingdicta b c khdkeys drat returns dictkeyskhd aha returns b c now actual question i see dict instance matter programmer might done hide if set dict class variable seems shadow actual dict objects inherited class my actual question class dunderdicthiderobject dict fake dict ddh dunderdicthider ddha ddhb print ddha prints print ddhdict drat prints fake dict this false value dict see interfere actual attribute setting getting mislead dir hiding b displaying fake object instance variable instead again goal write tool helps introspect class instances see “what really going on” i wondering set class instances taking much memory holding many files open — even though situation extremely contrived finding way around would let tool work time instead saying “works great unless class looking has… description exceptional situation above” i thought i would able infallibly grab dict something like dictdescr objectdict dict print dictdescrddh dunderdicthider but turns object dict descriptor instead subtypedict c function seems get separately attached subclass object programmer creates central way name fetch descriptor manually applied objects whose class shadows any ideas anyone,1 that problem import since colorswitcher static method must first create class instance call member function eventtype pygamemousebuttondown menusmenucolorswitchercounter screen alternatively declare class class menu staticmethod def colorswitchercounter screen use menusmenucolorswitchercounter screen,i writing dummy code pygame the first sample code function menuspy file i wanted practice using import this works fine i wanted put function class i get running classes this second block code unfortunately second block code run could someone explain i going wrong please menuspy def colorswitchercounter screen black white green red colors black white green red screenfillcolorscounter gamepy stuff eventtype pygamemousebuttondown menuscolorswitchercounter screen stuff this works fine this menuspy class menu def colorswitcherself counter screen black white green red colors black white green red screenfillcolorscounter gamepy stuff eventtype pygamemousebuttondown menusmenucolorswitchercounter screen stuff typeerror unbound method colorswitcher must called menu instance first argument got int instance instead could someone tell i wrong class please,1 you trying call instance method class method two solutions change client code call method instance class menusmenucolorswitchercounter screen note parentheses menu change definition change instance method class method using class method annotation,i writing dummy code pygame the first sample code function menuspy file i wanted practice using import this works fine i wanted put function class i get running classes this second block code unfortunately second block code run could someone explain i going wrong please menuspy def colorswitchercounter screen black white green red colors black white green red screenfillcolorscounter gamepy stuff eventtype pygamemousebuttondown menuscolorswitchercounter screen stuff this works fine this menuspy class menu def colorswitcherself counter screen black white green red colors black white green red screenfillcolorscounter gamepy stuff eventtype pygamemousebuttondown menusmenucolorswitchercounter screen stuff typeerror unbound method colorswitcher must called menu instance first argument got int instance instead could someone tell i wrong class please,1 i wanted put function class i get running classes it simple you really really really need complete python tutorial shows objectoriented programming you rarely call method class rarely you create instance class object call methods object not class the object x menu xcolorswitchercounter screen,i writing dummy code pygame the first sample code function menuspy file i wanted practice using import this works fine i wanted put function class i get running classes this second block code unfortunately second block code run could someone explain i going wrong please menuspy def colorswitchercounter screen black white green red colors black white green red screenfillcolorscounter gamepy stuff eventtype pygamemousebuttondown menuscolorswitchercounter screen stuff this works fine this menuspy class menu def colorswitcherself counter screen black white green red colors black white green red screenfillcolorscounter gamepy stuff eventtype pygamemousebuttondown menusmenucolorswitchercounter screen stuff typeerror unbound method colorswitcher must called menu instance first argument got int instance instead could someone tell i wrong class please,1 do literally need tuple or want values grouped you create numpy record array arbitrary shapes fields nparray abc cba dtype array abc cba dtype f s f this works even ndimensional arrays nparray abc cba dtype array abc cba dtype f s f partially applied specific problem desc names name color formats f colorlist nparray abc cba desc colorlistcolorlist name abc color array dtypefloat using recfromarrays generate record array two regular arrays desc names name color formats f nprecfromarrays abc cba desc array dtypefloat a full solution colorquery cursorexecuteselect r g b from colorsfetchall namequery cursorexecuteselect name from colorsfetchall desc names name color formats f colorlist nprecfromarrayscolorquery namequery desc if reason split query like split results query perhaps using list comprehension colorlist nprecfromarraysrow row query row row query desc,i currently reading colors sqlite database following way import numpy np apsw connection apswconnectiondbname cursor connectioncursor desc names name r g b formats float float float colorlist nparraycursorexecuteselect name r g b from colorsfetchalldesc but i hoping read data numpy array two columns second column tuple containing rgb ie something like desc names name color formats floattuple colorlist nparraycursorexecuteselect name r g b from colorsfetchalldesc i want simplify later statements i extract color array tuple eliminate need create dictionary colorlistcolorlist name bos color thanks,2 you need create instance menu call method for example mymenu menu mymenucolorswitchercounter screen you currently treating colorswitcher class method,i writing dummy code pygame the first sample code function menuspy file i wanted practice using import this works fine i wanted put function class i get running classes this second block code unfortunately second block code run could someone explain i going wrong please menuspy def colorswitchercounter screen black white green red colors black white green red screenfillcolorscounter gamepy stuff eventtype pygamemousebuttondown menuscolorswitchercounter screen stuff this works fine this menuspy class menu def colorswitcherself counter screen black white green red colors black white green red screenfillcolorscounter gamepy stuff eventtype pygamemousebuttondown menusmenucolorswitchercounter screen stuff typeerror unbound method colorswitcher must called menu instance first argument got int instance instead could someone tell i wrong class please,1 in example missing query you check view submissions really loaded something like submission submissions print submissionid submissiontitle watch console loading page then confirmed really loaded access link object submissionlink in link object access link attribute link submission submissions print submissionlinklink so template could write thinglinklink,i sure title question i also simplified code easier ask say i following code myprojectmodels pyramid class linksbase tablename links id columninteger primarykeytrue link columntext def initself link selflink link class submissionsbase tablename submissions id columninteger primarykeytrue title columntext linkid columninteger foreignkey linksid link relationshiplinks def initself title link selftitle title selflink link the view simple def myviewrequest dbsession dbsession submissions dbsessionquerysubmissions return submissions submissions i want return page using chameleon p talrepeatthing submissions thingtitle thinglink p however thinglink show link site questions how i reference thinglink link intuitively i would type thinglinklink work how i reference arbitrary subclass i want able extract attribute object subclass example thinglinklink thinglinkdomain thinglinkcreated etc btw someone please tell better title give question,1 you need use getstringvalue method instead enumkey import winreg import wmi c wmiwmicomputer userdevuser passworddevpassnamespacerootdefaultstdregprov result imagepath cgetstringvalue hdefkeywinreghkeylocalmachine ssubkeynamesystemcontrolsetservicesmrxdav svaluenameimagepath print imagepath,i trying retrieve values inside registry object retrieved using python wmi import winreg import wmi c wmiwmicomputer userdevuser passworddevpassnamespacerootdefaultstdregprov result names cenumkey hdefkeywinreghkeylocalmachine ssubkeynamesystemcontrolsetservicesmrxdav item names print item output encrypteddirectories parameters security enum i want retrieve value string imagepath present inside directory hkeylocalmachinesystemcontrolsetservicesmrxdav the part i want retrieve provided image,1 same problem answer reinstall pygtk grampy page it problem pygtk system gtk before import pygtk works well,i installed latest versions python gtk pygtk friends respective websites windows xp sp when try import gtk glib matter importerror raised python r mar msc v bit intel win type help copyright credits license information import gtk traceback recent call last file stdin line module file cpythonlibsitepackagesgtkgtkinitpy line module import gobject gobject file cpythonlibsitepackagesgtkgobjectinitpy line module glib import spawnasync idleadd timeoutadd timeoutaddseconds file cpythonlibsitepackagesgtkglibinitpy line module glibglib import importerror dll load failed the specified procedure could found this working machine around months ago although time around i reinstalled i tried different versions libraries still get work there couple pages relating suggest solution i unable find one,1 make sure directory app pythonpath,i several applications django project i would like reuse functions across apps i created new app added custom functionspy trying following mynewapp import mynewapp import functions i get nameerror global name xxx undefined am i omitting something important how would recommend i solve problem reusing code across multiple apps thanks,2 i similar problem handler set urlspy file also import docs add handler imports djangoconfurlsdefaults import patterns include url handler set handlerstringoftheviewtoload handlermyappviewspagenotfound define view viewpy usual view,i want able use extra variables custom template html extravar i already tried urlspy myprojectmyapp import views handler viewshandler viewspy djangotemplate import requestcontext loader django import http def handlerrequest extravar myextravar loadergettemplate html return httphttpresponsenotfoundtrenderrequestcontextrequest requestpath requestpath extravar extravar however seem work i access requestpath,2 have look google charts tools httpcodegooglecomapischart,i tasked producing analytic tool data get activities company work clients last week made mock view one possible graph using php flot jquery graphing tool unfortunatly i dont think i going able use flot need long term make graph needed work i hack divs one top otherwise got flat line so looking technologies work tool one senior members recommends using django framework graphs using reportlabs matplotlib i spent last couple days looking decent tutorials produce graphs using report labs matplotlib using django display unfortunately havent able find much use examples found django site werent terriably useful examples give something like drawing drawing data bc verticalbarchart bcx bcy bcheight bcwidth bcdata data bcstrokecolor colorsblack bcvalueaxisvaluemin bcvalueaxisvaluemax bcvalueaxisvaluestep bccategoryaxislabelsboxanchor ne bccategoryaxislabelsdx bccategoryaxislabelsdy bccategoryaxislabelsangle bccategoryaxiscategorynames jan feb mar apr may jun jul aug drawingaddbc intergrate djangos views attempt produced blank screen def charttestrequest import mycharts drawing drawing mychartstestchartdrawing binarystuff dasstring gif return httpresponsebinarystuff imagegif i manage make matplotlib produce graph grey background life i work make go away found hard looking google information like i little bit stuck atm anyone ideas i find helpful advice learning tools would awesome thanks,2 ppoll indicates whether process executing so returns false soon program exits so checking code pstdoutreadline reads single line iterates letter line not wanted use pstdoutreadlines return line but read entire file producing lines probably wanted so use line pstdout which give line line line nothing read,i know anwered many times i find working way scenario i hope help i want output data stdout andor stderr popen call real time socket connection stdout so sysstdoutflush work datasokrecv command execute p subprocesspopendata shelltrue stdoutsubprocesspipe stderrsubprocesspipe work spected subprocess ends fast get first line ppoll none soksendpstdoutreadline send last line pstdoutreadline soksendi sysstdoutflush sysstdout use pstdoutflush result,2 no code apart fact syntactically incorrect print every line b words in order want need information text file suppossing words separated single spaces could something like x openfile r words w w xreadsplit w b w,look code this finds letter b containing text file prints words containing letter b right x opentext file r line x b line print line searchfileclose now problem i would like search one several letters like b word and print list words containing letters and i like user decide letters how i now i come something new after reading answer x opentext file r line x b line c line r line print line would work instead and i make user enter letters,1 imagine project called commons store code want share and want use code commons project called foo imagine follow directories homesharedcommonspy hometimprojectsfoopy the commonspy content def sayhello return hello world if want able import module commons file testpy put file import sys syspathappendhomeshared import commons print commonssayhello and print hello world,i several applications django project i would like reuse functions across apps i created new app added custom functionspy trying following mynewapp import mynewapp import functions i get nameerror global name xxx undefined am i omitting something important how would recommend i solve problem reusing code across multiple apps thanks,2 use redotall match character including newlines import data processname report type periodic n line n line n linesn succ statistics n linesn repeat pattern several hundred times pattern r ddd dddsucc statisticsssdsd regex recompilepattern flagsremultilineredotall match regexfinditerdata results matchgroups printresults,considering following text pattern goals process report timestamp eg first two stats succ statistics line eg inputtext processname report type periodic n line n line n linesn succ statistics n linesn processname report type periodic n line n line n linesn succ statistics n repeat pattern several hundred times i got working iterating line line def parsefilefilehandler patterns results line filehandler key patternsiterkeys result rematchpatternskey line result resultsappend result return results patterns reportdatetime recompile processnamessd report stypesperiodicss servtermstats recompile succ statistics sds dsdssdsdsdss results parsefilefh patterns returning list tuples output goal i tried several combos initial patterns lazy quantifier figure capture patterns using multiline regex lazy quantifier match characters possible characters allowed reaching next expression pattern processnamessd report stypesperiodicsucc statistics sdsdsdssdsdsdss regex recompilepattern flagsremultiline data filehandlerread match regexfinditerdata results matchgroups how i accomplish,3 this work loggingformatterfmt asctimesmsecsd datefmt ymdhms,by default loggingformatter asctimes prints following format millisecond i need change comma dot to format time i use loggingformatterfmt asctimes datestrdateformatstr however documentation specify format milliseconds i found so question talks microseconds i would prefer milliseconds b following work python i working due f loggingformatterfmt asctimes datefmt ymdhmsf,3 you could simply multiple timetime value get precision want note many calls guarantee subsecond accuracy anyways so starttime inttimetime endtime inttimetime will satisfy condition endtime starttime sleeptime,is possible receive output timetime python decimal if float possible guarantee inaccuracy always rather less original value in words repr more i want repr less unacceptable code example import math time sleeptime true timebefore timetime timesleepsleeptime timeafter timetime timetaken timeafter timebefore assert timetaken sleeptime r r timetaken sleeptime edit now using following fail testing could still theoretically fail import time decimal import decimal def todecfloatnum return decimal f floatnum sleeptime todec true timebefore todectimetime timesleepfloatsleeptime timeafter todectimetime timetaken timeafter timebefore assert timetaken sleeptime r r timetaken sleeptime print timetaken sleeptime timetaken sleeptime,1 if using windows see httppermalinkgmaneorggmanecomppythonwindows,i like write short python script puts computer sleep i ve already searched api result suspend delayed execution what function trick,1 you could format float value f see python string formatting operations,is possible receive output timetime python decimal if float possible guarantee inaccuracy always rather less original value in words repr more i want repr less unacceptable code example import math time sleeptime true timebefore timetime timesleepsleeptime timeafter timetime timetaken timeafter timebefore assert timetaken sleeptime r r timetaken sleeptime edit now using following fail testing could still theoretically fail import time decimal import decimal def todecfloatnum return decimal f floatnum sleeptime todec true timebefore todectimetime timesleepfloatsleeptime timeafter todectimetime timetaken timeafter timebefore assert timetaken sleeptime r r timetaken sleeptime print timetaken sleeptime timetaken sleeptime,1 also look jqplot httpwwwjqplotcom uses jquery javascript library i usually pass data template chartsgraphs rendered client browser,i tasked producing analytic tool data get activities company work clients last week made mock view one possible graph using php flot jquery graphing tool unfortunatly i dont think i going able use flot need long term make graph needed work i hack divs one top otherwise got flat line so looking technologies work tool one senior members recommends using django framework graphs using reportlabs matplotlib i spent last couple days looking decent tutorials produce graphs using report labs matplotlib using django display unfortunately havent able find much use examples found django site werent terriably useful examples give something like drawing drawing data bc verticalbarchart bcx bcy bcheight bcwidth bcdata data bcstrokecolor colorsblack bcvalueaxisvaluemin bcvalueaxisvaluemax bcvalueaxisvaluestep bccategoryaxislabelsboxanchor ne bccategoryaxislabelsdx bccategoryaxislabelsdy bccategoryaxislabelsangle bccategoryaxiscategorynames jan feb mar apr may jun jul aug drawingaddbc intergrate djangos views attempt produced blank screen def charttestrequest import mycharts drawing drawing mychartstestchartdrawing binarystuff dasstring gif return httpresponsebinarystuff imagegif i manage make matplotlib produce graph grey background life i work make go away found hard looking google information like i little bit stuck atm anyone ideas i find helpful advice learning tools would awesome thanks,1 how in smstart refinditer out foo foobar foobarbaz,i hierarchical descriptor string looks like foobarbaz elements hierarchy delimited i would like iterate hierarchy levels is easy way something easier def hierarchys segments ssplit rangelensegments prefix joinsegmentsi print prefix something else instead prefix,3 you could use strip remove leading trailing whitespaces in strip out,i search text file word offering regular expression i use start end points search look column pull integers some instances column a leading whitespace i want i want print number would found column b file leading whitespace regex regex conditional price researchr soffering line rei price ps pricestart pe priceend a b offering offer,2 getdefaulttempdir checks access temp dirs writing deleting random file temp dir so might want check permissions temp dirs tmp vartmp usrtmp usrlibpython,this error seems shown latest set upgrades ubuntu traceback recent call last file usrlocalbinsupervisord line module loadentrypoint supervisora consolescripts supervisord file usrlocallibpythondistpackagessupervisorapyeggsupervisorsupervisordpy line main options serveroptions file usrlocallibpythondistpackagessupervisorapyeggsupervisoroptionspy line init existingdirectory defaulttempfilegettempdir file usrlibpythontempfilepy line gettempdir tempdir getdefaulttempdir file usrlibpythontempfilepy line getdefaulttempdir no usable temporary directory found dirlist ioerror errno no usable temporary directory found tmp vartmp usrtmp usrlibpython i think python thing i running supervisord process keep nodejs webserver running longer able run supervisord does anyone know fix know reliable alternative keeping nodejs webserver running apart seemingly obvious write stuff crashes,2 as turns disk full,this error seems shown latest set upgrades ubuntu traceback recent call last file usrlocalbinsupervisord line module loadentrypoint supervisora consolescripts supervisord file usrlocallibpythondistpackagessupervisorapyeggsupervisorsupervisordpy line main options serveroptions file usrlocallibpythondistpackagessupervisorapyeggsupervisoroptionspy line init existingdirectory defaulttempfilegettempdir file usrlibpythontempfilepy line gettempdir tempdir getdefaulttempdir file usrlibpythontempfilepy line getdefaulttempdir no usable temporary directory found dirlist ioerror errno no usable temporary directory found tmp vartmp usrtmp usrlibpython i think python thing i running supervisord process keep nodejs webserver running longer able run supervisord does anyone know fix know reliable alternative keeping nodejs webserver running apart seemingly obvious write stuff crashes,2 as discussed looks like problem starting unicode object string you want string import urllib u lacitcadelawest types type unicode print urllibunquotepluss la citãƒâ© de la west strs types type str print urllibunquotepluss la citã© de la west import sys sysstdoutencoding utf,i strings encoded following form lacitcadelawest i stored sqlite varchar field python these apparently utf encoded binary strings converted urlencoded strings the question convert back unicode string lacitcadelawest i used urllibunquoteplus python function convert ca unicode char i see la citãƒâ© de la west instead expected la citã© de la west i running code ubuntu windows encoding utf,3 no not directly anyway ctypes uses dynamic linker loadlibrary getprocaddress work you could wrap lib file dll possibly able use ctypes directly lib file,i need control device python using ctypes however libraries come device compiled lib files dlls is still possible use ctypes,1 because using match matches string beginning like used try research,could explain first regex match python r jun gcc based apple inc build llvm build darwin import rematchr rematchr sresrematch object xadbd,2 rematch tries match beginning string use research instead want locate match anywhere string ps you might want escape metacharacter matches character x would match second example rematchr x rematchr x sresrematch object xf except newlines unless redotall used,could explain first regex match python r jun gcc based apple inc build llvm build darwin import rematchr rematchr sresrematch object xadbd,3 function take parameter pass parameter def onefunction onevariable return onevariable def anotherfunctionaparam something aparam return,how i take one variable one function use another function without make variable global,1 there actually five levels logging debug info warning error critical i see setting logger explicitly setting leveli believe logger may default warning level set as printing multiple times warning i believe due creating two handlers info amp warning what happens logger cascades severity warning info debug calling handler since level set warning info handler ignored also i believe warning messages normally written sysstderr try following loggingbasicconfiglevellogginginfo see also logging module docs logging basic example,i really miss something basic python logging module in following code i create logger object log add two handlers one info level one warning level both supposed print stdout i expect calling loginfomsg result one copy msg stdout calling logwarnmsg sould result two copies msg printed stdout here code import logging import sys loggingbasicconfig log logginggetlogger mylogger loghandlers h loggingstreamhandlersysstdout hlevel logginginfo hformatter loggingformatter h h messages h loggingstreamhandlersysstdout hlevel loggingwarning hformatter loggingformatter h h messages logaddhandlerh logaddhandlerh print loglevel logginggetlevelnameloglevel print loginfo loginfo info print done print logwarn logwarn warning print done the output really strange the info call results visual effect however calling warn results two copies msg printed stdout ok also one copy printed stderr this output code note formatting last line output this line printed stderr loglevel notset loginfo done logwarn h h warning h h warning done warningmyloggerthis warning so questions call info result output despite fact h level set info call warn results additional output stderr,2 for reference search vs match httpdocspythonorglibraryrehtmlsearchvsmatch,could explain first regex match python r jun gcc based apple inc build llvm build darwin import rematchr rematchr sresrematch object xadbd,1 you basically two choices one pass second function parameter if want first function see changes value needs reference type eg dictlist overwrite object modify eg aappendb rather b the second define class used singleton technically still defining something globally lets keep things grouped class foosingletonobject classvar foo def func foosingletonclassvar bar def func printfoosingletonclassvar you could also dict instead class matter preference,how i take one variable one function use another function without make variable global,2 you use regular expression query parameter bookobjectsfiltertitleregexr,i model called book title field class bookmodelsmodel title modelscharfieldnull falseblankfalse now i need filter get books titles starting number this works i extend queryset b bookobjectsfiltertitlestartswith orderby title this work b b bookobjectsfiltertitlestartswith orderby title bextendbookobjectsfiltertitlestartswith orderby title,3 data bluered purpleyellow whitebrown data fee fie foe fum datatable dictssplit data line data key linesplit print joinline datatablegetkey gives feebluered fiepurpleyellow foewhitebrown fum and csv version import csv data bluered purpleyellow whitebrown data fee fie foe fum open outtxt w f combined csvwriterf data bluered purpleyellow whitebrown data fee fie foe fum datatable dictrow row row csvreaderdata row csvreaderdata key row combinedwriterowrow datatablegetkey,i want merge csv files one an example file id average another file could id max and i need output id average max this half works appends data two columns import glob string outfile open directoryfilenamecsv files globglobrdirectorycsv files newfile openy r data newfileread newfileclose outfilewriterowy how i append data new columns repeat id field,1 you could superpose quiver plot line plot,i line graph i want plot using arrows instead lines that line successive pairs points arrow going first point second point i know arrow function seems individual arrows before i work way try use whole plot nicer way,1 this problem similar problem project euler how many different ways ⣠made using number coins only example asking enumerate ways add numbers get the best way approach problem first try breaking single number let look possible breakups five using numbers the following python code give list combinations def possiblesplitsvaluevalidincrements ret increment validincrements increment value continue increment value retappendincrement continue increment value remainder value increment toadd possiblesplitsremainder validincrements toadd retappendincrement return ret this code assumes different orderings otherwise identical answers treated distinct for example appear solutions split if prefer constrain answers numerically ordered appears def orderedpossiblesplitsvalue validincrements ret splits possiblesplitsvalue validincrements value splits valuesort value ret retappendvalue return ret now use find possible splits possible splits combine increments tensplits orderedpossiblesplits increments foursplits orderedpossiblesplits increments results tensplit tensplits foursplit foursplits resultsappendtensplit foursplit edit as noted comments calling possiblesplits value slow upwards ten minutes counting the reason occurs possiblesplits recursively call possiblesplits possiblesplits possiblesplits call three possiblesplits we approximate processing time possiblesplitsn datalist large n processingtimen c processingtimen processingtimen processingtimen for constant time c so relative time possiblesplits n time supposing possiblesplits takes ns possiblesplits takes years this probably unsuitably long time practical programs however reduce time taking advantage memoization if save result previously calculated calls get linear time complexity reducing possiblesplits ns the comments also noted expected value orderedpossiblesplits elements possiblesplits therefore much much larger number elements impractical use even memoization instead discard rewrite orderedpossiblesplits use memoization depend possiblesplits sorts element seq returns def orderedinnerlistsseq return mapsorted seq returns copy seq duplicates removed def removeduplicatesseq ret value seq value ret retappendvalue return ret memoizedresults def orderedpossiblesplitsvaluevalidincrements memoizekey value tuplevalidincrements memoizekey memoizedresults return memoizedresultsmemoizekey ret increment validincrements increment value continue increment value retappendincrement continue increment value remainder value increment toadd orderedpossiblesplitsremainder validincrements toadd retappendincrement memoizevalue removeduplicatesorderedinnerlistsret memoizedresultsmemoizekey memoizevalue return memoizevalue on machine orderedpossiblesplits takes ten seconds much improved original three billion year run time,i bit confused approach problem i know i want wrap head logically solve problem say i list numlist i following values another list datalist i break numbers numlist using numbers datalist an example answer would i understand vaguely make loop entry list compare divided datalist print result i think i need recursions i trouble understanding code far i print statements troubleshooting def variablerecursionself solutionlist solution list contrains red green means redsvalue greenvalue adding fake lookup list real code i use real data i reversing order list red green blue x x zipsolutionlist solutionlist x list zipx x print x x keyname x keyshares x keyvalue lookupgetvaluex keyvaluey keyvalue templist print you break keyname keyvalue exactly keyvaluex times newkeyshares keyshares zipsolutionlist solutionlist print print you break keyname keyvalue exactly keyvaluey times newkeyshares keyshares print match change shares newkeyshares print keyname print templistappendkeyname newkeyshares elif print b templistappendy akeyvaluey else print c try templistappendy akeyvaluey except e templistappenda print templist appendlistappendlisttemplist templist exit print solutionlist,2 builddarraypyx specifies types index variables turns safety checks uses multiple cpus useful large vsize cython boundscheckfalse wraparoundfalse libcmath cimport log cythonparallel cimport prange import numpy pynp cimport numpy np copy declarations libcppvector allow nogil cdef extern vector namespace std cdef cppclass vectort void pushbacktamp nogil sizet size tamp operatorsizet def makearrayint cdef vectornpfloatt v cdef int nogil ranget vpushbacklogi cdef npndarraynpfloatt pynpemptyvsize dtypepynpfloat prangeashape nogiltrue ai vi return the nd part first loop therefore make sense optimize speed case mathh extern c system libcmathlog works pyarraysimplenewfromdata could used avoid copying data cost managing memory array,i timecritical model i wrote cython the main function cython extension one loop according cython profiler shows amount python calls shades yellow yellow part currently i appending python list i output python object i calling cython function python script this basic idea function rest superfluous i tested every part function append operation bottleneck libcmath cimport log def mainsome args cdef vars cdef list outputlist nb vars declared types x ranget cythonic stuff uses cimported log condition true outputlistappendx yellow line main loop return outputlist return python object python script calls main unfortunately i know length output arraylistvector whatever i end using however i could set i end resizing line python code i like get major speed boost without setting output array length i gladly toss hope holding back i also tried going c cython use c data structures vector queue etc removes ability nicely cimport log i see cython documentationwiki write shim module use purec functions c cython i idea i find anything go anyway i welcome suggestions adhere question what best way build listarrayvector unknown size cython or clear alternative settling knownlength iterable object makes moot unknownlength problem update the c containers show speed increase item assignment item assignment show speed increase appending lists numpy arrays the best method would use c containers also able cimport purec functionsthis would prevent slowdown look beyond libcmath quick log function,1 there two things need know the root logger initialized level warning any log message reaches logger discarded level logger level if logger level set take effective level parent logger so root logger level warning loggers default effective level warning if configure otherwise log messages level discarded when call basicconfig system automatically sets streamhandler root logger prints standard error stream when program prints log messages actually three handlers two added levels one system print message rejected logger that get line warningmyloggerthis warning it comes system logger it info level message previously discussed root logger configured reject messages default if want output call basicconfig further reading httpdocspythonorghowtologginghtml,i really miss something basic python logging module in following code i create logger object log add two handlers one info level one warning level both supposed print stdout i expect calling loginfomsg result one copy msg stdout calling logwarnmsg sould result two copies msg printed stdout here code import logging import sys loggingbasicconfig log logginggetlogger mylogger loghandlers h loggingstreamhandlersysstdout hlevel logginginfo hformatter loggingformatter h h messages h loggingstreamhandlersysstdout hlevel loggingwarning hformatter loggingformatter h h messages logaddhandlerh logaddhandlerh print loglevel logginggetlevelnameloglevel print loginfo loginfo info print done print logwarn logwarn warning print done the output really strange the info call results visual effect however calling warn results two copies msg printed stdout ok also one copy printed stderr this output code note formatting last line output this line printed stderr loglevel notset loginfo done logwarn h h warning h h warning done warningmyloggerthis warning so questions call info result output despite fact h level set info call warn results additional output stderr,3 you three problems read csv files merge common field write merged data new csv file code usrbinenv python import argparse csv name main parser argparseargumentparserdescription merge csv files field version progs parseraddargument infile nargs typestr help list input files parseraddargument typestr default tempcsv help name output file args parserparseargs data fields fname argsinfile openfname rb df reader csvdictreaderdf line reader assuming field called id line id data dataline id line else kv lineiteritems k dataline id dataline id k v k lineiterkeys k fields fieldsappendk del reader writer csvdictwriteropenargsout wb fields dialect excel write header top file writerwriteheader writerwriterowsdata del writer note ignore data identical field name an alternative parser section usrbinenv python import glob csv name main infiles globglob csv tempcsv data fields fname infiles df openfname rb reader csvdictreaderdf line reader assuming field called id line id data dataline id line else kv lineiteritems k dataline id dataline id k v k lineiterkeys k fields fieldsappendk del reader dfclose writer csvdictwriteropenout wb fields dialect excel write header top file writerwriteheader writerwriterowsdata del writer,i want merge csv files one an example file id average another file could id max and i need output id average max this half works appends data two columns import glob string outfile open directoryfilenamecsv files globglobrdirectorycsv files newfile openy r data newfileread newfileclose outfilewriterowy how i append data new columns repeat id field,2 don page pages newpage pageobjectscreate pagethis thatpagethat status pagedraft much simpler much clearer and actually works,i trying copy instance page model set new page status draft this code works perfectly django shell admin action lives new instance created status updated page pages pagepk pageid none none pagesave pagestatus pagedraft pageupdatedat datetimenow pagesaveforceupdatetrue so code creates new page change status i think might something page proxy models depending status publishedpage draftpage etc i sure problem though,1 i going use psychic debugging skills guess databaseclose if close file writing may still data python output buffers written os yet if program exits point data written disk missing data end,i new stackoverflow python might look obvious in procedure i want create new file named database list files generated previous procedure the files list quite big around mb the goal single file lines database open currentdatabase def fileapendernew line new databasewriteline def filejoinlistoffiles file listoffiles fileapenderfile then i filejoinafilelist i get database file lines missing last one complete here ending file i tried find memory limitation otherwise i got ideas,3 try timetime ospathgetmtimefilename print file older days,i need remove files older days directory stores backups i get time individual file using something like start ospathgetmtimejoindirpath name but i getting confused i use timedelta find difference current date i like use something like datetimetimedeltatimenow ospathgetmtimejoindirpath dirname i getting i i love help,2 instead except keyerror name try except keyerror name its difference python x python x the first form longer supported,i beginner using python book whos code python wrote part program keep getting syntax error invalid syntax then python idle highlights comma keyerror code tank import tank tanks atankalice btankbob ctankcarol alivetanks lentanks alivetanks print tankname sorted tankskeys print tankname tankstankname first rawinputwho fires lower second rawinputwho lower try firsttank tanksfirst secondtank tankssecond except keyerror name print no tank exists name continue,3 if prefer handle python code option pass closefdstrue popen sockets inherited forked process,i set development server running cherokee fedora using uwsgi interface wsgi application when application hit first request i spawn process like subprocess import popen popen bash bash example problem happens programs the first request takes seconds complete subsequent ones take less second without creation popen object first request takes seconds complete when i execute popen request python shell instantaneous what could causing behaviour have i missed something obvious,1 timedelta result subtracting datetime another datetime example show binbash days older devnull import datetime import ospath datetimedatetimefromtimestampospathgetmtimedevnull datetimedatetime datetimedatetimefromtimestampospathgetmtimebinbash datetimedatetime datetimedatetimefromtimestampospathgetmtimedevnulldatetimedatetimefromtimestampospathgetmtimebinbash datetimetimedelta datetimedatetimefromtimestampospathgetmtimedevnulldatetimedatetimefromtimestampospathgetmtimebinbash ddays,i need remove files older days directory stores backups i get time individual file using something like start ospathgetmtimejoindirpath name but i getting confused i use timedelta find difference current date i like use something like datetimetimedeltatimenow ospathgetmtimejoindirpath dirname i getting i i love help,1 try putting line top file according pep top two lines,i wrote simple html parsing class python seems work fine i try use django i get error ascii codec decode byte xc position ordinal range strange i added encoding utf top class i really know much encoding someone perhaps give idea going btw i also insured source html already utf thanks,1 if i guess i say done way avoid keep track long individual values stored cache would create memory processing overhead because caching object used dictionary inherently unordered good way know order items added without caching object well this could addressed using ordereddict place standard dictionary assuming working python otherwise need significantly redesign way caching implemented order eliminate need clear,while reading documentation python module i decided look repy source code when i opened i found cache maxcache def compilekey cachekey typekey key p cachegetcachekey p none return p here i skip part irrelevant question code lencache maxcache cacheclear cachecachekey p return p why cache cleared using cacheclear reaches maxcache entries is common approach clear cache completely start scratch why used longest time ago cashed value deleted,1 the point caching decrease average call time function the overhead associated keeping information cache pruning instead clearing would increase average call time the cacheclear call complete quickly even though lose cache preferable maintaining cache state overhead removing individual elements cache limit reached there things think calculating cache efficiency average call time cache hits short average call time cache misses longer frequency cache hits fairly uncommon call time cache cleared pruned fairly uncommon the question increasing make sense means increasing well my guess difference negligible enough keeping code simple preferable,while reading documentation python module i decided look repy source code when i opened i found cache maxcache def compilekey cachekey typekey key p cachegetcachekey p none return p here i skip part irrelevant question code lencache maxcache cacheclear cachecachekey p return p why cache cleared using cacheclear reaches maxcache entries is common approach clear cache completely start scratch why used longest time ago cashed value deleted,1 take look parsing python arguments your bash code would fine need edit python script take argument,eventually i understand works bash script binbash v cwd homesgejobsoutputjobidout j s binbash l memfreeg csgetaskid cd homexxxscratchtest filenamehead c testlisttail python testpythonpy filename python script binpython import sysos path homexxxscratchtest namesysargv jobidospathjoinpathname fopenjobid r readlines print f thx,1 i using simple field mysql backend modify backends class blobfieldmodelsfield description blob def dbtypeself return blob,i want create table like create table trialxml id int default null pid int default null sid varchar character set utf not null data blob primary key soid key suidindex suid enginemyisam default charsetlatin question i set data field blob django modelspy i mean syntax update i dont want set data field longtext i want blob datafield,1 i using simple field mysql backend modify backends class blobfieldmodelsfield description blob def dbtypeself connection return blob,how store blob binary data using django orm postgresql backend yes i know django frowns upon sort thing yes i know prefer use imagefield filefield suffice say impractical application i tried hacking using textfield i get occassional errors binary data strictly confirm models encoding type unicode default eg psycopgdataerror invalid byte sequence encoding utf xe,3 are absolutely certain x float array if i expect x see instead looks like integer xf arangedtypefloat xi arange xf xi yf xf yf yf e yf e xf yf xf e xi yf xi,i two arrays float type i assign value first second rounds value the following simple code illustrates problem excludes possibility mere number representation thing i schematized fragment code readable essence thing x zeros y zeros z x shorter way making new matrix equal x x y z print y print x print typey print typex xy print equal else print not equal i ran little snippet code coefficients outputs similar e type numpyfloat type numpyfloat not equal it seems x array another type created way zeros function standard type float edit the arrays initialized x zeros dtypefloat y zeros dtypefloat also included additional useful print example edit added problematic lines i found problem,2 okay i got all i needed include coding utf django view well solved,i wrote simple html parsing class python seems work fine i try use django i get error ascii codec decode byte xc position ordinal range strange i added encoding utf top class i really know much encoding someone perhaps give idea going btw i also insured source html already utf thanks,1 here quote one developers new regex module scheduled regarding caching part list features separates new module current module modify compiled expression cache better handle thrashing condition currently regular expressions compiled result cached expression compiled retrieved cache extra work done this cache supports entries once th entry reached cache cleared new compile must occur the danger rare one may compile th expression find one recompiles work may done expressions ago by modifying logic slightly possible establish arbitrary counter gives time stamp compiled entry instead clearing entire cache reaches capacity eliminate oldest half cache keeping half recent this limit possibility thrashing cases large number regular expressions continually recompiled in addition i update limit entries meaning recent kept httpbugspythonorgissue this seems indicate likely laziness developer emphasis readability explains current caching behavior,while reading documentation python module i decided look repy source code when i opened i found cache maxcache def compilekey cachekey typekey key p cachegetcachekey p none return p here i skip part irrelevant question code lencache maxcache cacheclear cachecachekey p return p why cache cleared using cacheclear reaches maxcache entries is common approach clear cache completely start scratch why used longest time ago cashed value deleted,2 you missing closequote class maxx soupfindallhref class yilbizttl maxx soupfindallhref class yilbizttl also i think search attribute like href like i think need search tag maxx link href link soupfindalla class yilbizttl,i trying parse html beautifulsoup the content i want like classyilbizttl idyilbizttl hrefhttpsomeweburl titlesome titletitlea tried got following error maxx soupfindallhref class yilbizttl file ipython console line maxx soupfindallhref class yilbizttl syntaxerror invalid syntax want string httpsomeweburl,1 soupfindall class yilbizttl href to find links link soupfindall class yilbizttl try print link href except keyerror pass,i trying parse html beautifulsoup the content i want like classyilbizttl idyilbizttl hrefhttpsomeweburl titlesome titletitlea tried got following error maxx soupfindallhref class yilbizttl file ipython console line maxx soupfindallhref class yilbizttl syntaxerror invalid syntax want string httpsomeweburl,1 you printmytest r strmytest mytest testthis,in python i create named tuple collections import namedtuple test namedtuple test i populate mytest testthis and i print like printmytest testthis i print like printmytest r mytest typeerror arguments converted string formatting edit i known look printing tuple string formatting python,1 since mytest tuple look format item tuple to get around wrap another tuple element mytest printmytest r mytest don forget comma,in python i create named tuple collections import namedtuple test namedtuple test i populate mytest testthis and i print like printmytest testthis i print like printmytest r mytest typeerror arguments converted string formatting edit i known look printing tuple string formatting python,3 it unpacking arguments compare printdummy dummy onetwo in case try putting tuple printmytest r mytest,in python i create named tuple collections import namedtuple test namedtuple test i populate mytest testthis and i print like printmytest testthis i print like printmytest r mytest typeerror arguments converted string formatting edit i known look printing tuple string formatting python,1 get pywin also contains winsecurity i remember correctly then try mentioned script,i like write short python script puts computer sleep i ve already searched api result suspend delayed execution what function trick,1 you asked post one questions answer goes this looks like need use django builtin count function docsdjangoprojectcomendevrefmodelsquerysets i see use code,i developing custom manager class chainable method got problem i need randomize filtered query to get random record i need count filtered distinct records but i know get on contrary i count records class randomquerysetmodelsqueryqueryset def randomizeself count selfaggregatecountcount id count randomindex randomrandint count return selfallrandomindex class randommanagermodelsmanager def getquerysetself return randomquerysetselfmodel usingselfdb def randomizeself return selfgetquerysetrandomize using posts postpagesrandomobjectsfilterimagegalleryisnullfalsedistinct postsrandomize sooner later i get error count exceeds number records current query indexerror list index range,1 bash variables actually environment variables you get osenviron object dictionarylike interface note two types variables bash local current process inherited child processes your python script child process need make sure export variable want child process access to answer original question need first export variable access within python script using osenviron binbash v cwd homesgejobsoutputjobidout j s binbash l memfreeg csgetaskid cd homexxxscratchtest export filenamehead c testlisttail chmod x testpythonpy testpythonpy binpython import sys import os arg sysargv print arg fopen homexxxscratchtest osenviron filename r readlines print f alternatively may pass variable command line argument code in case must look sysargv list arguments passed script they appear sysargv order specified invoking script sysargv always contains name program running subsequent entries contain arguments lensysargv indicates number arguments script received binpython import sys import os lensysargv print usage sysargv filename sysexit print this name python script sysargv print this st argument sysargv fopen homexxxscratchtest sysargv r readlines print f,eventually i understand works bash script binbash v cwd homesgejobsoutputjobidout j s binbash l memfreeg csgetaskid cd homexxxscratchtest filenamehead c testlisttail python testpythonpy filename python script binpython import sysos path homexxxscratchtest namesysargv jobidospathjoinpathname fopenjobid r readlines print f thx,3 this aptanaeclipse realize file opened debugged using python debugger associated python projectperspective lot environment setup project created aptanaeclipse the simplest solution imo would create simple sandbox python project stick files rundebug aptana realize dealing python start running python debugger without setup experience w pydev eclipse rate,in search python debugger i stumbled upon aptana based eclipse often i want debug single python script however aptana let rundebug currently opened file directly instead requires create debugrun configuration file i would like rundebug alternatively i could create python project aptana but i want i want able run debug currently opened file this way i would like debug scripts without forced create project first single script can hard,2 you following create alias make program help act program help import argparse def helpargs argsparserprinthelp parser argparseargumentparserdescription program subparsers parseraddsubparsers phelp subparsersaddparser help phelpsetdefaultsfunchelp parserparser args parserparseargs argsfuncargs,i want help option act help sidenote i created program command line behavior svn hg i managed subparsers however i want make things consistent that i want help work,2 the list function docs convert string list singlecharacter strings list hello h e l l even without converting lists strings already behave like lists several ways for example access individual characters singlecharacter strings using brackets hello e you also loop characters string loop elements list c hello print c c hh ee oo,how i turn string like hello list like hello,3 i solved switching distutils looks like distribute deprecated andor broken distutilscore import setup setup name myapp packages myapp packagedata myapp datatxt,when using setuptoolsdistribute i get installer pull packagedata files everything i read says following correct way can someone please advise setup name myapp packagesfindpackages packagedata myapp datatxt includepackagedatatrue zipsafefalse installrequires distribute myappdata location data files,3 to read string user use rawinput input input tries actually evaluate string user types python code result getting datatype expect worse things in contrast rawinput always returns string note applies python x starting python rawinput renamed input function input used,i created function takes word string forbidden letters returns true word use letter def avoidswordforbidden letter word letter forbidden return false else return true i want modify instead using forbidden letters avoid user prompted place couple letters print number words contain i also txt document contain words make interesting this i came wrong i would like assistance education possible since online teacher never around assist please help def wordnoforbidden forbidden input pick letters fin open wordstxt noforbiddenword line fin word linestrip letter word forbidden word continue print word this error i get i understand i sure else approach traceback recent call last file pyshell line module wordnoforbidden file cpythontestpy line wordnoforbidden forbidden word typeerror string requires string left operand tuple,1 my guess you python x when ran program typed b c on python x want use rawinput input that give string exactly type as python try interpret whatever right python expression dangerous generally bad idea your second problem reversed line code first example letter forbidden becomes forbidden word not thing,i created function takes word string forbidden letters returns true word use letter def avoidswordforbidden letter word letter forbidden return false else return true i want modify instead using forbidden letters avoid user prompted place couple letters print number words contain i also txt document contain words make interesting this i came wrong i would like assistance education possible since online teacher never around assist please help def wordnoforbidden forbidden input pick letters fin open wordstxt noforbiddenword line fin word linestrip letter word forbidden word continue print word this error i get i understand i sure else approach traceback recent call last file pyshell line module wordnoforbidden file cpythontestpy line wordnoforbidden forbidden word typeerror string requires string left operand tuple,1 for worth works fine bit windows xp python compiled iwmingwgexe version ctestcpp include windowsh define intelhookapi extern c declspecdllexport intelhookapi bool testvoid bool success false hwnd parent null parent findwindownotepad null parent null success true return success g testcpp testdll shared testpy import ctypes dll ctypescdllloadlibrary ctestdll printdlltest it prints notepad window open else,i following bare minimum function dll define intelhookapi extern c declspecdllexport intelhookapi bool testfuncvoid bool success false hwnd parent null parent findwindowariumsourcepont null parent null success true return success if i call main function dll works fine if i call python i get following windowserror exception access violation reading x my python script looks like ctypes import dll cdllhook print dlltestfunc i running win bit dll python bit cprojectshghooklibdumpbin headers hookdll microsoft r coffpe dumper version copyright c microsoft corporation all rights reserved dump file hookdll pe signature found file type executable image file header values c machine x print sysversion default jun msc v bit intel i attached debugger seem solve pythonexe loaded cpythonpythonexe pythonexe loaded cwindowssyswowntdlldll symbols loaded source information stripped pythonexe loaded cwindowssyswowkerneldll symbols loaded source information stripped pythonexe loaded cwindowssyswowkernelbasedll symbols loaded source information stripped pythonexe loaded cwindowssyswowpythondll pythonexe loaded cwindowssyswowuserdll symbols loaded source information stripped pythonexe loaded cwindowssyswowgdidll symbols loaded source information stripped pythonexe loaded cwindowssyswowlpkdll symbols loaded source information stripped pythonexe loaded cwindowssyswowuspdll symbols loaded source information stripped pythonexe loaded cwindowssyswowmsvcrtdll symbols loaded source information stripped pythonexe loaded cwindowssyswowadvapidll symbols loaded source information stripped pythonexe loaded cwindowssyswowsechostdll symbols loaded source information stripped pythonexe loaded cwindowssyswowrpcrtdll symbols loaded source information stripped pythonexe loaded cwindowssyswowsspiclidll symbols loaded source information stripped pythonexe loaded cwindowssyswowcryptbasedll symbols loaded source information stripped pythonexe loaded cwindowssyswowshelldll symbols loaded source information stripped pythonexe loaded cwindowssyswowshlwapidll symbols loaded source information stripped pythonexe loaded cwindowswinsxsxmicrosoftvccrtfcbbaeebnonefebcbebmsvcrdll symbols loaded source information stripped pythonexe loaded cwindowssyswowimmdll symbols loaded source information stripped pythonexe loaded cwindowssyswowmsctfdll symbols loaded source information stripped pythonexe loaded cwindowssyswowpgpmapihdll pythonexe loaded cpythondllsctypespyd pythonexe loaded cwindowssyswowoledll symbols loaded source information stripped pythonexe loaded cwindowssyswowoleautdll symbols loaded source information stripped pythonexe loaded cprojectshghooklibhookdll symbols loaded the thread win thread xb exited code x firstchance exception xdae hookdll pythonexe xc access violation reading location x the program pythonexe native exited code x the happens i access function java jna given function works calling main dll makes believe access restriction make sense i first one calling win functions indirectly dll thank advance taking time read cheers,1 in part code letter word forbidden word you letter forbidden letter word what want check every letter ones users entered word read file skip word go next one there pythonic ways i think clear easy understand,i created function takes word string forbidden letters returns true word use letter def avoidswordforbidden letter word letter forbidden return false else return true i want modify instead using forbidden letters avoid user prompted place couple letters print number words contain i also txt document contain words make interesting this i came wrong i would like assistance education possible since online teacher never around assist please help def wordnoforbidden forbidden input pick letters fin open wordstxt noforbiddenword line fin word linestrip letter word forbidden word continue print word this error i get i understand i sure else approach traceback recent call last file pyshell line module wordnoforbidden file cpythontestpy line wordnoforbidden forbidden word typeerror string requires string left operand tuple,1 while frequently askedfor application appear anyone actually implemented it seem like hard project you would need profile app track user reputation messaging app easily available products app users offer products users bid products given time bidding closed etc a weekend basics i think rip hell satchmo transaction handling get real authorization account authorizenet google checkout paypal thingy you hook one big fraud risk though auction sites generally big kids,i need build site similar ebay i found ecommerce packages django related cc model ebay i tried httpswwwdjangoshoporg httpwwwsatchmoprojectcom do know app package framework deal thank much,2 def wordnoforbidden forbidden rawinput pick letters fin open wordstxt noforbiddenword line fin word linestrip letter listword letter forbidden break else print word note as winston said use rawinput in case want traverse string use listyourstring get list characters else executes letter listword loop completes without ever going break words none letters forbidden,i created function takes word string forbidden letters returns true word use letter def avoidswordforbidden letter word letter forbidden return false else return true i want modify instead using forbidden letters avoid user prompted place couple letters print number words contain i also txt document contain words make interesting this i came wrong i would like assistance education possible since online teacher never around assist please help def wordnoforbidden forbidden input pick letters fin open wordstxt noforbiddenword line fin word linestrip letter word forbidden word continue print word this error i get i understand i sure else approach traceback recent call last file pyshell line module wordnoforbidden file cpythontestpy line wordnoforbidden forbidden word typeerror string requires string left operand tuple,1 import sybase helpsybaseconnect help function connect module sybase connectdsn user passwd databasenone strip autocommit delayconnect locking datetimenone bulkcopy localenone inputmapnone outputmapnone the first argument dsn hostname so configure dsn test isql use script,i host use ipportbut throws exception sybasedatabaseerror layer origin ctconnect directory service layer internal directory control layer error pysybasepre sybaseopenclient any idea thanks ford,1 the cacheddb cache backends support easy create djangocontribsessionsbackendscache import sessionstore cachedsessionstore djangocorecache import getcache djangoconf import settings class sessionstorecachedsessionstore a cachebased session store def initself sessionkeynone selfcache getcachesettingssessioncachealias supersessionstore selfinitsessionkey no need cacheddb backend since redis persistent anyway when using memcached cacheddb bit complex sessionstore implemented we replace completely djangoconf import settings djangocontribsessionsbackendsdb import sessionstore dbstore djangocorecache import getcache class sessionstoredbstore implements cached database backed sessions now control cache def initself sessionkeynone supersessionstore selfinitsessionkey selfcache getcachegetattrsettings sessioncachealias default def loadself data selfcachegetselfsessionkey none data none data supersessionstore selfload selfcachesetselfsessionkey data settingssessioncookieage return data def existsself sessionkey return supersessionstore selfexistssessionkey def saveself mustcreatefalse supersessionstore selfsavemustcreate selfcachesetselfsessionkey selfsession settingssessioncookieage def deleteself sessionkeynone supersessionstore selfdeletesessionkey selfcachedeletesessionkey selfsessionkey def flushself removes current session data database regenerates key selfclear selfdeleteselfsessionkey selfcreate,i django app set use multiple caches i hope is way set session use specific cache stuck default here caches default backend utilbackendssmartmemcachedcache location timeout anonymousonly true someothercache backend utilbackendssmartmemcachedcache location timeout anonymousonly true prefix something sessionengine djangocontribsessionsbackendscacheddb,2 you got indentation problem the selfsession session line everything inside init method inside class body session defined class body inside init mention question get error if remove line first thing gets looked self selfplayers selfsessionlistofplayerssplit get self defined error,i entirely sure happened i debugging script worked fine except said intermittent bugs sudden module cannot imported anymore i undid changes still problem exists well problems plural once i got unexpected indent error even though lines perfectly indented i fixed one deleting line retyping now following code i get one two errors class lottery def initself session selfprizes prizelist selfsession session selfplayers selfsessionlistofplayerssplit selfpickwinner most time gives error saying session defined this true i importing module it gets defined script calling runs i experimented removing line altogether told self defined all original code working minutes ago bugs i fixing different part module altogether certainly importing without problems please help traceback file minecraftmcadminpy line module lotterylottery import file hometomthorogoodminecraftlotterylotterypy line module class lottery file hometomthorogoodminecraftlotterylotterypy line lottery selfsession session nameerror name session defined edit solved okay somehow editing i accidentally switch tabs spacing lead problem i deleted rewrote block code exactly pasted working there ghost indent problem double edit core problem i recently turned autoindenting vim the configuration i using using tabs autoindents i using tabs past,1 here excellent resource open id providers form nice jquery plugin httpjvancecompagesjqueryopenidpluginxhtml,i successful methods log using federated log site google app engine python userscreateloginurl google httpswwwgooglecomaccountsoid userscreateloginurl yahoo httpopenloginyahooapiscomopenidwwwyahoocomxrds i wish provide log options users can anyone help getting federated identity facebook myspace wordpress etc,1 loadprofilereadline specifically says cap byte mean line try readit loadprofilereadline,i trouble reading entire specific line text file using python i currently loadprofile open usersfiletxt r readit loadprofilereadline print readit of course read one byte first line i want i also tried google find anything,1 what conditions line is certain index does contain certain string does match regex this code match single line file based string loadprofile open usersfiletxt r readit loadprofileread myline line readitsplitlines line this line i looking myline line break print myline and give first line file several ways well loadprofile open usersfiletxt r readit loadprofilereadsplitlines print readit or loadprofile open usersfiletxt r readit loadprofilereadline print readit check python file objects docs filereadlinesize read one entire line file a trailing newline character kept string may absent file ends incomplete line if size argument present nonnegative maximum byte count including trailing newline incomplete line may returned when size empty string returned eof encountered immediately note unlike stdio‘s fgets returned string contains null characters occurred input filereadlinessizehint read eof using readline return list containing lines thus read if optional sizehint argument present instead reading eof whole lines totalling approximately sizehint bytes possibly rounding internal buffer size read objects implementing filelike interface may choose ignore sizehint cannot implemented cannot implemented efficiently edit answer comment noah loadprofile open usersfiletxt r readit loadprofileread mylines line readitsplitlines linestartswithstart line lineendswithline end linefindsubstring line this line i looking mylinesappendline print mylines,i trouble reading entire specific line text file using python i currently loadprofile open usersfiletxt r readit loadprofilereadline print readit of course read one byte first line i want i also tried google find anything,3 ha found way least render page characters display correctly least renders something page the code simply mystring unicodemystring errors replace edit found even better way import chardet chartype chardetdetectmystring perhaps may want check confidence encoding first chartype confidence something mystring mystringdecodechartype encoding encode utf works like charm although characters still seem missing shows previous method,i working c assignment school here exact wording assignment write program prints list integers corresponding ascii character the actual code simple enough include stdioh int main int printfd cn return however i need display output webpage django i compiled code gcc stdc option enabled outputs fine however within webpage output anything our django view using popen open executable code ospathisfilefilesh output popenpopenfileshread page tested function c code class i added print statement within view verify output code sent browser correctly gets displayed correctly terminal browser in fact displayed browser upon inspection absolutely nothing within tag page would normally display output code i guessing something character encoding any ideas edit i forgot mention template i specified character encoding utf meta tag edit a friend mine version displays contents text file saved windows utf httpgeekingreendyndnsorgweekassignment tries display page output executable gets problem,1 def readlinenumberxfilex indexline enumerateiterfile index x return line return none f open filename x linenumberx readlinenumberxfx this return third line,i trouble reading entire specific line text file using python i currently loadprofile open usersfiletxt r readit loadprofilereadline print readit of course read one byte first line i want i also tried google find anything,1 you could use webapp outside app engine little app engine specific designed thus packaged documented separately if want webapplike framework use anywhere check webapp it close copy webapp lot improvements extensions in fact app engine team like much official replacement webapp python platform,google app engine includes minimal framework called webapp google code list project page webapp the documentationinformation google webapp google app engine documentation is webapp usable outside gae,1 edited eol recommended specific answering question create dim array i find scalar constructor either data nparray dtype start date s n int datandim access element dim array typedata class numpyvoid data b data start date b there also item method however returns element python type typedataitem class tuple i think easiest think structured arrays recarrays list arrays tuples indexing works name selects column integers selects rows tupleli range tupleli dt dtype start date s n npint dt start date s n class numpyint zero dimensional array element tuple ie one record changed scalar element see end data nparraytupleli dtypedt datashape data start date arrayb dtype s data n array dtypeint array one element data nparraytupleli dtypedt datashape data b array data nparraytupleli dtypedt datashape data b data start date arrayb b b b b dtype s data n array dtypeint direct indexing single record eol example i know works data data b data n data start date b trying understand eol example scalar element zerodimensional array different typedata class numpyndarray typedata get element dim array class numpyvoid data traceback recent call last file pyshell line module data indexerror arrays indexed data b datandim datandim note i typed example open python interpreter accident b,is possible create numpy object behaves much like collectionsnamedtuple sense elements accessed like data data start date slight generalization possible namedtuple i tried use complex data type data numpyemptyshapetuple dtype start date s n int this creates dimensional value kind namedtuple type almost works data start date data array dtype start date s n however element access work array dimensional data traceback recent call last file ipythoninputedb line module data indexerror arrays indexed is way obtaining desired behavior described item assignment string index numpy object,1 moksha moksha open source python web framework aims simplify creation highlyinteractive realtime web applications,i going developing web application uses realtime use http push service pusher rich client javascript jqueryui backbonejs i need framework following features it must fast bridge ajax requests push server it must complete user system simple authorization registration profile password recovery etc builtin plugin scalability my available languages php python ruby language preference python i think probably python efficient three easy scale correct i wrong i thinking using webpy even though i hate uppercase code read fast brings complete user system compatible gae thank ps i know tornado socketio comet i looking framework communicate server push implement,1 you multiply strings for example x gives xxx so size intinput convert whatever int printsize size x n print whole thing this intuitive languages let getting input straightforward enough,get number user n create n x n box xes screen without using loops yet eg if entered xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx the point assignment use string manipulation create box i loop i sure strings can anyone help,2 the model class foomodelsmodel email modelscharfieldmaxlength def getemailreversedself return selfemail def setemailreversedself value selfemail value emailreversedpropertygetemailreversed setemailreversed and form class fooformformsmodelform class meta model foo not sure meant screws form model form one field email i also added example models used def testfooself foo foo fooemail mocelpmaxeliametset selfassertequalsfooemailreversed testemailexamplecom def testsetfooreversedself foo foo fooemailreversed testemailexamplecom selfassertequalsfooemail mocelpmaxeliametset,for database indexing purposes email field model needs stored reverse i end needing access reversed forward version email field i curious following methods would considered best practice method a override save method model this method denormalizes database work update method queryset some need override forms generated model class foomodelsmodel emailforward modelscharfieldmaxlength emailreversed modelscharfieldmaxlength def saveself args kwargs selfemailreversed reversedselfemailforward superfoo selfsaveargs kwargs method b this way better database normalization still allows use update method querysets screws forms end override default forms generated model class foomodelsmodel email modelscharfieldmaxlength property def emailforwardself hasattrself emailf selfemailf reversedselfemail return selfemailf emailsetter def emailforwardself value selfemailf value selfemail reversedvalue propery def emailreversedself return selfemail clarification any alternative answers need meet minimum requirement reversed email stored database this question however much finding answer specific problem getting feedback best practices sort scenario two fields computed one another one required frontend context backend context,1 you send line using sendline whenever want arrive immediately may problem related server blocking a call sendline deferred make call middle bunch processing possible actioned message received reactor interrupts processing receives message gets queued message sent going back processing you read answers make sure processing blocking main thread,i server twisted implementing linereceiver protocol when i call sendline response client message writes line client immediately one would expect but say client asks server lengthy calculation i want server periodically send progress message client when server takes initiative calls sendline without client asked anything seems wait client send message server sending anything how i send message server client immediately without client explicitly ask,1 you passing string ie timer supermegaintensefunction main import supermegaintensefunction,i struggling using timeit wondering anyone tips basically i functionthat i pass value i want test speed created name main timeit import timer timersupermegaintensefunction print ttimeitnumber i run i get weird errors like coming timeit module valueerror stmt neither string callable if i run function works fine its i wrap time module i get errorsi tried using double quotes withoutsameoutput suggestions would awesome thanks,3 make callable name main timeit import timer timerlambda supermegaintensefunction print ttimeitnumber should work,i struggling using timeit wondering anyone tips basically i functionthat i pass value i want test speed created name main timeit import timer timersupermegaintensefunction print ttimeitnumber i run i get weird errors like coming timeit module valueerror stmt neither string callable if i run function works fine its i wrap time module i get errorsi tried using double quotes withoutsameoutput suggestions would awesome thanks,3 you return one usrbinenv python def main print main function args one returns myargs assigning args print got args one args print argspop def one print one function myargs qa return myargs def two print two function name main main getattrmyargs pop moved main outputs main function one function got args one qa qa,how get access myargs list data type main testpy usrbinenv python def main print main function one def one print one function myargs qa def two print two function name main main getattrmyargs pop,2 timersupermegaintensefunction means call supermegaintensefunction pass result timer that clearly want timer expects either callable sounds something called function string interpret contents string python code timer works calling callablething repeatedly seeing much time taken timersupermegaintensefunction would pass type check supermegaintensefunction callable however timer know values pass supermegaintensefunction the simple way around course use string code we need pass setup argument code string interpreted code fresh context access globals need run another bit code make definition available see oxtopus answer with lambda pablo answer bind parameter call supermegaintensefunction all creating another function takes arguments calls supermegaintensefunction it used def create another function like except new function get name need one,i struggling using timeit wondering anyone tips basically i functionthat i pass value i want test speed created name main timeit import timer timersupermegaintensefunction print ttimeitnumber i run i get weird errors like coming timeit module valueerror stmt neither string callable if i run function works fine its i wrap time module i get errorsi tried using double quotes withoutsameoutput suggestions would awesome thanks,3 use subprocesspopen docs just call communicate resulting object,i trying figure best solution accomplish basically i want open another program python matter could image executable etc i tried ossystem subprocesscall however terminate script instead wait return i looked osexecl seems close i need i sure i understand arg i always get exec format errors invalid arguments i even sure proper function i need any help would appreciated i tried using subprocesscall subprocesspopen using something similar import subprocess subprocesspopenbtesttxt ends following error windowserror error access denied,1 a little change input root node flair i use parent id instead import json pc pcappend flair pcappend analytics pcappend cluster pcappend agglomerativecluster pcappend communitystructure pcappend graph pcappend betweennesscentrality pcappend linkdistance def listtodictinput root lookup parentid id name attr input parentid root name name lookupid root else node name name lookupparentidsetdefault children appendnode lookupid node return root result listtodictpc print result print jsondumpsresult,i list list like the first column parent second child third node attributes i need convert json format like following flair analytics cluster agglomerativecluster communitystructure graph betweennesscentrality linkdistance pc pcappend flair pcappend analytics pcappend cluster pcappend agglomerativecluster pcappend communitystructure pcappend graph pcappend betweennesscentrality pcappend linkdistance name flare children name analytics children name cluster children name agglomerativecluster size name communitystructure size name graph children name betweennesscentrality size name linkdistance size,1 not sure size attributes coming appear pc list assuming taken th item list output tree work def maketreepclist results record pclist parentid record id record id results node resultsid else node resultsid node name record node size record parentid id parentid results parent resultsparentid else parent resultsparentid children parent parent children appendnode else parent children node assuming wanted node id top tree return results pretty printing output maketreepc i get children children children name agglomerativecluster size name communitystructure size name cluster size children name betweennesscentrality size name linkdistance size name graph size name analytics size name flair size although ordering key display different almost like sample output except size values,i list list like the first column parent second child third node attributes i need convert json format like following flair analytics cluster agglomerativecluster communitystructure graph betweennesscentrality linkdistance pc pcappend flair pcappend analytics pcappend cluster pcappend agglomerativecluster pcappend communitystructure pcappend graph pcappend betweennesscentrality pcappend linkdistance name flare children name analytics children name cluster children name agglomerativecluster size name communitystructure size name graph children name betweennesscentrality size name linkdistance size,1 use instead morelatestappearances end index noninclusive slicing abcdef abc abcdef ef abcdef def in order clarify things i suggest rewriting code little look like appearances issueobjectsorderby id orderby pubdate latestappearances appearances morelatestappearances appearances this way single query split results rather separate queries might return results differing order,i want retrieve latest objects shows shell lastissues issueobjectsorderby id orderby pubdate print lastissues issue xmen v issue uncanny xmen issue herc issue xmen schism issue xmen v issue xmen first class the high hand issue astonishing xmen issue xmen v issue generation hope issue xmen schism issue uncanny xmen issue xmen schism issue new mutants v note herc marked in template i slider shows latest objects rest objects slider so i latestappearances issueobjectsorderby id orderby pubdate morelatestappearances issueobjectsorderby id orderby pubdate latestappearances shows issue xmen v issue xmen schism issue uncanny xmen morelatestappearances shows issue xmen v issue xmen first class the high hand issue xmen v issue astonishing xmen issue xmen schism issue uncanny xmen issue generation hope issue xmen schism issue new mutants v issue secret avengers notice herc gone now since i ordered pubdate issues lastissues pubdate i fix i made sure issues show pubdate obviously help i issues pubdate ordering issues id help either sometimes i go back add older issues sometimes issues highest id actually latest issues ok odd case closed i slice template instead workswhich weird work views but anyone figure kudos,1 places asiaeuropelatamus placessort def getsectionplacesrequests pl lenplaces lastplaces r requests p rangepl r rlastkeep away integers range rplacesp print rplacesp break else break a call getsection getsectionplaces gives asia latam us,i simplest problem implement far i able get head around solution python i built table looks similar one asia europe latam us i test certain value see falls within ranges asia latam us a value greater return lookup value i normally one one match would implement dictionary lookup but case i consider ranges i seeing way problem maybe without providing whole solution could provide comments would help look right direction it similar vlookup spreadsheet i would describe python knowledge somewhere basic intermediate many thanks advance,1 join name c x n b g r h p w joinname icxnybgrhpwo,i trying make script generate random string text run i got far im problem formatting here code im using import random alphabet abcdefghijklmnopqrstuvwxyz min max name randomsamplealphabetrandomrandintminmax print name and ever end c x n b g r h p w i trying format one line string example c x n b g r h p w icxnybgrhpwo,3 assuming code handler invocation cursors work identically declared queries if changes query changes previouslysaved cursor work,do know cursor working when i click more results results displayed thanks n query mainall queryfiltertaglist queryorderdate cursor selfrequestgetcursor cursor querywithcursorcursor items queryfetch cursor querycursor item items mainid itemkeyid selfresponseoutwritep hrefs targetblankspan idlargesspana hrefcommentmainidsspan idsmallcommentsspanabr hrefeditmainidsampurlpathsearchhandlersearchstringsspan idsmalleditspana p itemurl itemtitle mainid ftruncateatspaceitempitch mainid searchstring selfresponseoutwrite hrefsearchhandlercursorsmore resultsa cursor edit as dave w smith answer problem changed cursor called i paste code log info class searchhandlerwebapprequesthandler def getself search form selfresponseoutwrite form namesearchform actionsearchhandler methodgetbr input typetext namesearchstring size input typesubmit valuesearch tags form searchstring selfrequestgetsearchstring filternone fstriplistselfrequestgetsearchstringsplit logginginfos cursor u python cursor n lens n query mainall queryfiltertaglist queryorderdate logginginfos u python cursor selfrequestgetcursor cursor querywithcursorcursor items queryfetch cursor querycursor relatedtags items logginginfos u python item items tag itemtaglist relatedtagsappendtag uniquetags sortedffrelatedtags tag uniquetags selfresponseoutwrite hrefrtrtssa tag tag selfresponseoutwritebr item items mainid itemkeyid selfresponseoutwritep hrefs targetblankspan idlargesspana hrefcommentmainidsspan idsmallcommentsspanabr hrefeditmainidsampurlpathsearchhandlersearchstringsspan idsmalleditspana p itemurl itemtitle mainid ftruncateatspaceitempitch mainid searchstring selfresponseoutwritea hrefsearchhandlercursorsmore resultsa cursor logginginfos u python selfresponseoutwritebr br else selfredirectnomatch edit problem solved suggested dave smith class searchhandlerwebapprequesthandler def getself searchstring selfrequestgetsearchstring searchstring filternone fstriplistselfrequestgetsearchstringsplit selfresponseoutwrite form namesearchform actionsearchhandler methodgetbr input typetext namesearchstring size values input typesubmit valuesearch tags form searchstring else ss selfrequestgetss filternone fstriplistselfrequestgetsssplit selfresponseoutwrite form namesearchform actionsearchhandler methodgetbr input typetext namesearchstring size values input typesubmit valuesearch tags form ss n lens n query mainall queryfiltertaglist queryorderdate cursor selfrequestgetcursor cursor querywithcursorcursor items queryfetch cursor querycursor selfresponseoutwritea hrefsearchhandlercursorsampsssmore resultsa tuplecursor searchstring,1 it seems want simple recursive function like def converttojtreebt return jtreebtdata converttojtreebtleft btleft else none converttojtreebtright btright else none something similar,i binary tree class class btree def initself data leftnone rightnone selfdata data selfleft left selfright right def unicodeself return selfdata i another tree serializing method listed class jtreeobject def initself id childrennone selfid id children none children selfchildren children def encodetreeobj isinstanceobj jtree raise typeerrorr json serializable return objdict i populate binary tree data bt btree btleft btree btrightbtree i serialize data i get following result tree jtreebtdata jtreebtleftdata jtreebtrightdata print jsondumpstree defaultencodetree id children id children id children the problem i figure program piece code generate result which means i want generator recursive function run code jtreebtdata jtreebtleftdata jtreebtrightdata can somebody give idea thanks,1 use json module import json jsondumpsrange print reprs print jsonloadss,i currently issue getting javascript python communicate webpy controller def testdb aappend aappend b aappend c return dictma eventually replaced array db rows currently i trying assign values array javascript i tried ways var tm returns meaningless characters then i tried var new array var iq ilenmessage ii forqqiqqq tqmq which failed python q variable would reset every time loop heart problem i also tried using pop forqqiqqq alertmpop but array keeps resetting start loop keeps showing variable is simpler way copy arrays stop python variables resetting even simply plug javascript q variable mq instead from i found problem comes python server side assign javascript values variables i sure loop part if i outside loop values reset the common solution seems use ajax json i like avoid possible thanks,1 this fixed since python clearly noted documentation in words book incorrect date,i following apress beginning python novice professional book it mentioned finally you use tryfinally need make sure code example cleanup code executed regardless whether exception raised this code put finally clause note cannot except clauses finally clause try statement—but put one inside i tried code def somefunction none try except zerodivisionerror e print yesss print e finally print cleanup del name main somefunction output yesss integer division modulo zero cleanup here i used except finally try segment i and code works fine expected i quite get book says someone please clarify thanks,3 that book might wrong i afraid python documentation uses three maybe time get new book,i following apress beginning python novice professional book it mentioned finally you use tryfinally need make sure code example cleanup code executed regardless whether exception raised this code put finally clause note cannot except clauses finally clause try statement—but put one inside i tried code def somefunction none try except zerodivisionerror e print yesss print e finally print cleanup del name main somefunction output yesss integer division modulo zero cleanup here i used except finally try segment i and code works fine expected i quite get book says someone please clarify thanks,1 i believe book actually gives example hence i know meant exactly as previous answer noted changed python try try print something except print weird error finally print finally something is equivalent try print something except print weird error finally print finally,i following apress beginning python novice professional book it mentioned finally you use tryfinally need make sure code example cleanup code executed regardless whether exception raised this code put finally clause note cannot except clauses finally clause try statement—but put one inside i tried code def somefunction none try except zerodivisionerror e print yesss print e finally print cleanup del name main somefunction output yesss integer division modulo zero cleanup here i used except finally try segment i and code works fine expected i quite get book says someone please clarify thanks,3 the easiest way define relationship outside class classes defined remove definition latestarticle newspaper add following code class article definition taken directly mike answer linked define relationship tarticle articletable tnewpaper newspapertable latestc selecttarticlecid wheretarticlecnewspaperid tnewpapercid orderbytarticleciddesc limit correlatetnewpaper asscalar newspaperlatestarticle relationshiparticle primaryjoinand tarticlecidlatestc tarticlecnewspaperidtnewpapercid uselistfalse one note though relationship working directly database include article instances yet commited part session and probably would ones really want so careful,i using sqlalchemy declarative syntax i like specify relationship provides latest max primary id element collection i found post how i define sqlalchemy relation representing latest object collection i tough time using pattern creating subquery using declarative any pointers help would greatly appreciated general idea sqlalchemyextdeclarative import declarativebase base declarativebasebindengine metadatametadata sqlalchemy import sqlalchemyorm import class newspaperbase tablename newspapers id columninteger nullablefalse primarykeytrue name columnstring latestarticle relationshiparticle primaryjoinarticlenewspaperidnewspaperid amp articleidsubqueryforlatestid def reprself return name formatselfname class articlebase tablename articles id columninteger nullablefalse primarykeytrue title columnstring newspaperid columninteger foreignkey newspapersid newspaper relationshipnewspaper backrefbackref articles def reprself return title formatselftitle,1 eryksun thank trying your answer lead find solution i missing msvc equivalent gcc shared ld compiling i initially developed tested dll functions c added exports forgot add ld option i mark question solved i still wonder causes access violation i proper dllmain,i following bare minimum function dll define intelhookapi extern c declspecdllexport intelhookapi bool testfuncvoid bool success false hwnd parent null parent findwindowariumsourcepont null parent null success true return success if i call main function dll works fine if i call python i get following windowserror exception access violation reading x my python script looks like ctypes import dll cdllhook print dlltestfunc i running win bit dll python bit cprojectshghooklibdumpbin headers hookdll microsoft r coffpe dumper version copyright c microsoft corporation all rights reserved dump file hookdll pe signature found file type executable image file header values c machine x print sysversion default jun msc v bit intel i attached debugger seem solve pythonexe loaded cpythonpythonexe pythonexe loaded cwindowssyswowntdlldll symbols loaded source information stripped pythonexe loaded cwindowssyswowkerneldll symbols loaded source information stripped pythonexe loaded cwindowssyswowkernelbasedll symbols loaded source information stripped pythonexe loaded cwindowssyswowpythondll pythonexe loaded cwindowssyswowuserdll symbols loaded source information stripped pythonexe loaded cwindowssyswowgdidll symbols loaded source information stripped pythonexe loaded cwindowssyswowlpkdll symbols loaded source information stripped pythonexe loaded cwindowssyswowuspdll symbols loaded source information stripped pythonexe loaded cwindowssyswowmsvcrtdll symbols loaded source information stripped pythonexe loaded cwindowssyswowadvapidll symbols loaded source information stripped pythonexe loaded cwindowssyswowsechostdll symbols loaded source information stripped pythonexe loaded cwindowssyswowrpcrtdll symbols loaded source information stripped pythonexe loaded cwindowssyswowsspiclidll symbols loaded source information stripped pythonexe loaded cwindowssyswowcryptbasedll symbols loaded source information stripped pythonexe loaded cwindowssyswowshelldll symbols loaded source information stripped pythonexe loaded cwindowssyswowshlwapidll symbols loaded source information stripped pythonexe loaded cwindowswinsxsxmicrosoftvccrtfcbbaeebnonefebcbebmsvcrdll symbols loaded source information stripped pythonexe loaded cwindowssyswowimmdll symbols loaded source information stripped pythonexe loaded cwindowssyswowmsctfdll symbols loaded source information stripped pythonexe loaded cwindowssyswowpgpmapihdll pythonexe loaded cpythondllsctypespyd pythonexe loaded cwindowssyswowoledll symbols loaded source information stripped pythonexe loaded cwindowssyswowoleautdll symbols loaded source information stripped pythonexe loaded cprojectshghooklibhookdll symbols loaded the thread win thread xb exited code x firstchance exception xdae hookdll pythonexe xc access violation reading location x the program pythonexe native exited code x the happens i access function java jna given function works calling main dll makes believe access restriction make sense i first one calling win functions indirectly dll thank advance taking time read cheers,1 osexeclpstart rbtesttxt that windows on unix system running x osexeclpxdgopen rbtesttxt,i trying figure best solution accomplish basically i want open another program python matter could image executable etc i tried ossystem subprocesscall however terminate script instead wait return i looked osexecl seems close i need i sure i understand arg i always get exec format errors invalid arguments i even sure proper function i need any help would appreciated i tried using subprocesscall subprocesspopen using something similar import subprocess subprocesspopenbtesttxt ends following error windowserror error access denied,1 in code posted double precision float passing fortran python means wrapping fortran double pyfloat object cost in pure python version k pyfloat pay price wrapping times another issue function call calling python functions c already bad performancewise calling fortran worse additional layer code transform fortran function call conventions regarding stack etc c function call conventions when calling python function c need prepare arguments python objects generally create pytuple object serve args argument python function make lookup table module get function pointer last least need take care array orders passing d arrays fortran numpy fpy numpy smart regard get performance hits python code written manipulate arrays fortran order i know pyfunc meant close posted writing loop python calling function save time and need intermediate values p let python function return numpy array intermediate values,i wrapped fortran subroutine python using fpy the subtlety fortran subroutine aslo takes python callback function one arguments subroutine ffoopyfunc realkindintentin fpy intentcallback pyfunc external pyfunc fpy real yx fpy pyfuncx debug begins print start loop p pyfunca end total etimeelapsed print end total total user elapsed system elapsed stop debug ends the pyfunc python function defined elsewhere python code the wrapper works fine running wrapped version i got elapsed time factor times longer i get using pure python follows def pythonfook k scalar returns scalar print pure python start loop start timetime xrange p pyfunck elapsed timetime start print end totalf elapsed so question overhead coming i really want leave pyfunc extremely timeconsuming recode pure fortran function way improve speed wrapper module,3 by preventing pip writing line twisted egginfotopleveltxt keep using packages twistedplugins working pip uninstall remove twisted this involves monkeypatching setuptoolsdistribute near top setuppy here sample setuppy distutilscore import setup when pip installs anything packages pymodules extmodules includes twistd plugin installed twistedplugins setuptoolsdistribute writes packageegginfotopleveltxt includes twisted if later uninstall package pip uninstall package pip removes twisted instead package twistd plugins see httpsgithubcompypapipissues fixed to work around problem monkeypatch setuptoolscommandegginfowritetoplevelnames write line twisted this fixes behavior pip uninstall package note even workaround pip uninstall package still correctly uninstalls package twistd plugins twistedplugins since pip also uses packageegginfoinstalledfilestxt determine uninstall paths plugin files indeed listed installedfilestxt try setuptoolscommand import egginfo egginfowritetoplevelnames except importerror attributeerror pass else def toplevelpackagename return namesplit def hackedwritetoplevelnamescmd basename filename pkgs dictfromkeys toplevelpackagek k cmddistributioniterdistributionnames toplevelpackagek twisted cmdwritefiletoplevel names filename n joinpkgs n egginfowritetoplevelnames hackedwritetoplevelnames setup name mypackage version descriptionyou anything mypackage anything urlhttpexamplecom authorjohn doe authoremailjdoeexamplecom packages mypackage twistedplugins you may want options including installrequires packagedata classifiers make twisted regenerate dropincache possible this necessary sitewide install dropincache cannot rewritten normal users try twistedplugin import iplugin getplugins except importerror pass else listgetpluginsiplugin i tested pip install pip install user easyinstall with install method monkeypatch pip uninstall work fine you might wondering i need clear monkeypatch avoid messing next install eg pip install nodeps mypackage twisted want affect twisted topleveltxt the answer monkeypatch affect another install pip spawns new python install related keep mind project must file twistedpluginsinitpy if see warning installation package init file twistedpluginsinitpy found regular file completely normal try fix adding initpy,the twisted plugin system preferred way write extensible twisted applications however due way plugin system structured plugins go twistedplugins directory python package writing proper setuppy installing plugins appears nontrivial i seen attempts add twistedplugins packages key distutils setup command since really package bad things happen example initpy helpfully added tools other attempts seem use packagedata instead eg httpbazaarlaunchpadnetglyphdivmodorgtrunkviewheadepsilonepsilonsetuphelperpy also fail weird ways the question anyone successfully written setuppy installing twisted plugins works cases,3 you could use repeat in arepeataxisrepeataxis out array i sure neat way combine two operations one,i would like scale array shape h w factor n resulting array shape hn wn say i x array array i would like scale array become x array that value cell original array copied corresponding cells resulting array assuming arbitrary array size scaling factor efficient way,3 so i got worked better format cleaner print code thanks help guys if anyone wants know difference codes getting floating point like others suggested converting needed integers multiplying integers specific amount say quarter subtracting int coinbill change worked well i tried experimenting statement turn well since i know lot yet either until next time again thanks guys here finished code anyone wondering import sys due inputplease enter amount due itemsn exit due print please enter amount lower sysexit underequal exit due print please enter amount greater sysexit due change converts change cents pennies per dollar else change due change done change print no change return makes change amount return else change change print amount returnn f change change subract get bill change bill change b intbill change change change change divided subtracted change quaters change dollars change dollar intdollars change change dollar change quaters change quater intquaters change change quater change dimes change dime intdimes change change dime change nickels change nickel intnickels change change nickel change pennies change penny intpennies change change penny print change returnn quatersin dimesin nickelsin penniesi b dollar quater dime nickel penny change print done,updated new code bottom page answer so cs class make program user input less change returned least amount coins bills cent pieces for part program well except run xx eg python va jun gcc apple inc build dot darwin type copyright credits license information restart amount due amount return quaters return dimes return nickels return program completely skips dimes section straight nickels providing solution least amount quarters dimes end also i really skilled loops much i know would possible lot shorter code cleaning code advice would nice well thanks help optionalpy calculating least amount change return bill amount due due inputamount duen amount exit program due print please enter number lower exit amount less exit program due print please enter number greater exit subtract amount else change due print amount returnn f change amount change change print no change return passes expression previous met pass elif change setting q dividing change q change maaking q integer quaters intq print quaters return r quaters subtracting quaters chane change change quaters change pass elif change change dimes intd print dimes return r dimes change change dimes change pass elif change n change nickels intn print nickels return r nickels change change nickels change pennies change print pennies return r pennies elif change p change print pennies return f p,1 you use kronecker product numpykron computes kronecker product composite array made blocks second array scaled first import numpy np nparray n npkrona nponesnn gives want array,i would like scale array shape h w factor n resulting array shape hn wn say i x array array i would like scale array become x array that value cell original array copied corresponding cells resulting array assuming arbitrary array size scaling factor efficient way,3 at end i settled branch makefile packaging procedure looks something like git checkout debianpackaging make getsource make deb copymypackageoutofthewayhere make reset if interested find full makefile disclaimer first makefile ever quite possible best makefile ever see in nutshell core trick getsource directive use git archive command accepts name branch argument produces tarball source branch here snippet fetch source code desired branch getsource git archive sourcebranch sourcebranchtar tar xf sourcebranchtar rm sourcebranchtar echo the source code fetched hope helps somebody else,for last python project i developed i used git versioning system now time development cycle i begin ship packages beta testers case would deb packages in order build packages i need number extra files copyright iconxpm setuppy setupcfg stdebcfg etc i would like keep separate source program source might used prepare packages platforms would make sense debianspecific files lingering around my question standard waybest practice in google wanderings i stumbled couple times including so gitbuildpackage suite i sure i looking seems thought packagers download targz upstream repository i thought possible way achive i want would branch git repository i keep packagingfiles branch also able see files master branch without every time manually merge master packaging branch however i know good idea way done although i suspect might involve git symbolicref magic i idea i imagined any help appreciated thanks advance time,1 i would recommend using yet i encountered strange bugs trying you functionality i using somewhat modified code i found time ago import wx sys try import wingui wincon win true except win false class balloontaskbariconwxtaskbaricon base taskbar icon class def initself wxtaskbariconinitself selficon none selftooltip def showballoonself title text msec flags show balloon tooltip param title title balloon tooltip param msg balloon tooltip text param msec timeout balloon tooltip milliseconds param flags one wxiconinformation wxiconwarning wxiconerror win selfisiconinstalled try selfsetballoontipselficongethandle title text msec flags except exception pass printe silent error def setballoontipself hicon title msg msec flags translate flags infoflags flags amp wxiconinformation infoflags winguiniifinfo elif flags amp wxiconwarning infoflags winguiniifwarning elif flags amp wxiconerror infoflags winguiniiferror show balloon lpdata selfgeticonhandle hwnd id winguinifmessagewinguinifinfowinguinificon flags combination nif flags callbackmessage message id pass hwnd processing messages hicon hicon handle icon displayed tip tooltip text msg info balloon tooltip text msec timeout timeout balloon tooltip milliseconds title infotitle title balloon tooltip infoflags infoflags combination niif flags winguishellnotifyiconwinguinimmodify lpdata selfseticonselficon selftooltip hack access real callbackmessage value def geticonhandleself find icon window this ugly way find window directly wx hasattrself chwnd try handle wxgettoplevelwindows handlegetwindowstyle continue handle handlegethandle lenwinguigetwindowtexthandle selfchwnd handle break hasattrself chwnd raise exception except raise exception icon window found return selfchwnd def seticonself icon tooltip selficon icon selftooltip tooltip wxtaskbariconseticonself icon tooltip def removeiconself selficon none selftooltip wxtaskbariconremoveiconself app wxpysimpleapp class testtaskbariconballoontaskbaricon def initself wxtaskbariconinitself create test icon bmp wxemptybitmap dc wxmemorydcbmp dcsetbrushwxredbrush dcclear dcselectobjectwxnullbitmap testicon wxemptyicon testiconcopyfrombitmapbmp selfseticontesticon selfbindwxevttaskbarleftup lambda e selfremoveiconsysexit selfshowballoon hello world icon testtaskbaricon appmainloop,i recently upgraded development release wxpython wxpython since i needed functionality wxnotificationmessage within application i trying unsuccessfully create notification bubbles certain user events due something i think might possible bug before submitting bug i wanted go ahead ask people mailing list think might problem hopefully find solution within code here code i used import wx sys app wxpysimpleapp class testtaskbariconwxtaskbaricon def initself wxtaskbariconinitself create test icon bmp wxemptybitmap dc wxmemorydcbmp dcsetbrushwxredbrush dcclear dcselectobjectwxnullbitmap testicon wxemptyicon testiconcopyfrombitmapbmp selfseticontesticon selfbindwxevttaskbarleftup lambda e selfremoveiconsysexit wxnotificationmessage hello worldshow icon testtaskbaricon appmainloop on windows computer code creates small white task bar icon creates popup phrase hello world the problem the message icon another icon created message placed see image httpwwwpasteallorgpic what i thought probably due fact i passed parent parameter line wxnotificationmessage hello worldshow here i changed wxnotificationmessage hello world selfshow where self refers task bar icon when i i get error traceback recent call last file cpythontestnotificationmessagepy line module icon testtaskbaricon file cpythontestnotificationmessagepy line init wxnotificationmessage hello world selfshow file cpythonlibsitepackageswxmswwxmiscpy line init miscnotificationmessageswiginitselfmiscnewnotificationmessageargs typeerror method newnotificationmessage expected argument type wxwindow what going if i remove argument i get result i add argument i get error how i supposed use wxnotificationmessage wxtaskbaricon please help i hope i provided enough details please comment need,3 python garbage collection need release memory manually,is way free memory google app engine is garbage collector python,3 python managing garbage collection normally need manual memory release although check python gc lib want manually,is way free memory google app engine is garbage collector python,3 here similar question whats best way implement enum python it suggests implementing something like class myclass a the letter a b the letter b c the letter c d the letter d variable myclassa ok variable myclasse error with get ide autocomplete well which contrary slott opinion i use time old java habit i guess it considered poor style use docstring restate obvious i think case makes code readability worse for information docstrings httpwwwpythonorgdevpepspep if curious enum type python might check pep httpwwwpythonorgdevpepspep,let assume current code using strings parameters want document valid values example def myfuncregion none region a b c none dosomething else complain invalid parameter now question i improve design order solve two problems able use autocomplete functionality ides autocomplete possible values parameter document list valid values parameter currently code documented using doxygen,2 o compiler flag set runtime script already compiled python nothing comparable compiler macros like simply write startmyprojectsh script sets flags,i like set optimize flag python o myscriptpy runtime within python script based command line argument script like myscriptpy optimize myscript nodebug i like skip assert statements without iffing away or better way efficiently ignore sections python code are python equivalents ifdef c,3 first make sure using latest coverage version assuming django project lives projectparentproject projectparent run coverage html includeproject give coverage report project ie output rd party lib coverage,i simple django project contains applicationseverything works wellnow check code coverage projecti installed coverge tool tried know coverage typing coverage report terminalit shows result like name file project stms number miss number cover in caseit display result shows file names projectit didnt shows coverage files projecthow make show file name please suggest better working coverage tool know,2 usrbinenv python def main assert printtada namemain import os sys optimize sysargv sysargvremove optimize osexeclsysexecutable sysexecutable o sysargv else main,i like set optimize flag python o myscriptpy runtime within python script based command line argument script like myscriptpy optimize myscript nodebug i like skip assert statements without iffing away or better way efficiently ignore sections python code are python equivalents ifdef c,2 if reading cells top bottom left right like us use optimized reader httpopenpyxlreadthedocsorgenlatestoptimizedhtml it works quite fast cpu bound smaller memory footprint regular reader disclaimer i author openpyxl,rownum range lenselfsheetrows cell selfsheetrowsrownum print cellvalue i want access cell values sheet row row openpyxl above code works slow how i access cell values faster,3 the authentication plone flexible modular after short search i found product already provides kind auth need write custom pas pluggable authentication service plugin more info httpploneorgdocumentationmanualdevelopermanualusersandsecuritypluggableauthenticationservice httpploneorgdocumentationmanualdevelopermanualarchetypesappendixpracticalsborgcreatingcontenttypestheplonewaywritingacustompasplugin,i new plone python but comes scenario want customize existing plone installation login include two factor auth duosecurity what easiest way accomplish for requirementwhat areas need explore if anyone done beforeplease give pointers,1 well writing csv file use space delimiter csv files use commas semicolons excel cell delimiters use delimiter really producing csv file you simply construct csvwriter default delimiter dialect if want read csv file later excel could specify excel dialect explicitly make intention clear although dialect default anyway example csvwriteropentestcsv wb dialectexcel,everyonei list lists i want write csv file columns rowsi tried writerows i wantan example list following thanks help with examplecsvwriteropen testcsv wb delimiter examplewriterows i get cell cell etcand cell next cell i cleari need write example list file i open excel every element cell my output like each element diferent cell,1 there native pygame way you may misunderstanding function pygame it drawing vector objects it writing pixels video surfaces since vector objects must define converted pixels doing workaround intended use pygame,this question related one in program uses pygame draw objects video i two representation world a physical one i use make calculations involved simulation objects located x metres surface a visual one i use draw screen objects located window measuring x pixels what i want achieve able pass pygame drawing functions normally accept inputs pixels physicalrealword coordinates in words i would like able say draw radius circle coordinates using precise pygame syntax pygamedrawcirclesurface get circle px radius centred pixels please note question native pygame way sort workaround achieve result want answer take look question i already mentioned instead thanks advance time support,1 use counter version,def myfuncfilename filenameopen hellotxt r linesfilenamereadlines filenameclose lengths line lines punc amp linelinereplacepunc wordslinesplit word words lengthlenword length lengths lengthslength lengthslength lengthcounter lengthsitems printlengthcounter filenameclose,1 only root setuid rootgroup enough,i trying build platform launch scripts this scripts placed home folder user every launch done user id i user userid pwdgetpwnam user userhome pwdgetpwnam user oschdir userhome ossetuid userid subprocesspopen shlexsplit userscriptpy but python trys ossetuid userid raise exception traceback recent call last file launcherpy line xx module oserror errno operation permitted by way user starts script root group gnulinux os root privileges if i try launch code root user i get different error oserror errno permission denied if someone help understand happening please,2 only superuser change uid whenever feels like adding user root group enough setuid example mentions the setuid system call permitted specified id equal real user id effective user id process effective user id super user on linux also under linux setuid implemented like posix version posixsavedids feature this allows setuserid root program drop user privileges unprivileged work reengage original effective user id secure manner i even know python directly implements exactly want anyway so short answer start initial process root if worried security start two processes one root one nonprivileged user nonprivileged process communicate root process socket this advanced setup though,i trying build platform launch scripts this scripts placed home folder user every launch done user id i user userid pwdgetpwnam user userhome pwdgetpwnam user oschdir userhome ossetuid userid subprocesspopen shlexsplit userscriptpy but python trys ossetuid userid raise exception traceback recent call last file launcherpy line xx module oserror errno operation permitted by way user starts script root group gnulinux os root privileges if i try launch code root user i get different error oserror errno permission denied if someone help understand happening please,1 first need read doc docx odt pdf second count words version,i trying get word counts doc docx odt pdf type files this pretty simple txt files i go word count mentioned types i using python django ubuntu trying word count documents words user uploads file system,2 in webpy serverside template language cannot mix serverside python code clientside javascript code way when page requested python webpy view evaluated pure html page javascript code included generated returned browser the browser get python code cannot execute mix javascript python the webpy view inserts textcode page somevalue note equals sign so things like mq effect if want see browser receiving webpy look page source browser show end result htmljavascript generated view as particular question use responsejson convert python list json object however include view escape quotes pass xml helper avoid escaping something like var xmlresponsejsonm,i currently issue getting javascript python communicate webpy controller def testdb aappend aappend b aappend c return dictma eventually replaced array db rows currently i trying assign values array javascript i tried ways var tm returns meaningless characters then i tried var new array var iq ilenmessage ii forqqiqqq tqmq which failed python q variable would reset every time loop heart problem i also tried using pop forqqiqqq alertmpop but array keeps resetting start loop keeps showing variable is simpler way copy arrays stop python variables resetting even simply plug javascript q variable mq instead from i found problem comes python server side assign javascript values variables i sure loop part if i outside loop values reset the common solution seems use ajax json i like avoid possible thanks,3 import itertools b b c e f listitertoolschainfromiterablezipab b c e f zip produces iterable length shortest argument you either append result use itertoolsziplongest iziplongest python x fill value delete value afterwards and use two input sequences solution for appending last value try dirty approach i really recommend clear b b c e f ai else bi rangelena b c e f for python x use single,i two lists length n n b b bn i want function giving result list alternate elements two b bn bn the following works look smart def listmixinglistlonglistshort listres rangelenlistshort listresextendlistlongi listshorti listresappendlistlong return listres can anyone suggest pythonic way thanks,3 mixing two lists job zip res ab ziplistlong listshort res ab lists differing lengths define function def mixlistlong listshort result ij iterlistlong iterlistshort ab zipij res ab rest result rest rest j result rest return result using answer given mihail shorten def mixlistlong listshort ij iterlistlong iterlistshort result item sublist zipij item sublist result item item result item item j return result,i two lists length n n b b bn i want function giving result list alternate elements two b bn bn the following works look smart def listmixinglistlonglistshort listres rangelenlistshort listresextendlistlongi listshorti listresappendlistlong return listres can anyone suggest pythonic way thanks,2 sumxy xy zipbab note this works given list lengths easily extended arbitrary length lists,i two lists length n n b b bn i want function giving result list alternate elements two b bn bn the following works look smart def listmixinglistlonglistshort listres rangelenlistshort listresextendlistlongi listshorti listresappendlistlong return listres can anyone suggest pythonic way thanks,1 as version localimport deprecated you able import mymodule look application modules folder checking syspath,localimport function randomly import modules modules directory the error importerror no module named testappmodulesmymodule i problem use webpy apache wsgi i problem run locally python webpypy command any suggestion,1 import csv open testcsv wb f wtr csvwriterf delimiter wtrwriterows open testcsv r f line f print line exactly said wanted to get loaded sensibly excel need use comma csv default delimiter unless locale eg europe need semicolon,everyonei list lists i want write csv file columns rowsi tried writerows i wantan example list following thanks help with examplecsvwriteropen testcsv wb delimiter examplewriterows i get cell cell etcand cell next cell i cleari need write example list file i open excel every element cell my output like each element diferent cell,3 first backslashes python need escaped path string servernamepathresourcetxt r servernamepathresourcetxt python open function support passwords you need use windows functions specify passwords here example program exactly,i need open file local network python script in basic case simple fh open servernamepathresourcetxt r the problem access network resource protected i tried something like fh open servernamepathresourcetxtusernamepass r work any idea,2 long short mixed rangelenlong mixedappendlongi lenshort mixedappendshorti mixed,i two lists length n n b b bn i want function giving result list alternate elements two b bn bn the following works look smart def listmixinglistlonglistshort listres rangelenlistshort listresextendlistlongi listshorti listresappendlistlong return listres can anyone suggest pythonic way thanks,2 imho best way result item sublist zipab item sublist it also faster sum reduce ways upd sorry missed second list bigger one element there another crazy way result item sublist mapnone b item sublist,i two lists length n n b b bn i want function giving result list alternate elements two b bn bn the following works look smart def listmixinglistlonglistshort listres rangelenlistshort listresextendlistlongi listshorti listresappendlistlong return listres can anyone suggest pythonic way thanks,3 use etree create file httpdocspythonorglibraryxmletreeelementtreehtml it included python protects generating broken xml eg fname contained amp special meaning xml,i new python i working gps files i need convert csv file gps data kml file below code python i using import csv input file name fname rawinputenter file name without extension data csvreaderopenfname csv delimiter skip st header row datanext open file written f open csvkmlkml w writing kml file fwritexml version encoding utf n fwritekml xmlns httpearthgooglecomkml n fwritedocumentn fwrite name fname kml namen row data fwrite placemarkn fwrite name strrow namen fwrite description strrow descriptionn fwrite pointn fwrite coordinates strrow strrow strrow coordinatesn fwrite pointn fwrite placemarkn fwritedocumentn fwritekmln print file created print press enter exit rawinput the csv file i using available dipsepneweditedcsv the kml file generated available csvkmlkml but kml file getting created correctly apparently rows csv code able generate placemarks its able iterate you see scrolling last part kml file generated can anyone help finding error code smaller csv files worked correctly created kml files fully thanks,2 the provided examples using csv modules great besides always simply write text file using formatted strings like following tentative example l open outcsv w row l column row outwrite column outwrite n outclose i used separator works best excell one requirements hope helps,everyonei list lists i want write csv file columns rowsi tried writerows i wantan example list following thanks help with examplecsvwriteropen testcsv wb delimiter examplewriterows i get cell cell etcand cell next cell i cleari need write example list file i open excel every element cell my output like each element diferent cell,3 i would use combination answers b b c e f g l iziplongesta b fillvalueobject l object b c e f g,i two lists length n n b b bn i want function giving result list alternate elements two b bn bn the following works look smart def listmixinglistlonglistshort listres rangelenlistshort listresextendlistlongi listshorti listresappendlistlong return listres can anyone suggest pythonic way thanks,1 this might depend bit model something like ie append every single element list seperately treestore i assume one column based picture l citems … char count l treestoreappendparent count char,i currently attempting append sorted list items pygtk treestore the list count times number occurs original list eg lots generating list collections import counter c counteraseries l citems lsortkey lambda item item print l example list printed u u u u u u u attempting append selftreestoreappendpath l image list appended httpistackimgurcomfbgupng i would like list appended like how modify way list counted printed play nicely syntax treestoreappend requires,1 you improve performance orm layer add bit overhead probably able experiment easier given size data might able create database memory would faster or might want look different type database like redis example,i implemented python program builds db protein fasta file a fasta file text file contains macromolecular sequences you read from protein program generate list peptides pieces proteins for goals program builds interrogates db sqlite do know many tricks populate interrogate sqlite db faster python if i use layers orms like sqlalchemy i improve performance,2 see tail first error message package called ggplot you need install ggplot package first fire r say installpackagesggplot,i working rpy v python i understand i use library ggplot import rpy rpyrobjects import r rlibraryggplot here error message i got error function package help pos libloc null characteronly false package called ggplot traceback recent call last file stdin line module file usrlocallibpythondistpackagesrpyrobjectsfunctionspy line call return supersignaturetranslatedfunction selfcallargs kwargs file usrlocallibpythondistpackagesrpyrobjectsfunctionspy line call res superfunction selfcallnewargs newkwargs rpyrinterfacerruntimeerror error function package help pos libloc null characteronly false package called ggplot,3 you answer query guess error closing output file would flush output fclose,i new python i working gps files i need convert csv file gps data kml file below code python i using import csv input file name fname rawinputenter file name without extension data csvreaderopenfname csv delimiter skip st header row datanext open file written f open csvkmlkml w writing kml file fwritexml version encoding utf n fwritekml xmlns httpearthgooglecomkml n fwritedocumentn fwrite name fname kml namen row data fwrite placemarkn fwrite name strrow namen fwrite description strrow descriptionn fwrite pointn fwrite coordinates strrow strrow strrow coordinatesn fwrite pointn fwrite placemarkn fwritedocumentn fwritekmln print file created print press enter exit rawinput the csv file i using available dipsepneweditedcsv the kml file generated available csvkmlkml but kml file getting created correctly apparently rows csv code able generate placemarks its able iterate you see scrolling last part kml file generated can anyone help finding error code smaller csv files worked correctly created kml files fully thanks,3 as suggested steabert comments workaround exporting graphics different format convert pdf afterwards adjusting example workflow could look something like import os import matplotlib mpl mpluseagg import numpy np import matplotlibpyplot plt pltrcparams textusetex true data nprandomrand pltimshowdata interpolation nearest pltxlabel x label pltsavefig aggeps ossystem epspdf aggeps aggpdf producing file kb looks good there still one difference examples presented using eps pipeline seems ignore interpolation nearest option ie image appears blurry final pdf luckily i live might interesting look issue,hej i like produce high quality pdfs matplotlib plots using code i produced large array numbers i plot figure using pltimshow if i produce pdf using pltsavefig i notice strong differences depending backend i use most importantly produced files get huge agg macosx backend reasonably small cairo see examples on hand cairo backend produces weird text conjunction tex rendering labels this looks awful tex document my question therefore twofold is possible produce small pdf ie presumably without interpolating raster image higher resolution using agg backend can one change text settings cairo backend looks similar ordinary tex case agg backend here example code test purposes import matplotlib mpl mpluse cairo import numpy np import matplotlibpyplot plt pltrcparams textusetex true data nprandomrand pltimshow data interpolation nearest pltxlabel x label pltsavefig cairopdf produces pdf kb bad looking xlabel import matplotlib mpl mpluse agg import numpy np import matplotlibpyplot plt pltrcparams textusetex true data nprandomrand pltimshow data interpolation nearest pltxlabel x label pltsavefig aggpdf produces pdf kb looks good i probably add i use matplotlib python osx in comments someone requested output grep font aggpdf shading r font r fontfile r descent fontbbox stemv flags xheight type fontdescriptor fontname nimbussanlregu capheight fontfamily nimbus sans l psadobefont nimbussanlregu fontdirectorynimbussanlregu knownnimbussanlregu findfont dupuniqueid knowndup uniqueid get eq exchfonttype get eq andpop falseifelse fonttype def fontmatrix readonly def fontname nimbussanlregu def fontbbox readonly def fontinfo dict dup begin basefont nimbussanlregu type font subtype type fontdescriptor r widths r lastchar firstchar fontfile r descent fontbbox stemv flags xheight type fontdescriptor fontname cmr capheight fontfamily computer modern italicangle ascent psadobefont cmr copyright httpwwwamsorg reserved font name cmr this font software licensed sil open font license version fontdirectorycmr knowncmr findfont dupuniqueid knowndup uniqueid get eq exchfonttype get eq andpop falseifelse fonttype def fontmatrix readonly def fontname cmr def fontbbox readonly def fontinfo dict dup begin notice copyright c american mathematical society httpwwwamsorg reserved font name cmr readonly def basefont cmr type font subtype type fontdescriptor r,3 directory structure root setuppy foopy note initpy file you could use distribute specify dependencies setuppy setuptools import setup setupname foo version pymodules foo installrequires beautifulsoup xxx this install required version beautifulsoup already present you need provide beautifulsoup case if want install beautifulsoup automatically root setuppy foobar initpy foopy beautifulsoup initpy beautifulsouppy etc setuppy setuptools import setup findpackages setupname foobar version packagesfindpackages note installrequires somewhere modules import pkgresources try pkgresourcesrequirebeautifulsoupxxx except pkgresourcesresolutionerror foobar import beautifulsoup else import beautifulsoup it less desirable unusual method,i writing setup script python distribution foo my code requires beautifulsoup currently directory structured like root setuppy initpy foopy beautifulsoup initpy beautifulsouppy etc and setuppy currently looks like less meta info setupname foo version pymodules foo i want include beautifulsoup case user installed already i also want install already installed particular version i noticed python docs i included packages setuppy file however section relationships distributions packages mentions way specify particular version package required i find examples use requires expression within setuppy i sure i need in short i need way say this package requires beautifulsoup least xxx version if version installed use one provided how i,2 selenium issues recognizing window try search http basic authentification details basically thing kinda works put username password url request assuming application runs httpexamplecom new url look like httpusernamepasswordexamplecom this solution works using google chrome default browser testing,i using python write seleniumrc test code server code the server application written aspnet configured windows authentication the execution steps python code look like following start python main create selenium instance say sel start selenium calling selstart open target url selenium instance via calling selopenurl windows authentication dialog box pops time selopenurl default set time seconds authentication process pending input username password at point i could find way seleniumrc interface make recognize pop dialog box i google around find seleniumrc interface python http authentication windows authentication i tried use autoit within selenium still without luck can shed light thanks advance marvinchen,1 no mature python framework i aware allows map urls python modules frankly good reason you cgi definitely recommended way deploy python apps setting requirement aside flask bottle lightweight micro webframeworks similar approaches allow reload automatically changes detected wise development,i used php applications for example cxampphtdocsapp cxampphtdocsapp accessed localhostapppagephp localhostapppagephp things noticed directory placed inside wwwroot directory maps directly url filedirectory addedremovedchanged worker processes seamlessly reflect change new files hotdeployed i lookout mature python web framework its web api deployed multiple clients copy diverge customization and workflow frequent interactionrevision cycles us clients hence drag drop deployment must which python framework enables i prefer lightweight solution doesnt impose mvc orms etc related how build twisted servers able hot code swap python python web hosting why server restarts necessary fastcgi cherrypy python,2 cherrypy mature web framework redeploys automatically changes detected the file structure url lightweight framework impose orm mvc even templating engine,i used php applications for example cxampphtdocsapp cxampphtdocsapp accessed localhostapppagephp localhostapppagephp things noticed directory placed inside wwwroot directory maps directly url filedirectory addedremovedchanged worker processes seamlessly reflect change new files hotdeployed i lookout mature python web framework its web api deployed multiple clients copy diverge customization and workflow frequent interactionrevision cycles us clients hence drag drop deployment must which python framework enables i prefer lightweight solution doesnt impose mvc orms etc related how build twisted servers able hot code swap python python web hosting why server restarts necessary fastcgi cherrypy python,1 edit i slightly staticroot refers directory django collect static files staticfilesdirs list searchpaths static files so like settingspy absolute path directory static files collected don put anything directory store static files apps static subdirectories staticfilesdirs example homemediamedialawrencecomstatic staticroot projectroot static url prefix static files example httpmedialawrencecomstatic staticurl static additional locations static files staticfilesdirs put strings like homehtmlstatic cwwwdjangostatic always use forward slashes even windows don forget use absolute paths relative paths cwwwdjangostatic list finder classes know find static files various locations staticfilesfinders djangocontribstaticfilesfindersfilesystemfinder djangocontribstaticfilesfindersappdirectoriesfinder add url urlspy urlpatterns staticfilesurlpatterns original answer this quite confusing the mediaroot directory files uploaded via fileupload form for physical files directly accessible client request eg style sheets scripts images use staticroot staticurl staticroot must absolute path think settingspy url myservercomstatic staticurl static refers directory staticroot homeuserstatic server files let say put css homeuserstatic server filescss refer like basehtml link relstylesheet href staticurl cssstylecss,i downloaded template online includes base html file images css file now i would like implement django so far i tried like good results page gets rendered without css file without images well something wrong settingspy mediaroot rel resources mediaurl resources basehtml link relstylesheet typetextcss hrefresourcesstylecss i put images css file resources folder templates folder doesnt work please help,1 case string decoded twice need unquote twice get back in import urllib in urllibunquoteurllibunquotewhatsbthebtimecbnowf out sthetimenow,how decode unicode string like whatsbthebtimecbnowf ascii like sthetimenow,3 there web framework python i know lets box need hard add bit convention configuration simply pick web framework choice python write wrapper main application walks directory set directory autoregisters routes modules inside have modules thing initpy files files located then set wsgi code autoreload wsgi script updated deployment development simply becomes two step process add file touch devappwsgi you could even add real deployment option wrapper walks set dev environment like generates hardcoded urltofunction mappings deployment however work really necessary python php way develop one necessarily translate well if client wants variable routes use dynamic routes give admin interface control mapping content url use flat files sqlite nosql datastore ether store mappings content use template engine like jinja mako cheetah genshi maintain general layout wrap object oriented structure make extending easy use functional paradigm comes naturally or drop whole dynamic production portion generate flat html files la jekyll,i used php applications for example cxampphtdocsapp cxampphtdocsapp accessed localhostapppagephp localhostapppagephp things noticed directory placed inside wwwroot directory maps directly url filedirectory addedremovedchanged worker processes seamlessly reflect change new files hotdeployed i lookout mature python web framework its web api deployed multiple clients copy diverge customization and workflow frequent interactionrevision cycles us clients hence drag drop deployment must which python framework enables i prefer lightweight solution doesnt impose mvc orms etc related how build twisted servers able hot code swap python python web hosting why server restarts necessary fastcgi cherrypy python,1 you probably need use ctypespointer like pcaplookupnetdev ctypespointernet ctypespointermask errbuf see ctypes tutorial section pointers information i assuming created ctypes proxies arguments well if dev requires string example simply pass python string need create ctypeswcharp something along lines,i trying use libpcap python using ctypes given following function c pcaplookupnetdev ampnet ampmask errbuf python i following pcaplookupnet pcappcaplookupnet mask ctypescuint net ctypescint ifpcaplookupnetdevnetmaskerrbuf printerror could get netmask device formaterrbuf sysexit error get file libpcappy line module ifpcaplookupnetdevnetmaskerrbuf ctypesargumenterror argument class typeerror don know convert parameter deal ampblah values,1 as gurney pointed two captures name since actually using name leave also r raw string notation good habit oh third thing grabbing wrong index whole match whole eitheror block inner capture successful researchr agroup,exemple bzzzzzz blabla blibli bloblo blublu i want catch first comment a comment may that ok researchpcomment agroup also researchpcomment agroup but want one comment tried something like researchpcomment pcomment agroup but work thanks,1 exception get work part quite explicit wrong sreconstantserror redefinition group name comment group group groups name rename second one researchpcomment pcomment agroup blabla researchpcomment pcomment agroups blabla blabla none refindallpcomment pcomment blabla blabla bloblo bloblo,exemple bzzzzzz blabla blibli bloblo blublu i want catch first comment a comment may that ok researchpcomment agroup also researchpcomment agroup but want one comment tried something like researchpcomment pcomment agroup but work thanks,1 build view json dump employeesoutputlist emp emplist namerankstr empfirstname emprank empdict id emppk label namerankstr value namerankstr employeesoutputlistappendempdict return httpresponsejsondumpsemployeesoutputlist something like know actual field names,i want parse query set output json data however i need make new jquery ui autocomplete use autocomplete needs keys label id value able read currently i use emplist employeesobjectsfilterengnameicontainsqterm jsonserializer serializersgetserializer json jsondata jsonserializerserialize emplist ensureasciifalse fields engname chiname output something like pk model systememployees fields rank manager engname eli i want able parse something like instead id label eli manager value eli manager best way,1 try conditional expression refinditerrpcomment print mgroup comment blabla bloblo,exemple bzzzzzz blabla blibli bloblo blublu i want catch first comment a comment may that ok researchpcomment agroup also researchpcomment agroup but want one comment tried something like researchpcomment pcomment agroup but work thanks,1 ctypescuint type you need instance mask ctypescuint net ctypescint then pass using ctypesbyref pcaplookupnetdevctypesbyrefmaskctypesbyrefneterrbuf you retrieve value using maskvalue,i trying use libpcap python using ctypes given following function c pcaplookupnetdev ampnet ampmask errbuf python i following pcaplookupnet pcappcaplookupnet mask ctypescuint net ctypescint ifpcaplookupnetdevnetmaskerrbuf printerror could get netmask device formaterrbuf sysexit error get file libpcappy line module ifpcaplookupnetdevnetmaskerrbuf ctypesargumenterror argument class typeerror don know convert parameter deal ampblah values,1 first need make sure cxoracle threadsafe since implements python db api spec v need check threadsafety module global values mean open multiple connections db run multiple queries time the best way use threading module pretty easy use this short sweet article get started of course guarantees pipelining queries result significant performance gains db engine io etc reasons definitely worth try good luck,i recently joined new company new python preferred scripting language working cxoracle create etl processes the scripts i built far singlethreaded jobs select subset columns i need oracle source db write output named pipe external process waiting read data insert target this worked fine i get tables million billion row range the job still works taking many hours complete these large source tables partitioned i trying research ways coordinate parallel reads different partitions i get two threads working concurrently writing separate named pipe is elegant way cxoracle handle multiple threads reading different partitions table here current simple code import cxoracle import csv connect via sqlnet string segment separate argument connection cxoracleconnectuserpasswordtns csvregisterdialect pipedelimited escapechar delimiter quotingcsvquotenone cursor connectioncursor f openpathtonamedpipe w writer csvwriterf dialect pipedelimited lineterminatorn r cursorexecuteselect columnlist sourcetable row cursor writerwriterowrow fclose some source tables partitions hardcoding partition names preferred option i thinking setting arrays partition names iterating folks ideas i love hear,1 you need create instances net mask use byref pass mask ctypescuint net ctypescint pcaplookupnetdev ctypesbyrefnet ctypesbyrefmask errbuf,i trying use libpcap python using ctypes given following function c pcaplookupnetdev ampnet ampmask errbuf python i following pcaplookupnet pcappcaplookupnet mask ctypescuint net ctypescint ifpcaplookupnetdevnetmaskerrbuf printerror could get netmask device formaterrbuf sysexit error get file libpcappy line module ifpcaplookupnetdevnetmaskerrbuf ctypesargumenterror argument class typeerror don know convert parameter deal ampblah values,3 the recent versions picklingtools libraries support tools converting xml python dict the download available picklingtools there quite bit documentation converters documentation describes detail decisions issues arise converting xml python dictionaries number edge cases attributes lists anonymous lists anonymous dicts eval etc converters handle in general though converters easy use if examplexml contains top aa bb cthreec top then convert dictionary xmlloader import example file examplexml r a document containing xml xl streamxmlloaderexample defaults operation result xlexpect xml print result top c three b there tools converting c python c python indentical conversion c x faster,i program reads xml document socket i xml document stored string i would like convert directly python dictionary way done django simplejson library take example str xml version personnamejohnnameageageperson dicxml converttodicstr then dicxml would look like person name john age thanks advance ze maria,3 you either create loop manually define custom range function the builtin requires integer step value,say i want loop step if try range whatever calls error saying step must is built way something like i using python something way thanks,2 in range int print if use numpy numpyarange would also trick,say i want loop step if try range whatever calls error saying step must is built way something like i using python something way thanks,3 you use integer steps range xrange that step gets internally converted get error try j j xrange,say i want loop step if try range whatever calls error saying step must is built way something like i using python something way thanks,2 if numpy two ways numpyarange numpylinspace endpointfalse,say i want loop step if try range whatever calls error saying step must is built way something like i using python something way thanks,3 i found jquery jquery ui like always solid choice matter building i always end using django languageframework matter users almost always cached browsers easy uselearn tons examples net developers probably already know technically able set almost js framework like django might require setting others,step django jquery prototype question can anyone tell experience ui application framework like yui spoutcore works best django,2 open file writing pass stdout keyword argument subprocesscall open stdouttxt wb subprocesscall ls l stdoutout subprocesscall accepts arguments subprocesspopen constructor,i using python call method subprocess module execute sqlldr command subprocess import call retcode callselfcommand selfconnectionstring control selfcontrolfile logselftemplogfile selfmode dataloadfile when run script output sqlldr command gets printed console wan redirect file ignore since sqlldr also writes log specified tried something like redirect output file throwing error line retcode callselfcommand selfconnectionstring control selfcontrolfile logselftemplogfile selfmode dataloadfile discardlog achieve,1 if know looking ahead time use index method stockslist aapl msft goog stockslistindex msft stockslistindex goog,stockslist print i know position so i stockslist future,3 you want use functoolspartial minarg functoolspartialmin keyitemgetter see httpdocspythonorglibraryfunctoolshtml docs example import functools operator import itemgetter minarg functoolspartialmin keyitemgetter minargvals b,this subtle question notation i want call function specific arguments without redefine for example min key function second argument key itemgetter would look like minarg lambda pq minpq key itemgetter i hoping call something like min itemgetter does anyone know thank,3 you use listingxpath agencynametext iterate list get agency name listing listing listings thisvalue bedrooms listingfindtext bedrooms bathrooms listingfindtext bathrooms agency listingxpath agencynametext listingsinfoappendthisvalue,i using etree parse external xml file trying get listing data tree external xml file add subtree agancy data i able pull data isting agancy fine seperately know merge listing gets correct agency info xml response listing bathroomsbathrooms bedroomsbedrooms agency namebob realtyname phonephone agency listing listing bathroomsbathrooms bedroomsbedrooms agency namelarry homesname phonephone agency listing response python tree lxmletreeparsehttpwwwsomeurlcomrandomblahblahblah listings treexpathresponselisting agencies treexpathresponselistingagency listingsinfo listing listings thisvalue bedroomslistingfindtextbedrooms bathroomslistingfindtextbathrooms agency agencies thisvalue agency agencyfindtextname listingsinfoappendthisvalue i tried adding one point listinginfoappendthisvalue occurs however correct appends last agency value every listing i outputting data json looks like you see one agency info put results listingsagency bob realty phone bathrooms bedrooms agency bob realty phone bathrooms bedrooms how i merge data responselistingagency responselisting original statement,1 using functools duncan answer better approach however use lambda expression get syntax correct minarg lambda pq minpq keyitemgetter,this subtle question notation i want call function specific arguments without redefine for example min key function second argument key itemgetter would look like minarg lambda pq minpq key itemgetter i hoping call something like min itemgetter does anyone know thank,1 pep cxoracle tries compliant really method like however process pretty straight forward pull contents file string split character call execute member resulting array i assuming character used delimit oracle sql statements within file f open tabledefinitionsql fullsql fread sqlcommands fullsqlsplit sqlcommand sqlcommands cursexecutesqlcommand,is way execute sql script file using cxoracle python i need execute create table scripts sql files,2 i got latest version httpcodegooglecompgeventdownloadsdetailnamegeventawinpymsi there exe look installer exe httpcodegooglecompgeventupdateslist,however gevent depends upon greenlet msi version i found fails install egg refuses install the msi version fails follows cwindowssystemeasyinstall greenlet installdir cpythonlibsitepackages searching greenlet reading httppypipythonorgsimplegreenlet reading httpbitbucketorgambroffgreenlet reading httpundefinedorgpythongreenlet best match greenlet downloading httppypipythonorgpackagessourceggreenletgreenlettargzmdddffeeebfaecd processing greenlettargz running greenletsetuppy q bdistegg distdir cusersianappdatalocaltempeasyinstallepggreenleteggdisttmpmqhun cpythonlibdistutilsdistpy userwarning unknown distribution option repository warningswarnmsg greenletc greenletc fatal error c idb illegal extension pdb file error setup script exited error command cprogram files xmicrosoft visual studio vcbinclexe failed exit status cwindowssystem i guess means i wrong version vs is anything else i use i want get pyqt gui lock database reached takes ages reply,1 does anyone know solve problem you really if openssl library problem could c library critical component your best solutions either a build version python operating system wish support b rework code use native system python platform your alternative create completely selfcontained build environment building redhat using system openssl library instead using one built this work everything c library tricky set the idea minimize relationship package system libraries if supporting redhat suse could conceivably pursue option a crafting appropriate spec file building binary packages platform this would nice way package everything,i following problem i need distribute version python magic in order process following i build python interpreter redhat linux install somewhere targz whole thing time make userpackage unpack targz directory become user package targz user package directory put targz web this method i use good bad i know i little experience packager case i propose change this way always it turns user unpacks targz suse tries run python setuptools installed together python hashlib module raises exception what i found building python redhat python configure script finds openssl library turns makes skip building shamodulec mdc compiles hashmodulec attach openssl library apparently openssl suse redhat somehow different meaning reason hashlib module imported suse raises import error leading hashlib try import md sha sha redhat reason compile since openssl jolly good does anyone know solve problem as i said experience packager bare minimum hint proposal welcome i try deploy much i allowed legacy,1 it bad practice it better comments less comments by documenting reasons using certain imports explain reader code reason maybe reader might see something able come better way you really ever shy away properly commenting code,i try make closedended question possible i often find i group imports go together like bunch mathy imports later i might delete move section code uses imported items another file the problem i often forget i using particular import example i use counter class often random stuff itertools for reason i might like comments specify imports way i longer need i delete whole chunk is considered bad style comments import statements,1 i pretty sure adding meaningful comments anywhere code plus i sometimes add comments strangeconfusing imports i say go,i try make closedended question possible i often find i group imports go together like bunch mathy imports later i might delete move section code uses imported items another file the problem i often forget i using particular import example i use counter class often random stuff itertools for reason i might like comments specify imports way i longer need i delete whole chunk is considered bad style comments import statements,1 i call bad practice comments provide clarity trying however getting confused imports used i would recommend determining perhaps modules getting big anyway,i try make closedended question possible i often find i group imports go together like bunch mathy imports later i might delete move section code uses imported items another file the problem i often forget i using particular import example i use counter class often random stuff itertools for reason i might like comments specify imports way i longer need i delete whole chunk is considered bad style comments import statements,1 well beautiful thing python explicit in case long imports considered bad practice know whether import referenced simply grep namespace and know whether delete allow also add counterpoint answers too much commenting indeed bad practice you adding redundant comments code patently obvious function additionally comments like code must maintained if creating excessive comments creating ton work,i try make closedended question possible i often find i group imports go together like bunch mathy imports later i might delete move section code uses imported items another file the problem i often forget i using particular import example i use counter class often random stuff itertools for reason i might like comments specify imports way i longer need i delete whole chunk is considered bad style comments import statements,3 comments help explainremind if useful use also tools pylint help spot unneeded imports well many things,i try make closedended question possible i often find i group imports go together like bunch mathy imports later i might delete move section code uses imported items another file the problem i often forget i using particular import example i use counter class often random stuff itertools for reason i might like comments specify imports way i longer need i delete whole chunk is considered bad style comments import statements,3 see run external python programs eclipse pydev note really need project file need,in search python debugger i stumbled upon aptana based eclipse often i want debug single python script however aptana let rundebug currently opened file directly instead requires create debugrun configuration file i would like rundebug alternatively i could create python project aptana but i want i want able run debug currently opened file this way i would like debug scripts without forced create project first single script can hard,1 import string import random def createrandomlength create random string length length chars stringletters stringdigits return joinrandomrandomsamplechars length,i trying make script generate random string text run i got far im problem formatting here code im using import random alphabet abcdefghijklmnopqrstuvwxyz min max name randomsamplealphabetrandomrandintminmax print name and ever end c x n b g r h p w i trying format one line string example c x n b g r h p w icxnybgrhpwo,1 initpy makes enclosing directory package it executed unless actually try import package directly,i using python following files initpy aoeupy initpy following contents aoeu aoeuaoeu aoeuaoeuaoeu i would expect running aoeupy error python tries load initpy the behavior whether pythonpath set unset what going,3 you want use aggregation djangodbmodels import sum def listinvoicesrequest invoices itemobjectsallannotatesubtotalsum invoicelineprice,i basic database i want pull sub data related view modelspy class invoiceheadermodelsmodel customer modelscharfieldmaxlength number modelsintegerfieldunique true class invoicelinemodelsmodel description modelscharfieldmaxlength price modelsdecimalfieldmaxdigits decimalplaces invoiceheader modelsforeignkeyinvoiceheader viewspy def listinvoicesrequest invoices invoiceheaderobjectsall what i trying get invoice total listinvoices view would consist invoicelinesprice totalled invoiceheader template i put invoice invoices invoicesubtotal endfor i think something def something modelspy file i getting lost so help would much appreciated,1 here option class parentobject classattr parent def initself parentfooself def fooself print selfclassattr selfclassclassattr class childparent classattr child def foocls raise exceptioni child parentfoo class method anymore end result want c child prints child calling parentfoo child cfoo childfoo raises exception traceback recent call last file stdin line module file stdin line foo exception i,say i following code class parentobject classattr parent def initself parentfoo classmethod def foocls print clsclassattr class childparent classattr child def foocls raise exceptioni child in parentinit i need call foo defined within parent i need call bound child accessing clsclassattr actually access attribute overridden child any ideas,1 actually probably error even wild import ie import settings settingsmyvariable would still show error codeanalysis find aside undefinedvariable place references ctrl show option i think better pattern module would myvariable default value updatedefaultvalues go override defaults that way codeanalysis anyone reading module would know variables expected otherwise know i think better approach would method ie getsettings myvariable unrelated actual problem i really advise using wild import even importing constant ie settings import myvariable a better approach settings module always using import settings settingsmyvariable otherwise place decides wants change myvariable place put reference namespace probably never get changed variable an even safer approach would method getsetting var would allow better lazyloading preferences ie load import called st time,in program i writing i created module called settings declares constants loads configuration file placing module namespace example value ï€ might code module weight user configuration file this modules i settings import everything works fine using aptana studio pydev code analysis tool throws lot undefined variable errors like i found flag usable prevent behaviour class docstrings effect i try use module level so i wonder two things is way selectively get rid errors meaning i want completely turn option mark errors undefined variables modules could fact error if alternative pattern achieve i want terms wild imports without confusing code analysis tool preemptive note i perfectly aware fact wild imports discouraged,1 class a def fself printrunning function f class a class ba def fself printrunning function f class b class ca pass this shows bf equal af so b must override f obj b printobjclassf af false this shows cf equals af so c must overridden f obj c printobjclassf af true,if i class a def fself printrunning function f class a class ba def initself ainitself def fself printrunning function f class b i make instance class b call f know see message class b but way inspect object make sure subclass overridden method something like obj b assertnot objflivesina,2 if want force child class override raise notimplementederror doing inspection possible and i see unutbu posted example i repeat,if i class a def fself printrunning function f class a class ba def initself ainitself def fself printrunning function f class b i make instance class b call f know see message class b but way inspect object make sure subclass overridden method something like obj b assertnot objflivesina,1 on system i get much better performance sending ethernet frames sendp compared sending ip packets using send gives appox pps system peetheripdsticmp sendppe looptrue gives approx pps system piipdsticmp sendpi looptrue but sending precreated packet socket manually way faster socketsocketsocketafpacket socketsockraw sbindeth peetheripdsticmp data pebuild true ssenddata but moving pebuild loop drastically reduces speed hinting actual packet building takes time,i know questions like asked plenty times i think subtley different i attempting write flexible traffic generator python using scapy producing packet fine comes sending traffic sufficiently fast rate needs somewhere range packets per second i seem hit wall around pps i believe may need threading i missing something easier,2 ssl de facto solution reason find shelter javascript libraries encrypt post data and plenty search but i believe achieve maximum security,aside using ssl way encrypt password django framework first post server for example i form accepts username password send another view passwords sent backend unencrypted if way encrypt passwords transmitting backend,3 what i done past seems work alright i need variable persistent throughout requests i jam onto web object right apprun for example i want variable called foo shared throughout requests persistent requests i webapp webapplicationurls globals add custom foo webfoo value start app webapprun then i need modify use foo variable code somewhere i import web webfoo value anything jam onto web object startup script persistent app restarted a bit hack works,i want update logfile soon request comes i class variable eventloggingenabled initialised true post function i check value eventloggingenabled now run time i modify value flag false subsequent requests but it remains true during debugging i found request received new object get created handle request pick initialized value ietrue this case functions like getlogenabled class can please suggest work around import web import threading class webserverthreadingthread port eventloggingenabled true def getlogenabledself print stub getlogenabled selfeventloggingenabled def initself threadingthreadinitself logging print initselfeventloggingenabled selfeventloggingfilename uelogslog def runself urls webserver app webapplicationurlsglobals sysargvappendwebserverport apprun def postself print post print stub post logging enabled selfeventloggingenabled,3 you want combination two things first want inner meta class enforce uniqueness database class speechmodelsmodel location modelsforeignkeylocation speaker modelscharfieldmaxlength date modelsdatefield class meta uniquetogether location date then data manipulation view want getorcreate method default model manager speech new speechobjectsgetorcreate locationmylocationstring datemydatetimevariable new speechspeaker myspeakerstring speechsave i hope gets started as always know needs better i blindly copy example adapt needs documentation uniquetogether getorcreate,i python function scrapes data different websites i want save data database certain condition met namely scraped data saved combination location date field unique so view i new location variable date variable essentially i need test combination values already database if combination unique save if nothing class speechmodelsmodel location modelsforeignkeylocation speaker modelscharfieldmaxlenth date modelsdatefield i pretty new django i sure go executing sort database query,1 you defining return type foo try adding foorestype cvoidp ctypes defaults int returntype looks cast done pdb session like bit system meaning pointer truncated converted int on system code seems work bit system unfortunately i bit system available test right also bar definition really match c code i suggest using something like bar cfunctypeclonglong cvoidpindlllib bar,i trying use ctypes call c function returned pointer another function it seems documentation i declaring function cfunctype creating instance using pointer this however seems give segfault here sample code samplec include stdioh unsigned long long simplevoid ptr printfpointer pn ptr return unsigned long longptr void foo return void simple unsigned long long barvoid ptr simple int main barfoo simplefoo simplepy ctypes import import pdb lib cdllloadlibrary simpleso simple libsimple simplerestype clonglong simpleargtypes cvoidp foo libfoo bar cfunctypecint cvoidpfoo pdbsettrace barfoo here gdbpdb session gdb r the program debugged started already start beginning n starting program usrbinpython simplepy thread debugging using libthreaddb enabled simplepymodule barfoo pdb p foo pdb castbarcvoidpvalue l pdb simplefoo pointer xfffffffffcc pdb int fffffffffcc l curiously i run using c main function i get simple pointer x pointer x match pointer i get python code what i wrong thanks advance guidance give,1 there always cgi add script mapping py cpythonpythonexe u drop py files folder iis execute i generally recommend real work—in longer term would definitely want write apps wsgi deploy number interfaces including cgi—but handy quick prototyping,for simple internal webapps using asp i able switch iis write asp scripts www directory would start working immediately is equivalent webserver app python scripts i run automatically start serving dynamic pages python scripts certain folder virtually configuration solutions i already found either limited eg simplehttprequesthandler serve dynamic content require configuring script serving,2 there quite options i think one best choice it depends use case preferences just give hints do really store data list in example could use dictionary insert object twice once using integer key using string key that would make getitem quite simple another option would make interface explicit use byint bystring methods you choose better names course if give details really want i could propose alternatives,is pythonic way write getitem following the issue checking type different things depending type parameter call class this def initself name value selfname selfvalue name value class that def initself selfthislist def addthisself selfthislistappendthis def getitemself x isinstancex int return selfthislistx could wrap tryexcept error checking elif isinstancex str selfthislist thisname x return return none this b this b c that caddthisa caddthisb print cname print c name,1 you define two private methods getitemint getitemstr then use getattr get handle proper method depending typexname call typespecific method see kantgeneratorparse implemented dive python parsing xml example,is pythonic way write getitem following the issue checking type different things depending type parameter call class this def initself name value selfname selfvalue name value class that def initself selfthislist def addthisself selfthislistappendthis def getitemself x isinstancex int return selfthislistx could wrap tryexcept error checking elif isinstancex str selfthislist thisname x return return none this b this b c that caddthisa caddthisb print cname print c name,1 separate arguments args list subprocesspopen find homebludiescripttvshows type f shellfalse stdoutsubprocesspipe subprocesspopen find mediafreeagent goflex drivetobinsmedia type f stdinsstdout shellfalse stdoutsubprocesspipe output mine import subprocess subprocesspopen find homebludiescripttvshows type f shellfalse stdoutsubprocesspipe traceback recent call last file stdin line module file usrlibpythonsubprocesspy line init errread errwrite file usrlibpythonsubprocesspy line executechild raise childexception oserror errno no file directory subprocesspopen find homebludiescripttvshows type f shellfalse stdoutsubprocesspipe find homebludiescripttvshows no file directory the first original code raises python exception the second runs correctly find complains i bludiescripttvshows directory system,i new python i trying make search bar searches directories using two find commands output results ordered list def searchentryself widget subprocesspopen find homebludiescripttvshows type f shellfalse stdoutsubprocesspipe subprocesspopen find mediafreeagent goflex drivetobinsmedia type f stdinsstdout shellfalse stdoutsubprocesspipe sstdoutclose selfcontents njoinselflist scommunicateselfcontents my search bar selfsearch gtkentry selfsearchconnectactivate selfsearchentry selfboxpackstartselfsearch true true selfsearchshow errormsg file usrlibpythonsubprocesspy line init errread errwrite file usrlibpythonsubprocesspy line executechild raise childexception oserror errno no file directory,1 the language support sometimes still useful requirement besides bunch recipe also write little method access dictionary using dotted string def getvarinputdict accessorstring gets data dictionary using dotted accessorstring currentdata inputdict chunk accessorstringsplit currentdata currentdatagetchunk return currentdata would support something like testdict thing spam foo cheeze bar output getvartestdict thingspamfoocheeze print output bar,how i make python dictionary members accessible via dot for example instead writing mydict val i like write mydictval also i like access nested dicts way for example mydictmydictval would refer mydict mydict val thanks boda cydo,2 django uses regular expressions match incoming requests in python dot matches character except newline see docs information try r checkstringpstring viewscheckstrname check str also keep mind accept character including forward slash may desirable be sure test make sure everything works would expect,in django i defined url like r checkstringpstringw viewscheckstrname check str but when enter string inputs like ibrahimyilmaz ibrahim ibrahimibrahimcom returns http so write url accept everykind string help appreciated ä°brahim,3 what finally worked selrunscript uploadfileframe contentsfind imgalthumana click basically use selenium find link iframe click use jquery selenium capability run arbitrary piece javascript apparently pythonselenium i guessing original selenium command runscript something i use jquery i something like selecting form iframe using jquery,so i absolutely baffled selenium find answer anywhere i sharing experience i trying select iframe luck repeatably anyway the html looked like iframeâ iduploadfileframeâ widthâ heightpxâ frameborderâ framemarginâ nameuploadfileframeâ srcblahimport html body divâ classimportdevices divâ classimporttype aâ classsecondarybuttonâ hrefblahblahsourceblah divâ classimportchoiceimage imgâ altblahâ srcpublicimagesblahimportblahpng div divâ classimportchoicetextblah blahdiv div div body html the python code using selenium library trying find iframe using timed def testpedometerself sel selfselenium timesleep range try selselectframecssuploadfileframe break except pass timesleep else selffailcannot find uploadfileframe iframe device upload image buttons repeated fails every combination selenium commands i could find the occasional success would reproducible perhaps sort race condition something never find right way get selenium proper,2 if i set backend template matplotlibmatplotlibrc i reproduce symptoms matplotlibmatplotlibrc backend gtkagg backend template note file matplotlibrc may directory matplotlib in case following code shows import matplotlib matplotlibmatplotlibfname in import matplotlibpyplot p in pplotrangerange out matplotliblineslined object xac in pshow if edit matplotlibmatplotlibrc change backend something like gtkagg see plot you list backends available machine import matplotlibrcsetup rcsetup printrcsetupallbackends it return list like gtk gtkagg gtkcairo fltkagg macosx qtagg qtagg tkagg wx wxagg cocoaagg agg cairo emf gdk pdf ps svg template reference customizing matplotlib,i need help matplotlib yes i forget calling pyplotshow ipython pylab import matplotlibpyplot p pplotrange range it returns matplotliblineslined xadebc output pshow there nothing happen no error message no new window nothing i install matplotlib using pip i take error messages details i use ubuntu ipython v python v matplotlib v,3 what happens drop import app authpy profilepy seems creating circular imports,trouble understanding distribute tornado application multiple filesi need one file creates application instance another file handles loginlogout functionality another handles profile page view onbut dont get lets say example two files apppycreating app instance authpyloginlogout functionality apppy import tornado import auth handlers r mainhandler rauth authauthhandler rlogout authlogouthandler works fine apppy import tornado import auth import profile handlers r mainhandler rauth authauthhandler rlogout authlogouthandler rprofile profileviewhandler authpy import tornado import app class authhandlerappbasehandler class logouthandlerappbasehandler profilepy import app import tornado class viewprofileappbasehandler shows error profilepy module app attribute basehandler,1 maybe update answers question since fmin uses downhill gradient algorithm searches neighborhood initial guess direction steepest descent if deep enough parameterregion function always returns inf algorithm see direction go,i using scipy fmin search compute log likelihood distribution fit data i using fmin search parameters maximize log likelihood like j fminlambda psumloglikelihoodcalculatordata p array fulloutputtrue likelihoodcalculator takes data parameter spits array likelihood values data point if start search parameter yields likelihood loglikelihood inf sum inf fmin run away initial parameter instead sticks value maximum number calls returns in print j array inf i thought perhaps problem fmin handling infs remove likelihood calculator hand directly get better behavior in fminlambda p sumlogp array fulloutput warning maximum number function evaluations exceeded in out array e this correct behavior happens use array zeros zeros floats use fminbfgs the incorrect behavior function call continues use fminbfgs fmin works correctly start parameter yield likelihood thus infs thoughts thanks update if broad area parameters result zeros push parameter value edge if parameter near enough edge fmin get zeroland start searching ex p inf p fmin work p,2 for development play around example using standard python library i used help friend wanted get basic cgi server running it serve python scripts cgibin files root folder i near windows computer moment make sure still works this also assumes pythonx python x named make directory harddrive cgibin folder ex cservercgibin in command window navigate cserver directory type following assuming installed python cpython cpythonpythonexe cgihttpserver you get message like serving http port linux python cgihttpserver directory cgibin,for simple internal webapps using asp i able switch iis write asp scripts www directory would start working immediately is equivalent webserver app python scripts i run automatically start serving dynamic pages python scripts certain folder virtually configuration solutions i already found either limited eg simplehttprequesthandler serve dynamic content require configuring script serving,1 such loop benefit much threading consider series additions whose intermediate values depend previous iterations this parallelized threads would stomping values overwriting things you lock data one thread works time lose benefit multiple threads working data threads work best independent data sets eg graphics renderer perfect example each thread renders subset larger image may share common data sources texturevertexcoloretc data thread little section total image work one touch areas image whatever thread little section pixels affect thread elsewhere image for related question password cracking another example threadingmultiprocessing makes sense each thread goes testing multiple possible passwords one common cracked list what one thread affect cracker threads unless get match may mean threads abort since job done once threads become interdependent lose lot benefits multiple threads they spend time waiting finish spend actual work of course say never use threads sometimes makes sense multiple threads even interdependent eg graphics thread sound effects thread action processor thread ai calculations thread etc game one nominally dependent sound thread busy generating bangricochet audio gun player shot ai thread calculating game mobs graphics thread drawing clouds background etc,background i bit new developing general pythonprogramming question if method recursion involved enabling multiple threads multiprocessing i done light reading examples seem applying syntax new codeand cpu intensive tasks i wondering i redesign existing code say i something thats cpu intensivebasically keeps adding limit hit def adderexamplesum number sum print sum larger stoping else sum sum number print sum number number adderexamplesum number adderexample questionsthough process how would i approach make run faster assuming i multiple cores availablei want eventually want span machines i think thats sperate issue hadoop i keep example one system multiple cpu it seems threading best choicebecause time takes spawn new threads thats true i focus multiprocessing if recursions split different cpu svai queues i assume rejoin done can i create multiple threads process split processes multiple cpu lastly recursion depth limits overall limit based threadsproceses multiprocessingthreading get around another questionrelated guys trying codesrsa wireless keysetc via brute force overcome problem i assume scaling mathematical processes multiple cpu somehow this example build understanding would great any tipssuggestions would great thanks,2 you may interested recent simpleitk work occuring there much information wwwsimpleitkorg the source code much documentation found httpwwwgithubcomsimpleitk,i numpy array want convert itk image processing how i without using pybuffer extension wrapitk i use i get bunch errors compiling externalprojectspybufferitkpybuffertxx in static member function ‘static pyobject itkpybuffertimagegetarrayfromimagetimage timage itkimagefloat u’ externalprojectspybufferwrapitkpybufferpythoncxx instantiated externalprojectspybufferitkpybuffertxx error cannot convert ‘int’ ‘npyintp’ argument passing i could use idea either fix compilation errors another way convert python objects,1 for simply contacting website consider requests twill libraries for screenscraping beautifulsoup friend if thirdparty libraries really option though need delve htmllib httplib urllib urllib python modules,i started learning python week always love learn much languages i python one easiest languages still lots things teachers tell interacting web pages obvious example registration forums websites gives headache building simple python application read labels input information first name last name sex address text boxes submit page end would fantastic another silly thing i must know contact website first if provide tips help i appreciate contribution,1 chr see ord see two functions looking though already seem know latter follow links detailed explanation the first gives onecharacter string based integer second reverse operaion technically handles unicode well chr though unichr need you base code following ch e print ord ch ord a give fifth letter val print chr val ord a give g seventh letter,i making program purposes naming program completely generates random name the problem i cannot assign number letter z z it gives syntaxerror i need assign random integer triggers letter random integer select a prints name edit i implemented advice works i grateful i wish program create readable names procedural here example name i tweaked program ddjau now look like name i want program work creating real names like samuel common names thanks edit thanks adam i need sort seed user enter start name seed a name adam seed g name george should i searching file line line beginning if i,1 bool false so int matter please tracing print count actually,i somewhat confused i found bug code i change amatchedimagescount true variable amatchedimagescount false variable since i quickly wanted know whether object images first code appear like photo images since expression evaluates true meaning really false images images did i understand correctly please answer comment expressions evaluate different values,1 what nature count if basic python number count count on hand count custom class needs implement either nonzero len python x bool len python x if methods defined every instance class considered true,i somewhat confused i found bug code i change amatchedimagescount true variable amatchedimagescount false variable since i quickly wanted know whether object images first code appear like photo images since expression evaluates true meaning really false images images did i understand correctly please answer comment expressions evaluate different values,2 without knowing count hard answer excerpt may use the following values considered false none false zero numeric type example l j empty sequence example empty mapping example instances userdefined classes class defines nonzero len method method returns integer zero bool value false all values considered true — objects many types always true,i somewhat confused i found bug code i change amatchedimagescount true variable amatchedimagescount false variable since i quickly wanted know whether object images first code appear like photo images since expression evaluates true meaning really false images images did i understand correctly please answer comment expressions evaluate different values,1 code work simple text boxes vb ported python edit tested python ctypes import import wingui import winapi import wincon user windlluser kernel windllkernel class rectstructure fields left culong top culong right culong bottom culong class guithreadinfostructure fields cbsize culong flags culong hwndactive culong hwndfocus culong hwndcapture culong hwndmenuowner culong hwndmovesize culong hwndcaret culong rccaret rect def getselectedtextfromfrontwindow as string vb python translation gui guithreadinfocbsizesizeofguithreadinfo txt astclipboardobjnone lastclipboardtemp usergetguithreadinfo byrefgui txt getcaretwindowtextguihwndcaret true txt then lastclipboardclip lastclipboardobj getclipboard lastclipboardtemp lastclipboardformat sendkeys c getclipboard txt lastclipboardclip lastclipboardclip then txt lastclipboardclip restoreclipboard lastclipboardobj lastclipboardtemp print clbrd txt end if return txt def getcaretwindowtexthwndcaret selected false as string startpos endpos txt hwndcaret bufsize winguisendmessagehwndcaret winconwmgettextlength bufsize buffer winguipymakebufferbufsize winguisendmessagehwndcaret winconwmgettext bufsize buffer txt bufferbufsize selected bufsize selinfo winguisendmessagehwndcaret winconemgetsel endpos winapihiwordselinfo startpos winapilowordselinfo return txtstartpos endpos return txt name main print getselectedtextfromfrontwindow,i trying create simple open source utility windows using python perform userdefined actions selected text currently active window the utility activated using predefined keyboard shortcut usage partially outlined following example the user selects text using mouse keyboard application window the user presses predefined keyboard shortcut the selected text retrieved utility copied clipboard approaches fine the keyboard shortcutdependent action performed selected text what puzzles step how selected text retrieved active window this work applications i use pywin module thanks advance answers tips update turns two approaches accomplish task find active window send messagekeystroke ctrlc order copy selected text clipboard then utility work text accessing using clipboardrelated functions find active window retrieve selected text directly without copying clipboard this seems difficult st approach as starting points get active window id anurag uniyal pointed reply or get window object following code import winui wnd winuigetforegroundwindow print wndgetwindowtext,1 example def makeincrementerstart def closure i know i could write x start use x point though true yield start start return closure x makeincrementer iter x print iternext,this bit python work def makeincrementerstart def closure i know i could write x start use x point though true yield start start return closure x makeincrementer iter x print iternext exception unboundlocalerror local variable start referenced assignment i know fix error bear this code works fine def teststart def closure return start return closure x test print x prints why i read start variable inside closure write what language rule causing handling start variable update i found so post relevant answer question readwrite python closures,2 whenever assign variable inside function local variable function the line start assigning new value start start local variable since local variable start exists function attempt look global scope start first try access hence error seeing in x code example work use nonlocal keyword def makeincrementerstart def closure nonlocal start true yield start start return closure on x often get around similar issues using global keyword work start global variable in scenario either something like suggested x start use mutable variable modify yield internal value def makeincrementerstart start start def closure true yield start start return closure,this bit python work def makeincrementerstart def closure i know i could write x start use x point though true yield start start return closure x makeincrementer iter x print iternext exception unboundlocalerror local variable start referenced assignment i know fix error bear this code works fine def teststart def closure return start return closure x test print x prints why i read start variable inside closure write what language rule causing handling start variable update i found so post relevant answer question readwrite python closures,3 in python x use nonlocal keyword rebind names local scope in x options modifying mutating closure variables adding instance variables inner function want creating local variable modifying call like x makeincrementer def makeincrementerstart def closure i know i could write x start use x point though true yield start start return closure adding instance variables call like x makeincrementer def makeincrementerstart def closure true yield closurestart closurestart closurestart start return closure creating local variable call like x makeincrementer def makeincrementerstart def closurestartstart true yield start start return closure,this bit python work def makeincrementerstart def closure i know i could write x start use x point though true yield start start return closure x makeincrementer iter x print iternext exception unboundlocalerror local variable start referenced assignment i know fix error bear this code works fine def teststart def closure return start return closure x test print x prints why i read start variable inside closure write what language rule causing handling start variable update i found so post relevant answer question readwrite python closures,2 i assume subsets considered duplicates noncommutatively course start converting query set ordering largest smallest then add query new list subset alreadyadded query since set subset logic covers exact duplicates q sortedsetq q sort keylen reversetrue anyqissubsetq q aappendq listq q back lists want,i seem find question so particular problem forgive asked anyway i writing script loop set url give list unique urls unique parameters the trouble i actually comparing parameters eliminate multiple duplicates it bit hard explain examples probably order say i list url like hxxpwwwsomesitecompagephpidamptitlederp hxxpwwwsomesitecompagephpidamptitleblah hxxpwwwsomesitecompagephpidampcamptitlething hxxpwwwsomesitecompagephpbampid i parsing url list lists eventually i list like sort id title id c title b id i nee figure way give lists list point new id c title b id as right i got bit sort little i know i close i slamming head couple days any ideas thanks advance edit sorry clear this script aimed finding unique entry points web applications postspidering basically url unique entry points id c title i prefer link unique entry points id title so i need new list lists eliminate one prefer one only smaller variables larger set if still unclear let know thank quick responses,3 it sounds like want run pair commands join output cmds find mediafreeagent goflex drivetobinsmedia type f find homebludiescripttvshows type f ouput n joinsubprocesscheckoutputshlexsplitcmd cmd cmds,sub process command search first searches one directory wrote omits first second reading python docs got confused code def searchentryself widget subprocesspopen find homebludiescripttvshows type f shellfalse stdoutsubprocesspipe subprocesspopen find mediafreeagent goflex drivetobinsmedia type f stdinsstdout shellfalse stdoutsubprocesspipe sstdoutclose selfcontents njoinselflist scommunicateselfcontents got confused shlex module use place subprocesspopen code would even make sense would like work better cmd find mediafreeagent goflex drivetobinsmedia type f find homebludiescripttvshows type f spl shlexsplitcmd subprocesspopenspl stdoutsubprocesspipe selfcontents njoinselflist scommunicateselfcontents thanks input,1 there two better pythonic ways python x using container get around lack nonlocal keyword one mentioned comment code bind local variable there another way using default argument def makeincrementerstart def closurestart start true yield start start return closure x makeincrementer iter x print iternext this benefits local variable without additional line code it also happens x makeincrememter line rather iter x line may may matter depending situation you also use actually assign referenced variable method elegant way using container using function attribute def makeincrementerstart def closure you still x closurestart want rebind local scope true yield closurestart closurestart closurestart start return closure x makeincrementer iter x print iternext this works recent versions python utilizes fact situation already object know name references attributes need create new container purpose,this bit python work def makeincrementerstart def closure i know i could write x start use x point though true yield start start return closure x makeincrementer iter x print iternext exception unboundlocalerror local variable start referenced assignment i know fix error bear this code works fine def teststart def closure return start return closure x test print x prints why i read start variable inside closure write what language rule causing handling start variable update i found so post relevant answer question readwrite python closures,2 use parameterized query query insert into mytableid html values curexecutequery html info,i storing html sqlite database using python when i go insert html sql table i get errorproblem i characters the following example problem creates incorrect sql statement insert into mytableid html value img srcimagespng alt info something like insert into mytableid html value img srcimagespng alt info how i sql statement characters import sqlite html img srcimagespng alt note characters insertqry insert into mytableid html values conn sqliteconnect globalvarsdbpath cur conncursor res curexecute insertqry html info these functions dont solve my problem def formatfordb srccode post srccode srccodereplace srccode srccodereplace return srccode def formatfordisplay srccode post srccode srccodereplace srccode srccodereplace return srccode def formatfordb srccode post srccode srccodereplace srccode srccodereplace return srccode def formatfordisplay srccode post srccode srccodereplace srccode srccodereplace return srccode,2 use astype x numpyarray na x array na dtype s wherex na x astypeint array,i numpy recarray several integer columns string columns the data string columns composed integers numpy things string na column so i two questions how i remove na change how i convert string columns integers i record array many integer columns thanks,1 your xpath looks wrong try selectoptionvalue today,i trying click option select menu via driverimplicitlywait driverfindelementbyxpathselectoptionvalue today click work prints none terminal html looks like select tabindex classitclistbox midoption valueoneday dayoptionoption valuesevendays daysoptionoption valuefourteendays daysoptionoption valueonemonth monthoptionoption valuesixmonth monthsoptionoption valueoneyear yearoptionoption value disableddisabled————————optionoption valuetodaytodayoptionoption valueyesterdayyesterdayoptionoption valueweektodateweektodateoptionoption valuelastdayslast daysoptionoption valuelastweeklast weekoptionoption valuemonthtodatemonthtodateoptionoption valuelastdayslast daysoptionoption valuecustomdaterangecustom optionselect i using firefox webdriver i think html generated js,2 for python interpreters must enter python python python v python python v python for background current recommendation python refer version python python refer version python see draft pep the python command unixlike systems,lion installed python pythonorg it comes terminal command supposed move version python earlier updating shell profile when run check default python terminal still says apple supplied one do i need run command sudo get change default python i also tried versioner method work,1 the signal must come qgraphicsview object defined ui you create class derived qgraphicsview like pyqtqtcore import pyqtqtgui import class myviewqgraphicsview moved pyqtsignalqmouseevent def initself parent none supermyview selfinitparent def mousemoveeventself event call base method sure events forwarded scene supermyview selfmousemoveeventevent print mouse pointer currently hovering eventpos selfmovedemitevent then designer rightclick qgraphicsview promote write class name promoted class name field eg myview write file name class header file field without py extension click add button promote button and regenerate file guipy pyuic,i trying write program interact qgraphicsview i want gather mouse keyboard events happen qgraphicsview for example user clicks qgraphicsview widget i get mouse position something like i hard code rather easily i want use qtdesigner ui changing frequently this code i guipy a simple widget qgraphicsview pyqt import qtcore qtgui try fromutf qtcoreqstringfromutf except attributeerror fromutf lambda class uigraphicsviewwidgetobject def setupuiself graphicsviewwidget graphicsviewwidgetsetobjectnamefromutfgraphicsviewwidget graphicsviewwidgetresize graphicsviewwidgetsetmousetrackingtrue selfgraphicsview qtguiqgraphicsviewgraphicsviewwidget selfgraphicsviewsetgeometryqtcoreqrect selfgraphicsviewsetobjectnamefromutfgraphicsview selfretranslateuigraphicsviewwidget qtcoreqmetaobjectconnectslotsbynamegraphicsviewwidget def retranslateuiself graphicsviewwidget graphicsviewwidgetsetwindowtitleqtguiqapplicationtranslategraphicsviewwidget form none qtguiqapplicationunicodeutf the code program usrbinpython import sys pyqt import qtcore qtgui gui import uigraphicsviewwidget class myformqtguiqmainwindow def initself parentnone qtguiqwidgetinitself parent selfui uigraphicsviewwidget selfuisetupuiself qtcoreqobjectconnectselfuigraphicsview qtcoresignalmoved selftest def mousemoveeventself event print mouse pointer currently hovering eventpos selfemitqtcoresignalmoved event def testself event print test name main app qtguiqapplicationsysargv myapp myform myappshow sysexitappexec when i run code gives opposite i want i get mouse position everywhere except inside qgraphicsview i sure problem qobjectconnect but every time i go back read signals slots makes sense i get please help i banging head past days i sorry asked i threads topic i get anywhere thanks,2 how build python if built sources good possibility zlib module get built necessary libraries header files installed system on ubuntu need i think zlibgdev package this true variety modules well example without appropriate openssl development librariesheaders place get ssl module either someone may also python package version ubuntu although neither natty maverick appear one official repositories,i trying deploy app google app engine using bottle microframework similar flask i running ubuntu comes python installed gae needs version i installed i realized i use make altinstall i may default version problem but real problem i try use gae server test locally i get following error traceback recent call last file optgoogleappenginedevappserverpy line module runfilefile globals file optgoogleappenginedevappserverpy line runfile execfilescriptpath globals file optgoogleappenginegoogleappenginetools devappservermainpy line module googleappenginetools import devappserver file optgoogleappenginegoogleappenginetools devappserverpy line module import zlib importerror no module named zlib can help,1 try running matrix notice becomes so changing three time read httpwwwdaniwebcomsoftwaredevelopmentpythonthreads that seems explain,the following code n matrix n n rangen j rangen matrixij n j printmatrix prints i expect why,1 iterrange nextit range range replace n n also answer making copies list multiplication therefore modifying one modify,the following code n matrix n n rangen j rangen matrixij n j printmatrix prints i expect why,1 note matrix x x matrix idx x matrix three rows one object see docs especially note n operation fix xrange idx x update here samples code gets answer simply ie without iter nrows ncols zeroes j xrangencols xrangenrows zeroes ap ncols j j xrangencols xrangenrows ap,the following code n matrix n n rangen j rangen matrixij n j printmatrix prints i expect why,2 i python i edited runcom function little work def runcombashcommand sp subprocesspopen osascript stdinsubprocesspipe stderrsubprocesspipe spcommunicate tell application terminalnactivatendo script command exitnend tell formatbashcommand,i seen similar questions eg running command new mac os x terminal window i need confirm command expected behavior mac i if anyone run following python mac import subprocess os def runcombashcommand sp subprocesspopen osascript stdinsubprocesspipe stderrsubprocesspipe spcommunicate tell application terminalnactivatendo script command exitnend tell formatbashcommand runcom echo this testnnthis come two lines later press keyread throwaway runcom echo this testnnecho this come one line later press keyread throwaway runcom echo this testing whether i enter sudo pw separate terminalsudo lsnecho you see current directory press keyread throwaway firstly basically spawn new terminal execute command correct for reference version runcom function came answer much cleaner original as actual tests first one tests internal double escaped n characters really work the second tests put unescaped newlines script still work like semicolon finally last one tests whether call sudo process separate terminal ultimate goal in cases new terminal disappear soon press key please also confirm if one work correctiondiagnosis would appreciated also appreciated pythonic way spawning terminal mac executing sudo extended bash commands thanks,1 your problem reusing variable p test code name main p primeiter first declaration p p range second declaration p print p uses second declaration p i recommend using itertoolsislice get first elements iterator name main p primeiter x itertoolsislicep print x,i wrote piece code print n prime numbers class primegen def initself selfcurrent def genprimeself num rangenum j range selfcurrent selfcurrent j selfcurrent selfcurrent break else break print selfcurrent selfcurrent selfcurrent name main p primegen pgenprime the code works fine i get output i tried make class iterable code but output i could quite figure i going wrong any help appreciated thanks class primeiter def initself selfcurrent def nextself selfcurrent selfcurrent range selfcurrent selfcurrent selfcurrent selfcurrent break break current loop else break break loop return return selfcurrent def iterself return self name main p primeiter p range print p,1 you using code print values p range print p if look printing values range you probably want print things prime iterator itertools functions may help prime itertoolsislicep print prime additionally may want consider using generator def primes current true current true xrange current current current break else break yield current,i wrote piece code print n prime numbers class primegen def initself selfcurrent def genprimeself num rangenum j range selfcurrent selfcurrent j selfcurrent selfcurrent break else break print selfcurrent selfcurrent selfcurrent name main p primegen pgenprime the code works fine i get output i tried make class iterable code but output i could quite figure i going wrong any help appreciated thanks class primeiter def initself selfcurrent def nextself selfcurrent selfcurrent range selfcurrent selfcurrent selfcurrent selfcurrent break break current loop else break break loop return return selfcurrent def iterself return self name main p primeiter p range print p,1 something like def maxpathtriangle idx total triangle row triangle next maxrowidxidx return maxpathtriangle rowindexnext totalnext return total,this question project euler problem find maximum path triangle i know may bad taste ask help i functions def choosebestrowoftriangle lenrowoftriangle return rowoftriangle return listmaxelement element ziprowoftrianglerowoftriangle def consolidatepathrowoftriangle bestpath return listsumelement element ziprowoftrianglebestpath work data set formatted like triangle solution triangle would look like consolidatepathtrianglechoosebestconsolidatepathtrianglechoosebestconsolidatepathtrianglechoosebesttriangle this outputs correctly writing nested function call far optimal going impossible i scale problem hundred rows how i alter consolidatepath choosebest call appropriate edit figured,1 short answer look python dictionaries allow type assignments below i working example would generate random name based gender litter disclaimer i fully understand via code trying accomplish charord random letter also note absolutely idea design goals requirements i made example complex may need instructional purposes additional resources python docs dictionary using python dictionary relationship search ways in response last edit if looking build random real names i think best bet use large list names pick random one if i i look something linking census results males females note malenamestxt femalenamestxt copy list found census website as disclaimer i sure efficient way load read file just use example proof concept update here quick dirty way seed random values again i sure pythonic way efficient way works example import random import time def getrandomnamegender seed ifgender male file malenamestxt elifgender female file femalenamestxt fid openfile r names totalnames line fid iflinelowerstartswithseed namesappendline totalnames totalnames randomindex randomrandinttotalnames return namesrandomindex name main print welcome name database n print boy print girl bog rawinput ngender print what name start print a ab abc b ba br etc print l rawinput leters lower newname bog boy print getrandomname male l elif bog print getrandomname female l output welcome name database boy girl gender what name start a ab abc b ba br etc leters br britta,i making program purposes naming program completely generates random name the problem i cannot assign number letter z z it gives syntaxerror i need assign random integer triggers letter random integer select a prints name edit i implemented advice works i grateful i wish program create readable names procedural here example name i tweaked program ddjau now look like name i want program work creating real names like samuel common names thanks edit thanks adam i need sort seed user enter start name seed a name adam seed g name george should i searching file line line beginning if i,1 here worked python i assume work similarly python precondition install mingw included pythonxy distrib using graphviz download pygraphviz sources edit setuppy change paths smth like librarypathrcprogram files xgraphviz bin includepathrcprogram files xgraphviz includegraphviz note bin lib linking libs work run python setuppy build c mingw result step cpythonlibsitepackagespygraphvizpython setuppy build c mingw librarypathcprogram files xgraphviz bin includepathcprogram files xgraphviz includegraphviz running build running buildpy running buildext building pygraphvizgraphviz extension cmingwxybingccexe mnocygwin mdll o wall icprogram files xg raphviz includegraphviz icpythoninclude icpythonpc c pygraph vizgraphvizwrapc buildtempwinreleasepygraphvizgraphvizwrapo pygraphvizgraphvizwrapc in function agattrlabel pygraphvizgraphvizwrapc warning return makes integer pointer wi thout cast writing buildtempwinreleasepygraphvizgraphvizdef cmingwxybingccexe mnocygwin shared buildtempwinreleasepy graphvizgraphvizwrapo buildtempwinreleasepygraphvizgraphvizdef lcprogram files xgraphviz bin lcpythonlibs lcpythonpcb uild wlrcprogram files xgraphviz bin lcgraph lcdt lpython lmsvcr buildlibwinpygraphvizgraphvizpyd copy result built libwin single subfolder called pygraphviz python sitepackages folder enjoy,anybody successfully installed pygraphviz windows since official release windows i trying build fails compile i first one face issue i could find answer this console output cpythonlibsitepackagespygraphvizcpythonpythonexe setuppy install librarypathcprogram filesgraphvizlibdebugdll includepathcprogram filesgraphvizincludegraphviz running install running build running buildpy running buildext building pygraphvizgraphviz extension cprogram filesmicrosoft visual studio vcbinclexe c nologo ox md w gs dndebug icprogram filesgraphvizincludegraphviz icpython include icpythonpc tcpygraphvizgraphvizwrapc fobuildtempwin releasepygraphvizgraphvizwrapobj graphvizwrapc warning i know runtimelibrarydirs cprogram files graphvizlibdebugdll error know set runtime library search path msvc any help would appreciated,2 if read words set one file use setdifference this works care order output if care order read first file list second set remove elements list set quick brown fox jumped lazy dog b quick brown c x x x b print c gives fox jumped lazy dog,i two text files file file file contains bunch random words file contains words i want remove file occur is way i know i probably include attempt script least show effort honest laughable help if someone could least give tip start would greatly appreciated,3 get words f openpathtofile r f openpathtofile r fileraw fread fileraw fread filewords filerawsplit filewords filerawsplit want unique words file file result setfilewordsdifferencesetfilewords care removing words text file w filewords fileraw filerawreplacew,i two text files file file file contains bunch random words file contains words i want remove file occur is way i know i probably include attempt script least show effort honest laughable help if someone could least give tip start would greatly appreciated,3 let take simplest approach use whatever language templating engine want write script generates config eg device name to check generate config device download actual config device run diff mail differences people charge auditing the templating engine makes difference case performance constraints seems i take python mako jinja cheetah ruby rails even bash sed script could work,i looking template engine pushing pulling data configuration files to specific cisco router configuration files my goal two parts to able template router config insert unique data hostname interface ip etc authoritative source mysql afterwards i mechanism loading configs once device configured placed production i need way auditing latest version template this would allow us discover operators change running configuration thoughts,1 you could use new regex library supports unicode fuzzy matching usrbinenv python coding utf itertools import ifilter imap import regex def apromatchwordre lines fuzzy e search recompileur wordre fuzzy search ifilternone imapsearch lines print mspan def main lst u moskau berlã­n bã¤rlin bxerlin berlã¤n split lst u london paris bã¤rlin lst u ã¤erlin beã¤lin split print print apromatch berlin lst print apromatch berlin lst print print apromatch berlin lst print apromatch berlin lst name main main e means one error kind permitted there three types errors insertion indicated deletion indicated substitution indicated output apromatch berlin lst berlã­n bã¤rlin bã¤rlin berlã¤n bã¤rlin ã¤erlin beã¤lin apromatch berlin lst berlã­n bã¤rlin bã¤rlin berlã¤n london paris bã¤rlin ã¤erlin beã¤lin,i trying use tre library python match misspelled input it important handle utf encoded strings well example the german capital name berlin pronunciation people would write bã¤rlin it working far nonascii character first second position detected string neither range detected string correct coding utf import tre def apromatchword list fz trefuzzynessmaxerr pt trecompileword l ptsearchifz print mgroups name main string u berlã­n encode utf string u bã¤rlin encode utf string u bxerlin encode utf string u berlã¤n encode utf string u london paris bã¤rlin encode utf string u ã¤erlin encode utf string u beã¤lin encode utf l moskau string string string string string string string print n print apromatch berlin l print apromatch berlin l print n print apromatch berlin l print apromatch berlin l output apromatch berlin l berlã­n ã¤rlin ã¤rlin berlã¤n ã¤rlin erlin beã¤lin apromatch berlin l berlã­n bã¤rlin bã¤rlin berlã¤n london paris bã¤rlin ã¤erlin beã¤lin not regex berlin works fine regex berlin u bã¤rlin encode utf u bxerlin encode utf u ã¤erlin encode utf working u berlã­n encode utf u berlã¤n encode utf u london paris bã¤rlin encode utf u beã¤lin encode utf work expected is something i wrong encoding do know trick,3 you could use set increment counter set count p count set count count endfor or could use loopindex p loopindex endfor check template designer documentation,i would like something like variable p testpy wich list b c p variable variable result output,3 its possible first noted app develop use python website backend serverside language know browser server outputs browser thats and i believe possible clientside language like javascript seem serious security privacy issue possible edit if developing chrome plugin lets say might whole different story goes towards chrome api tagging wrong python,is way programmatically obtain list open tabs browser index for example suppose google chrome open two tabs in program line something like tabslist listtabshwnd hwnd handle window overall chrome instance tabslist dictionary something like httpstackoverflowcom httpwwwcoolstuffffcom maybe title window instead url if bringing focus one possible python script keyboard commands control ctrl like control control an edit added later try help clarify picture local wxpython app already know activate given instance chrome box within wxpython app running locally browser instance multiple tabs open want insure certain tab focus able interact web page displayed maybe using ctrla ctrlc example harvest content this question issuing keyboard commands already known question obtain list open tabs possible thanks,1 regular expression way go but fill uncomfortably writing try small parser i wrote httpsgithubcomhgreccostringparser it translates string format regular expression in case following stringparser import parser parser parserip currently trusted white list using new trusted certificate ip parsertext if file multiple lines replace last line openlogtxt r fp ips parserline line fp good luck,i string ip currently trusted white list using new trusted certificate log file what i need look message extract ip address log file import os import shutil import optparse import sys def main file openmessages r logdata fileread fileclose searchstr currently trusted white list using new trusted certificate index logdatafindsearchstr print index return name main main how i extract ip address your response appreciated,1 if input string line input iterate lines iterates characters so lucas would never found onecharacter string tableinput would assigned the linebased iteration behaviour happens object file if wanted loop line string line inputsplit n since beautifulsoup available i say would much better use read value first cell row rather rely crude fragile stringsearching eta i would get table entry row contains string lucas hints use tdparent get containing row tdparentparent get containing tabletbody if wanted get v x next column could say something like tr soupfindtext recompile lucas parentparent vorx trfindall td find span string,i trying get line textfile contains certain sequence characters input trtdlucasvlanbetd tdspan stylecolorgreenfontweightboldvspantd tdspan stylecolorgreenfontweightboldvspantd tdspan stylecolorgreenfontweightboldvspantd tr trtdjeanpierrevlanbetd tdspan stylecolorgreenfontweightboldvspantd tdspan titlecannot connect stylecolorredfontweightboldxspantd tdspan titleno response dns stylecolorredfontweightboldxspantd tr trtdsofievlanbetd tdspan stylecolorgreenfontweightboldvspantd tdspan titlecannot connect stylecolorredfontweightboldxspantd tdspan titleno response dns stylecolorredfontweightboldxspantd tr trtdthomasvlanbetd tdspan stylecolorgreenfontweightboldvspantd tdspan stylecolorgreenfontweightboldvspantd tdspan stylecolorgreenfontweightboldvspantd tr now i need get line contains lucas i tried beautifulsoup meant get line content html tags i tried regular operator def soupparsertotableselfinput global header soup selfbeautifulsoupinput header soupfirst tr tableinput line input lucas line tableinput line print tableinput however keeps returning instead trtdlucasvlanbetd tdspan stylecolorgreenfontweightboldvspantd tdspan stylecolorgreenfontweightboldvspantd tdspan stylecolorgreenfontweightboldvspantd tr,2 while sure target os mac os x appscript import maplambda x xtitle app google chrome windowstabs u stack overflow u google on windows want look ole automation python,is way programmatically obtain list open tabs browser index for example suppose google chrome open two tabs in program line something like tabslist listtabshwnd hwnd handle window overall chrome instance tabslist dictionary something like httpstackoverflowcom httpwwwcoolstuffffcom maybe title window instead url if bringing focus one possible python script keyboard commands control ctrl like control control an edit added later try help clarify picture local wxpython app already know activate given instance chrome box within wxpython app running locally browser instance multiple tabs open want insure certain tab focus able interact web page displayed maybe using ctrla ctrlc example harvest content this question issuing keyboard commands already known question obtain list open tabs possible thanks,3 threading kinda sorta implies multiple stacks recursion single stacks that said get recurseleft recurseright part decide spawn threads subproblems current count threads low straight recursion otherwise combine concepts but regular python good language pattern python threads run interpreter hardware thread actually pick multiprocessing goodness,background i bit new developing general pythonprogramming question if method recursion involved enabling multiple threads multiprocessing i done light reading examples seem applying syntax new codeand cpu intensive tasks i wondering i redesign existing code say i something thats cpu intensivebasically keeps adding limit hit def adderexamplesum number sum print sum larger stoping else sum sum number print sum number number adderexamplesum number adderexample questionsthough process how would i approach make run faster assuming i multiple cores availablei want eventually want span machines i think thats sperate issue hadoop i keep example one system multiple cpu it seems threading best choicebecause time takes spawn new threads thats true i focus multiprocessing if recursions split different cpu svai queues i assume rejoin done can i create multiple threads process split processes multiple cpu lastly recursion depth limits overall limit based threadsproceses multiprocessingthreading get around another questionrelated guys trying codesrsa wireless keysetc via brute force overcome problem i assume scaling mathematical processes multiple cpu somehow this example build understanding would great any tipssuggestions would great thanks,1 if wraithext etc useful necessary split can imagine someone would use wraitutil without installing wraithcolor if decide split need set installrequires setuppy tells setuptools etc package dependencies also need setup namespacepackages telling wrait namespace receive packages more info httptarekziadewordpresscomtipsforpackagingyourpythonprojects httppackagespythonorgdistributesetuptoolshtml,i written python module i like make available others right one large module nested subfolders wraith util ext color i think best split subfolders separate packages the tipfy project however ext color modules depend util what best way organize release modules do i split name wraithutil wraithext wraithcolor like tipfy do i include util people install ext color,1 you following def somefunctionsettingssettings … unmodified code settings refers local settings variable lets somefunction use application settings default call application sending local settings somefunctionapplicationsettings explicit settings sent application one advantage approach code application explicitly shows somefunction gives results settingdependent,in application i settingspy file utilspy contains following applicationone import settings def somefunction logic based imported settings then application i applicationoneutils import somefunction in application i local settingspy i import somefunction i want use local settingspy file application so would one overide import application,1 tryexcept like exceptions python here example def raiseerror raise ioerror error message print before call try raiseerror except ioerror error printerror print after call edit to make realistic example def connecttoclient timesinceclientresponded raise clienttimeouterrorclientname timed try connecttoclientserver except clienttimeouterror error printerror sysexit,i got piece code jabberid xmppprotocoljidjid jid selfclient xmppclientserver jabberidgetdomain debug selfclientconnect raise ioerror cannot connect jabber server else selfclientauthuser jabberidgetnode password password resource jabberidgetresource raise ioerror cannot authenticate jabber server it using xmpppy since xmpppy throw exceptions could connect authenticate i need throw the question i catch exceptions i throw output error message full traceback keep code running despite edit is construction appropriate def raiseerror raise ioerror error selfclientconnect try selfraiseerror except ioerror error print error,2 proxy requires username passwordhow i modify url use credentials the format url httpusernamepasswordhostportpath though deprecated note safe send username password http,is true proxy http access url browser eg wwwcnncom httpwwwcnncom is true twisted i use proxy get page follows iurlhttpwwwcnncom clientgetpageiurlmethod get addcallbackselfprocesspageiurladderrbackselfprinterroriurl,1 as jakob bowyer noted pygame really way go i wanted add concerned pygame size selectively enable modules want runtime in case using midi playback features pygame consume much system resources,i making simple text adventure python thought background midi music would make little less boring is simple lightweight midi player api python or i need use full game library like pygame because i rather pass i want make lightweight possible,1 then enthought suite traitsui complete provides everything building model showing including input validation it plays nicely numpy scipy nice scientific app enthought ui use qt via pyside pyqt wx backends you also use qt directly via pyqt pyside embed plots using matplotlib pyqwt qtdesigner allows generate nice ui little effort you achieve type initialization validation traits effort,i looking good cross platform mac windows amp linux python gui framework library make life easier writing data analysis program since data represented custom data classes would great gui framework library could take away burden code input checks validation etc ie create input dialogs take care checking correct data range data type based data model the library i found far traitsui are similar libraries frameworks,2 the first thing comes mind python generator memory efficient def catdatafile cat generator f opendatafile r line f yield line then put logic another function supposing save results file def foodatafile outputfile f openoutputfile w cnt suma line catdatafile suma linesplit cnt cnt fwritestsn cnt suma suma fclose edit the solution assumed numbers first column all numbers n as case follow pattern extra details comments correct function def fooforyourcasedatafile outputfile f openoutputfile w interval suma cnt keep track number elements interval line catdatafile spl linesplit intspl interval cnt fwritestsn interval sumacnt else fwritestn interval interval suma cnt suma floatspl cnt fclose,there two numeric columns data file i need calculate average second column intervals first column i program task r r code really slow relatively large data file millions rows value first column changing here i show r code how could i tune faster other solutions perl python awk shell based appreciated thanks advance data file tabdelimited millions rows n n n n n n n n n n n n n n n n n n n n i want get interval intervalsoffirstcolumns averageofnd columnbytheinterval n n n n r code chr set limit interval window set size interval spe readtablemydatafile headerf read data namesspe cpos rho name data intervalchr dataframeposseq chr window setup intervals meanrhochr null object mean i want get real calculation really slow data fori nrowintervalchr countsubsubsetspe chrom amp posintervalchrposi amp posintervalchrposi meanrhochrimeancountsubrho,1 you use decorator import sys def noinff def wrappedargs kwargs res fargs kwargs res float inf return sysfloatinfomax return res return wrapped noinf def mymultx return xy printmymultsysfloatinfomax prints e,i several functions multiple calculations might return inf like in numpyexp out inf i rather return maximum float value in sysfloatinfomax out e i could put checks every time inf might pop wrap calculation function rounds inf desired float however i really like simple hack beginning every function like inf sysfloatinfomax which obviously work is smart way thanks,2 i know replacing infinity value using min something like assuming x yields value return min x sysfloatinfomax,i several functions multiple calculations might return inf like in numpyexp out inf i rather return maximum float value in sysfloatinfomax out e i could put checks every time inf might pop wrap calculation function rounds inf desired float however i really like simple hack beginning every function like inf sysfloatinfomax which obviously work is smart way thanks,1 based code i would guess would work full data set depending system memory chr window pos cutchr seq chr window meanrhochr tapplysperho index pos fun mean i think want factor defines groups intervals every within first column rho use standard apply family functions get means within groups here data posted reproducible form spe structurelistpos cl l l l l l l l l l l l l l l l l l l l rho c names cpos rho rownames cna l class dataframe define intervals cut want every th value might want details tweaked per code real data set posindex cutspepos seq maxspepos now pass desired function mean group tapplysperho index posindex fun mean lots nas since start ee ee ee ee ee ee ee add arguments fun narm necessary eg tapplysperho index posindex fun mean narm true see tapply applying groups vector ragged array cut ways generate grouping factors,there two numeric columns data file i need calculate average second column intervals first column i program task r r code really slow relatively large data file millions rows value first column changing here i show r code how could i tune faster other solutions perl python awk shell based appreciated thanks advance data file tabdelimited millions rows n n n n n n n n n n n n n n n n n n n n i want get interval intervalsoffirstcolumns averageofnd columnbytheinterval n n n n r code chr set limit interval window set size interval spe readtablemydatafile headerf read data namesspe cpos rho name data intervalchr dataframeposseq chr window setup intervals meanrhochr null object mean i want get real calculation really slow data fori nrowintervalchr countsubsubsetspe chrom amp posintervalchrposi amp posintervalchrposi meanrhochrimeancountsubrho,1 i use sets letters setabcdeir openallthewordstxt r f word f setword letters check letters word letters print word you tweak required,ok i newbie i appreciate clues hints this first question sorry anything messy i found lot help types lists magic tricks things much i use one i want make list little text file containing words universe first i want user write letters i want list words contain letters the letters abcdeir example list would go bad bar beard etc here i far file openallthewordstxt r,1 there findobj method matplotlib import matplotlibpyplot plt import numpy np h pltfigure pltplotrange range gid dummy mylegend pltlegend line plttitle myfigure sure seth name myfigure myaxis pltgca myaxissetxlim p sethfindobjlambda x xgetgid dummy psetydatanpones pltshow note gid parameter pltplot usually used matplotlib backend set svg it use gid id attribute grouping elements like lined patch text,i trying go away matlab use python matplotlib instead however i really figured matplotlib equivalent matlab handles so matlab code i return handles i change certain properties what exact equivalent code using matplotlib i often use tag property handles matlab use findobj can done matplotlib well create figure return figure handle h figure add plot tag find handle later plot tag dummy add legend mylegend legend line change figure name seth name myfigure find current axes myaxis gca change xlimits setmyaxis xlim find plot object generated modify ydata setfindobj tag dummy ydata repmat,2 remember full power regexes match urls you simply need write regex accepts want r friendsptyperequestsoffers appviewspendingfriends if want list twice like r friendsptyperequests appviewspendingfriends r friendsptypeoffers appviewspendingfriends,i looking best way pass either two arguments views url without allowing additional arguments for example following urls r friendsrequests appviewspendingfriends r friendsoffers appviewspendingfriends if possible pass url views pendingfriends knows url called would work however i see way instead i could supply arguments requests offers url single django view r friendsptypew appviewspendingfriends the argument tell pendingfriends however leaves open possibility arguments passed url besides requests offers ideally i like url dispatcher stop happening via invalid arguments get passed views so questions best approach b way constrain arguments passed views url requests offers thanks,3 read docs the first argument provides initial value defaultfactory attribute defaults none all remaining arguments treated passed dict constructor including keyword arguments collections import defaultdict ddefaultdictint ziprangerange or given dictionary collections import defaultdict ddictziprangerange newdict defauldictintd,if i ddictziprangerange i build collectionsdefaultdict dict the argument defaultdict seems take factory function i initialize go original update defaultdict,3 fileout open outtxt w list b c fileoutwrite n joinlist,i like avoid writing newline character end text file python this problem i lot i sure fixed easily here example fileout open outtxt w list b c list fileoutwrite sn this prints n character end file how i modify loop avoid,3 in opinion text file consists lines text lines terminated line feed sequence exact details platformspecific thus proper text file must always contain exactly line feed sequence per line anyway could probably solve either treating last line differently building entire file inmemory writing binary data taking care omit final one two bytes depending platform line feed sequence exact format,i like avoid writing newline character end text file python this problem i lot i sure fixed easily here example fileout open outtxt w list b c list fileoutwrite sn this prints n character end file how i modify loop avoid,1 here solution avoids creating intermediate string helpful size list large instead worrying newline end file puts newline line printed except first line gets handled outside loop fileout open outtxt w mylist b c listiter itermylist first listiter fileoutwritefirst listiter fileoutwrite n fileoutwritei,i like avoid writing newline character end text file python this problem i lot i sure fixed easily here example fileout open outtxt w list b c list fileoutwrite sn this prints n character end file how i modify loop avoid,1 if really long lists want convert one string join good old flag varaibles come rescue isfirstline true mylist isfirstline see write branch isfirstline false else written line add newline outputwrite n outputwrites,i like avoid writing newline character end text file python this problem i lot i sure fixed easily here example fileout open outtxt w list b c list fileoutwrite sn this prints n character end file how i modify loop avoid,1 it looks like copied header output shell window module window you want file look like python r nov msc v bit intel win type copyright credits license information print hello world you want print hello world delete stuff,i started learning python writing programs python gui shell idle the code following def buildconnectionstringparams build connection string dictionary parameters returns string return joinss kv kv paramsitems name main myparams servermpligrim databasemaster uidsa pwdsecret printbuildconnectionstringmyparams i facing problem i i try run program in idle i click run module new windows opens saying invalid syntax here screenshot i able find run would appreciate help proceeding link httpiimgurcomuzafypng,1 you really need set output dataframe want here i would coded i guarantee fast datincrmt datv dat v v incrmt withdat tapplyv incrmt mean narmtrue you could done even less setup skip incrmt variable code withdat tapplyv v mean narmtrue and want result available something bymeanv withdat tapplyv v mean narmtrue,there two numeric columns data file i need calculate average second column intervals first column i program task r r code really slow relatively large data file millions rows value first column changing here i show r code how could i tune faster other solutions perl python awk shell based appreciated thanks advance data file tabdelimited millions rows n n n n n n n n n n n n n n n n n n n n i want get interval intervalsoffirstcolumns averageofnd columnbytheinterval n n n n r code chr set limit interval window set size interval spe readtablemydatafile headerf read data namesspe cpos rho name data intervalchr dataframeposseq chr window setup intervals meanrhochr null object mean i want get real calculation really slow data fori nrowintervalchr countsubsubsetspe chrom amp posintervalchrposi amp posintervalchrposi meanrhochrimeancountsubrho,3 if i understand correctly problem might use randomsample python import random pool setfoo bar baz elements slen lenpool need subsets set setrandomsamplepool slen st random subset pool set set setrandomsamplepool slen nd random subset pool set set pool rd random subset,for purpose conducting psychological experiment i divide set pictures described features real numbers subsets equal number elements subset way subsets approximately balanced respect features terms mean standard deviation can anybody suggest algorithm automate are packagesmodules python r i could use where i start,2 in wikipedia gave link external links bottom among interesting relatively project python implementation robert dick wouldn fulfil need a series two articles describing algorithms implemented r first article second article the r implementation exhaustive offers complete exact solutions it processes input variables you could use rpy python interface r language run r code quinemccluskey algorithm note rewrite rpy rpy also write new python script using enhancement algorithm done adrian duåŸa lying second article,i trying write quinemccluskey algorithm python i wanted see versions i might use instead a google search showed useful results i looking x map reduction x x any ideas references,2 here perl program i think want it assumes rows sorted first column usrbinperl use strict use warnings inputname tdat outputname toutdat initialinterval intervalsize startinterval initialinterval endinterval startinterval intervalsize intervaltotal intervalcount open data inputname die inputname open avgs outputname die outputname rowsin rowsout data rowsin progress indicator nice big data print unless rowsin print n unless rowsin key value split handle possible missing intervals key endinterval put value empty interval intervalavg empty intervalcount intervalavg intervaltotalintervalcount print avgs startintervalt intervalavg n rowsout intervalcount intervaltotal startinterval endinterval endinterval intervalsize intervalcount intervaltotal value handle last interval intervalcount intervalavg intervaltotalintervalcount print avgs startintervalt intervalavg n rowsout print n print rows rowsinn print rows rowsoutn exit,there two numeric columns data file i need calculate average second column intervals first column i program task r r code really slow relatively large data file millions rows value first column changing here i show r code how could i tune faster other solutions perl python awk shell based appreciated thanks advance data file tabdelimited millions rows n n n n n n n n n n n n n n n n n n n n i want get interval intervalsoffirstcolumns averageofnd columnbytheinterval n n n n r code chr set limit interval window set size interval spe readtablemydatafile headerf read data namesspe cpos rho name data intervalchr dataframeposseq chr window setup intervals meanrhochr null object mean i want get real calculation really slow data fori nrowintervalchr countsubsubsetspe chrom amp posintervalchrposi amp posintervalchrposi meanrhochrimeancountsubrho,1 just source virtualenvwrappersh script script import virtualenvwrapper functions you able use workon function script and maybe better could create shell script could name venvrunsh example run python script given virtualenv place usrbin usrlocalbin directory path such script could look like binsh virtualenvwrappersh path ie installed pip source virtualenvwrappersh source pathtovirtualenvwrappersh path workon python deactivate and could used simply like venvrunsh myvirtualenv pathtoscriptpy,so i make nice python program makes life ever easier saves lot time ofcourse involves virtualenv made mkvirtualenv function virtualenvwrapper the project requirementstxt file required libraries requests d program run without libraries i trying add binrunapp executable shell script would path symlink actually now inside script i need switch virtualenv i run program so i put binbash cd project directory workon cat venv python mainpy a file venv contains virtualenv name but i run script i get workon command found error of course i virtualenvwrappersh sourced bashrc seem available shell script so i access virtualenvwrapper functions or i wrong way how launch python tools virtualenv,3 i would tackle follows divide equal subsets figure mean variance subset from construct unevenness measure compare pair elements swapping would reduce unevenness swap continue either pairs compare total unevenness arbitrary good enough threshold,for purpose conducting psychological experiment i divide set pictures described features real numbers subsets equal number elements subset way subsets approximately balanced respect features terms mean standard deviation can anybody suggest algorithm automate are packagesmodules python r i could use where i start,1 if use columnspan use sticky we three labelframes width for example want use steptwo tkinterlabelframeform text enter table details steptwogridrow columnspan sticky we padx pady ipadx ipady questions when use frames grid row column specific size frame calculated based size form root window there interdependence the preferred size form depend preferred sizes children layout actual sizes children depend actual size form layout layout done children root determine preferred sizes gets root preferred size used actual size unless overridden layout goes back assigning actual sizes how size column determined grid the preferred size column determined based minimum preferred width items row the actual size column determined preferred size plus percentage extra space parent widget i fully understood weight within grid when used the weight determines percentage extra space i mentioned the amount extra space given column columnweighttotalweight,building small application personal use python thought i try hand little gui programming using tkinter this gui i created far application doubts how i make sure three lableframes a b c screenshot width or rather width equal widest three for example screenshot a widest i like b c also wide line d it dynamically calculated enough i ensure width i code first time round they need change runtime tk grid geometry manager doubts when use frames grid row column specific size frame calculated based size form root window how size column determined grid i fully understood weight within grid when used the python gui code import tkinter name main form tkintertk getfld tkinterintvar formwmtitle file parser stepone tkinterlabelframeform text enter file details steponegridrow columnspan sticky w padx pady ipadx ipady helplf tkinterlabelframeform text quick help helplfgridrow column columnspan rowspan sticky ns padx pady helplbl tkinterlabelhelplf texthelp come ask helplblgridrow steptwo tkinterlabelframeform text enter table details steptwogridrow columnspan sticky w padx pady ipadx ipady stepthree tkinterlabelframeform text configure stepthreegridrow columnspan sticky w padx pady ipadx ipady infilelbl tkinterlabelstepone textselect file infilelblgridrow column sticky e padx pady infiletxt tkinterentrystepone infiletxtgridrow column columnspan stickywe pady infilebtn tkinterbuttonstepone textbrowse infilebtngridrow column sticky w padx pady outfilelbl tkinterlabelstepone textsave file outfilelblgridrow column sticky e padx pady outfiletxt tkinterentrystepone outfiletxtgridrow column columnspan stickywe pady outfilebtn tkinterbuttonstepone textbrowse outfilebtngridrow column sticky w padx pady inenclbl tkinterlabelstepone textinput file encoding inenclblgridrow column sticky e padx pady inenctxt tkinterentrystepone inenctxtgridrow column sticky e pady outenclbl tkinterlabelstepone textoutput file encoding outenclblgridrow column padx pady outenctxt tkinterentrystepone outenctxtgridrow column pady outtbllbl tkinterlabelsteptwo textenter name table used statements outtbllblgridrow column sticky w padx pady outtbltxt tkinterentrysteptwo outtbltxtgridrow column columnspan pady sticky we fldlbl tkinterlabelsteptwo textenter field column names table fldlblgridrow column padx pady sticky w getfldchk tkintercheckbuttonsteptwo textget fields automatically input file onvalue offvalue getfldchkgridrow column columnspan pady sticky we fldrowtxt tkinterentrysteptwo fldrowtxtgridrow columnspan padx pady sticky we transchk tkintercheckbuttonstepthree textenable transaction onvalue offvalue transchkgridrow sticky w padx pady transrwlbl tkinterlabelstepthree text specify number rows per transaction transrwlblgridrow column columnspan sticky w padx pady transrwtxt tkinterentrystepthree transrwtxtgridrow column sticky we formmainloop note for python,3 sort compare sorteda sortedb,b c when comparing b return true items presented b items b presented when comparing c return false items exist c what pythonic way,3 use sets frozensets seta python higher set literal use setiter syntax older versions setb seta setb seta setb setb seta the biggest advantage using sets list method highly readable mutated original iterable perform well even cases huge b tiny checking whether b length first good optimization expect case often though using right data structure job pythonic,b c when comparing b return true items presented b items b presented when comparing c return false items exist c what pythonic way,3 use set in seta setb out true in seta setc out false,b c when comparing b return true items presented b items b presented when comparing c return false items exist c what pythonic way,1 turn sets set set true set set false if lists contain duplicate items compare lengths sets collapse duplicates,b c when comparing b return true items presented b items b presented when comparing c return false items exist c what pythonic way,1 you try put ab variable variable b variable not sure want,this posted googlecom wrote hi niklas if want map regioncitycategory supposing valid characters azaz following mainpy application webappwsgiapplication www handlerdebugtrue handler class handlerwebapprequesthandler def getself region city category use variables method hope helps my webapp suppossed handle uri like regioncitycategory optional city category eg riodejaneirogranderiodejaneirocasas regioncitycategory gujaratahmedabadvehiclesforsale regioncitycategory riodejaneirogranderiodejaneiro regioncity delhi region etc now i want enable request handler take optional arguments divided separator if i use regex variables request handler first varible becomes ab second variable becomes b nearly i want b different variables instead the regex i tried request handler application webappwsgiapplication mypage and function head request handler class mypagerequesthandler def getself location frankfurt category electronics to enable http query eg frankfurt frankfurt frankfurtelectronics madridapartments newyork etc allowing possible combinations can advice regex achieve i want i want functionality like modrewrite gae thanks clarification it question make directory variable clarify examples behave frankfurt put frankfurt variable frankfurt put frankfurt variable frankfurtelectronics put frankfurt variable electronics virable frankfurtelectronics eufrankfurtelectronics ie last groups count eufrankfurtelectronics torontolightnings start work torontolightnings limacarsold limacarsold typical cases i want handle regioncitycategory ie i apply example brazil could riodejaneirogranderiodejaneirocasas regioncitycategory india could delhidelhiforsale gujaratahmedabadvehiclesforsale solution as far i tell solution answer works purposes,1 selenium selectframe command accepts standard locators like css also extra set locators work specifically frame iframe elements as doc says selectframe locator selects frame within current window you may invoke command multiple times select nested frames to select parent frame use relativeparent locator select top frame use relativetop you also select frame based index number select first frame index third frame index you may also use dom expression identify frame want directly like domframesmainframessubframe arguments locator element locator identifying frame iframe in general better luck using specialized locators especially establish right context first eg selectframerelativetop selectframeiduploadfileframe,so i absolutely baffled selenium find answer anywhere i sharing experience i trying select iframe luck repeatably anyway the html looked like iframeâ iduploadfileframeâ widthâ heightpxâ frameborderâ framemarginâ nameuploadfileframeâ srcblahimport html body divâ classimportdevices divâ classimporttype aâ classsecondarybuttonâ hrefblahblahsourceblah divâ classimportchoiceimage imgâ altblahâ srcpublicimagesblahimportblahpng div divâ classimportchoicetextblah blahdiv div div body html the python code using selenium library trying find iframe using timed def testpedometerself sel selfselenium timesleep range try selselectframecssuploadfileframe break except pass timesleep else selffailcannot find uploadfileframe iframe device upload image buttons repeated fails every combination selenium commands i could find the occasional success would reproducible perhaps sort race condition something never find right way get selenium proper,1 check python build script github httpsgithubcomwavetossedpybuild run debian ubuntu vm the python tarball results run linux including centos build script needs run debian derived system because build uses runpathrpath untarred folder however one bit fixup needs done make run run included patchelf tool setinterpreter use new path binaries live this affects python binary patchelf binary untar datapackagespython first run patchelf move want directory tree or could change targ build,how would i create python distro like activepython basically linux centos platforms ideally work like activepython i could untar location eg nfs share pathtopython get scripts use this usually common scenario enterprise environments dont want touch standard servers builds eg install anything using rpms pollute usrlocal etc sure i could download amp use activepython i interested process behind creating distros edit this also main reason i use epel python packages sigh,2 if define prefix characters underscore check namepartition c l e b foo namepartition name namepartition,i need find whether name starts list prefixes remove like name c l e b name name the works list prefixes length two i need functionality variablelength prefixes how done efficiently little code good performance a loop iterating prefix checking namestartswithprefix finally slice name according length prefix works lot code probably inefficient nonpythonic does anybody nice solution,1 prefix prefixes namestartswithprefix namenamelenprefix break,i need find whether name starts list prefixes remove like name c l e b name name the works list prefixes length two i need functionality variablelength prefixes how done efficiently little code good performance a loop iterating prefix checking namestartswithprefix finally slice name according length prefix works lot code probably inefficient nonpythonic does anybody nice solution,3 i sure i know exception getting since trying get sqlalchemy execute similar query one posted select statement clause need call mapper result sqlalchemyselect similar linked example this mapped class x query trying imitate then sessionqueryfruitsjoinx filter get final result the subquery method query object contrast situations desire select statement clause column select use subquery obtain become inner select final generated query you create separate outer query join result subquery call to get sqlalchemy use query similar example appear need use technique,i using example help learn sqlalchemy here mysql select ftype fvariety fprice select type minprice minprice fruits group type x inner join fruits f ftype xtype fprice xminprice here i far session sq squeryfuncminfruitpricegroupbyfruittypesubquery ans squeryfruitjoinsq fruitpricesqcpriceall clearly work am i even close i pouring docs price pk helps maybe need alias something any help direction appreciated,1 it works have tried files directories are sure user python run access tmpapy,python gnome binding gnomevfs module theoretically get mime types but calling gnomevfsgetmimetype name devnull raises error runtimeerror error reading file for example import gnomevfs gnomevfsgetmimetype tmpapy gnomevfsgetmimetype filetmpapy gnomevfsgetmimetype filetmpapy gnomevfsgetmimetype filetmpapy this fails with file folder name except devnull tmpapy exists acessible any suggestions,1 when comes search efficiency always thinks indexing techniques improve algorithms if long list prefixes use inmemory index simple indexing prefixes first character dict this solution worth long list prefixes performance becomes issue pref c l e b indexing prefixes dict do dict x pref x dx list dxappendx name cabcdf lookup check elements first character result filterlambda x namestartswithx name else dname print result,i need find whether name starts list prefixes remove like name c l e b name name the works list prefixes length two i need functionality variablelength prefixes how done efficiently little code good performance a loop iterating prefix checking namestartswithprefix finally slice name according length prefix works lot code probably inefficient nonpythonic does anybody nice solution,1 a bit hard read works namenamelenfilternamestartswithprefixes,i need find whether name starts list prefixes remove like name c l e b name name the works list prefixes length two i need functionality variablelength prefixes how done efficiently little code good performance a loop iterating prefix checking namestartswithprefix finally slice name according length prefix works lot code probably inefficient nonpythonic does anybody nice solution,3 strstartswithprefix start endâ¶ return true string starts prefix otherwise return false prefix also tuple prefixes look with optional start test string beginning position with optional end stop comparing string position,i need find whether name starts list prefixes remove like name c l e b name name the works list prefixes length two i need functionality variablelength prefixes how done efficiently little code good performance a loop iterating prefix checking namestartswithprefix finally slice name according length prefix works lot code probably inefficient nonpythonic does anybody nice solution,3 use strict use warnings binsize freq k v split bin binsize intk binsize freqbinn freqbinsum v bin sort b keys freq n sum map freqbin qwn sum print joint bin n sum sum n n,there two numeric columns data file i need calculate average second column intervals first column i program task r r code really slow relatively large data file millions rows value first column changing here i show r code how could i tune faster other solutions perl python awk shell based appreciated thanks advance data file tabdelimited millions rows n n n n n n n n n n n n n n n n n n n n i want get interval intervalsoffirstcolumns averageofnd columnbytheinterval n n n n r code chr set limit interval window set size interval spe readtablemydatafile headerf read data namesspe cpos rho name data intervalchr dataframeposseq chr window setup intervals meanrhochr null object mean i want get real calculation really slow data fori nrowintervalchr countsubsubsetspe chrom amp posintervalchrposi amp posintervalchrposi meanrhochrimeancountsubrho,2 if using zeromq set rcvtimeo socket option clientreceiverrcvtimeo milliseconds but general use pollers poller zmqpoller pollerregisterclientreceiver zmqpollin pollin recv pollout send and pollerpoll takes timeout evts pollerpoll wait one second message arrive evts empty list nothing receive you poll zmqpollout check send succeed or handle case peer might failed workersendmsg zmqnoblock might suffice always return immediately raising zmqerrorzmqeagain send could complete,i got started zmq i designing app whose workflow one many clients random pull addresses push request server server forever waiting client pushes when one comes worker process spawned particular request yes worker processes exist concurrently when process completes task pushes result client i assume pushpull architecture suited please correct but i handle scenarios clientreceiverrecv wait infinite time server fails respond client may send request fail immediately hence worker process remain stuck serversendersend forever so i setup something like timeout pushpull model edit thanks user suggestions i got working answer i sharing posterity,3 you easily using plyr library r here code requireplyr create dummy data mydf dataframefeature sampleletters replace true split by feature and divide into three subsets equally ddplymydf feature summarize sub sample replace true,for purpose conducting psychological experiment i divide set pictures described features real numbers subsets equal number elements subset way subsets approximately balanced respect features terms mean standard deviation can anybody suggest algorithm automate are packagesmodules python r i could use where i start,1 what using filter prefs c l e b name listfilterlambda item anyitemstartswithprefix prefix prefs name note comparison list item prefixes efficiently halts first match this behaviour guaranteed function returns soon finds true value eg def gen printyielding false yield false printyielding true yield true printyielding false yield false anygen last two lines gen performed yielding false yielding true true or using rematch instead startswith import patt joini c l e b name listfilterlambda item rematchpatt item name,i need find whether name starts list prefixes remove like name c l e b name name the works list prefixes length two i need functionality variablelength prefixes how done efficiently little code good performance a loop iterating prefix checking namestartswithprefix finally slice name according length prefix works lot code probably inefficient nonpythonic does anybody nice solution,1 regexes likely give best speed prefixes c l e b alsolonger reprefixes joinreescapep p prefixes rematchreprefixes mystring mystring mystringmendmstart,i need find whether name starts list prefixes remove like name c l e b name name the works list prefixes length two i need functionality variablelength prefixes how done efficiently little code good performance a loop iterating prefix checking namestartswithprefix finally slice name according length prefix works lot code probably inefficient nonpythonic does anybody nice solution,1 if variable class attribute may define setattr class,is way call function eachtime value variable changes python something like listener perhaps specifically i referring case variable shared scripts like gaesession which uses cookies memcache etc share data example scripta amp scriptb share session variable when script b changes sctipta call method handle change,1 this package may helpful,is way call function eachtime value variable changes python something like listener perhaps specifically i referring case variable shared scripts like gaesession which uses cookies memcache etc share data example scripta amp scriptb share session variable when script b changes sctipta call method handle change,1 given size problem need use datatable lightening fast requiredatatable n m mydt datatablev runifn m v rpoisn lambda ans mydtlistavgv meanv v this took seconds macbook pro specs ghz gb ram if na second column obtain x speedup replacing mean internalmean here speed comparison using rbenchmark replications note datatable internalmean x faster test replications elapsed relative fdt ftapply fdtinternal update matthew new v optimization replacing mean internalmean automatically made ie regular dtmeansomecolby runs x faster speed we try make convenience changes like future users need know many tricks order get best datatable,there two numeric columns data file i need calculate average second column intervals first column i program task r r code really slow relatively large data file millions rows value first column changing here i show r code how could i tune faster other solutions perl python awk shell based appreciated thanks advance data file tabdelimited millions rows n n n n n n n n n n n n n n n n n n n n i want get interval intervalsoffirstcolumns averageofnd columnbytheinterval n n n n r code chr set limit interval window set size interval spe readtablemydatafile headerf read data namesspe cpos rho name data intervalchr dataframeposseq chr window setup intervals meanrhochr null object mean i want get real calculation really slow data fori nrowintervalchr countsubsubsetspe chrom amp posintervalchrposi amp posintervalchrposi meanrhochrimeancountsubrho,2 this thick thick win stuff i started writing using pywin switched ctypes better deal structures note i wrote win xp you change tbbutton def bit i sure uac allocate memory another process import commctrl wincon ctypes import represent tbbutton structure note bit bit padds reserved bytes class tbbuttonstructure pack fields ibitmap cint idcommand cint fsstate cubyte fsstyle cubyte breserved cubyte dwdata culong istring cint get handle sytem tray hwnd windlluserfindwindowashelltraywnd none hwnd windlluserfindwindowexahwnd none traynotifywnd none hwnd windlluserfindwindowexahwnd none syspager none hwnd windlluserfindwindowexahwnd none toolbarwindow none get count icons tray numicons windllusersendmessageahwnd commctrltbbuttoncount allocate memory within system tray pid culong windllusergetwindowthreadprocessidhwnd byrefpid hprocess windllkernelopenprocesswinconprocessallaccess pid lppointer windllkernelvirtualallocexhprocess sizeoftbbutton winconmemcommit winconpagereadwrite init tool bar button handle tbbutton tbbutton buthandle cint rangenumicons query button memory allocated windllusersendmessageahwnd commctrltbgetbutton lppointer read memory button struct windllkernelreadprocessmemoryhprocess lppointer addressoftbbutton none read st bytes dwdata buthandle var first bytes contain handle button windllkernelreadprocessmemoryhprocess tbbuttondwdata addressofbuthandle none get pid created button butpid culong windllusergetwindowthreadprocessidbuthandle byrefbutpid leave get process pid trivial print butpid,is way use python get list icons system tray lower right hand corner associated processes executables here thread using ahk httpwwwautohotkeycomforumtopichtml relies heavily ahk note i interested windows xp thanks,1 a pipe simply wrong solution if want present consistent snapshot internal state process write temporary file rename public name this prevent issues arise processes reading state updating also not busy loop ideally thread sleeps least one second updates,i trying use unix named pipe output statistics running service i intend provide similar interface proc one see live stats catting file i using code similar python code true f open tmpreadstatshere w fwrite interesting statsn fclose tmpreadstatshere named pipe created mknod i cat see stats cat tmpreadstatshere interesting stats it works fine time however i cat entry several times quick successions sometimes i get multiple lines interesting stats instead one once twice even gone infinite loop printing line forever i killed the fix i got far put delay let say ms fclose prevent issue i like know exactly happens better way dealing thanks advance,1 use properties only mutable values change begin class somethingobject property def somevalueself return selfactual somevaluesetter def somevalueself value print somevalue changed value selfactual value,is way call function eachtime value variable changes python something like listener perhaps specifically i referring case variable shared scripts like gaesession which uses cookies memcache etc share data example scripta amp scriptb share session variable when script b changes sctipta call method handle change,2 after given details i propose another regex pattern import reg recompile z partial re matches first groups or nothing catched group always catching something possible second third group z end ss frankfurt frankfurt frankfurtelectronics frankfurtelectronics eufrankfurtelectronics eufrankfurtelectronics torontolightnings torontolightnings limacarsold limacarsold riodejaneirogranderiodejaneirocasasmagdalena mat regmatchss print ss n matgroups mat else no matching n result frankfurt frankfurt frankfurt frankfurt frankfurtelectronics frankfurt electronics eufrankfurtelectronics frankfurt electronics torontolightnings no matching limacarsold no matching riodejaneirogranderiodejaneirocasasmagdalena no matching but know using regex absolutely necessary solve problem ss frankfurt frankfurt frankfurtelectronics frankfurtelectronics eufrankfurtelectronics eufrankfurtelectronics torontolightnings torontolightnings limacarsold limacarsold riodejaneirogranderiodejaneirocasasmagdalena ss splitted ssrstrip split lensplitted grps splitted elif lensplitted grps splitted else grps none else grps none print ss n grps grps else incorrect string n the results,this posted googlecom wrote hi niklas if want map regioncitycategory supposing valid characters azaz following mainpy application webappwsgiapplication www handlerdebugtrue handler class handlerwebapprequesthandler def getself region city category use variables method hope helps my webapp suppossed handle uri like regioncitycategory optional city category eg riodejaneirogranderiodejaneirocasas regioncitycategory gujaratahmedabadvehiclesforsale regioncitycategory riodejaneirogranderiodejaneiro regioncity delhi region etc now i want enable request handler take optional arguments divided separator if i use regex variables request handler first varible becomes ab second variable becomes b nearly i want b different variables instead the regex i tried request handler application webappwsgiapplication mypage and function head request handler class mypagerequesthandler def getself location frankfurt category electronics to enable http query eg frankfurt frankfurt frankfurtelectronics madridapartments newyork etc allowing possible combinations can advice regex achieve i want i want functionality like modrewrite gae thanks clarification it question make directory variable clarify examples behave frankfurt put frankfurt variable frankfurt put frankfurt variable frankfurtelectronics put frankfurt variable electronics virable frankfurtelectronics eufrankfurtelectronics ie last groups count eufrankfurtelectronics torontolightnings start work torontolightnings limacarsold limacarsold typical cases i want handle regioncitycategory ie i apply example brazil could riodejaneirogranderiodejaneirocasas regioncitycategory india could delhidelhiforsale gujaratahmedabadvehiclesforsale solution as far i tell solution answer works purposes,1 since mysqlconnector db api v compliant need escape data automatically,i trying insert bunch strings mysql using python mysqlconnector my current code looks something like db mysqlconnectorconnect config blah blah cursor dbcursor data somestring somestring sql insert into mytable col col values cursorexecutesql data how i go escaping strings i could try python i know right way note i realise mysqlconnector still development update line read sql insert into mytable col col values,3 one method names mylist ages mylist nationalities mylist iterate name names print name etc,i list python following sample contents mark american james british arthur australian clear pattern first item list name second age third nationality what efficient way iterating separate elements inside one loop i new python know best method len lenmylist name age nationality,1 just loop steps xrangelenmylist name age nationality mylistii,i list python following sample contents mark american james british arthur australian clear pattern first item list name second age third nationality what efficient way iterating separate elements inside one loop i new python know best method len lenmylist name age nationality,2 the best way implement new kinds iteration write generator they let encapsulate iteration style separate rest code def bythreesseq iterseq true yield nextit nextit nextit b c bythreesrange print abc prints if need tuplize sequence flexibly could use def bychunksseq n yield lists ab seq list n elements l x enumerateseq lappendx n n yield l l,i list python following sample contents mark american james british arthur australian clear pattern first item list name second age third nationality what efficient way iterating separate elements inside one loop i new python know best method len lenmylist name age nationality,2 try make sure dll initialized regardless many times code actually invoked here link c singleton dll singleton dll,i new python embedding i trying embed python numpy code inside c callback function inside dll problem facing following pyinitialize python glue python invocation pyfinalize everything works fine pyinitialize importarray initialize numpy capi python glue numpy array object creation python invocation via pyobjectcallobject pyfinalize crashes second time reaches importarray meaning works first callback instead python numpy initialization finalization destructor thus every time initializingfinalizing everything crashes leaving callback the problem guess numpy dont know solve,1 use step indices zip itertoolsizip l mark american james british arthur australian name age nationality zipl l l print name age nationality mark american james british arthur australian,i list python following sample contents mark american james british arthur australian clear pattern first item list name second age third nationality what efficient way iterating separate elements inside one loop i new python know best method len lenmylist name age nationality,2 try handy pattern itertools import izip iters itermylist change number items group name age nationality izipiters print name age nationality,i list python following sample contents mark american james british arthur australian clear pattern first item list name second age third nationality what efficient way iterating separate elements inside one loop i new python know best method len lenmylist name age nationality,2 if java functionality critical application easy rewrite python could write simple web app java uses library run appengine separate version main python app you could call java app python app using http this elegant solution really need functionality get job done the key app engine let run one version app time including different runtimes,i using python google app engine i java class library i want use program is way import library use python program i searched net found something like jpype import import import string startjvmoptsunjrelibiclientlibjvmso djavaclasspathhometalatzemberekjar ea zerisim jpackage net zemberekerisimzemberek but i sure whether jpype used google app engine thank,1 a solution may work though may find hardcoded routes app structured like routes fooazaz testhandler fooazazazaz testhandler fooazazazazazaz testhandler and handler check lenargs something like class testhandlerwebapprequesthandler def getself args lenargs assign defaults perhaps,this posted googlecom wrote hi niklas if want map regioncitycategory supposing valid characters azaz following mainpy application webappwsgiapplication www handlerdebugtrue handler class handlerwebapprequesthandler def getself region city category use variables method hope helps my webapp suppossed handle uri like regioncitycategory optional city category eg riodejaneirogranderiodejaneirocasas regioncitycategory gujaratahmedabadvehiclesforsale regioncitycategory riodejaneirogranderiodejaneiro regioncity delhi region etc now i want enable request handler take optional arguments divided separator if i use regex variables request handler first varible becomes ab second variable becomes b nearly i want b different variables instead the regex i tried request handler application webappwsgiapplication mypage and function head request handler class mypagerequesthandler def getself location frankfurt category electronics to enable http query eg frankfurt frankfurt frankfurtelectronics madridapartments newyork etc allowing possible combinations can advice regex achieve i want i want functionality like modrewrite gae thanks clarification it question make directory variable clarify examples behave frankfurt put frankfurt variable frankfurt put frankfurt variable frankfurtelectronics put frankfurt variable electronics virable frankfurtelectronics eufrankfurtelectronics ie last groups count eufrankfurtelectronics torontolightnings start work torontolightnings limacarsold limacarsold typical cases i want handle regioncitycategory ie i apply example brazil could riodejaneirogranderiodejaneirocasas regioncitycategory india could delhidelhiforsale gujaratahmedabadvehiclesforsale solution as far i tell solution answer works purposes,1 you want glob want fnmatch dirpath dirnames filenames oswalktop filename filenames fnmatchfnmatchfilename mypattern print ospathjoindirname filename glob part work oswalk already done examine disk find files fnmatch pure string operation filename match pattern,currently oswalk code list files directories specified directory top homebludiescripttvshows dirpath dirnames filenames oswalktop filename filenames print ospathjoindirname filename could add globglobsearch search selfsearchgettext search pattern type gtkentry something would work current code,2 you want globglob checks names directory already retrieved instead use fnmatchfnmatch match pattern list pathnames got oswalk probably add path filename filenames fnmatchfnmatchfilename search print ospathjoindirname filename,currently oswalk code list files directories specified directory top homebludiescripttvshows dirpath dirnames filenames oswalktop filename filenames print ospathjoindirname filename could add globglobsearch search selfsearchgettext search pattern type gtkentry something would work current code,1 take look httpdocspythonorgwhatsnewhtmlpepabsoluteandrelativeimports you could mod import stuff,imagine directory structure app initpy sub initpy modpy sub initpy modpy i coding mod i need import something mod how i i tried sub import mod i getting attempted relative import nonpackage i googled around found syspath manipulation hacks isn clean way edit initpy currently empty edit i trying sub contains classes shared across sub packages sub subx etc edit the behaviour i looking described pep thanks john b,2 here one approach using multiprocessing many thanks voo suggesting many improvements code import multiprocessing mp import logging import queue import time loggermplogtostderrloggingdebug loggermplogtostderrloggingwarn uncomment silence debug info messages def workerurlqueueseen true urlurlqueueget url seen loggerinfo downloading u formatuurl seenurltrue replace code dowload url urllibopen timesleep contenturl loggerdebug parsing c formatccontent replace code finds interesting links puts urlqueue range content ucontenti loggerdebug adding u urlqueue formatuu timesleep urlqueueputu else loggerdebug skipping u seen formatuurl urlqueuetaskdone name main numworkers urlqueuempjoinablequeue managermpmanager seenmanagerdict prime url queue least one url urlqueueput downloadersmpprocesstargetworkerargsurlqueueseen rangenumworkers p downloaders pdaemontrue pstart urlqueuejoin a pool worker processes created there joinablequeue called urlqueue each worker gets url urlqueue finds new urls adds urlqueue only adding new items call urlqueuetaskdone the main process calls urlqueuejoin this blocks main process taskdone called every task urlqueue since worker processes daemon attribute set true end main process ends all components used example also explained doug hellman excellent python module week tutorial multiprocessing,i completely new multiprocessing i reading documentation multiprocessing module i read pool threads queues etc i completely lost what i want multiprocessing convert humble http downloader work multiple workers what i moment download page parse page get interesting links continue interesting links downloaded now i want implement multiprocessing but i idea moment organize work flow i two thoughts firstly i thought two queues one queue links needs downloaded links parsed one worker downloads pages adds queue items needs parsed and process parses page adds links finds interesting queue problems i expect approach first download one page time parse page time moreover one process know items added queue later exhausted items queue another approach i thought using have function called url argument this function downloads document starts parsing links every time encounters interesting link instantly creates new thread running identical function the problem i approach i keep track processes spawned around i know still processes running and also i limit maximum number processes so i completely lost can anyone suggest good strategy perhaps show example codes go idea,2 use rstrip method textfilereadlinerstrip,i want able read file add string onto line line without line break middle textfile openreadittxt r print textfilereadline outputs text i would like output format text,3 oneliner perl simple efficient usual perl ft lane beginli sub pprintrisn ifnrintfisnlast ifflp intfirsfnp,there two numeric columns data file i need calculate average second column intervals first column i program task r r code really slow relatively large data file millions rows value first column changing here i show r code how could i tune faster other solutions perl python awk shell based appreciated thanks advance data file tabdelimited millions rows n n n n n n n n n n n n n n n n n n n n i want get interval intervalsoffirstcolumns averageofnd columnbytheinterval n n n n r code chr set limit interval window set size interval spe readtablemydatafile headerf read data namesspe cpos rho name data intervalchr dataframeposseq chr window setup intervals meanrhochr null object mean i want get real calculation really slow data fori nrowintervalchr countsubsubsetspe chrom amp posintervalchrposi amp posintervalchrposi meanrhochrimeancountsubrho,1 you need install xcode osx install dvd online appstore it includes gcc compileer apprantly missing it also includes stuff like make probably need build maybe homebrew fink also gcc like included,i lot problems one when i try using easyinstall i get error warning gmp library found not building cryptopublickeyfastmath unable execute gcc no file directory error setup script exited error command gcc failed exit status how install paramiko i get error i try install pycrypto,1 what describing essentially graph traversal most graph traversal algorithms that sophisticated depth first keep track two sets nodes case nodes url the first set called closed set represents nodes already visited processed if processing page find link happens closed set ignore already handled the second set unsurprisingly called open set includes edges found yet processed the basic mechanism start putting root node open set closed set initially empty nodes processed yet start working each worker takes single node open set copies closed set processes node adds nodes discovers back open set long already either open closed sets once open set empty workers still processing nodes graph completely traversed actually implementing multiprocessing probably means master task keeps track open closed sets if worker worker pool indicates ready work master worker takes care moving node open set closed set starting worker workers pass nodes find without worrying already closed back master master ignore nodes already closed,i completely new multiprocessing i reading documentation multiprocessing module i read pool threads queues etc i completely lost what i want multiprocessing convert humble http downloader work multiple workers what i moment download page parse page get interesting links continue interesting links downloaded now i want implement multiprocessing but i idea moment organize work flow i two thoughts firstly i thought two queues one queue links needs downloaded links parsed one worker downloads pages adds queue items needs parsed and process parses page adds links finds interesting queue problems i expect approach first download one page time parse page time moreover one process know items added queue later exhausted items queue another approach i thought using have function called url argument this function downloads document starts parsing links every time encounters interesting link instantly creates new thread running identical function the problem i approach i keep track processes spawned around i know still processes running and also i limit maximum number processes so i completely lost can anyone suggest good strategy perhaps show example codes go idea,1 you check solutions like pagekite show off generally trivially easy set offer great deal flexibility mobility provide stable domain name localhost server,i used python manage runserver start server i access project computers wifi network browse internetipaddress another computer project load am i missing setting,1 it turned lxml better tool task lxmlhtmlclean import cleaner def cleanwordtexttext the thing i need cleaner clear contents stylestyle tags cleaner cleanerstyletrue return cleanercleanhtmltext,i using excellent bleach library removing bad html i got load html documents pasted microsoft word contain things like style stbehaviorurlieooui style using bleach style tag implicitly disallowed leaves stbehaviorurlieooui which helpful bleach seems options escape tags remove tags contents i looking third option remove tags contents is way use bleach htmllib completely remove style tag contents the documentation htmllib really great deal help,2 what mean internetipaddress that sounds like using external ip router you using ip particular machine serving internal address like,i used python manage runserver start server i access project computers wifi network browse internetipaddress another computer project load am i missing setting,3 you bind local ip address for example python managepy runserver,i used python manage runserver start server i access project computers wifi network browse internetipaddress another computer project load am i missing setting,2 use range function range print,i want python spit bunch numbers example date date print strdate want loop output numbers,2 assuming machines see eachother get ip address machine running runserver for example run ifconfig console ifconfig eth link encapethernet hwaddr ebab inet addr bcast mask check running firewall for example sudo ufw status active need open port console run sudo ufw allow tcp start runserver runserverplus using djangoextensions python managepy runserverplus open browser another machine httpadmin,i used python manage runserver start server i access project computers wifi network browse internetipaddress another computer project load am i missing setting,3 fnmatch implements unix shell wildcard syntax so whatever type ls command example work fnmatchfnmatchqxx azxx true fnmatchfnmatchabc true fnmatchfnmatchabcdef af true fnmatchfnmatchabcdef afk true keep mind fnmatch purely string matching operation if find convenient use different pattern style example regexes simply use regex operations match filenames,oswalk code search selfsearchgettext top homebludiescripttvshows dirpath dirnames filenames oswalktop filename filenames fnmatchfnmatchfilename search print ospathjoindirpath filename python docs shows match seq chars seq pattern matter try implement give kind error results would correct implementation match seq cars search print file files match implementations tried fnmatchfnmatchfilename search error got typeerror unhasable type list fnmatchfnmatchfilename search error got typeerror fnmatch function subscriptable fnmatchfnmatchfilename search error typeerror fnmatch takes two arguments given fnmatchfnmatchfilename search error typeerror expected string buffer fnmatchfnmatchsearch filename error typeerror expected string buffer fnmatchfnmatchfilename search seq error nameerror global name seq defined fnmatchfnmatchfilename search errors produce results search values hello mkv merry etc,3 change command lambda theyeartheyear yearsetertheyear the problem python looks value theyear when use lambda yearsetertheyear theyear local scope lambda function python goes looking extended global builtin scopes it finds global scope the forloop uses theyear forloop ends theyear retains last value since lambda function executed forloop ended value python assigns theyear in contrast use parameter default value default value fixed time function lambda defined thus lambda gets different value theyear fixed default value now lambda called python goes looking value theyear time finds lambda local scope it binds default value theyear ps you could also forgo defining yearseter lambda theyeartheyear yearsettheyear listofyears range also works,i currently working gui tkinter application i problems creating couple dropdown menus used choose date the application i written creates desired menus labels however clicking buttons value last menu entry gets passed tkinter mutable intvar this portion code emphasizes problem year year user clicks upon however always tkinter import import tkfiledialog dialog import datetime import calendar window tk text textwindow textpack year intvar listofyears def yearsetervalue yearsetvalue menubar menuwindow yearmenu menumenubar theyear listofyears yearmenuaddcommandlabelstrtheyear commandlambda yearsetertheyear menubaraddcascadelabel year menuyearmenu windowconfigmenumenubar label labelwindow textvariableyear labelpack windowmainloop can somebody please explain happening thank time,2 get list years read file repeatedly open yearstxt r yearfile years yearstrip year yearfile go entry names open namestxt r namefile name namefile remove extra whitespace including newline character end name name namestrip add year name form list nameandyears joinname year year years print entry new line print n joinnameandyears and add blank line done name print,i files trying put together one lines mabey i want file loop adds line text onto files lines here code put together far namefile opennamestxt r yearfile openyearstxt r line namefile print linestripyearfilereadline here examples output looks like runs numbers lloyd tommy leon derek warren darrell jerome floyd leo i want output like lloyd lloyd lloyd lloyd lloyd lloyd tommy tommy tommy tommy tommy tommy ect,1 regex tested import def makemultiprefixmatcherprefixes regextext joinreescapep p prefixes print reprregextext return recompileregextextmatch pfxs x ya foobar foo ab zsplit names xenon yadda yeti food foob foobarre foo ab b zyx zebrasplit matcher makemultiprefixmatcherpfxs name names matchername print reprname match continue n mend print reprname n reprnamen output xyafoobarfooabz xenon enon yadda dda yeti match food foob b foobarre foo ab match b match zyx yx zebra match,i need find whether name starts list prefixes remove like name c l e b name name the works list prefixes length two i need functionality variablelength prefixes how done efficiently little code good performance a loop iterating prefix checking namestartswithprefix finally slice name according length prefix works lot code probably inefficient nonpythonic does anybody nice solution,1 you might try setting debuglevel urllib see comes import urllib hurllibhttphandlerdebuglevel opener urllibbuildopenerh,i test code part webapp uses urllib perform operation i would usually perform via browser log remote website move another page perform post filling form i created separate clean virtualenvs nositepackages different machines different versions python exact packages via pip requirements file code works two virtualenvs local development machine work either production vpss in failing cases i log successfully move correct page i submit form remote server replies telling error application server error page complete request webserver error i successfully log maneuver second page seem session cookie problem particular final post i perform operation particular machine exact headers data seem problem i requestingposting i trying code two separate vps rented different companies seem problem vps physical environment code works different python versions i imagine incompabilty problem i completely lost stage work i even turneditoffandturnitonagain i see problem could i think something final post coming vps remote server like i figure could i feel like something going hood urllib causing remote server dislike reply edit i installed exact python version vps working local copy work remotely must something originating vps how could effect http request is something lower level,1 you probably need class name well module name with could use getattrimportmodulename classname if want make specify class name might able find class ends bot module importmodulename clazz none attributename dirmodule attribute getattrmodule attributename attributenameendswith bot callableattribute clazz attribute break however explicit better implicit — the zen python so i stick first approach letting specify module class name,i trying write script takes two bots feeds engine play game as example usage python rungamepy smartbotpy dumbbotpy detected smartbot smartbotpy detected dumbbot dumbbotpy running game the problem i i idea detectget bot objects modules provided via command line if helps i mind enforcing conventions how i,1 this list comprehension loop list comprehensions provide concise way create lists fread tisalpha this creates list alpha characters file f you join together you link documentation help comprehend comprehensions it tricky search things know called hope helps,python challenge answer i found filepath ltext f openfilepath print join fread tisalpha fclose question why loop fread i understand rest code except one bit if i try remove i get error thanks,2 open yearstxt year years yrstrip yr year open namestxt names name names name namestrip year years printss name year,i files trying put together one lines mabey i want file loop adds line text onto files lines here code put together far namefile opennamestxt r yearfile openyearstxt r line namefile print linestripyearfilereadline here examples output looks like runs numbers lloyd tommy leon derek warren darrell jerome floyd leo i want output like lloyd lloyd lloyd lloyd lloyd lloyd tommy tommy tommy tommy tommy tommy ect,1 fread tisalpha list comprehension basically takes given iterable fread forms list taking elements read applying optional filter clause mapping function part left however mapping part trivial makes syntax look bit redundant element given adds element value output list but complex expressions possible example would duplicate valid characters,python challenge answer i found filepath ltext f openfilepath print join fread tisalpha fclose question why loop fread i understand rest code except one bit if i try remove i get error thanks,1 the original url nothing scrape it returned meaning body location header indicates redirect you need figure access url without redirected perhaps authenticating,i trying parse sitewritten asp crawler gets redirected main site but i like parse given url redirected one is way i tried adding redirectfalse settingspy file without success here output crawler coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid,1 expected behavior this hard answer since commands i expect might expect as actual tests first one tests internal double escaped n characters really work the n doubled backslash indeed work correctly causes echo emit newline character however double quotes emitted echo the second tests put unescaped newlines script still work like semicolon that works also finally last one tests whether call sudo process separate terminal ultimate goal there reason work also indeed in cases new terminal disappear soon press key please also confirm that work several reasons read bash default read whole line one character script supply executed reason shell within terminal exit even shell would exit user configure terminalapp close window shell exits even default setting other problems script supply osascript appear terminal window executed examples user see every this test twice i cannot figure exit supposed the ls command show user current directory sense current working directory new terminal window always user home directory throwaway available script bashcommand exits finally script work python crashes typeerror communicate takes byte string argument string also appreciated pythonic way spawning terminal mac you look pyobjc it necessarily pythonic least would eliminate layers indirection,i seen similar questions eg running command new mac os x terminal window i need confirm command expected behavior mac i if anyone run following python mac import subprocess os def runcombashcommand sp subprocesspopen osascript stdinsubprocesspipe stderrsubprocesspipe spcommunicate tell application terminalnactivatendo script command exitnend tell formatbashcommand runcom echo this testnnthis come two lines later press keyread throwaway runcom echo this testnnecho this come one line later press keyread throwaway runcom echo this testing whether i enter sudo pw separate terminalsudo lsnecho you see current directory press keyread throwaway firstly basically spawn new terminal execute command correct for reference version runcom function came answer much cleaner original as actual tests first one tests internal double escaped n characters really work the second tests put unescaped newlines script still work like semicolon finally last one tests whether call sudo process separate terminal ultimate goal in cases new terminal disappear soon press key please also confirm if one work correctiondiagnosis would appreciated also appreciated pythonic way spawning terminal mac executing sudo extended bash commands thanks,1 here json approach i together code read results back it saves node edge attributes case need import simplejson json import networkx nx g nxdigraph add nodes edges etc g def saveg fname jsondumpdictnodesn gnoden n gnodes edgesu v gedgeuv uv gedges openfname w indent def loadfname g nxdigraph jsonloadopenfname gaddnodesfromd nodes gaddedgesfromd edges return g,seems like method networkx export json graph format i see i imagine easy nxtodictofdicts would require bit manipulation anyone know simple elegant solution,2 just looking output dirreadline functions getcompleterdelims setcompleterdelims look like might useful in fact documentation readline module includes setcompleterdelims setcompleterdelimsstring none set readline word delimiters tabcompletion i think describes exactly want this python running something earlier perhaps functionality available,hello coders brave gnureadline users a months ago i started using python readline module shelllike application i written the application nothing files filesystems tailored solution proprietary management software yesterday i found specific text causes unexpected autocompletion behavior found way resolve documentation i desperately asking help i start example follow code snippet reproduces unwanted behavior providing values autocompletion aaa aaa aaa bbb bbb bbb ccc ccc ccc ddd ddd ddd unexpected behavior follows action followed resulting output pipe sign represents cursor type b input b press tab configuration bound autocompletion action input bbb press tab your text remain receive following hint bbb bbb bbb input bbb type press tab bbb bbb bbb input bbb note space character cursor code snippet shall explain so far good trying result similar output without underscore aaa aaa aaa start type c input c press tab input ccc press tab aaa aaa aaa bbb bbb bbb ccc ccc ccc ddd ddd ddd input ccc this first half problem all values displayed instead values beginning ccc type press tab aaa aaa aaa bbb bbb bbb ccc ccc ccc ddd ddd ddd input ccc this second half problem see space character cursor snippet shall explain space in fact pressing tab neither changed text displayed hint tab presses behave in practice happens step misunderstanding readline mistakes dash character wordseparator goes questionmark character try autocompleting ddd common word separators example space tab so since current line buffer ends word separator time new word right hence step values displayed upon pressing tab in step line looks like input ccc pressing tab effect dash wordseparator separates line two words ccc so word completed alas none possible values start effect now sadly right wrong for instance application equalssign actually word separator dash i suppose must matter configuration i found way configure characters separate words that i need help i man word code snippet i promised import readline values aaa aaa aaa bbb bbb bbb ccc ccc ccc ddd ddd ddd def completetext state matches v v values vstartswithtext lenmatches matches text add space current text match return formatmatches state else none state lenmatches return none return matchesstate readlinesetcompletercomplete line tab complete set showallifunmodified readlineparseandbindline rawinputinput boys girls please help i promise thankful even return favor thanks much advance amnon g,3 cpython classic prevalent implementation python one thread executing python bytecode time this means computebound programs use one core io operations computing happening inside c extensions numpy operate simultaneously other implementation python jython pypy may behave differently i less clear details the usual recommendation use many processes rather many threads,question because python use gil python capable running separate threads simultaneously info after reading i came away rather uncertain whether python capable taking advantage multicore processor as well done python feels really weird think would lack powerful ability so feeling uncertain i decided ask if i write program multi threaded capable executing simultaneously multiple cores,3 the answer yes but but cpython cannot using regular threads concurrency you either use something like multiprocessing celery mpipy split parallel work another process or use something like jython ironpython use alternative interpreter gil a softer solution use libraries run afoul gil heavy cpu tasks instance numpy heavy lifting retaining gil python threads proceed you also use ctypes library way if cpu bound work ignore gil issue entirely kind since python aquire gil waiting io,question because python use gil python capable running separate threads simultaneously info after reading i came away rather uncertain whether python capable taking advantage multicore processor as well done python feels really weird think would lack powerful ability so feeling uncertain i decided ask if i write program multi threaded capable executing simultaneously multiple cores,3 python threads cannot take advantage many cores this due internal implementation detail called gil global interpreter lock c implementation python cpython almost certainly use the workaround multiprocessing module httpwwwpythonorgdevpepspep developed purpose documentation httpdocspythonorglibrarymultiprocessinghtml or use parallel language,question because python use gil python capable running separate threads simultaneously info after reading i came away rather uncertain whether python capable taking advantage multicore processor as well done python feels really weird think would lack powerful ability so feeling uncertain i decided ask if i write program multi threaded capable executing simultaneously multiple cores,3 if trying reimplement find yes code going get hairy find pretty hairy in cases though trying replicate complete behavior find performing much simpler task eg find files end txt if really need find run find read output as say gold standard might well use i often write code reads paths stdin i find bunch filters mypythoncodepy,perl lovely little utility called findperl translate quite faithfully command line unix find utility perl script if find command like find usr xdev type name share name shell expansion share directory file do go external file systems usr directory could multiple directories it finds directories ending share usr now run findperl usr xdev type name share emit perl script you modify script use python oswalk certainly needed functionality recursive directory listing big differences take simple case find type f print find print files current directory a naã¯ve implementation using oswalk would path dirs files oswalkroot files file files print ospathjoinpathfile however produce different results typing find type f print shell i also testing various oswalk loops create pipe find commands arg root findcmd find type f root argsshlexsplitfindcmd psubprocesspopenargsstdoutsubprocesspipe outerrpcommunicate outoutrstrip remove terminating n line outsplitlines print line the difference oswalk counts links files find skips so correct implementation file type f print becomes path dirs files oswalkroot files file files pospathjoinpathfile ospathisfilep ospathislinkp printp since hundreds permutations find primaries different side effects becomes time consuming test every variant since find gold standard posix world count files tree way python important so equivalent findperl used python so far i using findperl manually translating perl code this hard perl file test operators different python file tests ospath times,2 image imageopenfile to get image size pixels widthheight imagesize check dimensions width height resize image imageresizewidthnewheightnew,i trying check image dimension saving i need change make sure fits limits right i read file save aws without problem output pic file requestpost picturefile conn myprojectsawsauthconnectionawskeyid awskey filedata requestfiles picture read contenttype imagepng connput bucketname requestpost picturefile myprojectssobjectfiledata xamzacl publicread contenttype contenttype i need put step middle makes sure file right size width dimensions my file coming form uses imagefield solutions i seen use is way something like img imageopenfiledata,2 return match string return followed character one times this mean character group inside special characters threaded simple characters thus matches dollar sign why use return exactly want,i stuck dump import print research return return treasury millionnnow group the regex prints return treasury i expected include million what i understand regex i asking take every thing end line i want use i want endline delimiter go end line point if i remove search string prints full string why endline delimiter matching dollar sign,2 one common patterns problem define api object must particular name for instance might call special variable bot smartbotpy class smartbotobject a smart bot bot smartbot dumbbotpy class dumbbotobject a dumb bot bot bot dumbbot rungamepy import sys source sysargv l execfilesource l bot lbot print detected typebotname source print running game,i trying write script takes two bots feeds engine play game as example usage python rungamepy smartbotpy dumbbotpy detected smartbot smartbotpy detected dumbbot dumbbotpy running game the problem i i idea detectget bot objects modules provided via command line if helps i mind enforcing conventions how i,1 you way find timezone user one way set preference page storing database looking render page another way browser include current time request adjust times one know user offset server time use timedelta methods adjust datetime object,i python cgi program prints datetime values the timestamps formatted server time way local time users how i format automatically users based time zone here one formatted string that string created using datetimedatetime object sunjay,1 first vector first elements dv dd python indexed second walk array store dict example write dc ind corresponds column names row dd dcrowind row,i array like numpy array dd foo bar noo tar boo how would one loop array selecting foo getting floats singleton then select bar getting floats singleton i could get vector first elements list using dv dd the foo bar elements unknown variables change how would i change element position foo bar noo tar boo,1 you put numpy tag question assume want numpy syntax answer mine use if fact wish use numpy likely want strings array otherwise also represent floats strings what looking numpy syntax access elements d array row exclude first column that syntax mrowindex selects st col row given rowindex wrt second scenario question selecting nonadjacent columns mrowindex selects st amp rd cols row given rowindex the small complication question want use string rowindex necessary remove strings create d numpy array floats replace numerical row indices create lookup table map strings numerical row indices import numpy np create lookup table remove strings python nested list allow represent data d numpy array dtypefloat keys foo bar noo tar boo values d index array comprised one float value unique string keys array lut dictzipkeys values add index data inserting values array first column data matrix a nphstackvals a a nparray look item key write small function perform lookups def selectrowkey return alutkey selectrow foo array selectrow noo array the second scenario question index column changes eg move index column q a nprolla axis a array original function changed slightly select nonadjacent columns def selectrowkey return alutkey selectrow foo array,i array like numpy array dd foo bar noo tar boo how would one loop array selecting foo getting floats singleton then select bar getting floats singleton i could get vector first elements list using dv dd the foo bar elements unknown variables change how would i change element position foo bar noo tar boo,3 you quiver little tricky get keyword arguments right import numpy np import matplotlibpyplot plt x nplinspace nppi npsinx pltfigure pltquiverx xx yy scaleunits xy angles xy scale pltshow,i line graph i want plot using arrows instead lines that line successive pairs points arrow going first point second point i know arrow function seems individual arrows before i work way try use whole plot nicer way,3 potte match potter txt harry potter awsome harry james potter pat wwzpotter refindallpattxt potter awsome harry potter,import txt harry potter awsome harry james potter pat wpotter refindallpattxt according understanding output words followed potter potter awsome harry james potter actual output harry potter awsome harry james potter pattern also matching harry followed potter,2 try absolute file system paths input output files the current working directory apache directory run server could anything second attempt eliminating obvious the pdftk program java program relying able generatereceive sigpwr signal trigger garbage collection perform actions problem apachemodwsgi daemon mode signals blocked within request handler threads ensure received main thread looking process shutdown trigger events when forking process run pdftk unfortunately inheriting blocked sigmask request handler thread the consequence impedes operation java garbage collection process causes pdftk fail strange ways the solution use celery front end submit job celery queue celeryd fork execute pdftk because done process created distinct apache issue for gory details google modwsgi pdftk particular google groups httpgroupsgooglecomgroupmodwsgisearchgroupmodwsgiampqpdftkampqtgsearchthisgroup,i need launch pdftk process serving web request django wait finish my current pdftk code looks like proc subprocesspopenusrbinpdftk tmpinfilepdf tmpinfilepdf cat output tmpoutfilepdf proccommunicate this works fine long i executing dev server running user wwwdata but soon i switch modwsgi changing nothing else code hangs proccommunicate outfilepdf left open file handle zero length i tried several variants subprocess invocation well plain old ossystem setting stdinstdoutstderr pipe various file handles changes nothing using shelltrue prevents proccommunicate hanging pdftk fails create output file devserver modwsgi this discussion seems indicate might deeper voodoo going os signals pdftk i understand are workarounds get subprocess call like work properly wsgi i avoiding using pypdf combine pdf files i combine large enough numbers files several hundred runs memory pypdf needs keep every source pdf file open memory combining i recent ubuntu pythons,3 according understanding output words followed potter it the thing every word followed potter every word definition followed either whitespace end string,import txt harry potter awsome harry james potter pat wpotter refindallpattxt according understanding output words followed potter potter awsome harry james potter actual output harry potter awsome harry james potter pattern also matching harry followed potter,2 you two commas without anything remove one,i using python mysqldb i table displayed i get error message time i try insert table insert into reviews entrycreatedtime userid branchid titlevalues branches would lead use ciyrt oogletivers create table reviews id int unsigned null primary key autoincrement entry text null createdtime timestamp null userid tinyint unsigned null references usersid branchid tinyint unsigned null references branches id title varchar fulltexttitle entry mysqlexceptionsprogrammingerror you error sql syntax check manual corresponds mysql server version right syntax use near oogletivers line,1 yeah uh return unichrrandomchoicex x randomrandint xff,i trying generate random unicode characters two starting numberletter combination i tried following i getting error def randunicode b l joinrandomchoice abcdef x xrange return unicodeu u randomchoicebl utf the error i getting syntaxerror unicode error unicodeescape codec decode bytes position end string escape sequence i use python,3 you looking collectionsdefaultdict collections import defaultdict itertools import chain merged defaultdictint key value chainlist list mergedkey value if want list tuple list mergeditems if want without chain collections import defaultdict merged defaultdictint mergedupdatelist key value list mergedkey value edit as beni points comment collections import counter merged counterdictlist mergedupdatedictlist which requires convert lists dict otherwise perfect,i looking best way refactor python code i think pythonic way lines code figure i searched stackoverflow find similar problems solutions many thanks list python ruby java c list python ruby java php javascript i want make unsorted list like list python ruby java php javasript c commonkeys listsetdictlistkeys amp setdictlistkeys commonkeys commonlst x dictlistx dictlistx x commonkeys restlist x dictlistx x dictlistkeys x commonkeys restlist x dictlistx x dictlistkeys x commonkeys list commonlst restlist restlist else list list list,2 a noncapturing version regular parentheses matches whatever regular expression inside parentheses substring matched group cannot retrieved performing match referenced later pattern httpdocspythonorglibraryrehtml means match save groups remove try,i following question since question changed finding regex regioncitycategory the answer works outputs city category i also want output help modify little achieve it seems i finally able i want regex also applies earlier questions i asked can i use python regex letters dashes underscores how represent geographical locations my plan implement functionality multitenancy software serve large cities like sao paulo delhi time code i must make general locations expression ie plus problem mean say eg search new york region city one piece info output google maps defines new york region corresponds administrative area name new york status code request geocode placemark id p address new york ny usa addressdetails accuracy country administrativearea administrativeareaname ny subadministrativearea locality localityname new york subadministrativeareaname new york countryname usa countrynamecode us extendeddata latlonbox north south east west point coordinates id p address manhattan new york ny usa addressdetails accuracy country administrativearea administrativeareaname ny subadministrativearea locality dependentlocality dependentlocalityname manhattan localityname new york subadministrativeareaname new york countryname usa countrynamecode us extendeddata latlonbox north south east west point coordinates however i think code file since i make one file per region structure like since total number regions states whole world much larger total number countries total number cities world large number and seems file every country included project easy good way organize many thanks update the regex i found useful application webappwsgiapplication handlerdebugtrue,2 you set variables rain snow niceday use variables instead numbers rain snow mrain snow,numpy manipulate matrix and matrix element got via numerical indexes now say i square matrix m actually malcov transition matrix element speaks probability one state switching another and row column represent rain snow niceday order ordinarily i want get rainsnow element i would write m but i think readable enough so i wonder i get element m rain snow i defined dictlike matrix beforeif allowed numpy matrix manipulation rule,2 put quotes searchfor string searchfor big car you also define strings double quotes escape double quote character searchfor big car see googles python class information string literals python just clear urlencoded space character interpreted plain space google retrieves the urlencoded query quotes qbigcar double quote urlliburlencode encode string correctly submitted url just use syntax would use google normally searchfor big car hummer,i trying define google search ajax interface using good function described a martelli google search python app query urlliburlencode q searchfor if i define variable searchfor big car query generated bigcar however i want generate query big car two words ocurring together q that i would like define explicit phrase query google i would enter phrase within double quotes q how i define query i wxclude certain term in google enter sign,2 you use webappresponsesetcookie method import datetime selfresponsesetcookie name value expiresdatetimedatetimenow path domain examplecom formatting dates cookies something like print datetimedatetimenow datetimetimedeltaweeksstrftime b y hms gmt,i need implement following user input user id pass we validate another server if correct cookies details saved one month each time user uses site look cookies if found go step how i set cookies month will following work selfresponseheadersaddheader setcookie credentialss expiresfri dec gmt credentialsencode how calculate one month required format,3 i think two options also make overall solution somewhat flexible write web service write python parts restful web service should relatively straightforward use something like zeromq create message queue there zmq libraries php python also make option difficult implement as may noticed options somewhat clunky nature you mention exactly mean api eg library web service depending might easiest rewrite php bad language end used properly,i rather large api written php i worked years some functionality needs upgraded extent i really rewrite classes since i need scrap old code anyway i thinking perhaps i could replace old functionality python code i came across pip searching answers seems like exellent solution since i actually create python class instances php call methods etc seems abandoned alpha stages reasons unknown i suppose simplest solution would cli one meaning i could run python instance php collect results i particularly like solution though considering amount python code i write handle input php respond accordingly plus reusable i know normal problem google certainly seem think would best way complementing php code library python code,1 your user probably referring django user facebook user make sure synchronize two accounts correctly using custom authentication backend it possible accounts get sync ie user switches browsers keep mind facebook python sdk stop working october st unless update oauth unlikely i updated djangofacebookgraph work new authentication flow,i getting conflicting results facebook javascript sdk python requesthandler variables the javascript sdk says user logged correct template variable comes base request handler says user logged displays name user is enough info tell wrong i paste code i think relevant a link login page error the example i used called runwithfriends demo app facebook everything app worked except using logic app website without requiring user iframe app plus i seem get realtime api working i save userid refresh user data i code i sure relevant request handler relevant code basically exactly one demo app def renderself name data loggingdebug render render template data loggingdebug data data datau jsconf jsondumps u appid facebookconffacebookappid u canvasname facebookconffacebookcanvasname u useridonserver selfuserid selfuser else none datau loggedinuser selfuser variable problem datau message selfgetmessage datau csrftoken selfcsrftoken datau canvasname facebookconffacebookcanvasname selfresponseoutwritetemplaterender ospathjoin ospathdirnamefile templates name html data and even strange i also get application state javascript sdk says user logged template variable loggedinuser says otherwise why variables conflicting update here screenshots strange login flow i go page name facebook appears then i go next page also looks alright name but i log i gets impossible state name logged how i resolve strange conflict js backend update since i problem one apps i take works app integrate this page seems work app httpcyberfazeappspotcomfile,1 okay digging around i found problem requestfiles getting nothing hence nonetype needed add enctypemultipartformdata form order request work,how i upload images imagefield the following giving nonetype object attribute chunks i believe i wrong someone show correct way this i far saving uploaded image def addemployeerequest requestmethod post forminput addemployeerequestpost requestfiles forminputisvalid cd forminputcleaneddata newemp employees firstname cd firstname newempsave photofile cd photofile newempphotosave filename photofile return httpresponseredirect thanks formspy modelspy class addemployeeformsform photofile formsimagefieldrequiredfalse class employeesmodelsmodel photo modelsimagefielduploadto employeephotos blanktrue nulltrue,1 this easy actually delve objects i first assumed since axesd based axes could use setyticklabels method apparently work looking code see axis set wyaxis axisdyaxis turn eventually based axisaxis setticklabels method worked axwyaxissetticklabels what mean change axis interval axis named a,i managed create graph using matplotlib i would like remove axis named b change axis interval axis named a i trying quite sometime nowany suggestions code i written mpltoolkitsmplotd import axesd import numpy np import matplotlib import matplotlibpyplot plt fattributesopencontinuousdatar x spam count skew fig pltfigure ax axesdfig total count attributesfattributesreadline attributesattributesreplacen attributesattributessplit classificationintattributesreplacen floatattributes skewappendfloatattributes xappendcount yappendclassification classification axscatterx skew c g marker else axscatterx skew c r marker x skew count axsetxlabel a axsetylabel b axsetzlabel c pltshow please ignore irrelevant details,2 codeproject c check windows genuine vc include slpublich pragma commentlibslwgalib bool iswindowsgenuine guid uid rpcwstr rpcrpcwstrtcddedecff uuidfromstringrpcampuid slgenuinestate state slisgenuinelocalampuidampstatenull return state slgenuinestateslgenstateisgenuine,is possible check whether windows installation genuine programmatically lets say i want check windows c c java python,1 from here vbscript strcomputer set objwmiservice getobjectwinmgmts amp impersonationlevelimpersonate amp strcomputer amp rootcimv set colwpa objwmiserviceexecquery select winwindowsproductactivation for each objwpa colwpa wscriptecho activation required amp objwpaactivationrequired wscriptecho description amp objwpadescription wscriptecho product id amp objwpaproductid wscriptecho remaining evaluation period amp objwparemainingevaluationperiod wscriptecho remaining grace period amp objwparemaininggraceperiod wscriptecho server name amp objwpaservername next,is possible check whether windows installation genuine programmatically lets say i want check windows c c java python,1 i imagine come like using internationalization settings somewhere far east asia china perhaps using python command prompt i sure whether problem python command prompt combination two either way combination two work particularly well nonlatin internationalization settings i recommend using idle instead since appears support unicode characters properly here happens i viewed last string idle the text mean anything might idle z u udueauctestxlsuduuuudfuecfuufuuedufducufuufucuduuefuffcueubbaubueecufuuucueuuefuuedunuuufubcuecuefduuuffcubfuuedudfuecfuufuuuuffcuuucdubududuueduueueauuu print z 名为“testxlsâ€çš„æ–‡æ¡£å·²ç»æ‰“å¼€ã€‚ä¸èƒ½åŒæ—¶æ‰“å¼€åŒåæ–‡ä»¶ï¼Œæ— è®ºå®ƒä»¬æ˜¯å¦åœ¨åŒä¸€æ–‡ä»¶å¤¹ä¸­ã€‚ è¦æ‰“å¼€ç¬¬äºŒä»½æ–‡æ¡£ï¼Œè¯·å ³é—­å·²ç»æ‰“å¼€çš„æ–‡æ¡£ï¼Œæˆ–è€ é‡æ–°å‘½åå ¶ä¸­çš„ä¸€ä¸ªæ–‡æ¡£ã€‚ however even using idle chances get exception text still appear if happens need get data last exception raised print relevant string within to get last exception raised interpreter use syslastvalue here example different exception message import sys open nonexistenttxt f pass traceback recent call last file line open nonexistenttxt f pass ioerror errno no file directory nonexistenttxt syslastvalue ioerror no file directory printsyslastvalue no file directory,under python pywinwinpy installed i use wincom module process excel windows follows import wincomclient xlsapp wincomclientdispatch excelapplication xlsappworkbooksopenr dtestxls i get error traceback recent call last file stdin line module file comobject unknown line open pywintypescomerror xbxaxcxfaxdxexcdxexaxa u microsoft office excel u udueauctestxlsuduuu udfuecfuufuuedufducufuufucu duuefuffcueubbaubueecufuuucueu uefuuedunuuufubcuecuefduuuffc ubfuuedudfuecfuufuuuuffcuuu cdubududuueduueueauuu none none while imformation readable i konw going wrong after searching internet i find something helpful httpwwwpythonforumorgpythonforumviewtopicphpfampt pywintypescomerror exception occurred u microsoft office excel u test xls could found check spelling file name verify file location correctnnif trying open file list recently used files file menu make sure file renamed moved deleted u cprogram filesmicrosoft officeofficexlmainchm none i guess problem i create excel file dtestxls first everything turns ok xlsappworkbooksopenr dtestxls comobject open if i got readable error tip i would solve problem immediately without difficult i wonder error i get wincomclient like is anything i make information readable i appreciate help,2 the moment say pstart separate process forked main process all variable values copied so main process one copy p forked process separate copy p the worker modifies forked process copy pvalue main process pvalue still none there many ways share objects processes in case perhaps easiest way use mpvalue import multiprocessing mp class workermpprocess def initself print init mpprocessinitself selfnum mpvalue def runself print running selfnumvalue p worker pstart pjoin print pnumvalue note mpvalue default value it set none,in short say i following import multiprocessing class workermultiprocessingprocess def initself multiprocessingprocessinitself print init selfvalue none def runself print running selfvalue p worker pstart pjoin print pvalue i expect output init running instead init running none can someone explain case what i understanding i go correctly thanks,3 did define folder unicode string this implications oswalk matches subdirectories better type string returns abc oswalk print b break dlls doc include lib libs tcl tools abc oswalku print b break u dlls u doc u include u lib u libs u tcl u tools,so i trying fix idtags mp files it works except files kind accent oswalk seems strip for example i file co så‚ychaä‡mp code root dirs files oswalkfolder print files shows co slychacmp later resulting no file directory error how fixed,3 no possible since request object globally available thus available form unless explicitly passed the initial argument exists exactly problem trying solve you probably use form yourform initial yourfield requestmeta remoteaddr view edit if like pass request explicitly use something like pass requestrequest instantiates form class yourformformsform def initself args kwargs selfrequest kwargspop request superyourform selfinitargs kwargs use selfrequest clean etc,in django possible set default value form field tied request variable eg requestmeta remoteaddr this example like use headers available request variable without passing explicitly form thanks,1 take look implementation notice uses supplied ip port set new connection reactorconnecttcp subclass reverseproxyresource extend able connect randomly selected address,i use starting reactor fetching web pages soall pages i fetch use proxy reactor starts butwhat i want rotate proxies how i using eg randomchoiceproxylist thanks site serversiteproxyreverseproxyresource reactorlistentcp site reactorrun,1 httpwwwcotodigitalcomarlaspcatampid redirects httpwwwcotodigitalcomardefaultasp http response said this happens asp code checking condition wrong page cookies useragent referrer check mentioned conditions update just checked browser browser also redirected main page click skip ads after works ok this means sets cookies without redirects main page see also scrapy manage cookiessessions,i trying parse sitewritten asp crawler gets redirected main site but i like parse given url redirected one is way i tried adding redirectfalse settingspy file without success here output crawler coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid coto debug redirecting get httpwwwcotodigitalcomardefaultasp get httpwwwcotodigitalcomarlaspcatampid,1 as documentation output mergeab example indicates result merge iterator iterators consumed reset rewind even could code of course several independent iterators given collection least collection supports the first two merge calls return generators third call consumes generators hence b exhausted afterwards actually lista consumes first snippet mergea b see items b idea it mean pass eg list changed but consuming iterator means mutating,first i created result amp b using merge merge aampb i found list empty amerge bmerge lista mergeab generator object merge xc lista the final command lista empty mergeab changed,2 elemtextelemgetparentxpath valuesvaluetext elem treegetiteratortag name elemtextstartswith v yields v v v alternative alternative alternative alternative elem name element so get associated values first find parent variable search values child value subchild elements an alternative removes getparent call uses slightly complicated xpath elemtextelemxpath followingsiblingvaluesvaluetext elem treegetiteratortag name elemtextstartswith v followingsibling tells xpath generate siblings name followingsiblingvalues tells xpath generate siblings name values elements,i wonder possible make conditional statments connected treefindall statement lxml library i following xml structure file sss version datedate timetime originopstorigin useruser survey nametestname version version record identa variable ident typequantity namenovname labelanother questionlabel position start finish values range values variable variable ident typequantity namevname labelanother totally another questionlabel position start finish values range values variable variable ident typequantity namevname labeland questionlabel position start finish values range values variable variable ident typesingle namevname labelquestion alternativeslabel position start finish values range value codealternative value value codealternative value value codealternative value value codealternative value values variable record survey sss what i want get surveyrecordvariablename text surveyrecordvariablevaluesvalue text name starts v so far first part lxml import etree et tree etparse schemexml elemtext elem treegetiteratortag name elemtextstartswith v but i get surveyrecordvariablevaluesvalue text same elementand use surveyrecordvariablename text like filter thanks lot,1 it possible expand arrays using resize method slow operation large arrays avoid possible for example import scipy sci n time scizerosn double printtime timeresizen printtime instead figure large array need beginning allocate shape time in general faster overallocate resize,is way dynamically expand scipy array scipy import sci time scizerosn double can increase size time array,3 this https enabled locally machine could enable could alternatively run without ssl localhost to would edit function look something like def gethome return http requesthost,i testing heroku ability write facebook app python i problem running basic tutorial it seemed like question worth asking stackoverflow case answer helps people run exact problem i followed instructions heroku facebook development page httpdevcenterherokucomarticlesfacebook deploying heroku worked fine however running app locally when i follow instructions bring httplocalhost i get facebook login screen but i click log in screen i get ssl connection error unable make secure connection server this may problem server may requiring client authentication certificate error neterrsslprotocolerror ssl protocol error console output web httpslocalhost web httpswwwfacebookcomdialogoauthclientidampredirecturihttpslocalhostampscopeuserlikesuserphotosuserphotovideotags web sep get http web sep code message bad request syntax xxxxuxxxqxxnxeampxfxfxxdxbxfxaxfxbxnxccxblxedxxdxcxfxacxahxxxxffxxxxxxxxxxexdxfxxxxxaxxxxxxxxxxfexffx web sep uqnampõ¶nì³lchedfa when i try safari address bar shows following long url httpslocalhostcodeaqbpwpkbrdlbtkerfcusznhexigapkafmxbngyijqzwsgveivylixsdltnhpkxpddxhjaxoayedcpcaflcxckqzoarhgjbpxwwuclpgrprmddeixcoyiczoqgftbpvdzohfagmueshrivybqwjbjzrozfebpiclpoisnnici safari compains establish secure connection this running os x,3 if using pydev detect way import sys pydevd sysmodules print debugger else print commandline,is simple way detect within python code code executed python debugger i small python application uses java code thanks jpype when i debugging python part i like embedded jvm given debug options,1 future import printfunction import regexp recompiler w def main words open emachtxt r fp line fp item category regexpfindallline wordssetdefaultcategory setdefaultitem wordscategoryitem open resulttxt w fp category words sortedwordsitems printcategory filefp word count wordsitems printword count sep filefp printfilefp return name main raise systemexitmain you welcome if want also count weird ed tune regexp match character except whitespace regexp recompiler,i wanna count words text files contain data follows rok roknn new newsv releases releasesnn sy week weekep last lastjo compared comparevv edem year yeardt releases releasesnn the expressions like nn sv ep considered category i wanna extract words category count many words whole text i wanna write result new text file like nn releases rok sy new ep week jo last please help garage code work import os sys import wordset line open emachtxt r line word refindallr w line print word word wordset wordsetword else wordsetword f open resulttxt w word wordset print f word wordsetword fclose,1 this code produce output want maybe best way seems work expected data offspr male female data offspr male female line enumeratedata datai linesplit item data datacountitem print data item print data item datacountitem print data item print data item update with nested list include list datas offspr male female offspr male female data datas line enumeratedata datai linesplit data datas item data datacountitem print data item print data item datacountitem print data item print data item,i really know awk would appropriate tool task maybe something python would better anyway i thought asking first feasibility task here go datas offspr male female offspr male female so basicaly i need print first field matching bold first record matching second record output file offspr male offspr female offspr male any hint i could accomplish thanx,1 selftagnames string selfdoanything you invoke function using parens argument list len function lens invoking function argument simply using function name gets function leave parenthesized argument list longer invoking function,i tuple like following selftagnames string selfdoanything it execute specific function string matches another however i initialize selftagnames seems execute function already how i fix issue without executing function startup,1 selftagnames string selfdoanything the function call if want defer call later include function reference without parens like,i tuple like following selftagnames string selfdoanything it execute specific function string matches another however i initialize selftagnames seems execute function already how i fix issue without executing function startup,2 you remove parenthesis selftagnames string selfdoanything clearly selfdoanything calls method immediately instead selfdoanything returns python called bound method ie callable object pass parameters result calling method specific instance,i tuple like following selftagnames string selfdoanything it execute specific function string matches another however i initialize selftagnames seems execute function already how i fix issue without executing function startup,1 xpath let access ancestor ancestorspectrum return spectrum element contained within if use lxml use full xpath syntax find elements want lxml import etree tree etreexml filemzml ns httppsihupoorgmsmzml filesource treefindall ns selectedion spectrum filesourcexpath ancestorspectrum i think tested updated code actually works lxml import etree tree etreeparse fooxml el treefindallselectedion top elxpathancestorspectrum print top,i looking solution problem related xml python though spectrum root element let suppose example spectrum index idcontroller scan defaultarraylength cvparam cvrefms accessionms namems level value cvparam cvrefms accessionms namemsn spectrum value cvparam cvrefms accessionms namecentroid mass spectrum value precursorlist count precursor spectrumrefcontroller scan isolationwindow cvparam cvrefms accessionms namemz value cvparam cvrefms accessionms nameisolation width value isolationwindow selectedionlist count selectedion cvparam cvrefms accessionms namemz value selectedion selectedionlist activation cvparam cvrefms accessionms namecollisioninduced dissociation value cvparam cvrefms accessionms namecollision energy value activation precursor precursorlist binarydataarraylist count binarydataarray encodedlength cvparam cvrefms accessionms namebit float value cvparam cvrefms accessionms nameno compression value cvparam cvrefms accessionms namemz array value unitcvrefms unitaccessionms unitnamemz binaryaaaayhhsbeaaaadgyptqaaaaectgaaaaaanjbkaaaaaahljbinary binarydataarray binarydataarray encodedlength cvparam cvrefms accessionms namebit float value cvparam cvrefms accessionms nameno compression value cvparam cvrefms accessionms nameintensity array value binaryzfzuqwmvofhobrfuyqgxjuozkzdckqwkhuspqyzcsvnquhbinary binarydataarray binarydataarraylist spectrum what i trying achieve find selectedion element tree backtrack parent element spectrum if selectedion element found selectedion information mass spectra info index idcontroller scan length general info ms level msn spectrum centriod mass spectrum and cvparam name value binary mz array aaaayhhsbeaaaadgyptqaaaaectgaaaa intensity array zfzuqwmvofhobrfuyqgxjuozkzdckqc what i tried far import xmletreeelementtree et treeetparse filemzml nshttppsihupoorgmsmzml filesourcetreefindall ns selectedion will get selectedion element tree now i backtrace spectrum elementsubelement parse relevant information how i success,1 the main issue actually processing profile form look code written point anything take values entered user profile save database also adminstackedinline built purpose trying use that manages onetomany relationships onetoone relationships if must functionality admin follow exactly setup outlining probably best shot add custom view adminsite forms adding editing users alternatively people edit two forms create user anyway read adding views adminsite,i extended standard django user model userprofile created onetoone relationship userprofile user like class userprofilemodelsmodel user modelsonetoonefieldadminmodelsuser modelstextfield about author blanktrue picture modelsimagefield picture px x px blanktrue uploadto uploadsprofilepics default noonepng usersite modelsurlfieldblanktrue verifyexistsfalse class meta verbosename profiel verbosenameplural profielen to get corresponding admin form included user admin i created inline admin form added user admin like inline admin user profile class userprofileinlineadminstackedinline model userprofile fkname user maxnum extra include extra form class myuseradminadminmodeladmin inlines userprofileinline reregister user form adminsiteunregisteradminmodelsuser adminsiteregisteradminmodelsuser myuseradmin than lastly save instance userprofile i function connected postsave it looks like def onuserwassavedsenderinstancecreatedusingargskwargs typeinstance adminmodelsuser created profile userprofileobjectsgetorcreateuser instance profilesave else profile userprofileobjectsgetorcreateuser instance profilesave now two things go wrong when saving user anything user profile field user saved instance userprofile instance saved fields empty when entering something new fields save though nothing goes wrong a second instance userprofile form becomes available maxnum ignored after benjaoming input i changed postsave callback try profile userprofileobjectsgetuser instance profilesave except profile userprofileobjectsgetorcreateuser instance profilesave however solve either problems i already,1 the problem error never raised httpdocspythonorgtutorialerrorshtml you write raise eexceptionx somewhere x value,first file class eexception exception def initselfx selfxx def raiser selfx selfxx x so sue raise eexception new yorker else try number intx pass except valueerror raise valueerror second file import ea ea import def reporter fx try print fx return problem except valueerror return value except eexception return e else return generic question does function raiser static order used second file the problem eexception never caught solution,1 use numpyclip import numpy np npclipdata outdata datau dataastype uint note also brighten images without numpy way import imageenhance enhancerimageenhancebrightnessimg outimgenhancerenhance outimgsave outpng,for image processing class i point operations monochrome images pixels uint numpy uint wrap for example i need pixels saturate max truncate min instead wrapping my solution uses int pixels point math converts uint save image is best way or faster way usrbinpython import sys import numpy np import image def touint data maximum pixel latch npzeroslike data latch minimum pixel zeros npzeroslike data unrolled illustrate steps npmaximum zeros data npminimum latch cast uint return npasarray dtypeuint infilenamesysargv img imageopeninfilename data npasarray img dtypeint data datau touint data outimg imagefromarray datau l outimgsave outpng input image output image,3 i know work trying tweets dataset recently released from description as part trec microblog track twitter provided identifiers approximately million tweets sampled january rd february th the corpus designed reusable representative sample twittersphere ie important spam tweets included,i building project python needs scrape huge huge amounts twitter data something like million users tweets need scraped previously i used tweepy twython hit limit twitter fast how sentiment analysis companies etc get data how get tweets do buy somewhere build something iterates different proxies something how companies like infochimps example trst rank get data httpwwwinfochimpscomdatasetstwittercensustrstrank,3 the thing comes mind called something else wxpy print value wxfile verify rename,i running python wxpython bit windows python wx bit versions i trying import module import wx returns error traceback recent call last file cusersadamdesktoptest line module import wx file cusersadamdesktoptestpy line module class myframewxframe attributeerror module object attribute frame from research i think i set enviroment variables correctly everywhere i look one actually says i need add variables thanks lot,2 geventspawn creates greenlets processes even greenlets run single os thread so multiprocessingjoinablequeue appropriate gevent based cooperative multitasking ie call blocking function switches gevent event loop greenlets run for example conn uses patched gevent socket methods allow greenlets run wait reply site and without pooljoin gives control greenlet runs event loop connections made to limit concurrency making requests several sites could use geventpoolpool usrbinenv python geventpool import pool gevent import monkey monkeypatchsocket import httplib used multiple greenlets import logging info logginggetloggerinfo def processsite make head request site conn httplibhttpconnectionsite try connrequesthead res conngetresponse except ioerror e infoerror reason site e else infos site resstatus resreason finally connclose def main loggingbasicconfiglevellogginginfo formatasctimes msgs numworkerthreads pool poolnumworkerthreads sites googlecom bingcom duckduckgocom stackoverflowcom site sites poolapplyasyncprocess argssite pooljoin namemain main,anyone know wrong code it simply loads forever no output sites list dozen strings numworkerthreads def mwregisterworker true try print qget finally pass q multiprocessingjoinablequeue rangenumworkerthreads geventspawnmwregisterworker site sites qputsite qjoin block tasks done,3 this happened well turned sqlite boolean value boolean value false so django work wiht ones set false i saw discrepancy sqliteman simple update fixed problem i think happened schema upgrades migration dev environment worried,this frustrating better part hour i following model sold modelsbooleanfielddefaultfalse and following view code properties propertyobjectsfiltersoldfalseorderby createdon and following values sqlite database sqlite select sold clientsproperty and following template code does work hides sold items propertysold anyone know query set filter working i wrong i tried sold sold soldfalse soldfalse soldfalse,3 dom parsers always need read entire xml file you want sax parser,as probably know pythons xmldom readstring throws exception anything wrong xml code i currently writing simple xmpp chat server probably also know one first client request message close streamstream tag get reply is way use pythons xmldom without parsing xmlcode i write xml parser,1 i think streaming results likely help openpathtostoragefile w f row cursor fwriterow yourfield don hold everything memory,there mongo collection million items i need get representation held variable put file disk anything point single attribute documents my query something like cursor dbcollectionfindconditionalfield subfield true fieldiwant true my first silly attempt pickle cursor i quickly realized work like in case fieldiwant contains integer and example something i tried i practically locked server several minutes ints fieldiwant cursor get list integers this hogged cpu resources server far long is remotely simple way retrieve results list tuple set pickle file something totally hog cpu ideally i could dump results read back later but i like kind possible dumping,1 have seen shlex standard library check example,before i sit start hacking i thought i come see tips even something like done i want recreate basic shell like syntax within python program in words people run file python greeted little prompt for simple things using option parser say optparseargsinputsplit works fine i would like escape special characters like spaces character also treat quoted strings single argument like unix shell does exist anything might already help thanks suggestions chase,2 start shlex module pydoc shlex help module shlex name shlex a lexical analyzer class simple shelllike syntaxes you use like import shlex shlexsplit this test this test this splits things logical tokens anything like variable expansion forth that still actually running commands,before i sit start hacking i thought i come see tips even something like done i want recreate basic shell like syntax within python program in words people run file python greeted little prompt for simple things using option parser say optparseargsinputsplit works fine i would like escape special characters like spaces character also treat quoted strings single argument like unix shell does exist anything might already help thanks suggestions chase,3 here import string module python x import sysimp mycode mymodule impnewmodule mymodule exec mycode mymoduledict in python exec function work import sysimp mycode mymodule impnewmodule mymodule execmycode mymoduledict now access module attributes functions classes etc printmymodulea to ignore next attempt import add module sys sysmodules mymodule mymodule,i code form string would like make module without writing disk when i try using imp stringio object i get imploadsource mymodule stringio print hello world traceback recent call last file stdin line module typeerror loadsource argument must file instance imploadmodule mymodule stringio print hello world traceback recent call last file stdin line module valueerror loadmodule arg file none how i create module without actual file alternatively i wrap stringio file without writing disk update note this issue also problem python the code i trying load partially trusted i gone ast determined import anything anything i like i trust enough run i local variables running around could get modified i trust code stay way code i trying import i created empty module contains following def loadcode delete local variables globals code code del locals code run code execglobals code delete global variables added del globals load del globals code copy k use k locals globals k locals k del locals k copy rest variables k localskeys globalsk localsk then import mymodule call mymoduleloadcode this works i ensured code i loading use globals also global keyword parser directive refer anything outside exec this really way much work import module without writing disk ever want i believe best way,3 try foreignkeys option publishuser relationshipuser foreignkeyspublishinguserid primaryjoinpublishinguserid userid backrefbackref pages orderbyid edituser relationshipuser foreignkeyslastedituserid primaryjoinlastedituserid userid,i’ve looked sqlalchemy tutorial similar questions i seem struggling get join work the scenario i pages table represented page model pages created user edited user necessarily one my page model looks like abridged class pagebase tablename pages id columninteger primarykey true slug columntext title columntext directlink columntext body columntext categoryid columninteger foreignkey categoriesid publishedon columndatetime publishinguserid columninteger foreignkey usersid lastediton columndatetime lastedituserid columninteger foreignkey usersid define relationships publishuser relationship user backref backref pages orderby id primaryjoin pagepublishinguserid userid edituser relationship user primaryjoin pagelastedituserid userid category relationship category backref backref pages orderby id my users stored users table represented user model as i said i’ve sqlalchemy docs looking i’ve tried make look similar example possible avail any help would greatly appreciated,1 to serve image blobstore use getservingurl blobproperty look old code used serve blobproperties image class back blobstore class imagedbmodel name dbstringproperty desc dbstringproperty owner dbuserproperty secret dbstringproperty full dbblobproperty fullext dbstringproperty small dbblobproperty smallext dbstringproperty thumb dbblobproperty thumbext dbstringproperty published dbbooleanproperty added dbdatetimepropertyautonowaddtrue modified dbdatetimepropertyautonowtrue def thumbnameself return ss selfkey selfthumbext def smallnameself return ssmalls selfkey selfsmallext def fullnameself return sfulls selfkey selffullext class uploadimagewebapprequesthandler def postself key im dbgetdbkeykey im selferror return selfrequestpost id imsecret selferror return filedata selfrequestpost file fileread selfrequestpost size x imthumb filedata small elif selfrequestpost size x imsmall filedata full imsmall imthumb impublished true imsave logginginfos updated imkey selfresponseoutwriteok mimetypes jpeg imagejpeg jpg imagejpeg tiff imagetiff tif imagetiff gif imagegif png imagepng class serveimagewebapprequesthandler def getself key sz ext im dbgetdbkeykey im selferror return sz imthumb elif sz small imsmall elif sz full imfull else raise exception wrong sz r sz imfull else selfresponseheadersaddheaderexpires thu dec gmt selfresponseheaderscontenttype mimetypesext selfresponseoutwrited,i trying display image i saved datastore displayimage handler i see broken image link do know thanks class homepagedbmodel thumbnail dbblobproperty firmname dbstringproperty class imageuploadwebapprequesthandler def getself selfresponseoutwrite form actionimagesave enctypemultipartformdata methodpost divlabelfirm namelabel input typetext namefirmname sizediv divinput typefile nameimg div divinput typesubmit valueupload imagediv form class imagesavewebapprequesthandler def postself homepage homepage thumbnail selfrequestgetimg firmname selfrequestgetfirmname homepagethumbnail dbblobthumbnail homepagefirmname firmname homepageput selfredirectimageupload class imageresizewebapprequesthandler def postself q homepageimageall qfilterfirmname mta qtable qget qtable qtablethumbnail dbblobimagesresizeselfrequestgetimg dbputqtable else selfresponseoutwritefirm found selfredirectimageupload class displayimagewebapprequesthandler def getself query homepageall queryfilterfirmname mta result queryget selfresponseoutwritefirm name resultfirmname selfresponseoutwriteimg srcimgimgidsimg resultkey,1 in case still interested exhaustive search question you choose possibilities choose first set another choose second set point third set fixed in total gives clearly option,for purpose conducting psychological experiment i divide set pictures described features real numbers subsets equal number elements subset way subsets approximately balanced respect features terms mean standard deviation can anybody suggest algorithm automate are packagesmodules python r i could use where i start,1 use geventqueuejoinablequeue instead green threads gevent internally uses neither threads process coroutine w userlevel scheduling,anyone know wrong code it simply loads forever no output sites list dozen strings numworkerthreads def mwregisterworker true try print qget finally pass q multiprocessingjoinablequeue rangenumworkerthreads geventspawnmwregisterworker site sites qputsite qjoin block tasks done,2 the spaces make difference the difference due case sw vs sw you check sw compass s w sw perhaps change compassupper s w sw,i getting weird results i finally noticed habit putting spaces tuple causing problem if reproduce problem tell works way would saving left hair thanks jcomeauintrepidtmp cat haversinepy usrbinpython def dmstofloatdegrees compass degrees intd floatm floats floatdegrees floatdegrees compass s w sw return floatdegrees jcomeauintrepidtmp python python r jun gcc prerelease linux type help copyright credits license information haversine import dmstofloat sw dmstofloat sw with spaces tuple answer wrong without answer correct,3 in python i came type f type lambda xx yields true f function false but i think i prefer isinstance f typesfunctiontype feels less ad hoc i wanted type f function work,i variable x i want know whether pointing function i hoped i could something like isinstancex function but gives traceback recent call last file stdin line nameerror name function defined the reason i picked typex type function,1 class foo ffoo ffoo fa instance attribute f look class attribute foo fa create new instance attribute f fa instance attribute great let use fa instance attribute f look class attribute foo class foo ffoo ffoo fa instance attribute look class attribute foo faappend instance attribute modify class attribute inplace fa instance attribute look class attribute foo fa,i new python learned class attributes like static data members c however i got confused trying following code class foo ffoo ffoo fa fa fa fa shouldn fa also equal if defined list instead integer behavior expected class foo ffoo ffoo fa faappend fa fa i looked python difference class instance attributes answer question can anyone explain difference thanks,3 you thing second example in first example assigning fa new value fa in second example simply extending list faappend this change fa pointing if instead fa you would find behaves first example but consider example ffoo ffoo fooa fa fa in example actually changing value class attribute change visible instances class when type fa you overriding class attribute instance attribute,i new python learned class attributes like static data members c however i got confused trying following code class foo ffoo ffoo fa fa fa fa shouldn fa also equal if defined list instead integer behavior expected class foo ffoo ffoo fa faappend fa fa i looked python difference class instance attributes answer question can anyone explain difference thanks,3 my advice understand cases tests using id dict class foo fooa idfooa foodict module main doc none f foo fa idfa fdict f foo fa idfa fdict fa fa idfa fdict fa idfa fdict this shows long instruction fa executed instance f personal attribute then instruction print fa executed fa produce that a class instance namespace implemented dictionary first place attribute references searched when attribute found instance’s class attribute name search continues class attributes httpdocspythonorgreferencedatamodelhtmlthestandardtypehierarchy,i new python learned class attributes like static data members c however i got confused trying following code class foo ffoo ffoo fa fa fa fa shouldn fa also equal if defined list instead integer behavior expected class foo ffoo ffoo fa faappend fa fa i looked python difference class instance attributes answer question can anyone explain difference thanks,2 python class attributes object attributes stored separate dictionaries for object f accessed via respectively fclassdict fdict executing print fclass foo output true when reference attribute object python first tries look object dictionary if find checks class dictionary inheritance heirarchy when assign fa adding entry object dictionary f subsequent lookups fa find entry lookups fa still find class attribute — entry class attribute dictionary you cause value fa revert deleting del fa this remove entry object dictionary f subsequent lookups continue class dictionary so afterwards print fa output,i new python learned class attributes like static data members c however i got confused trying following code class foo ffoo ffoo fa fa fa fa shouldn fa also equal if defined list instead integer behavior expected class foo ffoo ffoo fa faappend fa fa i looked python difference class instance attributes answer question can anyone explain difference thanks,3 oh i see correct thing source virtualenvwrappersh path getting run subshell i guess,i new install virtualenvwrapper reason running virtualenvwrappersh functions available virtualenvwrappersh creating workon workon command found i know running aside successful creation ve files i wrapped function definitions echo please get statements get hit so,3 this may quite easy certainly need employ php given trivial python script cat cgibintestpy usrbinenv python print contenttype texthtml html head titlehello pythontitle head body hhello pythonh body html you run simple cgi http server commandline using python python cgihttpserver serving http port then another terminal window wm dump httplocalhostcgibintestpy hello python this useful testing cgi scripts local machine if want configure production http server serving python content best asking httpwebmastersstackexchangecom,i want begin fact i know nothing linux i found script i would like run server page i goto py file downloads file i suppose run i suppose use php file command run file thanks advance,1 you appear anything useful shelltrue probably safely skip alltogether try suphp subprocesspopenusrlocalcpanelbinrebuildphpconf current stdoutsubprocesspipecommunicate except oserror print couldn start subprocess suphp installed server note split command separate arguments since shell you always avoid using shell subprocesses unless absolutely require say set environment sourcing script,im creating python script check suphp trying create else statement declare suphp server using output subprocesspopen i tested output variable print created post pass correct output variable suphp this far check suphp suphp subprocesspopenusrlocalcpanelbinrebuildphpconf current shelltrue stdoutsubprocesspipecommunicate suphp binsh usrlocalcpanelbinrebuildphpconf no file directory print suphp installed server elif print suphp please note i new coding python decided try use python admin servers,1 read docstring str function you suppose return string representation print since return statement str function returns none print chokes instead actually return desired string let external print call display def strself return string representation set consists string representation shape categorized type circles squares triangles strings selfcollect typei square stringsappend square measurements striside typei circle stringsappend circle measurements striradius typei triangle stringsappend triangle measurements baseheight stribase striheight return n joinstrings,so i working python trying create shapeset instance contains list shape instances i need print list shape instances i use loop parts code without running error however i attempt print statement prints whole list end results error str returned nonstring type nonetype i understand fails understand stop end list at least i think any help greatly appreciated class shapeset def initself initialize needed variables selfcollect selfplace none def iterself return iterator allows iterate set shapes one shape time selfplace return self def nextself selfplace lenselfcollect raise stopiteration selfplace selfplace return selfcollectselfplace def addshapeself sh add shape sh set two shapes set may identical sh shape added scount ccount tcount selfcollectappendsh selfcollect typesh square typei square shside iside scount scount scount selfcollectremovesh print already typesh circle typei circle shradius iradius ccount ccount ccount selfcollectremovesh print already typesh triangle typei triangle shbase ibase shheight iheight tcount tcount tcount selfcollectremovesh print already def strself return string representation set consists string representation shape categorized type circles squares triangles selfcollect typei square print square measurements striside typei circle print circle measurements striradius typei triangle print triangle measurements baseheight stribase striheight,2 you wrote def strself return string representation set consists string representation shape categorized type circles squares triangles return anything print stuff put appropriate str method classes class square def strself return square measurements striside class circle def strself return circle measurements striradius representation shapeset class shapeset def strself return n joinstrx x selfcollect now printsomeshapeset well printsomecircle,so i working python trying create shapeset instance contains list shape instances i need print list shape instances i use loop parts code without running error however i attempt print statement prints whole list end results error str returned nonstring type nonetype i understand fails understand stop end list at least i think any help greatly appreciated class shapeset def initself initialize needed variables selfcollect selfplace none def iterself return iterator allows iterate set shapes one shape time selfplace return self def nextself selfplace lenselfcollect raise stopiteration selfplace selfplace return selfcollectselfplace def addshapeself sh add shape sh set two shapes set may identical sh shape added scount ccount tcount selfcollectappendsh selfcollect typesh square typei square shside iside scount scount scount selfcollectremovesh print already typesh circle typei circle shradius iradius ccount ccount ccount selfcollectremovesh print already typesh triangle typei triangle shbase ibase shheight iheight tcount tcount tcount selfcollectremovesh print already def strself return string representation set consists string representation shape categorized type circles squares triangles selfcollect typei square print square measurements striside typei circle print circle measurements striradius typei triangle print triangle measurements baseheight stribase striheight,2 a set hashes elements allow fast lookup you overwrite hash method element found class caobject def hashself return hashselfname lists use hashing compare element like loop,borrowing documentation contains documentation print setcontainsdoc xcontainsy x this seems work fine primitive objects int basestring etc but userdefined objects define ne eq methods i get unexpected behavior here sample code class caobject def initselfname selfname name def eqselfother selfname othername return true return false def neselfother return selfeqother obj ca hello obj ca hello thelist obj theset setthelist test list print obj thelist return true test set weird print obj theset return false unexpected test iterating set found false x theset x obj found true print found return true test typcasting set list print obj listtheset return true so bug feature,1 this ca implement hash a sensible implementation would def hashself return hashselfname,borrowing documentation contains documentation print setcontainsdoc xcontainsy x this seems work fine primitive objects int basestring etc but userdefined objects define ne eq methods i get unexpected behavior here sample code class caobject def initselfname selfname name def eqselfother selfname othername return true return false def neselfother return selfeqother obj ca hello obj ca hello thelist obj theset setthelist test list print obj thelist return true test set weird print obj theset return false unexpected test iterating set found false x theset x obj found true print found return true test typcasting set list print obj listtheset return true so bug feature,2 for set dicts need define hash any two objects equal hash order get consistent expected behavior set dicts i would reccomend using key method referencing anywhere need part item compare call eq neq instead reimplementing class caobject def initselfname selfname name def keyself return typeself selfname def hashself return hashselfkey def eqselfother selfkey otherkey return true return false def neselfother return selfeqother,borrowing documentation contains documentation print setcontainsdoc xcontainsy x this seems work fine primitive objects int basestring etc but userdefined objects define ne eq methods i get unexpected behavior here sample code class caobject def initselfname selfname name def eqselfother selfname othername return true return false def neselfother return selfeqother obj ca hello obj ca hello thelist obj theset setthelist test list print obj thelist return true test set weird print obj theset return false unexpected test iterating set found false x theset x obj found true print found return true test typcasting set list print obj listtheset return true so bug feature,3 well necessity checking types may topic bit open python considered good form follow duck typing the function uses interfaces needs caller pass arguments properly implement interface depending clever function may specify uses interfaces arguments takes,since i switched python c i feel like python care much type safety for example anyone explain checking types function parameters necessary python say i defined vector class follows class vector def initself args args contains components vector i check elements contained args numbers and i want dot product two vectors i add another function def dotselfother i check two vectors dimension first,2 this solution seems exactly want bringing browser foreground performing screen grab just replace firefox chrome,i want open page grab screen obtain mean color pil i want open pages i thought screen capture script python would useful i found several i decided use simple one a simple screen grabbing utility author fabio varesano date pil import imagegrab import time timesleep imagegrabgrabsavescreencapturejpg jpeg but i need run command prompt shows screen how i make script i call programmatically or think best way achieve thanks,1 import ast username asd filedusers astliteraleval username print filedusers typefiledusers asd type str you dictionary looks like one you string,i set dictionary filled file like filedusers cheap way keep track users production file openrgschoolcsuserstxt r filedusers astliteraleval filereadlinestrip fileclose later i test like filedusersgetwords words string username i get following error str object attribute get i verified already fileclose i dictionary correct values any idea going,2 python dynamically typed require define variables specific type and lets define variables implicitly what defining filedusers dictionary redefining string assigning result astliteraleval edit you need remove quotes astliteraleval evaluates string astliteraleval evaluates dictionary,i set dictionary filled file like filedusers cheap way keep track users production file openrgschoolcsuserstxt r filedusers astliteraleval filereadlinestrip fileclose later i test like filedusersgetwords words string username i get following error str object attribute get i verified already fileclose i dictionary correct values any idea going,1 literaleval takes string converts python object so following true astliteraleval however adding quotations needed if file simply contained empty dictionary string create would look like astliteraleval the quotes make return string so solution would change line astliteraleval filereadlinestrip astliteralevalfilereadlinestrip depending file layout otherwise literaleval sees string actual string quotes,i set dictionary filled file like filedusers cheap way keep track users production file openrgschoolcsuserstxt r filedusers astliteraleval filereadlinestrip fileclose later i test like filedusersgetwords words string username i get following error str object attribute get i verified already fileclose i dictionary correct values any idea going,3 you use selenium browser take screenshot selenium webdriver this crossplatform works every browser selenium designed functional web browser testing suitable also use cases like more info python selenium httppypipythonorgpypiselenium the benefit selenium finetuned control browser click buttons execute javascript whatever wish browser longer black box,i want open page grab screen obtain mean color pil i want open pages i thought screen capture script python would useful i found several i decided use simple one a simple screen grabbing utility author fabio varesano date pil import imagegrab import time timesleep imagegrabgrabsavescreencapturejpg jpeg but i need run command prompt shows screen how i make script i call programmatically or think best way achieve thanks,2 the problem line lineprefix joinstrvalue amp value penultargs you overwriting value original nondollarsigned value it works last argument line called args use different variable name loop python scoping within functions classes loops statements independently scoped,i trouble understanding inner loop method producing desired behavior i expecting i hoping someone help understand problem my method takes series arguments args argument integer i want add dollar signs around integer eg def trowargs columns lenargs columns count value args typevalue int value join strvalue count count lenargs penultargs args lineprefix joinstrvalue amp value penultargs elif count lenargs linesuffix joinstrvalue n count linelist lineprefix linesuffix line joinitem item linelist returnline the code used like qtrow data data data print data amp data amp amp data amp why i get dollar signs around integer how i fix code correct problem,1 in png palette always stored rgb bytes indexcolor arbitrary number entries if currently bit image colors palette total entries dont need alter pallete repack pixel bytes two indexes per byte if i think could pngj code untested public static void reencodestring orig string dest pngreader png filehelpercreatepngreadernew fileorig imageinfo pnginfo pngimginfo imageinfo pnginfo new imageinfopnginfocols pnginforows falsefalsetrue pngwriter png filehelpercreatepngwriternew filedest pnginfo false pngcopychunksfirstpng chunkstowritecopyall imageline l new imagelinepnginfo int row row pnginforows row imageline l pngreadrowrow ltfpacklscanline false lsetrownrow pngwriterowl pngend pngcopychunkslastpng chunkstowritecopyall pngend systemoutprintlndone elsewhere current pallette used colors length greater includes unused colors need work modifying palette chunk also done,i bunch images many hand color bit png format i need bit format palette i scouring google best library use i finding much specific problem i coming hopefully targeted solutions i trying use pil based answers i found luck img imageopen downarrowfocusedpng img imgpointlambda l imgsave downarrowfocusedpng png gives grayscale image i want pil work trying pypng gimp i hundreds things i need batch process and get batches convert one time thing a java based solution would acceptable well pretty much anything i run command line linuxosx machine acceptable,1 because line lineprefix joinstrvalue amp value penultargs pull values original list minus last item line value join strvalue you added never stored value back list the gets last item reference directly linesuffix joinstrvalue n a better way def trowself args lenargs selfcolumns result value args isinstancevalue int resultappend value else resultappendvalue return joinresult r as oneliner would trow lambda self args join value isinstancevalue int else value value args r lenargs selfcolumns else none actually good idea,i trouble understanding inner loop method producing desired behavior i expecting i hoping someone help understand problem my method takes series arguments args argument integer i want add dollar signs around integer eg def trowargs columns lenargs columns count value args typevalue int value join strvalue count count lenargs penultargs args lineprefix joinstrvalue amp value penultargs elif count lenargs linesuffix joinstrvalue n count linelist lineprefix linesuffix line joinitem item linelist returnline the code used like qtrow data data data print data amp data amp amp data amp why i get dollar signs around integer how i fix code correct problem,1 when printed output chance look like searchresult querydetails categorywomensclothescategory categorynameclothingcategoryname showsizefilterfalseshowsizefilter showcolorfiltertrueshowcolorfilter that xml json,i trying parse json using json library i executing chunk code i get error traceback recent call last file testpy line module parsedresponse jsonloadsdata file usrlocallibpythonjsoninitpy line loads return defaultdecoderdecodes file usrlocallibpythonjsondecoderpy line decode obj end selfrawdecodes idxws end file usrlocallibpythonjsondecoderpy line rawdecode raise valueerrorno json object could decoded valueerror no json object could decoded the code import urllib urllib djangoutils import simplejson import json opener urllibbuildopener requesturl httpapishopstylecomactionapisearchpidampftsreddressampminampcount data openeropenrequesturlreaddecode utf print data works parsedresponse jsonloadsdata i tried removing readdecode utf passing jsonload work either i appreciate help thanks,2 data null data proper json url seems outputting xml json tho post output data would help,i trying parse json using json library i executing chunk code i get error traceback recent call last file testpy line module parsedresponse jsonloadsdata file usrlocallibpythonjsoninitpy line loads return defaultdecoderdecodes file usrlocallibpythonjsondecoderpy line decode obj end selfrawdecodes idxws end file usrlocallibpythonjsondecoderpy line rawdecode raise valueerrorno json object could decoded valueerror no json object could decoded the code import urllib urllib djangoutils import simplejson import json opener urllibbuildopener requesturl httpapishopstylecomactionapisearchpidampftsreddressampminampcount data openeropenrequesturlreaddecode utf print data works parsedresponse jsonloadsdata i tried removing readdecode utf passing jsonload work either i appreciate help thanks,1 i going say earler i httpdocspythonorglibraryshutilhtml version copytree function i looked see would replace existing files i could tell would overwrite existing files fails directories already exist due osmkdirs failing directories already exist the needed imports import os import ospath import shutil taking mkdir httpcodeactivestatecomrecipesafriendlymkdir commenter mentions osmkdirs behavior notice mkdir fail directories made already exist def mkdirnewdir works way good mkdir already exists silently complete regular file way raise exception parent directoryies exist make well ospathisdirnewdir pass elif ospathisfilenewdir raise oserrora file name desired dir already exists newdir else head tail ospathsplitnewdir head ospathisdirhead mkdirhead print mkdir reprnewdir tail osmkdirnewdir although take mode argument like osmkdirs copytree use needed and change copytree call mkdir instead osmkdirs def copytreesrc dst symlinksfalse recursively copy directory tree using copy the destination directory must already exist if exceptions occur error raised list reasons if optional symlinks flag true symbolic links source tree result symbolic links destination tree false contents files pointed symbolic links copied xxx consider example code rather ultimate tool names oslistdirsrc osmakedirsdst mkdirdst xxx errors name names srcname ospathjoinsrc name dstname ospathjoindst name try symlinks ospathislinksrcname linkto osreadlinksrcname ossymlinklinkto dstname elif ospathisdirsrcname copytreesrcname dstname symlinks else shutilcopysrcname dstname xxx what devices sockets etc except ioerror oserror errorsappendsrcname dstname strwhy catch error recursive copytree continue files except error err errorsextenderrargs try shutilcopystatsrc dst except windowserror copy file access times windows pass,i like ignore pattern shutil copytree function provides and i want src tree replace existent filesfolders dest directory like distutildirutilcopytree i fairly new python user seem find posts,2 no the django framework provides interface datastore supports asynchronous calls directly possible make asynchronous calls,when using google app engine djangononrel way take advantage async datastore api i declare model classes django api,1 this total shot dark vpss bit home computer bit vice versa maybe difference default sizes accuracies something could freaking server barring try find information software stack web server using,i test code part webapp uses urllib perform operation i would usually perform via browser log remote website move another page perform post filling form i created separate clean virtualenvs nositepackages different machines different versions python exact packages via pip requirements file code works two virtualenvs local development machine work either production vpss in failing cases i log successfully move correct page i submit form remote server replies telling error application server error page complete request webserver error i successfully log maneuver second page seem session cookie problem particular final post i perform operation particular machine exact headers data seem problem i requestingposting i trying code two separate vps rented different companies seem problem vps physical environment code works different python versions i imagine incompabilty problem i completely lost stage work i even turneditoffandturnitonagain i see problem could i think something final post coming vps remote server like i figure could i feel like something going hood urllib causing remote server dislike reply edit i installed exact python version vps working local copy work remotely must something originating vps how could effect http request is something lower level,1 originally iso standard used represent monday sunday for convenience later interpretation sunday permitted if want use something consistent try using isoweekday the monday standard european convention i guess surprise p,in python showing day week integer using datetimestrftime shows different result using datetimeweekday import datetime datetimedatetimenow nowstrftime a sunday nowstrftime w day week integer nowweekday day week integer different way with strftime string format w sunday first day week with weekday monday instead what history two different,3 python strftime function emulates c library thus motivation w returns sunday comes entirely in contrast method dateweekday returns sunday seeks match behaviour much older time module within module times generally represented structtime within structtimetmday uses represent sunday the correct question becomes timestructtime represent sunday c library tm struct uses and answer this behaviour existed ever since guido first checked gmtime localtime functions and guido cannot wrong best ask,in python showing day week integer using datetimestrftime shows different result using datetimeweekday import datetime datetimedatetimenow nowstrftime a sunday nowstrftime w day week integer nowweekday day week integer different way with strftime string format w sunday first day week with weekday monday instead what history two different,3 i finally managed find answer problem i modify tinymceviewspy file like fburl sss requestissecure https http requestgethost urlresolversreverse filebrowserindex requestgethost urlresolversreverse fbbrowse i found answer post httpwwwmailarchivecomdjangousersgooglegroupscommsghtml,i trying integrate djangotinymce djangofilebrowser django admin site everything almost works fine managepy test filebrowser works ok httplocalhostadminfilebrowserbrowse works however i press browse button windows popup insertedit image tinymce button panel nothing happens firefox debug window i get error like pressing browse f undefined code httplocalhoststaticjstinymcetinymcesrcjs line devserver output window i get error like get tinymcefilebrowser http admin page tries load tinymcemodelshtmlfield text area any ideas i wrong ps i also use grappelli settingspy part loads apps installedapps usual django standard apps djangocontribstaticfiles grappelli filebrowser tinymce djangocontribadmin expedeatdbadmin,1 the problem code encoding script try saving different editor notepad windows works,code trouble encoding error file testpy line syntaxerror encoding problem bom i attached code clear idea fix input output file contain korean words numbers english charaters i try run code mac windows work os please help coding uft future import printfunction future import unicodeliterals import os sys import codecs import import subprocess shlex regexp recompiler w def main words codecsopen emachtxt r encoding cp fp line fp item category regexpfindallline wordssetdefaultcategory setdefaultitem wordscategoryitem codecsopen resulttxt w encoding cp fp category words sortedwordsitems printcategory filefp word count wordsitems printword count sep filefp printfilefp return name main raise systemexitmain,1 i found package magickwand ctypes based imagemagick binding python yet documentation still satisfies requirements plus i finally started project wand,i looking good python binding imagemagick seem lot bindings already i sure right tool job can guys recommend one here list requirements preferences order importance must available pypi simplify deployment prefer ctypes c api extension — go pypy soon pythonic api design naming conventions good documentation especially api references,3 you misspelled utf first line since used ascii characters code even required coding line,code trouble encoding error file testpy line syntaxerror encoding problem bom i attached code clear idea fix input output file contain korean words numbers english charaters i try run code mac windows work os please help coding uft future import printfunction future import unicodeliterals import os sys import codecs import import subprocess shlex regexp recompiler w def main words codecsopen emachtxt r encoding cp fp line fp item category regexpfindallline wordssetdefaultcategory setdefaultitem wordscategoryitem codecsopen resulttxt w encoding cp fp category words sortedwordsitems printcategory filefp word count wordsitems printword count sep filefp printfilefp return name main raise systemexitmain,2 maybe weekday based locale strftime because i different output in dstrftimea out sunday in dstrftimew out in nowweekday out,in python showing day week integer using datetimestrftime shows different result using datetimeweekday import datetime datetimedatetimenow nowstrftime a sunday nowstrftime w day week integer nowweekday day week integer different way with strftime string format w sunday first day week with weekday monday instead what history two different,1 doesn work b b true,say i b way test lists see without loop entry here i thinkingi know check two variables i could use ida work id different type checksum way python stores values table i simply compare two variables,3 operator function expected lists x x true,say i b way test lists see without loop entry here i thinkingi know check two variables i could use ida work id different type checksum way python stores values table i simply compare two variables,1 if want latest tweets specific users twitter offers streaming api the streaming api realtime sample twitter firehose this api developers data intensive needs if looking build data mining product interested analytics research streaming api suited things if trying access old information rest api severe request limits way go,i building project python needs scrape huge huge amounts twitter data something like million users tweets need scraped previously i used tweepy twython hit limit twitter fast how sentiment analysis companies etc get data how get tweets do buy somewhere build something iterates different proxies something how companies like infochimps example trst rank get data httpwwwinfochimpscomdatasetstwittercensustrstrank,3 store value session view context processor soon set first time requestsession roleid requestpost role then get actual role object context processor time currentrole roleobjectsgetroleidrequestsession roleid,i form sitebasehtml extends templates in sitebasehtml dropdown form allows user change role based selected role templates changes i thought persist information via context processor i problems writing right logic persist form value so basically user selected role i using roleid populate urls i i getting null value whenever i click new link thanks logic contextprocessor i kinda new python django i sure i go the good use case wild would github account context switcher form sitebasehtml form namecontext methodpost action csrftoken div classinputgroup select namerole onchangecontextform option valuenoneselect contextoption role requestusergetorcreateprofilerolesall option value roleid ifequal roleid currentroleid selectedselected endifequal rolename roleevent option endfor select div currentrole form naive contextprocessorpy def contextswitcherrequest get user role role requestpost roleid requestpostget role currentrole roleobjectsfilteridroleid else currentrole return currentrole currentrole,1 src unicode encoding print correctly sysstdoutwrite figures encoding use outputting,using mechanize i retrieved source page web contains nonascii characters chinese characters code goes using python mechanize import browser br browser bropenhttpwwwexamplehtml src brreponseread retrieve source web print src print src question according source page i see charsetgb i print src contents correct i mean gibberish why does print know src encoding should i explicitly decode encode src,2 osmakedirs gets relative path based tmp gets called calls chdir see dest initialisation usage,i following piece python code the code supposed get source temporary final output path user extract header files when full paths specified terminal program works perfectly terminal command python getiosprivatesdkspy p developerplatformsiphoneosplatformdevelopersdksiphoneossdksystemlibraryprivateframeworks tmp f testtxt header files instead getting generated tmp folder current directory go recursive loop each folder inturn tmp folder goes can anyone tell import optparseossubprocess glob import glob parser optparseoptionparser parseraddoptionppath help source path dest inputpath metavar path parseraddoptionttemphelp temporary folder path dest temppath metavar path parseraddoptionffilehelp destination pathdest outputpathmetavar path optsargs parserparseargs optsinputpath none optsoutputpath none optstemppath none print error please specify necessary paths else osmakedirsoptstemppath privatesdk dest optstemppath privatesdk rootsubfoldersfiles oswalkoptsinputpath file files osmakedirsdest file oschdirdest file command optlocalbinclassdump h ospathjoinrootfile subprocesscallcommand the folder also get created privatesdk gets created tmpprivatesdk basically i able get full path terminal tmp mentioned i make program run,2 urllib default useragent banned wikipedia results http response you modify application useragent something like option import urllib opener urllibbuildopener openeraddheaders useragent myuseragent res openeropen httpwhatsmyuseragentcom page resread option import urllib req urllibrequest httpwhatsmyuseragentcom reqaddheader useragent myuseragent urlliburlopenreq option req urllibrequesthttpwhatsmyuseragentcom headersuseragent myuseragent urlliburlopenreq bonus link high level wikipedia python clients httpwwwmediawikiorgwikiapiclientcodepython,i writing python web app i plan leverage wikipedia when trying url fetching code i able fetch google facebook via google app engine services i attempted fetch wikipediaorg i received exception can anyone confirm wikipedia accept types page requests how wikipedia distinguish user code snippet python import os import urllib googleappengineextwebapp import template class mainhandlerwebapprequesthandler def getself url httpwikipediaorg try result urlliburlopenurl except urlliburlerror e result ahh sky falling templatevalues test result path ospathjoinospathdirnamefile indexhtml selfresponseoutwritetemplaterenderpath templatevalues,3 i struggled despite many answers i risk adding another run python c import platform print platformplatform does end bit do ls l usrlocalmysql it symlink end x if python says bit want mysql x search httpdevmysqlcomdownloadsmysql if python says bit probably want x mysql if match still work read answers versionerpythonpreferbit etc for mismatch caused macho wrong architecture error the next error library loaded libmysqlclientdylib reason image found to solve one i recommend adding symlink rather set dyldlibrarypath explained answers sudo ln usrlocalmysqlliblibmysqlclientdylib usrlocallib,i time read many sites subject suspect i junk lying causing problem but this error i import mysqldb python import mysqldb librarypythonsitepackagesmysqlpythoncpymacosxuniversaleggmysqlpy userwarning module mysql already imported librarypythonsitepackagesmysqlpythoncpymacosxuniversaleggmysqlpyc usersphoebebrdownloadsmysqlpythonc added syspath traceback recent call last file stdin line module file mysqldbinitpy line module import mysql file buildbdistmacosxuniversaleggmysqlpy line module file buildbdistmacosxuniversaleggmysqlpy line bootstrap importerror dlopenusersphoebebrpythoneggsmysqlpythoncpymacosxuniversaleggtmpmysqlso suitable image found did find usersphoebebrpythoneggsmysqlpythoncpymacosxuniversaleggtmpmysqlso macho wrong architecture i trying bit checked file python usrbinpython macho universal binary architectures usrbinpython architecture x macho bit executable x usrbinpython architecture macho executable usrbinpython architecture ppc macho executable ppc file mysql usrlocalmysqlbinmysql macho bit executable x have set default version python python python r feb gcc apple inc build darwin tried deleting build directory python setuppy clean renamed pythonsitepackages could try pick update deleted everything followed instructions httpstackoverflowcomquestionsdjangomysqlonmacossnowleopard installing using macports but basically still get error traceback recent call last file stdin line module file optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagesmysqldbinitpy line module import mysql importerror dlopenoptlocallibraryframeworkspythonframeworkversionslibpythonsitepackagesmysqlso suitable image found did find optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagesmysqlso macho wrong architecture,3 yes there qr code library php check link httpphpqrcodesourceforgenet,i writing qr code generator i write reed solomon error correction methods free library php python thank,1 according wikipedia utc days almost always long due leap seconds occasionally could long though latter option never used december keeps days synchronized rotation earth universal time i expect double leap second could fact make day long ever used edit second guessed due confusing python documentation timemktime always returns utc epoch seconds there done,while reviewing past answers i noticed i proposed code import time def datesbetweenstart end muck around k time representation systems python start end seconds since epoch return start start start return rangestart end when rereading piece code i help feel ghastly touch tony pony spine gently murmuring leap seconds ears terrible terrible things when day seconds long assumption break epoch definitions second ever i assume functions python timemktime already return dstadjusted values snippet also work dst switching days i hope,3 regarding linux need enumerate devices even skip pyudev dependency project simply parse output sbinudevadm info exportdb command require root privileges it dump information present devices classes including usb product ids usb devices enough identify usbtoserial adapters of course also pyudev,i port signal relay connected computer via usb serial interface using pyserial module i control relays ease however based assumption i know beforehand comport devnode device assigned for project i enough since i want assume device always gets assigned example com windows i need able identify device programatically across possible platforms win linux osx i imagine would similar linux approach using python perhaps title suggests enumerate usbdevices system somehow get friendly names windows linux important platforms support any help would greatly appreciated edit seems like pyudevmodule would good fit linuxsystems has anyone experience,3 when apxs throws error complaining missing configvarsmk means build directory apache missing fox xampp users solution download xamppdev well extract path,i extracted xampp package xampplinux ubuntu system followed instuctions modwsgi documentation i get error raviibexmodwsgi configure withapxsoptlamppbinapxs checking apache version cannot open optlamppbuildconfigvarsmk no file directory optlamppbinapxs line cannot open optlamppbuildconfigvarsmk no file directory optlamppbinapxs line configure line directory checking python usrbinpython cannot open optlamppbuildconfigvarsmk no file directory optlamppbinapxs line configure creating configstatus configstatus error cannot find input file makefilein i could google instructions getting modwsgi running xampp please help solution the solution buried comments thanks martin v lã¶wis i able solve when apxs throws error complaining missing configvarsmk means build directory apache missing fox xampp users solution download xamppdev well extract path,1 at least linux use dummy hacks determine dev node inspecting example output ls dev grep ttyusb attach device this somehow must apply well osx case a good idea inspect commands using something like subprocesspopen command as windows might helpful,i port signal relay connected computer via usb serial interface using pyserial module i control relays ease however based assumption i know beforehand comport devnode device assigned for project i enough since i want assume device always gets assigned example com windows i need able identify device programatically across possible platforms win linux osx i imagine would similar linux approach using python perhaps title suggests enumerate usbdevices system somehow get friendly names windows linux important platforms support any help would greatly appreciated edit seems like pyudevmodule would good fit linuxsystems has anyone experience,1 see httpdocspythonorgtutorialmoduleshtml information modules to find characters valid look syntax import statement it shows module name needs valid identifier following rule identifier letter letter digit,i encountered invalid name python module filename analyzed warning message pydev i tried resolve replacing filename warning disappeared one problems fact module python script still i get warning warning says nothing solve issue what real requirements filenames necessary modules specified pip how i solve problem pydev,3 i think almost got right instead model names use table names defining primaryjoin so instead define relationships publishuser relationship user backref backref pages orderby id primaryjoin pagepublishinguserid userid edituser relationship user primaryjoin pagelastedituserid userid use define relationships publishuser relationship user backref backref pages orderby id primaryjoin pagespublishinguserid usersid edituser relationship user primaryjoin pageslastedituserid usersid,i’ve looked sqlalchemy tutorial similar questions i seem struggling get join work the scenario i pages table represented page model pages created user edited user necessarily one my page model looks like abridged class pagebase tablename pages id columninteger primarykey true slug columntext title columntext directlink columntext body columntext categoryid columninteger foreignkey categoriesid publishedon columndatetime publishinguserid columninteger foreignkey usersid lastediton columndatetime lastedituserid columninteger foreignkey usersid define relationships publishuser relationship user backref backref pages orderby id primaryjoin pagepublishinguserid userid edituser relationship user primaryjoin pagelastedituserid userid category relationship category backref backref pages orderby id my users stored users table represented user model as i said i’ve sqlalchemy docs looking i’ve tried make look similar example possible avail any help would greatly appreciated,3 windows pull usb information wmi need administrator the examples net able use python wmi module this give access usb identification strings may contain useful information for ftdi serial devices short cut using ftdi dll require privileged access linux available information sysbususb also available udev this looks like good answer,i port signal relay connected computer via usb serial interface using pyserial module i control relays ease however based assumption i know beforehand comport devnode device assigned for project i enough since i want assume device always gets assigned example com windows i need able identify device programatically across possible platforms win linux osx i imagine would similar linux approach using python perhaps title suggests enumerate usbdevices system somehow get friendly names windows linux important platforms support any help would greatly appreciated edit seems like pyudevmodule would good fit linuxsystems has anyone experience,1 as far windows goes could scan registry import winreg reg itertools import count key regopenkeyreghkeylocalmachine hardwaredevicemapserialcomm try count device port regenumvaluekey print device port except windowserror pass,i port signal relay connected computer via usb serial interface using pyserial module i control relays ease however based assumption i know beforehand comport devnode device assigned for project i enough since i want assume device always gets assigned example com windows i need able identify device programatically across possible platforms win linux osx i imagine would similar linux approach using python perhaps title suggests enumerate usbdevices system somehow get friendly names windows linux important platforms support any help would greatly appreciated edit seems like pyudevmodule would good fit linuxsystems has anyone experience,1 i found real answer yet i made calculations cost currently every indexed property field costs around per k inserts with upcoming billing model pricing faq cost exactly per k operations per indexed field per k inserts index write operations per insert so price seems go factor ten observed slowness indeed unexpected behaviour as free quota well enough test runs new pricing model coming i wont let bother time,i testing google app engine djangononrel free quota it seems database operations datastore hideously slow take example simplified function processing request takes multipartformdata xml blobs parses inserts database def postrequest fields cgifieldstoragerequest transactioncommitonsuccess xmlblob fieldsgetlist xmlblob blobobject parsexmlxmlblob blobobjectsave blobobject five fields type charfield for ca blobs kb xml altogether function takes seconds return uses apicpums cpu time equivalent amount work ghz intel x processor could time i pretty sure would take seconds insert rows database x processor available without saving objects database parsing xml throwing away result request takes merely milliseconds so google app engine really slow i save even dozen entities datastore normal request i missing something and course even i would inserts backend using task queue would still cost hundreds times would seem acceptable edit i found default gae two index writes per property entity most properties indexed question i set properties unindexed djangononrel i still feel though even index writes database operation taking ridiculous amount time,1 class parserobject def initself selfmysection selfflagsection false def parseconfigself fields selfmysection go fields selfflagsection true def parseeditself line def parsesetself line def parseendself line def parsefileself path openpath f line f fields fstripsplit method fields fetch call method getattrparser parse methodself fields,appologies really long drawn question i trying read config file get list rules i tried use configparser standard config file the file contains section header token ie config section set something something else config subsection set next end config firewall policy edit set srcintf there set dstintf here set srcaddr set dstaddr set action accept set schedule always set service tcp next edit set srcintf set dstintf set srcaddr set dstaddr set action accept set schedule always set service ping next end as i work get configparser work i thought i would try iterate file unfortunately i much programming skill i got stuck i really think i making complicated here code i written class parserobject def initself selfconfigsection selfconfigheader selfsectionlist selfheaderlist def parseconfigself fields create new section newlist selfconfigsection joinfields newlistappendselfconfigsection selfsectionlist create sub section selfsectionlistappendnewlist else selfsectionlistappendnewlist def parseeditself line create new header selfconfigheader line selfheaderlistappendselfconfigheader selfsectionlistappendselfheaderlist def parsesetself line key values keyvalue key line values line keyvaluekey values selfheaderlist selfheaderlistappendkeyvalue else selfsectionlistappendkeyvalue def parsenextself line close header selfconfigheader def parseendself line close section selfconfigsection def parsefileself path openpath f line f clean fields remove unused lines fields linereplace stripsplit fields set pass elif fields end pass elif fields edit pass elif fields config pass elif fields next pass else continue fetch call method method fields parsemethod parse method getattrparser parsemethodself fields return selfsectionlist config parserparsefile testconfigtxt print config the output i looking something like following section something something else subsection firewall policy srcintf there dstintf here etcetc i get section edit i changed reflect i currently i still issues getting output i expect i seem get list right,1 this quick hack i made i referred user answer httptaotetekwordpresscompythonmultiprocessingwithzeromq if better please post answer i recommend answer for wanting lasting solutions reliability refer httpzguidezeromqorgpagealltoc version zeromq beta atm supports timeout zmqrcvtimeo zmqsndtimeo httpapizeromqorgzmqsetsockopt server the zmqnoblock ensures client exist send block import time import zmq context zmqcontext ventilatorsend contextsocketzmqpush ventilatorsendbindtcp true ii timesleep print sending message try ventilatorsendsendreprizmqnoblock print succeed except print failed client the poller object listen many recieving sockets see python multiprocessing zeromq linked i linked workreceiver in infinite loop client polls interval ms the socks object returns empty message recieved time import time import zmq context zmqcontext workreceiver contextsocketzmqpull workreceiverconnecttcp poller zmqpoller pollerregisterworkreceiver zmqpollin loop accept messages channels acting accordingly true socks dictpollerpoll socks socksgetworkreceiver zmqpollin print got message workreceiverrecvzmqnoblock else print error message timeout,i got started zmq i designing app whose workflow one many clients random pull addresses push request server server forever waiting client pushes when one comes worker process spawned particular request yes worker processes exist concurrently when process completes task pushes result client i assume pushpull architecture suited please correct but i handle scenarios clientreceiverrecv wait infinite time server fails respond client may send request fail immediately hence worker process remain stuck serversendersend forever so i setup something like timeout pushpull model edit thanks user suggestions i got working answer i sharing posterity,3 solution following version fruit table instance q selectfruitctype funcminfruitcpricelabelminprice groupbyfruitctypealiassubq selectfruit andfruitctype qctype fruitcprice qcminprice res sessionexecutes version fruit model type q selectfruittype funcminfruitpricelabelminprice groupbyfruittypealiassubq sessionqueryfruit joinq andfruittypeqctype fruitprice qcminprice res sall side note float column pk sound like great idea really cannot two different fruits price violate uniqueness,i using example help learn sqlalchemy here mysql select ftype fvariety fprice select type minprice minprice fruits group type x inner join fruits f ftype xtype fprice xminprice here i far session sq squeryfuncminfruitpricegroupbyfruittypesubquery ans squeryfruitjoinsq fruitpricesqcpriceall clearly work am i even close i pouring docs price pk helps maybe need alias something any help direction appreciated,1 import glob operator fpout openresultdatw path globglobdata openpath r fp fields linesplit line fp maxline joinmaxfields key lambda row floatrow print fpout maxline,i fairly simple task i need automate analysis i found similar questions forum applied plain text file i python newbie i sure convert solutions directly needs so i appreciate help i series files format file named data data data etc the data separated single spaces header i would like script go file find row max value column eg value print row new output file in end i need one output file contains rows max value column input files so input files output file would rows i hope clear help really appreciated,1 function alternative the mechanism exactly,in perl quite common things like function alternative if first returns false run second one how easily implemented python update examples pseudocode x func raise exeption x func printx func print something if possible solutions work python note there implied assumption cannot modify func raise exceptions write wrappers,1 use function alternative also conditional expression defined pep x condition else which sometimes useful expressions bit readable,in perl quite common things like function alternative if first returns false run second one how easily implemented python update examples pseudocode x func raise exeption x func printx func print something if possible solutions work python note there implied assumption cannot modify func raise exceptions write wrappers,1 use python uses short circuit evaluation boolean expressions function alternative if function returs true final value expression determined alternative evaluated,in perl quite common things like function alternative if first returns false run second one how easily implemented python update examples pseudocode x func raise exeption x func printx func print something if possible solutions work python note there implied assumption cannot modify func raise exceptions write wrappers,3 try def bye return print bye unfortunately work like perl perl assignment like c c value undefined in python get error nameerror name defined,in perl quite common things like function alternative if first returns false run second one how easily implemented python update examples pseudocode x func raise exeption x func printx func print something if possible solutions work python note there implied assumption cannot modify func raise exceptions write wrappers,1 you another module named imp either rename move either spot later syspath standard library modules syspath completely rearrange syspath it likely directory views case easiest thing probably move directory modules import imp rename,i function def loadfromfilefilepath expectedclass modname fileext ospathsplitextospathsplitfilepath pymod imploadsourcemodname filepath templatetags file ok but copypaste function view get error module object attribute loadsource my example view import os imp def getmodulerequest position imod loadfromfilesettingsprojectroot coremanagermodules modtypefileview py modulemanager def loadfromfilefilepath expectedclass why working,1 twill odd one prints lot output terminal it variable assignment causing stuff printed show method it print rather return output,i making simple command line program gathering parsing information websites pretty generic using twill module python i want assign html output variable using twill show command run page parsing commands every time i assign variable htmlstring twillcommandsshow i get humongous flood html command line idle matter why i asking print variable print command anywhere near i want assign manipulation why would variable assignment cause print occur it fatal error anything really really inconvenient i python twill ubuntu pertains anything,1 you need escapes r utmsourceputmsourcewamputmmediumputmmediumw then regex matches complete string find submatch perhaps need remove anchors r utmsourceputmsourcewamputmmediumputmmediumw finally slash end required regex missing example string so r utmsourceputmsourcewamputmmediumputmmediumw,i need help validate regular expression link python here link look like httpwwwexamplecomutmsourcesomethingamputmmediumsomethingelse and i tried something like r utmsourceputmsourcewamputmmediumputmmediumw but work can please help which characters escaped,1 this classic xy problem tim answer gives solution asked i suggest need regular expressions want validate query string take look urlparse aurl httpwwwexamplecomutmsourcesomethingamputmmediumsomethingelse parser urlparseurlparseaurl qs urlparseparseqsparserquery utmmedium qs true lenqs utmmedium true qs utmmedium isalpha true utmsource qs true lenqs utmsource true qs utmsource isalpha true utmzone qs false,i need help validate regular expression link python here link look like httpwwwexamplecomutmsourcesomethingamputmmediumsomethingelse and i tried something like r utmsourceputmsourcewamputmmediumputmmediumw but work can please help which characters escaped,2 how getting whole range worksheetusedrange property,i using pywin read write excel now method i know accessing rangevalue however i usually know size full excel table advance so moment i read line line i find completely empty line this quite slow of course i try tricks like reading blocks data i find optimal block size do know another method maybe internal excel function approaches faster,1 you use self first argument regular methods instance passed automatically argument so whatever first argument method points current instance when method decorated classmethod gets class passed first argument common name cls points class you usually prefix variables hungarian notation bad here example class testobject def helloself print instance r says hello self classmethod def greetcls print class r greet cls output testhello instance maintest object xf says hello testgreet class class maintest greet,yet another question self happens use self cls i done homework i want make sure i got self to access attribute object need prefix attribute name object name objnameattributename the way self used access attribute inside object class so prefix variable self class method able access variable methods class outside class so could omit wanted make variable local method the way method variable wanted share methods could omit self method arguments cls each instance creates copy attributes wanted instances class share variable would prefix variable name cls class declaration is right thanks,2 you use xlrd open workbook read size particular worksheet it quite fast hints book xlrdopenworkbookmyfilexls get sheet object sheet booksheetbyindexsheetx sheet booksheetbynamesheetname sheetnrows property number rows given sheet here api documentation,i using pywin read write excel now method i know accessing rangevalue however i usually know size full excel table advance so moment i read line line i find completely empty line this quite slow of course i try tricks like reading blocks data i find optimal block size do know another method maybe internal excel function approaches faster,2 in vba often use end statement like worksheetssheetcellsrowscount aendxluprow that may help find last used cell column yet i know extend method pywin,i using pywin read write excel now method i know accessing rangevalue however i usually know size full excel table advance so moment i read line line i find completely empty line this quite slow of course i try tricks like reading blocks data i find optimal block size do know another method maybe internal excel function approaches faster,1 the way self used access attribute inside object class not inside object class inside class instance methods self convention could call whatever wanted even something different method so prefix variable self class method able access variable methods class outside class self used instance methods cls often used class methods otherwise correct so could omit wanted make variable local method yes inside method variable name like inside function interpreter looks name locally closures globals module level python builtins the way method variable wanted share methods could omit self method arguments no omit self method arguments you tell python want staticmethod automatically get passed instance class ether staticmethod def line mymethod staticmethodmymethod method body each instance creates copy attributes wanted instances class share variable would prefix variable name cls class declaration inside class definition outside methods names bound class define methods etc you prefix cls anything else cls generally used new special staticmethod classmethod make similarly staticmethod these methods need access class things specific instance class inside classmethod yes use refer attributes wanted instances class class share like self cls convention could call whatever wanted a brief example class fooobject use self cls mean anything class attribute thing athing def initself bar i want methods called instance foo access bar i create attribute self pointing selfbar bar staticmethod def defaultfoo static methods often used alternate constructors since need access part class method anything class use module level function return foo baz classmethod def twothingscls access class attributes like thing instance attributes like bar print clsthing clsthing,yet another question self happens use self cls i done homework i want make sure i got self to access attribute object need prefix attribute name object name objnameattributename the way self used access attribute inside object class so prefix variable self class method able access variable methods class outside class so could omit wanted make variable local method the way method variable wanted share methods could omit self method arguments cls each instance creates copy attributes wanted instances class share variable would prefix variable name cls class declaration is right thanks,3 bpf means raised bpf power,in randompy source code following constant definition bpf number bits float recipbpf bpf i math major readable invert bpf placing or something multiplication convenient division programming nevermind in effort clean question i found on many machines particularly without hardware support division division slower operation multiplication approach yield considerable speedup the first step relatively slow needs done httpenwikipediaorgwikimultiplicativeinverse,1 recipbpf despite name bpf it bpf i speak everyone i find easier read bpf i would bpf note speed multiplication division really relevant particular since constants compiler interpreter needs evaluate compiler even compile time moreover since exact powers two direct ways produce result without either multiplication division using fact floatingpoint uses binary encoding,in randompy source code following constant definition bpf number bits float recipbpf bpf i math major readable invert bpf placing or something multiplication convenient division programming nevermind in effort clean question i found on many machines particularly without hardware support division division slower operation multiplication approach yield considerable speedup the first step relatively slow needs done httpenwikipediaorgwikimultiplicativeinverse,2 redability subjective that said i personally find bpf easier read bpf without parentheses around bfp as performance differences i doubt relevant since expression evaluated module imported,in randompy source code following constant definition bpf number bits float recipbpf bpf i math major readable invert bpf placing or something multiplication convenient division programming nevermind in effort clean question i found on many machines particularly without hardware support division division slower operation multiplication approach yield considerable speedup the first step relatively slow needs done httpenwikipediaorgwikimultiplicativeinverse,1 that tuple list if depend format exactly shown probably get away something like convert list mystring mystringtranslatenone numbers mystringsplit xrangelennumbers outappendintnumbers int this probably improved using better listwalking mechanism this pretty clear though if really really want tuple tuples convert final list tupleout,i like convert python script following string mystring list tuples mytuple print mytuple yields,1 you might want check pybrain,i planning implementing document ranker uses neural networks how one rate document taking consideration ratings similar articles any good python libraries can anyone recommend good book ai python code edit i planning make recommendation engine would make recommendations similar users well using data clustered using tags user would given chance vote articles there hundred thousand articles documents would clustered based tags given keyword articles would fetched based tags passed neural network ranking,2 i use astliteraleval in astliteraleval out as seen returns tuple tuples if want list tuples simply apply list result,i like convert python script following string mystring list tuples mytuple print mytuple yields,3 use eval mytuple evalmystring if want list enclose mystring brackes mytubleevals mystring that simplest solution nothing import work python however astliterateeval seems appropriate defensive context,i like convert python script following string mystring list tuples mytuple print mytuple yields,1 if know sure cp input ddecode cp encode utf,i using mutagen convert id tags data cp cp utf in linux problem but windows calling setvalue wxtextctrl produces error unicodedecodeerror ascii codec decode byte xc position ordinal range the original string assumed cp encoded i pulling mutagen u xcxexebxexff xffxexebxfbxedxff xexfxeexecxf i tried converting utf dd ddecode utf even changing default encoding ascii utf syssetdefaultencoding utf but i get error,3 here script maybe would helpful someone import bpy import xmldomminidom path usersxdocumentsygameprojectstestxml dom xmldomminidomgetdomimplementation tree domcreatedocumentnone document none root treedocumentelement rootsetattributeversion object bpydataobjects objecttype mesh objectdatashapekeys objectelement treecreateelementobject objectelementsetattributename objectname rootappendchildobjectelement keyselement treecreateelementshapekeys objectelementappendchildkeyselement keyblocks objectdatashapekeyskeyblocks block keyblocks keyelement treecreateelementkey keyelementsetattributename blockname keyselementappendchildkeyelement data blockdata vertex dataco element treecreateelementvertex elementsetattributex strvertexx elementsetattributey strvertexy elementsetattributez strvertexz keyelementappendchildelement file openpath w encodingutf treewritexmlfile encoding utf indent n addindent fileclose,i want export shape keys object how get access shape key mesh i using blender thanks,3 if correct unicode string dencode utf yields encoded utf bytestring don test printing though might display properly codepage shenanigans,i using mutagen convert id tags data cp cp utf in linux problem but windows calling setvalue wxtextctrl produces error unicodedecodeerror ascii codec decode byte xc position ordinal range the original string assumed cp encoded i pulling mutagen u xcxexebxexff xffxexebxfbxedxff xexfxeexecxf i tried converting utf dd ddecode utf even changing default encoding ascii utf syssetdefaultencoding utf but i get error,2 okay answer post well done d produces increase speed system going single core thread quad core multiprocessing import multiprocessing time psycopg class consumermultiprocessingprocess def initself taskqueue resultqueue multiprocessingprocessinitself selftaskqueue taskqueue selfresultqueue resultqueue def runself procname selfname true nexttask selftaskqueueget nexttask none print tasks complete selftaskqueuetaskdone break answer nexttask selftaskqueuetaskdone selfresultqueueputanswer return class taskobject def initself selfa def callself pyconn psycopgconnectdbname geobase host localhost pyconnsetisolationlevel pycursor pyconncursor procquery update city set gidfkey gid from country where stwithinselect thegeom from city where cityid countrythegeom and cityid selfa selfa pycursorexecuteprocquery print what self print selfa return selfa def strself return arc def runself print in name main tasks multiprocessingjoinablequeue results multiprocessingqueue numconsumers multiprocessingcpucount consumers consumertasks results xrangenumconsumers w consumers wstart pyconnx psycopgconnectdbname geobase host localhost pyconnxsetisolationlevel pycursorx pyconnxcursor pycursorxexecute select count from cities where gidfkey is null temp pycursorxfetchall numjob temp numjobs numjob pycursorxexecute select cityid from city where gidfkey is null cityidlisttuple pycursorxfetchall cityidlist x cityidlisttuple cityidlistappendx xrangenumjobs tasksputtaskcityidlisti xrangenumconsumers tasksputnone numjobs result resultsget print result numjobs now i another question i posted create db connection maintain multiple processes multiprocessing hopefully get rid overhead speed baby even,i need update every record spatial database i data set points overlay data set polygons for point feature i want assign key relate polygon feature lies within so point new york city lies within polygon usa usa polygon gid i assign gidfkey point new york city to i created following query procquery update city set gidfkey gid from country where stwithinselect thegeom from city where wpid countrythegeom and cityid cityid cityid at present i getting cityid info another query selects cityid gidfkey null essentially i need loop run query shown earlier as query relies static information table theory processes run i implemented threading procedure i seem make migration multiprocessing import psycopg pprint threading time queue queue queuequeue pyconn psycopgconnectdbname geobase host localhost pyconnsetisolationlevel pycursor pyconncursor getgid select cityid from city pycursorexecutegetgid gidlist pycursorfetchall class threadclassthreadingthread def initself queue threadingthreadinitself selfqueue queue def runself true gid selfqueueget procquery update city set gidfkey gid from country where stwithinselect thegeom from city where wpid countrythegeom and cityid cityid cityid pycursor pyconncursor pycursorexecuteprocquery print gid print done def main range threadclassqueue tsetdaemontrue tstart gid gidlist queueputgid queuejoin main i even sure multithreading optimal definitely faster going one one the machine i using four cores quad core minimal linux os gui postgresql postgis python makes difference what i need change get painfully easy multiprocessing task enabled,2 if data cdoubledatalengthvalue array could npfrombufferdata copy changes reflected data if data pointercdouble could get numpy array using numpyfromiter it loop question faster npfromiterdata dtypenpfloat countdatalengthvalue copy to create numpy array pointercdouble instance without copying could use fromaddress method arraytype ctypescdoubledatalengthvalue addr ctypesaddressofdatacontents npfrombufferarraytypefromaddressaddr or arraypointer ctypescastdata ctypespointerarraytype npfrombufferarraypointercontents both methods convert pointercdouble instance cdoubledatalength passing numpyfrombuffer cythonbased solution is anyway load data c array convert array fit scipy here c extension module python written cython provide c api conversion function cimport numpy np npimportarray initialize c api call pyarraysimplenewfromdata cdef public api tonumpyarraydouble data long long size gil data size raise valueerror cdef npnpyintp dims size note take ownership data you must free data return nppyarraysimplenewfromdata ampdims npnpydouble voiddata it could used ctypes follows ctypes import pyfunctype pyobject pointer cdouble clonglong pydll cfunctype cbool cdll import pointerndarray tonumpyarray pyfunctypepyobject pointercdouble clonglong tonumpyarray pydllloadlibrarypointerndarrayfile cfunctypecbool pointercdouble clonglong def callbackdata size tonumpyarraydata size call scipy functions array return true cpplib cdllloadlibrarycallcallbackso c lib goes cpplibcallcallbackcallback where callcallback void callcallbackbool double long long,i c callback function calls python using ctypes this function parameters pointer array double number elements there lot elements approximately i need send scipy functions the c prototype bool ptsetdatasourcedouble long long following python code cpfsetdatasource cfunctypecbool pointercdoubleclonglong cpfsetselection cfunctypecboolccharp clonglongclonglong cpfresetsequence cfunctypecbool def setdatasourcedata datalength datalist range datalistidatai print datalist return true the problem print datalist returns correctdata filled lot numbers checked c side also i use code convert data python list locks computer allocate step is anyway load data c array convert array fit scipy,3 please foreign keys right thing never prevent database protecting consistency if need something special table sure break integrity temporarily disable checks set foreignkeychecks something set foreignkeychecks,create model foreign key relationship something like class postmodelsmodel title modelscharfieldmaxlength datecreated modelsdatetimefieldautonowfalse autonowaddtrue owner modelsforeignkeyuser syncdb dump models db creates table post foreign key table user how avoid creation foreign key mysql i hate foreign keys different reasons thank edit please guys answer you use foreign keys that asking i reasons use,1 try isolate creation connection consumer constructor give executed task import multiprocessing time psycopg class consumermultiprocessingprocess def initself taskqueue resultqueue multiprocessingprocessinitself selftaskqueue taskqueue selfresultqueue resultqueue selfpyconn psycopgconnectdbname geobase host localhost selfpyconnsetisolationlevel def runself procname selfname true nexttask selftaskqueueget nexttask none print tasks complete selftaskqueuetaskdone break answer nexttaskconnectionselfpyconn selftaskqueuetaskdone selfresultqueueputanswer return class taskobject def initself selfa def callself connectionnone pyconn connection pycursor pyconncursor procquery update city set gidfkey gid from country where stwithinselect thegeom from city where cityid countrythegeom and cityid selfa selfa pycursorexecuteprocquery print what self print selfa return selfa def strself return arc def runself print in,similar another post i made answers post creates new question recap i need update every record spatial database i data set points overlay data set polygons for point feature i want assign key relate polygon feature lies within so point new york city lies within polygon usa usa polygon gid i assign gidfkey point new york city okay achieved using multiprocessing i noticed increase speed using work but i think bunch unecessary overhead one db connection required record so code import multiprocessing time psycopg class consumermultiprocessingprocess def initself taskqueue resultqueue multiprocessingprocessinitself selftaskqueue taskqueue selfresultqueue resultqueue def runself procname selfname true nexttask selftaskqueueget nexttask none print tasks complete selftaskqueuetaskdone break answer nexttask selftaskqueuetaskdone selfresultqueueputanswer return class taskobject def initself selfa def callself pyconn psycopgconnectdbname geobase host localhost pyconnsetisolationlevel pycursor pyconncursor procquery update city set gidfkey gid from country where stwithinselect thegeom from city where cityid countrythegeom and cityid selfa selfa pycursorexecuteprocquery print what self print selfa return selfa def strself return arc def runself print in name main tasks multiprocessingjoinablequeue results multiprocessingqueue numconsumers multiprocessingcpucount consumers consumertasks results xrangenumconsumers w consumers wstart pyconnx psycopgconnectdbname geobase host localhost pyconnxsetisolationlevel pycursorx pyconnxcursor pycursorxexecute select count from cities where gidfkey is null temp pycursorxfetchall numjob temp numjobs numjob pycursorxexecute select cityid from city where gidfkey is null cityidlisttuple pycursorxfetchall cityidlistlist x cityidlisttuple cityidlistappendx xrangenumjobs tasksputtaskcityidlisti xrangenumconsumers tasksputnone numjobs result resultsget print result numjobs it looks seconds per connection i measure time module is way make db connection per process use cityid info variable i feed query cursor open this way i make say four processes db connection drop cityid somehow process,3 if i understand correctly task something related collaborative filtering there many possible approaches problem i suggest follow wikipedia page overview main approaches choose for project work i suggest looking python based intro neural networks simple backprop nn implementation classification example this solution perhaps build system example without need bigger framework,i planning implementing document ranker uses neural networks how one rate document taking consideration ratings similar articles any good python libraries can anyone recommend good book ai python code edit i planning make recommendation engine would make recommendations similar users well using data clustered using tags user would given chance vote articles there hundred thousand articles documents would clustered based tags given keyword articles would fetched based tags passed neural network ranking,3 use bytearray frame bytearray frameappendxa frameappendx frameappendx frameappendx frameappendx frame bytearrayb xaxxxx using code fixing errors frame b frame b xa frame b x frame b x frame b x frame b x,i need build tcp frame raw binary data examples tutorials i found talking bytes always involve conversion string i need in short i need build array bytes xa x x x x please note i come cc world i tried frame b frame bytes int xa frame bytes int x frame bytes int x frame bytes int x frame bytes int x then throw frame variable send method socket working expected frame contain i want i know basic question python could point right direction,3 simply constructing frame standard list frame bytesxaxxxx bytes constructor build byte frame iterable containing int values iterable anything implements iterator protocol list iterator iterable object like returned range,i need build tcp frame raw binary data examples tutorials i found talking bytes always involve conversion string i need in short i need build array bytes xa x x x x please note i come cc world i tried frame b frame bytes int xa frame bytes int x frame bytes int x frame bytes int x frame bytes int x then throw frame variable send method socket working expected frame contain i want i know basic question python could point right direction,3 frame b xaxxxx mentionned till,i need build tcp frame raw binary data examples tutorials i found talking bytes always involve conversion string i need in short i need build array bytes xa x x x x please note i come cc world i tried frame b frame bytes int xa frame bytes int x frame bytes int x frame bytes int x frame bytes int x then throw frame variable send method socket working expected frame contain i want i know basic question python could point right direction,2 apache subversion written c provides native libraries os on windows means dll subversion provides bindings number different languages including python this gives shim lets write code language bindings handle making calls native libraries to use python bindings need install python system also need make sure appropriate subversion native library path your python code load python bindings code load make calls native dll so path matching version there pure python version subversion,what alternative python svn bindings provided collabnet directories svn libsvn second lot precompiled libraries the problem configured run windows version python we done written various fora work at best would package written fully python compilation issues i know pysvn seems clientside functionality based checkouted code serverside based provided repository path svnlook,2 the python bindings need load native subversion libraries dll if python bit would need bit versions native subversion libraries path,i trying configure run svn postcommit hook sending mails i downloaded class mailerpy installed python svnwin bindings svn the machine windows bit python bit now mailerpy ends error caused import problem when i python console type import svncore i following error import svncore traceback recent call last file stdin line module file ctoolspythonlibsitepackagessvncorepy line module libsvncore import file ctoolspythonlibsitepackageslibsvncorepy line module import core importerror no module named core directory sitepackageslibsvn files coredll i installed bindings pysvn installed correctly far i noticed totally api i use pythonpy does someone similar problem knows deal,1 query first table ordering descending insertion time limiting results then query second table way then merge results python return first a django example could look like operator import attrgetter recentposts postobjectsorderby created recentcomments commentobjectsorderby created bothcombined listrecentposts listrecentcomments bothsorted sortedbothcombined keyattrgetter created reversetrue mostrecent bothsorted,i dashboard realtime updates latest notifications imagine blogging system subscribe authors posts comments i want type notifications appear dashboard sorted insertion time last posts last comments imagine i want updates show i load dashboard later updtes i getting ajax how i query database i sort results i thought querying tables posts comments data i subscribed add data list sort results datetime return last i feel good solution since would take lots time sort tables subscriptions begin grow what answersthoughts problem,1 the worked run python codepy import getopt sys def usage print nthis usage functionn print usage sysargv file option def mainargv try opts args getoptgetoptargv hiotbpms help input output opts print no options supplied usage except getoptgetopterrore print e usage sysexit opt arg opts opt h help usage sysexit name main mainsysargv,i problem usage function python this part main function def mainargv try opts args getoptgetoptargv hiotbpms help input output opts print no options supplied usage except getoptgetopterrore print e usage sysexit opt arg opts opt h help usage sysexit name main mainsysargv i define usage function well def usage print nthis usage functionn print usage sysargv file option i run code codepy codepy h executable i got anything python help,3 i know little late use boyermoore search first line small image lines large image the moment find match x y position check remainder lines smaller image match remainder lines larger image starting position x y at first mismatch continue search first line i think get faster,i trying use python determine one small image within another large image any suggestions i take completely wrong path edit ok ideas i using pil i converting image p mode i compare pixel integer i trying implement something like boyer–moore string search knuth–morris–pratt algorithm dimensions maybe help instead searching abc xxxabcxxx answer searching abc def ghi xxxxx xabcx xdefx xghix xxxxx answer,2 import mysqldb import mysqldbcursors connmysqldbconnecthost user root passwd root db test cursorconncursorcursorclass mysqldbcursorsdictcursor this rough hack may advisable use the script throw dictionary object default application might require tuple array,i trying execute following code import mysqldb import mysqldbcursors connmysqldbconnecthost user root passwd root db test cursorclass mysqldbcursorsdictcursor cursorconncursor but gives following error traceback recent call last file stdin line module file buildbdistlinuxxeggmysqldbconnectionspy line cursor attributeerror connection object attribute cursorclass why,2 one way stack frames top simply raise one stacking order the one top one visible this works best frames size little work get work sized frames here bit contrived example show general concept import tkinter tk python import tkinter tk python titlefont helvetica bold class sampleapptktk def initself args kwargs tktkinitself args kwargs container stack bunch frames top one want visible raised others container tkframeself containerpacksidetop fillboth expandtrue containergridrowconfigure weight containergridcolumnconfigure weight selfframes f startpage pageone pagetwo pagename fname frame fparentcontainer controllerself selfframespagename frame put pages location one top stacking order one visible framegridrow column stickynsew selfshowframestartpage def showframeself pagename show frame given page name frame selfframespagename frametkraise class startpagetkframe def initself parent controller tkframeinitself parent selfcontroller controller label tklabelself textthis start page fonttitlefont labelpacksidetop fillx pady button tkbuttonself textgo page one commandlambda controllershowframepageone button tkbuttonself textgo page two commandlambda controllershowframepagetwo buttonpack buttonpack class pageonetkframe def initself parent controller tkframeinitself parent selfcontroller controller label tklabelself textthis page fonttitlefont labelpacksidetop fillx pady button tkbuttonself textgo start page commandlambda controllershowframestartpage buttonpack class pagetwotkframe def initself parent controller tkframeinitself parent selfcontroller controller label tklabelself textthis page fonttitlefont labelpacksidetop fillx pady button tkbuttonself textgo start page commandlambda controllershowframestartpage buttonpack name main app sampleapp appmainloop over time people asked questions using code starting point you might want read answers questions understanding parent controller tkinter init tkinter understanding switch frames how get variable data class how would i make method run every time frame shown tkinter tkinter frame resize py tkinter code pages separate files,i built first scripts nice little gui tutorials shown none address complex program if something start menu opening screen upon user selection move different section program redraw screen appropriately elegant way does one destroy start menu frame create new one filled widgets another part and reverse process press back button,3 initialize flag loop inerror false then switch needed linestartswith error inerror true elif linestartswith end error printline inerror false inerror printline,i piece code reads last line log file log written i want print errors occur logs basically start printing linestartswith error finish printing linestartwith end error my code could anybody help please log cmyloglog file openlog r res osstatlog size res fileseeksize filetell line filereadline line timesleep fileseekwhere else linestartswith error print lines come end error,1 djangonani brandnew application fast wellwritten using probably best design approach it still development works well complete documentation this snippet see multilingual models defined djangodb import models nanimodels import translatablemodel translatedfields class djangoapplicationtranslatablemodel name modelscharfieldmaxlength uniquetrue author modelscharfieldmaxlength translations translatedfields description modelstextfield descriptionauthor modelscharfieldmaxlength def unicodeself return selfname,i developing new project scratch django i see many apps handling translation dynamic content djangomultilingual djangopluggablemodelin djangomodeltranslation transdb djangomultilingualmodel djangotransmeta name transdb transmeta multilingual sounded fair i want read personal experiences which one i choose,1 there two ways look question how i read keyvalue pairs python is standard way how i give full expressive power configuration script if question first obvious answer use configparser module configparser import rawconfigparser parser rawconfigparsermyvar defaultvalue never use configparserconfigparser parserreadmyconfig myvar parsergetmysection myvar which would read value file looks like normal ini style config you use comments mysection myvar specialvalue for second option really want give full power python configuration rare sometimes necessary you probably want use import instead use execfile config execfilemyconfig config myvar configgetmyvar defaultvalue which turn read python script read global variable myvar matter script derives import random myvar randomchoicespecialvalue anothervalue,in shell script one might something like myvar defaultvalue source myfilesh echo myvar myfilesh something like echo myvar specialvalue myfilesh i know several safe ways python way i think getting similar behaviour python albeit ugly unsafe following myvar defaultvalue myimport import myfile execmyimport printmyvar myfilepy looks like myvar specialvalue i guess i would happiest something like mmyvar defaultvalue mupdateimportmyimport objects updated i think easy way without writing something loop objects,2 it likely textmate using different pythonpath terminal i textmate user i help point right direction,i installed lxml parsing xml file python i using textmate ide problem i try import lxml lxml import entree i get importerror no module named lxml but i use terminal everything fine python va jun gcc apple inc build dot darwin type help copyright credits license information lxml import etree rootetreeelementroot rootetreeelementroot print roottag root rootappendetreeelementchild child etreesubelementroot child child etreesubelementroot child print etreetostringrootprettyprinttrue root child child child root it pretty weird does something textmate suggestion please,1 you need define shell variables textmate settings specifically tmpython needs point python binary to find python using terminal could type python,i installed lxml parsing xml file python i using textmate ide problem i try import lxml lxml import entree i get importerror no module named lxml but i use terminal everything fine python va jun gcc apple inc build dot darwin type help copyright credits license information lxml import etree rootetreeelementroot rootetreeelementroot print roottag root rootappendetreeelementchild child etreesubelementroot child child etreesubelementroot child print etreetostringrootprettyprinttrue root child child child root it pretty weird does something textmate suggestion please,1 this probably means one python installation system textmate terminal using different ones default one workaround in python file specify interpreter directive point python installation executable choice usrlocalbinpython even thought standard python usrbinpython want another,i installed lxml parsing xml file python i using textmate ide problem i try import lxml lxml import entree i get importerror no module named lxml but i use terminal everything fine python va jun gcc apple inc build dot darwin type help copyright credits license information lxml import etree rootetreeelementroot rootetreeelementroot print roottag root rootappendetreeelementchild child etreesubelementroot child child etreesubelementroot child print etreetostringrootprettyprinttrue root child child child root it pretty weird does something textmate suggestion please,2 import matplotlibpyplot plt pltgetfignums windows open else windows,i using matplotlib interactive mode show user plot help enter range variables they option hitting show plot prompt variables repeated how i know redraw plot still displayed superficially i clunky pseudoish code answer none doneplot false answer none answer getanswer answer doneplot haveclosed true user already requested plot closed check needed haveclosed haveclosed false print you already plot display redraw answer none continue pltion fig pltfigure plotting stuff doneplot true answer none else answer user i use terms pltgca fig etc determine i need replot is status somewhere i check many thanks david,3 you use osenviron example path osenvironpath separated string path varcustombin osenvironpath path or single line osenvironpath joinosenvironpathsplit varbin,how i change environmental path variable code python i trying return path executable file the code work shell pointing another directory any help appreciated,2 you looking path variable you want either set current working directory oschdir pass absolute path ospathabspath,how i change environmental path variable code python i trying return path executable file the code work shell pointing another directory any help appreciated,1 osenvironpath usrlocalbin see httpdocspythonorglibraryoshtmlosenviron,how i change environmental path variable code python i trying return path executable file the code work shell pointing another directory any help appreciated,1 when call fileread read entire file memory then call fileread file object already reached end file return empty string instead try eg reopening file stringio import file open bmp r print fileread n fileclose file open bmp r print stringiofilereadgetvalue fileclose you also use statement make code cleaner stringio import open bmp r file print fileread n open bmp r file print stringiofilereadgetvalue as aside i would recommend opening binary files binary mode open bmp rb,i seem get different outputs stringio import file open bmp r print fileread n print stringiofilereadgetvalue why is stringio supports text strings something,3 the second fileread actually returns empty string you fileseek rewind internal file offset,i seem get different outputs stringio import file open bmp r print fileread n print stringiofilereadgetvalue why is stringio supports text strings something,2 if using bash regular grep escape chars ie grep bob error weberrorsgrailsexceptionresolver exception occurred processing request get bobevent catalinaout not sure really asking search minute time period andor displayed next three lines beneath error it help answers supplied show sample input sample output i hope helps,i python script reports many times error shows catalinaout within minute time period some errors contain information displayed next three lines beneath error unfortunately sentence i grepping contains i want search using regular expressions is way turn regular expression function exact search here example sentence im searching bob error weberrorsgrailsexceptionresolver exception occurred processing request get bobevent thanks,1 something like abc def abcdef w abc xxx def yyy def replacetext words regex rb joinreescapeword word words rb reobj recompileregex rei return reobjsublambda xwordsxgroup text replaces w xxx yyy abcdef note works reliably dictionary keys start end letter digit underscore otherwise b word boundaries fail match,i trying build dictionary frequent terms website so basically i retrieve paragraph database paragraph likely contain terms appear aforementioned dictionary what i looking nice way fast parse paragraph text map dictionary terms might appear text dictionary entries is python module assist task i looking something fancy must fast thanks,1 assuming using standard grep command is way turn regular expression function exact search sure pass f flag grep like grep f get catalinaout remember put search term quotes else bash interpret brackets special way,i python script reports many times error shows catalinaout within minute time period some errors contain information displayed next three lines beneath error unfortunately sentence i grepping contains i want search using regular expressions is way turn regular expression function exact search here example sentence im searching bob error weberrorsgrailsexceptionresolver exception occurred processing request get bobevent thanks,1 you use java json serializer like gson jackson serilaise quite easily use python json pickle deserialize,i using python service uses pickled messages part protocol i like query service java i need pickle message client java are implementations pickle run jvm ideally minimal dependencies clarification modifying server side option alternate serializations would convenient solve problem,1 note answer obsolete setuptools works python distribute deprecated setuptools work python but use distribute fork drop replacement setuptools httppackagespythonorgdistribute httppypipythonorgpypidistribute from bottom page install distribute curl o httppythondistributeorgdistributesetuppy python distributesetuppy,will setuptools windows python httppypipythonorgpypisetuptoolsfiles compatible python x runtime the installer fails detect python settings install should i wait new release,3 the xlrd xlwt xlutils packages mentioned read write xls files size limitations rows columns aside good tool but i moved another pythonexcel package openpyxl read write xlsx files also i find easy use documentation good openpyxl httppackagespythonorgopenpyxlindexhtml,i recently taken project teach program python overall i must say i impressed in past i typically stuck programming vba mostly ms excel also bit ms access word struggled find ways make things python easily single command i wondering reasonable way harness programming power ease python time make use various tools office mostly excel,2 i agree quite broad question i’ll try address many parts anyway about subjective statement i don’t see simplicity elegance python would imply packaging deployment matters suddenly become simple things some things related packaging simple could it would best users one complete robust easy packaging system hasn’t turned way distutils created development paused setuptools created added new solutions new problems distribute forked setuptools social problems finally distutils created make one official complete library more differences distribute distutils setuptools the situation far ideal developers users working making better how best multiple versions python machine use package manager you’re modern os use “make altinstall” compile source unix use similar nonconflicting installation scheme compile source windows as debian user i know i call individual versions using “pythonxy” default versions “python” “python” decided debian developers a oses started break assumption python python pep progress bless condemn httpwwwpythonorgdevpepspep windows seems lack way use one python version default there’s another pep httpwwwpythonorgdevpepspep where packages installed using distutils i install projects user sitepackages directory see pep docspythonorg what exactly question parallel installation different versions project supported it would need pep discuss changes import system packaging tools before someone starts discussion using virtualenv buildout works well enough i don’t understand question location “components python environment” i mostly use system packages ie using aptitude package manager debian to try projects i clone repository if i need something that’s available aptitude i install put pth file repo user sitepackages directory i don’t need custom pythonpath i changed location user sitepackages pythonuserbase i don’t like magic eggs concept setuptoolsdistribute i don’t use i’ve started use virtualenv pip one project though use setuptools cover i made private install global python setuptools,many posts different aspects question i seen post brings together first subjective statement seems like simplicity experience working python language shot pieces move outside interpreter start grappling deployment issues how best multiple versions python machine where packages installed disutils vs setuptools vs pip etc it seems like zen python abused pretty badly comes deployment i feeling eerie echoes dll hell experience windows do experts agree degree best practice questions do run multiple versions python machine how remain confident coexist newer version break assumptions processes rely earlier version scripts provided os vendor example is safe does virtualenv suffice what best choices locations different components python environment including rd party packages local file system is strict rough correspondence locations many different versions unixy windows os relied upon and murkiest corner swamp install tools use setuptools distutils pip etc play well choices file locations python virtual environments python path etc these sound like hard questions i hopeful experienced pythonistas may defined canonical approach two challenges any approach hangs together system used confidence feeling less like separate unrelated tools would helpful,1 float default data type numpy you could try using float precision warned certain functions basically everything windows coerce float anyway i would recommend using scipysparse sparse eigenvector problems i tried pysparse scipysparse i would conclude although pysparse easier use scipysparse mature here sparse linear algebra documentation httpdocsscipyorgdocscipyreferencesparselinalghtml,i started using numpy along pysparse package interfaces umfpack however problem floating point results numpy by way lanczos eigenvalue solver structural problems when i operations matlab i get different results well results order ee matlab representation i get right eigenvalues numpy pysparse results also far least order level however using create triadiagonal matrix find eigenvalues source problem i could understand going wrong well issue floating point representation fix possible i tried use float datatype make change results problem such q onesn dtype float one mature sparse package python kind interfaces provided as told pysparse seemed fine first sight,1 when use create method default model manager django also attempt create instance database save you two ways i show approach may help understanding first want create userhistory object actually save this done simply instantiating model class default values like b userhistoryuseri after set attributes bpointsearned randomrandint bdatetime datetimedatetimenow bsave and work because saving b set datetime there ways improve course simply create everything one call since one logical step like b userhistoryobjectscreate useri pointsearnedrandomrandint datetimedatetimedatetimenow you improve reading datefield docs django give tips set default date current time hope helps,following modelspy class userprofilemodelsmodel user modelsonetoonefielduser belongstousercategory modelsforeignkeyusercustomcategory nulltrue blanktrue class userhistorymodelsmodel datetime modelsdatetimefield user modelsforeignkeyuserprofile nulltrue blanktrue pointsearned modelsdecimalfieldmaxdigits decimalplaces clear userhistory foreign key userprofile for test purpose wanted update points user whose name starts i wrote following code python shell myappmodels import uobj userprofileobjectsall uobj iuserusername b userhistoryobjectscreateuseri bpointsearned randomrandom bdatetime datetimedatetimenow bsave also tried b userhistoryobjectsgetorcreateuseri error get following error error an unexpected error occurred tokenizing input the following traceback may corrupted invalid the error message eof multiline statement error an unexpected error occurred tokenizing input the following traceback may corrupted invalid the error message eof multiline statement error an unexpected error occurred tokenizing input the following traceback may corrupted invalid the error message eof multiline statement error internal python error inspect module below traceback internal error traceback recent call last file usrlocallibpythondistpackagesipythonultratbpy line text localsformatvaluevarrepr file usrlibpythoninspectpy line formatargvalues specsappendstrseqargsi convert join file usrlibpythoninspectpy line strseq return convertobject file usrlibpythoninspectpy line convert return formatargname formatvaluelocalsname keyerror connection ipython exception reporting continues integrityerror traceback recent call last integrityerror column datetime cannot null,1 this intentional choice within django regardless value debug setting configuration file django tests run debugfalse this ensure observed output code matches seen production setting ref httpsdocsdjangoprojectcomendevtopicstestingothertestconditions,python django i getting odd localsettings behavior i testing django app i projectsettingspy set like debug false templatedebug debug admins me memecom managers admins person personblahcom rest settings try localsettings import except importerror pass projectlocalsettingspy i debug true managers me memecom so working locally managers setting me memecom debug set true however tests one apps i testing settingsdebug getting false managers setting set correctly me any ideas would happen here relevant parts projectapptestspy file djangoconf import settings djangotest import testcase class myteststestcase def mytestself settingsdebug selfassertequalsettingsmanagers me memecom else selfassertequalsettingsmanagers me memecom person personblahcom the result assertionerror me memecom me memecom person personblahcom so looks like testing else branch due settingsdebug set incorrectly raising assertionerror since settingsmanagers set correctly if i run python managepy shell i get djangoconf import settings settingsdebug true settingsmanagers me memecom so set correctly i know i override settings manually tests i wanted try use settingsdebug test would pass matter whether run locally production any ideas,3 setattrinstance name value syntactic sugar instancesetattrname value you would need call objectsetattr inside class definition directly subclassing object subclassing something else spam example either use super get next item heirarchy call spamsetattr way risk missing behavior superclasses defined skipping directly object,i know call objectsetattr objects inherited object anything else different two i working python matters,3 this start started false collectedlines openpath r fp line enumeratefpreadlines linerstrip start started true print started line counts zero continue started linerstripend print end line break process line collectedlinesappendlinerstrip the enumerate generator takes generator enumerates iterations eg print listenumeratea b csplit prints b c update poster asked using regex match lines like import print rematch none print rematch none print rematch none print rematch abc none print rematch abc none,i talking specific line numbers reading multiple files format vary length say text file something start i want block text b c e f g h j k l n end line file something i hope know mean thinking iterating file search using regular expression find line number start end use linecache read start line end line but get line number function use,1 agf bytearray solution workable find needing build complicated packets using datatypes bytes try structpack httpdocspythonorgreleaselibrarystructhtml,i need build tcp frame raw binary data examples tutorials i found talking bytes always involve conversion string i need in short i need build array bytes xa x x x x please note i come cc world i tried frame b frame bytes int xa frame bytes int x frame bytes int x frame bytes int x frame bytes int x then throw frame variable send method socket working expected frame contain i want i know basic question python could point right direction,1 here something work datafile opentesttxt block found false line datafile found block line linestrip end break else linestrip start found true block start datafileclose,i talking specific line numbers reading multiple files format vary length say text file something start i want block text b c e f g h j k l n end line file something i hope know mean thinking iterating file search using regular expression find line number start end use linecache read start line end line but get line number function use,2 as gsk noted bigmemory great package along packages biganalytics bigtabulate worth checking there also ff though easy use common r python support hdf see ncdf netcdf packages r makes speedy easy access massive data sets disk personally i primarily use bigmemory though r specific as hdf available python fast probably going best bet python,in python environment rpy scipy packages already installed the problem i want tackle a huge set financial data stored text file loading excel possible i need sum certain fields get totals i need show top rows based totals which package scipy rpy best suited task if could provide pointers eg documentation online example help implement solution speed concern ideally scipy rpy handle large files even files large cannot fitted memory,1 if simply want block text start end something simple like open testtxt inputdata skips text beginning interesting block line inputdata linestrip start or whatever test needed break reads text end block line inputdata this keeps reading file linestrip end break print line line extracted blockoflinesappendline etc in fact need manipulate line numbers order read data start end markers the logic read until… repeated blocks quite clear efficient methods typically involve checking state blockwithin blockend block reached incurs time penalty,i talking specific line numbers reading multiple files format vary length say text file something start i want block text b c e f g h j k l n end line file something i hope know mean thinking iterating file search using regular expression find line number start end use linecache read start line end line but get line number function use,3 in vein unutbu answer also check whether given figure still opened import matplotlibpyplot plt pltfignumexistsfigure number figure still opened else figure closed the figure number figure fignumber ps note number figurenum… actually string displayed window title however figure still number attribute numeric original string num value cannot used fignumexists pps that said subplots… numstring num properly recovers existing figure given string number thus figures still known string number parts matplotlib fignumexists use strings,i using matplotlib interactive mode show user plot help enter range variables they option hitting show plot prompt variables repeated how i know redraw plot still displayed superficially i clunky pseudoish code answer none doneplot false answer none answer getanswer answer doneplot haveclosed true user already requested plot closed check needed haveclosed haveclosed false print you already plot display redraw answer none continue pltion fig pltfigure plotting stuff doneplot true answer none else answer user i use terms pltgca fig etc determine i need replot is status somewhere i check many thanks david,3 p x xyf y fxy var p x is looking,i working program user inputs values one dictionary notation form i trouble finding work special notation the user input look like x xyf y fxy i store variable p i know pkeys i get x y pvalues i get xyf fxy how i relate x xyf say value first key p x store xyf var value second key p y store fxy var is something like also possible approach stated answers if x found string swap x value p x,1 are asking get value associated particular key you acess value putting key square brackets mydict x xyf y fxy myxval mydict x myyval mydict y print myxval myyval output xyf fxy if want different behavior based keys exist dict use x mydict stuff mydict x edit response op edit my psychic debugging powers tells trying implement l system you need replace instances x xyf instances y fxy i would implement function like path string want replacements replacementdict dict containing keyvalue pairs mentioned post def iteratelsystempath replacementdict strings mutable make mutable list version path listpath listpath rangelenlistpath currentchar listpathi currentchar replacementdict listpathi replacementdictcurrentchar glob listpath back single string return joinlistpath,i working program user inputs values one dictionary notation form i trouble finding work special notation the user input look like x xyf y fxy i store variable p i know pkeys i get x y pvalues i get xyf fxy how i relate x xyf say value first key p x store xyf var value second key p y store fxy var is something like also possible approach stated answers if x found string swap x value p x,1 regular expressions take ranges like you want something like year presto i flippant trying use regular expression use straightforward comparison if string convert string integer first even need python otherwise going really ugly regular expression hard maintain edit if really keen using regular expression three problem broken three regular expressions dd fourcharacter years you could combine dddd but note regular expression ugly hell b accepts years you mitigate judicious use something like ddd could work but i hope find year lot better edit hell regex wrong years greater you probably want use dddd and still work enter year like,i writing regular expression validate year starting the regular expression i wrote it seem work can anyone point i get wrong,3 you call sorted function values datetime comparison key sorteddvalues keylambda item itemlcreatedon,how sort dict per datetime is possible l createdon datetimedatetime l createdon datetimedatetime l createdon datetimedatetime,2 internally calls equivalent import os import sys f ospopen file b sysexecutable osdevnull fread fclose for popen work able get sigchld signal telling child process exited it seems environment executes iotop custom reaper process intercepts sigchld prevents python getting notified process exiting thus function calls close python tries kill process already dead gets error operating system if cannot reconfigure environment let sigchld pass i think ro resort ugly hacking wrapping iotop script monkeypatches platformarchitecture function always returns tuple something like bit elf —consult output real architecture let progress alternatively make local copy platformpy file edit directly setting pythonpath cron job point new file,i csf installed configure safe firewall function allow custom scripts executed load average events my script usrbinenv bash iotop bto iter amp mail hostname iotop output incidents it works fine via bash shell executed lfd monitoring process csf i get following output traceback recent call last file usrbiniotop line module iotopui import main file usrlibpythonsitepackagesiotopuipy line module iotopdata import finduids taskstatsnetlink processlist stats file usrlibpythonsitepackagesiotopdatapy line module iotop import ioprio vmstat file usrlibpythonsitepackagesiotopiopriopy line module nrioprioget findiopriosyscallnumberiopriogetarchsyscall file usrlibpythonsitepackagesiotopiopriopy line findiopriosyscallnumber bits platformarchitecture file usrlibpythonplatformpy line architecture output syscmdfileexecutable file usrlibpythonplatformpy line syscmdfile rc fclose ioerror errno no child processes can anyone shed light,1 you sort dict the dict implict order print dicta b c c b if want keep full structure dict flatten dict dd list li first then sort datetime value key import operator dd li dditems l ititems c dt ititems liappendi l c dt lisortkeyoperatoritemgetter print li,how sort dict per datetime is possible l createdon datetimedatetime l createdon datetimedatetime l createdon datetimedatetime,1 you get sorted list keys dictionary dictionaries cannot sorted sorteddkeys keylambda k dk l createdon ps if really need dictionary sorted keys standard ordereddict type friend described comments rocksportrocker agf frã©dã©ric answer,how sort dict per datetime is possible l createdon datetimedatetime l createdon datetimedatetime l createdon datetimedatetime,2 not certain python wrt regex work like thinkingranges single character so reason must regexp ie sort regexp datafilled validation engine any number,i writing regular expression validate year starting the regular expression i wrote it seem work can anyone point i get wrong,1 here example issues warning import numpy np npseterrall warn a nparray aa aa yields runtimewarning overflow encountered longscalars in example happens dtype int maximim value storable int since exponentiation results number bigger stored int note rely npseterrall warn catch overflow errors numpy for example bit numpy npmultiplyreducenparange bit numpy npmultiplyreducenparange both fail without warning although also due overflow error the correct answer equals in import math in mathfactorial out l according numpy developer robert kern unlike true floating point errors hardware fpu sets flag whenever atomic operation overflows need implement integer overflow detection we scalars arrays would slow implement every atomic operation arrays so burden choose appropriate dtypes operation overflows,i new programming latest python project i encountered following runtimewarning overfow encountered longscalars could someone please elaborate means i could fix the code runs i sure good idea ignore warning it happens append process like somelistappendverylongformula thanks comments best t,3 you use items iteritems walk pairs p x xyf y fxy k v piteritems print k v y fxy x xyf if want check existence key use keyword x p true y p print p y fxy,i working program user inputs values one dictionary notation form i trouble finding work special notation the user input look like x xyf y fxy i store variable p i know pkeys i get x y pvalues i get xyf fxy how i relate x xyf say value first key p x store xyf var value second key p y store fxy var is something like also possible approach stated answers if x found string swap x value p x,1 you walk dictionary using items method key value pitems print key value x xyf y fxy …,i working program user inputs values one dictionary notation form i trouble finding work special notation the user input look like x xyf y fxy i store variable p i know pkeys i get x y pvalues i get xyf fxy how i relate x xyf say value first key p x store xyf var value second key p y store fxy var is something like also possible approach stated answers if x found string swap x value p x,1 the following code works well default class object hashable class fooobject def initself pass myinstance foo mydict myinstance hello world print mydictmyinstance output hello world in addition advanced usage read post object dictionary key,i want use class instance dictionary key like classinstance class dictionaryclassinstance hello world python seems able handle classes dictionary key i wrong in addition i could use tuplelist like classinstance helloworld instead dictionary looks unprofessional do clue fixing issue,1 your instances need hashable the python glossary tells us an object hashable hash value never changes lifetime needs hash method compared objects needs eq cmp method hashable objects compare equal must hash value hashability makes object usable dictionary key set member data structures use hash value internally all python’s immutable builtin objects hashable mutable containers lists dictionaries objects instances userdefined classes hashable default compare unequal hash value id,i want use class instance dictionary key like classinstance class dictionaryclassinstance hello world python seems able handle classes dictionary key i wrong in addition i could use tuplelist like classinstance helloworld instead dictionary looks unprofessional do clue fixing issue,3 there nothing wrong using instance dictionary key long follows rules a dictionary key must immutable,i want use class instance dictionary key like classinstance class dictionaryclassinstance hello world python seems able handle classes dictionary key i wrong in addition i could use tuplelist like classinstance helloworld instead dictionary looks unprofessional do clue fixing issue,1 try implementing hash eq methods class for instance simple hashable dictionary class i made class hashabledict def initself selfmydict selfmyfrozenset frozensetditems def getitemself item return selfmydictitem def hashself return hashselfmyfrozenset def eqself rhs return isinstancerhs hashabledict selfmyfrozenset rhsmyfrozenset def neself rhs return self rhs def strself return hashabledict strselfmydict def reprself return selfstr,i want use class instance dictionary key like classinstance class dictionaryclassinstance hello world python seems able handle classes dictionary key i wrong in addition i could use tuplelist like classinstance helloworld instead dictionary looks unprofessional do clue fixing issue,2 why use python client library directly it includes set methods exactly want import gdatacontactsclient import gdatacontactsdata might also need atomdata gdatadata gdclient gdatacontactsdatacontactsclientsource equinoxcontacts gdclientclientlogin equinoxgmailcom password feed gdclientgetgroups entry feedentry print atom id groupidtext print group name grouptitletext entrysystemgroup print edit link entrygeteditlinkhref print etag entryetag else print system group id entrysystemgroupid does solve problem it cleaner way if still trouble reason my contacts show documentation note the feed may contain user contact groups default limit number results returned for information see maxresults query parameter retrieving contact groups using query parameters note the newer documentation includes sample python code sidebyside protocol explanation python code helps wrap head around generic protocol,i wrote small python script gets groups google contacts list however reason my contacts show i using api similar problems api the following except taken google contacts documentation to determine my contacts group id example retrieve feed groups given user find group entry subelement take value group entry element currently response i get gcontactsystemgroup tag anywhere how i proceed order get group id particular group my script shown userblahgmailcom pasblah dataemailuser passwdpas service cp sourcetester import urllib data urlliburlencodedata import urllib req urllibrequest httpswwwgooglecomaccountsclientlogin data resp urlliburlopenreq x respread authasplit req urllibrequest httpswwwgooglecommfeedsgroupsblahgmailcomfull headers authorization googlelogin auth auth resp urlliburlopenreq x respread print x print my contacts x print gcontactsystemgroup x some clues i could troubleshoot would awesome thanks,1 is pythonic way write getitem following only slightly getitem used sequences int slice used mappings pretty much anything used it looks like implementing sequencetype mappingtype interfaces stuck checking type missing two things support slices put want that support raising exception failure returning none case pythonic here updated getitem def getitemself x isinstancex int return selfthislistx elif isinstancex slice return selfthislistslice elif isinstancex str selfthislist thisname x return return none raise keyerrorinvalid key r x at point two possible exceptions raised indexerror x outside range thislist keyerror name found something besides str int passed this may fine might want create custom exception gets returned cases class lookuperrorexception x neither int str matching this instance found here updated code python x class lookuperrorindexerror keyerror x neither int str matching this instance found class this def initself name value selfname selfvalue name value class thatobject def initself selfthislist def addthisself selfthislistappendthis def getitemself x try isinstancex int return selfthislistx elif isinstancex slice return selfthislistslice elif isinstancex str selfthislist thisname x return raise keyerrorinvalid key r x except indexerror keyerror err raise lookuperrorerrmessage this b this b c that caddthisa caddthisb print cname print c name try print c except lookuperror e print e try print c c except lookuperror e print e,is pythonic way write getitem following the issue checking type different things depending type parameter call class this def initself name value selfname selfvalue name value class that def initself selfthislist def addthisself selfthislistappendthis def getitemself x isinstancex int return selfthislistx could wrap tryexcept error checking elif isinstancex str selfthislist thisname x return return none this b this b c that caddthisa caddthisb print cname print c name,1 python reduce function always know default initial value there version takes initial value supply sensible initial value reduce work beautifully also comments probably use factorial second argument lambda reducelambda xy x factorialy lst,i attempting write function calculates number unique permutations string for example aaa would return abc would return i writing method like pseudocode lenstring abc abc number occurrences unique character for example string aaa would abc would my code far like def permutationsn returns number unique permutations n math import factorial lst n strn l setn lstappendncountl return factoriallenn reducelambda xy factorialx factorialy lst everything works fine except i try pass string one unique character ie aaa i get wrong answer perm abc perm aaa perm aaaa now i tell problem running lambda function factorials list length i know though most lambda functions works list length even expecting two elements reducelambda xy x reducelambda xy x this one reducelambda xy ordx ordy reducelambda xy ordx ordy b is something i differently i know i rewrite function many different ways circumvent eg using lambda i looking specifically work,1 if want lens abc use reduce work calculate factorialfactorialafactorialbfactorialc in words really needs operation commutative instead need generate list factorials multiply together import operator reduceoperatormul factorialx x lst,i attempting write function calculates number unique permutations string for example aaa would return abc would return i writing method like pseudocode lenstring abc abc number occurrences unique character for example string aaa would abc would my code far like def permutationsn returns number unique permutations n math import factorial lst n strn l setn lstappendncountl return factoriallenn reducelambda xy factorialx factorialy lst everything works fine except i try pass string one unique character ie aaa i get wrong answer perm abc perm aaa perm aaaa now i tell problem running lambda function factorials list length i know though most lambda functions works list length even expecting two elements reducelambda xy x reducelambda xy x this one reducelambda xy ordx ordy reducelambda xy ordx ordy b is something i differently i know i rewrite function many different ways circumvent eg using lambda i looking specifically work,1 see documentation reduce optional initializer argument placed elements list behavior one element lists consistent example ord lambda could set initializer character ord reducelambda x ordx ordy chr,i attempting write function calculates number unique permutations string for example aaa would return abc would return i writing method like pseudocode lenstring abc abc number occurrences unique character for example string aaa would abc would my code far like def permutationsn returns number unique permutations n math import factorial lst n strn l setn lstappendncountl return factoriallenn reducelambda xy factorialx factorialy lst everything works fine except i try pass string one unique character ie aaa i get wrong answer perm abc perm aaa perm aaaa now i tell problem running lambda function factorials list length i know though most lambda functions works list length even expecting two elements reducelambda xy x reducelambda xy x this one reducelambda xy ordx ordy reducelambda xy ordx ordy b is something i differently i know i rewrite function many different ways circumvent eg using lambda i looking specifically work,1 one way solve store money values cents integers convert decimal representation printing values this called fixed point arithmetic,how i get decimals stay places representing money using decimal module i setting precision damn near everything else met failure,1 when working money usually want limit precision late possible things like multiplication aggregate rounding errors in python quantize decimal precision want unitprice decimaldecimal quantity decimaldecimal price unitprice quantity cents decimaldecimal money pricequantizecents decimalroundhalfup,how i get decimals stay places representing money using decimal module i setting precision damn near everything else met failure,3 you almost always better testing behavior kind item want rather explicitly testing type in case i simply try get desired item index first catch typeerror check name def getitemself key try return selfthislistkey except typeerror try return nextitem item selfthislist itemname key except stopiteration raise keyerrorkey found key note automatically work slices since case key slice object work fine notation you probably using dict rather list inside class though rather searching list object attribute exceptions would really need slicing names changed code outside class another perhaps slightly unconventional possibility implement special method eq this class allowing compared string class name attribute say jerry thisjerry jerry then actually need container class use regular list class thisobject def initself name value selfname selfvalue name value def eqself return selfname thislist thisjerry thisamy jerry thislist true thislistindexamy the syntax accessing item name still little hairy thislistthislistindexamy but simply subclass list combine previous suggestion becomes simpler generic since works object knows compare whatever kind key using class thatlist def getitemself key try return listgetitemself key except typeerror return listgetitemself selfindexkey thislist thatthisjerry thisamy thislistamyvalue,is pythonic way write getitem following the issue checking type different things depending type parameter call class this def initself name value selfname selfvalue name value class that def initself selfthislist def addthisself selfthislistappendthis def getitemself x isinstancex int return selfthislistx could wrap tryexcept error checking elif isinstancex str selfthislist thisname x return return none this b this b c that caddthisa caddthisb print cname print c name,1 you use regex pretty easily you make robust needed simple example import start end hello test somensample textnthat thenwords hello worldn recompiler ss startendres msearchtestgroup somensample textnthat thenwords hello,i talking specific line numbers reading multiple files format vary length say text file something start i want block text b c e f g h j k l n end line file something i hope know mean thinking iterating file search using regular expression find line number start end use linecache read start line end line but get line number function use,1 import recompiler txt pattern yourpattern recompiler pattern file filtermsearch oslistdirsomedir msearchopenfile r read print file contains pattern else print file contain pattern modify output per tastes,wanna read files hard drive find pattern like see file contains string return true return false in function call print nicely saying found filetxt etc came far import os path folder oslistdirpath n def blapattern book folder book txt data openpath bookread pattern sanitizedata ypattern book contains pattern return true else npattern book contain pattern return false bla jane printy jane printn jane desired output txt contains txt contain txt contains txt contain works without return true return false thingy desired any better way than this import os path folder oslistdirpath def blapattern book folder book txt data openpath bookread pattern sanitizedata printbook contains pattern else printbook contain pattern bla,1 try mydatadtypenames this return tuple field names in mydatadtypenames out time fx fy fz,let say i data file called datatxt looks like time fx fy fz in python run import numpy np mydata npgenfromtxtdatatxt namestrue print mydatatime the names top data file vary i would like find names arrays data file so i would like something like print mydatanames time f f f i thought read data file get first line parse separate operation seem efficient elegant,3 it possible performance difference may significant enough worry you make simple test concerned performance use python timeit module test performance cases,say i object called tag i three types tags indicated instance variable following way class tagobject def initself name type selfname name selftype type tagblue cold tagred warm tagblack hot let say i allowed three types cold warm hot would better go checking one types like ttype cold something elif ttype warm something else else ttype hot something even elser or i create enumlike object like one question class type cold warm hot and instead create tags like tagblue typecold the reason i ask question i heard lot processing power goes comparing strings even though short letter long words possible i making tens thousands comparisons types do think worth go creating enum objects determining type object example i shown or better way i attempting,1 ted wrote for validate empty value am i correct yes correct ted wrote when i attempt execute python returns true empty value am i wrong somewhere the empty string get matched the following snippet usrbinenv python import n xrange ones n matches rematchr ones matches div n matchesgroup none else lenmatchesgroup div div else lenonesdiv print formatn div div ones print and input matched matched group repeated least case repeated,i regular expression python since pipe i split regex for validate empty value am i correct for regex would validate value the first pair based second pair due when i attempt execute python returns true empty value am i wrong somewhere,1 groups it already part django authentication httpsdocsdjangoprojectcomentopicsauthgroups how i relate relate user you get profile user you get groups user relate primary central important entity think profile addon thing,i building site similar ebay i two kind users sellers buyers i read httpsdocsdjangoprojectcomentopicsauthstoringadditionalinformationaboutusers created userprofileabstract model two models seller buyer now model comment comment wrote sellers buyers how relate i thinking options expirience django maybe better idea class commentmodelsmodel createdby modelsforeignkeyuserprofile class commentmodelsmodel createdby modelsforeignkeyauthmodelsuser edit i want different classes seller buyer becouse different data,1 use official method use pickle instead,my program saves data external py file use later this works fine normally however converted executable saves file externally draws internal data this code looks like def savegame opensavepy save savewritevariables used later saveclose def loadgame import save reloadsave x savex in py creates savepy writes variables when loads variables imported exactly written after exe created creates savepy variables uses iteration savepy existed exe created is way achieve similar functionality converting app executable,1 i worried performance unless profiling shows indeed problem if using ide enum approach benefit typochecking,say i object called tag i three types tags indicated instance variable following way class tagobject def initself name type selfname name selftype type tagblue cold tagred warm tagblack hot let say i allowed three types cold warm hot would better go checking one types like ttype cold something elif ttype warm something else else ttype hot something even elser or i create enumlike object like one question class type cold warm hot and instead create tags like tagblue typecold the reason i ask question i heard lot processing power goes comparing strings even though short letter long words possible i making tens thousands comparisons types do think worth go creating enum objects determining type object example i shown or better way i attempting,1 random import random equivalent import random assigns module random local variable random randomrandom assigns method random module random you call module call method random module method name confusing humans syntax makes clear one mean,here program takes list words sorts longest shortest breaks ties random module import random def sortbylengthwords word words tappendlenword random word tsortreverse true res length randomm word resappendword return res i get error typeerror module object callable but i module import module it works why,1 random module random function when import random get module obviously callable when random import random get function callable that see error second case you test repl import random typerandom module random import random typerandom builtinfunctionormethod,here program takes list words sorts longest shortest breaks ties random module import random def sortbylengthwords word words tappendlenword random word tsortreverse true res length randomm word resappendword return res i get error typeerror module object callable but i module import module it works why,1 random import random equivalent import random random random randomrandom import random use randomrandom instead random,here program takes list words sorts longest shortest breaks ties random module import random def sortbylengthwords word words tappendlenword random word tsortreverse true res length randomm word resappendword return res i get error typeerror module object callable but i module import module it works why,2 i think would much easier map reduce input actual list words to achieve split string passing map then map word either mapper encounters palindrome none you filter results discard none values sort pass reduce reduce would reduce dict mapping words total count i provide working solution take away learning factor,i currently struggling assignment the solution would input txt file run counting number palindromes frequency i need use map reduce create for example string bab bab bab cab cac dad would output bab cab dad here i far def palindromestring palindromes word stringsplit word word palindromesappendword return palindromes string abc abd bab tab cab tat yay uaefdfdu print maplambda x palindromex bab abc dab bab bab dad crap pap pap currently prints bab bab bab dad pap pap here attempt far reduce section def plists list lists seth setlist return seth p function i want create set palindromes found then run count palindromes list make dict print reducep bab bab bab dad pap pap am i right track,2 after mx shell python ret ch k ret displayed help buffer say comintsendinput command executed ret if showing comintsendinput command executed ret probably something one init files emacs file init file overriding binding so try running emacs emacs nw q nositefile repeat if displaying comintsendinput previously displaying comintsendinput definitely something one init files look local httpwwwgnuorgsoftwareemacsemacslispintroelispinitfilehtmlinitfile sitewide httpwwwgnuorgsoftwareemacsemacslispintrohtmlnodesitedwideinithtmlsitedwideinit init files try find culprit if obvious examining files best bet rename init files find gradually reintroduce code find causing breakage,when i start pythonshell even start python mx shell emacs gives expected prompt bash python python r jun gcc based apple inc build llvm build darwin type help copyright credits license information but i type something prompt press ret cursor moves line command executed the commands i get subprocess respond interrupts like cc cc after interrupt another prompt appears i use mn mp navigate lines i entered earlier test hmmm definitely pressed enter cc cc keyboardinterrupt curiously occurs aquaemacs emacs nw i tried moving emacs emacsd files behavior any ideas might causing,2 i used nltk load wordnet neoj graph database see httpsgroupsgooglecomdtopicgremlinuserscoltgxcpodiscussion and i used bulbs httpbulbflowcom create library called wordgraph interacting neojwordnet rexster rest server httpsgithubcomtinkerpoprexsterwiki bulbs python library allows use graph programming language gremlin httpsgithubcomtinkerpopgremlinwiki querytraverse neoj case specifically wordnet i process posting wordgraph github httpsgithubcomespeedwordgraph message questions,i would like find relatedness similarity two words using python the hso hirst stonge lesk banerjee pedersen vector patwardhan algorithms implemented perl cant seem find python nltk lib i need use python part larger team project python any leads,2 for reduce function start empty dict updatepopulate counts reduce functions require parameters one dict palindrome you feed initial value reduce like reducelambda x xy somelist initialvalueforx take look dict get set default values help simplify reduce function lot,i currently struggling assignment the solution would input txt file run counting number palindromes frequency i need use map reduce create for example string bab bab bab cab cac dad would output bab cab dad here i far def palindromestring palindromes word stringsplit word word palindromesappendword return palindromes string abc abd bab tab cab tat yay uaefdfdu print maplambda x palindromex bab abc dab bab bab dad crap pap pap currently prints bab bab bab dad pap pap here attempt far reduce section def plists list lists seth setlist return seth p function i want create set palindromes found then run count palindromes list make dict print reducep bab bab bab dad pap pap am i right track,1 if i understood correctly following produce result looking need edit attribute names def unicodeself return u formatselficon selfattrib selfattrib,i new django building first app i want locations admin section displayed combination different attributes model currently shown icon using following code def unicodeself return selficon i want able add two attributes code result look like iconattribute attribute how i edit code,1 first call toplevel unit test package test that name python unit tests never able run tests installed configuration depending python set may end importing python tests instead second syspath vast subtle mystery trial supports running files directories quick gettingstarted hack never really completely correct using path names the right thing pass trial module package name import python module inspect so directory structure looks like projectsmyproject projectsmyprojectmyproject projectsmyprojectmyprojectinitpy projectsmyprojectmyprojectstuffpy projectsmyprojectmyprojecttest projectsmyprojectmyprojecttestinitpy projectsmyprojectmyprojecttestteststuffpy run tests like pythonpathhomeprojectsmyproject cd tmp trial myprojecttest words run tests within project directory dumps trialtemp directories source code confuses place i load code current directory generally makes muddle various things difficult untangle later so set pythonpath path using pathmanagement tool choice combinator setuppy develop virtualenv – dumping junk bashrc – run trial temporary location uniquelynamed toplevel python package everything work fine,how i run trial executes tests within directory all unit tests pass i run trial file individually i try something like trial test test directory gives one passed following message userwarning module init path importer cache pep violation check local configuration rather actually running tests within directory,2 you lock file order ensure nobody else writing time see file locking lockfile posixfile details update and cannot write data file disk full i sure python implementation output redirection write system call write less bytes requested,what steps need taken ensure full lines always correctly appended end file multiple following example program running concurrently usrbinenv python import random passwdtextopenpasswdtxta ujsmithxjoe smithroom jsmithrosettacodeorghomejsmithbinsh jdoexjane doeroom jdoerosettacodeorghomejdoebinsh xyzxx yzroom xyzrosettacodeorghomexyzbinsh rangerandomrandint print passwdtext randomchoiceu passwdtextclose and can nothing append guaranteed linuxunix even disk becomes full ulimit f set note similar question how append file python,2 to get got try masterlist print joini to get i think try masterlist print joini there many many ways,i new python have question regarding join function masterlist ap boxer rd new york ny axe w th street apt b new york ny i want print element list delimited pipe if i try masterlist mystring joini print mystring the error typeerror sequence item expected string list found so i trying masterlist mystring mystring joini print mystring i get ap boxer rdnew yorkny axe w th street apt bnew yorkny so works would like know better way join masterlist using join function,1 this particular symbol comes libpythonso replace wildcards version python you see listing dynamic symbols using nm ldd usrlibpythonsitepackagespsycopgpsycopgso grep libpython libpythonso usrliblibpythonso xfefc nm d usrliblibpythonso grep pyobjectnextnotimplemented t pyobjectnextnotimplemented are using custom build it seems version psycopgso linked libpython,environment ubuntu lts build python configure withzlib enableunicodeucs postgresql wsgi django virtualenv apache i trying build ubuntu django app server the installation completed error message the exact installation method successful ubuntu however installation completed ubuntu try load psycopg django i got following error i get error file homenreevesvenvlibpythonsitepackagesdjangodbbackendspostgresqlpsycopgbasepy line module raise improperlyconfigurederror loading psycopg module e improperlyconfigured error loading psycopg module homenreevesvenvlibpythonsitepackagespsycopgpsycopgso undefined symbol pyobjectnextnotimplemented my guess linkage library incorrect i idea start i following output sure help help ldd homenreevesvenvlibpythonsitepackagespsycopgpsycopgso linuxgateso xbda libpqso usrliblibpqso xb libpthreadso libtlsicmovlibpthreadso xbf libcso libtlsicmovlibcso xb libsslso libicmovlibsslso xbcc libcryptoso libicmovlibcryptoso xba libkrbso usrliblibkrbso xbc libcomerrso liblibcomerrso xbc libgssapikrbso usrliblibgssapikrbso xb libldaprso usrliblibldaprso xbe libldlinuxso xbdb libdlso libtlsicmovlibdlso xba libzso liblibzso xb libkcryptoso usrliblibkcryptoso xb libkrbsupportso usrliblibkrbsupportso xb libkeyutilsso liblibkeyutilsso xb libresolvso libtlsicmovlibresolvso xbf liblberso usrlibliblberso xbe libsaslso usrliblibsaslso xbcb libgnutlsso usrliblibgnutlsso xbf libtasnso usrliblibtasnso xbe libgcryptso liblibgcryptso xbab libgpgerrorso liblibgpgerrorso xba and following command outputs ls l usrliblibpq rwrr root root usrliblibpqa lrwxrwxrwx root root usrliblibpqso libpqso lrwxrwxrwx root root usrliblibpqso libpqso rwrr root root usrliblibpqso to appears correct any advice would appreciated,1 i think splitting tuples loop would cleaner identifier data masterlist print ss identifier joindata,i new python have question regarding join function masterlist ap boxer rd new york ny axe w th street apt b new york ny i want print element list delimited pipe if i try masterlist mystring joini print mystring the error typeerror sequence item expected string list found so i trying masterlist mystring mystring joini print mystring i get ap boxer rdnew yorkny axe w th street apt bnew yorkny so works would like know better way join masterlist using join function,2 masterlist print joini,i new python have question regarding join function masterlist ap boxer rd new york ny axe w th street apt b new york ny i want print element list delimited pipe if i try masterlist mystring joini print mystring the error typeerror sequence item expected string list found so i trying masterlist mystring mystring joini print mystring i get ap boxer rdnew yorkny axe w th street apt bnew yorkny so works would like know better way join masterlist using join function,1 for actual use case image widget djangoformutils package good match on general level if simply want modify html generated standard widget subclass widget tweak rendermethod take look blog post get basic idea,hi guys simple django form i need get type field elements i made special operations according is easy way get type form field django template any help appreciated,1 sqlite support write concurrency one client write single database point time with constraint place gain get using transactions ability roll back if plan use multiple databases make sure drag deadlock two processes hold transactional write lock one database try simultaneously obtain one,what best way use fork sqlalchemy sqlite project the sqlalchemy documentation mentions one call createengine child mention caveats i sure plenty write locks busytimeout disposeconnectionissues etc would design issue whether use transactions scoped sessions matter,1 i longer actively work wx cannot test solution however i believe looking setsashgravity the default behaviour splitterwindow upon resize event right bottom window resized and case imposed maximum size upon window see docs setsashgravity,i quiet new wxpython i hope nothing basic i overlooking i want use splitterwindow split frame content two resizable subwindows a b i want one windows b maxsize set unfortunately poses problem when i resize enlarge whole frame i trying adapt wxpython terminology normally i would say resize window i would hope maxsize window b reached window a would automatically enlarged fill whole content frame sadly how make sure i able move sash left decrease size window b in current situation window b moves left change width exposes blue background windowsplitter here code import wx class mainwindowwxframe def initself parent title wxframeinitself parent titletitle size create view selfloadview selfsetautolayout selfgetsizerfitself selfcentre selfshow def loadviewself splitter wxsplitterwindowself wxidany style wxspborder size splittersetbackgroundcolour ff panelleft wxpanelsplitter size panelleftsetbackgroundcolour ff panelright wxpanelsplitter size panelrightsetbackgroundcolour ff panelrightsetmaxsize splittersplitverticallypanelleft panelright selfsetsizerwxboxsizerwxhorizontal selfgetsizeraddsplitter wxexpand app wxappfalse frame mainwindownone test appmainloop a picture speaks thousand words the blue area part splitter filled window a any helphint right direction appreciated thanks daniel,2 itertools import chain symbol items masterlist print joinchain symbol items,i new python have question regarding join function masterlist ap boxer rd new york ny axe w th street apt b new york ny i want print element list delimited pipe if i try masterlist mystring joini print mystring the error typeerror sequence item expected string list found so i trying masterlist mystring mystring joini print mystring i get ap boxer rdnew yorkny axe w th street apt bnew yorkny so works would like know better way join masterlist using join function,1 if numpy installed somewhere server add import path python beginning script something like import sys syspathappendpathtonumpy import numpy,right i script uses numpy i want run automatically server when i ssh run manually works fine however i set run cron job find numpy apparently due shared server environment cron demon whatever reason find numpy i contacted server host tech support told set vps get damn server is way hack workaround perhaps moving certain numpy files directory script,1 the cronjob runs empty environment as either using python binary shell pythonpath set crontab you run env homehome sh get fascimile cronjob environment set environment variables command works record you set crontab file using env command like env pythonpathmypythonpath othervarcorrectvalue pathtomycommand,right i script uses numpy i want run automatically server when i ssh run manually works fine however i set run cron job find numpy apparently due shared server environment cron demon whatever reason find numpy i contacted server host tech support told set vps get damn server is way hack workaround perhaps moving certain numpy files directory script,1 your cron job probably executing different python interpreter log via ssh say python that tell python then cron job execute python interpreter run script chmod x script put path line top script,right i script uses numpy i want run automatically server when i ssh run manually works fine however i set run cron job find numpy apparently due shared server environment cron demon whatever reason find numpy i contacted server host tech support told set vps get damn server is way hack workaround perhaps moving certain numpy files directory script,1 processes invoked cron daemon minimal environment generally consisting home logname shell it sounds like numpy perhaps somewhere pythonpath if need specify within crontab line such usrbinenv pythonpath command run if linux system using vixie cron also specify global variables crontab using lines environment settings pythonpath path somethingelse blah normal cron line see man crontab,right i script uses numpy i want run automatically server when i ssh run manually works fine however i set run cron job find numpy apparently due shared server environment cron demon whatever reason find numpy i contacted server host tech support told set vps get damn server is way hack workaround perhaps moving certain numpy files directory script,1 it looks like resulting image jpeg the jpeg format support transparency try changing thumbnail template thumbnail projectimage x cropcenter formatpng im,i using sorlthumbnail pil django webserver dynamically create thumbnails templates pil installed png support reason transformations creating really bizarre artifacts transparent portions images i used gist github install required dependencies httpsrawgithubcomgistebceaaffaabapatchsh here template code generates images i think problem hurt show thumbnail projectimage x cropcenter im img src imurl endthumbnail below example happens any help greatly appreciated before after,3 i suggest rather look sorl pil backend handles scaling i imagine creates helper image apply additional effects tells pil scale original onto you need make sure destination using rgba mode support transparency starts alpha set zero pure white pitch black something similar if image using indexed palette possible get converted rgba in indexed mode pngs store transparent color index metadata process creating thumbnail alter pixels due antialiasing cannot preserve indexed transparency source imageopen deadparrotpng sourceconvert rgba dest sourceresize resampleimageantialias destsave exparrotpng,i using sorlthumbnail pil django webserver dynamically create thumbnails templates pil installed png support reason transformations creating really bizarre artifacts transparent portions images i used gist github install required dependencies httpsrawgithubcomgistebceaaffaabapatchsh here template code generates images i think problem hurt show thumbnail projectimage x cropcenter im img src imurl endthumbnail below example happens any help greatly appreciated before after,1 use ordereddict b else c,i reading file storing info dict reads top bottom i want print wrong order compared original file also small question i remember seeing somewhere short form else statement b c do know exact form thanks,3 oschdirruthsdatafecefr,i currently working server i created directory need access files located different directory server basically i code needs access files located another directory server i know go is command code i add something command line type the error i get code looks like aburacmcbbigramruthsdataaburac python getcontribspy traceback recent call last file getcontribspy line module fecfiles filterlambda x xendswith fec oslistdirdname oserror errno no file directory the file located directory ruthsdatafecefr so i get access files directory,1 you specify whole path enter file name for example say want open file footxt directory homedocs you could run command f openhomedocsfootxt f handle file alternatively command oschdir module os changes current working directory the following snippet effect import os oschdirhomedocs f openfootxt,i currently working server i created directory need access files located different directory server basically i code needs access files located another directory server i know go is command code i add something command line type the error i get code looks like aburacmcbbigramruthsdataaburac python getcontribspy traceback recent call last file getcontribspy line module fecfiles filterlambda x xendswith fec oslistdirdname oserror errno no file directory the file located directory ruthsdatafecefr so i get access files directory,1 you use ordereddict store data list index dict store dict save keys list go,i reading file storing info dict reads top bottom i want print wrong order compared original file also small question i remember seeing somewhere short form else statement b c do know exact form thanks,1 you mention wsgi tag if means using apachemodwsgi aware modwsgi must compiled python versioninstallation need verify modwsgi picking libpythonso run time modwsgi dictates python library linked,environment ubuntu lts build python configure withzlib enableunicodeucs postgresql wsgi django virtualenv apache i trying build ubuntu django app server the installation completed error message the exact installation method successful ubuntu however installation completed ubuntu try load psycopg django i got following error i get error file homenreevesvenvlibpythonsitepackagesdjangodbbackendspostgresqlpsycopgbasepy line module raise improperlyconfigurederror loading psycopg module e improperlyconfigured error loading psycopg module homenreevesvenvlibpythonsitepackagespsycopgpsycopgso undefined symbol pyobjectnextnotimplemented my guess linkage library incorrect i idea start i following output sure help help ldd homenreevesvenvlibpythonsitepackagespsycopgpsycopgso linuxgateso xbda libpqso usrliblibpqso xb libpthreadso libtlsicmovlibpthreadso xbf libcso libtlsicmovlibcso xb libsslso libicmovlibsslso xbcc libcryptoso libicmovlibcryptoso xba libkrbso usrliblibkrbso xbc libcomerrso liblibcomerrso xbc libgssapikrbso usrliblibgssapikrbso xb libldaprso usrliblibldaprso xbe libldlinuxso xbdb libdlso libtlsicmovlibdlso xba libzso liblibzso xb libkcryptoso usrliblibkcryptoso xb libkrbsupportso usrliblibkrbsupportso xb libkeyutilsso liblibkeyutilsso xb libresolvso libtlsicmovlibresolvso xbf liblberso usrlibliblberso xbe libsaslso usrliblibsaslso xbcb libgnutlsso usrliblibgnutlsso xbf libtasnso usrliblibtasnso xbe libgcryptso liblibgcryptso xbab libgpgerrorso liblibgpgerrorso xba and following command outputs ls l usrliblibpq rwrr root root usrliblibpqa lrwxrwxrwx root root usrliblibpqso libpqso lrwxrwxrwx root root usrliblibpqso libpqso rwrr root root usrliblibpqso to appears correct any advice would appreciated,2 httppypipythonorgpypienum implementation pep,at one point enums considered python developers add language dropped feature is implementation pep mdash specification seems pretty robust,1 in basecontroller init need call unittesttestcase init like testmycontroller the call construct testcase framework may passing argument the best way handle deriving classes class mysubclassparentclass def initself args kw parentclassinitself args kw,i basic setupteardown code i want reuse whole bunch unit tests so i got bright idea creating derived classes avoid repeating code every test class in i received two strange errors one i cannot solve here unsolvable one attributeerror testdesktoprootcontroller object attribute testmethodname here base class import unittest import twill import cherrypy cherrypycpwsgi import cpwsgiapp class basecontrollertestunittesttestcase def initself selfcontroller none def setupself app cherrypyapplicationselfcontroller wsgi cpwsgiappapp twilladdwsgiintercept localhost lambda wsgi def teardownself twillremovewsgiintercept localhost and derived class import twill basecontrollertest import basecontrollertest class testmycontrollerbasecontrollertest def initself args selfcontroller mycontroller basecontrollertestinitself def testrootself script find contacts twillexecutestringscript initialurl httplocalhost the strange error typeerror init takes exactly argument given the solution add word args init function derived class is way avoid remember i two errors one,1 it inserting double backslash that simply interactive interpreter showing string string literal use print see actual string n n print n n,i trying regex substitute backslash python seems inserting doublebackslash i make stop resub b b double backslash supposed backslash escape backslash backslash ends literal if i remove double slash print one resub b b b how i get python sub one backslash,3 the key noted near end section hrd testing in local environment performing get entity belongs entity group unapplied write always make results unapplied write visible subsequent global queries in production case simply add get operations tests get appropriate records show future queries,i following recommendations app engine site unit testing coding gae i set pseudorandomhrconsistencypolicy probability force code account cases data yet consistent the problem test suite i want data setup creating adding data datastore need way force datastore flush data consistent state i exercise code test ie make sure datastore return global entities i written next time i query is way people setting data tests suites using consistency models,3 i suppose answer i second liquidfire suggestion b b rb b use r raw strings simplify backslashes python,i trying regex substitute backslash python seems inserting doublebackslash i make stop resub b b double backslash supposed backslash escape backslash backslash ends literal if i remove double slash print one resub b b b how i get python sub one backslash,1 numpy scypy pygame windows installers you advised use installers favor archive versions make sure match version archetecture x python binary installed,i windows vista running python i truble installing python libraries including numpy scipy pygame i currently trying coppy numpy file straight computer cnumpy unziping file in command prompt i run code cd cnumpy python setuppy config python setuppy install when i get python setuppy config part command promt says wrong setuppy file run any suggestions,2 it overriding init incorrectly almost certainly want override init everything setup i using unittest years i think i ever overridden init however really need override init remember control constructor called framework calls so provide signature call from source code unittestcasepy signature def initself methodname runtest the safe way accept arguments pass em base class here working implementation class basetestunittesttestcase def initself args kwargs unittesttestcaseinitself args kwargs def setupself print basesetup def teardownself print baseteardown class testsomethingbasetest def initself args kwargs basetestinitself args kwargs selfcontroller object def testsillyself selfasserttrue,i basic setupteardown code i want reuse whole bunch unit tests so i got bright idea creating derived classes avoid repeating code every test class in i received two strange errors one i cannot solve here unsolvable one attributeerror testdesktoprootcontroller object attribute testmethodname here base class import unittest import twill import cherrypy cherrypycpwsgi import cpwsgiapp class basecontrollertestunittesttestcase def initself selfcontroller none def setupself app cherrypyapplicationselfcontroller wsgi cpwsgiappapp twilladdwsgiintercept localhost lambda wsgi def teardownself twillremovewsgiintercept localhost and derived class import twill basecontrollertest import basecontrollertest class testmycontrollerbasecontrollertest def initself args selfcontroller mycontroller basecontrollertestinitself def testrootself script find contacts twillexecutestringscript initialurl httplocalhost the strange error typeerror init takes exactly argument given the solution add word args init function derived class is way avoid remember i two errors one,3 i would go combination approach enum part tag class accept string initialization convert also instead using bunch ifelse branches use dict create dispatch table class tagobject cold warm hot def initself name temp tempupper cold warm hot raise valueerrorinvalid temp r temp selftemp getattrself tempupper selfname name def processself func selftempdispatchselftemp funcself note pass self explicitly def coldself print brrr def warmself print ahhh def hotself print ouch tempdispatch coldcold warmwarm hothot tag tag testing cold tagprocess,say i object called tag i three types tags indicated instance variable following way class tagobject def initself name type selfname name selftype type tagblue cold tagred warm tagblack hot let say i allowed three types cold warm hot would better go checking one types like ttype cold something elif ttype warm something else else ttype hot something even elser or i create enumlike object like one question class type cold warm hot and instead create tags like tagblue typecold the reason i ask question i heard lot processing power goes comparing strings even though short letter long words possible i making tens thousands comparisons types do think worth go creating enum objects determining type object example i shown or better way i attempting,1 you set useragent string wish modified app engine append string appenginegoogle httpcodegooglecomappengine appid yourapp in urllib set useragent header like req urllibrequesthttpenwikipediaorg headersuseragent foo response urlliburlopenreq,i writing python web app i plan leverage wikipedia when trying url fetching code i able fetch google facebook via google app engine services i attempted fetch wikipediaorg i received exception can anyone confirm wikipedia accept types page requests how wikipedia distinguish user code snippet python import os import urllib googleappengineextwebapp import template class mainhandlerwebapprequesthandler def getself url httpwikipediaorg try result urlliburlopenurl except urlliburlerror e result ahh sky falling templatevalues test result path ospathjoinospathdirnamefile indexhtml selfresponseoutwritetemplaterenderpath templatevalues,1 split string list map map lists sets dicts strings wordlist wordsstrsplit avoid using mapfilterreduce unless assignment dictates gvr says the proper solution uses python list comprehension syntax in fact pretty nasty oneliner palcount x wordlistcountx reduceish x wordlist mapish x x filterish x palcountiteritems print x print results breaking catch dictionary object print later palcount define return objects x wordlistcountx we use keyvalue syntax associate palindrome x number occurrences count like builtin reduce function lists iterate list loop assigning current value x x wordlist we want return palindromes add comparison operator filter bad values x x cool logic btw hurray by way i homework i never mine the slower less flexible less portable less awesome equivalent uses nested loops palcount dict x wordlist loop x x palindrome x palcount seen palcountx else one new palcountsetdefaultx,i currently struggling assignment the solution would input txt file run counting number palindromes frequency i need use map reduce create for example string bab bab bab cab cac dad would output bab cab dad here i far def palindromestring palindromes word stringsplit word word palindromesappendword return palindromes string abc abd bab tab cab tat yay uaefdfdu print maplambda x palindromex bab abc dab bab bab dad crap pap pap currently prints bab bab bab dad pap pap here attempt far reduce section def plists list lists seth setlist return seth p function i want create set palindromes found then run count palindromes list make dict print reducep bab bab bab dad pap pap am i right track,1 it looks like trying follow relationships backward in shell fetch events db events eventobjectsall event events fetch choices event eventchoices eventchoicesetall print eventchoices in template include parenthesis method call event locationlist eventlat eventlong ul choice eventchoicesetall li choice li endfor ul endfor you may want define relatedname parameter foreign key definition class choicemodelsmodel event modelsforeignkeyevent relatednamechoices then use eventchoicesall views choice eventchoicesall templates,i trying create first application using django i using following code create list events event locationlist eventlat eventlong html eventid endfor i need edit code eventid becomes something like get choice choicelist where event is eventid what proper syntax modelpy djangodb import models class eventmodelsmodel info modelscharfieldmaxlength long modelscharfieldmaxlength lat modelscharfieldmaxlength def unicodeself return selfinfo class choicemodelsmodel event modelsforeignkeyevent choice modelscharfieldmaxlength link modelscharfieldmaxlength def unicodeself return selfchoice viewspy def indexrequest locationlist eventobjectsall choicelist choiceobjectsall loadergettemplate mapindexhtml c context locationlist locationlist choicelist choicelist return httpresponsetrenderc update i replaced eventid choice eventchoicesetall choice endfor it print events,1 you need add result recursion already,the following example walks directory prints names files calls recursively directories import os def walkdir name oslistdirdir path ospathjoindirname ospathisfilepath print path else walkpath ospathjoin takes directory file name joins complete path my exercise modify walk instead printing names files returns list names can someone explain function per line i good idea gets line else walkpath throws since explanation for exercise way i could think change list def walkdir res name oslistdirdir path ospathjoindirname ospathisfilepath resappendpath else walkpath return res my output went many output lines mere did i correctly,1 ok i investigated bit found alternative way deal django model ie django features still access async api mainly using datastore directly googleappengineapi import datastore i already methods convert models tofrom json dict mostly matter discovering djangononrel behind scenes eg considering project class tojson fromjson methods ie create dictionary for simple query seems run work asynchronously one could queryrun later start another queryrun would work time query datastorequeryprojectmetadbtable p queryrun p id ckeyid convert app engine key print projectfromjsonp now using api get object asynchronously djangoappenginedbcompiler import createkey async datastoregetasynccreatekeyprojectmetadbtable projectid p asyncgetresult p id ckeyid convert app engine key print projectfromjsonp so possible retain model django structure needed wrappers needed work asynchronously,when using google app engine djangononrel way take advantage async datastore api i declare model classes django api,2 if serializing python objects simple datatypes use pickle try cpicklehighestprotocol myserializedobject cpickledumpsmyobject cpicklehighestprotocol the default protocol compatible older versions python likely care i simple benchmark key dict almost orderofmagnitude faster update since appear already using highest protocol going extra work get performance here i would point identify classes slowest pickle create pair methods class implement faster serialization method say tostring fromstrings the actual serialization tailored object encompasses going used for example objects may really contain simple string rendered template may actually sent browser json case simply serialize json serve directly use timeit module ensure method actually faster in decorator check hasattrobject tostring use instead exists this method lets tackle worst classes first introduces minimal disruption code base,i working web app aggressive caching virtually every component web app views partial views controller output disk loads restapi calls database queries everything cached level cached using decorators naturally blazing fast since vast majority htmlgeneration comprises pure functions loads diskrest apis furthermore disk loadsdatabase queriesrest api queries perform also cached invalidated unless something changed really fast so everything blazing fast hitch stuff cached memory one huge global dictionary wsgi process hence stored directly without serialization once start putting stuff memcached time taken cache hits change much putting stuff cache starts taking much longer in general ok initial fill cache generation page goes ms already pretty fast considering many flat files reads disk ms for reference generating arbitrary page takes something like ms cache warmed profiling code vast majority time going cpickle so question i make faster are inmemory caches i directly pass objects without serialization or way make caching huge pile objects faster i could go without persistent memcached performance lack thereof whim apachewsgi process manager,2 here annotated version small fix recursion def walkdir res entries folder name oslistdirdir compute path relative dir path ospathjoindirname include entries recursively ospathisfilepath path points file save resappendpath else path points directory need fetch list entries resextendwalkpath produce entries return res,the following example walks directory prints names files calls recursively directories import os def walkdir name oslistdirdir path ospathjoindirname ospathisfilepath print path else walkpath ospathjoin takes directory file name joins complete path my exercise modify walk instead printing names files returns list names can someone explain function per line i good idea gets line else walkpath throws since explanation for exercise way i could think change list def walkdir res name oslistdirdir path ospathjoindirname ospathisfilepath resappendpath else walkpath return res my output went many output lines mere did i correctly,1 which efficient depends used if user loading lot mashups makes sense send separate images fewer images browser cache abc images instead abc your code much egregious performance issue however def getrandomimageself category fileinfos fileinfoallfiltercategory category return fileinfosrandomrandint fileinfoscount every time call function perform count operation on number fileinfo entities perform offset query on offset this extremely slow inefficient get increase number images if expect set images small less thousand fairly constant simply store code faster option if set larger changes runtime assign random value entity use query like retrieve randomly selected one q fileinfoall qfilter category category qfilter random randomrandom return qget,my facebook app lets user upload image select image eyes nose mouth body part combine selecting three random images category works fine code looks ok readable though advanced class cyberfazehandlerbasehandler def getrandomimageself category fileinfos fileinfoallfiltercategory category return fileinfosrandomrandint fileinfoscount def getself eyesimage selfgetrandomimagecategoryeyes noseimage selfgetrandomimagecategorynose mouthimage selfgetrandomimagecategorymouth eyesdata none try eyesdata blobstorefetchdataeyesimageblobkey except exception e selfsetmessagetypeu error contentu could find eyes data file streyesimagekeyid unicodee u eyesimg none try eyesimg imagesimageimagedataeyesdata i fetch random images combine template hreffileeyesimagekeyidimg srceyesurlabr hreffilenoseimagekeyidimg srcnoseurlabr hreffilemouthimagekeyidimg srcmouthurla could improved sending composite image combining three images one with advantage everything image load time saved already randomization comes next time result already saved what think thank application appsfacebookcomcyberfaze may inspect i fun learning the entire class class cyberfazehandlerbasehandler def getrandomimageself category fileinfos fileinfoallfiltercategory category return fileinfosrandomrandint fileinfoscount optimize def getself eyesimage selfgetrandomimagecategoryeyes noseimage selfgetrandomimagecategorynose mouthimage selfgetrandomimagecategorymouth eyesdata none try eyesdata blobstorefetchdataeyesimageblobkey except exception e selfsetmessagetypeu error contentu could find eyes data file streyesimagekeyid unicodee u eyesimg none try eyesimg imagesimageimagedataeyesdata except exception e selfsetmessagetypeu error contentu could find eyes img file streyesimagekeyid unicodee u nosedata none try nosedata blobstorefetchdatanoseimageblobkey except exception e selfsetmessagetypeu error contentu could find nose data file strnoseimagekeyid unicodee u noseimg none try noseimg imagesimageimagedatanosedata except exception e selfsetmessagetypeu error contentu could find nose img file strnoseimagekeyid unicodee u mouthdata none try mouthdata blobstorefetchdatamouthimageblobkey except exception e selfsetmessagetypeu error contentu could find mouth data file streyesimagekeyid unicodee u mouthimg none try mouthimg imagesimageimagedatamouthdata except exception e selfsetmessagetypeu error contentu could find mouth img file strmouthimagekeyid unicodee u minimum mininteyesimgwidth intnoseimgwidth intmouthimgwidth eyesurl imagesgetservingurlstreyesimageblobkey sizeminimum noseurl imagesgetservingurlstrnoseimageblobkey sizeminimum mouthurl imagesgetservingurlstrmouthimageblobkey sizeminimum selfrenderu cyberfaze minimumminimum eyesimageeyesimage eyesurleyesurl noseimagenoseimage noseurlnoseurl mouthimagemouthimage mouthurlmouthurl formurl blobstorecreateuploadurl upload after rewrite working like said class cyberfazehandlerbasehandler def getrandomimageself category q fileinfoall qfilter category category qfilter randomvalue randomrandom return qget def getrandomimagelegacyself category fileinfos fileinfoallfilter category category return fileinfosrandomrandint fileinfoscount def getself eyesimage selfgetrandomimagecategory eyes eyesimage loggingdebuggetting eyes failed trying legacy method eyesimage selfgetrandomimagelegacycategory eyes noseimage selfgetrandomimagecategory nose noseimage noseimage selfgetrandomimagelegacycategory nose mouthimage selfgetrandomimagecategory mouth mouthimage mouthimage selfgetrandomimagelegacycategory mouth eyesdata none try eyesdata blobstorefetchdataeyesimageblobkey except exception e selfsetmessagetypeu error contentu could find eyes data file streyesimagekeyid unicodee u eyesimg none try eyesimg imagesimageimagedataeyesdata except exception e selfsetmessagetypeu error contentu could find eyes img file streyesimagekeyid unicodee u nosedata none try nosedata blobstorefetchdatanoseimageblobkey except exception e selfsetmessagetypeu error contentu could find nose data file strnoseimagekeyid unicodee u noseimg none try noseimg imagesimageimagedatanosedata except exception e selfsetmessagetypeu error contentu could find nose img file strnoseimagekeyid unicodee u mouthdata none try mouthdata blobstorefetchdatamouthimageblobkey except exception e selfsetmessagetypeu error contentu could find mouth data file streyesimagekeyid unicodee u mouthimg none try mouthimg imagesimageimagedatamouthdata except exception e selfsetmessagetypeu error contentu could find mouth img file strmouthimagekeyid unicodee u minimum mininteyesimgwidth intnoseimgwidth intmouthimgwidth eyesurl imagesgetservingurlstreyesimageblobkey sizeminimum noseurl imagesgetservingurlstrnoseimageblobkey sizeminimum mouthurl imagesgetservingurlstrmouthimageblobkey sizeminimum selfrender u cyberfaze minimumminimum eyesimageeyesimage eyesurleyesurl noseimagenoseimage noseurlnoseurl mouthimagemouthimage mouthurlmouthurl formurlblobstorecreateuploadurl upload,1 your problem likely caused file remote object you opened server requesting one line time local request takes much longer file sitting hard drive the best alternative probably copy file local location first using paramiko sftp get once done open file local location using osopen,i using paramiko open remote sftp file python with file object returned paramiko i reading file line line processing information this seems really slow compared using python inbuilt method open os following code i using get file object using paramiko slower times client paramikosshclient clientloadsystemhostkeys clientsetmissinghostkeypolicyparamikoautoaddpolicy clientconnectmyhostmyportmyusermypassword sftp clientopensftp fileobject sftpfilefullfilepath rb using os import os fileobject openfullfilepath rb am i missing anything is way make paramiko fileobject read method fast one using os fileobject thanks,3 have thought using json pass data post flask built support passing json data in addition set contenttype headers applicationjson flask automatically dejson post data put requestjson here requesting application import urllib import json name main headers contenttype applicationjson postdata usertestuser print posting request req urllibrequesthttplocalhostlogin jsondumpspostdata headers resp urlliburlopenreq print response respread this flask view flask import request approute login methods post def login user requestjson user return user i suggest test using curl well using linux terminal here example curl x post h contenttypeapplicationjson userthis username localhostlogin this username,i recreating service pythonflask running issue way existing clients authenticate i match existing clients scheme compatibility reasons the existing clients take username password base encode this http basic authentication despite sounding similar below sample code would create login request credentials username testexamplecom password password data bencodeurlencodecredentials request urllibrequestloginurl requestadddatadata requestaddheader contenttype applicationgooblygop applicationxwwwformurlencoded seems default contenttype login urlliburlopenrequest on server side i take post data base decode get username password information flask server approute login methods post def login error none requestmethod post post data cgfzcdvcmqzgvmyxvsdczlbwfpbdzxnjtqwzxhhbxbszsjb data bdecoderequestdata decoded data passworddefaultampemailtestexamplecom return ok the problem content type if i specify unknown contenttype client applicationgooblygop flask exposes post data requestdata i decode base string if i leave contenttype default applicationxwwwformurlencoded raw data exposed requestdata i know retrieve base encoded string make use the existing client software pretty much defaults xwwwformurlencoded i rely always case essentially i need reliable serverside method accessing encoded string matter contenttype client program states other notes i new python coming php background so i open suggestions also project primarily personal use,1 in factthe method installing numpy easy quickfirstmake sure python already installedthendownload numpy module sitessuch httpsourceforgenetprojectsnumpyfilesnumpy provides numpy module python finallydouble click modulethe rest let go onandit installed naturally,i windows vista running python i truble installing python libraries including numpy scipy pygame i currently trying coppy numpy file straight computer cnumpy unziping file in command prompt i run code cd cnumpy python setuppy config python setuppy install when i get python setuppy config part command promt says wrong setuppy file run any suggestions,1 specifically unsupported operand type int generator take hint you use generator trivial formula you expand generator expression ron db has generator b right b value it kind sequence values so apply value sequence formula ron dx x b get value sequence compute new value it clear actually useful since original ron db b collection values make much sense,reading site seem find specific answer want tried reading david beasly slides iteration generators still quite get answer looking though question seems simple running clockbased simulation brian neural networking generator manipulating outputs adding running sum order n exponential decay simple lowpass filter want take outputs generators timestep use another function update state variables says since item generator type cannot code explanation code follows import numpy ourrangenumpyarangemsdurationdefaultclockdtdefaultclockdt aourrange cdefaultclockt clock part program running updates every timestep runs range given def sumtauneuron gives running sum want access alphas ignored problem specific c express like c run c x elif defaultclockstillrunningfalse return else x xalpha pneuronalpha print x yield x pneuron takes neurons variables gives number bsumtaudn specify neuron working problem specific networkoperation def x bnext networkoperation means every clock timestep function executed therefore updating sum required value now want update value used simulation output another generator shown similar b typing ron db however says cannot use generator object way used print statements determine b give outputs want every timestep simulation run i cannot seem take outputs anything specifically unsupported operand type int generator tried converting number float obviously work reason feel must simple solution problem seem find thanks advance,1 in first example executing abc first context abc second context so testvar true first context false second context in second example caught interesting situation interpreter removed testvar context testvar referenced,i two code really confused def getcontext gc globals lc locals def precompilercode exec code lc def compilerscript scope return compilescript scope eval def executorexpr return evalexpr gc lc return precompiler compiler executor maker compiler executor getcontext maker compiler executor getcontext makerabc makerabc expr compilerabc testpy print executorabc executorexpr print executorabc executorexpr result executorabc true executorabc false why compile execute closure bytecode could run and another code def getcontext gc globals lc locals testvar def compilerscript scope return compilescript scope eval def executorexpr return evalexpr gc lc return compiler executor compiler executor getcontext compiler executor getcontext expr compilertestvar testpy print executortestvar executorexpr print executortestvar executorexpr result nameerror name testvar defined and happen why compile need check environmentvariable others closure dependent closure this i confused,1 some additional investigation yielded pyrolite mitlicensed library allows java net programs interface python world in addition remote object functionality importantly includes pickle serializer deserializer,i using python service uses pickled messages part protocol i like query service java i need pickle message client java are implementations pickle run jvm ideally minimal dependencies clarification modifying server side option alternate serializations would convenient solve problem,3 for first question compile takes python code produces bytecode it dependent way closure compiled its different produced say string that string permantely tied function created neither code object for second question locals builds dictionary local variables called since setup testvar calling locals if want testvar inside locals need call afterwards,i two code really confused def getcontext gc globals lc locals def precompilercode exec code lc def compilerscript scope return compilescript scope eval def executorexpr return evalexpr gc lc return precompiler compiler executor maker compiler executor getcontext maker compiler executor getcontext makerabc makerabc expr compilerabc testpy print executorabc executorexpr print executorabc executorexpr result executorabc true executorabc false why compile execute closure bytecode could run and another code def getcontext gc globals lc locals testvar def compilerscript scope return compilescript scope eval def executorexpr return evalexpr gc lc return compiler executor compiler executor getcontext compiler executor getcontext expr compilertestvar testpy print executortestvar executorexpr print executortestvar executorexpr result nameerror name testvar defined and happen why compile need check environmentvariable others closure dependent closure this i confused,1 which compiler using msvc gcc for msvc start python first attach pythondexe windbg visual studio load module setup breakpoint verify whether module symbol got loaded debugmodule windows msvc,i python extension i successfully built used windows osx linux i need able debug python extension i averse use gdb command line i would really like get work eclipse to begin i best follow instructions httpwwwheikkitoivonennetblogdebuggingpythonextensionwrittenincwitheclipse i added folder python source well folder python extension code source folders empty project since relatively easy get debug builds everything required linux i started debug development ubuntu once i got debug build python lets call pythond i ran setuppy extension pythond setuppy build also yield debug build extension module i verified symbols exported opening extension application eclipse i see source code linked python shared object now i create another project eclipse folder code add breakpoint source used create extension stop breakpoint it entirely possible i missing something rather critical life i get work the crux problem how get eclipse stop breakpoint python extension module,1 to encode string using public key usrbinenv python mcrypto import rsa x x xloadcertrecipientcertpem rsa xgetpubkeygetrsa print rsapublicencryptyour string encrypt rsapkcspadding,is way encode string publickey i found two packages pycrypto mcrypto but i find use,1 the simplest way would run selfdialognotification main gtk thread just add gobjectidleaddselfdialognotification args thread,i pygtk add gtkbutton pressed job lets say seconds so thought implementing timeintensive function signal handler thread first i added gtkgdkthreadsinit beginning my signal handler def sendsms i another function def sendsmsmycantos i call thread threadingthreadtarget selfsendsmsmycantos argsphoneno messagetext username passwordstart i also function displays dialogs def dialognotificationself message dialogtype dlg gtkmessagedialogselfwindow gtkdialogdestroywithparent dialogtype gtkbuttonsclose message dlgrun dlgdestroy now i call function thread selfdialognotificationmessage sent successfully gtkmessageinfo i get error smssenderpy fatal io error resource temporarily unavailable x server is right way implement threading what i wrong the error like thread know xserver running,1 just accepts funcu,in following code i pass dictionary func how func called def funcac lenc print lenc print c u b funcu,1 assuming hist histogram red pixels histogram pixel counts indexed red component that means sumhist always going number pixels image lenhist always going this always give answer three red green blue you need multiply pixel counts values histogram pixel values index list add get weighted sum then divide number pixels get weighted average maybe something like redhist hist weightedsum sumi redhisti rangelenredhist numpixels sumredhist weightedaverage weightedsum numpixels,in answer detecting color image olooney said loop histogram take average pixel color weighed pixel count i ran histogram like class imageresizewebapprequesthandler def getself q homepageall qfilterfirmname noise qtable qget id qtablekeyid id homepage homepagegetbyidid homepage img imagesimagehomepagethumbnail hist imghistogram idle color histogram hist i tried get average divided pixel count i get number what i wrong averagered floatsumhistlenhist averagered averagegreen floatsumhistlenhist averagegreen averageblue floatsumhistlenhist averageblue update thanks saxon druce answer here code i used def histweighedaveragehist redhist hist greenhist hist bluehist hist redweighedsum floatsumi redhisti rangelenredhist greenweighedsum floatsumi greenhisti rangelengreenhist blueweighedsum floatsumi bluehisti rangelenbluehist rednumpixels floatsumredhist greennumpixels floatsumgreenhist bluenumpixels floatsumbluehist redweighedaverage redweighedsum numpixels greenweighedaverage greenweighedsum numpixels blueweighedaverage blueweighedsum numpixels return redweighedaverage greenweighedaverage blueweighedaverage hist hist histweighedaveragehist hist hist histweighedaveragehist,2 i aware existing functions would however pretty easy write one using regular expressions import returns floatendpos def strtods pos rematchr ddeed spos mgroup raise valueerror bad float spos return floatmgroup pos mend print strtod ae print strtod ae a better overall approach might build lexical scanner would tokenize expression first work sequence tokens rather directly string indeed go whole hog build yaccstyle parser,i working converting parts c program python i trouble replacing c function strtod the strings i working consists simple mathmaticalish equations km the problem constants numbers mixed i therefore unable use float how python function written simulate c strtod returns converted number position next character,2 this run multiple parameters name but change def funcxc lenc print lenc print c then call func b u b func u,in following code i pass dictionary func how func called def funcac lenc print lenc print c u b funcu,1 faster solution see timeit import timer import os import binascii def testspeedstatement setup pass print statement print timerstatement setuptimeit setup import os value osurandom winner statement import binascii binasciihexlifyvalue testspeedstatement setup loser statement import binascii valueencode hexcodec testspeedstatement setup results import binascii binasciihexlifyvalue valueencode hexcodec,i string binary string characters i would like convert binary first hex the string qqg qasavcdnaj how i go converting string python output hex format similar bfaf,1 take look docs explaining genericinlinemodeladmin if get right example exactly want class imagemodelsmodel image modelsimagefielduploadtoimages contenttype modelsforeignkeycontenttype objectid modelspositiveintegerfield contentobject genericgenericforeignkeycontenttype objectid class productmodelsmodel name modelscharfieldmaxlength it bit different design image field part model adds generic relations kind content objectsmodels that way simply attach images via admin interface using already mentioned inlineadmins class imageinlinegenericgenerictabularinline model image class productadminadminmodeladmin inlines imageinline,i models need many many relation images instead creating relation individually i want generic model relations i use models so i created image imageitem models i sure i right track djangocontribcontenttypes import generic djangocontribcontenttypesmodels import contenttype class imagemodelsmodel title modelscharfieldmaxlength image modelsimagefielduploadto images class imageitemmodelsmodel image modelsforeignkeyimage contenttype modelsforeignkeycontenttype objectid modelspositiveintegerfield object genericgenericforeignkey contenttype objectid what i want every time i create new image i want select objects i want assign image so admin i need something like image chicagobullsjpg selected model player selected michael jordan scotie pippen image kobebryantjpg selected model team selected los angeles lakers us national team is model design correct i also want use modelmultiplechoicefield i figure,1 here good starting point introduction oop python,can one suggest links python object oriented concepts clearly explained example data abstraction encapsulation class object datahiding inheritance polymorphism,2 just implement lt class objobject def initself value selfvalue value def ltself return selfvalue othervalue def reprself return objr selfvalue objlist obj obj obj obj print maxobjlist print minobjlist print sortedobjlist cmp deprecated functions mentioned use lt comparisons if reason really compare way something like operator import attrgetter functools import partial valget attrgetter value maxval partialmax keyvalget minval partialmax keyvalget sortedval partialsorted keyvalget sortval partiallistsort keyvalget where call maxvalobjlist instead maxobjlist etc sortvalobjlist sort inplace instead objlistsort,i multiple subclasses superclass store something instanceofaclassvalue i override cmp provide reasonable etc comparisons however i multiple places code i minlistofinstancesofclass keylambda value maxlistofinstancesofclass keylambda value occasional sorted is function override class i specify key function call said functions i need subclass list override max min sorted methods,2 not directly the simplest thing would probably define specific functions use place minmaxsorted eg functools import partial minmyclass partialmin key operatorattrgetter value maxmyclass partialmax key operatorattrgetter value minmyclasslistofinstancesofmyclass,i multiple subclasses superclass store something instanceofaclassvalue i override cmp provide reasonable etc comparisons however i multiple places code i minlistofinstancesofclass keylambda value maxlistofinstancesofclass keylambda value occasional sorted is function override class i specify key function call said functions i need subclass list override max min sorted methods,1 replace square brackets round braces call range genres valuefromkeywb genre n range,what would efficient way following genres valuefromkeywb genre n valuefromkeywb genre n valuefromkeywb genre n valuefromkeywb genre n i tried list comprehension genres valuefromkeywb genre n range kept raising typeerror saying object unsubscriptable what would dry way thank,3 just place mutable object two places if change object change places dictionary only donwside add delete explicitly could create helper method though in in c in c in c in out in cappend in out if want store unmutable types like string tuple probably need create object store change inside object,hi i fairly sure i wondering could dictionary values accessed via two keys without duplicating dictionary the reason i want two keys represent thing one shortened version eg tyr y value,3 define fk including schema dbotbconsumeradvicecategoriesidconsumeradvicecategories,going mental getting error i try instantiate consumeradvice class foreign key associated column tbconsumeradviceconsumeradvicecategoryid could find table tbconsumeradvicecategories generate foreign key target column idconsumeradvicecategories here class definitions class consumeradvicecategorybase tablename tbconsumeradvicecategories tableargs schema dbo idconsumeradvicecategories columninteger sequence idcac primarykeytrue name columnvarchar nullablefalse def initselfname selfname name def reprself return consumeradvicecategory selfname class consumeradvicebase tablename tbconsumeradvice tableargs schema dbo idconsumeradvice columninteger sequence idconsumeradvice primarykeytrue consumeradvicecategoryid columninteger foreignkey tbconsumeradvicecategoriesidconsumeradvicecategories name columnvarchar nullablefalse categorysubid columninteger consumeradvicecategory relationshipconsumeradvicecategory backrefbackref consumeradvices def initselfname selfname name def reprself return consumeradvice selfname,3 allowing amount concurrent connections single system requires huge list kernel tuning probably never able manage load production first increase number ephemeral port socket backlog queue number allowed file descriptor per process in addition already enough stop unrealistic test increase number async core uwsgi k nothing wrong taht core consume less page memory end least k opened socket system this nginxuwsgi with apache end k processes threads even worse k opened sockets,coming bottleneck server pass x benchmark test matter adjustments made server g ram xeon core cpu centosbit good shape try combinations including nginx uwsgi python nginx apache modwsgi python apache modwsgi python none could make apache benchmarking ab c n without k coincidentally almost tests failed around requests detail nginx uwsgi nginx workerprocesses use epoll workerconnections uwsgi listen master true workers uwsgi x etcuwsgiconfxml async file varwwwexamplepy amp anybody idea thanks advance possible solutions suggestions,1 you like try researchr hellobyeend r qwehellosdfsend groups except attributeerror print match,i using python regex try extract optional middle string researchr hellobyeend r qwehellosdfsend groups none qwehellosdfsend i want qwe hello sdfsend researchr hellobyeend r qweblahsdfsend groups none qweblahsdfsend middle match ok how i extract optional middle note this first post,1 your regex fails first part happy matching empty string second part fails ok since optional third part captures solution make first part match anything hello end researchr hellobyehellobyeend r qwehellosdfsend groups qwe hello sdfsend researchr hellobyehellobyeend r qweblahsdfsend groups qweblahsdfs none end is acceptable explanation try match following first assert impossible match hellobye hello bye point string if match character do number times,i using python regex try extract optional middle string researchr hellobyeend r qwehellosdfsend groups none qwehellosdfsend i want qwe hello sdfsend researchr hellobyeend r qweblahsdfsend groups none qweblahsdfsend middle match ok how i extract optional middle note this first post,1 there thing key filters couchdb every item emit view sorted key find items given startkey endkey in case items first sorted date stringkey stringkey it sounds like expecting see items starttime endtime items string second item string third item couchdb views work they onedimensional list items sorted whole key,i need filter view function doc docdoctype asd emitdocdate docstringkey docstringkey doclistfield i keyfilter starttime string string keyfilter endtime string string viewkeyfilterkeyfilter view filtered starttime endtime it ignored string string key filters,1 kept raising typeerror saying object unsubscriptable because range means use tuple subscript range since range function want call ie put arguments parentheses valuefromkey i really see would conclude error like something wrong list comprehension oo what would dry way with list comprehension,what would efficient way following genres valuefromkeywb genre n valuefromkeywb genre n valuefromkeywb genre n valuefromkeywb genre n i tried list comprehension genres valuefromkeywb genre n range kept raising typeerror saying object unsubscriptable what would dry way thank,1 returning values one rule another let say want parse simple expressions provide map variables runtime used expressions a simple grammar including custom python code returns statements rules parameter vars entry point grammar could look like grammar t options languagepython members variables parsewith vars returns value initselfvariables vars expression eof value expressionvalue expression returns value addition value additionvalue addition returns value emultiplication value evalue emultiplication value value evalue emultiplication value value evalue multiplication returns value eunary value evalue eunary value value evalue eunary value value evalue unary returns value atom value atomvalue atom value atomvalue atom returns value number value floatnumbertext id value selfvariablesidtext expression value expressionvalue number id z a z space channelhidden if generate parser using antlr v later version java cp antlrjar organtlrtool tg run script usrbinenv python import antlr antlr import tlexer import tparser import input lexer tlexerantlrantlrstringstreaminput parser tparserantlrcommontokenstreamlexer print formatinput parserparsewith see following output printed note define single return type parse foo print b c formatfooa foob fooc foo returns b c a b c aatext bbtext bctext how write target language code the easiest go simply put print statements inside custom code blocks pipe output file parsewith vars initselfvariables vars expression eof print out expressionvalue run script like runpy outtxt create file outtxt containing out if grammar big might get away however might become bit messy case could set output parser template options outputtemplate languagepython emit custom code defined templates see stringtemplate minute introduction where get python antlr package use stringtemplate,i trying use antlr take simple grammar produce assembly output my language choice antlr python many tutorials seem complicated elaborate things relevant i really need simple functionality so i two questions returning values one rule another so let say i rule like assignment nameidentifier assignment expression i run python code rule recognised i pass args python code expression something like assignment nameidentifier assignment expressionvariableslist expressionvariableslist blah blah but i return value original rule eg i calculate value expression send back assignment rule use python how i write target language code so i python runs rules recognised i calculate assembly i want statement produce but i say write string assembly instructions target file any good tutorials relevant kind stuff attribute grammars compiling something ast etc would helpful if questions make much sense please ask clarify i hard time wrapping head around antlr,3 try ddskg the negative look behind so matches one two digits preceded digit i also changed literal space one space chars seeing asked python questions demo python usrbinenv python import string something kg something kg print refindallr ddskg string print kg edit as tim mentioned word boundary b enough r bdskg,i string something kg something kg i regex kg string returns kg times i need return kg first case,2 there privacy setting override check settings friends account see options how people bring info apps use setting httpswwwfacebookcomsettingstabprivacy allows users stop apps friends use accessing data even would normally available friend,i writing facebook application accesses user friends photos for reason i access certain photos i narrowed able access photos friends friends privacy setting turned on the pictures i access still friends privacy settings turned on user application acting behalf friends people per facebook privacy scheme i able access i access photos via facebook site my application following permissions userphotos friendsphotos i receiving oauth errors i merely getting nothing back server eg user photos set friends i get blank data array useridalbums api call anyone know happening should i requesting permissions app users,1 your unpack function calls fread twice i suspect walked end file you also trouble reading file text mode windows any incidental occurrences rn read n make following change avoid problem f openinfilename rb,i difficulties parsing binary stl file python bit windows the file k size parser suddenly stops working parsing triangles en exception structunpack exception unpack requires string argument length the cursor position file line row but line contains characters so seem newline problem this code import struct normals points triangles bytecount fb debug list def unpack f sig l fread l fbappends return structunpacksig def readtrianglef n unpackff p unpackff p unpackff p unpackff b unpackfh normalsappendn l lenpoints pointsappendp pointsappendp pointsappendp trianglesappendl l l bytecountappendb def readlengthf length structunpacki fread return length def readheaderf fseekftell def writeasasciioutfilename f openoutfilename w fwrite solid outfilenamen n rangelentriangles fwrite facet normal nformatnormalsnnormalsnnormalsn fwrite outer loopn fwrite vertex nformatpointstrianglesnpointstrianglesnpointstrianglesn fwrite vertex nformatpointstrianglesnpointstrianglesnpointstrianglesn fwrite vertex nformatpointstrianglesnpointstrianglesnpointstrianglesn fwrite endloopn fwrite endfacetn fwrite endsolid outfilenamen fclose def main infilename rcuphemisstl outfilename rcuphemisasciiteststl try f open infilename r readheaderf l readlengthf try true readtrianglef except exception e print exceptione print lennormals lenpoints lentriangles l writeasasciioutfilename except exception e print e name main main the unpack function struct collects strings written file when i compare file seem equal file position unpack stops working i opened binary file notepad next character sub are restrictions unpack i aware regarding file size limitation characters something is something wrong code thanks advance,3 you splitting whole line words you need split first word second word rest like linesplitnone it would probably use regular expressions and use oposite logic starts number use otherwise pass like pattern recompiler sdss f open xxtxt r no calling readlines lazy iteration better line f patternmatchline cuexecute insert into buginfo pa k details values mgroup mgroup mgroup oh course using prepared statement parsing sql orders magnitude slower executing,really struggling one time many text files specific format need extract data file different fields database the struggle tweaking parameters parsing ensuring get info correctly format shown whitespace here unknown length k pa details need sentace one db record one well one content vary x max sometimes line beginning max need there line need whitespace here unknown length the tough parts getting rid whitespace defining fields see best attempt dict xx openxxtxt rreadlines line xx lineisspace pass elif linestartswith there pass elif linestartswith max pass elif linestartswith k pass else word linesplit wordstartswith tmppa word elif word word word word word tmpk word else tmpdetails word cuexecute insert into buginfo pa k details values tmppatmpktmpdetails at minute pull k amp pa fields problem using however details pulling one word need entire sentance least chars thanks much reading i hope help k,1 you use closures hide object away code please accept python considered unpythonic pretty much philosophy language you supposed document proper behavior guard users class kittenfactoryobject def createtehsecretobjectzself class kittenobject icanhazinvisible true return kitten willing programmers still able either copy get type instantiate manually in words go,i domain object user i looking way restrict python classes form creating objects user type,1 user mutable object passed reference anything correct,noticed strange behaviour interacting session variables django in one app created middlewarepy file containing function copy session variable stores object local one change attribute object local var it happens changes make local variable applied also session variable it seems local var reference session is behaviour correct here code class cloudmiddlewareobject user requestsession user useremail myemail when user requestsession user email useremail the value email equal myemail i always thought save object back session want store could someone explain really works,1 this nothing sessions simple consequence python mutable objects work when user requestsession user getting reference object exactly would mutable object stored standard dictionary so yes change one attributes change referenced reference note sessions change persisted lifetime current request that django know session object changed save unless specifically tell see documentation details,noticed strange behaviour interacting session variables django in one app created middlewarepy file containing function copy session variable stores object local one change attribute object local var it happens changes make local variable applied also session variable it seems local var reference session is behaviour correct here code class cloudmiddlewareobject user requestsession user useremail myemail when user requestsession user email useremail the value email equal myemail i always thought save object back session want store could someone explain really works,1 if templating requirements really simple i suggest use python builtin string formatting engine,for python web development large selection template engines my work limited fairly narrowspecific set use cases a description might suggest someone working knowledge manymost one better suited particular use cases in words might one among group optimized spec close use case would like know here criteria describe uses cases serverside language python hope need lot python expressions templates use python web servers cherrypy likely twisted jquery language data display librariesplugins written templates describe abstract web pages used data display bi dashboard fair description server delivers data template response form selections submitted antecedent page want display data grid eg jquery plugin jqgrid plot eg one standard types flot performance critical scope narrowonly data handling renderingi expect grids often populated several thousand data rows though grid paginated likewise plots could easily thousand data points though preprocessing computation done elsewhere little need rich syntax need complex multiway branching etci prefer processiongcomputation server data filtering almost always done jquery plugin use render data likewise user interaction displayed data native elements supplied jquery plugin eg page updown sort etc designerfriendly template really important like designers design effort required low enough even,1 you may want take look jinja it offers precompilation templates allows familiar python syntax frameworkagnostic,for python web development large selection template engines my work limited fairly narrowspecific set use cases a description might suggest someone working knowledge manymost one better suited particular use cases in words might one among group optimized spec close use case would like know here criteria describe uses cases serverside language python hope need lot python expressions templates use python web servers cherrypy likely twisted jquery language data display librariesplugins written templates describe abstract web pages used data display bi dashboard fair description server delivers data template response form selections submitted antecedent page want display data grid eg jquery plugin jqgrid plot eg one standard types flot performance critical scope narrowonly data handling renderingi expect grids often populated several thousand data rows though grid paginated likewise plots could easily thousand data points though preprocessing computation done elsewhere little need rich syntax need complex multiway branching etci prefer processiongcomputation server data filtering almost always done jquery plugin use render data likewise user interaction displayed data native elements supplied jquery plugin eg page updown sort etc designerfriendly template really important like designers design effort required low enough even,1 this question nothing python everything particular operating system file system using could please provide details at least windows use sysinternals handle force particular handle file closed especially file opened another user network operation extremely destabilising probably render network connection subsequently useless you looking c commandline argument documentation reads closes specified handle interpreted hexadecimal number you must specify process pid warning closing handles cause application system instability and forceclosing file mounted samba linux speaking experience excruciating experience futility however others tried mixed success see force samba process close file,i program creates bunch movie files i runs cron job every time runs movies previous iteration moved previous folder always previous version look these movie files accessed across network various users i running problem when script runs tries move files throws resource busy error files open various users is way python force close files i attempt move further clarification jmax correct mentions server level problem i access windows server administrative tools computer management shared folders open files manually close files i wondering whether python equivalent achieve result something like try shutilmovesrc dst except oserror close src file machines currently accessing try,2 logginggetlogger return exactly object time call so time instantiate logger use oldstyle classes attaching one handler resulting printing one target as targets pointing thing last call debug print three streamhandler objects pointing sysstdout resulting three lines printed,i hate give question heading i actually know whats happening goes i another project i wanted use logging module the code distributed among files amp instead creating separate logger objects seperate files i thought creating logspy contents import sys logging class logger def initself formatter loggingformatter filenameslinenos levelnamesmessages stdouthandler loggingstreamhandlersysstdout stdouthandlersetformatterformatter selfloggerlogginggetlogger selfloggeraddhandlerstdouthandler selfloggersetlevelloggingdebug def debugself message selfloggerdebugmessage use class like different files import logs b logslogger bdebughi apy i stripped whole problem ask question now i files apy bpy amp mainpy all files instantiate logslogger class prints debug message apy amp bpy imports logs prints debug message mainpy imports logs amp b prints debug message the file contents like httpiimgurcomxokvfpng why debug message bpy printed times amp mainpy times,1 first don create class logger just configure existing logger classes exising logging configuration tools second each time create class logger also create new handlers attach new duplicating handler root logger this leads duplication messages if several modules must run standalone also run part larger composite application need this assure logging configuration done import logging logger logginggetlogger file unique logger b main name main loggingbasicconfig streamsysstdout levelloggingdebug format filenameslinenos levelnamesmessages from point forward use logger object loggerinfo hi,i hate give question heading i actually know whats happening goes i another project i wanted use logging module the code distributed among files amp instead creating separate logger objects seperate files i thought creating logspy contents import sys logging class logger def initself formatter loggingformatter filenameslinenos levelnamesmessages stdouthandler loggingstreamhandlersysstdout stdouthandlersetformatterformatter selfloggerlogginggetlogger selfloggeraddhandlerstdouthandler selfloggersetlevelloggingdebug def debugself message selfloggerdebugmessage use class like different files import logs b logslogger bdebughi apy i stripped whole problem ask question now i files apy bpy amp mainpy all files instantiate logslogger class prints debug message apy amp bpy imports logs prints debug message mainpy imports logs amp b prints debug message the file contents like httpiimgurcomxokvfpng why debug message bpy printed times amp mainpy times,1 specify name logger otherwise always use root logger import sys logging class logger def initself name formatter loggingformatter filenameslinenos levelnamesmessages stdouthandler loggingstreamhandlersysstdout stdouthandlersetformatterformatter selfloggerlogginggetloggername selfloggeraddhandlerstdouthandler selfloggersetlevelloggingdebug def debugself message selfloggerdebugmessage httpdocspythonorghowtologginghtmladvancedloggingtutorial a good convention use naming loggers use modulelevel logger module uses logging named follows logger logginggetloggername,i hate give question heading i actually know whats happening goes i another project i wanted use logging module the code distributed among files amp instead creating separate logger objects seperate files i thought creating logspy contents import sys logging class logger def initself formatter loggingformatter filenameslinenos levelnamesmessages stdouthandler loggingstreamhandlersysstdout stdouthandlersetformatterformatter selfloggerlogginggetlogger selfloggeraddhandlerstdouthandler selfloggersetlevelloggingdebug def debugself message selfloggerdebugmessage use class like different files import logs b logslogger bdebughi apy i stripped whole problem ask question now i files apy bpy amp mainpy all files instantiate logslogger class prints debug message apy amp bpy imports logs prints debug message mainpy imports logs amp b prints debug message the file contents like httpiimgurcomxokvfpng why debug message bpy printed times amp mainpy times,1 you try code import random n countlist rangen randomshufflecountlist countlist value countlistpop whatever want value,i taken count something came n now i would like list containing n numbers example n countlist how would i able also i created list i would like randomly select number list use number after i would like select another number remaining numbers list n use also this goes list empty could someone please help thanks,3 as first part n countlist xrangen countlist as second read httpdocspythonorglibraryrandomhtml random import choice choicecountlist countlistremovea countlist that general idea by way may also interested reading httpcodeactivestatecomrecipesrandomselectionofelementsinalistwithnorep there implementations fast random selection,i taken count something came n now i would like list containing n numbers example n countlist how would i able also i created list i would like randomly select number list use number after i would like select another number remaining numbers list n use also this goes list empty could someone please help thanks,1 you create enumeration elements something like mylist listxrange use randomchoice function select items import random randomchoicemylist edit as asim ihsan correctly stated answer yet address full problem op to remove values list simply listremove called import random value randomchoicemylist mylistremovevalue,i taken count something came n now i would like list containing n numbers example n countlist how would i able also i created list i would like randomly select number list use number after i would like select another number remaining numbers list n use also this goes list empty could someone please help thanks,3 you need count stuff want pick random element just use randomchoice pass iterable import random items foo bar baz print randomchoiceitems if really count use randomrandint count,i taken count something came n now i would like list containing n numbers example n countlist how would i able also i created list i would like randomly select number list use number after i would like select another number remaining numbers list n use also this goes list empty could someone please help thanks,1 you use import random randomchoicerangen randomchoicerangen want n,i taken count something came n now i would like list containing n numbers example n countlist how would i able also i created list i would like randomly select number list use number after i would like select another number remaining numbers list n use also this goes list empty could someone please help thanks,1 have seen configuration files work read rc files sometimes called bashrc vimrc etc there usually multistep search configuration file local directory myprojectconf user home directory usermyprojectconf a standard systemwide directory etcmyprojectmyprojectconf a place named environment variable myprojectconf the python installation would last place look config none loc oscurdir ospathexpanduser etcmyproject osenvirongetmyprojectconf try openospathjoinlocmyprojectconf source configreadfp source except ioerror pass,in development mode i following directory tree myproject setuppy myproject initpy mainpy conf myprojectconf i use configparser parse myprojectconf file in code easy load file good path myprojectconfmyprojectconf the problem when i install project using setuppy configuration file situated thanks setuppy etcmyprojectmyprojectconf application usrlibpythonversionsitepackagesmyproject how i refer myprojectconfmyprojectconf file project production mode refer local file myprojectconfmyprojectconf devel mode in addition i would like portable possible work windows example what good practice,3 if using setuptools see chapter using nonpackage data files don try look files,in development mode i following directory tree myproject setuppy myproject initpy mainpy conf myprojectconf i use configparser parse myprojectconf file in code easy load file good path myprojectconfmyprojectconf the problem when i install project using setuppy configuration file situated thanks setuppy etcmyprojectmyprojectconf application usrlibpythonversionsitepackagesmyproject how i refer myprojectconfmyprojectconf file project production mode refer local file myprojectconfmyprojectconf devel mode in addition i would like portable possible work windows example what good practice,3 in django able use function reverselazy djangocoreurlresolvers import reverselazy urlpatterns patternsmyappviews r redirectto url reverselazymyapptitle rptitle article namemyapptitle reverselazy resolves url given string name parameter provided argument reverselazy if working earlier version specify full path course violates dry principle r redirectto url myapptitle,the url config app currently looks like djangoconfurlsdefaults import patterns djangoviewsgenericsimple import redirectto urlpatterns patternsmyappviews r redirectto url main rptitle article this works fine app’s urls used without prefix now want include app’s urls project’s url config prefix like urlpatterns patterns rmyapp includemyappurls but httpmyserverorgmyapp isn’t redirected httpmyserverorgmyappmain httpmyserverorgmain i think i understand works the project’s url patterns get myapp this matches prefix stripped away leaving passed app’s patterns the app agnostic stripping redirects main django interprets main doesn’t work deeper nested urls see edit how tell django redirect url relative app’s prefix edit mistake aah above code works fine browser cached permanent redirect previous url main i cleared cache new url main temporary prevent caching works fine sorry but i realized answer would helpful i want go url relative app’s root deeper nesting relative may work httpmyserverorgmyappfoo httpmyserverorgmyappfoobar,1 what ascii encoded mean as know code expected base input produced base output removing calls bdecode bencode encrypt decrypt functions let pass raw data decode input java raw bytes,i trying decrypt python mcrypto encrypted message generated java library my code i actually found works decrypting messages encrypted java library i get following error evperror wrong final block length i tried aescbc aesecb i get error i guess failure java result ascii encoded python code expecting encoding works base i know make change python code i open use python encryption library thanks import mcrypto base import bencode bdecode enc dec def aesbuildcipherkey iv openc return mcryptoevpcipheralg aescbc keykey iviv opop def aesencryptorkeymsg ivnone decode key iv key bdecodekey iv none iv else iv bdecodeiv return encryption function def encryptdata cipher aesbuildcipherkey iv enc v cipherupdatedata v v cipherfinal del cipher v bencodev return v print aes encryption successfuln return encryptmsg def aesdecryptorkeymsg ivnone decode key iv key bdecodekey print key print iv none iv else iv bdecodeiv return decryption function def decryptdata data bdecodedata cipher aesbuildcipherkey iv dec v cipherupdatedata v v cipherfinal del cipher return v print aes dencryption successfuln return decryptmsg name main result aesdecryptorbencodesecretkey msgencryptedmessage,1 after i would like select another number remaining numbers list n use also then arguably really want create list numbers n purpose picking one ask random number range directly instead explicitly creating choose instead shuffle list fortunately random module covered use randomshuffle of course huge list numbers want draw certainly makes sense draw using randomchoice remove but want select numbers range corresponds count items are going use number select one items don going way make things complicated if want select one items directly randomchoice,i taken count something came n now i would like list containing n numbers example n countlist how would i able also i created list i would like randomly select number list use number after i would like select another number remaining numbers list n use also this goes list empty could someone please help thanks,1 replace uclick click the u indicates unicode string type unicode instead str python python distinction str unicode types gone u scrapped,i following tutorial httpsebsauvagenetpythonguiaddbutton making widgets tkinter i making sure follow carefully i run step i get invalid syntax error here code import tkinter class simpleapptktkintertk def initselfparent tkintertkinitselfparent selfparent parent selfinitialize def initializeself selfgrid selfentry tkinterentryself selfentrygridcolumnrowsticky ew button tkinterbuttonselftextuclick buttongridcolumnrow name main app simpleapptknone apptitle application appmainloop the idle points error line selecting second quotation marks button tkinterbuttonselftextuclick the tutorial written python i using python can anyone see error fix python thanks advance help i new programming english native language,2 there u prefix unicode strings python,i following tutorial httpsebsauvagenetpythonguiaddbutton making widgets tkinter i making sure follow carefully i run step i get invalid syntax error here code import tkinter class simpleapptktkintertk def initselfparent tkintertkinitselfparent selfparent parent selfinitialize def initializeself selfgrid selfentry tkinterentryself selfentrygridcolumnrowsticky ew button tkinterbuttonselftextuclick buttongridcolumnrow name main app simpleapptknone apptitle application appmainloop the idle points error line selecting second quotation marks button tkinterbuttonselftextuclick the tutorial written python i using python can anyone see error fix python thanks advance help i new programming english native language,1 the error pretty much describes problem you missing call patterns first definition urlpatterns,i got error urls typeerror concatenate tuple list tuple can get i wrong where list djangoconf import settings djangoconfurlsdefaults import patterns include url uncomment next two lines enable admin djangocontrib import admin adminautodiscover urlpatterns googleapiapiappviews r firstview urlpatterns patterns uncomment admindoc line enable admin documentation r admindoc include djangocontribadmindocsurls uncomment next line enable admin r admin includeadminsiteurls static files url r sitemediamediappath djangoviewsstaticserve documentroot settingsmediaroot r sitemediastaticppath djangoviewsstaticserve documentroot settingsstaticroot django config traceback file homeienvgoogleapilibpythonsitepackagesdjangocorehandlersbasepy getresponse requestpathinfo file homeienvgoogleapilibpythonsitepackagesdjangocoreurlresolverspy resolve pattern selfurlpatterns file homeienvgoogleapilibpythonsitepackagesdjangocoreurlresolverspy geturlpatterns patterns getattrselfurlconfmodule urlpatterns selfurlconfmodule file homeienvgoogleapilibpythonsitepackagesdjangocoreurlresolverspy geturlconfmodule selfurlconfmodule importmoduleselfurlconfname file homeienvgoogleapilibpythonsitepackagesdjangoutilsimportlibpy importmodule importname file homeiworkspaceapirootgoogleapigoogleapiurlspy module documentroot settingsstaticroot exception type typeerror exception value concatenate tuple list tuple,2 destroy signal main window must connected gtk mainquit windowconnectdestroy gtkmainquit,is way i tell gtk automatically call gtkmainquit last open window application closeddestroyed if direct feature offering functionality i could think following in window destroy method get list open windows process empty quit is way get list the obvious solution would keep manually track open windows i would want avoid possible,2 typeerror concatenate tuple list tuple it means exactly says it complaining urlpatterns patterns the attempts concatenate chain together two things urlpatterns tuple the value returned patterns list you mix concatenation to fix must first decide whether want tuple list result concatenating two tuples gives tuple concatenating two lists gives list fix one side accordingly in case apparently want list the value assign urlpatterns first looks like set arguments patterns the simple explanation patrys points meant forgot call function that would give list could append concatenate list second call note also one go urlpatterns patterns patterns where list the result patterns calls explained also documentation presumably i know anything django i good debugging,i got error urls typeerror concatenate tuple list tuple can get i wrong where list djangoconf import settings djangoconfurlsdefaults import patterns include url uncomment next two lines enable admin djangocontrib import admin adminautodiscover urlpatterns googleapiapiappviews r firstview urlpatterns patterns uncomment admindoc line enable admin documentation r admindoc include djangocontribadmindocsurls uncomment next line enable admin r admin includeadminsiteurls static files url r sitemediamediappath djangoviewsstaticserve documentroot settingsmediaroot r sitemediastaticppath djangoviewsstaticserve documentroot settingsstaticroot django config traceback file homeienvgoogleapilibpythonsitepackagesdjangocorehandlersbasepy getresponse requestpathinfo file homeienvgoogleapilibpythonsitepackagesdjangocoreurlresolverspy resolve pattern selfurlpatterns file homeienvgoogleapilibpythonsitepackagesdjangocoreurlresolverspy geturlpatterns patterns getattrselfurlconfmodule urlpatterns selfurlconfmodule file homeienvgoogleapilibpythonsitepackagesdjangocoreurlresolverspy geturlconfmodule selfurlconfmodule importmoduleselfurlconfname file homeienvgoogleapilibpythonsitepackagesdjangoutilsimportlibpy importmodule importname file homeiworkspaceapirootgoogleapigoogleapiurlspy module documentroot settingsstaticroot exception type typeerror exception value concatenate tuple list tuple,1 data mime containers usually encoded using “quotedprintable” codec i know internals imaplib i believe looking quopridecodestring,i want read email messege utf format and working following code i guess take different format the output gives sth like csterreich ã–sterreich so far i thisthanx import imaplib import email imap imaplibimapserver imaploginuser password imapselect typ data imapsearchnone unseen subject subject num datasplit typ data imapfetchnum rfc msg emailmessagefromstringdata typ data imapstorenum flags seen print msg,2 print tuplex instead print x,i construct string python varying number tokens match number entries list x i need write formatted string the following work indicates i trying in example three tokens list three entries blah foo bar x print x i like output string blah foo bar,3 you take look format method python you could define formatting string like blah blah blah blah blah blah x print sformatx blah blah blah blah blah blah,i construct string python varying number tokens match number entries list x i need write formatted string the following work indicates i trying in example three tokens list three entries blah foo bar x print x i like output string blah foo bar,3 you explicitly specifying pid file twistd write pid file you check system see process pid you could also reenable logging custom log observer logs startup event discards log messages then watch log startup event another possibility add another server application exposes internals mentioned then try connecting server looking around see wanted see fact server running seems like good indication process started properly though if make manhole server get ability evaluate arbitrary python code lets inspect state process want you could also application code write extra state file explicitly indicates successful startup make sure delete starting application fine indicator success vs failure,i need reliable way check twistedbased server started via twistd tacfile started successfully it may fail network options setup wrong since i cannot access twistd log logged devnull i need logclutter twistd produces i need find server started successfully within launchscript wraps twistdcall the launchscript bash script like usrbinbash twistd pidfile myservicepid logfile devnull python myservicetac all i found net hacks using ps stuff like but i like approach like i think reliable so i thinking way access internals twisted get currently running twisted applications that way i could query currently running apps name twisted application i named tacfile start i also thinking using twistd executable implementing pythonbased launch script includes twistdcontent like answer question provides i know helps getting status server run so question reliable notugly way tell twisted server started twistd started successfully twistdlogging disabled,3 the u longer used python string literals unicode default see what new python you longer use u literals unicode text however must use b literals binary data,the following code sreplaceuamp uampamp causing error python syntaxerror invalid syntax removing u fixes problem work i using python,3 on python strings unicode there need discovered put u string literal designate unicode instead put b byte literal designate unicode,the following code sreplaceuamp uampamp causing error python syntaxerror invalid syntax removing u fixes problem work i using python,2 note original version question asked read and write cmd window writing you write existing command window code pywinauto import application app applicationapplication appconnectpath rcwindowssystemcmdexe dlg apptopwindow dlgtypekeys hello world notes i installed latest version pywinauto python installation direct mercurial repository command pip install e hghttpscodegooglecomppywinautoeggpywinauto i would make rather robust assuming path cmdexe documentation selecting application httppywinautogooglecodecomhgpywinautodocshowtohtml reading reading existing command window appears somewhat difficult someone pywinautousers mailing list got working amp offering post working example httpthreadgmaneorggmanecomppythonpywinautouserfocus i suggest get touch,i trying connect existing cmd window read content it arbitrary cmd window child process any ideas done python thanks advance omer,1 use researchreg textgroup case patternsearchtextgroup,i attempting write regex python extract part paragraph in paragraph part i wish extract bolded proposal boost bailout fund inject cash banks cut greek debt says reports my regex output follows text proposal boost bailout fund inject cash banks cut greek debt says reports pattern recompiler boost bailoutssdebt print refindallpattern text boost bailout fund inject cash banks cut greek debt although extract correct section right extraction separated parts tuple single line boost bailout fund inject cash banks cut greek debt,1 rather editing installed python code also find errors like def handleerrorrecord raise runtimeerrorrecord handlerhandleerror handleerror handler one handlers giving problem now format error occurs see location,when i lots different modules using standard python logging module following stack trace little help find exactly i badly formed log statement traceback recent call last file usrlibpythonlogginginitpy line emit msg selfformatrecord file usrlibpythonlogginginitpy line format return fmtformatrecord file usrlibpythonlogginginitpy line format recordmessage recordgetmessage file usrlibpythonlogginginitpy line getmessage msg msg selfargs typeerror arguments converted string formatting i starting use python logging module maybe i overlooking something obvious i sure stacktrace useless i using greenlets normal logging module help would appreciated i willing modify source anything make logging library actually give clue problem lies,3 from documentation if one groups present pattern return list groups list tuples pattern one group empty matches included result unless touch beginning another match httpdocspythonorglibraryrehtml if want one match usrbinenv python import text proposal boost bailout fund inject cash banks cut greek debt says reports pattern recompiler boost bailoutssdebt print refindallpattern text,i attempting write regex python extract part paragraph in paragraph part i wish extract bolded proposal boost bailout fund inject cash banks cut greek debt says reports my regex output follows text proposal boost bailout fund inject cash banks cut greek debt says reports pattern recompiler boost bailoutssdebt print refindallpattern text boost bailout fund inject cash banks cut greek debt although extract correct section right extraction separated parts tuple single line boost bailout fund inject cash banks cut greek debt,1 it depends define update website the simplest solution would use urllib get contents given website storing variable quering website contents comparing have running infinite loop set,i need make script notify change made website i sure best way go i know python useful any push right direction would helpful,1 numpy supports mapping binary data directly array like objects via numpymemmap you might able memmap file extract data need via offsets for endianness correctness use numpybyteswap read you use conditional expression check endianness host system structpack f nppi structpack f nppi host bigendian inplace conversion arraynamebyteswaptrue,i large datasets stored binary files hard disk here example file structure file header byte ascii header record start byte int record timestamp sample start byte int data stream sample byte int data stream sample byte int data stream sample byte int data stream sample sample end there samples per record records per file this yields total size bytes the sample rate number records vary sometimes i code detection number per file currently code i use import data arrays works like time import clock numpy import zeros int int hstack array savez struct import unpack ospath import getsize starttime clock filesize getsizeinputfile openinputfile rb openfile inputdata openfileread header inputdata recordsize intheader numberofrecords filesize recordsize samplerate recordsize timeseries zerosdtypeint tseries zerosdtypeint xseries zerosdtypeint yseries zerosdtypeint zseries zerosdtypeint record xrangenumberofrecords timestamp array unpack l inputdata record recordsize record recordsize dtype int unpackedrecord unpack strsamplerate h inputdata record recordsize record recordsize recordt zerossamplerate dtypeint recordx zerossamplerate dtypeint recordy zerossamplerate dtypeint recordz zerossamplerate dtypeint sample xrangesamplerate recordtsample unpackedrecord sample recordxsample unpackedrecord sample recordysample unpackedrecord sample recordzsample unpackedrecord sample timeseries hstack timeseries timestamp tseries hstack tseries recordt xseries hstack xseries recordx yseries hstack yseries recordy zseries hstack zseries recordz savezoutputfile ttseries xxseries yyseries zzseries timetimeseries endtime clock print total time endtime starttime seconds this currently takes seconds per mb file seems high is efficient way i could final solution using numpy fromfile method custom dtype cut runtime seconds x faster original code the final code numpy import savez dtype fromfile ospath import getsize time import clock starttime clock filesize getsizeinputfile openfile openinputfile rb header openfileread recordsize intheader numberofrecords filesize recordsize samplerate recordsize recorddtype dtype timestamp samples samplerate data fromfileopenfile dtype recorddtype count numberofrecords timeseries data timestamp tseries data samples ravel xseries data samples ravel yseries data samples ravel zseries data samples ravel savezoutputfile ttseries xxseries yyseries zzseries fidtimeseries endtime clock print it took endtime starttime seconds,1 f init needs saved call method needs call something like class mydecoratorobject def initself f print inside mydecoratorinit selff f print function saved def callself args print inside mydecoratorcall result selffargs print done f return result mydecorator def afunctiona print print inside afunction afunction what happens decoration original function replaced whatever decorator returns your original code however saving reference afunction getting lost,i trying understand functioning decorators what wrong following code please correct as i understood afunction called turn calls mydecorator also makes call afunction right also pass parameters afunction class mydecoratorobject def initself f print inside mydecoratorinit f prove function definition completed def callself print inside mydecoratorcall mydecorator def afunctiona print print inside afunction print finished decorating afunction afunction,1 your call method missing parameter give afunction class mydecoratorobject def initself f print inside mydecoratorinit f prove function definition completed selffunction f def callself args args magic mirror original parameter list decorated function but better place parameter list function want decorate order minimize error possibilities print inside mydecoratorcall return selffunctionargs mydecorator def afunctiona print print inside afunction print finished decorating afunction afunction afunction,i trying understand functioning decorators what wrong following code please correct as i understood afunction called turn calls mydecorator also makes call afunction right also pass parameters afunction class mydecoratorobject def initself f print inside mydecoratorinit f prove function definition completed def callself print inside mydecoratorcall mydecorator def afunctiona print print inside afunction print finished decorating afunction afunction,1 i use matplotlib reading tiff files import matplotlibpyplot plt i pltimreadtifffile i type ndarray according documentation though actually pil works behind scenes handling tiffs matplotlib reads pngs natively working fine there also pltimsave function saving,i need python routine open import tiff images numpy arrays i analyze modify contained data afterwards save tiffs they basically light intensity maps greyscale representing respective values per pixel i tried find something documentation pil methods concerning tiff i tried figure got bad mode file type supported errors what i need use,3 class mydecoratorobject def initself f print inside mydecoratorinit save reference real function called later selff f def callself args kwargs print inside mydecoratorcall call real function return result passing arguments return selffargs kwargs mydecorator def afunctiona print print inside afunction print finished decorating afunction afunction print finished calling afunction,i trying understand functioning decorators what wrong following code please correct as i understood afunction called turn calls mydecorator also makes call afunction right also pass parameters afunction class mydecoratorobject def initself f print inside mydecoratorinit f prove function definition completed def callself print inside mydecoratorcall mydecorator def afunctiona print print inside afunction print finished decorating afunction afunction,2 one glaring inefficiency use hstack loop timeseries hstack timeseries timestamp tseries hstack tseries recordt xseries hstack xseries recordx yseries hstack yseries recordy zseries hstack zseries recordz on every iteration allocates slightly bigger array series copies data read far this involves lots unnecessary copying potentially lead bad memory fragmentation i accumulate values timestamp list one hstack end would exactly recordt etc if bring sufficient performance improvements i comment body loop would start bringing things back one time see exactly time spent,i large datasets stored binary files hard disk here example file structure file header byte ascii header record start byte int record timestamp sample start byte int data stream sample byte int data stream sample byte int data stream sample byte int data stream sample sample end there samples per record records per file this yields total size bytes the sample rate number records vary sometimes i code detection number per file currently code i use import data arrays works like time import clock numpy import zeros int int hstack array savez struct import unpack ospath import getsize starttime clock filesize getsizeinputfile openinputfile rb openfile inputdata openfileread header inputdata recordsize intheader numberofrecords filesize recordsize samplerate recordsize timeseries zerosdtypeint tseries zerosdtypeint xseries zerosdtypeint yseries zerosdtypeint zseries zerosdtypeint record xrangenumberofrecords timestamp array unpack l inputdata record recordsize record recordsize dtype int unpackedrecord unpack strsamplerate h inputdata record recordsize record recordsize recordt zerossamplerate dtypeint recordx zerossamplerate dtypeint recordy zerossamplerate dtypeint recordz zerossamplerate dtypeint sample xrangesamplerate recordtsample unpackedrecord sample recordxsample unpackedrecord sample recordysample unpackedrecord sample recordzsample unpackedrecord sample timeseries hstack timeseries timestamp tseries hstack tseries recordt xseries hstack xseries recordx yseries hstack yseries recordy zseries hstack zseries recordz savezoutputfile ttseries xxseries yyseries zzseries timetimeseries endtime clock print total time endtime starttime seconds this currently takes seconds per mb file seems high is efficient way i could final solution using numpy fromfile method custom dtype cut runtime seconds x faster original code the final code numpy import savez dtype fromfile ospath import getsize time import clock starttime clock filesize getsizeinputfile openfile openinputfile rb header openfileread recordsize intheader numberofrecords filesize recordsize samplerate recordsize recorddtype dtype timestamp samples samplerate data fromfileopenfile dtype recorddtype count numberofrecords timeseries data timestamp tseries data samples ravel xseries data samples ravel yseries data samples ravel zseries data samples ravel savezoutputfile ttseries xxseries yyseries zzseries fidtimeseries endtime clock print it took endtime starttime seconds,1 you may use lastmodified date remote page import urllib u urlliburlopenhttpwwwgooglecom uinfogetlastmodified,i need make script notify change made website i sure best way go i know python useful any push right direction would helpful,2 joinlinerstrip line f,probably simple question i new python i file containing email addresses one per line i want read file append together separated comma is pythonic way def getemaillistfilename f openfilename r emailstr line f emailstr linerstrip fclose return emailstr,1 you could following def getemaillistfilename openfilename f return joinxrstrip x f the key features version using statement file automatically closed control leaves block using list comprehension generator expression xrstrip x f strip line thanks agf correction using strjoin put item sequence,probably simple question i new python i file containing email addresses one per line i want read file append together separated comma is pythonic way def getemaillistfilename f openfilename r emailstr line f emailstr linerstrip fclose return emailstr,3 timestrptime python it returns time tuple converted datetime shown start timestrptime ymd hms start datetimedatetimestart,i datetime field sql its content i want know much time passed date in python easy import timedatetime start datetimedatetimestrptime ymd hms end datetimedatetimenow delta start end print delta but i web server running python in python strptime datetime module i figure accomplish thing,3 with command line curl save json file say datajson then try curl x post datajson httpyourserviceurl it also possible enter json directly parameter sounds like know already get quoting escaping exactly correct,a user needs pass json object part request it would look something like token ayaljltja addresses name home address main street city newyork name work address x street city ohio i two problems right first i figure test code recreating nested post i successfully post dict posting list addresses within json object messing simply using curl might i how might i urrlib my second issue deserializing json post object server side i guess i need see successful post determine input deserialize json module any tips,1 i assume using plex xml api the documentation states call xmlelementfromurlfeed encoding gb know really encoding used if xml really encoded gb declaration must xml version encodinggb begin byte order mark utf otherwise xml invalid if encoding xml declaration byte order mark parsers must assume utf encoding default therefore invalid use character encoding xml without encoding declaration since specifying encoding produces error i think possible rss feed valid xml,i rss feed shich encoded gb when i trying parse using following code item xmlelementfromurlfeedxpath item title itemfind title text it able parse feed any idea parse gb encoded rss feed the error log plex media server using encoding item xmlelementfromurlfeed encoding gb xpath item title itemfind title text error log file cdocuments settingssubhenduswainlocal settingsapplication dataplex media serverpluginszaobaobundlecontentscodeinitpy line getdetails item xmlelementfromurlfeed encoding gb xpath item file cdocuments settingssubhenduswainlocal settingsapplication dataplex media serverpluginsframeworkbundlecontentsresourcesversionspythonframeworkapiparsekitpy line elementfromurl return selfelementfromstringselfcorenetworkinghttprequesturl values headers cachetime autoupdate encoding errors immediatetrue sleepsleep openerselfopener txnidselftxnidcontent ishtmlishtml file cdocuments settingssubhenduswainlocal settingsapplication dataplex media serverpluginsframeworkbundlecontentsresourcesversionspythonframeworkapiparsekitpy line elementfromstring return selfcoredataxmlfromstringstring ishtml file cdocuments settingssubhenduswainlocal settingsapplication dataplex media serverpluginsframeworkbundlecontentsresourcesversionspythonframeworkcomponentsdatapy line fromstring return etreefromstringmarkup file lxmletreepyx line lxmletreefromstring srclxmllxmletreec file parserpxi line lxmletreeparsememorydocument srclxmllxmletreec file parserpxi line lxmletreeparsedoc srclxmllxmletreec file parserpxi line lxmletreebaseparserparsedoc srclxmllxmletreec file parserpxi line lxmletreeparsercontexthandleparseresultdoc srclxmllxmletreec file parserpxi line lxmletreehandleparseresult srclxmllxmletreec file parserpxi line lxmletreeraiseparseerror srclxmllxmletreec xmlsyntaxerror switching encoding encoder error line column debug core response,1 you could also use gdal i realize geospatial toolkit nothing requires cartographic product link precompiled gdal binaries windows assuming windows httpwwwgisinternalscomsdk to access array use osgeo import gdal dataset gdalopenpathtodatasettiff gdalgareadonly x xrange datasetrastercount band datasetgetrasterbandx array bandreadasarray,i need python routine open import tiff images numpy arrays i analyze modify contained data afterwards save tiffs they basically light intensity maps greyscale representing respective values per pixel i tried find something documentation pil methods concerning tiff i tried figure got bad mode file type supported errors what i need use,3 you seem confusing terminology a subprocess separate process the processes created children main process program sense subprocesses if want threads use multithreading instead multiprocessing note python use multiple corescpus multiple threads i hesitant use subprocess module seems suited run external processes i sorry i understand remark,i writing program uses multiple worker processes preforking model following code multiprocessing import process range processtargetworker argsistart i use windows i notice run separate processes i wanted start subprocesses instead how i make subprocesses main process i hesitant use subprocess module seems suited run external processes far i used an update it seems windows launch new processes subprocesses python doesnt support getppid get parent pid windows,2 short answer httpdocspythonorglibrarythreadinghtml longer i understand question aitchnyu in typical unix model processes process start subprocesses i strong feeling vocabulary conflict two us i know unravel you seem something like internal process mind example language operating system i attest python subprocess module widely used you write multiple working threads have read documentation i refer first line top response,i writing program uses multiple worker processes preforking model following code multiprocessing import process range processtargetworker argsistart i use windows i notice run separate processes i wanted start subprocesses instead how i make subprocesses main process i hesitant use subprocess module seems suited run external processes far i used an update it seems windows launch new processes subprocesses python doesnt support getppid get parent pid windows,1 what wall subprocess to subprocess main process here example returned output import time os multiprocessing import process def worker print i process father osgetpid osgetppid print i main process osgetpid range processtargetworkerstart the output i main process i process father i process father i process father you subprocesses attached main process,i writing program uses multiple worker processes preforking model following code multiprocessing import process range processtargetworker argsistart i use windows i notice run separate processes i wanted start subprocesses instead how i make subprocesses main process i hesitant use subprocess module seems suited run external processes far i used an update it seems windows launch new processes subprocesses python doesnt support getppid get parent pid windows,2 this difficult problem social space there tradeoff two approaches push when user produces event eg status update push status update stream user friends when user loads stream read record single place pull when user produces event write even user data record when user loads stream poll data record friends aggregating results fly the push method good loading stream happens much often user updates fanout users eg maximum number followers user low the pull method good user loading stream rare number users user follow low i coauthored paper efficiently basically used hybrid method determining push pull based user statistics for simplicity i would recommend implement pull model cache results aggregation refresh user feed cache entry stale certain period time,i trying something like stream facebook socketio tornadio each user comet channelgroup wall i sending comet message wall friends even online the problem scaling million friends it would take long time write walls is solution efficient using comet,1 first make sure json valid paste jsonlint web page currently json two issues comma token ayaljltja addresses single quote valid way delimiting json string replace double quotes,a user needs pass json object part request it would look something like token ayaljltja addresses name home address main street city newyork name work address x street city ohio i two problems right first i figure test code recreating nested post i successfully post dict posting list addresses within json object messing simply using curl might i how might i urrlib my second issue deserializing json post object server side i guess i need see successful post determine input deserialize json module any tips,1 i problem in mcrypto install file note fedora core based distributions fedora core redhat centos etc made changes openssl configuration compared many linux distributions if build mcrypto normally try fedorasetupsh script included mcrypto sources my solution get sources pypi source then mcrypto directory chmod x fedorasetuppy fedorasetuppy install if using virtualenv change path python interpreter file activate environment building the dependency i satisfied system openssldevel,i trying install mcrypto centos compiling source python setuppy build but i get following error usrlocallibpythondistutilsdistpy userwarning unknown distribution option testsuite warningswarnmsg running build running buildpy running buildext building mcryptomcrypto extension swigging swigmcryptoi swigmcryptowrapc swig python iusrlocalincludepython iusrinclude includeall swigmcryptowrapc swigmcryptoi swigmcryptoi error unable find opensslopensslvh swigevpi error unable find opensslopensslconfh swigeci error unable find opensslopensslconfh error command swig failed exit status please advise prasanna,3 use cycle template tag,in template i looping list trying make twocolumn layout because desired twocolumn layout markup i need write loop dependent whether forloopcounter even odd if i full power python template language determining parity forloopcounter would trivial unfortunately case how i test whether forloopcounter even odd using django template language good another way i could get elements list display alternatively left right columns thanks advance,1 clearest fastest way you also consider using set constructing set list may take time faster membership testing save the way certain benchmark well also depends operations require,i searching fastest way know value exists list list millions values index i know values list unique like example my first methods i try issec real code acount baindex do something variable b my second methods i try x fastersec real code try baindex except valueerror do nothing else do something variable b proposed methods so user sec real code aindex in real code first method take sec second methods take sec it good improvement i beginner pythonscripting i want know fastest way exist things save process time more specific explication application in api blender access list particles particles etc from i access location particlesxlocation xyz and i test particles neighbour exist searching location particles like xyz particleslocation find identity neighbour particles xthe index particles array particlesindexxyz,3 you could put items set set lookups efficient try seta stuff edit in comment say like get index element unfortunately sets notion element position an alternative presort list use binary search every time need find element,i searching fastest way know value exists list list millions values index i know values list unique like example my first methods i try issec real code acount baindex do something variable b my second methods i try x fastersec real code try baindex except valueerror do nothing else do something variable b proposed methods so user sec real code aindex in real code first method take sec second methods take sec it good improvement i beginner pythonscripting i want know fastest way exist things save process time more specific explication application in api blender access list particles particles etc from i access location particlesxlocation xyz and i test particles neighbour exist searching location particles like xyz particleslocation find identity neighbour particles xthe index particles array particlesindexxyz,3 you use divisibleby filter forloopcounter forloopcounterdivisibleby even else odd endif,in template i looping list trying make twocolumn layout because desired twocolumn layout markup i need write loop dependent whether forloopcounter even odd if i full power python template language determining parity forloopcounter would trivial unfortunately case how i test whether forloopcounter even odd using django template language good another way i could get elements list display alternatively left right columns thanks advance,1 you probably use cycle instead as question filter called divisibleby the philosophy behind django template system avoid serious logic template thus provide tools fairly basic calculations cases like drawing grids etc,in template i looping list trying make twocolumn layout because desired twocolumn layout markup i need write loop dependent whether forloopcounter even odd if i full power python template language determining parity forloopcounter would trivial unfortunately case how i test whether forloopcounter even odd using django template language good another way i could get elements list display alternatively left right columns thanks advance,3 the problem writing file the problem n line break inside what really want either i like n ride bike r i like n ride bike notice r prefix,i using csv module python escape characters keep messing csv for example i following import csv rowwriter csvwriteropen bikecsv w delimiter text i like n ride bike text pumpkin sauce rowwriterwriterowtext text rowwriterwriterow chicken wings i would like csv look like i like n ride bikepumpkin sauce chickenwings but instead turns i like ride bikepumpkin sauce chickenwings i tried combinations quoting doublequote escapechar parameters csv module i seem make work does anyone know whats note i also using codecs encodeutf text really looks like i like n ride bikeencodeutf,1 first import oauth module set service url consumer information import oauth requesttokenurl httpwwwtumblrcomoauthrequesttoken authorizationurl httpwwwtumblrcomoauthauthorize accesstokenurl httpwwwtumblrcomoauthaccesstoken consumerkey yourconsumerkey consumersecret yourconsumersecret consumer oauthconsumerconsumerkey consumersecret client oauthclientconsumer step get request token this temporary token used user authorize access token sign request obtain said access token resp content clientrequestrequesttokenurl get requesttoken dicturlparseparseqslcontent print request token print oauthtoken requesttoken oauthtoken print oauthtokensecret requesttoken oauthtokensecret step redirect provider since cli script redirect in web application would redirect user url print go following link browser print soauthtokens authorizationurl requesttoken oauthtoken after user granted access consumer provider redirect whatever url told redirect you usually define oauthcallback argument well oauthverifier rawinput what pin step once consumer redirected user back oauthcallback url request access token user approved you use request token sign request after done throw away request token use access token returned you store access token somewhere safe like database future use token oauthtokenrequesttoken oauthtoken requesttoken oauthtokensecret tokensetverifieroauthverifier client oauthclientconsumer token resp content clientrequestaccesstokenurl post accesstoken dicturlparseparseqslcontent print access token print oauthtoken accesstoken oauthtoken print oauthtokensecret accesstoken oauthtokensecret print now access token call protected methods edit turns tumblr support pin authorization method relevant post,i new oauth in past twitter applications written python used pythonoauth library initialize client like consumer oauthconsumerkey consumerkey secret consumersecret token oauthtokenkey accesskey secret accesssecret client oauthclientconsumer token that easy twitter provides consumer access keys secrets but need tumblr the problem tumblr provides consumerkey consumersecret urls requesttoken url httpwwwtumblrcomoauthrequesttoken authorize url httpwwwtumblrcomoauthauthorize accesstoken url httpwwwtumblrcomoauthaccesstoken using data initialize client access tumblr api upd jterrace suggested code tried use the problem oauthcallback if specify api returns error no oauthcallback specified specify url like httpexamplecomoauthcb follow link httpwwwtumblrcomoauthauthorizeoauthtokenygtf press allow button tumblr show pin code page immediately redirects callback url useless since desktop application why pin code shown upd tumblr api support pin code authorization use xauth instead httpsgroupsgooglecomgrouptumblrapibrowsethreadthreadeabdccdlnkgstampqpindccd,3 solved thanks patrys graham dumpleton clear custom build python wsgi installation wrong critical library linking absent now problem resolved following instruction resolved issue thanks smart kind people sharing information reinstall python httpaskubuntucomquestionswillpythonbeavailableforlucidinfuture then uninstall wsgi sudo aptget purge libapachemodwsgi install wsgi httpgrokzopeorgdocumentationtutorialinstallingandsettingupgrokundermodwsgiinstallingandconfiguringmodwsgi,environment ubuntu lts build python configure withzlib enableunicodeucs postgresql wsgi django virtualenv apache i trying build ubuntu django app server the installation completed error message the exact installation method successful ubuntu however installation completed ubuntu try load psycopg django i got following error i get error file homenreevesvenvlibpythonsitepackagesdjangodbbackendspostgresqlpsycopgbasepy line module raise improperlyconfigurederror loading psycopg module e improperlyconfigured error loading psycopg module homenreevesvenvlibpythonsitepackagespsycopgpsycopgso undefined symbol pyobjectnextnotimplemented my guess linkage library incorrect i idea start i following output sure help help ldd homenreevesvenvlibpythonsitepackagespsycopgpsycopgso linuxgateso xbda libpqso usrliblibpqso xb libpthreadso libtlsicmovlibpthreadso xbf libcso libtlsicmovlibcso xb libsslso libicmovlibsslso xbcc libcryptoso libicmovlibcryptoso xba libkrbso usrliblibkrbso xbc libcomerrso liblibcomerrso xbc libgssapikrbso usrliblibgssapikrbso xb libldaprso usrliblibldaprso xbe libldlinuxso xbdb libdlso libtlsicmovlibdlso xba libzso liblibzso xb libkcryptoso usrliblibkcryptoso xb libkrbsupportso usrliblibkrbsupportso xb libkeyutilsso liblibkeyutilsso xb libresolvso libtlsicmovlibresolvso xbf liblberso usrlibliblberso xbe libsaslso usrliblibsaslso xbcb libgnutlsso usrliblibgnutlsso xbf libtasnso usrliblibtasnso xbe libgcryptso liblibgcryptso xbab libgpgerrorso liblibgpgerrorso xba and following command outputs ls l usrliblibpq rwrr root root usrliblibpqa lrwxrwxrwx root root usrliblibpqso libpqso lrwxrwxrwx root root usrliblibpqso libpqso rwrr root root usrliblibpqso to appears correct any advice would appreciated,1 b c return find whatever value want array this fastest way know chosen value array,i searching fastest way know value exists list list millions values index i know values list unique like example my first methods i try issec real code acount baindex do something variable b my second methods i try x fastersec real code try baindex except valueerror do nothing else do something variable b proposed methods so user sec real code aindex in real code first method take sec second methods take sec it good improvement i beginner pythonscripting i want know fastest way exist things save process time more specific explication application in api blender access list particles particles etc from i access location particlesxlocation xyz and i test particles neighbour exist searching location particles like xyz particleslocation find identity neighbour particles xthe index particles array particlesindexxyz,3 you download appengine sdk set pythonpath calling make html for example i downloaded sdk ls homejterracedownloadsgoogleappenginegoogle appengine initpy net pyglib storage pythonpathhomejterracedownloadsgoogleappenginegoogle python python r apr gcc linux type help copyright credits license information import appengine import appengineapi so would something like pythonpathhomejterracedownloadsgoogleappenginegoogle make html,i google app engine project i trying document sphinx i trying use autodoc feature many modulesclassesfunctions my sphinx rest markup automodule urls members urls when i run make html i get error warning autodoc importfind module urls reported error no module named appengineapi please check spelling syspath the file urls imports webapp i believe turn try import appengineapi i think possible provide appengineapi syspath is workaround ps i married sphinx i would open epydoc alternatives,1 unfortunately colleague also problem already uninstalled csvn thing i check but reading doc suggests culpable variable might pythonhome check whether set try unsetting,i installed cygwin windows xp mercurial cygwin stopped working i installed software windows the symptom simplified python able locate modules library import os traceback recent call last file stdin line module importerror no module named os one pieces software i installed windows subversion uses python windows python installation don ask i wish use mercurial cygwin subversion windows suffice say i beside point it seems cygwin tries use windows python instead least i think happening if cause please enlighten anyway find cygdrivec name ospy cygdriveccsvnpythonlibospy cygdriveccygwinlibpythonospy echo path confirms cygdriveccsvnpython usrlibpython i cygwin wiz i tell etcprofile adds windows path cygwin path i know keep as workaround i modified profile explicitly set path excluding paths windows but problem remains echo path usrlocalbinusrbinusrlibpython hg import site failed use v traceback traceback recent call last file usrbinhg line module import os importerror no module named os ls usrlibpythonospy usrlibpythonospy it looks like path conflict actually resolved i issue find command i get results cygdriveccsvnpythonlibospy showing first in theory may reason python working cygwin able control path would still problem any ideas,3 this done onm n lengths input strings the pseudocode function lcsubstrsm tn l arraym n z ret j n si tj j lij else lij lij lij z z lij ret lij z ret ret ∪ sizz return ret see longestcommonsubstringproblem wikipedia article details,how find intersections also called longest common substrings two strings positions strings for example snever sforever resulted intersection must ever positions if saddress soddness resulted intersections ddess positions shortest solution without including library preferable but correct solution also welcomed,3 first i downloaded test tiff image page called aimagetif then i opened pil like pil import image im imageopen aimagetif imshow this showed rainbow image to convert numpy array simple import numpy imarray numpyarrayim we see size image shape array match imarrayshape imsize and array contains uint values imarray array dtypeuint once done modifying array turn back pil image like imagefromarrayimarray imageimage image model sizex x,i need python routine open import tiff images numpy arrays i analyze modify contained data afterwards save tiffs they basically light intensity maps greyscale representing respective values per pixel i tried find something documentation pil methods concerning tiff i tried figure got bad mode file type supported errors what i need use,3 i guessing tutorial would great help considering planning additionally look ctypes carrying operations way want,currently i accessing mfc c dll using python script everything works well far my next step continuously access dll carry various operations simultaneously i feel multithreading good option could guys suggest good links learn multithreading implement application thanks advance,1 the el packages el python since installed python source perform source installation modules,i installed pythonpycryptoelpp pythonparamikoelrf red hat linux using python version and i import paramiko i get runtimewarning mismatch usrlocallibpythonsitepackagescryptorandomfortunashadpy runtimewarning python c api version mismatch module cryptohashsha this python api version module cryptohashsha version please help resolve problem,1 as far i know need use java eclipse written java even vanilla application made several java components glued together core plugin loader jython might work crosscompile python java bytecode indeed thanks sayth pointing access eclipse apis inside jython so less plugin architecture might look like if get eclipse apis write jython make java wrapper embedding jython instructions if get eclipse functionality jython still write code python eclipse api access happening java layer this annoying proportion evenly split code python java i worked project embedded python c might way around major headache plan right,as far i understand eclipse provide user python bindings default nor projects kind i able find google are thirdparty plugins any tutorial may jython,2 i assuming want substrings match absolute position within respective strings for example abcd bcde matches even though contain bcd address b oddness matchesx true ax bx matches maplambda x x x ziplista listb positions filterlambda x matchesx rangelena substrings filterlambda x xfind x joinmaplambda x axmatchesx rangelenasplit positions substrings dd ess if want substrings squish one line filterlambda x xfind x joinmaplambda x axmaplambda x x x ziplista listbx rangelenasplit,how find intersections also called longest common substrings two strings positions strings for example snever sforever resulted intersection must ever positions if saddress soddness resulted intersections ddess positions shortest solution without including library preferable but correct solution also welcomed,1 here i could come import itertools def longestcommonsubstrings set setsbeginend begin end itertoolscombinationsrangelens set setsbeginend begin end itertoolscombinationsrangelens common setintersectionset maximal com com common sumsfindcom common lencommon return sindexs sindexs maximal checking values longestcommonsubstring address oddness dd ess longestcommonsubstring never forever ever longestcommonsubstring call wall longestcommonsubstring abcd abcd abcd,how find intersections also called longest common substrings two strings positions strings for example snever sforever resulted intersection must ever positions if saddress soddness resulted intersections ddess positions shortest solution without including library preferable but correct solution also welcomed,3 python dynamically typed cases need genericstemplates,i worked months c programmer got used idea genericstemplates interfaces i could pass library without caring object created i start relatively large project probably python i written lot python mostly code data analysis etc wondering exists similar concept language i tried googling come much if answer fine case people generally instead,3 if answer fine case people generally instead duck typing what important approach python dropping technical baggage c learn python new language don try map concepts python c that way lies madness interfaces generics templates doesn matter all static type declaration technology necessary for matter type casting order break rules necessary either,i worked months c programmer got used idea genericstemplates interfaces i could pass library without caring object created i start relatively large project probably python i written lot python mostly code data analysis etc wondering exists similar concept language i tried googling come much if answer fine case people generally instead,3 if problem text initially shows behind button clicked force sizer update adding call panel layout method class mainpanelwxpanel def initself parent supermainpanel selfinitparent atributos bmp wxbitmap imgpng wxbitmaptypepng selfboton wxbitmapbuttonselfbitmapbmp layout selfsizer wxboxsizerwxhorizontal selfsizeraddselfboton selfsetsizerselfsizer selfbindwxevtbuttonselfaddselfboton def addselfevent selfsizeraddwxstatictextselflabel testing selflayout,i want display button i click adds main panel static text automatic adds boxsizer panel i code dosen work good anyone help i desperate thanks import wx class myappwxapp def oninitself selfframe mainframenonetitle selfsettopwindowselfframe selfframeshow return true class mainframewxframe def initself args kwargs supermainframe selfinitargs kwargs atributos selfpanel mainpanelself selfcreatestatusbar layout selfsizer wxboxsizerwxhorizontal selfsizeraddselfpanelwxexpand selfsetsizerselfsizer class mainpanelwxpanel def initself parent supermainpanel selfinitparent atributos bmp wxbitmap imgpng wxbitmaptypepng selfboton wxbitmapbuttonselfbitmapbmp layout selfsizer wxboxsizerwxhorizontal selfsizeraddselfboton selfsetsizerselfsizer selfbindwxevtbuttonselfaddselfboton def addselfevent selfsizeraddwxstatictextselflabel testing name main app myappfalse appmainloop,3 index dictyx xy enumeratea try aindex index except keyerror print not found else print found this good idea change thus dict part use repeatedly if change please provide detail,i searching fastest way know value exists list list millions values index i know values list unique like example my first methods i try issec real code acount baindex do something variable b my second methods i try x fastersec real code try baindex except valueerror do nothing else do something variable b proposed methods so user sec real code aindex in real code first method take sec second methods take sec it good improvement i beginner pythonscripting i want know fastest way exist things save process time more specific explication application in api blender access list particles particles etc from i access location particlesxlocation xyz and i test particles neighbour exist searching location particles like xyz particleslocation find identity neighbour particles xthe index particles array particlesindexxyz,3 they use different collation extraction operator i guess dbkey strong probabilities bind db properties so operator sees different data first say ut source based second weird db collation based dash specific meaning unknown get specification i experienced pain past feeding massive data across db interfaces but internationalization inherently complex,i found interesting curious know db keys ordered differently strings if test following example python development environment true server well see following somewhat unexpected behaviour str agpybhbmnlyxbwchileglvcvytwkzwwyagbgw str agpybhbmnlyxbwchileglvcvytwkzwwykowbbqw result str str true however following key dbkeystr key dbkeystr result key key false,1 i think actually misunderstanding works each time call linereader new linereaderiter generator created it appears work use infile time call readline return next line file consider following simpler example counter lambda nextiterrange counter counter time lambda called new range iter created you get behavior want using following linereader linereaderiterinfilenext here would work range example counter iterrangenext counter counter yay actually using iterator,i following function def linereaderiterfileobject true aline fileobjectreadline lenaline raise stopiteration yield aline somewhere i say linereader lambda nextlinereaderiterinfile clearly lambda works seems difference compiletime vs runtime behaviour welcome linereaderiter puts reference iterator object lambda expression instead creation generator object time lambda evaluated but portable stable behaviour i python novice i know code grey area respect python execution model can someone enligthen slarti,3 got answer mitsuhiko flask lead dev httpflaskpocooorgsnippets you need define reverseproxied class flask app add several proxysetheader lines location foo block nginx config,i like static site root publichtml directory flask apps subdirectories eg publichtmlfoo the static root directory functions expected i spent hours editing nginx configuration get flask apps working always end back place namely following code always returns bad config i migrate mysitefoo i want return hello world if i alter nginx configuration server root publichtmlfoo flask applications work expected ie mysitecom returns hello world in following configuration flask index still points mysitecom i believe point mysitecomfoo etcnginxsitesenabledmysite upstream frontends gunicorn server server listen servername wwwmysitecom rewrite httpmysitecom permanent server listen servername mysitecom servernameinredirect root homeubuntupublichtmlmysite accesslog homeubuntulogsmysiteaccesslog errorlog homeubuntulogsmysiteerrorlog location index indexhtml location foo tryfiles uri foo location foo proxypass httpfrontends break homeubuntupublichtmlmysitefoofoopy flask import flask flask import rendertemplate app flaskname approute def index return hello world approute foo def test return bad config apperrorhandler def pagenotfounde return rendertemplate html name main apprun homeubuntupublichtmlmysitefoodeploypy workers bind procname foogunicorn pidfile foopid flask launched gunicorn c deploypy fooapp update adding rewrite foo break nginx location foo block makes mysitefoo return hello world however links stylesheet template still point site root eg mysitestaticstylecss instead mysitefoostaticstylecss,3 from stack trace python interpreter crashing atexit handlers c library runs process exits specifically looks like code cleans hdf library hitting error i believe crash comes python runtime mostly cleaned library tries invoke error handler handler already gone your c app problem also use uninitialized variable if python always crashes similar stack trace look crashed thread x dump report find x thread crashed backtrace dump something wrong hdf used perhaps known bug mac python port i really sure hdf library,i strange error duplicated machines it may limited python bit clear yet on mac os x i get segmentation fault i get simple segmentation fault whenever i close python however error hard reproduce simple python scripts like python c import sys print sysmaxint open close without issue i suspected issue matplotlib similarly python c import pylab pylabplot pylabshow suffer issues either however number different packages do cause segmentation faults python closes interactive session script finished so error affect code makes mess running anything focusstealing error messages pop i make effort list document scripts modules lead crashes i thought i throw question see anyone else come across similar issue here sample trackback thanks suggestion ned process python path usrlocalbinpython identifier python version code type x native parent process bash datetime os version mac os x b report version interval since last report sec crashes since last report perapp crashes since last report anonymous uuid cefbdafaadbabad crashed thread dispatch queue comapplemainthread exception type excbadaccess sigsegv exception codes kerninvalidaddress x vm regions near x text k rxrwx smcow libraryframeworkspythonframeworkversionsbinpython application specific information objc garbage collection off thread crashed dispatch queue comapplemainthread orgpythonpython xcf newthreadstate orgpythonpython xcfe pygilstateensure heso xc pyxfhpyheerrcallback hec libhdfdylib x hedumpapistack libhdfdylib x hegetauto libhdfdylib xbff htermlibrary libsystemcdylib xfffffbd cxafinalize libsystemcdylib xfffffb exit python xe start python xd start thread dispatch queue comapplelibdispatchmanager libsystemkerneldylib xfffbcfde kevent libdispatchdylib xfffbdfe dispatchmgrinvoke libdispatchdylib xfffbdfe dispatchmgrthread thread libsystemkerneldylib xfffbcfd workqkernreturn libsystemcdylib xfffffa pthreadwqthread libsystemcdylib xfffffbb startwqthread thread libsystemkerneldylib xfffbcfd workqkernreturn libsystemcdylib xfffffa pthreadwqthread libsystemcdylib xfffffbb startwqthread thread libsystemkerneldylib xfffbcfd workqkernreturn libsystemcdylib xfffffa pthreadwqthread libsystemcdylib xfffffbb startwqthread thread libsystemkerneldylib xfffbcfcdf select tcl xebb notifierthreadproc libsystemcdylib xfffffbf pthreadstart libsystemcdylib xfffffbb threadstart thread crashed x thread state bit rax x rbx x rcx xb rdx xffffbff rdi xab rsi xbb rbp xffffbffc rsp xffffbffa r xffffbffc r xffffbff r x r xeaf r xbfb r x r x r xbda rip xcf rfl x cr x logical cpu binary images x xfff python badabeccdfef usrlocalbinpython x xfe orgpythonpython c python software foundation cadddaabade libraryframeworkspythonframeworkversionspython snip too long xfff xfffcdef libobjcadylib compatibility cfdbadbedfffdec usrliblibobjcadylib external modification summary calls made processes targeting process taskforpid threadcreate threadsetstate calls made process taskforpid threadcreate threadsetstate calls made processes machine taskforpid threadcreate threadsetstate vm region summary readonly portion libraries totalm residentm swappedoutorunallocatedm writable regions totalm writtenm residentm swappedoutk unallocatedm region type virtual cg image k cg raster data k cg shared images k coregraphics k coreservices k malloc m malloc guard page k memory tag k memory tag k stack guard m stack m vmallocate m cibitmap k data m image k linkedit m text m unicode k mapped file m shared memory k total m c code produces approximately error helloworldcpp includeiostream using namespace std int main char blah cout hello world endl i c sea endl cin blah cout blah endl return compiled g helloworldcpp helloworldout helloworldout error report process helloworldout path usersuserhelloworldout identifier helloworldout version code type x native parent process bash datetime os version mac os x b report version interval since last report sec crashes since last report perapp crashes since last report anonymous uuid cefbdafaadbabad crashed thread dispatch queue comapplemainthread exception type excbadaccess sigsegv exception codes xd x vm regions near text caca k rxrwx smcow usersuserout thread crashed dispatch queue comapplemainthread helloworldout xcad main x thread crashed x thread state bit rax x rbx x rcx x rdx x rdi xfffcee rsi xfab rbp xfffae rsp xfffad r xfbfb r x r x r x r x r x r x r x rip xcad rfl x cr xfab logical cpu binary images xca xcaff helloworldout fdedfbbedefbdbc usersuserhelloworldout xfffa xfffdac dyld aebcaadbb usrlibdyld xfffbce xfffbdfff libsystemkerneldylib compatibility afdbdaa usrlibsystemlibsystemkerneldylib xfffbdf xfffbefff libdispatchdylib compatibility fefbec usrlibsystemlibdispatchdylib xfffc xfffccfff libcopyfiledylib compatibility bdebceac usrlibsystemlibcopyfiledylib xfffcf xfffcfaff libcommoncryptodylib compatibility abecfbfefb usrlibsystemlibcommoncryptodylib xfffcfcc xfffcfccfff libkeymgrdylib compatibility efedaaebcdf usrlibsystemlibkeymgrdylib xfffcfcd xfffcfdfff libmathcommonadylib compatibility ffaffbeafdca usrlibsystemlibmathcommonadylib xfffd xfffdfff libcompilerrtdylib compatibility ecdfecacdcba usrlibsystemlibcompilerrtdylib xfffebb xfffecfff libsystemdnssddylib fafdddfbdb usrlibsystemlibsystemdnssddylib xfffed xfffedfff libdylddylib compatibility fbadffabebada usrlibsystemlibdylddylib xfffed xfffeaff libxpcdylib compatibility febbdadeaecd usrlibsystemlibxpcdylib xfffe xfffefff libunwinddylib compatibility eccccbefbabeeab usrlibsystemlibunwinddylib xfffebdd xfffebeff libcabidylib compatibility ffddfacced usrliblibcabidylib xffff xfffffff libsystemsandboxdylib dbbfeabcc usrlibsystemlibsystemsandboxdylib xffffe xffffffff libuncdylib compatibility cdebacecf usrlibsystemlibuncdylib xffffd xffffdff libsystemblocksdylib compatibility bcaababbdeaca usrlibsystemlibsystemblocksdylib xffffeda xfffffbfef libsystemcdylib compatibility dabdfdfcccbc usrlibsystemlibsystemcdylib xfffe xfffefff libcachedylib compatibility dcaadfcecbfe usrlibsystemlibcachedylib xfffec xfffffff libstdcdylib compatibility bddeabeedcdff usrliblibstdcdylib xfffeb xfffecfe libsystembdylib compatibility bbcdadecd usrliblibsystembdylib xfffc xfffdfff libdnsinfodylib compatibility fefebcbecebcac usrlibsystemlibdnsinfodylib xfff xffffff libsysteminfodylib bccdabafefd usrlibsystemlibsysteminfodylib xfffe xfffeff libremovefiledylib compatibility aacadaeddfedc usrlibsystemlibremovefiledylib xfff xffffff libnotifydylib compatibility bddacfcbf usrlibsystemlibnotifydylib xfffee xfffefff libquarantinedylib compatibility abcfadcbeccbddcb usrlibsystemlibquarantinedylib xfffe xffffff libmachodylib compatibility baebccbfabcecbcab usrlibsystemlibmachodylib xfff xfffbff liblaunchdylib compatibility ebcbdbacadcf usrlibsystemliblaunchdylib xfffd xfffff libsystemnetworkdylib abceefafecefb usrlibsystemlibsystemnetworkdylib external modification summary calls made processes targeting process taskforpid threadcreate threadsetstate calls made process taskforpid threadcreate threadsetstate calls made processes machine taskforpid threadcreate threadsetstate vm region summary readonly portion libraries totalm residentm swappedoutorunallocatedm writable regions totalm writtenk residentk swappedoutk unallocatedm region type virtual malloc k malloc guard page k stack guard m stack k data k linkedit m text k shared memory k total m model macbookair bootrom mbab processors intel core ghz gb smc f graphics intel hd graphics intel hd graphics builtin mb memory module bank dimm gb ddr mhz xad xdd memory module bank dimm gb ddr mhz xad xdd airport spairportwirelesscardtypeairportextreme xe xe broadcom bcmxx bluetooth version f service devices incoming serial ports serial ata device apple ssd smc gb usb device facetime camera builtin applevendorid xa xfa usb device hubdevice x smsc x xfa usb device brcm hub xac broadcom corp x xfa usb device bluetooth usb host controller applevendorid xf xfa usb device apple internal keyboard trackpad applevendorid xc xfa usb device hubdevice x smsc x xfd usb device internal memory card reader applevendorid x xfd,2 i believe go ahead close another thread thread trying read return error if multiple threads refactor use nonblocking mode option osononblock open socket,i service uses blocking socket receive data the problem i i know properly close socket still waiting data below short snip i opening waiting data i want implement timeouts according python documentation socket must blocking order use makefile i may going completely wrong i new programming sockets edit it noted i cannot alter server operates import socket socketsocketsocketafinet socketsockstream sconnecthost port reader smakefilerb line readerreadline,1 you need use applesupplied gcc comes xcode developer tools there snow leopard version xcode either came mac system restore dvd retail copy snow leopard downloaded free registration apple developer connection,i trying install mysqlpython package following error cc error unrecognized command line option arch cc error unrecognized command line option wnolongdouble error setup script exited error command gcc failed exit status i using mac osx version gcc bash gcc version gcc gcc apple inc build dot how i resolve issue thanks,2 my understanding interfaces java hopefully close enough mean there syntactic way assert particular object set methods fields python uses dynamic typing duck typing if want check whether object certain method field dig reflection work check want dict dictionary object members myobjdicthaskeyo want i think pretty easy just use object trust fellow developers users given proper object maximum easy dangerous or wrap tryexcept block this familiar java programmers designing complex set classes python different experience clike languages prepared things may uncomfortable like option good luck,i worked months c programmer got used idea genericstemplates interfaces i could pass library without caring object created i start relatively large project probably python i written lot python mostly code data analysis etc wondering exists similar concept language i tried googling come much if answer fine case people generally instead,2 the problem i expect exceptions raised inside processes join calls i suggest try wrapping process main method tryexcept loop then flag eg instance multiprocessingvalue except statement sets false each process could check value flag stop cleaning set false note terminate process clean sending sigterm,i python program several processes threads per process i would like catch every exception especially shut program cleanly ctrlc i get work everytime exception occurs program stops shut correctly leaving unusable commandline what i tried far pseudocode try process processes processjoin except pass just suppress errormessages removed later finally process processes processterminate but i already said luck also note i get exception error message processes halted i believe maybe i also mention threads blocked listening pipe edit so i nearly got working i needed try every thread make sure threads joined correctly there one flaw exception keyboardinterrupt module threading usrlibpythonthreadingpyc ignored shutting this raised mainthread mainprocess this thread already finished meaning passed last line code,1 i restored gcc comes mac removed first error cc error unrecognized command line option arch second one i removed option libraryframeworkspythonframeworkversionscurrentlibpythonconfigmakefile basecflags added following bashrc export cincludepathdevelopersdksmacosxsdkusrinclude export librarypathdevelopersdksmacosxsdkusrlib removed error cc error unrecognized command line option wnolongdouble,i trying install mysqlpython package following error cc error unrecognized command line option arch cc error unrecognized command line option wnolongdouble error setup script exited error command gcc failed exit status i using mac osx version gcc bash gcc version gcc gcc apple inc build dot how i resolve issue thanks,3 zopeinterface but people use,i worked months c programmer got used idea genericstemplates interfaces i could pass library without caring object created i start relatively large project probably python i written lot python mostly code data analysis etc wondering exists similar concept language i tried googling come much if answer fine case people generally instead,2 one solution close socket ask server close if server close client socket client receive connection reset peer error may break blocking receive another solution would use readline put timeout socket indefinite wait could wait indefinitely,i service uses blocking socket receive data the problem i i know properly close socket still waiting data below short snip i opening waiting data i want implement timeouts according python documentation socket must blocking order use makefile i may going completely wrong i new programming sockets edit it noted i cannot alter server operates import socket socketsocketsocketafinet socketsockstream sconnecthost port reader smakefilerb line readerreadline,1 astliteralevaluu city u newyork u name u home u displayvalue u main street u city u newyork u name u home u displayvalue u main street,a request object i dealing following value key address uu city u newyork u name u home u displayvalue u main street i need operate unicode object dictionary unfortunately jsonloads fails json compatible object is way deal do i work jsonjsondecoder object,3 i written blog srsessionxenapisrgetbynamelabeldvd drives recorddvdsessionxenapisrgetrecordsr vdidvdrecorddvdvdis vbdconnectcd vdi vdidvd vm vmref userdevice mode ro type cd bootable true unpluggable true empty false otherconfig qosalgorithmtype qosalgorithmparams vbdrefsessionxenapivbdcreatevbdconnectcd here vmref refers uuid newly created vm want add dvd drive every physical dvd drive vdi stored properties one get pass one parameters create vbd linking dvd drive vm,i want add dvd drive vm xenserver using python i created vm using python i want add dvd drive attached host accessible vm also so i need create vbd dvd drive well but i unable get property i need set vbdrecord attaching disk i set vdi property got attached but dvd drive i unable figure property i need set attach cd drive xenserver do help regarding,1 the badroot class demonstrate problem you comment call class verify complete working example if run code written update label goodroot class the first line commented shows alternative syntax changing text label tkinter import tk label time import sleep random import random class badroottk def initself price time superinit selflabels true selflabelsappendlabelself textprice time selflabelspack selfupdate sleep class goodroottk def initself callback superinit selflabel labelself textstrcallback selflabelpack true selflabel text strcallback selflabelconfiguretextstrcallback selfupdate sleep name main badroot pm goodrootrandom the problem original code new label created packed interface time loop what actually want edit text displayed label instead replacing label new one there others ways method work,when i call update method using tkinter instead rewriting label writes label previous call i would like rewrite previous line for example roottk true wlabelroot text price time wpack rootupdate,1 from i see code stack trace emails sent using mailadmins method serveremail specified address mail emailmultialternativesu ss settingsemailsubjectprefix subject message settingsserveremail settingsadmins connectionconnection which defined class emailmultialternativesemailmessage def initself subject body fromemailnone tonone bccnone connectionnone attachmentsnone headersnone alternativesnone ccnone i would suggest putting trace output emailmultialternatives verify proper email address used,as noted docs serveremail setting supposed change from address crash emails sent admins django server but does work or django version django insists using emailhostuser email loginactual address address i using gmail smtp server i wonder could something does gmail block sort thing i swear i gotten work it little annoying multiple projects seem emailing address dig traceback see project,1 batteries included the difflib module might help quick dirty sidebyside diff import difflib listdifflibndiffneverforever n f r e v e r diffs listdifflibndiffneverforever diffs print dd n f r e v e r,how find intersections also called longest common substrings two strings positions strings for example snever sforever resulted intersection must ever positions if saddress soddness resulted intersections ddess positions shortest solution without including library preferable but correct solution also welcomed,2 no i suspect without seen least couple confusions code wdroter written in general not necessary wellstructured tkinter code use update here small example illustrates updates text label import tkinter import time def updatethelabel updatedtext timestrftimethe gm time hms timegmtime wconfiguretext updatedtext root tkintertk w tkinterlabelroot text hello world b tkinterbuttonroot text update label command updatethelabel wpack bpack rootmainloop run push button each time long pushes differ least second see text update,when i call update method using tkinter instead rewriting label writes label previous call i would like rewrite previous line for example roottk true wlabelroot text price time wpack rootupdate,1 actually fifth image blue note white rgb image completely white much blue image completely blue a darker blue smaller blue component white,i took average color method wrote average red green blue database here images sorted blue as see th image blue am i something wrong possible get average color histogram this handler i create histogram class imagesavewebapprequesthandler def postself homepage homepage originalimage selfrequestgetimg url selfrequestgeturl firmname selfrequestgetfirmname originalimage dbbloboriginalimage thumbnail imagesresizeoriginalimage img imagesimagethumbnail hist imghistogram rgbweighedaverage histweighedaveragehist update database homepageoriginalimage originalimage homepagethumbnail thumbnail homepagefirmname firmname homepageurl url homepagered rgbweighedaverage homepagegreen rgbweighedaverage homepageblue rgbweighedaverage homepageput selfredirectimageupload thanks,3 unless using cygwin windows shebang support however install python add file association py files if put name script command line double click windows explorer run python what i include usrbinenv python shebang scripts this allows shebang support linux if run windows machine python installed file association run well,i small utility scripts written python i want usable windows linux i want avoid explicitly invoke python interpreter is easy way point shebang notation correct locations windows linux if another way allow implicit invocation python interpreter windows linux without modify script transferring operating systems edit the shebang support windows provided cygwin i want use native windows python interpreter windows cygwin one edit it appears shebang notation overrides file associations cygwin terminals i guess i could uninstall cygwin python symlink usrbinpython windowsnative python,3 if use curseswrapper handle cleanup set httpdocspythonorglibrarycurseshtmlcurseswrapper,i wrote small program python outputted screen display using curses library for simple output seems work i run python program command line my problem i kill python program terminal properly display for example ls al displays properly i run python curses program ls al display properly i kill python curses program what i make terminal display output properly i kill python curses program,2 i read docs i think use function following parameters i assume x size n p s q a b g vertically stacked in in in identity matrix size n x n and corresponding right hand side h g wb wb cwb cwb that one g n times wb n times cwb hth,i using cvxopt quadratic programming compute optimal weights potfolio using meanvariance optimization there great example httpabeleeuclaeducvxoptuserguideconeproghtmlquadraticprogramming however arguments regularized form according author the example basic version i looking bit complex problem min x sx st x g x x wb x c wb x active weights assets active weight portfolio weight benchmark weight s covariance matrix asset returns expected stock excess returns g target gain wb weights assets benchmark c upper limit weight asset portfolio assume variables computed known the basic example presented documentation min x sx st p x g x where p asset returns what i know referring code httpabeleeuclaeducvxoptexamplesbookportfoliohtml optimization problem i think arguments setup constraints i entirely sure g matrix nn gn h matrix n a matrix n b matrix i believe part minimization problem regulated form i sure means mus tn xrangen what arguments qp solverqp quadratic optimizer xs qpmus pbar g h a b x mu mus looking documentation i pretty sure mus first argument objective function minimzed pbar returns this looks like maximization problem however maximizing negative returns i know however arguments used i looking help using optimizer given minimization problem constraints,1 upgrade version that fixed bug i saw thing,windows i using python idle every time i edit load program i get new pythonwexe process shown windows task managereven program prints hello world this special nuisance program static ram drive i kill processes individually i eject drive is bug idle is way i prevent happening or least way i kill pythonw processes instead one time,2 read carefully httpsdocsdjangoprojectcomendevrefcontribstaticfiles is djangocontribstaticfiles installedapps is debugfalse if need call runserver insecure parameter collectstatic bearing serving files via development server it collecting static files one location staticroot web server find in fact running collectstatic staticroot set path staticfilesdirs bad idea you doublecheck make sure css files even exist,i running django development server runserver local machine mac os x cannot get css files load here relevant entries settingspy staticroot usersusernameprojectsmysitestatic staticurl static staticfilesdirs usersthaymoreprojectsmysitecalstatic staticfilesfinders djangocontribstaticfilesfindersfilesystemfinder djangocontribstaticfilesfindersappdirectoriesfinder djangocontribstaticfilesfindersdefaultstoragefinder installedapps apps djangocontribstaticfiles in viewspy i requesting context return rendertoresponsecalmainhtmldictentriesentriescontextinstancerequestcontextrequest and template staticurl renders correctly link typetextcss href staticurl cssmaincss turns link typetextcss hrefstaticcssmaincss which file actually located i also ran collectstatic make sure files collected i also following lines urlspy djangocontribstaticfilesurls import staticfilesurlpatterns urlpatterns staticfilesurlpatterns i new django probably missing something simple would appreciate help,3 you could ossystemgnometerminal e bash c sudo aptget update exec bash,i developing program button when pressed i want open terminal runs sudo aptget update i using ossystemgnometerminal e sudo aptget update this works fine the problem update finished terminal closes what i leave terminal open,3 there choices add read p hit enter exit end command line add sleep end command line wait bit exit configure gnome terminal go edit menu click current profile click title command tab in setting called when command exits change hold terminal open you could also create new profile,i developing program button when pressed i want open terminal runs sudo aptget update i using ossystemgnometerminal e sudo aptget update this works fine the problem update finished terminal closes what i leave terminal open,2 a small module i wrote pathfinder makes easier opinion anyway find paths pathfinder import pathfind paths pathfindadir justfilestrue it layer top oswalk removes confusion surrounding,the following example walks directory prints names files calls recursively directories import os def walkdir name oslistdirdir path ospathjoindirname ospathisfilepath print path else walkpath ospathjoin takes directory file name joins complete path my exercise modify walk instead printing names files returns list names can someone explain function per line i good idea gets line else walkpath throws since explanation for exercise way i could think change list def walkdir res name oslistdirdir path ospathjoindirname ospathisfilepath resappendpath else walkpath return res my output went many output lines mere did i correctly,1 it unrelated gevent you configure logging eg loggingbasicconfiglevelloggingdebug formatasctimes msgs,i code like log logginggetloggerfile def func print logdebugprinted g geventspawnfunc gjoin i ran log show shell any ideas is better way logging inside gevent based coroutines,3 i believe column type uuid version cassandra ignore unique component uuid use time part range,pycassa pycassautilconverttimetouuidtimearg lowestvaltrue randomizefalse phpcassa static string uuid string node null int time null can phpcassa uuid used get lowesthighest uuids like pycassa if best approach ensure get everything two given timestamps,1 fabric sudo command it uses paramico ssh connections your code would fabfilepy fabricapi import run sudo def update run sudo aptget update lorem ipsum sudoaptget update def hostname run hostname runhostname usage fab update h examplecom examplecom executing task update examplecom sudo aptget update snip examplecom reading package lists done examplecom done disconnecting examplecom done fab display update displaying detailed information task update run sudo aptget update lorem ipsum fab list available commands hostname run hostname update run sudo aptget update from docs in addition use via fab tool fabric’s components may imported python code providing pythonic interface ssh protocol suite higher level provided eg paramiko fabric leverages,i problems commands sudo using paramiko fex sudo aptget update code try import paramiko except try import paramiko except print there error paramiko module cmd sudo aptget update ssh paramikosshclient sshsetmissinghostkeypolicyparamikoautoaddpolicy try sshconnectipusernamelexelpasswordpassword print succesfully conected except print there error conecting stdin stdout stderr sshexeccommandcmd stdinwrite passwordn stdinflush print stderrreadlines print stdoutreadlines this quick code i know i need add sysexit demostration i used reference jessenollercom,1 in list arguments entry must using output subprocesscheckoutputping c w fix problem,i using subprocesscheckoutput pythons subprocess module execute ping command here i output subprocesscheckoutputpingc w it raising calledprocesserror says output one arguments function can anyone help read output i would like read output string parse so say example ping returns packet loss i need capture if better wayplease suggest thanks,3 i believe possible ip address set outgoing packets network stack outside mechanize control,i playing around mechanize website appears differently based ip is way change ip mechanize i tried brsetproxieshttp timesout is something else i supposed make work,1 install pywin one nice thing setups file association py python interpreter,i small utility scripts written python i want usable windows linux i want avoid explicitly invoke python interpreter is easy way point shebang notation correct locations windows linux if another way allow implicit invocation python interpreter windows linux without modify script transferring operating systems edit the shebang support windows provided cygwin i want use native windows python interpreter windows cygwin one edit it appears shebang notation overrides file associations cygwin terminals i guess i could uninstall cygwin python symlink usrbinpython windowsnative python,1 i like using brew none top three explanations worked enticing however i look found brew friendly explanation solution httpjholewinskiorgbloginstallingmatplotlibonosxwithhomebrew summary libpng snow leopard friendly terms matplotlib you manually install unreleased matplotlib work around brew install python brew install gfortran brew install pkgconfig easyinstall pip pip install numpy git clone httpsgithubcommatplotlibmatplotlibgit cd matplotlib python setuppy build python setuppy install,i trying install matplotlib graphing applications python mac os x when i run python setuppy install gives load errors httppastebincomuflic a quick snippet srcftfontcpp error ‘ftloadtargetmono’ declared scope srcftfontcpp error ‘ftloadtargetlcd’ declared scope srcftfontcpp error ‘ftloadtargetlcdv’ declared scope srcftfontcpp error ‘ftlibrary’ declared scope srcftfontcpp error ‘ftinitfreetype’ declared scope srcftfontcpp in destructor ‘virtual ftfontmoduleftfontmodule’ srcftfontcpp error ‘ftlibrary’ declared scope srcftfontcpp error ‘ftdonefreetype’ declared scope lipo figure architecture type varfoldersnjnjnlpqsfsmeswcadnktitmpcchyymmout error command gcc failed exit status i installed freetype using macports i thought would fix issue luck gives error it looks like find right freetype files building matplotlib matplotlib python r mar gcc apple inc build platform darwin required dependencies numpy freetype found unknown version pkgconfig warning could find freetype headers freetype where i put freetype files found right optlocallib any ideas,1 if want map regioncitycategory supposing valid characters azaz following mainpy application webappwsgiapplication www handler debugtrue handler class handlerwebapprequesthandler def getself region city category use variables method hope helps,this posted googlecom wrote hi niklas if want map regioncitycategory supposing valid characters azaz following mainpy application webappwsgiapplication www handlerdebugtrue handler class handlerwebapprequesthandler def getself region city category use variables method hope helps my webapp suppossed handle uri like regioncitycategory optional city category eg riodejaneirogranderiodejaneirocasas regioncitycategory gujaratahmedabadvehiclesforsale regioncitycategory riodejaneirogranderiodejaneiro regioncity delhi region etc now i want enable request handler take optional arguments divided separator if i use regex variables request handler first varible becomes ab second variable becomes b nearly i want b different variables instead the regex i tried request handler application webappwsgiapplication mypage and function head request handler class mypagerequesthandler def getself location frankfurt category electronics to enable http query eg frankfurt frankfurt frankfurtelectronics madridapartments newyork etc allowing possible combinations can advice regex achieve i want i want functionality like modrewrite gae thanks clarification it question make directory variable clarify examples behave frankfurt put frankfurt variable frankfurt put frankfurt variable frankfurtelectronics put frankfurt variable electronics virable frankfurtelectronics eufrankfurtelectronics ie last groups count eufrankfurtelectronics torontolightnings start work torontolightnings limacarsold limacarsold typical cases i want handle regioncitycategory ie i apply example brazil could riodejaneirogranderiodejaneirocasas regioncitycategory india could delhidelhiforsale gujaratahmedabadvehiclesforsale solution as far i tell solution answer works purposes,1 perhaps meant printinputmap also use null line eval raised nameerror you could use simplejsonloads instead import simplejson line id null type null orderfor null name name inputmap simplejsonloadsline printinputmap u orderfor none u type none u id none u name u name printsimplejsondumpsinputmap orderfor null type null id null name name,input id null type null orderfor null name name code inputmap simplejsondumpsevalline print typeinputmap returns type str wrong thank,2 some hints don use struct module instead use numpy structured data types fromfile check httpscipylecturesgithubcomadvancedadvancednumpyindexhtmlexamplereadingwavfiles you read records passing suitable count fromfile something like untested get idea import numpy np file openinputfile rb header fileread parse header recorddtype npdtype timestamp samples samplerate data npfromfilefile dtyperecorddtype countnumberofrecords nb count omitted reads whole file timeseries data timestamp tseries data samples ravel xseries data samples ravel yseries data samples ravel zseries data samples ravel,i large datasets stored binary files hard disk here example file structure file header byte ascii header record start byte int record timestamp sample start byte int data stream sample byte int data stream sample byte int data stream sample byte int data stream sample sample end there samples per record records per file this yields total size bytes the sample rate number records vary sometimes i code detection number per file currently code i use import data arrays works like time import clock numpy import zeros int int hstack array savez struct import unpack ospath import getsize starttime clock filesize getsizeinputfile openinputfile rb openfile inputdata openfileread header inputdata recordsize intheader numberofrecords filesize recordsize samplerate recordsize timeseries zerosdtypeint tseries zerosdtypeint xseries zerosdtypeint yseries zerosdtypeint zseries zerosdtypeint record xrangenumberofrecords timestamp array unpack l inputdata record recordsize record recordsize dtype int unpackedrecord unpack strsamplerate h inputdata record recordsize record recordsize recordt zerossamplerate dtypeint recordx zerossamplerate dtypeint recordy zerossamplerate dtypeint recordz zerossamplerate dtypeint sample xrangesamplerate recordtsample unpackedrecord sample recordxsample unpackedrecord sample recordysample unpackedrecord sample recordzsample unpackedrecord sample timeseries hstack timeseries timestamp tseries hstack tseries recordt xseries hstack xseries recordx yseries hstack yseries recordy zseries hstack zseries recordz savezoutputfile ttseries xxseries yyseries zzseries timetimeseries endtime clock print total time endtime starttime seconds this currently takes seconds per mb file seems high is efficient way i could final solution using numpy fromfile method custom dtype cut runtime seconds x faster original code the final code numpy import savez dtype fromfile ospath import getsize time import clock starttime clock filesize getsizeinputfile openfile openinputfile rb header openfileread recordsize intheader numberofrecords filesize recordsize samplerate recordsize recorddtype dtype timestamp samples samplerate data fromfileopenfile dtype recorddtype count numberofrecords timeseries data timestamp tseries data samples ravel xseries data samples ravel yseries data samples ravel zseries data samples ravel savezoutputfile ttseries xxseries yyseries zzseries fidtimeseries endtime clock print it took endtime starttime seconds,3 you multiple directories ie commonproject frontendproject backendproject directories pythonpath overlapping hierarchies ie project top level package default python happy uses first matching directory finds search many languages php java etc get import errors however putting project directory initpy effectively telling python keep looking place find code package import pkgutil path pkgutilextendpathpath name many pythonistas shun mock ridiculous aberration declare foolishness endeavor possibly make unpleasant suggestions primate ancestry namespace packages terrible idea say prepare defend decision and dare add two lines source tree without accompanying comments explaining this page good explanation concepts explanation httpwwwdoughellmanncompymotwpkgutil if follow approach make distribution common frontend another common backend,i planning write visitors kiosk pythongtk the project two applications frontend kiosk backend management linked mysql db i want applications common code i thinking structuring project like projectcommon common code projectfrontend frontend projectbackend backend so project common frontend backend the problem i going application datafiles i want applications packaged separately the frontend run linux backend windowscxfreeze linux can anyone give advice,1 there way get formatted queries without actually connecting database running not really the rdbms handles internally prepared queries bind variables the formatted actually exist anywhere,python sort libraries interface databases provide nice way build sql queries without worrying sql injections for instance sqlite buy ibm buy msoft sell ibm cexecute insert stocks values the trouble i want execute query i want format get query string i guess i could escape things elegant solution there way get formatted queries without actually connecting database running the context i writing filter prepares series sql statements input i want run specific database save later,3 it um works right i cut pasted example what python os using and sure accidentally add additional quotes somewhere are printing terminal,i would like pretty print key value pair dictionaries nested list so i working updatedat urlhttpdiveintopythonnethttpwebservicesredirectshtmlannotationsusernamesharedyestagspythonhandleropenerurllibreadlaternocreatedat titlexcxahandling redirectscommentsdescupdatedat urlhttpwwwpolimexnetsklepindexphppagecategoryampcatidannotationsusernamesharedyestagsplasticsnapbuttonsclothingreadlaternocreatedat titlepolimex plasticxcxaaccessoriescommentsdesc when i pprint import pprint data updatedat urlhttpdiveintopythonnethttpwebservicesredirectshtmlannotationsusernamesharedyestagspythonhandleropenerurllibreadlaternocreatedat titlexcxahandling redirectscommentsdescupdatedat urlhttpwwwpolimexnetsklepindexphppagecategoryampcatidannotationsusernamesharedyestagsplasticsnapbuttonsclothingreadlaternocreatedat titlepolimex plasticxcxaaccessoriescommentsdesc pprintdata result i get original list string updatedat urlhttpdiveintopythonnethttpwebservicesredirectshtmlannotationsusernamesharedyestagspythonhandleropenerurllibreadlaternocreatedat titlexcxahandling redirectscommentsdescupdatedat urlhttpwwwpolimexnetsklepindexphppagecategoryampcatidannotationsusernamesharedyestagsplasticsnapbuttonsclothingreadlaternocreatedat titlepolimex plasticxcxaaccessoriescommentsdesc how i make pretty print data look something like updatedat urlhttpdiveintopythonnethttpwebservicesredirectshtml annotations username sharedyes tagspythonhandleropenerurllib readlaterno createdat titlexcxahandling redirects comments desc updatedat urlhttpwwwpolimexnetsklepindexphppagecategoryampcatid annotations username sharedyes tagsplasticsnapbuttonsclothing readlaterno createdat titlepolimex plasticxcxaaccessories commentsdesc,1 one possibility comes mind are supplying json string pprint if first decode pprintjsonloadsdata,i would like pretty print key value pair dictionaries nested list so i working updatedat urlhttpdiveintopythonnethttpwebservicesredirectshtmlannotationsusernamesharedyestagspythonhandleropenerurllibreadlaternocreatedat titlexcxahandling redirectscommentsdescupdatedat urlhttpwwwpolimexnetsklepindexphppagecategoryampcatidannotationsusernamesharedyestagsplasticsnapbuttonsclothingreadlaternocreatedat titlepolimex plasticxcxaaccessoriescommentsdesc when i pprint import pprint data updatedat urlhttpdiveintopythonnethttpwebservicesredirectshtmlannotationsusernamesharedyestagspythonhandleropenerurllibreadlaternocreatedat titlexcxahandling redirectscommentsdescupdatedat urlhttpwwwpolimexnetsklepindexphppagecategoryampcatidannotationsusernamesharedyestagsplasticsnapbuttonsclothingreadlaternocreatedat titlepolimex plasticxcxaaccessoriescommentsdesc pprintdata result i get original list string updatedat urlhttpdiveintopythonnethttpwebservicesredirectshtmlannotationsusernamesharedyestagspythonhandleropenerurllibreadlaternocreatedat titlexcxahandling redirectscommentsdescupdatedat urlhttpwwwpolimexnetsklepindexphppagecategoryampcatidannotationsusernamesharedyestagsplasticsnapbuttonsclothingreadlaternocreatedat titlepolimex plasticxcxaaccessoriescommentsdesc how i make pretty print data look something like updatedat urlhttpdiveintopythonnethttpwebservicesredirectshtml annotations username sharedyes tagspythonhandleropenerurllib readlaterno createdat titlexcxahandling redirects comments desc updatedat urlhttpwwwpolimexnetsklepindexphppagecategoryampcatid annotations username sharedyes tagsplasticsnapbuttonsclothing readlaterno createdat titlepolimex plasticxcxaaccessories commentsdesc,2 use isatty detect whether program interactive session reading file sysstdinisatty not interactive device read stdin however sake consistency reproducability consider following norm reading stdin filename you may want consider let fileinput module handle,i found useful syntax parseraddargument inputfile typeargparsefiletype r default specifying input file using stdin—both i want program however input file always required if i using redirecting input one someprog mypythonprog mypythonprog inputfile i want python program wait input i want move along use default values,3 alternatively depending time constraints situation could use enthought prepackaged python distribution windows the free version httpwwwenthoughtcomproductsepdfreephp everything need except pygame able install easyinstall everything else place,i windows vista running python i truble installing python libraries including numpy scipy pygame i currently trying coppy numpy file straight computer cnumpy unziping file in command prompt i run code cd cnumpy python setuppy config python setuppy install when i get python setuppy config part command promt says wrong setuppy file run any suggestions,1 you get zip program httpinfoziporgziphtml i would recommend using python zipfile module also standard backup file location you make one,the problem i want program creates backup important files this lesson located httpwwwibiblioorggswapbyteofpythonreadproblemsolvinghtml import os import time the files directories backed specified list source homeswaroopbyte homeswaroopbin if using windows use source r cdocuments r dwork something like the backup must stored main backup directory targetdir mntebackup remember change using the files backed zip file the name zip archive current date time target targetdir timestrftime ymdhms zip we use zip command unixlinux put files zip archive zipcommand zip qr target joinsource run backup ossystemzipcommand print successful backup target else print backup failed i using windows for apply windows for i find commands zip file default windows zipping program this would easy lesson explained use windows zipping commands any assistance appreciated this homework reading it helpful applicable tools defined,1 i know tornado i gave look simply catch exceptions way the exception generated constructor httpconnection code constructor already wrapped different stack context stackcontextstackcontextselfcleanup parsed urlparseurlsplitunicodeselfrequesturl so basically whenever exception generated gaierror example caught already handled selfcleanup turns generate response afaict contextlibcontextmanager def cleanupself try yield except exception e loggingwarninguncaught exception excinfotrue selfruncallbackhttpresponseselfrequest errore requesttimetimetime selfstarttime not sure answers question,i trying handle exception occurred asyncclientfetch way tornadohttpclient import asynchttpclient tornadohttpclient import httprequest tornadostackcontext import exceptionstackcontext tornado import ioloop def handleexcargs print exception occured return true def handlerequestresponse print handle request httpclient asynchttpclient exceptionstackcontexthandleexc httpclientfetch httpsomesitecom handlerequest ioloopioloopinstancestart see next output warningrootuncaught exception traceback recent call last file homecrchemistpythonlibpythonsitepackagestornadopyeggtornadosimplehttpclientpy line cleanup yield file homecrchemistpythonlibpythonsitepackagestornadopyeggtornadosimplehttpclientpy line init socketgaierror errno no address associated hostname handle request what i wrong,2 looks like html escaped what happens change inline hrefopinionsali whichnav opinions else opinions n edit put n disable filtering after conditional,so i playing mako pyramid i trying inline statements li hrefopinionsali whichnav opinions else opinions outputs liamplta hrefampampampgtopinionsampltaampgtampltliampgt whereas whichnav opinions lia hrefopinionsali else liopinionsli endif outputs correctly without escaping html characters lia hrefopinionsali i want make code clean possible inline statements preferable i understand html characters escaped whereas using thanks,1 check pyvision it part research project colorado state university fairly mature i good success using though i never used facelabeling parts,using opencv haardetectobjects haarcascadefrontalfacedefaultxml i found i detect face fairly reliably however anyone aware libraries methods identifying face ie labeling name,1 the problem gmail all way smtplib library correct address specified library sends right address gmail this gmail support page implies especially near bottom note popimap users need add address additional email address gmail settings able send mail gmail smtp servers this course requires verification since address inbox fake currently possible but least django bug note pretty obvious way gmail stop spamming i sure,as noted docs serveremail setting supposed change from address crash emails sent admins django server but does work or django version django insists using emailhostuser email loginactual address address i using gmail smtp server i wonder could something does gmail block sort thing i swear i gotten work it little annoying multiple projects seem emailing address dig traceback see project,2 i know happen use cax argument colorbar set axe contain colorbar import numpy matplotlib import pyplot pyplotimshownumpyrandomrandom extent cax pyplotaxes pyplotcolorbarcaxcax pyplotshow,i using matplotlib plotting i like able use extent keyword control aspect ratio plots well display size image along axis tick marks my problem i try make image longer row direction column direction i add colorbar image shifts center figure canvas right side some example code would import numpy matplotlib import pyplot pyplotimshownumpyrandomrandom extent pyplotcolorbar pyplotshow is way keep image centered figure window is bug i using latest version github repository python ubuntu,1 what comparing string encoded keys passed base order safe output text base preserve string ordering if decode using baseurlsafebdecode compare order expect,i found interesting curious know db keys ordered differently strings if test following example python development environment true server well see following somewhat unexpected behaviour str agpybhbmnlyxbwchileglvcvytwkzwwyagbgw str agpybhbmnlyxbwchileglvcvytwkzwwykowbbqw result str str true however following key dbkeystr key dbkeystr result key key false,1 it printed create class instance rather class scope executed this code print loaded even though i never made instance test class test print loaded if want run code class initialized take look init this code print loaded instance made instead class defined class test def initself print loaded qt qobject metaclass appears rewriting class attributes prevent duplicate signals initialize new instance class perhaps assign attribute like class testqobject def initself signal selfevtspam signal sig signal testsig b testsig or class testqobject def signalself signal selfevtspam evtspam return self evtspam signal testsignalevtspam b testsignalevtspam,pysideqtcore import class eggsqobject evtspam signal print loaded eggs b eggs print aevtspam print bevtspam print aevtspam bevtspam outputs loaded pysideqtcoresignal object xaffa pysideqtcoresignal object xaffb false loaded printing expected class variable instances signal created also class variable,2 you could use numpy fancy indexing repopy dddd array repopy dddd array alternatively could use list comprehension repopy nparrayrow row dd row array repopy nparrayrow row dd row array edit time things ipython repopy timeit dddd loops best us per loop repopy timeit nparrayrow row dd row loops best us per loop,i array like numpy array dd i need seperate array dd dd these array i na na i tried npwhere really work,3 void foomaamp ampfoom boostpythonclassfoofoo defm,assume exist class foo two overloaded methods class foo void maamp void mbamp b i need expose one methods boostpython boostpythonclassfoofoo defm ampfoom how i specify signature maampa used mbampb,3 the problem daylight savings time applied twice a trivial example timetuple datetimeutctimetuple timestructtimetmyear tmmon tmmday tmhour tmmin tmsec tmwday tmyday tmisdst datetimefromtimestamptimemktimetimetuple datetimedatetime i fairly certain fault lies within timemktime as says documentation this inverse function localtime its argument structtime full tuple since dst flag needed use dst flag unknown expresses time local time utc it returns floating point number compatibility time if input value cannot represented valid time either overflowerror valueerror raised depends whether invalid value caught python underlying c libraries the earliest date generate time platformdependent when pass time tuple timemktime expects flag whether time daylight savings time as see utctimetuple returns tuple flag marked says documentation if datetime instance naive dtimetuple except tmisdst forced regardless ddst returns dst never effect utc time if aware normalized utc time subtracting dutcoffset timestructtime normalized time returned tmisdst forced note result’s tmyear member may minyear maxyear dyear minyear maxyear utc adjustment spills year boundary since told timemktime time dst job convert times local time currently daylight savings time area adds hour make daylight savings time hence result while i post handy i came across method couple days ago convert timezoneaware datetimes naive ones local time this might work much better application currently uses excellent pytz module import pytz def converttolocaltimedtaware tz pytztimezone americalosangeles replace time zone string dtmytz dtawareastimezonetz dtnaive dtmytzreplacetzinfonone return dtnaive replace americalosangeles timezone string find somewhere pytzalltimezones,i parsing national weather service alerts feed web application i like purge alerts hit expiration time i also like display expiration time local time format geographic area pertain the alerts cover whole us i think best approach store compare times utc timestamps the expiration time arrives feed string like t i using labix dateutils package parse string timezoneaware manner dateutilparser import parse parset datetimedatetime tzinfotzoffsetnone i also able capture utc offset hours offsethours dutcoffsetdays dutcoffsetseconds offsethours using datetimeutctimetuple timemktime methods i able convert parsed date utc timestamp import time expirationutcts timemktimedutctimetuple expirationutcts at point i feel pretty good i able convert raw strings timestamp representing expiration time utc i able compare current time utc timestamp expiration determine needs purged nowutcts timemktimetimegmtime nowutcts nowutcts expirationtcts true the difficulty i trying convert stored utc timestamp back original localized format i offset hours stored original conversion string i parsed store timezone label print offsethours print timezone edt i like convert utc timestamp back locally formatted time converting back datetime seem working import datetime datetimedatetimefromtimestampexpirationutcts datetimetimedeltahoursoffsethours datetimedatetime the hour it looks like hour i sure error introduced i put together another test got similar results running pm edt utcnow datetimedatetimeutcnow utcnowts timemktimerightnowutctimetuple datetimedatetimefromtimestamputcnowts datetimedatetime off hour can someone help find mistake i sure daylight savings issue i came across stuff leads believe might trying localize dates times point i pretty stumped i hoping calculationscomparisons timezoneagnostic manner,2 you use absolute imports instead relative imports eg import mypackagemypath mypath,i process finishing python package i writing however i release i like get feedback overall structure package well initpy file this give idea initpy file looks like a docsting describing package author myname copyright mycopyright credits listofcredits license mylicense version maintainer email myemail status indevelopment this contains module directories strings file reference import mypath modules import import gui widget classes windowmodule import windowwidget widgetmodule import someguiwidget someothermodule import someotherguiwidget andanotherguiwidget def demo demo package name main demo this give decent idea overall package structure mypackage mypathpy initpy licensetxt readmetxt modules thispy thatpy windows windowmodulepy widgets widgetmodulepy images imagefileswhatever tools toolspy,1 you probably crosscompile xmpppy using openwrt sdk,python xmpp client library openwrt tnx,1 assuming values dict lists foundthree false key val dcitems val foundthree foundthree true dosomething elif val dosomethingelse else doanotherthing edit update comments finding first list value dict item work key val dcitems foundthree false n val n foundthree foundthree true dosomething elif n dosomethingelse else doanotherthing,i newbie python dictionary multiple values dc if iterate dc find three occurrences first occurrence i would like iterate dict first occurrence occurs dosomething else occurrence afterwardsie nd time rd time dosomethingelse how i python thank,2 most asking pretty straightforward part i see trouble determining number occurs first element you list for instance false false true here something work dc def dosomething print something def dosomethingelse print something else keyvalue dcitems value dosomething elif value dosomethingelse,i newbie python dictionary multiple values dc if iterate dc find three occurrences first occurrence i would like iterate dict first occurrence occurs dosomething else occurrence afterwardsie nd time rd time dosomethingelse how i python thank,2 dict def dosomething print something def dosomethingelse print something else threehandler dosomething v dictvalues three x x v x threehandler threehandler dosomethingelse output something something else something else,i newbie python dictionary multiple values dc if iterate dc find three occurrences first occurrence i would like iterate dict first occurrence occurs dosomething else occurrence afterwardsie nd time rd time dosomethingelse how i python thank,2 here alternative use statement check first occurrence def dosomething print ds def dosomethingelse print dse keyvalue diteritems dosomething item value item dosomethingelse,i newbie python dictionary multiple values dc if iterate dc find three occurrences first occurrence i would like iterate dict first occurrence occurs dosomething else occurrence afterwardsie nd time rd time dosomethingelse how i python thank,1 l long integer string treat number word urlspy r albumpalbumidd coreviewsalbum url album end calling def albumrequest albumid album albumobjectsgetpkl album albumobjectsgetpkalbumid or need keep l url reason cast long using album albumobjectsgetpklongalbumid,i trying retrieve model object like code r albumpalbumidw coreviewsalbum def albumrequest albumid album albumobjectsgetpkalbumid the problem pk integer albumobjectsall apk l the error i getting i run view valueerror albuml invalid literal int base l ideas thanks,1 dictionaries good chapter enus chapter frfr chapitre chapter enus chapter chapter frfr chapitre,what would best approach following langenus chapterchapter langfrfr chapterchapitre etc essentially i looking mapping would something like lang enus frfr chapter chapter chapitre how would i accomplish thank,2 i always use dictionary langs enus chapter frfr chapitre test langs enus but translations also consider gettext,what would best approach following langenus chapterchapter langfrfr chapterchapitre etc essentially i looking mapping would something like lang enus frfr chapter chapter chapitre how would i accomplish thank,3 there also allfoo bar foobar barfoo foobarfoo barfoobar print oh yeah also shortcircuit,whenever i coding something requires lot conditionals i end foo bar foobar barfoo foobarfoo barfoobar and forever ever ever i write foo bar foobar i check value list elements foo bar inside somewhere line list index exist i get error is shortcut conditionally checking things like alternative method thanks,1 i sure issue pyglet playing mp using simpler import pyglet sound pygletmediaload mysoundmp streamingfalse soundplay pygletapprun pyglet wellmaintained crossplatform small multimedia library,i seen questions topic almost outdated this dupe my requirement preferably light weight library simply playing audio files mpetc python these libraries i far looked i listing things stopping using pymedia last updated feb mpplay supports xp last updated i also tried pyglet even look good also heard wx support mp i trying any comments which reliable lightweight library others use days ps please post one library per answer,3 add following line coding utf assuming using utf top python file able use unicode without issue see python docs unicode also use dict variable name shadow builtin type name,i following dict dict eses capã­tulo however i try use dict i get following error syntaxerror nonascii character xc file i looked massive python unicode docs httpdocspythonorghowtounicodehtml able figure yet how would i encode dict i could call dict eses thank,2 you also keep count times element seen use dict increment sighting usrbinpython dc de def dosomethingik print first time key ik def dosomethingelseijk print element seen times now key ijk k sorteddc dck de dei dosomethingik else dei dosomethingelseideik as others said dictionaries order necessarily insertion code listing you sort keys sorteddc distinguish first vs subsequent sort order this method easily extended dosomthing based many times item seen output first time key first time key element seen times now key element seen times now key first time key alternatively r k sorteddc print dck dck rappend number key formatlenrk produces number key number key number key the list r strings order keys dc sorted iterate sequence r and looking first rest use list comprehension li sub dck k sorteddc sub l l l rest,i newbie python dictionary multiple values dc if iterate dc find three occurrences first occurrence i would like iterate dict first occurrence occurs dosomething else occurrence afterwardsie nd time rd time dosomethingelse how i python thank,1 if def gooself foo nobody calling way know type foo however call goo code known foo ide figure goo always passed foo autocomplete work this python tools visual studio works note terribly useful though requires write code calls function function actually written here snippet showing works make obvious,for example suppose i code class fooobject def barself x blah blah blah return x and suppose i creating another class method takes instance foo object something class bazobject def gooself foo foobar i foo object autocomplete please i would desperately love typing foo creating goo method baz class ide would provide intellisense you know show available methods foo class params doc etc in c i would declare param foo type foo autocompletion trivial i realize python dynamically typed way ide know foo parameter type foo but info directive convention ide use determine type strictly sake intellisense autocompletion one workaround i found type foo cause ide show intellisense methods foo this useful exactly i looking another workaround type foo foo go using foo normally would some ide sniff foo type foo provide intellisense but must remember delete line foo foo else got nasty bug perhaps much better way accomplish i trying i using c intellisense point reference maybe visual studio thing whereas coding python i open mind different way accomplishing similiar thing any suggestions would much appreciated i sure i one craving intellisense python objects,1 well start httpwwwsamontabcomwebcreateinstallableapplicationssisfilesfromyourpythonscriptsforsymbian httpwwwdevelopernokiacomcommunitywikipysquickstart book mobile python rapid prototyping applications mobile platform book best tutorial started yesterday already fun everything instructed simple steps easy know python winner case i hand starting python python apps rd smartphone,i new mobile programming i would like make mobile app symbian python i read s rd edition i use ensymble thing i using python v seems yet supported ensymble does anyone know software maybe tutorials thanks,1 i sure trying say if list odd size take central element otherwise take mean central two elements i see code actually in particular it calling avg function avglist note without arguments it ignoring value computing way branches are sure complete code meant work,my professor wrote median function i understand well can someone please explain part lenlist median avg else statement def avglistnumbers sum num numbers sum num avg floatsumlennumbers print avg def medianlist listsort lenlist take avg middle two lenlist median avg else find middle remembering lists start lenlist median list return median to add example i saw even list length def medians lens return sisi return si this works well i understand last return si for odd list length x median sortedxlenx since x list length odd lenx floating number index i getting way any explanation better mine much appreciated,1 we missing code puzzle the comments instructive when check lenlist then checking see list even length if list even number members true middle element take avg middle two lenlist median avg we assume avg function going return average two middle elements since include definition avg function possible really supposed avglist function taking middle two elements list now list odd length middle element else find middle remembering lists start lenlist median list now looks kinda wrong guess intention read median listi that would us returning middle element list since list sorted middle element true median list hope helps,my professor wrote median function i understand well can someone please explain part lenlist median avg else statement def avglistnumbers sum num numbers sum num avg floatsumlennumbers print avg def medianlist listsort lenlist take avg middle two lenlist median avg else find middle remembering lists start lenlist median list return median to add example i saw even list length def medians lens return sisi return si this works well i understand last return si for odd list length x median sortedxlenx since x list length odd lenx floating number index i getting way any explanation better mine much appreciated,3 always use unicode literals chaptermapping chapter u チャプター,how would i encode following chaptermapping chapter チャプター i call chaptermapping chapter thank,1 why wrong line line def medianlist listsort lenlist take avg middle two lenlist median avg else find middle remembering lists start lenlist median list return median it bad idea give variables name data types namely list listsort modify list passed one would expect getter like median it calls function avg arguments completely meaningless even function defined calculated way regardless branch taken regardless never used it sets median original list makes zero sense here i would rewrite maintaining clarity def medianalist srtd sortedalist returns sorted copy mid lenalist remember integer division truncates lenalist take avg middle two return srtdmid srtdmid else return srtdmid also avglist function used could used median could rewritten def avglistnumbers return floatsumnumberslennumbers sum function returns sum elements iterable,my professor wrote median function i understand well can someone please explain part lenlist median avg else statement def avglistnumbers sum num numbers sum num avg floatsumlennumbers print avg def medianlist listsort lenlist take avg middle two lenlist median avg else find middle remembering lists start lenlist median list return median to add example i saw even list length def medians lens return sisi return si this works well i understand last return si for odd list length x median sortedxlenx since x list length odd lenx floating number index i getting way any explanation better mine much appreciated,3 the expat error means gotten file something wrong open file verify corrupted edit aaah binary plist yeah plistlib handle you want libplist instead,i trying modify plist file volumesmacintoshhduserschristianlibraryapplication supportiphone simulatorlibrarypreferencescomappleaccessibilityplist here noob python script import plistlib import ospath set path prefspath ospathexpanduserlibraryapplication supportiphone simulatorlibrarypreferencescomappleaccessibilityplist parse prefs plistlibreadplistprefspath i get ioerror no file directory if i remove backslashes path i get expaterror wellformed invalid token line column update ignacio vazquezabram answer suggests file corrupted it still editable xcode viewable quicklook also simulator works fine when i open textmate i see bplistã¿ d applicationaccessibilityenabledvotquicknavenabledaccessibilityenabledscreencurtainvoiceovertouchrotoritemspreferenceaxinspectorenabledaxinspectorframeaxinspectorenabled ã˜â€œ yrotoritemwenabledycharacter “ tword “ tline “ vheader “ tlink “ formelement “ ztablestart “ampyliststart“ylandmarks“visitedlink“nonvisitedlink“vbutton“ytextfield“uimage“zstatictext“internallink“atzoom pguã¶âˆžæ’å¸â„€‹›ã’ë†afrsxcdistyã‰ã‘ã¢ã¯ã±ãµâ„¢â´âˆžâˆ‘∏î©â«â»ã•”‘å¸â€°ã‚ãëœâ¯ëf are iphone simulator plists editable python corrupted file is way around,2 you also need add header file python coding utf chaptermapping chapter u チャプター,how would i encode following chaptermapping chapter チャプター i call chaptermapping chapter thank,1 i recommend writing processing code separately writing gui wrapper around there many choices however i consider big three tkinter standard install simple bit clunky wxpython better choice higher quality bit complicated uses native widgets pyqt many love toolkit documentation i limited expertise uses custom drawn widgets,so i taking digital image processing class requires implementing image filters reconstruction enhancements i plan use python professor wants simple gui two canvas pre postprocessing images drop box filter selection textboxes filter valuethresholds stuff i following questions ask is possible load image canvas python gui library does advantage coding outweight disadvantages code gui manually given requirements would best easiest library use i choose python since reduces implementation time gui turns bummer i would rather use java if answer previous questions yes please point right direction documents thank,2 well saying include library however python standard difflib contains function exactly expect considering python interview question familiarity difflib might interviewer expected in import difflib in difflibsequencematchernone never forevergetmatchingblocks out matcha b size matcha b size in difflibsequencematchernone address oddnessgetmatchingblocks out matcha b size matcha b size matcha b size you always ignore last match tuple since dummy according documentation,how find intersections also called longest common substrings two strings positions strings for example snever sforever resulted intersection must ever positions if saddress soddness resulted intersections ddess positions shortest solution without including library preferable but correct solution also welcomed,3 i believe djangodbmodels import q personobjectsfilterqidinmycampaignrecipientsall,i following basic model… class campaignmodelsmodel name modelscharfield name maxlength uniquetrue recipients modelsmanytomanyfield person blanktrue nulltrue recipient class recipientmodelsmodel campaign modelsforeignkeycampaign person modelsforeignkey person class personmodelsmodel firstname modelscharfield first name maxlength blanktrue lastname modelscharfield last name maxlength blanktrue i like queryset queries person objects within given campaign it nice easy personobjectsallexcludemycampaignrecipientsall know work to specific i trying get work form class follows q object comment seems right i get work… here form class recipientsformformsform def initself campaign args kwargs selfcampaign campaign selfhelper formhelper selfhelperaddinputsubmit submit add cssclass primaryaction selfhelperlayout layout fieldset recipients cssclass inlinelabels return superrecipientsform selfinitargs kwargs recipients formsmodelmultiplechoicefield old queryset querysetpersonobjectsall querysetpersonobjectsfilterqidinselfcampaignrecipientsall widgetformswidgetscheckboxselectmultiple labeladd recipients requiredtrue def saveself forceinsertfalse forceupdatefalse committrue recipients selfcleaneddata recipients person recipients recipient recipientcampaignselfcampaignpersonperson recipientsave,1 just use following get messages sent since activating mail stub googleappengineapi import apiproxystubmap sentmessages apiproxystubmapapiproxyapiproxystubmapstubmap mail getsentmessages,i newbie python app engine i code sends email based request params auth logic unit tests using gaeunit i confirm email specific contents sent ie i mock emailer fake emailer verify send called class emailhandlerwebapprequesthandler def badinputself selfresponsesetstatus selfresponseheaders contenttype textplain selfresponseoutwritehtmlbodybad input bodyhtml def getself toaddr selfrequestgetto subj selfrequestgetsubject msg selfrequestgetbody mailisemailvalidtoaddr return error message selfbadinput pass authenticate message mailemailmessage messagesender mycompanygmailcom messageto toaddr messagesubject subj messagebody msg messagesend selfresponseheaders contenttype textplain selfresponseoutwritehtmlbodysuccessbodyhtml and unit tests import unittest webtest import testapp googleappengineext import webapp email import emailhandler class sendingemailsunittesttestcase def setupself selfapplication webappwsgiapplication emailhandler debugtrue def testsuccessself app testappselfapplication response appget httplocalhostsendtovijaysanthanamgmailcomampbodyblahblahblahampsubjectmysubject selfassertequal ok responsestatus selfasserttrue success response somehow assert email sent,1 sentry overkill djangodblog deprecated i rolled cannibalising necessary parts how works catching error signal then uses django inbuilt exception reporter generate fancy error page django displays debugging enabled we store db render admin console here implementation model class errormodel model storing individual errors kind charfield type nulltrue blanktrue maxlength dbindextrue info textfield nullfalse data textfield blanktrue nulltrue path urlfield nulltrue blanktrue verifyexistsfalse datetimefield nullfalse autonowaddtrue dbindextrue html textfield nulltrue blanktrue class meta meta information model verbosename error verbosenameplural errors def unicodeself string representation object return selfkind selfinfo admin class erroradminadminmodeladmin listdisplay path kind info listdisplaylinks path ordering id searchfields path kind info data readonlyfields path kind info data html fieldsets none fields kind data info def hasdeletepermissionself request objnone disabling delete permissions return false def hasaddpermissionself request disabling create permissions return false def changeviewself request objectid extracontext the detail view error record obj selfgetobjectrequest unquoteobjectid extracontextupdate instance obj errorbody marksafeobjhtml return supererroradmin selfchangeviewrequest objectid extracontext adminsiteregistererror erroradmin helper class loggingexceptionhandlerobject the logging exception handler staticmethod def createfromexceptionsender requestnone args kwargs handles exception upon receiving signal kind info data sysexcinfo issubclasskind http error errorobjectscreate kind kindname html exceptionreporterrequest kind info datagettracebackhtml path requestbuildabsoluteuri info info data n jointracebackformatexceptionkind info data errorsave init djangocoresignals import gotrequestexception moduleserrorsignals import loggingexceptionhandler gotrequestexceptionconnectloggingexceptionhandlercreatefromexception,are lightweight alternatives djangosentry error logging django environment i used djangodblog earlier known djangosentry some others i found pretty much dead commits last two years almost thanks,3 this explained copied link it operator equivalent calling extend method treats argument generic sequence enforce type,in l in sasdsad in ls in l out however in ls typeerror traceback recent call last homexiaohancodeproteincrawleridcrawlerpy module typeerror concatenate list str list so operators different but i think plus am i wrong something happens behind scene,3 ajax url resultshandler type post data data success functiondata status check status something data may post help jqueryajax post request get data app engine server,how call python handler jquery ajax one give example,1 if i understand correctly want show html content prepared dynamically python within django template correct if case need iframe iframes necessary would like integrate parts different uri webpage frame section webpage page here sample html head titleiframe exampletitle head body p myheading p div idcontent myhtml div body html addition code base comment sounds like want show entire page iframe second page comes form another viewurl box then use html head titleiframe exampletitle head body p myheading p iframe srcurltomyndviewindjango width heightiframe body html iframe explanation wschools iframe description wc site,i html template i rendering using django i passing necessary context variables — myheading heading myhtml marksafed html i like display myhtml iframe html head titleiframe exampletitle head body p myheading p iframe nameiframe width height srchttpwwwyahoocom frameborderyes scrollingyesiframe body html would know all examples i found show iframe pointing url i godhorrible html js thanks,2 chapter enus chapter frfr chapitre chapterkeys chaptervalues enus frfr chapter chapitre if looking translation best option gettext,what would best approach following langenus chapterchapter langfrfr chapterchapitre etc essentially i looking mapping would something like lang enus frfr chapter chapter chapitre how would i accomplish thank,1 i made example api v httpsgistgithubcom,i trying post picture tumblr using python particular httpcodegooglecomppythontumblr usrbinpython tumblr import api import sys blog exampletumblrcom user exampleexamplecom password example api apibloguserpassword postdata picturepng title title entry body story picture apiwriteregulartitle body postdata when i run result blog arrives instead title entry story picture img i get title entry story picturepicturepng,1 your string unicode string utfencoded string so decode must encode utf whatever encoding need u xcxexebxexff xffxexebxfbxedxff xexfxeexecxf u xcxexebxexff xffxexebxfbxedxff xexfxeexecxf print ãã¥ã«ã ã¿ ã¿ã¡ã«ã»ã­ã¿ ã£ã°ã®ã¬ã³ aencodeutf xcxxcxaxcxabxcxaxcxbf xcxbfxcxaxcxabxcxbbxcxadxcxbf xcxaxcxbxcxaexcxacxcxb something end processing need save utf encoded file example if input different encoding way around schoãŸhã¼ndchen native encoding cp schoãŸhã¼ndchendecodecp decode windows codepage unicode string work u schoxdfhxfcndchen print displays correctly shell knows glyphs schoãŸhã¼ndchen dencodeutf output convert utf schoxcxfhxcxbcndchen,i using mutagen convert id tags data cp cp utf in linux problem but windows calling setvalue wxtextctrl produces error unicodedecodeerror ascii codec decode byte xc position ordinal range the original string assumed cp encoded i pulling mutagen u xcxexebxexff xffxexebxfbxedxff xexfxeexecxf i tried converting utf dd ddecode utf even changing default encoding ascii utf syssetdefaultencoding utf but i get error,2 micro k unique visitorsmonth k pageviews small k unique visitorsmonth k pageviews medium k unique visitorsmonth k pageviews large k unique visitorsmonth m m pageviews it hard tell many users fit django site idea io throughput expecting read vs write ratio looks like if building standard webapp every write occurs user reads able fit comfortable one medium site see definitions linode mb box condition cache dynamically generated html memcache great put truly static content cdn cloudfiles rackspace awesome hope helps m cloudfiles cdn rackspace akamain rackspace cloud servers linode mb equivalent bucks month memcache awesome distributed caching,what would consider micro small medium large site based unique visitors etc assuming sites basic like django blogging photo uploading etc no special apps crazy processing normal business website im trying figure many django sites would comfortable linode similar any ideas,2 michael klocker answer question answer given better solution you rather but answer question you pass url iframe really want use iframe need set second urlview django return myhtml response ie http requests happen page containing iframe request contents iframe,i html template i rendering using django i passing necessary context variables — myheading heading myhtml marksafed html i like display myhtml iframe html head titleiframe exampletitle head body p myheading p iframe nameiframe width height srchttpwwwyahoocom frameborderyes scrollingyesiframe body html would know all examples i found show iframe pointing url i godhorrible html js thanks,2 try checking output command there may error written see current code try stdin stdout stderr sshexeccommand python homeubuntuoptimizationpvserverpy print exitcode stdoutchannelrecvexitstatus print stdoutread print stderrread once figured wrong fixed return using nohup i think wrong way calling export display command this affect env commands running you need something like stdin stdout stderr sshexeccommand sh c export displaylocalhost python homeubuntuoptimizationpvserverpy,below code when log server i run ps aux grep python i see process start die second two if i run command serverit works i tried nohupwhithout nohup etc i explanation this long process take hours key paramikorsakeyfromprivatekeyfilersaprivatekey ssh paramikosshclient sshsetmissinghostkeypolicyparamikoautoaddpolicy sshconnecthostnameportusernameusernamepkeykey stdin stdout stderr sshexeccommand tar xf homeubuntuopttargz stdin stdout stderr sshexeccommand ls stdin stdout stderr sshexeccommandbash stdin stdout stderr sshexeccommand ls stdin stdout stderr sshexeccommand export displaylocalhost stdin stdout stderr sshexeccommand nohup python homeubuntuoptimizationpvserverpy amp stdin stdout stderr sshexeccommand nohup python homeubuntuoptimizationpvserverpy amp stdin stdout stderr sshexeccommand nohup python homeubuntuoptimizationpvserverpy amp stdin stdout stderr sshexeccommand python homeubuntuoptimizationpvserverpy amp stdin stdout stderr sshexeccommand python homeubuntuoptimizationpvserverpy amp stdin stdout stderr sshexeccommand python homeubuntuoptimizationpvserverpy amp stdin stdout stderr sshexeccommand python homeubuntuoptimizationpvserverpy amp sshclose,1 please modify code run tell us exception getting try print newclassname coursenameandcodeassociationobjectsgetdepartmentcodeiexact nameandnumberstore print newclassname except exception e print haha print e also would probably help debugger installed box i recommend eclipse combination pydev personal choice there lots great options eclipse ide download basic java version mb install plugin top pydev,i code try print newclassname coursenameandcodeassociationobjectsgetdepartmentcodeiexact nameandnumberstore print newclassname except print haha this always prints haha despite fact i run newclassname code console worked why happening edit def newgetallinformationsearchterm nameandnumberstore modifysearchtermsearchterm urlstore modifyurlnameandnumberstore need make change i go site check course name switch scrape soup gethtmlurlstore storeofbooks storeofbooks scrapesoupnameandnumberstore print nameandnumberstore try newclassname coursenameandcodeassociationobjectsgetdepartmentcodeiexact nameandnumberstore nameandnumberstore modifysearchtermnewclassnamedepartmentname nameandnumberstore urlstore modifyurlnameandnumberstore soup gethtmlurlstore storeofbooks scrapesoupnameandnumberstore except print haha return storeofbooks edit after investigation entering valid code manually worked i think something taking code array despite fact data type string newclassname coursenameandcodeassociationobjectsgetdepartmentcodeiexact econ works file newclassname coursenameandcodeassocitionobjectsgetdepartmentcodeiexact nameandnumberstore nameandnumberstore holds econ,3 ,i user profile contains manytomany field points set favorite objects i queryset returns set types objects independent favorites though may contain favorites what i want object objects p usergetprofilefavorites contains object unfavorite else favorite endif p endfor but thus far i cannot find easy way ideas,3 have tried object usergetprofilefavorites in case processing views templates,i user profile contains manytomany field points set favorite objects i queryset returns set types objects independent favorites though may contain favorites what i want object objects p usergetprofilefavorites contains object unfavorite else favorite endif p endfor but thus far i cannot find easy way ideas,1 i tried vijay methodbut work i use method httpkmdarshancomblogp works goto httptwistedmatrixcomtracwikidownloads download pycrypto package exe windowspython this needed running paramiko next download paramiko package httpwwwlagnetparamiko unzip paramiko temporary folder better unzip folder python installed go folder paramiko open command prompt see python set environment variable run command python setuppy install you get series lines compilation just make sure dont error if errors need compile just sure everything alright import paramiko program see fyi paramiko used sshand,this may sound like repeated question sf i could find clear answer yetso i installed paramiko setuppy install command running demopy program i got error traceback recent call last file cdocuments settingsfixavierdesktopparamikodemosdemopy line module import paramiko file cpythonlibsitepackagesparamikoinitpy line module transport import randpool securityoptions transport file cpythonlibsitepackagesparamikotransportpy line module paramiko import util file cpythonlibsitepackagesparamikoutilpy line module paramikocommon import file cpythonlibsitepackagesparamikocommonpy line module cryptoutilrandpool import persistentrandompool randompool importerror no module named cryptoutilrandpool i getting error even installing pycrypto on running testpywhich comes installation i got following error traceback recent call last file cdocuments settingsfixavierdesktoppycryptopycryptotestpy line module cryptoutil import test file cdocuments settingsfixavierdesktoppycryptopycryptobuildlibwincryptoutiltestpy line module import testdata file cdocuments settingsfixavierdesktoppycryptopycryptotesttestdatapy line module cryptocipher import aes importerror cannot import name aes i confidence go ahead install aes i know i may get another importerror please adviceis way installation thats problematic,2 i tested apply seems many sub groups slow groups attribute grouped dict choice index directly subsampled dfixchoicex x groupedgroupsitervalues edit as pandas version itervalues longer works groupby objects use values subsampled dfixchoicex x groupedgroupsvalues,i trying subsample rows dataframe according grouping here example say i define following data pandas import df dataframe group abaabcccc caaabbbb group value applepearorangeapple bananadurianlemonlime raspberrydurianpeachnectarine bananalemonguavablackberrygrape if i group group group number rows group in dfgroupby group group value agg count len out count b c if even concise way compute please tell i want construct dataframe one randomly selected row group my proposal like in random import choice in grouped dfgroupby group group in subsampled groupedapplylambda x dfreindexindexchoicerangelenx in subsampledindex rangelensubsampled in subsampled out group group value b pear apple b pear apple apple apple apple apple apple apple apple apple works however real data million rows columns if i dirty way building data structures i complete operation matter seconds however implementation finish within minutes appear memorylimited as side note i tried implementing r i first tried plyr also finish reasonable amount time however solution using datatable finished rapidly how i get work rapidly pandas i want love package please help thanks uri,3 how dir function getattr mymethod dirdyn true,in function getattr referred variable found gives error how i check see variable method exists part object import string import logging class dynamo def initselfx print in init def selfxx def reprself print selfx def strself print selfx def intself print in init def def getattrself key print in getattr key color return papayawhip else raise attributeerror dyn dynamo print dyncolor dyncolor lemonchiffon print dyncolor dynint dynmymethod how check whether exist,3 how looking dyndict try method dyndict mymethod except keyerror print mymethod dyn,in function getattr referred variable found gives error how i check see variable method exists part object import string import logging class dynamo def initselfx print in init def selfxx def reprself print selfx def strself print selfx def intself print in init def def getattrself key print in getattr key color return papayawhip else raise attributeerror dyn dynamo print dyncolor dyncolor lemonchiffon print dyncolor dynint dynmymethod how check whether exist,2 check class method hasattrdynamo key callablegetattrdynamo key hasattrdynamo mymethod callablegetattrdynamo mymethod you use selfclass instead dynamo,in function getattr referred variable found gives error how i check see variable method exists part object import string import logging class dynamo def initselfx print in init def selfxx def reprself print selfx def strself print selfx def intself print in init def def getattrself key print in getattr key color return papayawhip else raise attributeerror dyn dynamo print dyncolor dyncolor lemonchiffon print dyncolor dynint dynmymethod how check whether exist,3 the first argument findall function string so use string concatenation line refindall varname data,need use variable python regular expression line refindall data using code match line times values changes need use variable like line refindall varname data please help use variable python regular expression thanks advance,1 if know variable cannot contain characters special meaning regular expression use string concatenation ways create string line refindall varname data if chance variable could contain special characters escape first line refindall reescapevarname data,need use variable python regular expression line refindall data using code match line times values changes need use variable like line refindall varname data please help use variable python regular expression thanks advance,3 first need install python development headers then need tell configure use python pythonpython configure compile install normally make make install you able use pygobject python,i trying install pygobject using variety methods first using aptget installs python x next i attempted compile i problems getting compile python does anyone know install,2 try easy way line refindall formatvarname data,need use variable python regular expression line refindall data using code match line times values changes need use variable like line refindall varname data please help use variable python regular expression thanks advance,3 use string formatting operations line refindall varname data,need use variable python regular expression line refindall data using code match line times values changes need use variable like line refindall varname data please help use variable python regular expression thanks advance,1 the easiest way would tested djangoregistration somewhere project say formspy organization app registrationforms import registrationform djangoforms import modelform models import organization class organizationformformsmodelform class meta model organization registrationformbasefieldsupdateorganizationformbasefields class customregistrationformregistrationform def saveself profilecallbacknone user supercustomregistrationform selfsaveprofilecallbacknone org c organizationobjectsgetorcreateuseruser logoselfcleaneddata logo nameselfcleaneddata name then root urlconf regex pattern includes registrationurls assuming regex r accounts add organizationforms import customregistrationform urlpatterns patterns r accountsregister registrationviewsregister formclass customregistrationform obviously also create custom backend imho way easier,i model called organization i setup user profile i would like fields organization model show registration page how i go djangoregistration modelspy class organizationmodelsmodel user modelsforeignkeyuser uniquetrue logo modelsimagefielduploadto organizations name modelscharfieldmaxlength nulltrue uniquetrue fields etc settingspy authprofilemodule volunteeringorganization,3 this pretty easy actually need couple hacks first need force gtk create header button gtktreeviewcolumn label gtklabelcolumn title labelshow treeviewcolumnsetwidgetlabel after need fetch internal gtkbutton header widget treeviewcolumngetwidget isinstancewidget gtkbutton widget widgetgetparent finally button reference something useful def buttonreleaseeventbutton event eventbutton menupopupevent widgetconnect buttonreleaseevent buttonreleaseevent this taken kiwi library objectlist provides python list like api creating gtktreeviews,i want popup context menu user rightclicks header row gtktreeview in gtk gtktreeviewcolumn getbutton method makes easy simply attach menu button connect clicked event however gtk work you call getwidget method returns none set widget via setwidget i tried putting gtklabel column name gtkeventbox set widget after connecting eventbox callback buttonpressevent clicking generate event i tried something like listed getparent column widget returns none never reaches button code implies what solutions people found,2 change except coursenameandcodeassociationdoesnotexist each model create gets doesnotexist exception extends core objectdoesnotexist exception also best approach use try … except around precise line expect fail a pythonic way write would departmentcode nameandnumberstore classnames coursenameandcodeassociationobjectsall try newclassname classnamesgetdepartmentcodeiexactdepartmentcode except coursenameandcodeassociationdoesnotexist print haha else searchterm u newclassnamedepartmentname nameandnumberstore nameandnumberstore modifysearchtermsearchterm urlstore modifyurlnameandnumberstore soup gethtmlurlstore storeofbooks scrapesoup nameandnumberstore please also note convention python use lowercaseunderscorednames variables attributes function names camelcasenames class names instance names either variables attributes,i code try print newclassname coursenameandcodeassociationobjectsgetdepartmentcodeiexact nameandnumberstore print newclassname except print haha this always prints haha despite fact i run newclassname code console worked why happening edit def newgetallinformationsearchterm nameandnumberstore modifysearchtermsearchterm urlstore modifyurlnameandnumberstore need make change i go site check course name switch scrape soup gethtmlurlstore storeofbooks storeofbooks scrapesoupnameandnumberstore print nameandnumberstore try newclassname coursenameandcodeassociationobjectsgetdepartmentcodeiexact nameandnumberstore nameandnumberstore modifysearchtermnewclassnamedepartmentname nameandnumberstore urlstore modifyurlnameandnumberstore soup gethtmlurlstore storeofbooks scrapesoupnameandnumberstore except print haha return storeofbooks edit after investigation entering valid code manually worked i think something taking code array despite fact data type string newclassname coursenameandcodeassociationobjectsgetdepartmentcodeiexact econ works file newclassname coursenameandcodeassocitionobjectsgetdepartmentcodeiexact nameandnumberstore nameandnumberstore holds econ,1 the original pep raised found distutils become standard method distributing installing python modules why it happens python wonderful language perform installation python modules,as long time python programmer i wonder central aspect python culture eluded long time what instead makefiles most rubyprojects i seen rails use rake shortly nodejs became popular cake in many compliled languages classic make files but python noone seems need infrastructure i randomly picked python projects github automation besides installtion provided setuppy what reason behind is nothing automate do programmers prefer run stylechecks tests etc manually some examples dependecies sets virtualenv installs dependencies check calls pep pylint commandlinetools test task depends dependencies enables virtualenv starts seleniumserver integration tests calls nosetest coffeescript task compiles coffeescripts minified javascript runserver task depends dependencies coffeescript deploy task depends check test deploys project docs task calls sphinx appropiate arguments some one twoliners imho add due makefile remember to clarify i looking python equivalent rake i glad paver i looking reasons,1 i basically found issue indeed fact pyinotify threaded notifier wxpython main loop dont play nice together the solution create custom main loop something i know could first place place pyinotify threaded notifier within loop that way ran part wxpython main loop i got idea httpwwwjavascomopensourcepythonguiwxpythonwxpythonsrcwxpythonsamplesmainloopmainlooppyhtm code explains concept class customappwxapp def mainloopself global handler global wm global notifier global wdd global updateui global pingtimer create event loop make active if going temporarily nested event loop get reference old one set active event loop done one evtloop wxeventloop old wxeventloopgetactive wxeventloopsetactiveevtloop this outer loop determines exit application example let main frame reset flag closes selfkeepgoing at point outer loop could whatever implemented mainloop it quick nonblocking otherwise gui freeze callyourcodehere handler handler eventhandler wm wm pyinotifywatchmanager watch manager notifier notifier pyinotifythreadednotifierwm handler notifierstart print notifier started wdd wdd wmaddwatchwatchpath wmmask rectruequietfalse this inner loop process gui events waiting evtlooppending evtloopdispatch send idle events idle handlers you may want throttle back bit somehow much cpu time spent idle handlers for example i snooze little timesleep selfprocessidle wxeventloopsetactiveold def oninitself global updateui updateui updateui updater updateuishow selfsettopwindowupdateui selfkeepgoing true return true watcher app customappfalse additionally i wanted catch sigint program i solved using recipe url httpcodeactivestatecomrecipesworkaroundformissedsigintinmultithreadedprog hope helps another python newbie oldie,i working pyinotify i issues multiple changes folder simply stops receiving notifications i feeling something fact two threads running namely notifier thread wxpython thread the purpose app essentially load picture screen detects ip connection monitor folder file checklist based file processing ie move files around it works intermittently python newbie im exactly sure issue might i basically taken threaded example worked around sometimes gets one notification stops receiving file change notifications additionally i restart linux box try works good number file changes stops receiving notifications makes think perhaps releasing watches properly any help would greatly appreciated well optimizations improvements welcome i sure i could learn lot feedback the code import pyinotify import ospath import shutil import errno import subprocess import logging import wx import time import signal import sys update checklist name checklist checklist must exist update archive static values dirupdate fileupdate f pingip localhost change production paths watchpath hometest logpath hometestupdatelog connectedimg updatejpg updatingimg updatingpng msgs updatefoundmsg update found updateunzippedstartmsg update unzipping updateunzippedmsg update unzipped updatefilemsg update file updatefilemsgcont moved path removefilemsgcont removed update folder updatecompletecont update complete roadangelrestartmsg update restarting app dircreatedmsg directory created path errors updatefailedmsg update process failed badlyformedmsg badly formed srcdest combination updatesrcunavailable invalid update file specified updatedestunavailable invalid update destination specified invalidupdateformat invalid format string startup create watchfolder doesnt exist wm pyinotifywatchmanager watch manager wmmask pyinotifyinclosewrite watched events setup logger logger logginggetlogger updater loghandle loggingfilehandlerlogpath formatter loggingformatter asctimes levelnames messages loghandlesetformatterformatter loggeraddhandlerloghandle loggersetlevellogginginfo global values used primarily main function loop handler none notifier none wdd none updateui none window none currimg none lastcurrimg none class eventhandlerpyinotifyprocessevent verbose false main class monitor file events process accordingly def processinclosewriteself event only executes checklist finished written path eventpathname print evt look updateready file processing ospathbasenamepath checklist eventhandlerparseupdateswatchpath global currimg currimg ospathjoinwatchpath updatingimg showwindow print update completed timesleep classmethod def parseupdatescls path parses update files handle errors opening file filepath ospathjoinpath checklist print filepath files openfilepath handle errors malformed tuplesdone handle errors unavailable filesdone handle errors unavailable destsdone created automatically handle permission errors line files remove linebreaks etc ensure empty linestrip array linesplit length lenarray length eventhandlerprocesslinepath array else length eventhandlerprintbadmsgarray else eventhandlerprintbadmsg print removing filepath osremovefilepath remove checklist file classmethod def mkdircls path makes directory path try osmkdirpath print dircreatedmsg path except oserror err print err errerrno errnoeexist thrown dir already exists return false classmethod def movefilecls src dest moves file src dest remove expects dest already exists point otherwise ignores move print moving src dest ospathisfiledest shutilcopysrc dest else print updatedestunavailable remove src file done osremovesrc classmethod def processlinecls path array process line checklist remove newlines etc updatefile arraystrip updatesrc ospathjoinpath updatefile updatedest arraystrip updatetype arraystrip ensure valid values three fields updatefile updatedest updatetype ensure src file exists ospathisfileupdatesrc check destination directory copy file directory updatetype dirupdate eventhandlermkdirupdatedest dest ospathjoinupdatedest updatefile eventhandlermovefileupdatesrc dest else eventhandlermovefileupdatesrc updatedest else print updatesrcunavailable else print invalidupdateformat classmethod def printbadmsgcls msg print badly formed message optional value msg print badlyformedmsg msg else print badlyformedmsg class updateframewxframe displays update images screen def initself path wxframeinitself none wxidany imagefile path image wxbitmapimagefile imagesize imagegetsize set frame size fit screen size selfsetclientsizewxdisplaysize bitmap upper left corner frame position x default pos wxstaticbitmapself wxidany image size imagesize parent frame selfsettitle update mode def pingip ping establish connection ret subprocesscallping c pingip shelltrue stdoutopen devnull w stderrsubprocessstdout ret return true else return false def showwindow update screen window currimage changes set global updateui global window global currimg global lastcurrimg lastcurrimg currimg updateui updateui wxapp window window updateframecurrimg updateuiexitmainloop whileupdateuiismainlooprunning pass windowdestroy window updateframecurrimg windowshowtrue updateuimainloop lastcurrimg currimg print changed def inupdatemode return pingip true try inupdatemode print waiting connect timesleep notifier notifierstop else handler handler eventhandler notifier notifier pyinotifythreadednotifierwm handler notifierstart wdd wdd wmaddwatchwatchpath wmmask rectruequietfalse ip active show image start notifier state ip active currimg ospathjoinwatchpath connectedimg showwindow print except keyboardinterrupt print notifierstop break,1 in case want index repo index part httpwwwsambaorgjelmerdulwichapidocsdulwichreporepohtml something like work dulwichrepo import repo x repo xstage xdocommitmessagefoo ddfddefbeaeb,how i add something index git add git commit message git push origin master using dulwich so far i found httpwwwsambaorgjelmerdulwichapidocsdulwichindexindexhtml say much thanks,1 to install pip globally python x easyinstall appears best solution adriã¡n states however installation instructions pip recommend using virtualenv since every virtualenv pip installed automatically this require root access modify system python installation installing virtualenv still requires easyinstall though,pip replacement easyinstall but i install pip using easyinstall windows is better way,3 two alternatives print tstring divfindallmatchonlynondivs u navigate none u main navigation none none u home none u about print tstring divfindallmatchonlynondivs tstring u navigate u main navigation u home u about,i want find htmlfree content tags except tags inside div idnav for example following html div idnav hnavigateh nav rolenavigation h classstructuralmain navigationh ul lia hrefhomeali lia hrefaboutaboutali ul nav div idinsidenav ul lia hrefinsidehomeali lia hrefaboutinsideaboutali ul div div code div soupfinddiv idnav def matchonlynondivstag return tagfindparentdivget id divget id tagname div print divfindallmatchonlynondivs texttrue this code output u n u navigate u main navigation u home u about u n but actually outputting u n u navigate u main navigation u home u about u n u insidehome u insideabout u n the code walk inside inner div idinsidenav going inside please help,2 your obfuscated code works fine python adapted changes trivially done running code execprintinputevalinput although eval case replaced int want obviously ridicolous using exec multiplication strings instead loops ignored rangeintinput printinput you also list expression printinput rangeintinput although people would say i would agree using list expressions side effects loop generally bad form list expressions used create lists this piece clear selfdocumenting code numintegers intinput how many integers want input x rangenumintegers printinput integer formatx,to take number test cases output input numbers i following python execprint inputinput how python shortest possible way,2 any decent test tool way running entire suite single command nothing stopping using rake make anything else really there little reason invent new way things existing methods work perfectly well reinvent something you invent nih,as long time python programmer i wonder central aspect python culture eluded long time what instead makefiles most rubyprojects i seen rails use rake shortly nodejs became popular cake in many compliled languages classic make files but python noone seems need infrastructure i randomly picked python projects github automation besides installtion provided setuppy what reason behind is nothing automate do programmers prefer run stylechecks tests etc manually some examples dependecies sets virtualenv installs dependencies check calls pep pylint commandlinetools test task depends dependencies enables virtualenv starts seleniumserver integration tests calls nosetest coffeescript task compiles coffeescripts minified javascript runserver task depends dependencies coffeescript deploy task depends check test deploys project docs task calls sphinx appropiate arguments some one twoliners imho add due makefile remember to clarify i looking python equivalent rake i glad paver i looking reasons,1 as cause problem doc says regarding text keyword if use text values give name keyword arguments ignored so findall basically ignoring matchonlynondivs divfindallmatchonlynondivs texttrue you get text matching john keyes suggested,i want find htmlfree content tags except tags inside div idnav for example following html div idnav hnavigateh nav rolenavigation h classstructuralmain navigationh ul lia hrefhomeali lia hrefaboutaboutali ul nav div idinsidenav ul lia hrefinsidehomeali lia hrefaboutinsideaboutali ul div div code div soupfinddiv idnav def matchonlynondivstag return tagfindparentdivget id divget id tagname div print divfindallmatchonlynondivs texttrue this code output u n u navigate u main navigation u home u about u n but actually outputting u n u navigate u main navigation u home u about u n u insidehome u insideabout u n the code walk inside inner div idinsidenav going inside please help,1 it easier ask forgiveness ask permission don check see method exists don waste single line code checking try dynmymethod how check whether exist method exists used except attributeerror method exist what,in function getattr referred variable found gives error how i check see variable method exists part object import string import logging class dynamo def initselfx print in init def selfxx def reprself print selfx def strself print selfx def intself print in init def def getattrself key print in getattr key color return papayawhip else raise attributeerror dyn dynamo print dyncolor dyncolor lemonchiffon print dyncolor dynint dynmymethod how check whether exist,3 you need reconnect reinitialize class login using conn imaplibimapsslimapgmailcom a complete example true imap imaplibimapsslserver r imaploginaccount password assert r ok login failed try things imap except imapabort e continue imaplogout break,i programming python applet watches unread count email boxes workplace ran eof error i try use imaplib methods applet sits idle minutes everything works fine applet alive minutes here relevant code imaplib object conn imaplibimapsslimapgmailcom def loginimap imapobj login helpdesk google apps email account using encryption imapobjloginbasebdecodeusrencryption basebdecodepwdencrytion returngetunreadimapobj def closeimap imapobj imapobjlogout def getunread imapobj check connection status ok try uc intresearchunseen imapobjstatusinbox unseengroup uc intresearchunseen imapobjstatusa box unseengroup uc intresearchunseen imapobjstatusa box unseengroup except print shit disconnected n stuff loginimapconn unreadcount ucucucucuc unreadcount unreadcount return unreadcount usrencryption pwdencryption masking helpdesk logins public when i try call getunreadconn applet open ten minues i get following output traceback recent call last file cjamin sappsdevelopmentprojectscheck hd boxcheckhdboxpy line onrefresh unread getunreadconn file cjamin sappsdevelopmentprojectscheck hd boxcheckhdboxpy line getunread uc intresearchunseen imapobjstatusinbox unseengroup file cjamin sappsdevelopmentpythonpythonlibimaplibpy line status typ dat selfsimplecommandname mailbox names file cjamin sappsdevelopmentpythonpythonlibimaplibpy line simplecommand return selfcommandcompletename selfcommandname args file cjamin sappsdevelopmentpythonpythonlibimaplibpy line commandcomplete raise selfabort command name val imaplibabort command status socket error eof traceback recent call last file cjamin sappsdevelopmentprojectscheck hd boxcheckhdboxpy line onrefresh unread getunreadconn file cjamin sappsdevelopmentprojectscheck hd boxcheckhdboxpy line getunread uc intresearchunseen imapobjstatusinbox unseengroup file cjamin sappsdevelopmentpythonpythonlibimaplibpy line status typ dat selfsimplecommandname mailbox names file cjamin sappsdevelopmentpythonpythonlibimaplibpy line simplecommand return selfcommandcompletename selfcommandname args file cjamin sappsdevelopmentpythonpythonlibimaplibpy line command raise selfabort socket error val imaplibabort socket error errno an established connection aborted software host machine the exception block doesnt really seem work problem i really need help so i keep connection alive kicking thanks,3 before fclose wait subprocess def systemexecuteself command path outfile paramslist commandsplit filepath ospathjoinpath outfile f openfilepath w sp subprocesspopenparamslist stdoutf spwait fclose def systemexecuteself command path outfile paramslist commandsplit filepath ospathjoinpath outfile f openfilepath w subprocesscallparamslist stdoutf fclose easier file handling openfilepath w f subprocesscallparamslist stdoutf,i simple python script execute test suite windows linux every test writes output separate file i use subprocesspopen class execute shell command cycle every shell command starts like def systemexecuteself command path outfile paramslist commandsplit filepath ospathjoinpath outfile f openfilepath w subprocesspopenparamslist stdoutf fclose it works fine script finishes work output files written actually i getting hundreds zerosize files takes time finish writing output close handles could anyone explain reason works strange synchronous way job thanks,3 you used nrnrn end handshake format rnrn currently n part key although i understand still able open connection looks like removing first n solves problem,i trying implement new hybi protocol python server i succeeded handshake receiving data client javascript i problems sending data client i using bit code websockify encodehybi function encode frames according protocol but unfortunately client seem receive data message event never fires so code i def encodehybiself buf opcode x buf bencodebuf b x opcode amp xf payloadlen lenbuf payloadlen header structpack bb b payloadlen elif payloadlen payloadlen header structpack bbh b payloadlen elif payloadlen header structpack bbq b payloadlen print reprheader buf return header buf def sendself data logginginfomessage sent data selfprotocol hixie selfclientsendxsxff data elif selfprotocol hybi msg selfencodehybidata selfclientsendmsg i sending simple ok socket so encodehybi function i get xxts sent javascript i response errors i tried send data example okkk after encodehybi function i get xxttlsw don know helps data sent javascript presents error unrecognized frame opcode this error appears every time length data sent bigger characters i really understand problem is something wrong encoding,2 the colour text filled graphics set using one g rg k operators content stream object pdf file described section color operators pdf reference manual the example g simple graphics example reference manual shows operators used stroke fill shapes text httpwwwadobecomdevnetpdfpdfreferencehtml when parsing pdf file start reading trailer end file contains file offset cross reference table this table contains file offset object pdf file the objects tree structure references objects one objects content stream this described sections file structure document structure pdf reference manual it possible parse pdf file quite lot work the content stream may compressed contain references objects contain comments etc must handle cases the pdfminer software already reading content stream perhaps would easier extend pdfminer report colour text,i working piece software analyses pdf files generates html based there number things already i know possible i write business reasons i managed get text information positions fonts pdf i struggling read colour text i currently using pdfminer analyse pdf beginning think i need write pdfreader even i figure document colour information text even kept i even read pdf spec cannot find information i need i scoured google joy thanks advance,1 there number options automation python i think culture automation one dominant way the common denominator distutils the one closed description buildout this mostly used zopeplone world i use combination following distribute pip fabric i mostly developing using django managepy automation commands it also actively worked python,as long time python programmer i wonder central aspect python culture eluded long time what instead makefiles most rubyprojects i seen rails use rake shortly nodejs became popular cake in many compliled languages classic make files but python noone seems need infrastructure i randomly picked python projects github automation besides installtion provided setuppy what reason behind is nothing automate do programmers prefer run stylechecks tests etc manually some examples dependecies sets virtualenv installs dependencies check calls pep pylint commandlinetools test task depends dependencies enables virtualenv starts seleniumserver integration tests calls nosetest coffeescript task compiles coffeescripts minified javascript runserver task depends dependencies coffeescript deploy task depends check test deploys project docs task calls sphinx appropiate arguments some one twoliners imho add due makefile remember to clarify i looking python equivalent rake i glad paver i looking reasons,2 your problem simply true create infinite loop the code loop run force program exit in loop create label thus create infinite number labels if want update label regular basis take advantage already running infinite loop event loop you use schedule function called future that function reschedule run guaranteeing run program quits here simple example import tkinter tk import time class sampleapptktk def initself args kwargs tktkinitself args kwargs selfclock tklabelself text selfclockpack start clock ticking selfupdateclock def updateclockself timestrftimehms timegmtime selfclockconfiguretextnow call function one second selfafter selfupdateclock name main app sampleapp appmainloop,when i call update method using tkinter instead rewriting label writes label previous call i would like rewrite previous line for example roottk true wlabelroot text price time wpack rootupdate,3 the stacktrace actually pretty clear you calling decode list instead tree element try getting first element list calling decode firsttext selftextdecodememberstringencoding,i recently started writing simple client using blogger api basic posting i implemented client python used example code verbatim blogger developer guide login get blog id make new post i ran script everything went fine i got line return bloggerservicepostentry feedsspostsdefault blogid i got error message traceback recent call last file cspostpy line module cspost file cspostpy line cspost return bloggerservicepostentry feedsspostsdefault blogid file usrlocallibpythondistpackagesgdataservicepy line post mediasourcemediasource converterconverter file usrlocallibpythondistpackagesgdataservicepy line postorput headersextraheaders urlparamsurlparams file usrlocallibpythondistpackagesatominitpy line optionalwarnfunction return fargs kwargs file usrlocallibpythondistpackagesatomservicepy line request contentlength calculatedatalengthdata file usrlocallibpythondistpackagesatomservicepy line calculatedatalength return lenstrdata file usrlocallibpythondistpackagesatominitpy line str return selftostring file usrlocallibpythondistpackagesatominitpy line tostring return elementtreetostringselftoelementtree encodingstringencoding file usrlocallibpythondistpackagesatominitpy line toelementtree selfaddmemberstoelementtreenewtree file usrlocallibpythondistpackagesatominitpy line addmemberstoelementtree memberbecomechildelementtree file usrlocallibpythondistpackagesatominitpy line becomechildelement selfaddmemberstoelementtreenewchild file usrlocallibpythondistpackagesatominitpy line addmemberstoelementtree extensioncontaineraddmemberstoelementtreeself tree file usrlocallibpythondistpackagesatominitpy line addmemberstoelementtree treetext selftextdecodememberstringencoding attributeerror list object attribute decode by i taking elementtree fault i installed elementtree via sudo python setuppy install case matters is known incompatibility elementtree python v has happened anybody else get working if need additional information please reply thread all source code relevant basically example code developers guide mentioned i modified even variable names any input greatly appreciated,1 i answer question i started using modproxy everything ok,localimport function randomly import modules modules directory the error importerror no module named testappmodulesmymodule i problem use webpy apache wsgi i problem run locally python webpypy command any suggestion,1 your error message xmlsyntaxerror switching encoding encoder error line column you asked ideas here novel idea tell us first bytes line then somebody may able come remedy update the encoding declaration incorrect the data not encoded gb it least gbk aka cp gb year limited character set chinese websites using utf would using least superset gbk use well years moving supersuperset gb utf see python import urllib url httpwwwzaobaocomspspxml data urlliburlopenurlread lendata data xml version encodinggbnnrss versionnnnchannelntitlexcxaaxbaxcfxdxexbxaxcdxf zaobaoco x datadecode gb traceback recent call last file stdin line module unicodedecodeerror gb codec decode bytes position illegal multibyte sequence data xn x datadecode utf traceback recent call last file stdin line module file cpythonlibencodingsutfpy line decode return codecsutfdecodeinput errors true unicodedecodeerror utf codec decode byte xc position invalid start byte x datadecode gbk datadecode cp x true i suggest try xmlelementfromurlfeed encoding gbk if works may wish bulletproof code notuncommon problem reading data urllib checking gb find use gb instead update in case anyone mentions chardet due gbk using many unused slots gb chardet working actuallyused slots attempting verify answer trial decode charget guesses gb,i rss feed shich encoded gb when i trying parse using following code item xmlelementfromurlfeedxpath item title itemfind title text it able parse feed any idea parse gb encoded rss feed the error log plex media server using encoding item xmlelementfromurlfeed encoding gb xpath item title itemfind title text error log file cdocuments settingssubhenduswainlocal settingsapplication dataplex media serverpluginszaobaobundlecontentscodeinitpy line getdetails item xmlelementfromurlfeed encoding gb xpath item file cdocuments settingssubhenduswainlocal settingsapplication dataplex media serverpluginsframeworkbundlecontentsresourcesversionspythonframeworkapiparsekitpy line elementfromurl return selfelementfromstringselfcorenetworkinghttprequesturl values headers cachetime autoupdate encoding errors immediatetrue sleepsleep openerselfopener txnidselftxnidcontent ishtmlishtml file cdocuments settingssubhenduswainlocal settingsapplication dataplex media serverpluginsframeworkbundlecontentsresourcesversionspythonframeworkapiparsekitpy line elementfromstring return selfcoredataxmlfromstringstring ishtml file cdocuments settingssubhenduswainlocal settingsapplication dataplex media serverpluginsframeworkbundlecontentsresourcesversionspythonframeworkcomponentsdatapy line fromstring return etreefromstringmarkup file lxmletreepyx line lxmletreefromstring srclxmllxmletreec file parserpxi line lxmletreeparsememorydocument srclxmllxmletreec file parserpxi line lxmletreeparsedoc srclxmllxmletreec file parserpxi line lxmletreebaseparserparsedoc srclxmllxmletreec file parserpxi line lxmletreeparsercontexthandleparseresultdoc srclxmllxmletreec file parserpxi line lxmletreehandleparseresult srclxmllxmletreec file parserpxi line lxmletreeraiseparseerror srclxmllxmletreec xmlsyntaxerror switching encoding encoder error line column debug core response,1 len gets length list it actually get number elements list there could spaces empty still part list,i new python following code liste asdfasfasdasdfafaergasde example string looks like liste strsplit listecount print not yet supported according doc httpdocspythonorglibrarystdtypeshtml python return number i‘s si x is function give number elements list thanks advance,3 setuptools automate lot things things builtin easily extensible to run unittests use setuppy test command added testsuite argument setup call documentation dependencies even available pypi handled adding installrequires extrasrequire dependencylinks argument setup call documentation to create deb package use stdeb module for everything else add custom setuppy commands but i agree slott tasks wish automate except dependencies handling maybe one i find really useful tasks run everyday real productivity improvement automating,as long time python programmer i wonder central aspect python culture eluded long time what instead makefiles most rubyprojects i seen rails use rake shortly nodejs became popular cake in many compliled languages classic make files but python noone seems need infrastructure i randomly picked python projects github automation besides installtion provided setuppy what reason behind is nothing automate do programmers prefer run stylechecks tests etc manually some examples dependecies sets virtualenv installs dependencies check calls pep pylint commandlinetools test task depends dependencies enables virtualenv starts seleniumserver integration tests calls nosetest coffeescript task compiles coffeescripts minified javascript runserver task depends dependencies coffeescript deploy task depends check test deploys project docs task calls sphinx appropiate arguments some one twoliners imho add due makefile remember to clarify i looking python equivalent rake i glad paver i looking reasons,3 i see file wsgi application implements application method you need configure apache send requests using modwsgi wsgi server try adding site htaccess correct file path wsgiscriptalias torbulkexitlist usrlocalwwwcgibintorbulkexitlistpy visit httpexamplecomtorbulkexitlist click read modwsgi configuration,i web server run python scripts i experience python i uploaded file torbulkexitlistpy server inside cgibin folder i tried calling browser giving internal server error here python script httpssvntorprojectorgsvnchecktrunkcgibintorbulkexitlistpy is anything i need i could run script i change anything script any alternative i need get list tor exit ips i linuxphpapache server btw,1 it called docstring,here snippet code djangocoreexceptions class middlewarenotusedexception this middleware used server configuration pass is bare string body class mere literal documentation or perform magic,1 it docstring the magic ends object doc,here snippet code djangocoreexceptions class middlewarenotusedexception this middleware used server configuration pass is bare string body class mere literal documentation or perform magic,1 it doc string a docstring string literal occurs first statement module function class method definition such docstring becomes doc special attribute object all modules normally docstrings functions classes exported module also docstrings public methods including init constructor also docstrings a package may documented module docstring initpy file package directory,here snippet code djangocoreexceptions class middlewarenotusedexception this middleware used server configuration pass is bare string body class mere literal documentation or perform magic,3 use platformpythoncompiler,when i start python interpreter command line mode i get message saying compiler used building is way get information python i know i could start interpreter subprocesspopen parse output i looking easier elegant method the background i want build python extensions cmake based c framework i would like write cmake macro wich checks correct compiler installed,3 in cpython threadingtimer accuracy waiting part based conditionwait call the conditionwait implemented done successive sleep delay mindelay remaining delay originally set us initial delay ms according implementation os independant argue accuracy least timesleep accuracy but timesleep accuracy based os used implementation floatsleep windows uses waitforsingleobject internal windows timer linux uses select method at least apart sleep delay charge os could interfer reactivity python process scheduling algorithm also influence accuracy,what time accuracy python threadingtimer depend does depend os used does depend python implementation used does depend interval how benchmarked are already benchmarks,2 you use sysversion variable access information sysversion default jun ngcc it tell compiler used compile python ensure mentioned compiler installed system could prebuilt python version,when i start python interpreter command line mode i get message saying compiler used building is way get information python i know i could start interpreter subprocesspopen parse output i looking easier elegant method the background i want build python extensions cmake based c framework i would like write cmake macro wich checks correct compiler installed,2 fields editable fields use readonlyfields instead,lets say i django model list numbers field i compute statistics field using custom method model these models displayed admin panel inlineadminmodel embedded parent object is way display custom method value admin panel modifying parent model would obviously apply ones already created eg truncated class listmodelmodelsmodel numberlist modelscommaseparatedintegerfieldmaxlength def sumself return sumints numberlistsplit class listmodeladminadmintabularinline model listmodel listdisplay sum works fine displaying listmodel fields numberlist sum obviously doesn work demonstrates i want accomplish sum settable displayed numberlist updated,1 sure in entry point function mainglobalconfig settings initpy cases config accessible settings variable for example ini appmain blogtitle custom blog name blogcommentsenabled true in initpy def mainglobalconfig settings config configuratorsettingssettings blogtitle settings blogtitle also access settings via config commentsenabled configregistrysettings blogcommentsenabled return configmakewsgiapp according latest pyramid docs access settings view function via requestregistrysettings also far i know event subscribers via eventrequestregistrysettings regarding question using another file i pretty sure good practice put config regular init file using dotted notation like,each pyramid application associated ini file contains settings for example default might look like appmain use eggmyproject pyramidreloadtemplates true pyramiddebugauthorization false pyramiddebugnotfound false pyramiddebugroutematch false i wondering possible add configuration values read runtime mostly view callable for instance i might want appmain blogtitle custom blog name blogcommentsenabled true or better separate ini file parse startup,3 your code binds server localhost ie listens local connections replace udpserverinitself localhost growludpport requesthandler udpserverinitself growludpport requesthandler accept connections anywhere,i trying run script ubuntu box httptaoofmaccomspaceprojectsregrowl its small script bound udp port designed relay growl packets i send script growl packets local machine works exactly expected however trying send packets another machine network seem dropped make script i configured ubuntu allow port output netstat looks like rootubuntuvm netstat grep udp udp localhost udp mdns udp mdns udp udp udp mdns my script first entry list i used wireshark confirmed ubuntu machine receiving packets do i need todo anything ubuntu allow python bind udp ports anyone know whats going thanks advance update the output script look like sep register network responder sep notify network status connection status test network responder the first ip source packet array ips end destinations packet relayed as packet originated local machine i send packet form another machine ip apear first here portion script implements udp server class growlrelayudpserver growl notification relay allowreuseaddress true def initself inpassword none outpassword none initializes relay launches resolver thread selfinpassword inpassword selfoutpassword outpassword selfresolver rendezvouswatcher selfresolverstart udpserverinitself localhost growludpport requesthandler def servercloseself selfresolvershutdown the full script dependant classes available link,2 you using import for example foobar importfoobar but really rename module instead that way avoid confusion filename module different identifier used program,i existing python module dash name foobarpy changing module name something i would prefer avoid module shared i would chase places used special case work is way load module whose name contains typically forbidden i understand best practice but situation i would prefer redesign test much larger set applications also i think corporate masters would approve taking time implement change,3 this tested answer closer push part set wants master def wantmasterhaves wants global repo return refsheadsmaster reporefshead client src dulwichclientgettransportandpathoriginuri clientsendpacksrc wantmaster repoobjectstoregeneratepackcontents a variation working code,how i add something index git add git commit message git push origin master using dulwich so far i found httpwwwsambaorgjelmerdulwichapidocsdulwichindexindexhtml say much thanks,2 if talking strictly cjavalike interface answer simple they concepts belong statically typed languages really apply dynamic language python the usual pythonic approach trust objects get assume necessary traits need should might expect runtime errors handled left caller this matches general dynamic nature language something goes wrong expect surface runtime interfaces java c hand means checking necessary preconditions ie objects certain methods compilation this arguably trades runtime flexibility increased safety compiletime checks note mean concept interface place dynamically typed language in fact python slightly blurred notion metatypes iterables often checked eg verifying presence particular methods def processsequenceseq hasattrseq iter seq seq turn single element iterable elem seq processelementelem this conceptually similar nonmanifest interfaces go language if want iterable implement iter method without explicitly stating implement java would inherit list class should anyone wants check whether object indeed iterable verify whether contract ie iter method indeed fulfilled this andronikus described answer as shameless plug i point pyduck library i implementing it aims simplify maybe even standarize verification contracts via reflection make slightly reliable,i worked months c programmer got used idea genericstemplates interfaces i could pass library without caring object created i start relatively large project probably python i written lot python mostly code data analysis etc wondering exists similar concept language i tried googling come much if answer fine case people generally instead,2 use i format code instead l on linux machine l twice long h four times long bytes bits instead bytes bits i bytes bits edit make sure read eryksun comment,coding linux debian machine python my neighbour windows xp python he run code w w w unpacklll packllhh localtime ipddr counter aid but try code become error w w w unpacklll packllhh localtime ipddr counter aid structerror unpack str size match format can version python maybe system,2 the datetime module written entirely c this includes function subtracts one datetimedatetime object another that function called newdelta directly instantiates pydatetimedeltatype original datetimetimedelta class written c it notice rebound datetimetimedelta class pythonland i see easy workarounds,i trying make one libraries compatible python it uses method datetimetimedeltatotalseconds added make work i wanted monkey patch timedelta like import datetime hasattrdatetimetimedelta totalseconds class timedeltadatetimetimedelta def totalsecondsself return selfdays selfseconds selfmicroseconds e datetimetimedelta timedelta this actually work cases eg i create timedelta variable method but new timedelta object produced subtracting two datetimedatetime values method missing resulting object what going wrong i fix,2 looks like imported pyopencv cv so editting cvmedian cvcvmedian help,i need fast median filter images python time google seems like opencv way go speed even python i got opencv running filters like erode dilate works fine cverodecvimcvimnone cvdilatecvimcvimnone the median filter however seem work cvsmoothcvimcvimcvmedian nameerror global name cvmedian defined i seem figure i wrong according documentation httpopencvwillowgaragecomdocumentationpythonimagefilteringhtmlsmooth looks like i correct way any ideas many thanks advance,2 example create dict maps names classes dictname cls name cls moddictitems isinstancecls type mod loaded module,i module child package imported dynamically i iterate classes contains i importing module listing names like package currentmodulename package packagepackagerindex get package package ssubspackagename make name child print loading package spackage module importpackage succeeds nameobj inspectgetmembersmodule print nametypeobj this prints module attributes class types module defines builtins type dict doc type nonetype file type str name type str package type nonetype path type list importedpackage type module update it seems classes dict unless fromlist nonempty the values fromlist seem validated though seems work fine suddenly classes show can anyone explain standard ubuntu python r,3 for wxpython x complete build source instructions httpwxpythonorgbuildhtml if rather go use following instructions instead httpwxpythonorgbuilddocphp if run issues join wxpythonusers mailing list google group httpwxpythonorgmaillistphp tell versions wxpython python using along linux almost certainly get help there lot linux guys,i trying install wxpython source linux the steps i followed download wxpython httpdownloadssourceforgenetwxpythonwxpythonsrctarbz run configure prefixhomelocal at end configure process output configured wxwidgets xunknownlinuxgnu which gui toolkit wxwidgets use gtk should wxwidgets compiled single library should wxwidgets compiled debug mode should wxwidgets linked shared library yes should wxwidgets compiled unicode mode what level wxwidgets compatibility enabled wxwidgets wxwidgets yes which libraries wxwidgets use jpeg sys png sys regex sys tiff builtin zlib sys odbc expat builtin libmspack sdl make wxpython appears run without errors make install but i try import wx python console v python find module so questions am i missing dependencies although wxpython seems build install without errors did i miss anything installation process how i make python aware new package any hint link article appreciated,1 have considered using signals you could send signal recentactivitypostsave could listener stores information cache the view would refer cache see new notifications of course need signals imho would bit cleaner way could add notification handlers this seems optimal need poll db artificial load notifications visible almost immediately time required process signals interact cache so pseudocode would look like model def recentactivitypostsave postsavesignalsend listener def myhandler cacheset notification postsavesignalconnect myhandler view def myview request newnotification none newnotification sleep newnotification cacheget notification return httpresponse,i need develop realtime recent activity feed django ajax longpolling i wondering best strategy serverside pseudocode def recentactivitypostsave notifyview view newactivity sleep return httpresponsenewactivity the first thing comes mind querying db every second not feasible other options using cache notification service using specialized tool like celery i rather seems like overkill what best way go,1 you right thing userprofile extension user model and logically making relation object object relation object extra information also mentioned always issue getprofile get extra data,finally make djangoauth app works i add extra information user docs say now simple question when building model related user user relate to authmodelsuser accountsuserprofile an example i model product product belongs user which would best option class productmodelsmodel user modelsforeignkeyauthmodelsuser class productmodelsmodel user modelsforeignkeyaccountsuserprofile i currently using authmodelsuser becouse issue getprofile friend told wrong thank,2 operatoritemgetter need inpcsvreaderopen outpcsvwriteropen mapoutpwriterowmapoperatoritemgetterxyzinp where xyz columns want reorder however since first row summarycsv headers might consider using dictreader dictwriter writenames idaveragemaxminmedianmodestddevskewnesskurtosissplit reader csvdictreaderopenhomeusrschrissummarycsv rb writer csvdictwriteropenhomeusrschrissummarynewcsv wb fieldnameswritenames reorderfunct lambda r dictcol rcol col writenames writerwriteheader row reader writerwriterowreorderfunctrow,i would like similar process csv file detailed question i get error message saying typeerror list indices must integers the csv file i want rearrange combination float text integer data types i assuming problem figure way modify code insert data it writes header information new csv file though i using code suggested john machin write names variable uses writenames idaveragemaxminmedianmodestddevskewnesskurtosissplit reader csvreaderopenhomeusrschrissummarycsv rb writer csvwriteropenhomeusrschrissummarynewcsv wb readnames readernext namesindicies dictnameindex index name enumeratereadnames writeindices namesstringname name writenames reorderfunct operatoritemgetterwriteindices writerwriterowwritenames row reader writerwriterowreorderfunctrow,1 in request client sending wsgirequest client header httpacceptencodxddng gzip deflate if actual encoding wsgirequest supposed utf server error legitimate unless really client sent in utf byte value xdd used first twobyte character coding case next byte must leading bits but byte following xdd leading bit decode error using utf if actual encoding wsgirequest something else server error may legitimate client header could interpreted httpacceptencodãng gzip deflate case iso ignored try identify specific client sending requests,i django web application running apache modwsgi dedicated server centos however sometimes six seven times day starts give error random pages but i refresh page two three times page turns normal but starts give error every page web site gives error after i restarted apache turns normal hours never ends give error i paste full error log indeed says djangounicodedecodeerror utf codec decode byte xdd position invalid continuation byte what may cause kind error i detect i may provide additional information asap ps i setup local pcapachemodwsgi win i never got error wed sep error client modwsgi pid exception occurred processing wsgi script varwwwhtmlmysitedjangowsgi referer httpwwwmysitecom wed sep error client traceback recent call last referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangocorehandlerswsgipy line call referer httpwwwmysitecom wed sep error client response selfgetresponserequest referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangocorehandlersbasepy line getresponse referer httpwwwmysitecom wed sep error client response selfhandleuncaughtexceptionrequest resolver sysexcinfo referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangocorehandlersbasepy line handleuncaughtexception referer httpwwwmysitecom wed sep error client return debugtechnicalresponserequest excinfo referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangoviewsdebugpy line technicalresponse referer httpwwwmysitecom wed sep error client html reportergettracebackhtml referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangoviewsdebugpy line gettracebackhtml referer httpwwwmysitecom wed sep error client frame vars k forceescapepprintv k v frame vars referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangotemplatedefaultfilterspy line dec referer httpwwwmysitecom wed sep error client args forceunicodeargs referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangoutilsencodingpy line forceunicode referer httpwwwmysitecom wed sep error client raise djangounicodedecodeerrors eargs referer httpwwwmysitecom wed sep error client djangounicodedecodeerror utf codec decode byte xdd position invalid continuation byte you passed wsgirequestngetquerydict npostquerydict ncookiesnmeta csrfcookie edacbdadfcb n documentroot varwwwhtmlmysite n gatewayinterface cgi n httpaccept applicationxmlapplicationxhtmlxmltexthtmlqtextplainqimagepngq n httpacceptencodxddng gzip deflate n httpacceptlanguage enus n httpcachecontrol maxage n httpconnectxddon keepalive n httpcookxdde csrftokenbcdefbcedafafb sessionidfbffeeffb n httphost wwwmysitecom n httpreferer httpwwwmysitecom n httpuseragent mozilla ipad u cpu os like mac os x enus applewebkit khtml like gecko version mobileb safari n pathinfo u mainfaq n pathtranslated varwwwhtmlmysitedjangowsgimainfaq n querystring n remoteaddr n remoteport n requestmethod get n requesturi mainfaq n scriptfilename varwwwhtmlmysitedjangowsgi n scriptname u n serveraddr n serveradmin bilgimysitecom n servername wwwmysitecom n serverport n serverprotocol http n serversignature addressapache centos server wwwmysitecom port addressn n serversoftware apache centos n modwsgiapplicationgroup mysitecom n modwsgicallableobject application n modwsgihandlerscript n modwsgiinputchunked n modwsgilistenerhost n modwsgilistenerport n modwsgiprocessgroup n modwsgirequesthandler wsgiscript n modwsgiscriptreloading n modwsgiversion n wsgierrors modwsgilog object xbdddbfbn wsgifilewrapper builtin method filewrapper modwsgiadapter object xbdfan wsgiinput modwsgiinput object xbdfaan wsgimultiprocess truen wsgimultithread falsen wsgirunonce falsen wsgiurlscheme http n wsgiversion type str referer httpwwwmysitecom the web site works seamlessly apache django builtin developer server local computerwinapachemodwsgi,1 the error already says md operates bytes encode unicode string bytes eg lineencode utf,i error traceback recent call last file pythonmdcrackerpy line module mupdateline typeerror unicodeobjects must encoded hashing i try execute code python import hashlib sys hashlibmd hash hashfile inputwhat file name hash resides wordlist inputwhat wordlist enter file name try hashdocument openhashfiler except ioerror printinvalid file rawinput sysexit else hash hashdocumentreadline hash hashreplacen try wordlistfile openwordlistr except ioerror printinvalid file rawinput sysexit else pass line wordlistfile hashlibmd flush buffer caused massive problem placed beginning script buffer kept getting overwritten thus comparing incorrect hashes line linereplacen mupdateline wordhash mhexdigest wordhashhash printcollision the word corresponding given hash line input sysexit printthe hash given correspond supplied word wordlist input sysexit,3 it probably looking character encoding wordlistfile wordlistfile openwordlistrencoding utf or working linebyline basis lineencode utf,i error traceback recent call last file pythonmdcrackerpy line module mupdateline typeerror unicodeobjects must encoded hashing i try execute code python import hashlib sys hashlibmd hash hashfile inputwhat file name hash resides wordlist inputwhat wordlist enter file name try hashdocument openhashfiler except ioerror printinvalid file rawinput sysexit else hash hashdocumentreadline hash hashreplacen try wordlistfile openwordlistr except ioerror printinvalid file rawinput sysexit else pass line wordlistfile hashlibmd flush buffer caused massive problem placed beginning script buffer kept getting overwritten thus comparing incorrect hashes line linereplacen mupdateline wordhash mhexdigest wordhashhash printcollision the word corresponding given hash line input sysexit printthe hash given correspond supplied word wordlist input sysexit,3 use revision past one simply download tip wtforms moving html way generating form elements adding new widgets i believe see thread one bit information there also extension wtforms adds xhtml back decide need,i noticing wtforms flaskwtf output input elements closing slash like input nametext typetext value my documents html therefore need xhtmltype closure how would i make wtforms output input tag input nametext typetext value i tearing docs source code finding clues i could create series custom widgets course seems bit excessive something simple is easier way or perhaps jinja configuration issue i missing,1 im sure i get question right i believe investigate framework middleware give access screen i would say pygame pyglet maybe even panda it may overkill bit pygame panda framework let develop game pyglet wrapper opengl python let control pixels windows similar easy,i wanting something like following pixel draw r pixel xy pixel draw g pixel xy pixel draw b pixel xy i hope display many different configurations pixels colours short space time writing intermediary file would expensive how i best go achieving goal python,1 although exactely say paint pixel i like use python gtk cairo in case create gtk window add drawingarea create cairo context paint operations the difference continuous canvas floatingpoint coordinates instead pixels draw geometric shapes strokes fills you could even draw rectangles onepixelsized fill would fast also take raster object image pixbuffer render then could generate images fast sequence render pixels similar movie a working example seen previous answer second snippet quickest way get started cairo,i wanting something like following pixel draw r pixel xy pixel draw g pixel xy pixel draw b pixel xy i hope display many different configurations pixels colours short space time writing intermediary file would expensive how i best go achieving goal python,1 if look docs bytes points bytearray bytearraysource encoding errors return new array bytes the bytearray type mutable sequence integers range x it usual methods mutable sequences described mutable sequence types well methods bytes type see bytes byte array methods the optional source parameter used initialize array different ways if string must also give encoding optionally errors parameters bytearray converts string bytes using strencode if integer array size initialized null bytes if object conforming buffer interface readonly buffer object used initialize bytes array if iterable must iterable integers range x used initial contents array without argument array size created so bytes much encode string it pythonic would allow call constructor type source parameter makes sense for encoding string i think somestringencodeencoding pythonic using constructor self documenting take string encode encoding clearer bytessomestring encoding explicit verb use constructor edit i checked python source if pass unicode string bytes using cpython calls pyunicodeasencodedstring implementation encode skipping level indirection call encode also see serdalis comment unicodestringencodeencoding also pythonic inverse bytestringdecodeencoding symmetry nice,there appears two different ways convert string bytes seen answers typeerror str support buffer interface which methods would better pythonic or matter personal preference b bytesmystring utf b mystringencode utf,3 direct answer this done osspecific apis some oses allow changing pixels screen directly on windows use pywin libraries get screen device context dc getdc call paint pixels setpixeldc x color of course paint way erased moment right answer painting pixel pixel slowest way paint something for example windows creating image memory painting one operation order magnitude faster painting setpixel if need speed use user interface library python example tkinter module pyqt create window image memory paint image window if need manipulate pixels manipulate image repaint every time,i wanting something like following pixel draw r pixel xy pixel draw g pixel xy pixel draw b pixel xy i hope display many different configurations pixels colours short space time writing intermediary file would expensive how i best go achieving goal python,3 you state encoding feed iso in case bytes say interpreted â® fact c ae text really truly emmyã‚â® awards everything working if sender intended different text would sent different data set encoding differently if encoding feed utf bytes sent wire still c ae text would emmyâ® awards if encoding feed iso bytes sent wire simply ae c text would emmyâ® awards to sure bytes use od x command unix command debugexe windows don trust notepad situations like it lies,my rss feed ontains title cdatahbo wins emmyâ® awards the most any network this yeartitle now i parsing rss assigning title title item xmlelementfromurlfeedxpath item namespacesnewsns title itemfind title text logtitle title i checking put log file i see title hbo wins emmyã‚â® awards the most any network this year â® gets converted ã‚â® any i tried using html parser use,1 don put inside loop csvwriteropenfilelocation wb delimiter instead openfilelocation wb fout csvwriterfout delimiter put forloop notes openfilelocation wb creates new file destroying old file name this looks like writer overwriting old lines use open automatically closes file withblock ends this makes explicit file closed otherwise file remains open maybe completely flushed deleted reassigned new value it really main problem using useful mention,i trying create csv file list urls i pretty new programming please excuse sloppy code i loop runs list places get list urls i loop within loop exports data csv file import urllib csv beautifulsoup import beautifulsoup listofurls csvreaderopenfilelocationforurlstoparse row listofurls rowstring joinrow file urlliburlopenrowstring pagehtml fileread soup beautifulsouppagehtml parsing html thumbnailimage soupfindalldiv class remositorythumbnail thumbnailimagestring strthumbnailimage soup beautifulsoupthumbnailimagestring thumbnailimageurl soupfindall attrs href recompilehttp this part working csvwriteropenfilelocation wb delimiter tag soupfindall hreftrue outwriterowtag href basically writer keeps writing way jump first empty row csv start writing,2 are closing file every write opening file every write just check also try using ab mode instead wb ab append file,i trying create csv file list urls i pretty new programming please excuse sloppy code i loop runs list places get list urls i loop within loop exports data csv file import urllib csv beautifulsoup import beautifulsoup listofurls csvreaderopenfilelocationforurlstoparse row listofurls rowstring joinrow file urlliburlopenrowstring pagehtml fileread soup beautifulsouppagehtml parsing html thumbnailimage soupfindalldiv class remositorythumbnail thumbnailimagestring strthumbnailimage soup beautifulsoupthumbnailimagestring thumbnailimageurl soupfindall attrs href recompilehttp this part working csvwriteropenfilelocation wb delimiter tag soupfindall hreftrue outwriterowtag href basically writer keeps writing way jump first empty row csv start writing,1 this rounding issue decimal values cannot represented exactly binary x never exactly equals try replacing x x btw parentheses unnecessary python statement edit printing values steps shows case zero prints e,in python program statement entered i simplified code following x x x print x this program output anything however changing last line x makes program output what problem,2 floating point number representation might accurate enough you never test zero equality instead use something along absx e,in python program statement entered i simplified code following x x x print x this program output anything however changing last line x makes program output what problem,3 archie answer good become outdated socketio updates specifically protocol httpsgithubcomlearnboostsocketiospec far tell need perform handshake manually ask transport eg websockets connection note code incomplete insecure one ignores list supported transports returned handshake response always tries get websocket also assumes handshake always succeeds nevertheless good place start import websocket httplib connect socketio server perform http handshake open websocket connection def connectself conn httplibhttpconnection localhost connrequest post socketio resp conngetresponse hskey respreadsplit selfws websocketwebsocket wslocalhostsocketiowebsocket hskey onopen selfonopen onmessage selfonmessage might also want read pythonwebsockets httpsgithubcommtahpythonwebsocket,can anyone recommend socketio client library python i look around ones i find either server implementations depend framework twisted i need client library dependencies frameworks simply using one many connection types sufficient python client need work multiple socketio servers many support websockets example,3 others pointed issue floatingpoint numbers unable represent values exactly if need exact decimal representation number use decimal class decimal import decimal x decimal x x print x decimal this print expect note use string increment if used decimal problem accurate representation converting floatingpoint number already lost accuracy class allow,in python program statement entered i simplified code following x x x print x this program output anything however changing last line x makes program output what problem,2 behold power print statement let us insert print statement x x x print x print x running program inspecting output around reveals problem e oh boy never actually equal zero solutions use integers most reliable x times make integerbased program x x print x never test equality floating point arithmetic rather use range delta close need get point point interested pointdelta x pointdelta stuff,in python program statement entered i simplified code following x x x print x this program output anything however changing last line x makes program output what problem,3 try picloud pay per second,i periodic task i need run ec this task take minutes run i want end paying minutes task idle from understanding i start instance run task matter whether i use resources i billed usage so i looking something following lines every minutes highlevel sketch def invoketimeri timeri expired copydatafromnodei killnodei true range startnodei allow node boot startscripti invoketimeri sleep assuming i able convey idea good way implementing clean fashion perhaps tutorial could help,3 use strjoin result joiniterable if items collection strings use map generator expression result joinstritem item iterable,in c i collection strings i want get commaseparated string representing collection without extraneous comments beginning end i string result collectionaggregates stringformat i could something like result collection string collection result formatresult string but feels like cludge does python elegant way accomplish thing,3 nssdll linked following dlls located firefox directory nssutildll plcdll pldsdll nsprdll mozcrtdll the system library loader looks files dll search path process includes application directory system directories current directory directories listed path environment variable the simplest solution change current directory dll firefox directory however thread safe i rely general another option append firefox directory path environment variable i suggested original version answer however much better modifying current directory newer versions windows nt update kb allow dll search path updated threadsafe manner via setdefaultdlldirectories adddlldirectory removedlldirectory but approach would top in case sake simplicity compatibility older versions windows suffices call loadlibraryex flag loadwithalteredsearchpath you need load dll using absolute path else behavior undefined for convenience subclass ctypescdll ctypeswindll call loadlibraryex instead loadlibrary import os import ctypes osname nt ctypes import wintypes kernel ctypeswindll kernel uselasterrortrue def checkboolresult func args result raise ctypeswinerrorctypesgetlasterror return args kernelloadlibraryexwerrcheck checkbool kernelloadlibraryexwrestype wintypeshmodule kernelloadlibraryexwargtypes wintypeslpcwstr wintypeshandle wintypesdword class cdllexctypescdll def initself name mode handlenone useerrnotrue uselasterrorfalse osname nt handle none handle kernelloadlibraryexwname none mode supercdllex selfinitname mode handle useerrno uselasterror class windllexctypeswindll def initself name mode handlenone useerrnofalse uselasterrortrue osname nt handle none handle kernelloadlibraryexwname none mode superwindllex selfinitname mode handle useerrno uselasterror here available loadlibraryex flags dontresolvedllreferences x loadlibraryasdatafile x loadwithalteredsearchpath x loadignorecodeauthzlevel x nt loadlibraryasimageresource x nt loadlibraryasdatafileexclusive x nt these cannot combined loadwithalteredsearchpath install update kb nt amp loadlibrarysearchdllloaddir x loadlibrarysearchapplicationdir x loadlibrarysearchuserdirs x loadlibrarysearchsystem x loadlibrarysearchdefaultdirs x for example firefoxpath r fsoftwaresmozilla firefox nss cdllexospathjoinfirefoxpath nssdll loadwithalteredsearchpath nssnssgetversionrestype ccharp nssnssgetversion basic ecc,i trying access functions dll nssdll ships firefox web browser to handle task i used ctypes python the problem fails initial point loading dll memory this code snippet i ctypes import windllloadlibraryenssdll the exception i getting traceback recent call last file pyshell line module windllloadlibraryenssdll file cpythonlibctypesinitpy line loadlibrary return selfdlltypename file cpythonlibctypesinitpy line init selfhandle dlopenselfname mode windowserror error the specified module could found i also tried loading firefox installation path assuming maybe dependencies windllloadlibraryfsoftwaresmozilla firefoxnssdll but i getting exception mentioned thanks,3 it seems weird try limit rate across multiple threads if limit thread independently avoid locking nonsense just guess i think want set lasttime timetime currenttime sleep,given number threads i want limit rate calls worker function rate say one per second my idea keep track last time call made across threads compare current time thread then currenttime lasttime rate i let thread sleep bit something wrong implementation i presume i may gotten wrong idea locks work my code queue import queue threading import thread lock rlock import time numworkerthreads rate q queue lock lock lasttime timetime def doworki idx do work print dummy print thread item time formati idx timetime def workeri true lockacquire currenttime timetime interval currenttime lasttime lasttime currenttime interval rate timesleeprate interval lockrelease item qget doworki item qtaskdone rangenumworkerthreads threadtargetworker argsi tdaemon true tstart item xrange qputitem qjoin i expecting see one call per second dowork however i get mostly calls time thread followed one second pause what wrong ok edit the advice simply throttle rate items put queue good however i remembered i take care case items readded queue workers canonical example pagination backingoffretry network tasks i came following i guess actual network tasks eventletgevent libraries may easier resources example it basically uses priority queue pile requests uses extra thread shovel items pile actual task queue even rate i simulated reinsertion pile workers reinserted items treated first import sys import os import time import random queue import queue priorityqueue threading import thread rate def workerq qpile idx true item qget printthread processed formatitem idx randomrandom printthread reinserting item formatitem idx qpileput timetime item qtaskdone def scheduleqpile q true qpileempty printitems pile formatqpileqsize qputqpileget qpiletaskdone timesleeprate def main qpile priorityqueue q queue range threadtargetworker argsq qpile tdaemon true tstart tschedule threadtargetschedule argsqpile q tscheduledaemon true tschedulestart qpileput timetime range qpilejoin qjoin name main main,1 literal foobar wordpypalphas defines pyparsing parseexpression requires text startwith foobar followed alphacharacter for example import pyparsing pyp ident pypcombinepypliteral foobar pypwordpypalphas foo match identsearchstring bar foobarfoo bar foobarbafoo printmatchfoo yields foobarfoo foobarbafoo,hey i written simple parser pyparsing detects tokens text replaces different string the problem right code works exact matches what i like detect partial matches for example token foobar i like match word like foobarfoo is way pyparsing i looked examples research i came nothing thanks edit i list tokens match list words text so i want solution takes account fact the list tokens quite big,2 simplest would use pyparsing regex expression grammar startswithfoobar regexrfoobarazaz,hey i written simple parser pyparsing detects tokens text replaces different string the problem right code works exact matches what i like detect partial matches for example token foobar i like match word like foobarfoo is way pyparsing i looked examples research i came nothing thanks edit i list tokens match list words text so i want solution takes account fact the list tokens quite big,2 i get mostly calls time thread followed one second pause what wrong that exactly expect implementation lets say time starts rate thread lockacquire threads wait one gets lock currenttime timetime start interval currenttime lasttime interval lasttime currenttime lasttime interval rate rate sleep timesleeprate interval lockrelease thread wakes job thread lockacquire get lock currenttime timetime still interval currenttime lasttime interval lasttime currenttime interval rate interval rate sleep timesleeprate interval lockrelease threads start work around my advice limit speed items put queue,given number threads i want limit rate calls worker function rate say one per second my idea keep track last time call made across threads compare current time thread then currenttime lasttime rate i let thread sleep bit something wrong implementation i presume i may gotten wrong idea locks work my code queue import queue threading import thread lock rlock import time numworkerthreads rate q queue lock lock lasttime timetime def doworki idx do work print dummy print thread item time formati idx timetime def workeri true lockacquire currenttime timetime interval currenttime lasttime lasttime currenttime interval rate timesleeprate interval lockrelease item qget doworki item qtaskdone rangenumworkerthreads threadtargetworker argsi tdaemon true tstart item xrange qputitem qjoin i expecting see one call per second dowork however i get mostly calls time thread followed one second pause what wrong ok edit the advice simply throttle rate items put queue good however i remembered i take care case items readded queue workers canonical example pagination backingoffretry network tasks i came following i guess actual network tasks eventletgevent libraries may easier resources example it basically uses priority queue pile requests uses extra thread shovel items pile actual task queue even rate i simulated reinsertion pile workers reinserted items treated first import sys import os import time import random queue import queue priorityqueue threading import thread rate def workerq qpile idx true item qget printthread processed formatitem idx randomrandom printthread reinserting item formatitem idx qpileput timetime item qtaskdone def scheduleqpile q true qpileempty printitems pile formatqpileqsize qputqpileget qpiletaskdone timesleeprate def main qpile priorityqueue q queue range threadtargetworker argsq qpile tdaemon true tstart tschedule threadtargetschedule argsqpile q tscheduledaemon true tschedulestart qpileput timetime range qpilejoin qjoin name main main,1 for notcamelcase using regex loop sounds like overkill strtitlereplace,basically reverse here attempt working def titlecasevalue resub azaz r upper value return,1 you need pass csvfile positional argument keyword argument csvdict csvdictreaderf dialect,i getting grips first python project got pretty stumped trying use python csvdictreader class consume csv file code follows import os import csv f open mycsvfiletxt rb csvsniffersnifffread csvdict csvdictreadercsvfile f dialect line csvdict print line balance date the csv file roughly looks like balance date currency code main accountbalance float day forty fields eur gbp jpy python liking use dictreader gworkcsvtestpython csvtestpy traceback recent call last file csvtestpy line module csvdict csvdictreadercsvfile f dialect typeerror init takes least arguments given could someone point right direction,2 according code supplied documentation would work better open mycsvfiletxt rb source dialect csvsniffersniffsourceread sourceseek csvdict csvdictreadersource dialect,i getting grips first python project got pretty stumped trying use python csvdictreader class consume csv file code follows import os import csv f open mycsvfiletxt rb csvsniffersnifffread csvdict csvdictreadercsvfile f dialect line csvdict print line balance date the csv file roughly looks like balance date currency code main accountbalance float day forty fields eur gbp jpy python liking use dictreader gworkcsvtestpython csvtestpy traceback recent call last file csvtestpy line module csvdict csvdictreadercsvfile f dialect typeerror init takes least arguments given could someone point right direction,1 vein import platform iswindowsplatformsystemlowerfindwin ifiswindows lvdlllvdllmysodlldll else lvdlllvdllmysodllso,what i need look see i windows unix etc,1 for python module import work must src path genpylib when processing import like import genpylib looks module genpy looks submodule lib as module genpy genpylib path added nothing help import process depending running try adding relative path src folder perhaps syspathappend you might also success running script inside src folder directly via relative paths like python mainmyserverpy,i python application following directory structure src main util genpy lib in package main i python module named myserverpy import statement like genpylib import myservice in order statement work i placed following line beginning myserverpy import sys syspathappend genpylib when i run myserverpy terminal i get following error importerror no module named genpylib what i missing,3 genpylib import myservice maingenpylib import myservice make sure least empty initpy file directory,i python application following directory structure src main util genpy lib in package main i python module named myserverpy import statement like genpylib import myservice in order statement work i placed following line beginning myserverpy import sys syspathappend genpylib when i run myserverpy terminal i get following error importerror no module named genpylib what i missing,2 your modification syspath assumes current working directory always main this case instead add parent directory syspath import sys import ospath syspathappendospathjoinospathdirnamefile import genpylib don forget include file initpy genpy lib otherwise recognized python modules,i python application following directory structure src main util genpy lib in package main i python module named myserverpy import statement like genpylib import myservice in order statement work i placed following line beginning myserverpy import sys syspathappend genpylib when i run myserverpy terminal i get following error importerror no module named genpylib what i missing,3 your code fixed follows import numpy np cv vis npzeros npfloat hw visshape vis cvcreatemath w cvcvfc vis cvfromarrayvis cvcvtcolorvis vis cvcvgraybgr short explanation npuint data type supported opencv supports uint int uint int int float float cvcvtcolor handle numpy arrays arguments converted opencv type cvfromarray conversion both arguments cvcvtcolor must depth so i changed source type bit float match ddestination also i recommend use newer version opencv python api uses numpy arrays primary data type import numpy np cv vis npzeros npfloat vis cvcvtcolorvis cvcolorgraybgr,i trying convert d numpy array representing blackandwhite image channel opencv array ie rgb image based code samples docs i attempting via python like import numpy np cv vis npzeros npuint hw visshape vis cvcreatemath w cvcvfc cvcvtcolorvis vis cvcvgraybgr however call cvtcolor throwing following cpplevel exception opencv error image step wrong cvsetdata file buildbuilddopencvsrccxcorecxarraycpp line terminate called throwing instance cvexception buildbuilddopencvsrccxcorecxarraycpp error function cvsetdata aborted what i wrong,3 thank eric wilson if i type function call processstringmystring hit ctrl code completiontemplate window appears offering option create new class method assign field assign variable this exactly i looking,i noticed particular feature visual studio i wondering feature also available eclipse pydev in visual studio one type function call particular function already exist vs would show code error give option generate new empty function matching signature provided function call in words i working particular python function class i realize i need new function process string in current function i type processstringmystring returns error processstring function currently exist is way click processstring function call create new block module def processstringmystring pass thanks advance help,1 you might also use chunked response first push chunk code would display “please wait” screen flush response start work then either push flush chunks periodical progress updates push one end “completed” information obviously employ javascript get nice ui the apply using wsgi first wsgi specification written way blocks using responses unknown length using chunked responses impossible,lets say operation could take minutes server perform example update index time consuming would perform operation holding request ie sending http response operation finished and clientbrowser drops request continue operation anyway what alternative to kickoff operation response longtime operation kicked what operation fails midway would client know maintain serverside status operation thanks,2 for requests know take long time seconds process must assume minimum connection may forcibly severed firewall i would say implement queue system backend the request perform operation becomes request queue operation when operation actually completed either wait client poll proactively notify somehow for browser pretty much either poll send email,lets say operation could take minutes server perform example update index time consuming would perform operation holding request ie sending http response operation finished and clientbrowser drops request continue operation anyway what alternative to kickoff operation response longtime operation kicked what operation fails midway would client know maintain serverside status operation thanks,1 if looking rapid normalized cross correlation either one two dimensions i would recommend opencv library see httpopencvwillowgaragecomwiki httpopencvorg the crosscorrelation code maintained group fastest find normalized results while c library code maintained cmake python bindings access cross correlation functions convenient opencv also plays nicely numpy if i wanted compute d crosscorrelation starting numpy arrays i could follows import numpy import cv create random template place larger image templatenp numpyrandomrandom image numpyrandomrandom image templatenp create numpy array storing result resultnp numpyzeros convert numpy format opencv format templatecv cvfromarraynumpyfloattemplate imagecv cvfromarraynumpyfloatimage resultcv cvfromarraynumpyfloatresultnp perform cross correlation cvmatchtemplatetemplatecv imagecv resultcv cvcvtmccorrnormed convert result back numpy array resultnp npasarrayresultcv for d crosscorrelation create d array shape equal n though extra code involved convert opencv format speedup scipy quite impressive,in r i using ccf acf compute pairwise crosscorrelation function i find shift gives maximum value from looks r gives normalized sequence values is something similar python scipy i supposed using fft module currently i follows xcorr lambda xy irfftrfftxrffty x numpyarray numpyarray print xcorrxy,3 i enough stackoverflow rep leave comment question unfortunately i know answer question worth need call webdriverfirefox firefoxprofile browserprofile done see also httpcodegooglecompseleniumsourcebrowsetrunkpyseleniumwebdriverfirefoxwebdriverpy,i want load firefox addon requestpolicy this tried rp openwd requestpolicyxpi firefoxprofile firefoxprofile firefoxprofileaddextensionrp selfdriver webdriverfirefoxfirefoxprofile selfusr useruserselfdriver username password world selfusrlogin no error according docs work still starts without addon next thing tried calling way selfdriver webdriverfirefoxbrowserprofilefirefoxprofile output typeerror init got unexpected keyword argument browserprofile but aspect python dont know much i got idea source looks way,2 i say yes require parse tree source else would know constitutes line valid statement a practical simplification though might statement profiler instead line profiler in r parse tree readily available bodythefunction fairly easy insert measuring code around statement with work insert around group statements belong line in r body function loaded file typically also attribute srcref lists source line actually statement here sample function put exampler f functionx two statements one line x one statement two lines foo bar one string two lines then r sourceexampler dputattrbodythefunction srcref which prints linecolumn information liststructurecl l l l l l l l srcfile environment class srcref structurecl l l l l l l l srcfile environment class srcref structurecl l l l l l l l srcfile environment class srcref structurecl l l l l l l l srcfile environment class srcref structurecl l l l l l l l srcfile environment class srcref as see last two numbers structure beginend line expressions map line good luck,i trying determine necessary write line profiler language like available python matlab a naive way interpret line profiler assume one insert time logging around every line definition line dependent parser handles whitespace first problem it seems one needs use parse tree insert timings around individual nodes is conclusion correct does line profiler require parse tree needed beyond time logging update offering bounty question still unresolved update here link well known python line profiler case helpful answering question i yet able make heads tails behavior relative parsing i afraid code matlab profiler accessible also note one could say manually decorating input code would eliminate need parse tree automatic profiler update although question language agnostic arose i thinking creating tool r unless exists i found update regarding use line profiler versus call stack profiler post relating using call stack profiler rprof case exemplifies painful work call stack rather directly analyze things via line profiler,2 after fseek insert nextf advance file pointer second line initializing dictreader,i want csvdictreader deduce field names file the docs say if fieldnames parameter omitted values first row csvfile used fieldnames case first row containts title nd row contains names i apply nextreader per python skip line csvdictreader fieldname assignment takes place initializing reader i wrong the csvfile exported excel original source canvec vm entityattributes combinationspecification code pointspecification code linespecification code areageneric codethemegml entity name shape file name pointgml entity name shape file name linegml entity name shape file name aream amusement parkamusement parklxlxm auto wreckerauto wreckericicm my code f openentitiestable rb try dialect csvsniffersnifffread fseek reader csvdictreaderf dialectdialect print i think field names arensn readerfieldnames row reader print row finally fclose current results i think field names canvec v desired result i think field names entity attributes combination specification code point snip i realize would expedient simply delete first row carry i trying get close reading data situ i minimize manual intervention,3 print datetimeutcnowstrftime ymdhmsf httpdocspythonorglibrarydatetimehtmlstrftimestrptimebehavior,i want datetime string date milliseconds this code typical i eager learn shorten datetime import datetime timeformatted strdatetimeutcnow semiformatted timeformattedreplace almostformatted semiformattedreplace formattedalmostformattedreplace withspacegoawayformattedreplace formattedstrippedwithspacegoawaystrip print formattedstripped,3 you wrap writerow method call try catch exception ignore tag soupfindall hreftrue try outwriterowtag href except unicodeencodeerror pass almost certainly want pick encoding ascii csv file utf unless good reason use something else open codecsopen instead builtin open,when i run loop bunch urls find links certain divs pages i get back error traceback recent call last file filelocation line module outwriterowtag href unicodeencodeerror ascii codec encode character u u position ordinal range the code i written related error csvwriteropenfilelocation ab delimiter tag soupfindall hreftrue outwriterowtag href is way solve possibly using statement ignore urls unicode errors thanks advance help,2 the question seems little bit old but let suggest function parsestr makes something similar returns integer float given ascii string cannot converted none returns untouched the code course might adjusted want import string parsestr lambda x xisalpha x xisdigit intx xisalnum x lensetstringpunctuationintersectionx xcount floatx x parsestr parsestr parsestr hc hc parsestr e parsestr parsestr,in python i parse numeric string like corresponding float value or parse string integer i want know parse float string float separately int string int,3 sounds like overcomplicating things consider common method show form invoked different circumstances class formhandlerwebapprequesthandler def getself selfshowform def postself formisvalid handlesuccess else selfshowform feedback validation failed def showformself vals vals field selfrequestget field vals field selfrequestget field html templaterender formhtml vals selfresponseoutwritehtml if really need display form process form different handler classes accomplish thing defining showform common parent class,goal using app engine basic webapp framework i want create new request post data send another requesthandler something like pagegeneratorpost message message datum datum problem description one request handler call pagegenerator creates page form when user submits form post goes different handler dataprocessor if dataprocessor finds problem submitted data would send submitted data plus error message pagegenerator post method pagegenerator would serve page error message how i pass data control back forth like i would like pagegenerator able get data selfrequestget message,2 i believe find answer httpdocspythonorglibraryrehtmlresub you provide tolower function takes match object sub method return replacement string,i use following respect letters language text regexsubpalphad text can i use palpha convert letters lower case equivalent equivalency exists how would regex look,1 from python docs wiki link i think sorteda keylambda aentry aentry print output,how i sort array numpy nth column eg array i like sort second column i get back array thanks,3 resub aeiou lambda mgrouplower some text here some text here,i use following respect letters language text regexsubpalphad text can i use palpha convert letters lower case equivalent equivalency exists how would regex look,3 use csv package iterate csv file output columns want another csv file the example tested illustrate solution import csv filename ctempmyfilecsv outputfile ctempnewfilecsv csvfile openfilename r note index year column excluded columnindices openoutputfile w fh reader csvreadercsvfile delimiter row reader tmprow colinx columnindices tmprowappendrowcolinx fhwrite jointmprow,i able create csv python using input several users site i wish express gratitude posts i stumped post first question my inputcsv looks like daymonthyearlatlong i trying delete year column entries in total entries range years,1 if call leastsq like import scipyoptimize pcovinfodictmesgier optimizeleastsq residualsaguessargsxyfulloutputtrue def residualsaxy return yfxa using definition r given sserrinfodict fvec sum sstotyymeansum rsquaredsserrsstot what infodict fvec ask it array residuals in optimizeleastsq infodict dictionary optional outputs keys fvec function evaluated output for example import scipyoptimize optimize import numpy np import collections import matplotlibpyplot plt x nparray nparray def sigmoidpx xyckp c npexpkxx return def residualspxy return sigmoidpx paramcollectionsnamedtuple param x c k pguessparamxyck pcovinfodictmesgier optimizeleastsq residualspguessargsxyfulloutputtrue pparamp xp nplinspace print x px py c pc k pk formatpp pxpsigmoidpxp you could compute residuals way residresidualspxy printresid but compute resid infodict fvec already contains info printinfodict fvec sserrinfodict fvec sum sstotyymeansum rsquaredsserrsstot printrsquared pltplotx xp pxp pltxlim pltylim pltxlabel x pltylabel rotation horizontal pltgridtrue pltshow,i data surface i fitting using scipy leastsq function i would like estimate quality fit leastsq returns i expected would included return function seem clearly documented is return barring function i pass data returned parameter values fit function give estimate fit quality r thanks,3 off top head without sort error checking ability configure anything that left reader outfile open newfile w line open oldfile items linesplit outfilewrite join items items outfileclose,i able create csv python using input several users site i wish express gratitude posts i stumped post first question my inputcsv looks like daymonthyearlatlong i trying delete year column entries in total entries range years,1 as oxtopus suggested simply convert letters lowercase version textlower need regular expression this works unicode strings 〠ã etc,i use following respect letters language text regexsubpalphad text can i use palpha convert letters lower case equivalent equivalency exists how would regex look,2 the de facto standard way manipulating arrays way use dedicated numpy package things work way want numpy import numpy numpyarray array in fact purpose numpy provide powerful array manipulations,example by something like i expect give st elements row however i get i always make function def columnarrayindex result row array resultappendrowindex return result but i wondering smarter way,1 a bit list comprehension job col c c no idea speed implications,example by something like i expect give st elements row however i get i always make function def columnarrayindex result row array resultappendrowindex return result but i wondering smarter way,1 you also use one line loop already result item item,example by something like i expect give st elements row however i get i always make function def columnarrayindex result row array resultappendrowindex return result but i wondering smarter way,1 socketsetblockingfalse switches socket nonblocking mode platform call socket creation remove msgdontwait flags if need switch blocking nonblocking io usually case call socketsetblocking every time want switch two,i python app uses udp sendtorecvfrom socketmsgdontwait flag in linux mac os x works fine however flag exist windows environment what equivalent flag windows alternatively i nonblocking sendtorecvfrom windows,1 work gives copy gets first value copy instead use list comprehension col row row,example by something like i expect give st elements row however i get i always make function def columnarrayindex result row array resultappendrowindex return result but i wondering smarter way,2 use zip zipa zipa but note zip builds tuples may require convert back lists depending application,example by something like i expect give st elements row however i get i always make function def columnarrayindex result row array resultappendrowindex return result but i wondering smarter way,1 i assume mean looking something faster datetimedatetimestrftime essentially stripping nonalpha characters utc timestamp you approach marginally faster i think speed things even slicing string import timeit ttimeittimer datetimeutcnowstrftimeymdhmsf datetime import datetime ttimeitnumber def replaceutcs return replace replace replace replace strip ttimeittimer replaceutcstrdatetimedatetimeutcnow main import replaceutc import datetime ttimeitnumber def sliceutcs return ttimeittimer sliceutcstrdatetimeutcnow main import sliceutc datetime import datetime ttimeitnumber,i want datetime string date milliseconds this code typical i eager learn shorten datetime import datetime timeformatted strdatetimeutcnow semiformatted timeformattedreplace almostformatted semiformattedreplace formattedalmostformattedreplace withspacegoawayformattedreplace formattedstrippedwithspacegoawaystrip print formattedstripped,1 the range normilization really feature colormap often implemented feature functions plot using colormaps for example imshow uses vmin vmax might try using keywords drawcircular i find documentation maybe norm other make colormap exact color arrangement want there plenty examples make custom colormaps different approaches available here b c examples might useful,i using matplotlib plot simple graph cmpltgetcmap blues nxdrawcircularg nodecolor white edgecolorrangegnumberofedges edgecmapcm nodesize width i want set range colormap blues way delete white color visible draw please help sorry bad english,1 if want create class b calling function predefined class a simply b wrapclassa function wrapclass looks like import copy def wrapclasscls wraps class exceptions methods caught the copy necessary mutable class attributes shared old class cls new class newcls copydeepcopycls vars used instead dir attributes base classes modified one might want use dir instead attrname value varsclsitems isinstancevalue typesfunctiontype setattrnewcls attrname funcwrappervalue return newcls b wrapclassa as jã¼rgen pointed creates copy class needed however really want keep original class a around like suggested original question if care a simply decorate wrapper perform copy like def wrapclasscls wraps class exceptions methods caught vars used instead dir attributes base classes modified one might want use dir instead attrname value varsclsitems isinstancevalue typesfunctiontype setattrcls attrname funcwrappervalue return cls wrapclass class aobject … original a class methods wrapped exception catching the decorated class a catches exceptions the metaclass version heavier principle similar import types def funcwrapperf returns version function f prints error message exception raised def wrappedfargs kwargs try return fargs kwargs except exception ex print function f raised ex return wrappedf class exceptioncatchertype metaclass wraps methods funcwrapper def newmeta cname bases cdict cdict contains attributes class cname attrname value cdictitems isinstancevalue typesfunctiontype various attribute types wrapped differently cdictattrname funcwrappervalue return supermeta exceptioncatchernewmeta cname bases cdict class bobject metaclass exceptioncatcher exceptioncatcher used creating class a classattr will wrapped def initself pass def fself return def fself b raises division zero exception test b b print bf print bclassattr print bf this prints function function f xd raised integer division modulo zero none what want fact typically done metaclass class whose instances class way building b class dynamically based parsed python code code class a question more information found nice short description metaclasses given chris wiki part parts,object type a is way programatically wrap class object given class aobject def initself def fself def fself b i want another class wraps a class bobject def initself selfa a def fselfa try afa except exceptionex def fself b try afab except exceptionex is way create bf amp bf reflectioninspection class a,2 at least suds maybe earlier http headers also passed constructor via setoptions method client sudsclientclienturl headers key value clientsetoptionsheaders key value,i application python sends data suds the problem data contains nonascii characters i need following header exist soap message contenttypetexthtml charsetutf header exists soap message contenttypetexthtml i know fixed suds requires python i need python i use centos needs version so question how could i change add new http headers soap message,3 i recommend pygame library it crossplatform library well suited general computer graphics game development check examples pygame action the library pretty simple yet powerful you draw window fullscreen well,i wanting something like following pixel draw r pixel xy pixel draw g pixel xy pixel draw b pixel xy i hope display many different configurations pixels colours short space time writing intermediary file would expensive how i best go achieving goal python,1 meta classes option generally hard understand as much reflection needed simple cases easy catch many internal functions if wrapped functions stable known set b might gain functions delegate explicitly function function still keep error handling code one place class bobject def initself a selff errorhandleraf selff errorhandleraf you might assignments loop many using getattrsetattr the errorhandler function need return function wraps argument error handling code def errorhandlerf def wrappedargs kw try return fargs kw except log something return wrapped you also use errorhandler decorator new functions delegating a instance def ba errorhandler def fnewself this solution keeps b simple quite explicit going,object type a is way programatically wrap class object given class aobject def initself def fself def fself b i want another class wraps a class bobject def initself selfa a def fselfa try afa except exceptionex def fself b try afab except exceptionex is way create bf amp bf reflectioninspection class a,1 need tell python using external variable use gps function the code look like def gpsinfo global gps new line true sessionpoll timesleep gpspacketset sessionstream print sessionfixlatitude sessionfixlongitude timesleep def wifidetectp global p observedclients new line phaslayerdot ptype psubtype stamgmtstypes paddr observedclients print paddr observedclientsappendpaddr,i currently python piece code runs two loops simultaneously the code uses gps gpsd module scapy module basically first function gpsinfo contains continual loop grabbing gps data gps device writing location console the second function clientdetect runs continual loop also sniffs air wifi data prints data specific packets found i threaded two loops gps one running background thread what i looking struggling days work clientdetect function finds match prints respective info i want respective gps coordinates hit made also printed console at present code seem work observedclients p relate wifi packet session gpsgpsmodegpswatchnewstyle def gpsinfo true sessionpoll timesleep gpspacketset sessionstream print sessionfixlatitude sessionfixlongitude timesleep def wifidetectp phaslayerdot ptype psubtype stamgmtstypes paddr observedclients print paddr observedclientsappendpaddr def activatewifidetect sniffifacemon prnwifidetect name main threadingthreadtargetgpsinfo tstart wifidetect can anybody look code see best grab data simultaneously wifi hit gps coordinates printed somebody mentioned implementing queuing i researched avail regards implement as said aim code scan gps specific wifi packets detected print details relating packet location detected,1 i think specific goal if want get gps coords wifi network sniffed psuedocode true networksniffed asyncgetgpscoords if want log gps coords want match wifi network data print data along timestamps postprocessing match wifi networks gps coords via timestamp,i currently python piece code runs two loops simultaneously the code uses gps gpsd module scapy module basically first function gpsinfo contains continual loop grabbing gps data gps device writing location console the second function clientdetect runs continual loop also sniffs air wifi data prints data specific packets found i threaded two loops gps one running background thread what i looking struggling days work clientdetect function finds match prints respective info i want respective gps coordinates hit made also printed console at present code seem work observedclients p relate wifi packet session gpsgpsmodegpswatchnewstyle def gpsinfo true sessionpoll timesleep gpspacketset sessionstream print sessionfixlatitude sessionfixlongitude timesleep def wifidetectp phaslayerdot ptype psubtype stamgmtstypes paddr observedclients print paddr observedclientsappendpaddr def activatewifidetect sniffifacemon prnwifidetect name main threadingthreadtargetgpsinfo tstart wifidetect can anybody look code see best grab data simultaneously wifi hit gps coordinates printed somebody mentioned implementing queuing i researched avail regards implement as said aim code scan gps specific wifi packets detected print details relating packet location detected,1 import csv opensourcerb source rdr csvreader source openresultwb result wtr csvwriter result r rdr wtrwriterow r r r r btw loop removed really simplified initer r r r r r rdr wtrwriterows initer also stick hyperliteral way requirements delete column i find bad policy general apply removing column when try remove second discover positions shifted resulting row obvious but one column works del r wtrwriterow r,i able create csv python using input several users site i wish express gratitude posts i stumped post first question my inputcsv looks like daymonthyearlatlong i trying delete year column entries in total entries range years,3 a simple way getting store gps location global variable wifi sniffing thread read global needs print data the gotcha since two threads accessing global variable time want wrap mutex lastlocation none none locationmutex threadinglock def gpsinfo global lastlocation true sessionpoll timesleep gpspacketset sessionstream locationmutex don t print inside thread lastlocation sessionfixlatitude sessionfixlongitude timesleep def wifidetectp phaslayerdot ptype psubtype stamgmtstypes paddr observedclients locationmutex print paddr lastlocation observedclientsappendpaddr lastlocation,i currently python piece code runs two loops simultaneously the code uses gps gpsd module scapy module basically first function gpsinfo contains continual loop grabbing gps data gps device writing location console the second function clientdetect runs continual loop also sniffs air wifi data prints data specific packets found i threaded two loops gps one running background thread what i looking struggling days work clientdetect function finds match prints respective info i want respective gps coordinates hit made also printed console at present code seem work observedclients p relate wifi packet session gpsgpsmodegpswatchnewstyle def gpsinfo true sessionpoll timesleep gpspacketset sessionstream print sessionfixlatitude sessionfixlongitude timesleep def wifidetectp phaslayerdot ptype psubtype stamgmtstypes paddr observedclients print paddr observedclientsappendpaddr def activatewifidetect sniffifacemon prnwifidetect name main threadingthreadtargetgpsinfo tstart wifidetect can anybody look code see best grab data simultaneously wifi hit gps coordinates printed somebody mentioned implementing queuing i researched avail regards implement as said aim code scan gps specific wifi packets detected print details relating packet location detected,1 first sqlite going fancy features larger dbms if want write select statement fragment question need pivot table sqlite the original format confusing i would create single table columns person question answer year parse person question number go if work use original format single table from computing final table something could easily python instead sql,i series text files one per year contain answers annual surveyquestionnaire column headings files refer question numbers row represents one person answers questions eg q q q pa pa pa pa pa pa etc q question p person a answer the questionnaire uses core set questions year year new questions also added old ones removed my tables therefore lots fields common eg year year year etc q q q q q q q q q pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa in example q q core questions qs amp depend survey year removed question numbers never reused new question added given completely new number the real surveys questions approximately people respond year i want combine data single table column headings would set distinct headings original files plus column year for years question relevant i like nulls eg year q q q q q pa pa pa null null pa pa pa null null pa pa null pa null pa pa null pa null pa pa null null pa pa pa null null pa essentially i want append columns match otherwise nulls possible i like generate set column headings final table automatically input tables number questions survey large prospect workingout typing create table statement horrific i suppose i kind variation union all require specify columns order handle nonmatching columns does anyone tips suggestions please i originally hoping use sqlite i willing try prettymuch anything i databasing expert i basic understanding sql bit python scripting help if made far thanks reading i thought would simple problem surprisingly difficult describe detail,1 step stop coding step buy book data warehousing starschema design ralph kimball data warehouse toolkit example httpwwwamazoncomdatawarehousetoolkitcompletedimensionaldp step design proper star schema question dimension time specifically year dimension respondent know dimension response individual survey instrument dimension facts answers questions given year each survey becomes multiple rows facts step load star schema various years data the dimensions questions little complex load year reuses questions adds new ones once dimensions loaded fact rows pretty easy load step now write quick reporting application extract requisite data various fact rows assemble desired report,i series text files one per year contain answers annual surveyquestionnaire column headings files refer question numbers row represents one person answers questions eg q q q pa pa pa pa pa pa etc q question p person a answer the questionnaire uses core set questions year year new questions also added old ones removed my tables therefore lots fields common eg year year year etc q q q q q q q q q pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa in example q q core questions qs amp depend survey year removed question numbers never reused new question added given completely new number the real surveys questions approximately people respond year i want combine data single table column headings would set distinct headings original files plus column year for years question relevant i like nulls eg year q q q q q pa pa pa null null pa pa pa null null pa pa null pa null pa pa null pa null pa pa null null pa pa pa null null pa essentially i want append columns match otherwise nulls possible i like generate set column headings final table automatically input tables number questions survey large prospect workingout typing create table statement horrific i suppose i kind variation union all require specify columns order handle nonmatching columns does anyone tips suggestions please i originally hoping use sqlite i willing try prettymuch anything i databasing expert i basic understanding sql bit python scripting help if made far thanks reading i thought would simple problem surprisingly difficult describe detail,1 datetime import datetime time import clock datetimeutcnow print snn ttypet n te clock xrange tstripped tstrftime ymdhmsf print clockte print tstripped tstrftime ymdhmsf print te clock xrange tstripped strtreplace replace replace replace print clockte print tstripped strtreplace replace replace replace print te clock xrangen tstripped strttranslatenone print clockte print tstripped strttranslatenone print te clock xrangen strt tstripped print clockte print tstripped result type datetimedatetime tstrftime ymdhmsf strtreplace replace replace replace strttranslatenone use translate slicing method run time translate presents advantage usable one line comparing times basis first one tstrftime ymdhmsf strtreplace replace replace replace strttranslatenone,i want datetime string date milliseconds this code typical i eager learn shorten datetime import datetime timeformatted strdatetimeutcnow semiformatted timeformattedreplace almostformatted semiformattedreplace formattedalmostformattedreplace withspacegoawayformattedreplace formattedstrippedwithspacegoawaystrip print formattedstripped,1 rough sudo code sketch using basic python stuff master list entries read first line file getting questions create set add set questions years create dictionary keys question additionally add key person name year load new dictionary person append list file st list dictionaries make formatting function asks elementinlisthaskey question set questions great print none set questions casted list preserve order final output yearnamebobqhello yearnamerobqworld,i series text files one per year contain answers annual surveyquestionnaire column headings files refer question numbers row represents one person answers questions eg q q q pa pa pa pa pa pa etc q question p person a answer the questionnaire uses core set questions year year new questions also added old ones removed my tables therefore lots fields common eg year year year etc q q q q q q q q q pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa pa in example q q core questions qs amp depend survey year removed question numbers never reused new question added given completely new number the real surveys questions approximately people respond year i want combine data single table column headings would set distinct headings original files plus column year for years question relevant i like nulls eg year q q q q q pa pa pa null null pa pa pa null null pa pa null pa null pa pa null pa null pa pa null null pa pa pa null null pa essentially i want append columns match otherwise nulls possible i like generate set column headings final table automatically input tables number questions survey large prospect workingout typing create table statement horrific i suppose i kind variation union all require specify columns order handle nonmatching columns does anyone tips suggestions please i originally hoping use sqlite i willing try prettymuch anything i databasing expert i basic understanding sql bit python scripting help if made far thanks reading i thought would simple problem surprisingly difficult describe detail,1 i going use psychic debugging skills say trying str ify something getting error ascii codec what really use utf codec instead like insertvalueuni unicoderowgetvaluecurrentfield name insertvalue insertvalueuniencode utf,i python file creates populates table ms sql the sticking point code breaks nonascii characters single apostrophes quite although i run replace function rid strings apostrophes i would prefer keep intact i also tried converting data utf luck either below th error messages i get ascii codec encode character u position nonascii characters single quotes class pyodbcprogrammingerror microsoftodbc sql server driversql server incorrect syntax near s x m eligibilty when i try encode string utf i instead get following error message type exceptionsunicodedecodeerror ascii codec decode byte xe position ordinal range the python code included i believe point code break occurs following line insertvalue strrowgetvaluecurrentfield name coding utf import pyodbc import sys import arcpy import arcgisscripting gp arcgisscriptingcreate sqlkeywords percent select insert drop table sourcefgdb sourcetable sourcetable sysargv tempinputname sysargv sourcetable sysargv target database settings targetdatabasedriver sql server targetdatabaseserver targetdatabasename targetdatabaseuser targetdatabasepassword get schema fgdb table this ordered list dictionary elements fgdbname fgdbalias fgdbtype fgdbwidth fgdbprecision fgdbscale gpexistssourcetable print the source exist sysexit should see actually table type could feature data set something print processing items from sourcetable fieldlist fieldlist gplistfieldssourcetable print getting number rows result gpgetcountmanagementsourcetable numberoffeatures gpgetcountmanagementsourcetable print number rows strnumberoffeatures print getting fields fieldlist gplistfieldssourcetable layer fieldlist gplistfieldssourcetable comments fieldlist gplistfieldssourcetable category fieldlist gplistfieldssourcetable state fieldlist gplistfieldssourcetable label fieldlist gplistfieldssourcetable dateupdate fieldlist gplistfieldssourcetable objectid currentfield fieldlist fieldlist fieldlist fieldlist fieldlist fieldlist fieldlist print field found currentfieldname currentfieldaliasname sqlkeywords targetname currentfieldname else targetname currentfieldname print alias currentfieldaliasname print type currentfieldtype print length strcurrentfieldlength print scale strcurrentfieldscale print precision strcurrentfieldprecision fieldlistappend name currentfieldname aliasname currentfieldaliasname type currentfieldtype length currentfieldlength scale currentfieldscale precision currentfieldprecision unique unique targetname targetname create table sql server based fgdb table schema cnxn pyodbcconnectr driversql serverserverdatabaseuidsqlwebenvaspwd cursor cnxn cursor drop table first try droptablesql drop table dbo tempinputname test print droptablesql cursorexecutedroptablesql dbconnectioncommit except print warning can drop table may exist tempinputname test createtablesql create table tempinputname test layer varchar comments varchar state int label varchar dateupdate datetime category varchar objectid int cursorexecutecreatetablesql cnxncommit cursor row fgdb table get values insert sql server table we got numberoffeatures earlier use numberprocessed print processing strnumberoffeatures features rows gpsearchcursorsourcetable row rowsnext row numberprocessed print processed strnumberprocessed strnumberoffeatures insertsqlfields insert into tempinputname test insertsqlvalues values currentfield fieldlist insertsqlfields insertsqlfields currentfield targetname insertvalue strrowgetvaluecurrentfield name insertvalue none insertvalue null use escape quote sql insertvalue insertvaluereplace currentfield type upper string char text insertvalue null insertsqlvalues insertsqlvalues null else insertsqlvalues insertsqlvalues insertvalue elif currentfield type upper geometry we handling geometry transfers time insertvalue null insertsqlvalues insertsqlvalues else insertsqlvalues insertsqlvalues else insertsqlvalues insertsqlvalues insertvalue insertsqlfields insertsqlfields insertsqlvalues insertsqlvalues insertsql insertsqlfields insertsqlvalues print insertsql cursorexecuteinsertsql cnxncommit numberprocessed numberprocessed row rowsnext print processed strnumberprocessed del row del rows,1 inheritance fluid concept python for starters always use new style classes to make sure classes always inherit object it important note classes must inherit classes instances classes example really work in fact i really see difference inheriting x x inheritance python closely tied method resolution order mro you view objects mro using inspect module import inspect import pprint class xobject pass class yx pass pprintpprintinspectgetmroy class mainy class mainx type object the tuple end shows order python try resolve method attribute calls you modify mro runtime modifying class bases attribute ybases class mainx class zobject pass ybases tuplez pprintpprintinspectgetmroy class mainy class mainz type object this get complicated classes use multiple inheritance want preserve certain parts inheritance tree others,is possible change class c object python subclass i using pygtk i listmodel i wrapped class around i want turn treemodelfilter the directions tell create class myliststoregtkliststore def initself title selftitle title liststore myliststoregobjecttypeint gobjecttypestring modelfilter liststorefilternew so i thought i could create class myfilteredliststoregtktreemodelfilter def initself title selftitle title but i know use filternew use class instead gtktreemodelfilter,1 you two problems something server user mangling header user sending turning httpconnection httpconnectãon this kind thing usually done ancient braindead kinds web proxy sometimes used misguided mobile internet providers in case even screwing httpcookie sure make app nonfunctional anyway even fix problem it bug django gets exception trying read header name nonasciinonutf byte sequence inside http explicitly defines header names represented iso django using encoding convert header names unicode utf all byte sequences valid iso never unicodedecodeerror in practice headers ever use nonascii names browser handling nonascii header values bumpy inconsistent ride but still django allow ignore bogus headers,i django web application running apache modwsgi dedicated server centos however sometimes six seven times day starts give error random pages but i refresh page two three times page turns normal but starts give error every page web site gives error after i restarted apache turns normal hours never ends give error i paste full error log indeed says djangounicodedecodeerror utf codec decode byte xdd position invalid continuation byte what may cause kind error i detect i may provide additional information asap ps i setup local pcapachemodwsgi win i never got error wed sep error client modwsgi pid exception occurred processing wsgi script varwwwhtmlmysitedjangowsgi referer httpwwwmysitecom wed sep error client traceback recent call last referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangocorehandlerswsgipy line call referer httpwwwmysitecom wed sep error client response selfgetresponserequest referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangocorehandlersbasepy line getresponse referer httpwwwmysitecom wed sep error client response selfhandleuncaughtexceptionrequest resolver sysexcinfo referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangocorehandlersbasepy line handleuncaughtexception referer httpwwwmysitecom wed sep error client return debugtechnicalresponserequest excinfo referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangoviewsdebugpy line technicalresponse referer httpwwwmysitecom wed sep error client html reportergettracebackhtml referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangoviewsdebugpy line gettracebackhtml referer httpwwwmysitecom wed sep error client frame vars k forceescapepprintv k v frame vars referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangotemplatedefaultfilterspy line dec referer httpwwwmysitecom wed sep error client args forceunicodeargs referer httpwwwmysitecom wed sep error client file optpythonlibpythonsitepackagesdjangoutilsencodingpy line forceunicode referer httpwwwmysitecom wed sep error client raise djangounicodedecodeerrors eargs referer httpwwwmysitecom wed sep error client djangounicodedecodeerror utf codec decode byte xdd position invalid continuation byte you passed wsgirequestngetquerydict npostquerydict ncookiesnmeta csrfcookie edacbdadfcb n documentroot varwwwhtmlmysite n gatewayinterface cgi n httpaccept applicationxmlapplicationxhtmlxmltexthtmlqtextplainqimagepngq n httpacceptencodxddng gzip deflate n httpacceptlanguage enus n httpcachecontrol maxage n httpconnectxddon keepalive n httpcookxdde csrftokenbcdefbcedafafb sessionidfbffeeffb n httphost wwwmysitecom n httpreferer httpwwwmysitecom n httpuseragent mozilla ipad u cpu os like mac os x enus applewebkit khtml like gecko version mobileb safari n pathinfo u mainfaq n pathtranslated varwwwhtmlmysitedjangowsgimainfaq n querystring n remoteaddr n remoteport n requestmethod get n requesturi mainfaq n scriptfilename varwwwhtmlmysitedjangowsgi n scriptname u n serveraddr n serveradmin bilgimysitecom n servername wwwmysitecom n serverport n serverprotocol http n serversignature addressapache centos server wwwmysitecom port addressn n serversoftware apache centos n modwsgiapplicationgroup mysitecom n modwsgicallableobject application n modwsgihandlerscript n modwsgiinputchunked n modwsgilistenerhost n modwsgilistenerport n modwsgiprocessgroup n modwsgirequesthandler wsgiscript n modwsgiscriptreloading n modwsgiversion n wsgierrors modwsgilog object xbdddbfbn wsgifilewrapper builtin method filewrapper modwsgiadapter object xbdfan wsgiinput modwsgiinput object xbdfaan wsgimultiprocess truen wsgimultithread falsen wsgirunonce falsen wsgiurlscheme http n wsgiversion type str referer httpwwwmysitecom the web site works seamlessly apache django builtin developer server local computerwinapachemodwsgi,1 no thing exists that default defaultifnone filters exist this feature makes think instead relying behavior would often times misleading if potential variable none plan contingency if variable always value none indicates something right if default render blank string would know whether value defined actually blank string write coherent code forget shortcuts,i looking django setting programmatic way make django template tags show empty string value none for example imagine i django template cat chases mouse cat mouse none render none chases none i aware i set one using catdefault mousedefaultifnone however i looking sort setting would allow set default tags without explicitly adding default every tag i also aware setting called templatestringifinvalid however setting applies invalid strings none considered valid,3 explicit better implicit think enraged would things render properly forgot enabled magic render everything false value null string setting if find using defaultifnone filter lot might want consider changing casting none before passed template your template simpler explicitly made decision stringify null values,i looking django setting programmatic way make django template tags show empty string value none for example imagine i django template cat chases mouse cat mouse none render none chases none i aware i set one using catdefault mousedefaultifnone however i looking sort setting would allow set default tags without explicitly adding default every tag i also aware setting called templatestringifinvalid however setting applies invalid strings none considered valid,2 backslash escape whitespace so import subprocesscall callsvn rename rtest png r test png the r syntax means python treat literally escapes it passes svn treated escapes,i trying batch rename files svn i issue files space i try run i get error svn cannot copy path png child png code import subprocesscall callsvn rename test png test png looks like splitting whitespace ideas,1 this work callsvn rename test png test png basically surrounding paths quotes easily say something like file,i trying batch rename files svn i issue files space i try run i get error svn cannot copy path png child png code import subprocesscall callsvn rename test png test png looks like splitting whitespace ideas,1 since decorating method self method argument decorator access self runtime obviously parsetime objects yet class so change decorator def decoratorfunc def decoratorself args kwargs access testsample print self self funcself args kwargs return decorator,in setup method unittest i setup self variables later referenced actual tests i also created decorator logging is way i access self variables decorator for sake simplicity i posting code def decoratorfunc def decoratorargs kwargs access testsample funcargs kwargs return decorator class testsampleunittesttestcase def setupself selfa def teardownself tear code decorator def testaself testing code goes what would best way accessing set setup decorator,3 httppypipythonorgpypiselenium you install selenium package run server machine different process connect python code java jar seleniumserverstandalonejar selenium import webdriver seleniumcommonexceptions import nosuchelementexception seleniumwebdrivercommonkeys import keys import time browser webdriverfirefox get local session firefox browsergethttpwwwyahoocom load page assert yahoo browsertitle elem browserfindelementbynamep find query box elemsendkeysseleniumhq keysreturn timesleep let page load added api try browserfindelementbyxpathacontainshref httpseleniumhqorg except nosuchelementexception assert find seleniumhq browserclose you could use subprocess start server inside python code,how i embed web browser python program it needs run linux gtk qt fine crossplatform i looked embedding pywebgtk qt webkit widget but seem little rendering engine in particular i like support backforward tabbed browsing is something like prepackaged i implement wxwebconnect seems roughly i thinking python bindings,2 you use entrycget method menu item get attributes including label value,i cascade menu parent menu the cascade items created dynamically addcheckbutton method a user able check menu items selectconfirm however i know access text menu items decide item selected obvious solution generate tkstringvar dynamically i would like avoid since complicates code significantly how get value menu labeltext tkinter is solution problem,1 james i believe real issue using unicode accross board try following make sure input file using populate db utf reading utf encoder make sure db actually storing data unicode when retrieve data file db want manipulate strings operator instance need make sure parts proper unicode you not use str method you need use unicode dave pointed if define strings code use u string instead string otherwise considered unicode also please provide us full stack trace exception name,i python file creates populates table ms sql the sticking point code breaks nonascii characters single apostrophes quite although i run replace function rid strings apostrophes i would prefer keep intact i also tried converting data utf luck either below th error messages i get ascii codec encode character u position nonascii characters single quotes class pyodbcprogrammingerror microsoftodbc sql server driversql server incorrect syntax near s x m eligibilty when i try encode string utf i instead get following error message type exceptionsunicodedecodeerror ascii codec decode byte xe position ordinal range the python code included i believe point code break occurs following line insertvalue strrowgetvaluecurrentfield name coding utf import pyodbc import sys import arcpy import arcgisscripting gp arcgisscriptingcreate sqlkeywords percent select insert drop table sourcefgdb sourcetable sourcetable sysargv tempinputname sysargv sourcetable sysargv target database settings targetdatabasedriver sql server targetdatabaseserver targetdatabasename targetdatabaseuser targetdatabasepassword get schema fgdb table this ordered list dictionary elements fgdbname fgdbalias fgdbtype fgdbwidth fgdbprecision fgdbscale gpexistssourcetable print the source exist sysexit should see actually table type could feature data set something print processing items from sourcetable fieldlist fieldlist gplistfieldssourcetable print getting number rows result gpgetcountmanagementsourcetable numberoffeatures gpgetcountmanagementsourcetable print number rows strnumberoffeatures print getting fields fieldlist gplistfieldssourcetable layer fieldlist gplistfieldssourcetable comments fieldlist gplistfieldssourcetable category fieldlist gplistfieldssourcetable state fieldlist gplistfieldssourcetable label fieldlist gplistfieldssourcetable dateupdate fieldlist gplistfieldssourcetable objectid currentfield fieldlist fieldlist fieldlist fieldlist fieldlist fieldlist fieldlist print field found currentfieldname currentfieldaliasname sqlkeywords targetname currentfieldname else targetname currentfieldname print alias currentfieldaliasname print type currentfieldtype print length strcurrentfieldlength print scale strcurrentfieldscale print precision strcurrentfieldprecision fieldlistappend name currentfieldname aliasname currentfieldaliasname type currentfieldtype length currentfieldlength scale currentfieldscale precision currentfieldprecision unique unique targetname targetname create table sql server based fgdb table schema cnxn pyodbcconnectr driversql serverserverdatabaseuidsqlwebenvaspwd cursor cnxn cursor drop table first try droptablesql drop table dbo tempinputname test print droptablesql cursorexecutedroptablesql dbconnectioncommit except print warning can drop table may exist tempinputname test createtablesql create table tempinputname test layer varchar comments varchar state int label varchar dateupdate datetime category varchar objectid int cursorexecutecreatetablesql cnxncommit cursor row fgdb table get values insert sql server table we got numberoffeatures earlier use numberprocessed print processing strnumberoffeatures features rows gpsearchcursorsourcetable row rowsnext row numberprocessed print processed strnumberprocessed strnumberoffeatures insertsqlfields insert into tempinputname test insertsqlvalues values currentfield fieldlist insertsqlfields insertsqlfields currentfield targetname insertvalue strrowgetvaluecurrentfield name insertvalue none insertvalue null use escape quote sql insertvalue insertvaluereplace currentfield type upper string char text insertvalue null insertsqlvalues insertsqlvalues null else insertsqlvalues insertsqlvalues insertvalue elif currentfield type upper geometry we handling geometry transfers time insertvalue null insertsqlvalues insertsqlvalues else insertsqlvalues insertsqlvalues else insertsqlvalues insertsqlvalues insertvalue insertsqlfields insertsqlfields insertsqlvalues insertsqlvalues insertsql insertsqlfields insertsqlvalues print insertsql cursorexecuteinsertsql cnxncommit numberprocessed numberprocessed row rowsnext print processed strnumberprocessed del row del rows,1 use set instead list setslist if really need list convert back list slist listsetslist note conversion preserve original order elements if need order use instead result seen set innerlist mylist item innerlist item seen seenadditem resultappenditem result,i list tuples like mylist if i use list comprehension slist item sublist mylist item sublist i could get slist how i modify i need unique elements slist like,3 you use python sets httpdocspythonorglibrarysetshtml setyourlist trick,i list tuples like mylist if i use list comprehension slist item sublist mylist item sublist i could get slist how i modify i need unique elements slist like,1 you actually make first part bit easier using itertoolschainfromiterable passing result set retain unique elements mylist import itertools setitertoolschainfromiterablemylist set,i list tuples like mylist if i use list comprehension slist item sublist mylist item sublist i could get slist how i modify i need unique elements slist like,2 import itertools chain itertoolschainmylist printsetchain taken flattening shallow list python adapted use question,i list tuples like mylist if i use list comprehension slist item sublist mylist item sublist i could get slist how i modify i need unique elements slist like,1 operator import itemgetter itertools import groupby maxitems key items groupbylkey itemgetter it assuming initial list tuples sorted key values groupby creates iterator yields objects like itertoolsgrouper object x first value key value second one another iterator gives tuples key maxitems selects tuple maximum value since second values group also key gives tuple maximum first value a list comprehension used form output list tuples based output functions,i list tuples like i want keep tuples max first value every tuple second value for example share second key value i want keep one max first value in end i would get i mind oneliner i wondering efficient way go,3 probably using dict rd vk mytuples v rdsetdefaultkv rdk v result vk kv rditems,i list tuples like i want keep tuples max first value every tuple second value for example share second key value i want keep one max first value in end i would get i mind oneliner i wondering efficient way go,1 looks like use closure def decoratorarg def wrapklass return wrap call evaluated class bandcreateviewcreateview bandcreateview successmessage band created successfully bandcreateview note double call,i written decorator display success message object creation djangocontrib import messages def successmessageklass def formvalidself form response superklass selfformvalidform messagessuccessselfrequest object added successfully return response klassformvalid formvalid return klass use decorate class based generic view successmessage class bandcreateviewcreateview model band now i want parameterize decorator possible successmessage band created successfully class bandcreateviewcreateview model band how i i tried adding message parameter successmessage compiler complained parameter count mismatch i figure must another way,1 from macports bug installed xcode version python built clang c compiler rather gcc there least one known problem building clang os x fixed python subsequent release either apply patch better ensure build uses gcc something like untested sudo bash export ccusrbingcc port clean python port upgrade force python prior build might work macports override update the required patch applied macports port files python see httpstracmacportsorgchangeset,after thorough read python decimal module documentation i still find puzzled happens i divide decimal in python makes sense import decimal decimaldecimal decimal in python python python puzzling import decimal decimaldecimal decimal more confusing yet result even appear valid decimaldecimal traceback recent call last file stdin line module file optlocallibraryframeworkspythonframeworkversionslibpythondecimalpy line new invalid literal decimal r value file optlocallibraryframeworkspythonframeworkversionslibpythondecimalpy line raiseerror raise errorexplanation decimalinvalidoperation invalid literal decimal the result using decimaldecimal decimaldecimal issue using int divisor part issue clearly around precision decimaldecimal decimaldecimal decimal decimaldecimal decimaldecimal decimal but ample precision decimaldecimal divide safely get answer least right ballpark the fact behavior unchanged three major revisions python says bug what i wrong what i missing how i divide decimal short using python,3 egg cache issue solved setting environment variable wsgi script httpcodegooglecompmodwsgiwikiapplicationissuesaccessrightsofapacheuser apache configuration httpcodegooglecompmodwsgiwikiconfigurationdirectiveswsgipythoneggs httpcodegooglecompmodwsgiwikiconfigurationdirectiveswsgidaemonprocess which latter two used depends whether using emebedded mode daemon mode,this long question detailing i start hope helps i working django application need deploy production server the production server virtual server managed it i root access they given rights manage installations modules swadm homeswadm so i planned create following arrangement swadmetchttpdconf i maintain httpdconf swadmetchttpdusermodules i maintain apache modules modwsgi swadmvarwwwdjangoapp i maintain django code swadmusrlocalpython i maintain python installation modules like django south etc homeswadmsetup i storing required source tarballs building installing homeswadmworkspace i maintaining application code development the system python python installed it recommended i maintain python installation i required lot custom modules installed i would so i downloaded python source i needed ensure python installed shared library available when i ran configure script option enableshared prefixswadmusrlocalpython would get installed surprisingly point system installation python swadmusrlocalpythonbinpython python r feb gcc red hat linux type help copyright credits license information so i ran configure script following instructions building python enableshared nonstandard location configure enableshared prefixswadmusrlocalpython ldflagswlrpath swadmusrlocalpythonlib also making sure i created directories beforehand link suggests avoid errors expected now typing swadmusrlocalpythonbinpython would start correct python version so i moved configuring installing modwsgi i configured configure withpythonswadmusrlocalpythonbinpython makefile created tries install module usrlibhttpdmodules i write permissions i modified makefile install swadmetchttpdusermodules there might command argument i could figure the module got created fine a test wsgi script i used import sys def applicationenviron startresponse status ok output hello world output output strsysversioninfo output output nsysprefix reprsysprefix output output nsyspath reprsyspath responseheaders contenttype textplain contentlength strlenoutput startresponsestatus responseheaders return output and output shown surprisingly hello world final sysprefix swadmusrlocalpython syspath swadmusrlocalpythonlibpythonzip swadmusrlocalpythonlibpython swadmusrlocalpythonlibpythonplatlinux swadmusrlocalpythonlibpythonlibtk swadmusrlocalpythonlibpythonlibold swadmusrlocalpythonlibpythonlibdynload so see somehow modwsgi module still got configured system python installation custom one i tried various things detailed modwsgi documentation set wsgipythonhome httpdconf swadmusrlocalpython wsgipythonpath swadmusrlocalpythonlibpython created symlink python config directory point libpythonso file ln libpythonso when i ldd libpythonso i see ldd libpythonso linuxvdsoso xfffcfc libpthreadso liblibpthreadso xbed libdlso liblibdlso xbefe libutilso liblibutilso xbf libmso liblibmso xbf libcso liblibcso xbf libldlinuxxso xaba and ldd modwsgiso gives ldd swadmetchttpdusermodulesmodwsgiso linuxvdsoso xfffade libpythonso usrliblibpythonso xafaec libpthreadso liblibpthreadso xafb libdlso liblibdlso xafbc libutilso liblibutilso xafb libmso liblibmso xafb libcso liblibcso xafbb libldlinuxxso xaba i trying reinstalling reconfiguring python modwsgi avail please let know i going wrong sorry long post tldr system nonroot access default python installation i maintaining python python modules modwsgi configured built custom python still points system python i run test script prints sys versioninfo path update on browsing stackoverflow done earlier i found answer graham dumpleton modwsgi python ubuntu problem solved error now i ldd modwsgiso i see linked correct shared library python i installed django mysqldb using custom python install and now i facing error the following error occurred trying extract files python egg cache errno permission denied varwwwpythoneggs the python egg cache directory currently set varwwwpythoneggs perhaps account write access directory you change cache directory setting pythoneggcache environment variable point accessible directory so i change value pythoneggcache export pythoneggcacheswadmvarwwwpythoneggs i still getting error i investigating will update i solve,1 you could use find utility linux on command prompt find projectdirectorypath name py xargs wc l this give count files ending py projectdirectory finally total i assuming want count py files if want total nothing else could use find projectdirectorypath name py xargs wc l tail,how i calculate number lines written project containing multiple sub dirs python project example dir structure like a files b files,3 emailaddr fooyyycom emailaddrendswithyyycom something elif emailaddrendswithzzzcom something else yyycom emailaddr something elif zzzcom emailaddr something else,lets say email address xxxyyycom want create something like python email mystuffyyycom try yyycom something zzzcom something else except something how would i,3 no you pass scriptdir option easyinstall specify you could add project setupcfg file recommended surprise people configured python installation install scripts location even take effect users actually run setuppy most installation tools ignore script path specified project setupcfg,i setuppy script entrypoints defined like entrypoints consolescripts gun gunsyncmain this installs executable usrbin is way i tell entrypoints install usrsbin instead,3 you need configure rows columns nonzero weight take extra space x range gridcolumnconfiguregrid x weight range gridrowconfiguregrid weight you also need configure buttons expand fill cell btngridcolumnx rowy stickynsew this done way full example tkinter import root tk frameframeroot gridrowconfigureroot weight gridcolumnconfigureroot weight framegridrow column stickynsew gridframeframe gridgridstickynsew column row columnspan gridrowconfigureframe weight gridcolumnconfigureframe weight example values x range range btn buttonframe btngridcolumnx rowy stickynsew x range gridcolumnconfigureframe x weight range gridrowconfigureframe weight rootmainloop,i trying create grid buttonsin order achieve clickable cell effect tkinter my main problem i cannot make grid buttons autoresize fit parent window for example i high number buttons grid instead shrinking buttons grid fits inside window i get stretched frame goes screen the effect i looking grid filling available space resizing cells fit within space i read documentation i still cannot figure make work this basic code starting point def initself root tk frame frameroot framegrid widgets get added first rows frame grid initialize grid grid frameframe gridgridstickynsew column row columnspan example values x range range btn buttongrid btngridcolumnx rowy rootmainloop,3 if using python x try factor index fadelength an int divided larger int you coerce operation floating point division edit you also use future import division make division operator use true division like python use floor division,i student programming class i get fading work right muting first samples length fadelength anyone tell i find way fix code erased help without direct answers would great thank,1 modules executed top bottom when import seen first time execution current module suspended module imported when module attempts import first module gets reference currently partiallyexecuted module since code located import module yet executed names contained within cannot yet exist mainpy import apy var foo import b var bar bpy import print avar works print avar fails the way around access names imported module execution completed,i know python discourages situation get circular import but i wanted understand python internals fromimports seemingly arbitrarily less forgiving normal imports circular import situations for example code compiles mainpy import commonutil commonutilpy import util class commonutil code uses utilutil pass utilpy import commonutil class util code uses commonutilcommonutil pass but code mainpy import commonutil commonutilpy import util class commonutil code uses utilutil pass utilpy commonutil import commonutil class util code uses commonutil pass traceback recent call last file mainpy line module import commonutil file commonutilpy line module import util file utilpy line module commonutil import commonutil importerror cannot import name commonutil you hit compiler errors long try use relevant classes imports completed but try aliasing fails can someone explain going internally python causes error rear head fromimport used and secondarily easy way around besides obvious pull shared code third module i likely anyways,1 vim normally create temporary file rename this filesystem aspects links soft hard preserved writing files this discussed briefly writing section vim documentation information backupcopy option documentation your file change events might limited changing directory entries,i using watchdog monitor less file change events os x if i change contents less file textmate sublime text modification event captured however i edit content vim file modification event fired file creation events files created vim captured i seen behaviour fsevents kqueue i practically zero knowledge i wonder anybody explain behaviour,2 see httpeffbotorgzoneimportconfusionhtmcircularimports explanation happening i assume launch mainpy file python first try load commonutil it create module object start filling class function global variable encountering definition the first statement import python creates util module start filling the common module exist empty in first version access commonutil object load time everything fine in second one try fetch specific variable commonutil exist moment if used something like fcommonutilcommonutil first version would also crashed,i know python discourages situation get circular import but i wanted understand python internals fromimports seemingly arbitrarily less forgiving normal imports circular import situations for example code compiles mainpy import commonutil commonutilpy import util class commonutil code uses utilutil pass utilpy import commonutil class util code uses commonutilcommonutil pass but code mainpy import commonutil commonutilpy import util class commonutil code uses utilutil pass utilpy commonutil import commonutil class util code uses commonutil pass traceback recent call last file mainpy line module import commonutil file commonutilpy line module import util file utilpy line module commonutil import commonutil importerror cannot import name commonutil you hit compiler errors long try use relevant classes imports completed but try aliasing fails can someone explain going internally python causes error rear head fromimport used and secondarily easy way around besides obvious pull shared code third module i likely anyways,1 one solution problem would change program writing files write files temporary file first move temporary file destination done on operating systems source destination file system move atomic,i python script checks pickup directory processes files finds deletes how i make sure pickup file still written process drops files directory my test case pretty simple i copypaste mb files pickup directory frequently script grab file still written it operates partial file delete this fires file operation error os file writing disappeared i tried acquiring lock file using filelock module i openprocessdelete but helped i considered checking modification time file avoid anything within x seconds but seems clunky my test osx i trying find solution work across major platforms i see similar question how check file still written clear solution thank,1 as workaround could listen file modified events watchdog crossplatform the modified event os x least fired write fired close so detect modified event assume writes complete of course file written chunks saved chunk work,i python script checks pickup directory processes files finds deletes how i make sure pickup file still written process drops files directory my test case pretty simple i copypaste mb files pickup directory frequently script grab file still written it operates partial file delete this fires file operation error os file writing disappeared i tried acquiring lock file using filelock module i openprocessdelete but helped i considered checking modification time file avoid anything within x seconds but seems clunky my test osx i trying find solution work across major platforms i see similar question how check file still written clear solution thank,1 note i longer advocate solution much cleaner one by trial error looking django source i wrote class listcreateviewlistview basecreateview def getcontextdataself kwargs selfobject none selfobjectlist selfgetqueryset formclass selfgetformclass form selfgetformformclass kwargsupdate objectlist selfobjectlist form form context superlistcreateview selfgetcontextdatakwargs return context works fine creating listing although may issue extra database calls sure,i looking easiest way combine list create functionally generic class views i want page item list form add new item bottom i thought mixin architecture would allow combine necessary classes i luck yet this almost works class resourcelistviewlistview basecreateview contextobjectname resources model resource formclass resourceform but form accessible inside template thing crashes invalid output form valid fine this may multiple inheritance i really python yet gets confusing is simple way combine mixins viewandcreate view i roll,2 docs processtemplateresponse called response instance render method indicating templateresponse,i defined middleware class added middlewareclasses attribute setting when request comes middleware class gets created debugger catches code breakpoint class commonfiilter line now expect function def processtemplateresponseself request response get called i debug point inside function debugger never traps execution the debugger though traps execution line function name parameters defined this class class commonfilter debugger breaks def processtemplateresponseself request response debugger breaks responsetemplatename storeindexhtml not here line catnamesgetcategories responsecontextdataupdate catnames catnames user requestgetgetkey user defaultnone return response also tried class commonfilter debugger breaks def processtemplateresponseself request response debugger breaks responsetemplatename storeindexhtml not here catnamesgetcategories responsecontextdata catnames catnames responsecontextdata user requestgetgetkey user defaultnone return response just case setting middlewwareclasses variable middlewareclasses storemodelscommonfilter djangomiddlewarecsrfcsrfviewmiddleware djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware store app project ofcourse commonfilter defined modelspy why function processtemplateresponse function executed thanks time kind concern,1 i found example httposdircommlpythonmatplotlibgeneralmsghtml,i want generate map united states color state using different shade is way using python basemap,3 if control writing portion watch file stops growing certain amount time call good i use method found seconds safe conditions,i python script checks pickup directory processes files finds deletes how i make sure pickup file still written process drops files directory my test case pretty simple i copypaste mb files pickup directory frequently script grab file still written it operates partial file delete this fires file operation error os file writing disappeared i tried acquiring lock file using filelock module i openprocessdelete but helped i considered checking modification time file avoid anything within x seconds but seems clunky my test osx i trying find solution work across major platforms i see similar question how check file still written clear solution thank,1 it seems really compatible statement try twilio import twiml r twimlresponse rsayhello g rgatherfinishonkey gsayworld print strr here i get twilio import twiml r twimlresponse rsayhello twiliotwimlsay object xdd g rgatherfinishonkey gsayworld twiliotwimlsay object xd print strr xml version encodingutfresponsesayhellosaygather finishonkeysayworldsaygatherresponse,im using twiliopython im following tutorial httpreadthedocsorgdocstwiliopythonenlatestusagetwimlhtmlhighlightnest but try twilio import twiml r twimlresponse rsayhello rgatherfinishonkey g gsayworld print strr but get attributeerror exit any idea,1 you use generator quickly convert dictionary dictx none x l where l list that results none c none b none none,i list b c i need construct dict list elements list keys dict default value elements none how should i need write function constructor available,1 see dictfromkeys dictfromkeys b c return dictionary none values dictfromkeys b c foo return dictionary foo values,i list b c i need construct dict list elements list keys dict default value elements none how should i need write function constructor available,3 lst b c using list comprehension dictx none x lst using fromkeys dictfromkeyslst,i list b c i need construct dict list elements list keys dict default value elements none how should i need write function constructor available,1 you try dictfromkeysdata defaultvalue if omit defaultvalue defaults none,i list b c i need construct dict list elements list keys dict default value elements none how should i need write function constructor available,1 the amp symbol stands bitwise and the symbol stands bitwise xor fffffff hex number in programming represent hex number using x fffffff xfffffff some reading hex numbers to binary and python use amp xfffffff see bitwise operations python,just fully front regarding homework assignment the assignment using noise create cool graphics i bit experience python enough figure simple thing i trouble generating seededrandom the pseudocode teacher gave hugo elias pseudocode function noiseinteger x integer n x n n n return n n n amp fffffff end function my attempt python def noisex n x n n n return n n n amp fffffff the problem amp fffffff bit return statement first i sure operation maybe bitshift second i sure operation python i removed part i getting huge negative numbers nowhere near,2 as rocksportrocker implies need take account histogramd returns edges addition histogram another detail probably want explicitly pass range otherwise one chosen based actual min max values data you want convert edges cell centers plot something like import numpy np import matplotlibpyplot plt n many data points xmin xmax distances ymin ymax angles make random data xinprandomnormalxmax xmax n yinprandomnormalymax ymax n z xedges yedges nphistogramdxiyi bins rangexmin xmax ymin ymax find cell centers cell edges x xedges xedges yedges yedges promote d arrays y x npmeshgridy x pltcontourxyz pltylabel angles pltxlabel distance pltcolorbar pltsavefighistdpng yields countour plot like personally i use contours case since histogram likely noisy,despite using search function i unable find answer i got two assumptions know far may apply now problem i like plot contour for i got following python code import numpy np import matplotlibpyplot plt xilistofdistance yilistofangle x nparange nparange z nphistogramdxiyibins x y npmeshgridx pltcontourxyz pltylabel angles pltxlabel distance pltcolorbar pltshow xi yi lists containing float values x defining intervals example x generates list values steps generates list values steps z i make use numpy function create dhistograms actually seems spot causes trouble when function pltcontourxyz called following error message emerges file usrlibpymodulespythonnumpymacorepy line new data nparraydata dtypedtype copycopy suboktrue ndminndmin valueerror setting array element sequence now assumptions may cause problem it seems like expects array instead numpyarray receives list we got row shorter others i came thought collegue ran issue year ago fixed figuring last row elements shorter others,1 i replaced fffffff xfffffff existing code tried plugging random values answers i got,just fully front regarding homework assignment the assignment using noise create cool graphics i bit experience python enough figure simple thing i trouble generating seededrandom the pseudocode teacher gave hugo elias pseudocode function noiseinteger x integer n x n n n return n n n amp fffffff end function my attempt python def noisex n x n n n return n n n amp fffffff the problem amp fffffff bit return statement first i sure operation maybe bitshift second i sure operation python i removed part i getting huge negative numbers nowhere near,1 the problem added dictionary mydict every key you want add different dictionaries like mydict dictkey key keylist in code create new dictionary pair key in original code function fromkeys took argument empty dictionary provided added exact argument single empty dictionary created pass function keys when one dictionary changed change showed everywhere,the code mydict keylist b c mydictdictfromkeyskeylist mydict sample mydict sample c sample b sample i expecting mydict sample would set value dictionary value would get sample c b what i missing what i get expected output,3 on old ooorg forums superuser villeroy posted illustration call python functions ooorg basic used formulae the key use comsunstarscriptprovidermasterscriptproviderfactory service bridge here adaptation solution generalized call arbitrary functions arbitrary modules rem keep global reference scriptprovider since stuff may called many times global gmasterscriptprovider object rem specify location python script providing cell functions const urlmain string vndsunstarscript const urlargs string languagepythonamplocationuser function invokepyfuncfile as string func as string args as array outidxs as array outargs as array surl urlmain amp file amp py amp func amp urlargs omsp getmasterscriptprovider on local error goto errorhandler oscript omspgetscriptsurl invokepyfunc oscriptinvokeargs outidxs outargs exit function errorhandler dim msg as string tofix as string msg error tofix if err and instrerror error occurred file opening then msg couldn open script file tofix make sure python folder exists user scripts folder former contains amp file amp py end if msgbox msg amp chr amp tofix error amp err amp calling amp func end function function getmasterscriptprovider isnullgmasterscriptprovider omasterscriptproviderfactory createunoservicecomsunstarscriptprovidermasterscriptproviderfactory gmasterscriptprovider omasterscriptproviderfactorycreatescriptprovider endif getmasterscriptprovider gmasterscriptprovider end function this used create ooorg basic function callable formula using example pytype const libfile string util rem functions live utilpy function pytypevalue pytype invokepyfunclibfile pytype arrayvalue array array end function another potential implementation create python addin however much heavier option requires installing openoffice sdk obvious whether approach would work free functions works classes,to extend openoffice capabilities i defined python macros file user script directory libraryapplication supportopenofficeorguserscriptspython case the macros visible python macro organizer however using functions cell formula results name ooorg error suppose i defined following function def pytypeval return strtypeval how i call pytype cell formula eg pytypestring background i importing data authorizenet mysql database analysis mysql parse date amp time format used authorizenet datetime timestamp field i trying massage data format mysql handle import openoffice also recognize data date amp time far i able determine ooorg generic date parsing function thus i extending ooorg capabilities there approaches larger issue for example i could also try fix data mysql postimport using additional columns in fact i first time however existing data table contend because tasks future i hope accomplish using macros formulas i mostly interested calling python macros formulae,2 use gdisplay create graph window visualgraph import graphx gcurvecolor colorcyan gdisplay graphy gcurvecolor colorred,if i graph like vpython graphx gcurvecolor colorcyan i make another graph graphy gcurvecolor colorred different window different set axes,1 the rd option paste mask see docs it accepts rgba image simplest solution use overlay image impasteoverlay overlay,i trying place png watermark partial transparency top facebook profile pic jpg using python image library the part transparent simply comes white here code con urlliburlopen facebooklinktoprofilepic im imageopencstringiostringioconread overlaycon urlliburlopen linktooverlay overlay imageopencstringiostringiooverlayconread impasteoverlay imsave name jpeg quality i tried different ways gotten anything work any help appreciated,3 the problem amp fffffff bit return statement first i sure operation maybe bitshift a bit mask used shifting amp bitwiseand fffffff interpreted hexadecimal number quantity rewritten binary bits the effect select loworder bits value to tell python fffffff interpreted hexadecimal number must prefix x hence xfffffff second i sure operation python the way pseudocode ie amp,just fully front regarding homework assignment the assignment using noise create cool graphics i bit experience python enough figure simple thing i trouble generating seededrandom the pseudocode teacher gave hugo elias pseudocode function noiseinteger x integer n x n n n return n n n amp fffffff end function my attempt python def noisex n x n n n return n n n amp fffffff the problem amp fffffff bit return statement first i sure operation maybe bitshift second i sure operation python i removed part i getting huge negative numbers nowhere near,1 create array python first pass c in c get shape x nx nx nx and use macros defined array access elements for example xkji xkji python outji outji python you view automatic created c code know variables macros use arrays to get folder c code scipy import weave print weavecatalogdefaultdir my compiler support isnan i use tmptmp check coding utf import scipyweave weave import numpy np def foox npzerosxshape code int ijkn foriinxi forjjnxj n forkknxk double tmp xkji iftmp tmp isnan available outji tmp n outji n weaveinlinecode xout headersmathh compilergcc return nprandomseed x nprandomrand x npnan mx npmaarrayx masknpisnanx avg foox avg npmaaveragemx axis print npallavg avg you also use blitz converter access array c for detail try google weaveconvertersblitz,i playing scipy inline tool via weave fun i running trouble my c rusty i feeling i missing something simple the function designed take d float numpy array i using massive set gridded atmospheric data work d array this takes grid gets arithmetic mean across axis point jk ie time axis j k latlon i averaging across time grid point i hope code avoiding numpy nans i believe isnan works inline cc but whether i trouble getting code compile without errors toolspy in function ‘pyobject compiledfuncpyobject pyobject’ toolspy error invalid types ‘floatint’ array subscript toolspy error invalid types ‘floatint’ array subscript toolspy in function ‘pyobject compiledfuncpyobject pyobject’ toolspy error invalid types ‘floatint’ array subscript toolspy error invalid types ‘floatint’ array subscript i think i declaring initializing properly perhaps something passed weave way i think i would love someone could help here function scipyweave import inline def foox xi npshapex xj npshapex xk npshapex code line toolspy int n float outxjxk int k k xk k int j j xj j n int xi isnanxijk n outjk xijk outjk outjkn returnval awesomeness inlinecode x xi xj xk compiler gcc returnawesomeness,1 it extracts blocks mids curids block consists chunk elements if change loop print values intidxchunk intidxchunkchunk see for example lenmids chunk indices would get printed these starting ending indices slice mids start index inclusive end index note last value allowed go lenmids problem given python slicing works slice end mids,i trying understand going specifically curids getting set idx xrange intmathceilfloatlenmidschunk curids midsintidxchunkintidxchunkchunk i sure syntax midsintidxchunkintidxchunkchunk trying,1 a number like could local number unspecified area unspecified country maybe local number area code unspecified country maybe local number country code without context impossible tell the symbol vital identifying country code part,is easy way check whether phone number entered user includes country code validate number correct i use specific formats number must digits like is validation possible without asking user country the trick i want work numbers worldwide i guess done regex googled bit found lots stuff problem is library i using python or maybe would make sense enforce format eg xyyyyyyyy x would country code something like,1 timedelta instance attributes days seconds save lines they also keep values small convert int early instead string format this also removes need abs floor,i wrote little script format timedelta object according needs def dueformatself timediff absselfdue datetimedatetimenowtotalseconds days timediff hours timediff minutes timediff hourswodays hours mathfloordays minuteswohours minutes mathfloorhours days selfdueformat days formatintdays elif hours selfdueformat days hours formatintdays inthourswodays elif hours hours selfdueformat hours formatinthours elif hours selfdueformat minutes formatintminutes elif hours selfdueformat hours f minutes formatinthours intminuteswohours i getting feeling approach makes things overly complicated wanted ask guys would attacked problem differently are shortcuts i could take advantage i hope question appropriate so,1 that dictionary urlspy entry gets passed keyword arguments view function register access page register keyword argument formclass if register first link referring register second first link wrong because register accept keyword arg one answer seems define different register method i think might something else if understand formclass supposed passed could add kwarg register manually,trying follow answers provided djangoregistration amp djangoprofile using custom form creating django registration form extending djangoregistation application extend djangoregistration form i added following code urlpy urlr accountsregister register backend registrationbackendsdefaultdefaultbackend formclass userregistrationform name registrationregister r accounts includeregurls whenever access httplocalhostaccountsregister getting following error register got unexpected keyword argument formclass please help why getting error i goggled lot still could figure solution,1 yes better way simply create list lists playing vars ommited possible it really hard read debug regret attitude lately when create list like players hand cards even dict players like players player player one third card much happy,i trying make blackjack game i made functions drawing cards checking sum one hand exceeds players that easy i lists but i want n number players i want keep functions make another one switches players hands def createhands global totalplayers x range totalplayers varshandd x print hand i want create many hands hand hand etc many n players totalplayers because code get global name hand defined error so comes how i make handd x global is better way,1 int constructor callable use map,if following code exactly following documentation mapfunction iterable x sortedmapint datsplit is int function expressed,2 when ask expressed i suppose mean brackets like function the answer put brackets get function instead function compare happens enter int versus int,if following code exactly following documentation mapfunction iterable x sortedmapint datsplit is int function expressed,1 i use python matplotlib to graphic inserted gui i need backend httpmatplotlibsourceforgenetfaqinstallingfaqhtmlbackends code snippet matplotlibbackendsbackendgtkagg import figurecanvasgtkagg canvas then instance addsubplot prepares place one plot figsn matplotlibpyplotfigure ax figsnaddsubplot canvas canvasfigsn snboxpackstartcanvas true true canvasdraw so i want say need backend package may able draw gtk recognize it suppose chaco lib compiled gtk support i install chaco today please dig way let know find,embedding chaco qt wx seems problem does anyone example idea embed chaco gtk,1 in case dat string split generates list strings splitting input string whitespaces eg split returns the map function two input arguments the first argument something called python say callable eg function int realy function thing python slang object eg int return so int applied string tries convert string integer gives integer value back the second argument something iterate case list if call map function first argument applied elements second argument so mapint returns if combine i explained understand mapint split returns,if following code exactly following documentation mapfunction iterable x sortedmapint datsplit is int function expressed,2 i would recommend sbinary it uses implicits resolved compile time effective typesafe it comes builtin support many common scala datatypes you manually write serialization code case classes easy a usage example simple adt,is simple hasslefree approach serialization scalajava similar python pickle pickle deadsimple solution reasonably efficient space time ie abysmal care crosslanguage accessibility versioning etc allows optional customization what i aware java builtin serialization infamously slow bloated fragile also mark classes serializableannoying things clearly serializable annotation eg many pointd authors mark serializable scala bytepickle requires bunch boilerplate every type want pickle even work cyclic object graphs jserial unmaintained seem much fastersmaller default java serialization kryo cannot deserialize objects arg ctors severe limitation also register every class plan serialize else get significant slowdownsbloat even still faster pickle protostuff afaict register every class intend serialize advance schema kryo protostuff closest solutions i found i wondering anything else way use i aware please include usage examples ideally also include benchmarks,2 of course it seems replacing wordhist dict one values plus try wordhistv wordhistv even better wordhistv instead edit there another bug kv wordfreqiteritems key wordhist wordhistv wordhistv else wordhistv makes sense key tested presence wordhist v used i know key either use k v,import nltk nltkbook import nltkcorpus import brown corpustext brownwords wordfreq freqdistcorpustext wordhist dict kv wordfreqiteritems key wordhist wordhistv wordhistv else wordhistv print wordhistviewkeys print wordhistviewvalues i making mistake dictionary handling need create dictionary keys words freqdict values number corresponding word i perform increment i certain wordhistv wordhistv else wordhistv bug,1 use bool array access elements array def testcy f fc fc f absf idx ffc amp ffc yidx return,a question complete python novice i column array i need force certain values zero depending conditional statement applied another array i found two solutions provide correct answer but quite time consuming larger arrays i typically need e elements also i suspect poor programming technique the two versions numpy import zerosabsmultiplyarrayreshape def testay f fc fc c zeroslenf n xrangelenf absfn fc absfn fc cn w multiplycy return w def testby f fc fc z absfnfc absfnfc n xrangelenf z multiplyarrayzdtypefloatreshapelenf return z the input arrays column arrays matches post processing done the test done like numpyrandom import normal randn fs n e f fsnarangenreshapen x randnsizen w testaxf z testbxf on laptop testa takes seconds testb takes n in testb i also tried include z nonelenf preallocate suggested another thread really make difference i two questions i hope answer what correct python solution problem is anything i get answer faster i deliberately used time using compiled python example i wanted working code first hopefully also something good python style i hope able get execution time n two seconds this particular operation used many times execution time matter i apologize advance question stupid i able find answer overwhelming amount always easily accessible python documentation another thread,2 try works real rename pngxpng pngxpng import os files oslistdir filename files filewoext fileext ospathsplitextfilename fileext png newfile filewoext png osrenamefilename newfile,i large set images png extension say imagepng i want convert png lower case i got script internet unable process here script files oslistdircurdir filename files fileext ospathsplitextfilename oldext fileext newfile filenamereplaceoldext newext osrenamefilename newfile when i try run terminal i get error nameerror name filename defined what could problem,3 if using django best way imho create view handle python code access onclick event via ajax request yourappviewspy def yourpythonscriptrequest requestisajax stuff else return httprequeststatus if using django also jquery template add javascript code something like yourbuttonidclick function postyourpythonscripturl dict args need function what request successfully completed and forget crsf token using how handle find offical django documentation update you add csrf token page template like script var csrftoken csrftoken script next need bind global jquery ajaxsend event add token post request bodybindajaxsend functionelm xhr stype post xhrsetrequestheader xcsrftoken csrftoken something like work,i currently making website using django now i want execute python script templateview button website it possible honest i know an example would best thanks help,1 not sure got answer looking mean parse model entry data query object directly json object at least i searching i wrote parse entries query object list json objects def gqljsonparserqueryobj result entry queryobj resultappenddictp unicodegetattrentry p p entryproperties return result you app respond ajax requests encoding simplejson eg querydata mymodelall jsonquerydata gqljsonparserquerydata selfresponseheaders contenttype applicationjson selfresponseoutwritesimplejsondumpsjsonquerydata your app return something like property value property value let know helps,how i get json object python getting data via google app engine datastore i got model datastore following field id keyname object userid created now i want get objects one user query modelallfilter userid useruserid how i create json object query i write i want get data via ajax call,3 masterlistappendkeyvalue,i want add dictionary nested list within nested list masterlist list sublist list list would end like masterlist list sublist keyvalue list list i know exact position within lists i want add dictionary i add dictionary without looping lists i got far masterlistappendlist i find call lower lists,2 create view function dajaxiceregister decorator a silly example follows modelspy class funkynessmodelsmodel funktasm modelscharfieldmaxlength funfasticness modelstextfield urlspy urlr funk viewsmyfunkyview viewspy def myfunkyviewrequest rendertorequest indexhtm home contextinstancerequestcontextrequest indexhtm you endif when go httpyoursitecomfunk get indexhtm rendered get page says you home now dynamic part write view method djangoutils import simplejson def gethowfunkyrequest v html div classmymessage this really funky almost stinky br strv div return simplejsondumps message html back indexhtm script typetextjavascript first argument return js function second dictionary data sent python method function init dajaxicepackagegethowfunkyshowfunky v your truly fubar function showfunkydata this data returned back ajax dajaxice call documentwritedatamessage script so build python method takes inputs returns something you register dajaxice call passing callback method it runs succeeds send python return possibly json object callback method argument that method writes screen got dajaxice call for info dajaxice go httpdajaxprojectcom props jorge bastida sole developer dajaxdajaxice,i currently making website using django now i want execute python script templateview button website it possible honest i know an example would best thanks help,1 each os different solution file locking mechanisms portable on windows use os locking on linux peek open files similarily lsof file open leave,i python script checks pickup directory processes files finds deletes how i make sure pickup file still written process drops files directory my test case pretty simple i copypaste mb files pickup directory frequently script grab file still written it operates partial file delete this fires file operation error os file writing disappeared i tried acquiring lock file using filelock module i openprocessdelete but helped i considered checking modification time file avoid anything within x seconds but seems clunky my test osx i trying find solution work across major platforms i see similar question how check file still written clear solution thank,1 import random lst string hello world hello world print join ss x randomchoicelst randomrandom else x string,for example str hello world hello world turns list str hello world hello world,3 if want get separate numbers treat separate numbers you need binascii hexinput ca decoutput inthexinput inthexinput inthexinput inthexinput print decoutput this generalised i leave exercise,i difficulty changing hex intchar char preferably via website httphomepaulschounettoolsxlate i enter hex ca hex box dec char box correctly outputs ip i expected contain this data pulled external database i aware saved i work hex string i tried using binasciiunhexlify function see i could decode i fear i may great enough understanding hex appreciate i attemping print using int cast also produced required results i need way convert hex string one similar original ip update for anyone comes across future i modified answer slightly provide exact printout ip using decoutput strinthexinput strinthexinput strinthexinput strinthexinput,3 you might also need chr function chr a,i difficulty changing hex intchar char preferably via website httphomepaulschounettoolsxlate i enter hex ca hex box dec char box correctly outputs ip i expected contain this data pulled external database i aware saved i work hex string i tried using binasciiunhexlify function see i could decode i fear i may great enough understanding hex appreciate i attemping print using int cast also produced required results i need way convert hex string one similar original ip update for anyone comes across future i modified answer slightly provide exact printout ip using decoutput strinthexinput strinthexinput strinthexinput strinthexinput,1 htext ca inthtextii rangelenhtext,i difficulty changing hex intchar char preferably via website httphomepaulschounettoolsxlate i enter hex ca hex box dec char box correctly outputs ip i expected contain this data pulled external database i aware saved i work hex string i tried using binasciiunhexlify function see i could decode i fear i may great enough understanding hex appreciate i attemping print using int cast also produced required results i need way convert hex string one similar original ip update for anyone comes across future i modified answer slightly provide exact printout ip using decoutput strinthexinput strinthexinput strinthexinput strinthexinput,1 a simple way ca mapord sdecode hex prefer list comprehensions ordc c sdecode hex,i difficulty changing hex intchar char preferably via website httphomepaulschounettoolsxlate i enter hex ca hex box dec char box correctly outputs ip i expected contain this data pulled external database i aware saved i work hex string i tried using binasciiunhexlify function see i could decode i fear i may great enough understanding hex appreciate i attemping print using int cast also produced required results i need way convert hex string one similar original ip update for anyone comes across future i modified answer slightly provide exact printout ip using decoutput strinthexinput strinthexinput strinthexinput strinthexinput,3 here approach leans towards clarity performancewise may optimal random import randint string hello world hello world char pos randint lenstring pick random position insert char string joinstringpos char stringpos insert char pos print string update taken answer related question essentially derived drtysra answer random import choice s hello world hello world l print join ss x choicechoicel x s,for example str hello world hello world turns list str hello world hello world,1 i suspect least one module name one pythonpath either look old copies left around try changing module names see happens you see similar effect forgot reload modules running modified restarting python session would obviously cause modules loaded afresh first import,i issue python looks really weird my script starts quite big suposed run test suite program my inclusion tree runpy module section test the weird behavior i i add modification module section test module source file take effect i developing emacs terminal simply run script using python runpy i tried restarting term restarting computer days bad idea anyway cleaning pyc files the version python i working debian lenny virtualbox and i able reproduce behavior another smaller program observe better,1 selecting imap folder retrieve messages selects folder if get message attributes like flags internal date need use fetch if want get messages two folders simply loop turn,i like retrieve two folders using select method i like get inbox well sent is way currently way i know i get one folder time using imapselect inbox,1 when confronted complex syntax add print statements xx x range print not helpful try xx x range print print helpful maybe try xx x range b lista print b hmmm the loop stops working also this generator object seems thing either loop list tuple function try x range print x x okay so learned xx x range generator expression httpwwwpythonorgdevpepspep it iterable used statement list function also learned add print statements explore confusing syntax,i trying problems projecteuler i got one sum squares squares sums i want brute force i looked solution sum sum xx x range sum sum printsum sum i get xx x range i seen another code golf solution javascript is specific syntax unfamiliar way something regular can someone please explain,2 collections import defaultdict wordhist defaultdictint kv wordfreqiteritems wordhistv,import nltk nltkbook import nltkcorpus import brown corpustext brownwords wordfreq freqdistcorpustext wordhist dict kv wordfreqiteritems key wordhist wordhistv wordhistv else wordhistv print wordhistviewkeys print wordhistviewvalues i making mistake dictionary handling need create dictionary keys words freqdict values number corresponding word i perform increment i certain wordhistv wordhistv else wordhistv bug,1 since indicate whether want word characterlevel ngrams i going assume former without loss generality i also assume start list tokens represented strings what easily write ngram extraction def ngramstokens minn maxn ntokens lentokens xrangentokens j xrangeiminn minntokens imaxn yield tokensij then replace yield actual action want take ngram add dict store database whatever get rid generator overhead finally really fast enough convert cython compile example using defaultdict instead yield def ngramstokens int minn int maxn cdef pyssizet j ntokens count defaultdictint joinspaces join ntokens lentokens xrangentokens j xrangeiminn minntokens imaxn countjoinspacestokensij return count,i using nltk search ngrams corpus taking long time cases i noticed calculating ngrams uncommon feature packages apparently haystack functionality does mean potentially faster way finding ngrams corpus i abandon nltk if i use speed things,3 timout duration could make longer anyway plenty flash ajax uploaders nothing server side afaik,i got working web application python downloads file web server upon user request this works fine small file downloads user requests larger file connection times so i think i need process download background i sure tool suitable celery seems right i really want queuedthe download must start immediately what would suggest,1 which version google api using according google documentation versions wrap document mediasource object order pass upload method so i think need replace clientuploaddocumententryfile splitted ms gdatamediasourcefilepathentryfile contenttypegdatadocsservicesupportedfiletypes doc clientuploadms splitted note assumes uploading word files you set contenttype parameter correct type file upload if using version longer need create mediasource object simply pass pathname title mime type directly upload method clientuploadentryfile splitted contenttype applicationmsword uploading pdfs if attempt upload pdf files using version api fails error status body contenttype applicationpdf valid input type reason unsupported media type this fixed using workaround shown comment issue google code site simple edit uploadfile method sitepackagesgdatadocsservicespy file shown ticket once made change pdf uploads work fine i checked amp works,i developing application works google api according understanding def pushtogarequest client gdatadocsservicedocsservice clientclientlogin accountgmailcom password entrys entryobjectsall entry entrys splitted entryfilesplit clientuploaddocumententryfile splitted return httpresponseredirect httpsdocsgooglecomhome have error traceback file homeienvgoogleapilibpythonsitepackagesdjangocorehandlersbasepy getresponse response callbackrequest callbackargs callbackkwargs file homeiworkspaceapirootgoogleapigoogleapiapiappviewspy pushtoga clientuploaddocumententryfile my entry strentryid file homeienvgoogleapilibpythonsitepackagesatom init py deprecatedfunction return fargs kwargs file homeienvgoogleapilibpythonsitepackagesgdatadocsservicepy uploaddocument folderorurifolderoruri file homeienvgoogleapilibpythonsitepackagesgdatadocsservicepy uploadfile extraheaders slug mediasourcefilename exception type attributeerror pushtoga exception value unicode object attribute filename i find docs description methods how upload file google docs api,1 think like def map function iterable return functionx x iterable in x sortedmapint datsplit function int named evaluated this code provides function object map function the map function evaluate given function,if following code exactly following documentation mapfunction iterable x sortedmapint datsplit is int function expressed,1 sounds like time redesign program replace list defaultdictnone mapping objects list node properties call node get node object x nodex you get list nodes unordered nodevalues o time number objects associated node alternatively store node attribute objects none indicating node get nodes xnode x list xnode none takes o n time may faster loop,i two list list contain objects object node property list contain lists node properties objects stored list i want create separate list contain list objects whose node present list i want create list without using loop object list large code takes long time run i use loop how i achieve python,1 assuming working development server mediaurl httplocalhostmedia calculated paths django site used starting points various paths djangoroot ospathdirnameospathrealpathdjangofile siteroot ospathdirnameospathrealpathfile projectroot ospathdirnamefile templatedirs ospathjoinsiteroot templates mediaroot ospathjoinsiteroot templatesmedia the solve problem iot worked fine while referring css files kept templatesmedia link hrefmediacssbasebasecss relstylesheet typetextcsslink hope helps,i downloaded template online includes base html file images css file now i would like implement django so far i tried like good results page gets rendered without css file without images well something wrong settingspy mediaroot rel resources mediaurl resources basehtml link relstylesheet typetextcss hrefresourcesstylecss i put images css file resources folder templates folder doesnt work please help,1 resubr ed r e e returns e result different logic replace e e resubr ed r e,i trying using python resub match string e character insert curly braces immediately e character lastdigit for example e e e e i seem find correct regex insert desired curly braces for example i properly insert left brace like import x e pattern recompiler e sub z resubpattern e x printsub e correct placement left brace my problem arises using two back references import x e pattern recompiler e sub z resubpattern e x printsub e i want digits removed can anyone point problem thanks help,3 taking internal part server answer containing actualy body structure struct text plain charset iso nil nil bit text html charset iso nil nil quotedprintable alternativeimage gif name gif goomojigmail nil base image png name fpng gtalkfgoomojigmail nil base related image jpeg name avatarairbenderjpg nil nil base mixed next step replace tokens would prepair string transform python types struct structreplace replace using builtin module compiler parse structure import compiler expr compilerparsestructreplace replace eval performing simple recursive function transform expression def transformexpression isinstanceexpression compilertransformerexpression return transformexpressionnode elif isinstanceexpression compilertransformertuple return tupletransformitem item expressionnodes elif isinstanceexpression compilertransformerconst return expressionvalue elif isinstanceexpression compilertransformername return none expressionname nil else expressionname and finally get desired result nested python tuples result transformexpr print result text plain charset iso none none bit text html charset iso none none quotedprintable alternative image gif name gif goomojigmail none base image png name fpng gtalkfgoomojigmail none base related image jpeg name avatarairbenderjpg none none base mixed from recognize different headers body structure text attachments result result,i looking simple way split parenthesized lists come imap responses python lists tuples i want go bodystructure text plain charset iso nil nil quotedprintable nil nil nil nil bodystructure text plain charset iso none none quotedprintable none none none none,1 you simulate web browser python without using much resources mechanize debianubuntu package called pythonmechanize it handles cookies submitting forms way web browser would one great example python dropbox uploader script transform needs,i trying use code read kent korner formbased authentication at least i told web site i trying read formbased authenticated but i seem able get past login page the code i using import urllib urllib cookielib string configure opener handle cookies opener urllibbuildopenerurllibhttpcookieprocessor urllibinstallopeneropener use opener post login form protected page params urlliburlencodedictusername user password stuff f openeropen httpwwwhammernutritioncomforumsmemberlistphpmodeviewprofileampu params data fread fclose f openeropen httpwwwhammernutritioncomforumsmemberlistphpmodeviewprofileampu data fread fclose,2 your brace placement incorrect here solution ensuring number optional decimal place e import samples e e samples print resubr dde gegs yields e e,i trying using python resub match string e character insert curly braces immediately e character lastdigit for example e e e e i seem find correct regex insert desired curly braces for example i properly insert left brace like import x e pattern recompiler e sub z resubpattern e x printsub e correct placement left brace my problem arises using two back references import x e pattern recompiler e sub z resubpattern e x printsub e i want digits removed can anyone point problem thanks help,1 you regex import aattaatctatatattgaaatggggccccaattttcccaaatc mstart mend refinditer aatatgtttatc refinditer searches multiple nonoverlapping matches regex returns matchobject one the start end methods match object give start end index matched string the regex searches aat followed anything including first occurrence atg ttt atc you may need construct regex dynamically know start amp end strings program runs pretty simple start aat end atg ttt atc regex ss start joinend,imagine long string characters aattaatctatatattgaaatggggccccaattttcccaaatc i define strings aat atg ttt atc my mission find end point every string aat long string characters my end points three last strings atg ttt atc means i need find index start position aat end position either atg ttt atc i told advance steps im sure i tried openopentext uopenread stringaat true pufindstringp pp mylistappendp print mylist print locations strings atg textfile im sure move i guess could find positions strings well i create function starts atg stops meets one end points hope somehow understandable,1 given rigor shown analysis i surprised results thus far i put answer long comment provide possibility though i expect considered i would thought numpypython approach add much overhead matrix reasonable complexity since complexity increases proportion python participates small i interested results right hand side graph orders magnitude discrepancy shown would disturbing i wonder using best algorithms numpy leverage from compilation guide linux build fftw scipy versions numpy because license configuration maintenance issues support fftw removed versions scipy numpy instead uses builtin version fftpack there couple ways take advantage speed fftw necessary analysis downgrade numpyscipy version includes support install create wrapper fftw see httpdeveloperberliosdeprojectspyfftw unendorsed example did compile numpy mkl httpsoftwareintelcomenusarticlesintelmkl if running linux instructions compiling numpy mkl httpwwwscipyorginstallingscipylinuxheadceaeccfceddadbfff spite url the key part mkl librarydirs optintelcomposerxespmkllibintel includedirs optintelcomposerxespmklinclude mkllibs mklintellpmklintelthreadmklcore if windows obtain compiled binary mkl also obtain pyfftw many related algorithms httpwwwlfduciedugohlkepythonlibs debt gratitude christoph gohlke laboratory fluorescence dynamics uc irvine caveat either case many licensing issues aware intel page explains again i imagine considered meet licensing requirements linux easy would speed numpy part great deal relative using simple automatic build without even fftw i interested follow thread see others think regardless excellent rigor excellent question thanks posting,i would like write program makes extensive use blas lapack linear algebra functionalities since performance issue i benchmarking would like know approach i took legitimate i speak three contestants want test performance simple matrixmatrix multiplication the contestants numpy making use functionality dot python calling blas functionalities shared object c calling blas functionalities shared object scenario i implemented matrixmatrix multiplication different dimensions runs increment matricies set like numpyrandomrandiiastypenumpyfloat numpyrandomrandiiastypenumpyfloat numpy the code used looks like tnumpy timeittimernumpydotm import numpy main import rnumpyappendi tnumpyrepeat python calling blas shared object with function blaslib ctypescdllloadlibrarylibblasso def mulm r notrans ccharn n cinti one cfloat zero cfloat blaslibsgemmbyrefnotrans byrefnotrans byrefn byrefn byrefn byrefone mctypesdataasctypescvoidp byrefn mctypesdataasctypescvoidp byrefn byrefzero rctypesdataasctypescvoidp byrefn test code looks like r numpyzerosii numpyfloat tblas timeittimermulm r import numpy main import r mul rblasappendi tblasrepeat c calling blas shared object now c code naturally little longer i reduce information minimum i load function void handle dlopenlibblasso rtldlazy void func dlsymhandle sgemm i measure time gettimeofday like gettimeofdayampstart null fampnotrans ampnotrans ampdim ampdim ampdim ampone a ampdim b ampdim ampzero return ampdim gettimeofdayampend null dtimesj calctimestart end j loop running times i calculate time passed double calctimetimeval start timeval end double factor return doubleendtvsec factor doubleendtvusec doublestarttvsec factor doublestarttvusec factor results the result shown plot questions do think approach fair unnecessary overheads i avoid would expect result would show huge discrepancy c python approach both using shared objects calculations since i would rather use python program could i increase performance calling blas lapack routines download the complete benchmark downloaded jf sebastian made link possible,3 it hard say exactly without seeing warning likely caused macros python headers to safe compile code uses python boostpython fnostrictaliasing,i defined enummytypemytype valueone valuetwo boostpythonmodule i expose class function taking parameter type mytype essentially int like void myfuncmytype i get following compiler warning dereferencing pointer p whatever break strictaliasing rules warning code works perfectly optimization enabled may i safely ignore warning i missing something thank,1 see answer opencv drawing rectangle matching you exactly problem matchtemplate returns kind similarity map instead single match position,i using opencv python bindings i trying use template match performing exactly i need if image matching template i supply i want return match it seems always return match whether actual template exists image i supply i looked documentation opencv python seem find mention set minimum threshold matching templates i need relatively strict comparing template image image loadimagecimagepng template loadimagecimagecroppng wh getsizeimage wh getsizetemplate width w w height h h result createimagewidth height matchtemplateimage template result cvtmccorr minx maxy minloc maxloc minmaxlocresult x minloc print result,1 i trying compare date string format like benchmark datetimedatetimestrptime ymd actualdate datetimedatetimestrptime ymd actualdatedate benchmarkdate print true,here little snippet i trying execute datetime import itemdate datetimestrptime mdy fromdate datetodaytimedeltadays print typeitemdate type datetimedatetime print typefromdate type datetimedate itemdate fromdate print item newer traceback recent call last file stdin line module typeerror compare datetimedatetime datetimedate i seem compare date datetime values what would best way compare should i convert datetime date viceversa how convert a small question seems little confusing,3 why create function fun save signal copies image file whereever want creates new object new image field modelspy class objectonemodelsmodel logo modelsimagefield class objecttwomodelsmodel logo modelsimagefield djangodbmodelssignals import postsave signals import mysignal postsaveconnectmysignal dispatchuid signalspy models import objectone objecttwo def mysignalsender instance args kwargs sender objectone newobj objecttwo newobjlogosavecustompathnewfilenamejpgfileopeninstanceimageurlw newobjsave i tested image copying code general idea there programmatically saving image django imagefield django add image imagefield image url manually assign imagefield django,i django model object normal attributes imagefield logo i want write method copy object new object it easy enough instanciate new object loop attributes copy old new eg newobjectname oldobjectname however i logo field ie newobjectlogo oldobjectlogo newobject oldobject point file harddisk if edit old file logo new object change what best way fulldeep copy imagefield i want different file name point different file disk exactly content,1 inv nextil totalm invmaturityamount and may set default maturityamount field and better use db aggregation djangodbmodels import sum totalm investmentobjectsfilterplan planorderby financialinstitution filtermaturitydateyearnextyearaggregatesum maturityamount,im trying add values values nonetype value now i looked question i need help im hoping someone explain i get work django here loop viewspy nextil investmentobjectsallfilterplan planorderby financialinstitution filtermaturitydateyearnextyear inv nextil totalm invmaturityamount now invmaturityamount value i trying handle nonetype any suggestions would greatly appreciated thanks steve,3 after checking link seems likely explanation empty row on line set loop go results query in python means list itemitemitem time go loop row variable points next item within loop checking contents current item each items tuple suppposedly least two entries but items entry row row get index range exception you posted enough code make determining occurred feasible get code running i suggest row curexecuteselect frames try print row strrowencode hex except indexerror e print indexerror formate that continue across entire query result even bad edit i saw update problem c hold contents query cexecute select ip item name host returns list ignore the original example works get list loop anonymous variable within loop context to fix code c conncursor rows cexecute select ip item name host row rows print row strrowencode hex,this follow python converting hex intchar i working solution converting stored hex value ip sqlite db readable usable format however i testing copying pasting values directly sqlite db viewer i trying poll db script lookup information however i discovered apparantly stores blob data buffer instantly human readable for example ip stored blob type field ip x ca since i worked copied pasted example code i constructed code strip x hex able convert what i cannot get value database x ca value i view db manager searching i found httpelithegreenplacenetstoringblobsinasqlitedbwithpythonpysqlite showed example reading blobs sqlite db methods work they displayed error print row strrowencode hex indexerror tuple index range i fairly new python apologies i missing something basic pointers code examples anyone help get head around would appreciated edit doh paste code example c conncursor cexecute select ip item name host row c print row strrowencode hex it may understanding thats really i read back way i want update using answer i modified code rows cexecute select ip item name host row rows print strrowencodehex,2 my websockify project support python the websocketpy module websockify built implements generic python websocket server it currently requires numpy module want use new versions hybi protocol i probably implement slower generic fallback next couple days you also might able use pywebsocket get running python pywebsocket really reference implementation websockets chrome mozilla test,i searching websocket server implementation python there projects web run httpcontext i need server started command line httpserver no httphandler object available ideally code require bigger third partyproject like twisted tornado any ideas concrete description use case my network contains several python servers web servers every python servers logs runtime information logger now i want able listen logs within browser websocket seems interesting solution,1 well case class try map different table to solve create class dynamically table class tableobject tableid primarykey pktype satypesstring def initself selfmappedclass type tempclass object but i would prefer slightly cleaner version class tableobject def initself tableid pkname pktype selftableid tableid selfprimarykey pkname selfpktype pktype selfmappedclass type class selftableid object wiwtbl tablewiwtbl portaluserid satypesstring locationstbl tablelocationstbl locationcode satypesinteger,i trying create program loads tables database i change appearances user user id rather map tables individually i decided use loop map tables using array objects this way table definitions stored config file later updated here code far def initmodelengine call using tables classes model metasessionconfigurebindengine metaengine engine class table tableid primarykey pktype satypesstring class mappedclassobject pass wiwtbl table locationstbl table wiwtbltableid wiwtbl wiwtblprimarykey portaluserid wiwtblpktype satypesstring locationstbltableid locationstbl locationstblprimarykey locationcode locationstblpktype satypesinteger tablelist wiwtbl locationstbl tablelist itableid satableitableidupper metametadata sacolumniprimarykey ipktype primarykeytrue autoloadtrue autoloadwithengine ormmapperimappedclass itableid the error code returns sqlalchemyexcargumenterror class class changeofnamemodelmappedclass already primary mapper defined use nonprimarytrue create non primary mapper clearmappers remove current mappers classes i cant use clearmappers wipes classes entityname scheme seem apply it seems every object wants use class although instance does anyone ideas i stuck hours,1 all names python references and references eg c sense available you need pass mutable object mutate function but returning new values preferred way,is way hack push python function def return results reference even immutable types a proposal application swap subroutine def swapa b ab ba note def swapa b return ba works function answer question for example function randomshufflea works inplace my idea call function written fortranc call via python it work disadvantages note both lambda def function following problem b swapa b requires care order variables in proposal possible subroutine used swapa b requirement care order variable,2 def generateysize xsize ycenter xcenter radius x nparangexsizenone nparangeysizenone return xcenter x ycenter radius generate array,is possible generate numpy matrix circular pattern rest matrix so basically generateysize xsize ycenter xcenter radius should look something like ok looks stupid x scale would make sense is possibility numpy,3 no things exist get given object reference reassign changed back you either work mutable container list dict object attributes case,is way hack push python function def return results reference even immutable types a proposal application swap subroutine def swapa b ab ba note def swapa b return ba works function answer question for example function randomshufflea works inplace my idea call function written fortranc call via python it work disadvantages note both lambda def function following problem b swapa b requires care order variables in proposal possible subroutine used swapa b requirement care order variable,2 in python way pass write pointer you pass object name callee use example setattr pass list index there thing context free address modifiable cell names indexes however also need context namespace array in general case really need pass write pointer solution python pass setter function used callee set value for example def foosetter setter def bar x def setfirstvalue x value foosetfirst print x,is way hack push python function def return results reference even immutable types a proposal application swap subroutine def swapa b ab ba note def swapa b return ba works function answer question for example function randomshufflea works inplace my idea call function written fortranc call via python it work disadvantages note both lambda def function following problem b swapa b requires care order variables in proposal possible subroutine used swapa b requirement care order variable,1 i sure wrong it looks like work i copied put runnable example works windows import wx class myformwxframe def initself wxframeinitself none wxidany tutorial panel wxpanelself wxidany selfct selfphaseselection selfopselection selfinstselection selforgselection phaseslist preoperations inoperations postoperations selfcombo wxcomboboxpanel choicesphaseslist selfcombobindwxevtcombobox selfoncombo sizer wxboxsizerwxvertical sizeraddselfcombo panelsetsizersizer def oncomboself event selfphaseselection selfcombogetvalue print selfphaseselection run program name main app wxappfalse frame myformshow appmainloop,i working design gui using wxpython pecie code class fram declaration also declared variables wanna chage values based comboboxes selection folowing class mymenuwxframe def initself parent id title wxframeinitself parent id title size selfct selfphaseselection selfopselection selfinstselection selforgselection panel wxpanelself panelsetbackgroundcolour f phaseslist preoperations inoperations postoperations selfcbphases wxcomboboxpanel phase phaseslist wxcbdropdown selfbindwxevtcombobox selfonphaseselection id selfcbphasesgetid code onphaseselection event def onphaseselectionself event selfphaseselection selfcbphasesgetvalue wanna save selected value variable selfphaseselection declared empty string initial value wanna use variable new saved value run program variable contains default value combobox please problem work,1 it looks like bugs converting tofrom numpy mode if convert l first works fine im bmpimagepluginbmpimagefile image mode sizex xfe im imconvert l numpyasarrayim array dtypeuint also try convert bool numpy array pil get strange results testarr numpyarraytruefalsetruefalse dtypenumpybool testpil imagefromarraytestarr mode numpyasarraytestpil arrayfalse false false false dtypebool however exact thing uint works fine testarr numpyarray dtypenumpyuint imagefromarraytestarr imageimage image model sizex xb numpyasarrayimagefromarraytestarr array dtypeuint so i would suggest using l intermediate datatype converting saving need save format something like im bmpimagepluginbmpimagefile image mode sizex xfe im imconvert l arr numpyasarrayim arr array dtypeuint arr arr arr arrayfalse true true false dtypebool then convert back backarr numpyzerosarrshape dtypenumpyuint backarrarr backarr array dtypeuint imagefromarraybackarrconvert imageimage image mode sizex xbcb,i new image processing python met strange problem for example i blackwhite bitmap image pixels following black white white black use pil convert numpy import image import numpy im imageopen testbmp im bmpimagepluginbmpimagefile image mode sizex xaec numpyasarrayim array true true false false dtypebool what puzzles order pixel array why true false false true thanks update bitmap httpnjuerusclippittestbmp,1 reloading code python notoriously difficult problem here i would deal server startup listen http port start accepting connections use multiprocessing create worker processes happen socket starts listening subprocesses inherit socket worker accept connections service requests parent process learns reload shuts listening socket worker tries accept closed socket recieves socketerror exception terminate parent process start new main process subprocesspopensysargv new process start accepting connections immediately old process wait child workers finish children cannot accept new connections since listening socket shutdown once child process finished handling inflight requests closed parent process also terminate,multiprocessing import process aprocesstargetworker args astart i making multiple workerprocess app laugh yet worker gracefully reload whenever code updated new requests served new worker processes new code this a newly launched thread contains updated code ensure requests dropped i already made worker listens serves requests gets aa request signal kills next signal control signal i zeromq the clients connect server using zeromq the clients interact http what good way reload code can explain scheme simple stupid enough robust what i mind launch thread within main process iterates signal every worker process die launch new worker processes but approach drop i configured way requests death last old worker spawning first new worker and i college student the homework means curiositydriven pursuit,1 by l randomchoicecrandomchoicen limiting randomchoicel possible chars one list c n try instead random import random choice hello world c b c e f n l choicec n randomly choose either c n return join ss x choicel random else x as aside assuming want keep probability insertion also written char either append empty string random char list return join ss x choicechoicel x update note answer chooses substitution list c n uses whole process if want able use lists substitution either create intermediate list l c n perform list selection inline this rather convoluted return join ss x choicechoicechoicec n x alternatively e tuple single empty element return join ss x choicechoicec n e e x choose c n empty list e e appears twice keep nonempty probability change required from chosen listtuple choose random element,here code hello world c b c e f n l randomchoicecrandomchoicen return join ss x randomchoicel randomrandom else x this output helloe worlde but i aiming something like code would produce hello world n return join ss x randomchoicen randomrandom else x which hello world it would great someone could also explain two reacting differently i would assumed sorry i stated intentions i would like randomly select element two lists iteration loop within join instead i elements selected randomly choosing two elements selected this i want n l randomchoicen randomchoices hello world this i want n etc etc code randomly select list new element list hello world not sure i worded correctly hopefully understandable,3 you really use math module way c toyschemacontact clat clat import math mathcosclat mathcostoyschemacontactlat traceback recent call last file stdin line module typeerror float required you combine sqalchemyfunc place math greatcircledistanceexpression method kind cleverness unfortunately sqlite either provide trig functions you could use postgresql try add functions sqlite edit it actually hard add functions sqlite this not tested have add math functions sqlite engine sqlalchemycreateenginesqlitememory rawcon enginerawconnection rawconcreatefunctioncos mathcos rawconcreatefunctionacos mathacos class location hybridmethod def greatcircledistanceself tries calculate great circle distance two locations using haversine formula if succeeds return haversine formula multiplied calculates distance miles if cannot return none return mathacos selfcosradlat othercosradlat mathcosselfradlng otherradlng selfsinradlat othersinradlat greatcircledistanceexpression def greatcircledistancecls return sqlalchemyfuncacos clscosradlat othercosradlat sqlalchemyfunccosclsradlng otherradlng clssinradlat othersinradlat,i using python sqlalchemy store latitude longitude values sqlite database i created hybrid method location object hybridmethod def greatcircledistanceself tries calculate great circle distance two locations if succeeds return greatcircle distance multiplied calculates distance miles if cannot return none return mathacos selfcosradlat othercosradlat mathcosselfradlng otherradlng selfsinradlat othersinradlat all values like cosradlat sinradlat values i precalculated optimize calculation anyhow i run following query pq sessionquerymodellocationfiltermodellocationgreatcircledistanceloc i get following error line greatcircledistance mathcosselfradlng otherradlng typeerror float required when i print values selfradlng otherradlng i get example selfradlng locationradlng otherradlng what i wrong,2 the failing email contentdisposition set headers attachment skipping looks like going relax statement checks contentdisposition bit maybe could look see contenttype imagejpeg work,so i tried code downloads attachments alright the problem gmail account emails sent using mms mail mobile phone email attachments mobile network a downloaded script came mobile network b fails here links full email details httppastieorgprivateektvyfaxwdqzuysa from mobile network a works httppastieorgprivatecljaaadtzvjralq from mobile network b fails grabbed how i download emails attachments gmail import email getpass imaplib os detachdir directory save attachments default current user rawinputenter gmail username pwd getpassgetpassenter password connecting gmail imap server imaplibimapsslimapgmailcom mloginuserpwd mselectgmailall mail choose mail box like inbox instead use mlist get mailboxes resp items msearchnone all could filter using imap rules check httpwwwexamplecodecomcsharpimapsearchcriteraasp items itemssplit getting mails id emailid items resp data mfetchemailid rfc fetching mail rfc means get whole stuff ask headers etc emailbody data getting mail content mail emailmessagefromstringemailbody parsing mail content get mail object check attachments mailgetcontentmaintype multipart continue print mailfrom mailsubject use walk create generator iterate parts forget recursive headach part mailwalk multipart containers skip partgetcontentmaintype multipart continue part attachment partget contentdisposition none continue filename partgetfilename counter filename create one counter avoid duplicates filename filename partds counter bin counter attpath ospathjoindetachdir filename check already ospathisfileattpath finally write stuff fp openattpath wb fpwritepartgetpayloaddecodetrue fpclose,2 is essential keep every even line fact define even counting first row image if mind rows dropped use pil pil import image imgimageopenfilepng sizelistimgsize size size downsizedimgresizesize imagenearest nearest drops lines downsizedsavefilesmallpng,let assume image stored png file i need drop every odd line resize result horizontally order keep aspect ratio the result must resolution original image it enough recommend existing image library like pil i would like see working code update even question received correct answer i want warn others pil great shape project website updated months link bug traker list activity quite low i surprised discover simple bmp file saved paint loaded pil,1 indentation level statements significant python,refer listing iteration dictionary zero tuple two one k diterkeys printdk file stdin line printdk indentationerror expected indented block why,2 even using python interactive interpreter need make sure indentation new block code this k diterkeys printdk should k diterkeys printdk as aside link number errors expected output possibly copypaste problem,refer listing iteration dictionary zero tuple two one k diterkeys printdk file stdin line printdk indentationerror expected indented block why,1 python iterkeys just use k printdk even better v dvalues printv,refer listing iteration dictionary zero tuple two one k diterkeys printdk file stdin line printdk indentationerror expected indented block why,2 scala equivalent commands curl httpsrawgithubcomnhanconscriptmastersetupsh sh bincs nhangiter bing scalatrascalatrasbt namescalatraexample cd scalatraexample wget httptypesafeartifactoryonlinecomtypesafeivyreleasesorgscalatoolssbtsbtlaunchsbtlaunchjar java xmxm jar sbtlaunchjar jettyrun using play step download play play install scala play new myproject scala play run myproject,the following possible using python aptget install python easyinstall flask cat hellopy flask import flask app flaskname approute def hello return hello world name main apprun python hellopy commands lines code get web server running impressive indeed what scala equivalent,1 here answer… problem form recipient object instead campaign object… furbeenator answer good step right direction… along help django irc class recipientsformformsmodelform def initself args kwargs selfcampaign kwargspop campaign none superrecipientsform selfinitargs kwargs selfinstance selfcampaign selffields recipients formsmodelmultiplechoicefield querysetpersonobjectsfilterqidinselfcampaignrecipientsall widgetformswidgetscheckboxselectmultiple label recipients helptext pick recipients add campaign requiredfalse elif selfcampaign selffields recipients formsmodelmultiplechoicefield querysetpersonobjectsfilterqidinselfcampaignrecipientsall widgetformswidgetscheckboxselectmultiple label recipients helptext pick recipients add campaign requiredfalse else pass def saveself forceinsertfalse forceupdatefalse committrue recipients selfcleaneddata recipients person recipients recipient recipientcampaignselfcampaignpersonperson recipientsave class meta model campaign fields recipients,i following basic model… class campaignmodelsmodel name modelscharfield name maxlength uniquetrue recipients modelsmanytomanyfield person blanktrue nulltrue recipient class recipientmodelsmodel campaign modelsforeignkeycampaign person modelsforeignkey person class personmodelsmodel firstname modelscharfield first name maxlength blanktrue lastname modelscharfield last name maxlength blanktrue i like queryset queries person objects within given campaign it nice easy personobjectsallexcludemycampaignrecipientsall know work to specific i trying get work form class follows q object comment seems right i get work… here form class recipientsformformsform def initself campaign args kwargs selfcampaign campaign selfhelper formhelper selfhelperaddinputsubmit submit add cssclass primaryaction selfhelperlayout layout fieldset recipients cssclass inlinelabels return superrecipientsform selfinitargs kwargs recipients formsmodelmultiplechoicefield old queryset querysetpersonobjectsall querysetpersonobjectsfilterqidinselfcampaignrecipientsall widgetformswidgetscheckboxselectmultiple labeladd recipients requiredtrue def saveself forceinsertfalse forceupdatefalse committrue recipients selfcleaneddata recipients person recipients recipient recipientcampaignselfcampaignpersonperson recipientsave,1 this may help reason formcleaneddata reason reason dictformfields reason choicesreason,i choicefield i get label i need class contactformformsform reason formschoicefieldchoicesfeature a feature order an order widgetformsradioselect formcleaneddatareason would give feature order,3 you might want try functions strvar reprvar,i search python equivalent following bash code varecho var pseudo python code could var print var can help regards edit i search way dhip open dhipstxt r gi geoipnewgeoipgeoipmemorycache print gicountrycodebyaddrprint dhip line problem in bash would like print gicountrycodebyaddrdhip pseudo code hope clear edit thank here solution works thanks liquidfire remark newline char thanks hop code import geoip fp open dhipstxt r gi geoipnewgeoipgeoipmemorycache try dhip fp print gicountrycodebyaddrdhiprstripn finally fpclose,1 when make subquery select statement columns accessed must columns clause take example statement like select x mytable z if wanted make subquery group by z would legal sql select select x mytable z mysubquery group mysubqueryz because z columns clause mysubquery also illegal since x group by well different issue sqlalchemy works exact way when say querysubquery use alias function core selectable construct means wrapping select statement parenthesis giving usually generated name giving new c collection columns columns clause like real sql so need ensure tableb least column dealing externally available you also limit columns clause columns need sq sessionquerytableaattra tablebattrbjointableb groupbytablebattrbsubquery counta funccountsqcattra groupb funcfirstsqcattrb print sessionquerycounta groupball note query probably works mysql general sql illegal reference columns part aggregate function part group by grouping used mysql relaxed sloppy system regard edit want results without zeros import collections lettercount collectionsdefaultdictint count letter sessionqueryfunccountmyclassid myclassattrgroupbymyclassattr lettercountletter count letter a b c d e print letter elements lettercountletter note lettercountsomeletter defaults zero otherwise populated,all i want count tablea grouped column tableb course i need item tableb count associated better explained code tablea b model objects i trying follow syntax best i trying run query sq sessionquerytableajointableb groupbytablebattrbsubquery counta funccountsqcattra groupb funcfirstsqcattrb print sessionquerycounta groupball but gives attributeerror sq attrb i new sa i find difficult learn links recommended educational resources welcome,1 use first want know location file executed use second want know process current working directory,from code returns output when i use one import os ospath import abspath dirname print abspathdirnamefile print osgetcwd ps i wanted use dynamically changing path logs static files templates django project run different environments,2 open file access functions care syspath it used importing modules create variable contains path contains files use,i directory structure like following analytics conf script src setup source setup setupyaml sqlyaml source src folder a spy spy folder b mpy mpy how i inclue setup files structure source files structure without hardcoding paths i tried syspathappend path i try open file i see error import sys syspathappend usersuserdocumentsworkdwanalyticsconf f open setupyaml r traceback recent call last file stdin line module ioerror errno no file directory setupyaml f open setupyaml r,2 you need print use name variable dhip open dhipstxt r gi geoipnewgeoipgeoipmemorycache print gicountrycodebyaddrdhip also note iterating file object gives lines newline characters end you may want use something like dhiprstripn remove passing countrycodebyaddr,i search python equivalent following bash code varecho var pseudo python code could var print var can help regards edit i search way dhip open dhipstxt r gi geoipnewgeoipgeoipmemorycache print gicountrycodebyaddrprint dhip line problem in bash would like print gicountrycodebyaddrdhip pseudo code hope clear edit thank here solution works thanks liquidfire remark newline char thanks hop code import geoip fp open dhipstxt r gi geoipnewgeoipgeoipmemorycache try dhip fp print gicountrycodebyaddrdhiprstripn finally fpclose,2 just use dhip there need anything special dhip open dhipstxt r gi geoipnewgeoipgeoipmemorycache print gicountrycodebyaddrdhip nb there issues code without familiar library use seems unnecessarily instantiate geoip every iteration loop also throw away file handle close file afterwards fp open dhipstxt r gi geoipnewgeoipgeoipmemorycache try dhip fp print gicountrycodebyaddrdhip finally fpclose or even better use context manager open dhipstxt r fp gi geoipnewgeoipgeoipmemorycache dhip fp print gicountrycodebyaddrdhip,i search python equivalent following bash code varecho var pseudo python code could var print var can help regards edit i search way dhip open dhipstxt r gi geoipnewgeoipgeoipmemorycache print gicountrycodebyaddrprint dhip line problem in bash would like print gicountrycodebyaddrdhip pseudo code hope clear edit thank here solution works thanks liquidfire remark newline char thanks hop code import geoip fp open dhipstxt r gi geoipnewgeoipgeoipmemorycache try dhip fp print gicountrycodebyaddrdhiprstripn finally fpclose,1 newword locally scoped inside createword createword finished newword disappears consider creating newword global scope modify createword better yet let createword return value set newword value i would think printing word using parameter drawit would result thing using variable it want change length dragon curve copypaste string every time instead simply changing value maxit edit my solution sexy recursion import turtle def dragonbuildturtlestring n recursively builds draw string defining f additional rules anything rules x xyf fxy f f turtlestring joinrulesx x turtlestring n return dragonbuildturtlestring n else return turtlestring def dragondrawsize draws dragon curve length size turtlestring dragonbuild fx size x turtlestring x f turtleforward elif x turtleright elif x turtleleft def main n inputsize dragon curve int dragondrawn name main main,i created program draw dragon curve using turtle graphics result really look like picture link one problem i noticed i want save produced string variable newword i use newword parameter function drawit actually draws lines based string when i try i get error global variable newword defined so code i copied output newword drawn without actually passing variable i wanted pass i sure problem createword function i drawing enough drawit import turtle def createwordmaxit axiom procrules word axiom maxit word rewriteword procrules tt newword word def rewriteword procrules wordlist listword rangelenwordlist curchar wordlisti curchar procrules wordlisti procrulescurchar return joinwordlist def drawitnewword angle newwordls listnewword rangelennewwordls curchar newwordlsi curchar f turtleforwardd elif curchar turtlerightangle elif curchar turtleleftangle else sample test dragon curve def main createword fx x xyf y fxy drawit fxyffxyffxyffxyffxyffxyffxyffxyf name main main,2 i think good builtin solution it would easier builtin equivalent haskell scan function but concise enough import itertools collections import defaultdict partitionlengths rangestart rangeend endpoints defaultdictlist plen itertoolscyclepartitionlengths end rangestart plen end rangeend break endpointsplenappendrangestart end rangestart plen endpoints defaultdicttype list you format endpoints dictionary output however like as aside i really confused use set question i used partition instead,for life i see i need collect nonoverlapping endpoints several sets within range numbers python for example user could input range two sets i need get end points sets within range set groupings set groupings the range number sets size individual set arbitrary i cannot fall outside range half sets i keep thinking simple formula i come edit as requested example input range sets output set set set as near i figure i looking kind accumulator pattern something like psuedo code minirange range set sets listofcurrsetendpointsappendstart end,1 ok seems using foreach wrong way try secret fdbbabedcfffad code unia validinstitution array amount code code identifier text validinstitution code validinstitution identifier validinstitution amount secret print strtoupperhashmd text,please i need help getting exact md value python script php the python script def mdcodeparams params identifier amount code unia req dictkey paramsgetkey key code identifier amount secret fdbbabedcfffad text joinreqx x code identifier amount secret return mdtexthexdigestupper the return value dcdabff the php script secret fdbbabedcfffad code unia validinstitution array amount code code identifier foreachvalidinstitution k v text implode vk secret print strtoupperhashmd text the return value ddcdfbeecfe i expecting php script return exact md value any suggestions appreciated thanks,1 i tried extend solution arrays a one dimension supposing process array rowbyrow axis i extended first code loop rows probably improved temp aargsortaxis rank npemptyliketemp rangea nparangetempshape irow xrangetempshape rankirow tempirow rangea and second one following krooijers suggestion becomes temp aargsortaxis rank tempargsortaxis i randomly generated arrays shape first code took second one,i array numbers i like create another array represents rank item first array i using python numpy for example array ranks here best method i come array numpyarray temp arrayargsort ranks numpyarangelenarraytempargsort are betterfaster methods avoid sorting array twice,2 valid python code could look like hashlib import md params identifier amount code unia req dictkey paramsgetkey key code identifier amount secret fdbbabedcfffad text joinreqx x code identifier amount secret print mdtexthexdigestupper equivalent php php secret fdbbabedcfffad code unia validinstitution array code code identifier amount text implode validinstitution secret print strtoupperhashmd text,please i need help getting exact md value python script php the python script def mdcodeparams params identifier amount code unia req dictkey paramsgetkey key code identifier amount secret fdbbabedcfffad text joinreqx x code identifier amount secret return mdtexthexdigestupper the return value dcdabff the php script secret fdbbabedcfffad code unia validinstitution array amount code code identifier foreachvalidinstitution k v text implode vk secret print strtoupperhashmd text the return value ddcdfbeecfe i expecting php script return exact md value any suggestions appreciated thanks,1 here another benchmark linux type make httpdldropboxcomublascallbenchmarkzip i see essentially difference different methods large matrices numpy ctypes fortran fortran instead c matters benchmark probably broken your calctime function c seems sign error doublestarttvusec instead doublestarttvusec perhaps benchmark also bugs eg comparing different blas libraries different blas settings number threads real time cpu time edit failed count braces calctime function ok as guideline benchmark please always post code somewhere commenting benchmarks especially surprising without full code usually productive to find blas numpy linked python python default aug gcc linux type help copyright credits license information import numpycoredotblas numpycoredotblasfile usrlibpymodulespythonnumpycoredotblasso ldd usrlibpymodulespythonnumpycoredotblasso linuxvdsoso xfffebff libblassogf usrliblibblassogf xfbeb libcso libxlinuxgnulibcso xfbe update if import numpycoredotblas numpy using internal fallback copy blas slower meant used performance computing the reply woltan indicates explanation difference heshe sees numpy vs ctypesblas to fix situation need either atlas mkl check instructions httpscipyorginstallingscipylinux most linux distributions ship atlas best option install libatlasdev package name may vary,i would like write program makes extensive use blas lapack linear algebra functionalities since performance issue i benchmarking would like know approach i took legitimate i speak three contestants want test performance simple matrixmatrix multiplication the contestants numpy making use functionality dot python calling blas functionalities shared object c calling blas functionalities shared object scenario i implemented matrixmatrix multiplication different dimensions runs increment matricies set like numpyrandomrandiiastypenumpyfloat numpyrandomrandiiastypenumpyfloat numpy the code used looks like tnumpy timeittimernumpydotm import numpy main import rnumpyappendi tnumpyrepeat python calling blas shared object with function blaslib ctypescdllloadlibrarylibblasso def mulm r notrans ccharn n cinti one cfloat zero cfloat blaslibsgemmbyrefnotrans byrefnotrans byrefn byrefn byrefn byrefone mctypesdataasctypescvoidp byrefn mctypesdataasctypescvoidp byrefn byrefzero rctypesdataasctypescvoidp byrefn test code looks like r numpyzerosii numpyfloat tblas timeittimermulm r import numpy main import r mul rblasappendi tblasrepeat c calling blas shared object now c code naturally little longer i reduce information minimum i load function void handle dlopenlibblasso rtldlazy void func dlsymhandle sgemm i measure time gettimeofday like gettimeofdayampstart null fampnotrans ampnotrans ampdim ampdim ampdim ampone a ampdim b ampdim ampzero return ampdim gettimeofdayampend null dtimesj calctimestart end j loop running times i calculate time passed double calctimetimeval start timeval end double factor return doubleendtvsec factor doubleendtvusec doublestarttvsec factor doublestarttvusec factor results the result shown plot questions do think approach fair unnecessary overheads i avoid would expect result would show huge discrepancy c python approach both using shared objects calculations since i would rather use python program could i increase performance calling blas lapack routines download the complete benchmark downloaded jf sebastian made link possible,3 i believe need pass rpc object dictionary speaks obtained via getresult function rpc object,ho use memcache getmultiasync doc says returns dictionary values httpcodegooglecomappenginedocspythonmemcacheclientclasshtmlclientgetmultiasync i expecting return kind async object getresult later am missing something,2 so looking sdk source appears reversereferenceproperty translates collections query objects make attempt handle polymodels there related complaints issue tracker imo known limitation ought mentioned somewhere polymodel docs edit the collectionless workaround would something like mymodeloneallfilter container c,i trouble using dbreferenceproperty polymodel gae if i two models derived base polymodel one reference another container model collections container contain polymodels one would expect here test case shows problem googleappengineext import db googleappengineextdb import polymodel class mycontainerdbmodel name dbstringpropertydefault mycontainer multilinefalse class mybasemodelpolymodelpolymodel name dbstringpropertydefault mybasemodel multilinefalse class mymodelonemybasemodel container dbreferencepropertymycontainer collectionname modelones class mymodeltwomybasemodel container dbreferencepropertymycontainer collectionname modeltwos print beginning testn c mycontainernamecontainer cput one mymodelonenameone containerc two mymodeltwonametwo containerc oneput twoput print ones cmodelones print oname print ntwos cmodeltwos print oname and output beginning test ones one two twos one two am i missing something setting referenceproperties expected behavior,1 use datetime parse string convert base epoch time do math convert back datetime import datetime ddatetimestrptimes ymdims ddatetimestrptimes ymdims dd datetimetimedelta ddtotalseconds if looking arbitrary date string parsing check dateutil parse function,i two date strings taken user input vary greatly i wish find difference two minutes how i proceed tackle,1 using datetime module parse datetime object using strptime subtract you get timedelta then use timedeltatotalseconds divide,i two date strings taken user input vary greatly i wish find difference two minutes how i proceed tackle,2 what somefunction returns different values time called import random x randomrandom randomrandom,a quote something x somefunction somefunction x question is x somefunction x somefunction somefunction based understanding somefunction return exactly one value,3 they necessarily work somefunction returns mutable value consider def somefunction return x somefunction xappend x x somefunction somefunction xappend x,a quote something x somefunction somefunction x question is x somefunction x somefunction somefunction based understanding somefunction return exactly one value,3 import datetime datetimedatetimestrptime ymdhms datetimedatetimestrptime ymdhms diff dtotalseconds if need handle arbitrary datetime formats i believe built datetime library perhaps check something like httpwwwegenixcomproductspythonmxbasemxdatetime,i two date strings taken user input vary greatly i wish find difference two minutes how i proceed tackle,1 assuming financialinstitution model name field i think could add list values asking totallist planinvestmentsetfilter maturitydategte currentyear values financialinstitution financialinstitutionname annotatesum maturityamount,initially i asked question i wanted give credit daniel here new issue i however i works great i minor issue totallist planinvestmentsetfiltermaturitydategte currentyearvalues financialinstitution annotatesum maturityamount i trouble displaying financial institution name when i loop total list put loopvariablefinancialinstitution shows id name any ideas fix,1 if use kronecker product turn every pixel x submatrix enable get rid python loops im npkronim npones dm nptileditheringmatrix im splitnum dm on machine roughly x faster version,i working assignment converting grayscale image bit binary image dithering i trying simple x matrix make image times larger original ditheringmatrix array dtypeuint splitnum ditheringmatrixsize i read x image im ndarray following things output list row im rowoutput list pixel row pixelmatrix pixel splitnum ditheringmatrix rowoutputappendpixelmatrix outputappend hstack tuplerowoutput outputmatrix vstack tupleoutput i found took output i think loop im spent much time in software operation usually done flash so possible improve efficiency update ignacio vazquezabrams i vert fimiliar profiler i tried cprofile result strange function calls primitive calls seconds ordered internal time list reduced due restriction ncalls tottime percall cumtime percall filenamelinenofunction apymodule numpycoremultiarrayconcatenate dpythonlibsitepackagesnump ycoreshapebasepyatleastd numpycoremultiarrayarray dpythonlibsitepackagesnump ycorenumericpyasanyarray map method append list objects the line apy first line numpy import comments really puzzles,3 looks like gstelement generate newsegment events simply attach existing element the closest thing could using python would creating single shot periodic gstclockid use gstclockidwaitasync clock time hit but problem gstclockid wrapped pygst i think i actually working similar problem some kind solution i using gluing video streams real time gnonlin the good side seems work time thoroughly test yet bad side poorly documented buggy these sources flumotion project comments inside helpful understanding make whole thing work,i using python pygtk pygst gstreamer to ensure smooth playback one clip another without blink i combined clips i needed one larger video this lets seek exact place i need code one clips like fillin loop whenever one clips playing however make code easier streamlined i want use segments define various clips within larger video then end segment i know segment end event i seek fillin clip when i need another clip i seek segment my question exactly i create segments i guessing would eventnewnewsegment i sure can i create multiple clips seek using function is another i use are gotchas method seeking video i aware second i seek segement thank,1 you exit program raising systemexit this exit someone incorrectly written exception handler catches exceptions this catch exceptions handle,def main try print hardfart return except return name main exitmain can one kind programmer tell spits following error exit traceback recent call last file cappsexpexitpy line module exitmain file cappspythonlibsitepy line call raise systemexitcode systemexit this causing error exit project set similarly for project using guiexe compile exe closing program i get related error traceback recent call last file checkhdboxpy line module nameerror name exit defined so exit generating error i exit and i create exception handler exit replace default action python takes exit function thanks edit i think answers question the traceback idle i think default behavior sources i read traceback recent call last file cappsexpexitpy line module exitmain file cappspythonlibsitepy line call raise systemexitcode systemexit the traceback fixed using sysexit instead exit traceback recent call last file checkhdboxpy line module nameerror name exit defined,1 i managed integrate cxase custom imap class took care problems here code anyone reading class imapconnection def initself selfimap imaplibimapsslimapgmailcom def login self login helpdesk google apps email account using encryption selfimaploginbasebdecodeusername basebdecodepassword def logout self selfimaplogout def getunread self check connection status ok try uc intresearchunseen selfimapstatusinbox unseengroup uc intresearchunseen selfimapstatusa box unseengroup uc intresearchunseen selfimapstatusa box unseengroup except imapabort reinstantiate connection login selfimap imaplibimapsslimapgmailcom selflogin retry unread update block uc intresearchunseen selfimapstatusinbox unseengroup uc intresearchunseen selfimapstatusa box unseengroup uc intresearchunseen selfimapstatusa box unseengroup is helpdesk negative hell unreadcount ucucucucuc unreadcount unreadcount return unreadcount,i programming python applet watches unread count email boxes workplace ran eof error i try use imaplib methods applet sits idle minutes everything works fine applet alive minutes here relevant code imaplib object conn imaplibimapsslimapgmailcom def loginimap imapobj login helpdesk google apps email account using encryption imapobjloginbasebdecodeusrencryption basebdecodepwdencrytion returngetunreadimapobj def closeimap imapobj imapobjlogout def getunread imapobj check connection status ok try uc intresearchunseen imapobjstatusinbox unseengroup uc intresearchunseen imapobjstatusa box unseengroup uc intresearchunseen imapobjstatusa box unseengroup except print shit disconnected n stuff loginimapconn unreadcount ucucucucuc unreadcount unreadcount return unreadcount usrencryption pwdencryption masking helpdesk logins public when i try call getunreadconn applet open ten minues i get following output traceback recent call last file cjamin sappsdevelopmentprojectscheck hd boxcheckhdboxpy line onrefresh unread getunreadconn file cjamin sappsdevelopmentprojectscheck hd boxcheckhdboxpy line getunread uc intresearchunseen imapobjstatusinbox unseengroup file cjamin sappsdevelopmentpythonpythonlibimaplibpy line status typ dat selfsimplecommandname mailbox names file cjamin sappsdevelopmentpythonpythonlibimaplibpy line simplecommand return selfcommandcompletename selfcommandname args file cjamin sappsdevelopmentpythonpythonlibimaplibpy line commandcomplete raise selfabort command name val imaplibabort command status socket error eof traceback recent call last file cjamin sappsdevelopmentprojectscheck hd boxcheckhdboxpy line onrefresh unread getunreadconn file cjamin sappsdevelopmentprojectscheck hd boxcheckhdboxpy line getunread uc intresearchunseen imapobjstatusinbox unseengroup file cjamin sappsdevelopmentpythonpythonlibimaplibpy line status typ dat selfsimplecommandname mailbox names file cjamin sappsdevelopmentpythonpythonlibimaplibpy line simplecommand return selfcommandcompletename selfcommandname args file cjamin sappsdevelopmentpythonpythonlibimaplibpy line command raise selfabort socket error val imaplibabort socket error errno an established connection aborted software host machine the exception block doesnt really seem work problem i really need help so i keep connection alive kicking thanks,2 i working little java utils library called jools contains class range provides functionality need downloadable jar constructors either rangeint stop rangeint start int stop rangeint start int stop int step similiar loop either iterate used lazy evaluation use tolist method explicitly get range list int new range int new range int new range range range new range rangetolist,does java equivalent python rangeint int method,3 wtagbindtable strtablenumber button doevent tag changed tag table strtablenumber callback lambda event tagtag doevent tag wtagbindtag button callback the lambda creates function tag name default value second argument tkinter calls function one argument event second argument uses default value,lets say i created canvas tkinter app in canvas i drawn several rectangles what i want essence know rectangle user clicked main concern i tried i think might solution this layout x range range tablenumber x wcreaterectangletablexseparation tablewidth tablewidth tableyseparation tableheight x tableheight tablexseparation tablewidthy tableyseparation tableheight x fillbrown tagstable strtablenumber wtagbindtable strtablenumber button so creates rectangles rows columns layout each rectangle specific tag form table table table when i click rectangle function executes let say something like def doevent print click not i get click console every click rectangle i would like able get tag clicked rectangle able something like def doevent print strthetagoftheclickedrectangle so i checked events i call widget x xroot yroot char keysym keycode num width height type none seem pin point rectangle i clicked i thought adding parameters function wtagbindtable strtablenumber button doevent tag but seem work fine maybe i right doevent tag work print eventx print tag i hope question clear i got tag manner i get x event would comfortable the actual solution i think working math eventx eventy calculate based coordinates click rectangle user clicked seems overcomplicated i trying though i done obviously works i hope question clear wise please ask clarification note i tied code rather i looking solution problem efficient work even means working tags another type widget whatever easier,1 the dumbo feathers set java classes use together dumbo python library makes easy write efficient python mr programs hadoop output classes basically python dumbo mr job output key tuple two elements first element name directory output second element actual key the output class selected inspects tuple find output directory use use multipleoutputformat write different subdirectories with dumbo easy due use typedbytes output format i think doable even output formats,i read hadoop action found java using multipleoutputformat multipleoutputs classes reduce data multiple files i sure achieve thing using python streaming example outpart mapper reducer outpart if anyone knows heard done similar thing please let know,1 the best way handle problem subclass treemodel assign variable object liststore treemodelfilter class myliststoreobject def initself title filternone selftitle title selfmodel gtkliststoregobjecttypeint gobjecttypestring filterfunc selfmodel selfmodelfilternew selfmodelsetvisiblefuncfilter i think best way get around edit for anyone interested i found following helpful keep breaking old code it acts like inheritance without actually def getattrself name get attribute model possible hasattrselfmodel name return getattrselfmodel name isinstanceselfmodel gtktreemodelfilter hasattrselfmodelgetmodel name return getattrselfmodelgetmodel name,is possible change class c object python subclass i using pygtk i listmodel i wrapped class around i want turn treemodelfilter the directions tell create class myliststoregtkliststore def initself title selftitle title liststore myliststoregobjecttypeint gobjecttypestring modelfilter liststorefilternew so i thought i could create class myfilteredliststoregtktreemodelfilter def initself title selftitle title but i know use filternew use class instead gtktreemodelfilter,1 maybe create function joã£o proposed something like def cursorexeccursor query params expansionparams realparams p params isinstancep tuple list realparamsextendp expansionparamsappend slenp else realparamsappendp expansionparamsappends realquery query expansionparams cursorexecuterealquery realparams,i problem executing sql within python despite similar sql working fine mysql commandline the table looks like mysql select from foo fooid bar a b c d rows set sec i execute following sql query mysql commandline without problem mysql select fooid from foo where bar in a c select fooid from foo where bar in a c fooid rows set sec however i try within python i get rows i expected rows import mysqldb import config connectionmysqldbconnect hostconfighostuserconfiguserpasswdconfigpassdb test cursorconnectioncursor sql select fooid from foo where bar in args a c cursorexecutesqlargs datacursorfetchall printdata so question python code modified select fooid bar a c by way i noticed i switch roles bar fooid i get code select bar fooid successfully i understand one query works one sql select bar from foo where fooid in args cursorexecutesqlargs datacursorfetchall printdata a c and absolutely clear foo table created mysql drop table if exists foo query ok rows affected sec mysql create table foo fooid int not null autoincrement bar varchar not null primary key fooid query ok rows affected sec mysql insert foo bar values a b c d query ok rows affected sec records duplicates warnings edit when i enable general query log mysqld l tmpmyquerylog i see mysqld version ubuntulog ubuntu started tcp port unix socket varrunmysqldmysqldsock time id command argument connect unutbulocalhost test query set autocommit query select fooid from foo where bar in a c query select bar from foo where fooid in quit indeed looks like many quotes placed around a c thanks amber comment i understand better going wrong mysqldb converts parametrized argument a c a c is way make parametrized query using in sql syntax or must one manually construct sql string,1 afaik future import unicodeliterals make string literals unicode type instead string type that type type str future import unicodeliterals type type unicode but str unicode still different types behave like typestr type str always str type about r u issue design equivalent ru u without unicodeliterals from docs when r r prefix used conjunction u u prefix uxxxx uxxxxxxxx escape sequences processed backslashes left string probably way lexical analyzer worked python series in python works i would expect you type backslash twice u interpreted get two backslashes backslashes escaped preceding backslash however remain string ur u u u so imho two simple options do use raw strings escape backslashes compatible python hunittests be smart take advantage unicode codepoints compatible python r hucunittests,writing code python python mind i thought good idea put future import unicodeliterals top modules in words i asking troubles avoid future i might missing important knowledge i want able pass string representing filepath instantiate object simple myobject hunittests in python works fine need use double backslashes raw string even directory starting u exactly i want in init method i make sure single occurences interpreted including special characters b f n r v x remains problem also decoding given string unicode using local encoding works expected preparing python x simulating actual problem editor starting clean console python following happens u u r u u ok u encoded console using local encoding future import unicodeliterals u syntaxerror unicode error unicodeescape codec decode bytes position end string escape sequence in words unicode string interpreted unicode get decoded automatically local encoding even raw string r u syntaxerror unicode error rawunicodeescape codec decode bytes position truncated uxxxx u u u u syntaxerror unicode error unicodeescape codec decode bytes position end string escape sequence also i would expect isinstancestr unicode return true importing unicodeliterals make stringtypes unicode edit because python strings sequences unicode characters i would expect str return unicodestring typestr type unicode type str strings unicode also realise type unicode type str confusion around questions i best pass strings containing u without writing u future import unicodeliterals really implement python related unicode changes i get complete python string environment edit in python type str unicode object type unicode simply exist in case i want write code python work python but i import unicodeliterals i cannot check string type unicode i assume unicode part namespace unicode part namespace literal type str still unicode created module typemystring always return type str unicode literals python my modules use encoded utf coding utf comment top localegetdefaultlocale returns cp so i call myobject ã§ã§a console encoded cp python utf calling myobject ã§ã§a module in python encoded unicode literal edit i gave hope allowed avoid using u x matter also i understand limitations importing unicodeliterals however many possible combinations passing string module console vica versa different encoding top importing unicodeliterals python vs python made want create overview actual testing hence table in words typestr return type str python class str python problems seem avoided,3 since using python look xapian great python bindings what asking way sophisticated regular expressions you need full text search stemming tricks fuzzy matching,i read documentation module comes builtin python i seem get grasp in fact i exactly sure i looking let explain i huge dictionary what i want able type search criteria let say example hello search dictionary give list like hello hell hello world hello basically anything resembling search criteria would i use regex something else,1 emmet good catch matt pitch perfect response we pushed fix issue pick pypi github repo httpsgithubcomtwiliotwiliopython just update module documented approach work please shoot email address profile guys earned twilio tshirt,im using twiliopython im following tutorial httpreadthedocsorgdocstwiliopythonenlatestusagetwimlhtmlhighlightnest but try twilio import twiml r twimlresponse rsayhello rgatherfinishonkey g gsayworld print strr but get attributeerror exit any idea,1 there new regexp module pypi repository possibly replace current python module sometimes it allows fuzzy matching,i read documentation module comes builtin python i seem get grasp in fact i exactly sure i looking let explain i huge dictionary what i want able type search criteria let say example hello search dictionary give list like hello hell hello world hello basically anything resembling search criteria would i use regex something else,1 this exact pattern inline model formsets,i trying relate objects created formset object created webpage formset so example code def createbrequest speciesformset modelformsetfactoryspecies fields common scientific requestmethod post formset speciesformsetrequestpost form bformrequestpost formisvalid objcreate bmodelobjectscreate name formcleaneddata name objcreatesave forms formsetforms formsisvalid formset speciesobjectscreate common formscleaneddata common scientific formscleaneddata scientific bname formcleaneddata name formsetsave else formset speciesformset form bform c speciesformset speciesformset form form cupdatecsrfrequest return rendertoresponse formscreatebhtml c return httpresponseredirect accountsprofile else formset speciesformset form bform c speciesformset speciesformset form form cupdatecsrfrequest return rendertoresponse formscreatebhtml c the problem i trying relate formset object form one tells form object actually exist it creates object database however none formset objects i get error cannot assign u speciesbname must bmodel instance helps also relationship foreignkey is anyway solve thanks time,1 i believe looking aggregate totallist planinvestmentsetfilter maturitydategte currentyear aggregatesum maturityamount give maturityamountsum total amount,so i query set returns list financial institutions also total amount money investments i institution viewspy totallist planinvestmentsetfiltermaturitydategte currentyearvalues financialinstitutionabbr annotatesum maturityamount what i would like find grand total money my question i go calculating sum find total investments,1 you might want look something compute levenshtein edit distance there excellent article build something like talking scratch python well ported lots languages you might want go fromscratch route article give lots interesting background help decide tool right level sophistication xapian suggested lucene fulltext search engines provide kind capability sophisticated might need,i read documentation module comes builtin python i seem get grasp in fact i exactly sure i looking let explain i huge dictionary what i want able type search criteria let say example hello search dictionary give list like hello hell hello world hello basically anything resembling search criteria would i use regex something else,1 at bottom bashrc usually etcbashrc file put update pythonpath env variable include usrlibpythonsitepackages pythonpath export pythonpathpythonpathusrlibpythonusrlibpythonsitepackages else export pythonpathusrlibpythonusrlibpythonsitepackages fi or specific user running script put homeuserrunningscriptbashrc then source file source bashrc source etcbashrc,i working webpy reason i getting following error thu sep error client file usrlibpythonsitepackageswebpypyeggwebdbpy line init thu sep error client import mysqldb db thu sep error client importerror no module named mysqldb here syspath case culprit i see theegg though i know thoughts usrlibpythonsitepackagesbravopyegg usrlibpythonsitepackagestwistedpylinuxiegg usrlibpythonsitepackagesconstructpyegg usrlibpythonsitepackageszopeinterfacepylinuxiegg usrlibpythonsitepackageswebpypyegg usrlibpythonsitepackagesmysqlpythonpylinuxiegg usrlibpythonsitepackagessetuptoolscdevrpyegg usrlibpythonzip usrlibpython usrlibpythonplatlinux usrlibpythonlibtk usrlibpythonlibold usrlibpythonlibdynload usrlibpythonsitepackages usrlibpythonsitepackagespil here contents sitepackages directory rootxxxx locate egg rootmysqlpythondistmysqlpythonpylinuxiegg usrlibpythonsitepackageserrorhandlerpyegg usrlibpythonsitepackagessetuptoolscpyegg usrlibpythonsitepackagesxlrdpyegg usrlibpythonsitepackagesxlutilspyegg usrlibpythonsitepackagesxlutilspyegg usrlibpythonsitepackagesxlwtpyegg usrlibpythonsitepackagesbravopyegg usrlibpythonsitepackagesmysqlpythonpylinuxiegg usrlibpythonsitepackagestwistedpylinuxiegg usrlibpythonsitepackagesconstructpyegg usrlibpythonsitepackagessetuptoolscpyegg usrlibpythonsitepackagessetuptoolscdevrpyegg usrlibpythonsitepackageswebpypyegg usrlibpythonsitepackageszopeinterfacepylinuxiegg if i open python either i able import mysqldb problem thanks tom,1 code bellow isn t tested something like import urllib urllib host httpswwwvirwoxcom forms login action host indexphp data urlliburlencode uname username password orders action host ordersphp data urlliburlencode downloadopen download formatopen xml opener urllibbuildopener urllibhttpcookieprocessor try req urllibrequest url forms login action data forms login data openeropen req save login cookie print login ok except exception e print login fail print e try req urllibrequest url forms orders action data forms orders data print orders page ok except exception e print orders page fail print e try xml openeropen req read print xml except exception e print obtain xml fail print e,edit problem solve ultimately turned matter http instead https url stupid mistake part but nice clean code example cetver helped isolate problem thanks offered suggestions putting url firefox triggers appropriate download saveas dialog httpswwwvirwoxcomordersphpdownloadopendownloadampformatopenxls the link submitting form download button form page httpswwwvirwoxcomordersphp here relevant html form generates url form action ordersphp method get fieldsetlegendopen orders legend input type submit value download name downloadopen select name formatopen option value xls xlsoption option value csv csvoption option value xml xmloptionselect form but i try following python code i sort expected would work get orders list openordersurl virwoxtoplevelurlordersphp openordersparams urlencode downloadopendownload formatopenxml openordersrequest urllibrequestopenordersurlopenordersparamsheaders openordersresponse virwoxopeneropenopenordersrequest openordersxml openordersresponseread printopenordersxml openordersxml ends original page httpswwwvirwoxcomordersphp how firefox know also file downloaded i detect download file python please note securitylogin issue i would even able get ordersphp page i authentication trouble edit i wondering something redirection i using basic redirection handler maybe i using something liek urllibfileretrieve edit code complete program case relevant import urllib import urllib import cookielib import pprint urllib import urlencode username password virwoxtoplevelurl httpwwwvirwoxcom overviewurl httpswwwvirwoxcomindexphp header useragent mozilla compatible msie windows nt headers useragent useragent handlers cookie handler cookiehandler urllibhttpcookieprocessor cookielibcookiejar redirect handler redirecthandler urllibhttpredirecthandler create opener openerdirector instance virwoxopener urllibbuildopenerredirecthandlercookiehandler login loginurl httpswwwvirwoxcomindexphp values uname username password password logindata urlliburlencodevalues loginrequest urllibrequestloginurllogindataheaders loginresponse virwoxopeneropenloginrequest overviewhtml loginresponseread virwoxjsonurl httpapivirwoxcomapijsonphp gettest urlliburlencode methodgetmarketdepth symbolseursllsymbolsusdsllbuydepthselldepthid getresponse urlliburlopenvirwoxjsonurlgettest print getresponseread get orders list openordersurl virwoxtoplevelurlordersphp openordersparams urlencode downloadopendownload formatopenxml openordersrequest urllibrequestopenordersurlopenordersparamsheaders openordersresponse virwoxopeneropenopenordersrequest openordersxml openordersresponseread following prints html ordersphp page desired download data print printopenordersxml print print openordersresponseinfo print openordersresponsegeturl print following prints nothing assume without cookie handler fails authenticate note authentication php program html authentication authentication hangler print urlliburlopenhttpswwwvirwoxcomordersphpdownloadopendownloadampformatopenxmlread,1 that strstrip works strings immutable result returned method flnm flnmreplace repeat characters want remove,i trying strip characters timestamp stored matrix list lists want i want extract item use filename stripping unwanted characters stay unchanged original list i quite familiar stripping string operations i use routinely i stucked i know happening i tried almost everything i want get instead original in example replaced make easier am i missing something x filematrix flnm strx x matter string sure print typeflnm type str ok list whatever print check flnm flnmstrip want get starters print check flnm nothing stringstripflnm print check flnm nothing flnm flnmstrip print check flnm nothing flnmreplace print check flnm nothing thanks lot,2 two caveats answer right away i well versed framework urllib friends implementing still take bit time it trivial the openidrp code look uhm ready none less the latest version openidrp translated work python you need fix couple small things the included example code work use template write application if careful bytes vs strings take less two years get working openid login i managed translate cherrypy way while looking might helpful guide httppasteubuntucom as example kind code still remains running mackey basedecodestringsession mackey mackey basebdecodesession mackey encode you see things write actual logincode this initpy note methods i yet use still bugs httppasteubuntucom,i never done authentication stuff would like able track authenticate users via openid i saw couple modules allow openid authentication wsgi old none mention python i guessing work i like suggestions handleauthenticate openid wsgi python a simple implementation would appreciated,2 try import flnm resub flnm,i trying strip characters timestamp stored matrix list lists want i want extract item use filename stripping unwanted characters stay unchanged original list i quite familiar stripping string operations i use routinely i stucked i know happening i tried almost everything i want get instead original in example replaced make easier am i missing something x filematrix flnm strx x matter string sure print typeflnm type str ok list whatever print check flnm flnmstrip want get starters print check flnm nothing stringstripflnm print check flnm nothing flnm flnmstrip print check flnm nothing flnmreplace print check flnm nothing thanks lot,2 use namelist method zipfile class get list filenames archive without extract for example import zipfile myzip zipfilezipfile myzipzip r filenames myzipnamelist do something filenames,how i traverse contents zip file python without extract if extracting way efficient i create unique temp folder extract traverse remove temp folder afterwards,1 there problems code included example i would edit i sure looking the following import kll xx print resplit print k l l xx,i string like mystr kll xx i want break following format k l l xx k l l anything format char followed number i python using following regex kll xx resplitcda gives following output k l l i want something like k l l possible workaround,2 sounds like installed protobuf try pip install protobuf install pypipythonorgpypiprotobuf,i trying package script bbfreeze uses protocol buffers using bbfreeze like usrbinpython bbfreeze import freezer import os f freezer dist faddscript mainpy f results no module named googleprotbuf client reading docs bit i try usrbinpython bbfreeze import freezer import os f freezer dist includesgoogleprotobuf faddscript mainpy f results importerror no module named google running bbfreeze script bbfreeze version installed easyinstall anyone run issue similar one previously,1 the metadata collection table objects considered fixed immutable structure application unlike function class definitions as know forking child process modulelevel structures application remain present across process boundaries table defs usually category the engine however refers pool dbapi connections usually tcpip connections sometimes filehandles the dbapi connections generally portable subprocess boundary would want either create new engine subprocess use nonpooled engine means using nullpool you also kind association metadata engine bound metadata this practice prominent various outdated tutorials blog posts really general purpose thing i try deemphasize way working much possible if using orm similar dichotomy program structuresactive work exists mapped classes course shared subprocesses definitely want session objects local particular subprocess correspond actual dbapi connection well plenty mutable state best kept local operation,problem i writing program reads set documents corpus line document each document processed using function processdocument assigned unique id written database ideally want using several processes the logic follows the main routine creates new database sets tables the main routine sets group processesthreads run worker function the main routine starts processes the main routine reads corpus adding documents queue each process worker function loops reading document queue extracting information using processdocument writes information new entry table database the worker loops breaks queue empty appropriate flag set main routine documents add queue question i relatively new sqlalchemy databases general i think code used setting database main routine works fine i tell where i stuck i sure exactly put worker functions process write database without clashing others there nothing particularly complicated going process gets unique value assign entry multiprocessingvalue object protected lock i sure whether i passing worker function aside queue anything do i pass sqlalchemyengine instance i created main routine the metadata instance do i create new engine process is canonical way is something special i need keep mind additional comments i well aware i could bother multiprocessing single process i write code several processes reading database later i might well figure thanks advance help,2 this pretty fast want strip known nonalpha chars string flnmtranslatenone,i trying strip characters timestamp stored matrix list lists want i want extract item use filename stripping unwanted characters stay unchanged original list i quite familiar stripping string operations i use routinely i stucked i know happening i tried almost everything i want get instead original in example replaced make easier am i missing something x filematrix flnm strx x matter string sure print typeflnm type str ok list whatever print check flnm flnmstrip want get starters print check flnm nothing stringstripflnm print check flnm nothing flnm flnmstrip print check flnm nothing flnmreplace print check flnm nothing thanks lot,1 it unlikely easy way solve without proper parser you could probably get away hand built parser require tokenizing though something like following good guide def parses curs strings def flushstring stringspush joincurs curs def handlespecialcases todo fill c c break elif c handlespecialcases elif c flushstring else curspushc flushstring return strings,i would like split string similar abc defg hijk l mn opqrs tuv abc defg hijk l mn opqrs ie i want break semicolon inside nested quotes what easiest way tokenize it hurt fast short better edit i forgot one detail makes even tricky i need position semicolon cutting string none i changes legacy code used recursive stackoverflowed string became long,1 in python usually one way but first strip work way think flnm flnmstrip notice strip affects ends string you could join characters rejected rejected flnm joinc c flnm c rejected or join digit characters flnm joinc c flnm cisdigit or chain number calls stringreplace flnm flnmreplace replace replace or use resub import flnm resub d flnm since strings immutable make sure assign result back flnm edit even ways using reduce ivan answer rejected flnm reducelambda areplaced rejected flnm using translate oxtopus answer rejected flnm flnmtranslatenone rejected i prefer oxtopus use translate straight forward,i trying strip characters timestamp stored matrix list lists want i want extract item use filename stripping unwanted characters stay unchanged original list i quite familiar stripping string operations i use routinely i stucked i know happening i tried almost everything i want get instead original in example replaced make easier am i missing something x filematrix flnm strx x matter string sure print typeflnm type str ok list whatever print check flnm flnmstrip want get starters print check flnm nothing stringstripflnm print check flnm nothing flnm flnmstrip print check flnm nothing flnmreplace print check flnm nothing thanks lot,1 looks like question already answered might like take look requests package it basically nice wrapper around standard lib tools the following probably want import requests r requestsget httpwwwvirwoxcomordersphp allowredirectstrue auth user pass data downloadopen download formatopen xls print rcontent,edit problem solve ultimately turned matter http instead https url stupid mistake part but nice clean code example cetver helped isolate problem thanks offered suggestions putting url firefox triggers appropriate download saveas dialog httpswwwvirwoxcomordersphpdownloadopendownloadampformatopenxls the link submitting form download button form page httpswwwvirwoxcomordersphp here relevant html form generates url form action ordersphp method get fieldsetlegendopen orders legend input type submit value download name downloadopen select name formatopen option value xls xlsoption option value csv csvoption option value xml xmloptionselect form but i try following python code i sort expected would work get orders list openordersurl virwoxtoplevelurlordersphp openordersparams urlencode downloadopendownload formatopenxml openordersrequest urllibrequestopenordersurlopenordersparamsheaders openordersresponse virwoxopeneropenopenordersrequest openordersxml openordersresponseread printopenordersxml openordersxml ends original page httpswwwvirwoxcomordersphp how firefox know also file downloaded i detect download file python please note securitylogin issue i would even able get ordersphp page i authentication trouble edit i wondering something redirection i using basic redirection handler maybe i using something liek urllibfileretrieve edit code complete program case relevant import urllib import urllib import cookielib import pprint urllib import urlencode username password virwoxtoplevelurl httpwwwvirwoxcom overviewurl httpswwwvirwoxcomindexphp header useragent mozilla compatible msie windows nt headers useragent useragent handlers cookie handler cookiehandler urllibhttpcookieprocessor cookielibcookiejar redirect handler redirecthandler urllibhttpredirecthandler create opener openerdirector instance virwoxopener urllibbuildopenerredirecthandlercookiehandler login loginurl httpswwwvirwoxcomindexphp values uname username password password logindata urlliburlencodevalues loginrequest urllibrequestloginurllogindataheaders loginresponse virwoxopeneropenloginrequest overviewhtml loginresponseread virwoxjsonurl httpapivirwoxcomapijsonphp gettest urlliburlencode methodgetmarketdepth symbolseursllsymbolsusdsllbuydepthselldepthid getresponse urlliburlopenvirwoxjsonurlgettest print getresponseread get orders list openordersurl virwoxtoplevelurlordersphp openordersparams urlencode downloadopendownload formatopenxml openordersrequest urllibrequestopenordersurlopenordersparamsheaders openordersresponse virwoxopeneropenopenordersrequest openordersxml openordersresponseread following prints html ordersphp page desired download data print printopenordersxml print print openordersresponseinfo print openordersresponsegeturl print following prints nothing assume without cookie handler fails authenticate note authentication php program html authentication authentication hangler print urlliburlopenhttpswwwvirwoxcomordersphpdownloadopendownloadampformatopenxmlread,1 if want call method name wrapper function could look like def wrappermethodsymbol args obj foo getattrobj methodsymbolargs objclose wrapper bar you could also use method directly instead name def wrappermethod args obj foo methodobj args objclose wrapperfoobar,given object foo set methods bar baz quux close i want wrap calls foo follows def wrappermethodsymbol args object foo applyobjectmethodsymbol args objectclose so later i call wrapperbar mysweetargs wrapper correctly dispatch obviously lisp would simple simply quote methodsymbol away go the goal properly allocatedeallocate resources textefficient fashion i would prefer wrap foo safefoo class,2 you use something like reference clickedon object eventwidgetfindwithtagcurrent the tag current special represents topmost object mouse,lets say i created canvas tkinter app in canvas i drawn several rectangles what i want essence know rectangle user clicked main concern i tried i think might solution this layout x range range tablenumber x wcreaterectangletablexseparation tablewidth tablewidth tableyseparation tableheight x tableheight tablexseparation tablewidthy tableyseparation tableheight x fillbrown tagstable strtablenumber wtagbindtable strtablenumber button so creates rectangles rows columns layout each rectangle specific tag form table table table when i click rectangle function executes let say something like def doevent print click not i get click console every click rectangle i would like able get tag clicked rectangle able something like def doevent print strthetagoftheclickedrectangle so i checked events i call widget x xroot yroot char keysym keycode num width height type none seem pin point rectangle i clicked i thought adding parameters function wtagbindtable strtablenumber button doevent tag but seem work fine maybe i right doevent tag work print eventx print tag i hope question clear i got tag manner i get x event would comfortable the actual solution i think working math eventx eventy calculate based coordinates click rectangle user clicked seems overcomplicated i trying though i done obviously works i hope question clear wise please ask clarification note i tied code rather i looking solution problem efficient work even means working tags another type widget whatever easier,2 i would get tr table classlistings your search obviously broad information want because html structure easily get table data this easier long run getting hrefs filtering ones want beautifulsoup plent documentation httpwwwcrummycomsoftwarebeautifulsoupdocumentationhtml exact code tr soupfindall tr datalist trchildren datalistcontent datalistcontent new york datalistcontent region ignore etc,i want scrape following information except last row classregion row tdtd td bgcolor alignleft style widthpxa classxnternal hrefhttpwwwwhitecasecomwhite caseatd td bgcolor alignleftnew yorktd td bgcolor alignleft classregionnatd td bgcolor alignlefttd td bgcolor alignlefttd td bgcolor alignlefttd td bgcolor alignlefttd td bgcolor aligncentera classxnternal hrefnljfirmdetail view profile atdtrtr classsmall bgcolorffffff i tested handler class testurlopenwebapprequesthandler def getself soup beautifulsoupurlliburlopenhttpwwwilrgcomnlj linklist soupfindall hreftrue linklistappendahref selfresponseoutwriteplinklist sp linklist this works also get view profile link i want linklist u httpwwwilrgcom u httpwwwilrgcom u httpwwwilrgcomnations u httpwwwilrgcomgovhtml i easily remove u httpwwwilrgcom scraping site would nice list without what best way thanks,1 in order catch changes manytomanyfield need hook mmchanged signal you might want look documentation signals general mmchanged signal particular,i got admin form couple inlines displaying mm fields like class articleadminadminmodeladmin form articlecustomadminform inlines specificgeminline suiteinline base class looks something like class articlemodelsmodel articlecode modelscharfieldmaxlength gems modelsmanytomanyfieldgem specificgem model special field articlecode aggregate data mm fields represented inlines i written function createcodeinstance accessing model instance fields directly something like def createcodeinstance articlecodepart specificgemobjectsfilterarticleinstance articlecodepart instancesuitesetall instancearticlecode something parts the problem i call function overriden modeladmin savemodel model save functions following instance mm fields produces outdated results even retarded example help class articleadminadminmodeladmin def savemodelself request obj form change objsave createcodeobj objsave when i get inlineformset clean method i access forms data i could figure part articlecode even without actual saving i two inlines so i find topmost save method i could call aggregation function models validated saved db,1 in def connemailparser check data none calling datasplit if none check imap correctly initiated login worked if case post reduced part code pinpointing actually goes wrong as jim garrison pointed traceback would help us lot this import traceback try somecode except typeerror tracebackprintexc edit based comment when encode unicode string replacing characters part ascii codes xfc apparently saverwrite tries encode already encoded text first interpreting unicode got u xfc so encode if still goes wrong see change encoding eg utf cp get current encoding os import locale encodinglocalegetlocale,the following code results htmlbodyemailaddress connemailparser typeerror nonetype object iterable error works fine ide emails sent pdf files generated but command line connemailparser working what i program runs smoothly here code snipped import imaplib import email import quopri cstringio import stringio import hopisa pisa datetime import datetime import logging import smtplib emailgenerator import generator emailmimemultipart import mimemultipart emailmimebase import mimebase emailmimetext import mimetext emailutils import formatdate email import encoders def sendpdfsurvey def connemailparser try saver stringio server server user user password nono subjecta certain phrase imap imaplibimapserver imaploginuser password imapselect imapsearchnone all typ data imapsearchnone unseen subject subject looking phrase count num datasplit count count stupid gets oone messsage count typ data imapfetchnum rfc email emailmessagefromstringdata varsubject email subject the phase emailaddress subject field emailaddressraw varsubject emailaddressmedium emailaddressrawreplace emailaddress emailaddressmediumreplace msg emailmessagefromstringdata typ data imapstorenum flags seen astrmsg adecode quopri decode utf saverwritei savercontent savergetvalue body email html header elements get deleted planhtml savercontentsplit html xmlnshttpwwwworgxhtml strip return planhtml emailaddressstrip saverclose imapclose imaplogout except could get participant email somewhere trouble maker htmlbodyemailaddress connemailparser filenamepdf umfrageethicsspdf datetimeutcnowstrftime mdhmsf def printpdf try html htmlbody result stringio pdf pisapisadocumentstringiohtmlencodeutf result encoding utf filetoparseopenfilenamepdfwb filetoparsewriteresultgetvalue filetoparseclose pisastartviewerfilenamepdf except print could write pdf def sendpdfparticipant try onachricht mimemultipart onachricht from someemailcom onachricht to emailaddress onachricht date formatdatelocaltime true onachricht subject a subject oanhang mimebase application octetstream oanhangsetpayloadopenfilenamepdf rb read encodersencodebaseoanhang oanhangaddheader contentdisposition attachmentfilename somepdf messagetextplain u some message onachrichtattachmimetextmessagetextplainencode utf plain utf io stringio g generatorio false gflattenonachricht onachrichtattachoanhang user user pwd pwd smtpserver smtplibsmtpsmtpraumopolde smtpserverehlo smtpserverstarttls smtpserverehlo smtpserverloginuser pwd smtpserversendmail someemailcom emailaddressonachrichtasstring smtpserverquit except printcould send data sendpdfsurvey,1 here example sets point color based zaxis value import vtk numpy import random class vtkpointcloud def initself zmin zmax maxnumpointse selfmaxnumpoints maxnumpoints selfvtkpolydata vtkvtkpolydata selfclearpoints mapper vtkvtkpolydatamapper mappersetinputdataselfvtkpolydata mappersetcolormodetodefault mappersetscalarrangezmin zmax mappersetscalarvisibility selfvtkactor vtkvtkactor selfvtkactorsetmappermapper def addpointself point selfvtkpointsgetnumberofpoints selfmaxnumpoints pointid selfvtkpointsinsertnextpointpoint selfvtkdepthinsertnextvaluepoint selfvtkcellsinsertnextcell selfvtkcellsinsertcellpointpointid else r randomrandint selfmaxnumpoints selfvtkpointssetpointr point selfvtkcellsmodified selfvtkpointsmodified selfvtkdepthmodified def clearpointsself selfvtkpoints vtkvtkpoints selfvtkcells vtkvtkcellarray selfvtkdepth vtkvtkdoublearray selfvtkdepthsetname deptharray selfvtkpolydatasetpointsselfvtkpoints selfvtkpolydatasetvertsselfvtkcells selfvtkpolydatagetpointdatasetscalarsselfvtkdepth selfvtkpolydatagetpointdatasetactivescalars deptharray pointcloud vtkpointcloud k xrange point randomrand pointcloudaddpointpoint pointcloudaddpoint pointcloudaddpoint pointcloudaddpoint pointcloudaddpoint renderer renderer vtkvtkrenderer rendereraddactorpointcloudvtkactor renderersetbackground rendererresetcamera render window renderwindow vtkvtkrenderwindow renderwindowaddrendererrenderer interactor renderwindowinteractor vtkvtkrenderwindowinteractor renderwindowinteractorsetrenderwindowrenderwindow begin interaction renderwindowrender renderwindowinteractorstart,i point cloud i want visualize vtk i want see different colors depending conditions i using python any suggestions thanks lot,3 i think may looking the attrs argument helpful isolating sections want beautifulsoup import beautifulsoup import urllib soup beautifulsoupurlliburlopenhttpwwwilrgcomnlj rows soupfindallname tr attrs class small row rows number rowfind td text tds rowfindallname td attrs align left link tdsfind href firm tdstext office tdstext attorneys tdstext partners tdstext associates tdstext salary tdstext print number firm office attorneys partners associates salary,i want scrape following information except last row classregion row tdtd td bgcolor alignleft style widthpxa classxnternal hrefhttpwwwwhitecasecomwhite caseatd td bgcolor alignleftnew yorktd td bgcolor alignleft classregionnatd td bgcolor alignlefttd td bgcolor alignlefttd td bgcolor alignlefttd td bgcolor alignlefttd td bgcolor aligncentera classxnternal hrefnljfirmdetail view profile atdtrtr classsmall bgcolorffffff i tested handler class testurlopenwebapprequesthandler def getself soup beautifulsoupurlliburlopenhttpwwwilrgcomnlj linklist soupfindall hreftrue linklistappendahref selfresponseoutwriteplinklist sp linklist this works also get view profile link i want linklist u httpwwwilrgcom u httpwwwilrgcom u httpwwwilrgcomnations u httpwwwilrgcomgovhtml i easily remove u httpwwwilrgcom scraping site would nice list without what best way thanks,2 a little concisely eumiro answer essentially import numpy def generateysize xsize ycenter xcenter radius x numpymgridysizexsize return x ycenter xcenter radius,is possible generate numpy matrix circular pattern rest matrix so basically generateysize xsize ycenter xcenter radius should look something like ok looks stupid x scale would make sense is possibility numpy,3 you use subprocess module result subprocesscheckoutput yourprogramexe arg arg,i want call program exe written c compiled python the executable takes input two files returns score i need multiple files so i would like write small script python loops multiple files passes executable gets back values now i done search i know swig boostpython may option i trying find easier way i need extend c program i simply want call like i would command line get returned number,1 if trivial check whether something fail probably favor after constructing exceptions including associated tracebacks takes time exceptions used things unexpected things need jump one level logic eg break get far enough things know exactly going handling exception ahead time things checking ahead time failure expensive relative attempting operation note oftentimes real answer neither instance first example really use get provide default x mydictget abc noabc,should i test something valid try catch exception is solid documentation saying one way preferred is one way pythonic for example i lenmylist x mylist else x noabc or try x mylist except indexerror x noabc some thoughts pep says errors never pass silently unless explicitly silenced should using try instead interpreted error passing silently and explicitly silencing using way therefore making ok i referring situations things way example try import foo except importerror import baz,2 in particular case use something else entirely x mydictgetabc noabc in general though if expect test fail frequently use if test expensive relative trying operation catching exception fails use try if neither one conditions applies go whatever reads easier,should i test something valid try catch exception is solid documentation saying one way preferred is one way pythonic for example i lenmylist x mylist else x noabc or try x mylist except indexerror x noabc some thoughts pep says errors never pass silently unless explicitly silenced should using try instead interpreted error passing silently and explicitly silencing using way therefore making ok i referring situations things way example try import foo except importerror import baz,3 to run external program get output use subprocesscheckoutput python the example docs subprocesscheckoutputls l devnull crwrwrw root root oct devnulln checkcall returns return code program output,i want call program exe written c compiled python the executable takes input two files returns score i need multiple files so i would like write small script python loops multiple files passes executable gets back values now i done search i know swig boostpython may option i trying find easier way i need extend c program i simply want call like i would command line get returned number,2 should using try instead interpreted error passing silently and explicitly silencing using way therefore making ok using try acknowledging error may pass opposite pass silently using except causing pass using try except preferred cases else logic complicated simple better complex complex better complicated easier ask forgiveness permission what errors never pass silently warning case code could raise exception know design admits possibility designed way deal exception explicitly silencing error view would something like pass except block done understanding nothing really correct error handling particular situation this one times i feel like comment wellwritten code probably really needed however particular example neither appropriate x mydictget abc noabc the reason everyone pointing even though acknowledge desire understand general inability come better example equivalent sidesteps actually exist quite lot cases looking first step solving problem,should i test something valid try catch exception is solid documentation saying one way preferred is one way pythonic for example i lenmylist x mylist else x noabc or try x mylist except indexerror x noabc some thoughts pep says errors never pass silently unless explicitly silenced should using try instead interpreted error passing silently and explicitly silencing using way therefore making ok i referring situations things way example try import foo except importerror import baz,1 you prefer tryexcept ifelse results speedups example preventing extra lookups cleaner code less lineseasier read often go handinhand speedups in case trying find element long list try x mylistindex except indexerror x noabc try except best option index probably list indexerror usually raised this way avoid need extra lookup index lenmylist python encourages use exceptions handle phrase dive into python your example handles exception gracefully rather letting silently pass also exception occurs exceptional case index found hence word exception cleaner code the official python documentation page mentions eafp easier ask forgiveness permission rob knight notes catching errors rather avoiding result cleaner easier read code his example says like worse lbyl look leap check whether int conversion raise error isinstances str sisdigit return none elif lens many digits int conversion return none else return intstr better eafp easier ask forgiveness permission try return intstr except typeerror valueerror overflowerror int conversion failed return none,should i test something valid try catch exception is solid documentation saying one way preferred is one way pythonic for example i lenmylist x mylist else x noabc or try x mylist except indexerror x noabc some thoughts pep says errors never pass silently unless explicitly silenced should using try instead interpreted error passing silently and explicitly silencing using way therefore making ok i referring situations things way example try import foo except importerror import baz,3 i think glob could help implementation,perl lovely little utility called findperl translate quite faithfully command line unix find utility perl script if find command like find usr xdev type name share name shell expansion share directory file do go external file systems usr directory could multiple directories it finds directories ending share usr now run findperl usr xdev type name share emit perl script you modify script use python oswalk certainly needed functionality recursive directory listing big differences take simple case find type f print find print files current directory a naã¯ve implementation using oswalk would path dirs files oswalkroot files file files print ospathjoinpathfile however produce different results typing find type f print shell i also testing various oswalk loops create pipe find commands arg root findcmd find type f root argsshlexsplitfindcmd psubprocesspopenargsstdoutsubprocesspipe outerrpcommunicate outoutrstrip remove terminating n line outsplitlines print line the difference oswalk counts links files find skips so correct implementation file type f print becomes path dirs files oswalkroot files file files pospathjoinpathfile ospathisfilep ospathislinkp printp since hundreds permutations find primaries different side effects becomes time consuming test every variant since find gold standard posix world count files tree way python important so equivalent findperl used python so far i using findperl manually translating perl code this hard perl file test operators different python file tests ospath times,1 if want high performance minimal code footprint look farther python builtin plotting library tkinter no need write special c c code use large plotting package get performance much better fps the following code scrolls x strip chart fps ghz core duo fps ghz core the central routine scrollstrip plots set data points corresponding colors right edge along optional vertical grid bar scrolls stripchart left to plot horizontal grid bars include data color arrays constants along variable data points tkinter import import math random threading time class stripchart def initself root selfgf selfmakegraphroot selfcf selfmakecontrolsroot selfgfpack selfcfpack selfreset def makegraphself frame selfsw selfh selftop gf canvasframe widthselfsw heightselfh bg bd highlightthickness gfp photoimagewidthselfsw heightselfh selfitem gfcreateimage selftop imagegfp anchornw returngf def makecontrolsself frame cf frameframe borderwidth reliefraised buttoncf textrun commandselfrungridcolumn row buttoncf textstop commandselfstopgridcolumn row buttoncf textreset commandselfresetgridcolumn row selffps labelcf text fps selffpsgridcolumn row columnspan returncf def runself selfgo threadingenumerate tname gen printalready running return threadingthreadtargetselfdostart namegenstart def stopself selfgo threadingenumerate tname gen tjoin def resetself selfstop selfclearstripselfgfp def dostartself tx timetime selfgo mathsinmathpit randomrandom selfscrollstripselfgfp ff f af f else tx timetime selffpsconfigtext fps inttx tx tx tx timesleep def clearstripself p color fill strip background color selfbg color save background color scroll selfdata none clear previous data selfx ptkcallp put color p width p height def scrollstripself p data colors bar scroll strip add new data selfx selfx selfsw x double buffer position bg bar bar else selfbg ptkcallp put bg selfx selfx selfh ptkcallp put bg selfxselfsw selfxselfsw selfh selfgfcoordsselfitem selfx selftop scroll justwritten column selfdata selfdata data rangelendata intselfh selfdatad plot data points intselfh datad ya yb sortedy rangeya yb connect dots pputcolorsd selfxy pputcolorsd selfxselfswy selfdata data save next call def main root tk roottitlestripchart app stripchartroot rootmainloop main,i would like show read time graph one two curves samples per second using python wxpython the widget support win linux platforms any hints welcome edited add i need update display fps need show samples data curves reasonable update rate display fps okay edited add i used mathplotlib project good success i settled wxlibplot projects i found simpler somewhat easier use consuming less cpu cycles as wxlib comes part standard wxpython distribution particularly easy use,3 i wrote python script use oswalk searchandreplace might useful thing look writing something like replace strings files python and python replacement find going rely heavily osstat check various properties file for example flags find check size file last modified timestamp,perl lovely little utility called findperl translate quite faithfully command line unix find utility perl script if find command like find usr xdev type name share name shell expansion share directory file do go external file systems usr directory could multiple directories it finds directories ending share usr now run findperl usr xdev type name share emit perl script you modify script use python oswalk certainly needed functionality recursive directory listing big differences take simple case find type f print find print files current directory a naã¯ve implementation using oswalk would path dirs files oswalkroot files file files print ospathjoinpathfile however produce different results typing find type f print shell i also testing various oswalk loops create pipe find commands arg root findcmd find type f root argsshlexsplitfindcmd psubprocesspopenargsstdoutsubprocesspipe outerrpcommunicate outoutrstrip remove terminating n line outsplitlines print line the difference oswalk counts links files find skips so correct implementation file type f print becomes path dirs files oswalkroot files file files pospathjoinpathfile ospathisfilep ospathislinkp printp since hundreds permutations find primaries different side effects becomes time consuming test every variant since find gold standard posix world count files tree way python important so equivalent findperl used python so far i using findperl manually translating perl code this hard perl file test operators different python file tests ospath times,1 mydictget john defaultvaluecopy would create copy default dict time get called even john present returned faster ok use tryexcept option try return mydict john except keyerror return surname age alternatively also use defaultdict import collections def defaultfactory return surname age mydict collectionsdefaultdictdefaultfactory,let say i code mydict defaultvalue surname age get info john default dict item mydictget john defaultvalue edit data itemsurname smith itemage mydict john item the problem becomes clear check value defaultvalue defaultvalue age surname smith it obvious mydictget return value defaultvalue pointer the problem could worked around changing code item mydictget john surname age seem nice way any ideas comments,1 install pip already run pip install mysqlpython,so i pretty sure i managed dork mysqldb installation i following installed correctly fresh install os x lion phpmyadmin mysql django and yet i try run djangodb import connection django console i get following djangodb import connection traceback recent call last file line file librarypythonsitepackagesdjangopyeggdjangodb init py line connection connectionsdefaultdbalias file librarypythonsitepackagesdjangopyeggdjangodbutilspy line getitem backend loadbackenddb engine file librarypythonsitepackagesdjangopyeggdjangodbutilspy line loadbackend return importmodule base backendname file librarypythonsitepackagesdjangopyeggdjangoutilsimportlibpy line importmodule import name file librarypythonsitepackagesdjangopyeggdjangodbbackendsmysqlbasepy line raise improperlyconfigurederror loading mysqldb module e improperlyconfigured error loading mysqldb module dlopenusersmy usernamepythoneggsmysqlpythonpymacosxinteleggtmpmysqlso library loaded libmysqlclientdylib referenced usersmy usernamepythoneggsmysqlpythonpymacosxinteleggtmpmysqlso reason image found i idea happening could somebody help walk,1 in python perfectly valid common homedir users librarydir library systemdir system macportsdir optlocal frameworks python path commonsystemdirlibraryframeworks arthur nickname two sheds lastname jackson mydir commonhomedirtwosheds mypictures mydirpictures pythondir frameworkspathpythonversionsframeworkspython edit i saw using python section interpolation cannot done python it introduced python see section configparser interpolation values class configparserextendedinterpolation an alternative handler interpolation implements advanced syntax used instance zcbuildout extended interpolation using sectionoption denote value foreign section interpolation span multiple levels for convenience section part omitted interpolation defaults current section possibly default values special section for example configuration specified basic interpolation would look like extended interpolation paths homedir users mydir homedirlumberjack mypictures mydirpictures values sections fetched well common homedir users librarydir library systemdir system macportsdir optlocal frameworks python path commonsystemdirlibraryframeworks arthur nickname two sheds lastname jackson mydir commonhomedirtwosheds mypictures mydirpictures pythondir frameworkspathpythonversionsframeworkspython,with python configparser possible use interpolation across foreign sections my mind seems tell i seen possible somewhere i find searching this example work give idea i trying section root usr section root usrlocal section dir sectionrootbin dir sectionrootbin note i using python,3 how make server attribute instance gmailsmpt class gmailsmpt def initselfsendfromsendtousrnamepswd selfserver smtplibsmtp smtpgmailcom after serverlogin uses selfusrname selfpswd server domain relevance bound one instance gmailsmpt makes sense make server attribute instance also ps if make server attribute self also change server selfserver methods,i following code i using send message gmail account another gmail account import smtplib class gmailsmpt global server server smtplibsmtp smtpgmailcom def initselfsendfromsendtousrnamepswd selfsendfrom sendfrom selfsendto sendto selfusrname usrname selfpswd pswd def connectself msg test message serverstarttls serverloginselfusrnameselfpswd serversendmailselfsendfromselfsendtomsg print email sent def quitself serverquit first gmailsmpt sendfrom sendto usrname pswd firstconnect firstquit instead global variable server i would like use return server connect function pass server quit function how would i put parameter def quitself what i would normally non object oriented program def quitselfconnect case i want able call def connect def quit separately thanks,1 you running resub character line one time that slow do whole line resubr amp line also look sets counter class collections module it may faster count discard want afterwards,i text file several observations each observation one line i would like detect unique occurrence word line in words word occurs twice line still counted however i would like count frequency occurrence words across observations this means word occurs two linesi would like count number lines occurred here program i wrote really slow processing large number file i also remove certain words file referencing another file please offer suggestions improve speed thank import string itertools import chain tee izip collections import defaultdict def countwordsinfiledelfileoutfile dlist resplit n filedelfilereadlower dlist xstrip x dlist dict f openinfile r lines mapstringstripmapstrlowerfreadlines line lines dict newlist char line newlistappendresubr amp char joinnewlist word dlist sreplaceword word ssplit try dictword except dictword word dictkeys try dictword except dictword freqlist dictitems freqlistsort fclose wordcounthandle openoutfile w word freq freqlist printwordcounthandleword freq wordcounthandleclose return dict dict countwordsinfiletxtdeletewordstxtoutfiletxt,1 there library httpdereksimkowiaknetpygmentsforphp,is possible use python specifically pygments php currently i phpbb forum i developing js syntax highlighters working there already geshi mod i want develop something experience also would performance issues,3 without done performance testing following come mind using regexes are trying get rid certain characters using exceptions flow control although pythonic better ask forgiveness permission throwing exceptions often slow as seen word dictkeys try dictword except dictword turn dlist set use python test membership simultaneously avoid heavy use replace method strings i believe using filter words appear dlist this could accomplished instead avoiding replace filtering words line either list comprehension word word words word delwords filter pythonic filterlambda word word delwords words,i text file several observations each observation one line i would like detect unique occurrence word line in words word occurs twice line still counted however i would like count frequency occurrence words across observations this means word occurs two linesi would like count number lines occurred here program i wrote really slow processing large number file i also remove certain words file referencing another file please offer suggestions improve speed thank import string itertools import chain tee izip collections import defaultdict def countwordsinfiledelfileoutfile dlist resplit n filedelfilereadlower dlist xstrip x dlist dict f openinfile r lines mapstringstripmapstrlowerfreadlines line lines dict newlist char line newlistappendresubr amp char joinnewlist word dlist sreplaceword word ssplit try dictword except dictword word dictkeys try dictword except dictword freqlist dictitems freqlistsort fclose wordcounthandle openoutfile w word freq freqlist printwordcounthandleword freq wordcounthandleclose return dict dict countwordsinfiletxtdeletewordstxtoutfiletxt,1 id really unfortunate name column id builtin function always defined if chosen less mainstream name primary keys would seeing different error would obvious class commentpost tablename comment mapperargs polymorphicidentity comment inheritcondition id postid that id refers builtinsid function returns address python object probably meant easy solution move mapperargs line alias id mean actual table column,so i issues model right i came across two questions helped lot i stuck here current code class postbase tablename post id columninteger primarykeytrue type column type string created columntimestamp defaultdatetimenow updated columntimestamp defaultdatetimenow posterid columninteger foreignkey personid poster relationship person backrefbackref posts mapperargs polymorphicon type class commentpost tablename comment mapperargs polymorphicidentity comment inheritcondition id postid id columninteger foreignkey postid primarykeytrue postid columninteger foreignkey postid post relationship post primaryjoin commentpostid postid backrefbackref comments remoteside postid text columntext the current error i getting typeerror incompatible collection type int listlike what i wrong thanks,2 easy edit bashprofile vi bashprofile somewhere add following line export dyldlibrarypathusrlocalmysqllib this line assumes mysql install directory usrlocalmysql this solve executing via python interrupter launched shell bashprofile exports path needed mysqldb module load libmysqlclientdylib if issue python ide like pycharm add dyldlibrarypath variable launching module configuration i hope helps also to fully understand problem read following section httpmysqlpythonsourceforgenetfaqhtmlimporterror this explains error detail,so i pretty sure i managed dork mysqldb installation i following installed correctly fresh install os x lion phpmyadmin mysql django and yet i try run djangodb import connection django console i get following djangodb import connection traceback recent call last file line file librarypythonsitepackagesdjangopyeggdjangodb init py line connection connectionsdefaultdbalias file librarypythonsitepackagesdjangopyeggdjangodbutilspy line getitem backend loadbackenddb engine file librarypythonsitepackagesdjangopyeggdjangodbutilspy line loadbackend return importmodule base backendname file librarypythonsitepackagesdjangopyeggdjangoutilsimportlibpy line importmodule import name file librarypythonsitepackagesdjangopyeggdjangodbbackendsmysqlbasepy line raise improperlyconfigurederror loading mysqldb module e improperlyconfigured error loading mysqldb module dlopenusersmy usernamepythoneggsmysqlpythonpymacosxinteleggtmpmysqlso library loaded libmysqlclientdylib referenced usersmy usernamepythoneggsmysqlpythonpymacosxinteleggtmpmysqlso reason image found i idea happening could somebody help walk,2 ok i still trying figure whats working far variable hold reference python function pyobject pycallback following function invoked python populate call back reference pyobject setpycallbackpyobject callable pycallback callable remember new callback return pynone initialize acquire global interpreter lock pyevalinitthreads ensure current thread ready call python c api pygilstatestate state pygilstateensure invoke python function boostpythoncallvoidpycallback release global interpreter lock threads resume execution pygilstatereleasestate the python function invoked c executes expected,i want pass callback python code c i want code look something like in c typedef void mycallbackt callbackinfo class myclass void setcallbackmycallbackt cb and use python import mylib def mycallbackmylibcallbackinfo mylibmyclass tsetcallbackmycallback i saw topics near problem solve for example realtime processing callbacks python c advice use boostpython warning gli examples and how call python function foreign language thread c full description python code part boostpythonmodule part i also found link use pyboostfunctionhpp example boost python howto compile actualy i understand use,3 have tried looking pdfminer it sounds like want,i like write small script run headless linux server reads pdf highlights text matches anything array strings i pass saves modified pdf i imagine i end using something like python bindings poppler unfortunately next zero documentation i next zero experience python if anyone could point tutorial example helpful documentation get started would greatly appreciated,2 ruby comes ipaddr module specifies ipaddr class return representation integer require ipaddr addr ipaddrnew print addrtoi here irb rubyp require ipaddr true rubyp addr ipaddrnew ipaddr ipv rubyp addrtoi,need calculate ip int like httpsbitbucketorgloriendjangoipgeosrcdcbfipgeomodelspy ruby i pretty new ruby cannot translate ruby number structunpack l socketinetatonip struct socket python std ip string like,2 you use external program xsel subprocess import popen pipe p popen xsel pi stdinpipe pcommunicateinput hello world with xsel set clipboard want work p works primary selection that middle click one works secondary selection i know used anymore b works clipboard selection that ctrl v one read x clipboards a quick dirty function i created handle def pastestr ptrue ctrue subprocess import popen pipe p p popen xsel pi stdinpipe pcommunicateinputstr c p popen xsel bi stdinpipe pcommunicateinputstr paste hello false pastes clipboard paste hello cfalse pastes primary paste hello pastes you also try pygtk clipboard import pygtk pygtkrequire import gtk clipboard gtkclipboardget clipboardsettext hello world clipboardstore this works ctrl v selection,for example python script spit string giving path newly written file i going edit immediately running script would nice directly sent system clipboard rather stdout,3 if python language restriction may use wrappers flycapture javacpp presets calling appropriate functions via jython,i trying write code using opencv my sensor point grey systems uses flycapture api grab images i like grab images stuff opencv using python flycapture cc i firing swig create bindings am i reinventing wheel do python bindings flycapture already exist somewhere i know,1 have tried pygame sfml both support setting pixels canvas,i trying write program creates d grid user chooses edges points grid then program dynamically manipulate edgeseg flip connect till converges particular shape now question particular module suits kind interactive plotting so far i looked pyqwt guiqwt chaco cannot figure one applicable program it great someone could compare contrast suggest new modules thanks,1 this really python question shell question you already send output python script command clipboard instead standard piping output python script xclip command myscriptpy xclip if xclip already installed system default get sudo aptget install xclip if wanted directly python script i guess could shell run xclip command using ossystem simple deprecated there number ways see subprocess module current official way the command want execute something like echo n pathgoeshere xclip bonus under mac os x thing piping pbcopy,for example python script spit string giving path newly written file i going edit immediately running script would nice directly sent system clipboard rather stdout,3 i figured way prevent firefox loading css images flash seleniumwebdriverfirefoxfirefoxprofile import firefoxprofile def disableimagesself get firefox profile object firefoxprofile firefoxprofile disable css firefoxprofilesetpreference permissionsdefaultstylesheet disable images firefoxprofilesetpreference permissionsdefaultimage disable flash firefoxprofilesetpreference domipcpluginsenabledlibflashplayerso false set modified profile creating browser object selfbrowserhandle webdriverfirefoxfirefoxprofile thanks simon ernie suggestions,i using selenium python bindings fetch data partner site but average taking around secs perform operation i looking way disable images css flash etc i using firefox also using pyvirtualdisplay prevent opening firefox window any optimization speed firefox also helpful i already tried networkhttp options help much and also set permissionsdefaultimage,3 whatever urllib using figure contentlength seems get confused json calculate import json import urllib data jsondumps clen lendata req urllibrequesturl data contenttype applicationjson contentlength clen f urlliburlopenreq response fread fclose took ever figure i hope helps someone else,anyone point tutorial shows post request using urllib data json format,3 in regular expressions w match hyphens it match underscores for second pair keys result passing part key handler in url pattern try rviewspam instead,i using python gae webapp i form user create object database something like class spamrecorddbmodel author dbreferencepropertyauthor requiredtrue text dbstringproperty after created user redirected page whose url contains object key using code spam spamrecordauthorauthor texttext spamput newspamkey spamkey selfredirectviewspams newspamkey and mostly works able view items sitenamecomviewspamagwawnrexbyzxnlbnrzchqlegxbbmvdwjzwlbnqyyojda sitenamecomviewspamagwawnrexbyzxnlbnrzchqlegxbbmvdwjzwlbnqybojda however occasional key work here recent examples pages load return http found errors sitenamecomviewspamagwawnrexbyzxnlbnrzchqlegxbbmvdwjzwlbnqymjda sitenamecomviewspamagwawnrexbyzxnlbnrzchqlegxbbmvdwjzwlbnqybojda my htmlmappingspy contains following mapping rviewspamw viewspampage and viewspampage looks something like class viewspampagewebapprequesthandler def getself spamid selfresponseoutwritegot can anyone offer insight occurring may prevented thanks much,3 with thomas suggestion i came function import signal def inputortimeouttimeout def nothingsig frame pass signalsignalsignalsigalrm nothing signalalarmtimeout try rawinput signalalarm except ioerror eoferror pass it waits input timeout seconds under windows i suppose could replace rawinput getch msvcrt,i longrunning python script inside terminal session host machine freebsd box performs task every minutes now i like able interrupt sleep call moment performs task right away how i catching ctrl c option i need stop program rather merely interrupting sleep anything else i terminal window keyboard fine,2 as others pointed python batteries involves gui operations so it platform dependent if windows use win python module access win clipboard operations my suggestion though would picking one gui toolkit pyqtpyside qt pygtk gtk wxpython wxwidgets then use clipboard operations if don’t need heavy weight things toolkits make wrapper use win package windows whatever available platform switch accordingly for wxpython helpful links httpwwwwxpythonorgdocsapiwxclipboardclasshtml httpwikiwxpythonorgclipboard httpwwwpythonforumorgpythonforumviewtopicphpfampt,for example python script spit string giving path newly written file i going edit immediately running script would nice directly sent system clipboard rather stdout,1 you put test module inside module tests according the hitchhiker guide packaging here example towelstuff bin changestxt docs licensetxt manifestin readmetxt setuppy towelstuff initpy locationpy utilspy test initpy testlocationpy testutilspy this way module distributed tests users use verify works set see httpthehitchhikersguidetopackagingreadthedocsorgenlatestcreationhtml,i module sits namespace should tests data tests rely go namespace top level setuppy sites companyinitpy companynamespaceinitpy companynamespaceusefulpy companynamespacetestusefulpy companynamespacetestdatausefuldataxml setuppy companyinitpy companynamespaceinitpy companynamespaceusefulpy testusefulpy testdatausefuldataxml setuppy does question amount whether tests installed,3 i presume two instances application running instead fiddling namespaces i suggest turn analytics id configuration variable that either store config file database web using then set one id deployment place web running fetch runtime for example config file analyticsidua code datau analytics getvaluefromconfiganalyticsid getvaluefromconfig function define read appropriate value to use configuration files effortlessly may use configparser module now gained lot flexibility checking switching runtime you define value per web site done,my app serves multiple domains i understand done namespaces i researching since multiple domains multiple analytics ids i get analytics id code i want make even configurable osenvironget httphost endswith br osenviron servername endswith br datau analytics ua else datau analytics ua selfresponseoutwritetemplaterenderospathjoinospathdirnamefile templates name html data the sets analytics id brazilian domain id dot com but domains easiliy generalizable how i achieve function scientific scalable way becomes easy add application domain without manually adding domain application i suppose namespaces way go since domains google apps domains i understand use namespaces def namespacemanagerdefaultnamespaceforrequest determine namespace used request the value namespacepicker following effects if useservername read server name fooguestbookisvappspotcom set namespace if usegoogleappsdomain allow namespace manager infer namespace request if usecookie isv might gateway page sets cookie called namespace set namespace cookie value name none namespacepicker useservername name osenviron servername elif namespacepicker usegoogleappsdomain name namespacemanagergoogleappsnamespace elif namespacepicker usecookie cookies osenvironget httpcookie none cookies name cookiebasecookiecookiesget namespace return name i suppose i use namespace manager get namespace set analytics id according namespace thank,1 in testa variable class variable shared instances taa taa refer list in testb variable object variable each instance value see class object variables details,this script class testa class testb def initself selfa ta testa taaappend ta testa taaappend tb testb tbaappend tb testb tbaappend print taa taa tba tba produces output i expected why i wrong the definitions testa testb seem equivalent behavior change drastically edit this seems unintuitive different types like int str behave for reason lists created class variables initialized init ints strs created object variables matter,3 import numpy np nparray first possibility arepeat axis second npkrona both returning array,i wondering numpy function stretch array along specific axis like following thanks advance,2 one class variable instance variable class vars shared members class instance vars unique instance httpdocspythonorgtutorialclasseshtml,this script class testa class testb def initself selfa ta testa taaappend ta testa taaappend tb testb tbaappend tb testb tbaappend print taa taa tba tba produces output i expected why i wrong the definitions testa testb seem equivalent behavior change drastically edit this seems unintuitive different types like int str behave for reason lists created class variables initialized init ints strs created object variables matter,2 you you must dll,i c application would like take advantage one pythons libraries i seen info run python interpreter inside program however i want program selfsufficient i run windows computer even python how compile python c exe thanks,1 it helps remember class statement python much closer block statement case languages like c in python class statement contains bunch statements executed like def the difference interpreter block in case flow control block statements like interpreter executes block specified meaning flow control statement in def interpreter saves block executes whenever function object called in case class block python executes block immediately new scope uses whatever left scope execution finishes contents class so class testa python executes block then end scope contains bound empty list object so class not particular instance class class it inherits donothing constructor object instantiate class ta testa get empty instance then ask taa python finds instance variable named ta instance variables looks class testa this course finds finds one every instance testa get behaviour observed on hand class testb def initself selfa completely different here class block executed contents class scope single name time init bound function that becomes contents class now instantiate class testb python finds init class calls function new instance the execution function creates instance variable new instance so every instance testb gets variable get behaviour observed take home message class block python set declarations things contained instances class unlike traditional ooish languages like c java it actual code actually executed define contents class this really handy use statements results function execution anything would use context inside class body decide define class note i lied simplicity earlier even instances testa instance variables automatically created default instances see much daytoday python,this script class testa class testb def initself selfa ta testa taaappend ta testa taaappend tb testb tbaappend tb testb tbaappend print taa taa tba tba produces output i expected why i wrong the definitions testa testb seem equivalent behavior change drastically edit this seems unintuitive different types like int str behave for reason lists created class variables initialized init ints strs created object variables matter,2 well see file names write l contains file name and l filestrip seems unnecessary if want write file contents instead l openospathjoindir file rread,i currently working task got stuck please give advices the code i writing returns txt file name multiple folders i would like print content txt file save different rows excel the contents txt file numbers import os globxlwt create workbook worksheet wbk xlwtworkbook sheet wbkaddsheet data path ecagdata row dirsubdirfiles oswalkpath file files globfnmatchfnmatchfile txt l filestrip sheetwriterowl row wbksave readalltxtinfoldersxls print success,1 knowledge jpg support transparency probably want output png need set alpha channel nothing httpwwwtalkgraphicscomshowthreadphphowdoimakejpegimagebackgroundtransparent,i trying paste many small grayscale images bigger one all images jpegs the small images previously rotated black background what i wanted paste without background color words i need background color transparent thank suggestions,1 the simplest way python dict analyticsids mydomainbr ua mydomaincom ua data analytics analyticsidsselfrequesthost if perdomain stats may want make dictionary entry tuple nested dict configuration object sort fetch store current request easy reference if want able reconfigure runtime could use datastore model impose extra latency requests need fetch seems likely redeploying time add domain likely problem case namespaces tangential they good way divide rest data different domains useful dividing configuration data,my app serves multiple domains i understand done namespaces i researching since multiple domains multiple analytics ids i get analytics id code i want make even configurable osenvironget httphost endswith br osenviron servername endswith br datau analytics ua else datau analytics ua selfresponseoutwritetemplaterenderospathjoinospathdirnamefile templates name html data the sets analytics id brazilian domain id dot com but domains easiliy generalizable how i achieve function scientific scalable way becomes easy add application domain without manually adding domain application i suppose namespaces way go since domains google apps domains i understand use namespaces def namespacemanagerdefaultnamespaceforrequest determine namespace used request the value namespacepicker following effects if useservername read server name fooguestbookisvappspotcom set namespace if usegoogleappsdomain allow namespace manager infer namespace request if usecookie isv might gateway page sets cookie called namespace set namespace cookie value name none namespacepicker useservername name osenviron servername elif namespacepicker usegoogleappsdomain name namespacemanagergoogleappsnamespace elif namespacepicker usecookie cookies osenvironget httpcookie none cookies name cookiebasecookiecookiesget namespace return name i suppose i use namespace manager get namespace set analytics id according namespace thank,2 the answer chronographsh superseded chronograph despite supposedly able activate env early enough import argparse far tell inbuilt python getting right combination arguements chronograph script reference p e also run script root targetting script inside users virtualenv finally also add site paths packages directory chronograph script couldnt find argparse,i created custom management command py file usual place chronograph installed right place syncd ok i created cron job following homeshoftyvirtualenvswebbricksbinchronograph e homeshoftyvirtualenvswebbricksbinactivatethispy p homeshoftyvirtualenvswebbrickswebsite ive also tried following think may correct whats documentation homeshoftyvirtualenvswebbricksbinchronograph e homeshoftyvirtualenvswebbricksbinactivatethispy p homeshoftyvirtualenvswebbrickswebsitemanagepy cron i added managepy cron run tell chronograph function look jobs need running im virtual env run managepy cron works job runs jobs failing run try run manually su user fail due permissions denied sure permission referring anyone come across,1 i extending mercurial want test works tortoisehg correctly it good test compatibility official mercurial binaries tortoisehg they organized way namely python binaries stored libraryzip so make extension working either bundles need include extensions either py pyc form libraryzip configure extensions mercurialini while may possible force tortoisehg use another mercurial installation better offer users extension way use without adding extra mercurial installations systems so provide instruction integrate extension libraryzip,i installed mercurial python package now i want tortoisehg work however versions tortoisehg bundled version hg python libraries how i make sure tortoisehg using mercurial i installed,1 you find feeds head tag html files there specified link tags associated content type href attribute specifying location to extract feed urls page using python could use something like import urllib htmlparser import htmlparser class feedparserhtmlparser def initself args kwargs selffeeds set htmlparserinitself args kwargs def handlestarttagself tag attrs tag link try href attr attr attrs attr href except indexerror return none else type applicationatomxml attrs type applicationrssxml attrs selffeedsaddhref def getallfeedsfromurlurl f urlliburlopenurl contents fread fclose parser feedparser parserfeedcontents parserclose return listparserfeeds this code would extended quite bit though want cover quirky ways feed added html page,i looking code snippet language important extract feeds rss atom etc associated page so input url output list channels important completeness means page associated information channel found i asking preferably find html code find cover completeness thank,2 i use celery either single multiple machines onthefly strategy you aggregation task fetches data process task analyzes stores db this highly scalable approach tune according computing power the onthefly strategy efficient sense process data single pass the two involve extra step reretrieve data saved process of course everything depends nature data way process if process phase slower aggregation onthefly strategy hang wait completion processing but configure celery asynchronous continue aggregate data yet unprocessed,to analyze large number websites financial data pull parametric data optimal strategies i classifying following strategies either onthefly deferred which best onthefly process data onthefly store parametric data database deferred store source data ascii file system post process later processingdatadaemon deferred store pages blob database postprocess later processingdatadaemon number simplest especially single server can efficient single server see power multiple servers are python projects already geared toward kind analysis edit best i mean fastest execution prevent user waiting ease programming secondary,1 pyramid wsgi application this means dependent httphost environ key set host header determine host application it relative pointbeing pyramid restrictions accept thus world oyster set limit content various domains however like this course starts hosts webserver configured feed application assuming using url dispatch might want design custom route predicates check requesthost value whatever like returning false predicate prevent route ever matching request host this large topic might help give specifics for example since pyramid relative url may want generate examplecom redirect someone subexamplecom need done via pregenerator def pregenrequest elements kw kw appurl httpsubexamplecom return elements kw def reqsubinfo request return requesthoststartswith sub configaddroute subonly custompredicatesreqsub pregeneratorpregen configaddroute foo foo configaddviewview routename foo def viewrequest redirect user httpsubexamplecom regardless whether requesthost examplecom subexamplecom return httpfoundrequestrouteurl subonly,i looking multiple domains subdomains single pyramid instance however i seem find documentation the last question referred glossary little information examples do examples direct better documentation,3 the figurecanvasbase class located backends getsupportedfiletypes method for backendagg figure matplotlibfigurefigure fcb matplotlibbackendsbackendaggfigurecanvasbasefigure supportedfiletypes fcbgetsupportedfiletypes supportedfiletypes contains emf enhanced metafile eps encapsulated postscript pdf portable document format png portable network graphics ps postscript raw raw rgba bitmap rgba raw rgba bitmap svg scalable vector graphics svgz scalable vector graphics one remaining question matplotlibgetbackend returns agg is easier way directly point correct backend module,according matplotlib documentation matplotlibfiguresavefig takes optional argument format see matplotlibfigure documentation this parameters takes one file extensions supported active backend said official documentation my point know specific backend list supported extensions the list available backends accessible thru matplotlibrcsetupallbackends these backends available matplotlibbackends i find way retrieve supported extensions,1 if create figure get available supported file format canvas object import matplotlibpyplot plt fig pltfigure print figcanvasgetsupportedfiletypes svgz scalable vector graphics ps postscript emf enhanced metafile rgba raw rgba bitmap raw raw rgba bitmap pdf portable document format svg scalable vector graphics eps encapsulated postscript png portable network graphics list formats output current object,according matplotlib documentation matplotlibfiguresavefig takes optional argument format see matplotlibfigure documentation this parameters takes one file extensions supported active backend said official documentation my point know specific backend list supported extensions the list available backends accessible thru matplotlibrcsetupallbackends these backends available matplotlibbackends i find way retrieve supported extensions,3 you really need profile code find bottleneck here microoptimizations import numpy np import matplotlibpyplot plt import sys datafile sysargv data use autoclose file line opendatafile r line never false always least newline maybe mean linerstrip also try linestartswith instead line line line sure point linesplit allow number spaces need use list comprehension cols col col linesplit col filter userdefined function slow cols filterlambda x x linesplit indexcol enumeratecols made data collectionsdefaultdict initialized data defaultdictlist skip statement entirely lendata index dataappend dataindexappendfloatcol pltplotdatadata pltshow you may able something like opendatafile f lines linesplit line f linerstrip linestartswith data zipfloatcol col line line lines which give list tuple instead int keyed dict list otherwise appears identical it done oneliner i split make little easier read,i recently decided give matplotlibpyplot try used gnuplot scientific data plotting years i started simply reading data file plot two columns like gnuplot would plot datafile u the requirements comfort skip lines beginning skip empty lines allow arbitrary numbers spaces actual numbers allow arbitrary numbers columns fast now following code solution problem however compared gnuplot really fast this bit odd since i read one big advantage pyplotthon gnuplot speed import numpy np import matplotlibpyplot plt import sys datafile sysargv data line opendatafile r line line cols filterlambda x x linesplit indexcol enumeratecols lendata index dataappend dataindexappendfloatcol pltplotdatadata pltshow what would i make data reading faster i quick look csv module seem flexible comments files one still needs iterate lines file,1 this trickier might think split substring regex enough reliably tackle problem consider comments string literals inside sql code might contain text looks like sql contains parenthesis mess indentation levels a better way use sql parser here demo pythonsqlparse usrbinenv python import sqlparse sql select outer select outin select inner select innermax z x dateadddgetdate print sqlparseformatsql reindenttrue print select outer select outin select inner select innermax fromz wherex dateadddgetdatey,situation i several ssrs reports i need sqlcode documented for i need code formatted exactly way time time problem in reports i structures like select outer select outin select inner select innermax z x dateadddgetdate and i want result select outer select outin select inner select innermax z x dateadddgetdate but i problems indenting nested select i really appreciate provide examples i used splits regex substrings greetings,1 since matplotlib installed must also numpy installed numpygenfromtxt meets requirements much faster parsing file python loop import numpy np import matplotlibpyplot plt import textwrap fname tmptmpdat openfname w f fwritetextwrapdedent id col col col foo bar baz data npgenfromtxtfname comments skip comment lines dtype none guess dtype column namestrue use first line column names printdata pltplotdata id data col pltshow,i recently decided give matplotlibpyplot try used gnuplot scientific data plotting years i started simply reading data file plot two columns like gnuplot would plot datafile u the requirements comfort skip lines beginning skip empty lines allow arbitrary numbers spaces actual numbers allow arbitrary numbers columns fast now following code solution problem however compared gnuplot really fast this bit odd since i read one big advantage pyplotthon gnuplot speed import numpy np import matplotlibpyplot plt import sys datafile sysargv data line opendatafile r line line cols filterlambda x x linesplit indexcol enumeratecols lendata index dataappend dataindexappendfloatcol pltplotdatadata pltshow what would i make data reading faster i quick look csv module seem flexible comments files one still needs iterate lines file,3 it basically figure dolphin appears virtually always either bigrams dolphin watching miami dolphins sounds like want determine collocations dolphin occurs there various methods collocation finding popular compute pointwise mutual information pmi terms corpus select terms highest pmi dolphin you might remember pmi sentiment analysis algorithm i suggested earlier a python implementation various collocation finding methods included nltk nltkcollocations the area covered depth manning schã¼tze fsnlp still current topic,i trying write algorithm i assuming rely natural language processing techniques fill list search terms there probably name kind thing i unaware what kind problem called kind algorithm give following behavior input docs i bought ticket dolphin watching cruise i enjoyed dolphin watching tour the miami dolphins lost it good going miami dolphins game searchterm dolphin output dolphin watching miami dolphins it basically figure dolphin appears virtually always either bigrams dolphin watching miami dolphins solutions python preferred,3 there version available bit python windows you appear following options download source pypy port bit switch bit python option looks tractable,i trying use pypy windows x machine find way apparently win binary x binary installation guide i currently using python win python default jun msc v bit amd win installation sources raised following error translationerror windowserror error valid win application does anyone guidehint use pypy win or possible,2 a google query google maps caching kml seems indicate google caching kml files minutes a simple solution add random query url instead linking httpmapsgooglecommapsqhttpmy iplocationnamekml would link httpmapsgooglecommapsqhttpmy iplocationnamekmlrndsomerandomvalue your web server ignore google think new url refetch,i generate kml files ontheflyafter generating i call google maps like httpmapsgooglecommapsqhttpmy iplocationnamekml the name file i use based latlong starting location entered user obviously location new kml file generated starting location under circumstances old one overwritten but given google maps google maps shows old file am attaching snippets two sample files python code illustrate situation import sys import simplekml kmlsimplekmlkml dataopensysargv r line data pointslinesplit speedfloatpoints polykmlnewpolygondescriptionsegment numberstrpointsouterboundaryisfloatpointsfloatpointsfloatpointsfloatpointsfloatpointsfloatpointsfloatpointsfloatpoints polypolystyleoutline kmlsaveoverwritekml i call code sample twice two different files snippets posted file file snippet first kml file tessellatetessellate extrudeextrude coordinates coordinates linearring outerboundaryis polygon styleurlstyleselstyleurl visibilityvisibility openopen descriptionsegment numberdescription placemark placemark idfeat polygon idgeom tessellatetessellate extrudeextrude outerboundaryis linearring tessellatetessellate extrudeextrude coordinates coordinates linearring outerboundaryis polygon styleurlstyleselstyleurl visibilityvisibility openopen descriptionsegment numberdescription placemark document kml snippet nd kml file tessellatetessellate extrudeextrude coordinates coordinates linearring outerboundaryis polygon styleurlstyleselstyleurl visibilityvisibility openopen descriptionsegment numberdescription placemark placemark idfeat polygon idgeom tessellatetessellate extrudeextrude outerboundaryis linearring tessellatetessellate extrudeextrude coordinates coordinates linearring outerboundaryis polygon styleurlstyleselstyleurl visibilityvisibility openopen descriptionsegment numberdescription placemark document kml snapshot kml file generated cases i cleared cache evenbefore making nd request thanks sorry long description but i hope make things clear,1 if want write file contents instead openospathjoindir file r source l sourceread this assures file actually closed done reading that releases system resources,i currently working task got stuck please give advices the code i writing returns txt file name multiple folders i would like print content txt file save different rows excel the contents txt file numbers import os globxlwt create workbook worksheet wbk xlwtworkbook sheet wbkaddsheet data path ecagdata row dirsubdirfiles oswalkpath file files globfnmatchfnmatchfile txt l filestrip sheetwriterowl row wbksave readalltxtinfoldersxls print success,1 use list comprehension ternary operation conditional expression xxx item abc else item item mylist,code mylist abc def ghi mylist abc def ghi iv enumeratemylist v abc mylisti xxx mylist xxx def ghi here i try replace occurrences abc xxx is shorter way,3 instead using explicit loop use list comprehension this allows iterate elements list filter map new value in case use conditional expression it similar v abc xxx v languages putting together use code mylist xxx v abc else v v mylist,code mylist abc def ghi mylist abc def ghi iv enumeratemylist v abc mylisti xxx mylist xxx def ghi here i try replace occurrences abc xxx is shorter way,3 pypy compatible bit windows primary reason sizeofvoid sizeoflong bit annoying contributions welcome,i trying use pypy windows x machine find way apparently win binary x binary installation guide i currently using python win python default jun msc v bit amd win installation sources raised following error translationerror windowserror error valid win application does anyone guidehint use pypy win or possible,3 yes single underscore usage endorsed pep internaluse classes i believe double underscore usage real effect time since used active name mangling class attributes generally class attribute another class granted case python happily mangle name,i seen code functionsconstants prefixed underscores my understanding indicates used directly can i classes class fooobject pass class barobject pass,2 you use single underscore first character variable carries implied meaning do use outside classmodule unless really know eg intended protectedinternal import use module import using double underscore something never outside class could mess name mangling otherwise could i mean caused big headache past week i realize,i seen code functionsconstants prefixed underscores my understanding indicates used directly can i classes class fooobject pass class barobject pass,1 better use one this indicates name private within module it imported catchall module import features preferred destruction from if defined set public names includes names found module’s namespace begin underscore character from starting version python guarantees globals whose name begins single underscore deleted module globals deleted doubleunderscore starting class members namemangled,i seen code functionsconstants prefixed underscores my understanding indicates used directly can i classes class fooobject pass class barobject pass,3 yes convention when import module names starting underscore imported,i seen code functionsconstants prefixed underscores my understanding indicates used directly can i classes class fooobject pass class barobject pass,1 memcached i think primarily understands byte representation byte languages you serialize objects using protocol buffers similar library consume language i done projects,i working system components written following languages c c c php python these components use infrequently changing data comes source cached accesed memcache performance reasons because different data types may stored differently different language apis memcache i wondering would better store all data string objects stored json string however may pose problems strings almost surely different internal representations accross different languages i wondering wise decision as aside i using writer multiple readers pattern concurrency issue can anyone preferably actual experience something similar advice best formatway store data memcache may consumed different programming languages,2 the first line rationale section pep says python adds command line switch allow modules located using python module namespace execution scripts the motivating examples standard library modules pdb profile python implementation fine limited purpose so specify module python search path way files current directory you correct python mymodpy mymodpy args exactly effect the first line scope proposal section states in python module located using executed filename provided command line with possible like working modules part package etc that rest pep read info,could explain difference calling python mymod mymodpy args python mymodpy mymodpy args it seems cases mymodpy called sysargv mymodpy mymodpy args so switch,3 sometimes migrate much work want column automatically added run changed code so function caveats pokes around sqlalchemy internals tends require small changes every time sqlalchemy undergoes major revision there probably much better way i sqlalchemy expert it also handle constraints import logging import import sqlalchemy sqlalchemy import metadata table exceptions import sqlalchemyengineddl newsaddl sqlalchemyversionstartswith def createandupgradeengine metadata for table metadata database create if database add missing columns warn columns whose spec changed dbmetadata metadata dbmetadatabind engine modeltable metadatasortedtables try dbtable tablemodeltablename dbmetadata autoloadtrue except exceptionsnosuchtableerror logginginfo creating table modeltablename modeltablecreatebindengine else newsaddl ddlc enginedialectddlcompilerenginedialect none else ddlc enginedialectddlcompilerenginedialect dbtable else ddlc enginedialectschemageneratorenginedialect enginecontextualconnect loggingdebug table already exists checking missing columns modeltablename modelcolumns columnnamesmodeltable dbcolumns columnnamesdbtable tocreate modelcolumns dbcolumns toremove dbcolumns modelcolumns tocheck dbcolumnsintersectionmodelcolumns c tocreate modelcolumn getattrmodeltablec c logginginfo adding column ss modeltablename modelcolumnname assert modelcolumnconstraints arrrgh i cannot automatically add columns constraints database please consider fixing care modelcolspec ddlcgetcolumnspecificationmodelcolumn sql alter table add modeltablename modelcolspec engineexecutesql it difficult reliably determine model changed column definition eg default precision columns none means database decides therefore i look model may give sql column integer i look database i definite precision therefore returned type integer c tocheck modelcolumn modeltablecc dbcolumn dbtablecc x modelcolumn dbcolumn loggingdebug checking column ss modeltablename modelcolumnname modelcolspec ddlcgetcolumnspecificationmodelcolumn dbcolspec ddlcgetcolumnspecificationdbcolumn modelcolspec resub modelcolspec dbcolspec resub dbcolspec dbcolspec dbcolspecreplace decimal numeric dbcolspec dbcolspecreplace tinyint bool modelcolspec dbcolspec loggingwarning column ss specification r model r database modeltablename modelcolumnname modelcolspec dbcolspec modelcolumnconstraints dbcolumnconstraints todo check constraints loggingdebug column constraints checked i dumb c toremove modelcolumn getattrdbtablec c loggingwarning column ss database model modeltablename modelcolumnname def columnnamestable autoloaded columns return unicode column names make sure treat equal return setunicodeiname tablec,i want add field existing mapped class would i update sql table automatically does sqlalchemy provide method update database new column field added class,3 edit since csr format good row slicing csc format good column slicing i think listener solution b atocsrlist tocsc list faster one i show you could anparraylistnpnewaxisnparraylist numpy indexing many different behaviors depending type arguments you picking arbitrary rows columns use basic slicing that leaves socalled advanced indexing the key thing remember advanced indexing ndarrays arr arr ndarrays ij component aarrarr equals aarrijarrij thus want arrij equal listi j want arrij equal listj that arranged help broadcasting see setting arrnparraylistnpnewaxis arrnparraylist the shape arr lenlist shape arr lenlist broadcasted lenlist since new axes added left each array broadcasted shape lenlistlenlist this exactly want aarrijarrij make sense since want ij run possible indices result array shape lenlistlenlist import numpy np import scipysparse sparse import random randomseed list list n a sparselilmatrix nn xrangen arandomrandintnrandomrandintnrandomrandint x alist x xlist printxtoarray batocsc tocsr printbnparraylistnpnewaxisnparraylisttoarray,i would appreciate help understand following behavior slicing lilmatrix a scipysparse package actually i would like extract submatrix based arbitrary index list rows columns when i used two lines code x alist x xlist everything fine i could extract right submatrix when i tried one line failed the returning matrix empty xalist list why overall i used similar command matlab works so use first since works it seems quite time consuming since i go large amount entries i would like speed using single command maybe i use wrong sparse matrix typeany idea,3 i would suggest use selenium instead mechanizetwill mechanize would fail handling javascript,been scouring net something like firewatir python i trying automate firefox linux any suggestions,1 if really need could save instance first pk def saveself args kwargs selfpk none superorder selfsaveargs kwargs selfarticlesall selftotal aprice superorder selfsaveargs kwargs,my models look like class articlemodelsmodel name modelscharfieldmaxlength description modelstextfield price modelsfloatfield def unicodeself return selfname selfprice class ordermodelsmodel client modelsforeignkeyuser articles modelsmanytomanyfieldarticle total modelsfloatfieldeditablefalse blanktrue default def unicodeself return selfclientusername selftotal def saveself selfarticles selftotal aprice superorder selfsave and i try calculate total price save if i try save order via admin i get order instance needs primary key value manytomany relationship used if i call superorder selfsave calculating sum i get manyrelatedmanager object iterable i know i thought calculating total view i would like store database how i iterate articles ordermodel thanks advance,1 well course access objects attributes methods specific object eg class aobject def methodself othersomevar class bobject pass def main a b b bsomevar hello world amethodb printbsomevar prints,way pass value variable class another class without pass main function i using python,1 regardless backend chosen memcached mongodb redis mysql carrier pigeon speedefficient way store data would simple block data backend knowledge whether string byte blob really each language need agreed mechanism convert objects storable data format back you shouldn build mechanism reinventing wheel should think whether invalid objects might end backend either bug writer objects previous revision still present when comes choosing format i recommend two json protocol buffers this encoded size encodedecode speed among smallestfastest available encodings comparison json libraries available dozens languages sometimes part standard library very simple format humanreadable stored humanwritable no coordination required different systems agreement object structure no setup needed many languages eg php data jsonencodeobject object jsondecodedata no inherent schema readers need validate decoded messages manually takes space protocol buffers protocol buffers generating tools provided several languages minimal size difficult beat defined schema externally proto files autogenerated interface objects encodingdecoding eg c personserializetoostreamampoutput support differing versions object schemas add new optional members existing objects necessarily invalidated not humanreadable writable possibly harder debug defined schema introduces configuration management overhead unicode when comes unicode support handle without issues json will typically escape nonascii characters inside string uxxxx compatibility problem depending library may also possible force utf encoding protocol buffers seem use utf though i found info google documentation foothigh letters effect summary which one go depend exactly system behave often changes data structure occur points affect,i working system components written following languages c c c php python these components use infrequently changing data comes source cached accesed memcache performance reasons because different data types may stored differently different language apis memcache i wondering would better store all data string objects stored json string however may pose problems strings almost surely different internal representations accross different languages i wondering wise decision as aside i using writer multiple readers pattern concurrency issue can anyone preferably actual experience something similar advice best formatway store data memcache may consumed different programming languages,1 one way install signal handler sigterm directly calls osexitsignalsigterm however unless specify optional timeout argument queueget signal handler function run get method returns that completely undocumented i discovered so specify sysmaxint timeout put queueget call retry loop purity get around,i start bunch threads working queue i want kill sending sigint ctrlc what best way handle targets queuequeue threadsnum threads threadsnum mythread tsetdaemontrue threadsappendt tstart targetsjoin,1 x x for details slices like refer documentation,i string x verylongstringmorethancharlong i want keep first char delete rest would thanks,3 use powerful slicing mechanism x x,i string x verylongstringmorethancharlong i want keep first char delete rest would thanks,2 x fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo lenx x leny fooooooooooooooooooooooooooooooooooooooooooooooooo,i string x verylongstringmorethancharlong i want keep first char delete rest would thanks,1 you could use slicing x verylongstringmorethancharlong print x,i string x verylongstringmorethancharlong i want keep first char delete rest would thanks,1 events propagate children mygrid child main frame events posted main make mygrid what instead bind event handler directly function within instance mygrid like mainwindow selfworkerthread ftpthread selfmygrid mygrid bind event evtresultself selfmygridupdatefromevent i familiar kind binding i typically use wxbind,i following example given httpwwwblogpythonlibraryorgwxpythonandthreads i thread checking sftp server new files every seconds if finds files uploads db trigger update certain gui elements reload db the custom event code evtresultid wxnewid def evtresultwin func define result event winconnect evtresultid func class resulteventwxpyevent simple event carry arbitrary result data def initself data init result event wxpyeventinitself selfseteventtypeevtresultid selfdata data the ftp thread class ftpthreadthreadingthread def initselfwxobject init worker thread class threadingthreadinitself selfwxobject wxobject selfstop threadingevent selfstopset selfstart start thread def runself true timesleep selfstopisset wxcallafterselfparseftp def stopself selfstopset def resumeself selfstopclear def parseftpself connect db connect sftp site filesfoundfalse process file delete file dirlist filesfoundtrue process db sftpremovefile sftpclose tclose trigger update event files found filesfoundtrue wxposteventselfwxobject resulteventfiles found one gui elements class mygridwxgridgrid def initself parent wxgridgridinitself parentstylewxexpand selfparentparent selfupdate evtresultself selfupdatefromevent def updatefromeventselfevent selfupdate def updateself following debugging wxpostevent created triggering response grid the difference i find example code example evtresult main frame gui element required,1 i replace total field property class order property def totalself return selfarticlesaggregatesum price pricesum reason add items collection object saved update counter with property sure always correct data,my models look like class articlemodelsmodel name modelscharfieldmaxlength description modelstextfield price modelsfloatfield def unicodeself return selfname selfprice class ordermodelsmodel client modelsforeignkeyuser articles modelsmanytomanyfieldarticle total modelsfloatfieldeditablefalse blanktrue default def unicodeself return selfclientusername selftotal def saveself selfarticles selftotal aprice superorder selfsave and i try calculate total price save if i try save order via admin i get order instance needs primary key value manytomany relationship used if i call superorder selfsave calculating sum i get manyrelatedmanager object iterable i know i thought calculating total view i would like store database how i iterate articles ordermodel thanks advance,2 information concerning process memory exposed wmi using winprocess class in particular probably interested workingsetsize virtualsize properties since starting service want obtain processid property service order select appropriate winprocess instance monitoring total memory consumption iis bit complex iis spins multiple processes services depending configured see hierarchy managed entities described but let assume example interested memory consumed wsvc implements actual http protocol assuming using tim golden fantastic wmi library would need something like import wmi c wmiwmi wwwsrv cwinservicename wsvc process cwinprocessprocessid wwwsrvprocessid print memory used wsvc processworkingsetsize,i trying retrieve amount memory used windows service example iis i using python windows wmi extensions i find method winservice class would give information i need what best approach get information,1 both ruby python able connect ms sql databases python libraries pytds pymssql ruby libraries tinytds seem dbi compliant activerecord adapter,i using php number years found relatively well documented easy work setup use one main advantages capablility working without many modifications similarly windows nix platforms it also good support connecting microsoft sql servers particular mssql module ntwdblibdll freetds that said time i spend developing php i feel need pick another scripting language broaden skill set develop better webbased applications because i spent time exploring alternative scripting languages effort evaluate suitability at present biggest hurdle i come accross support provided recent versions open source scripting languages specifically python ruby node windows os winxp case microsoft sql server my existing working environ necessitates requirement connecting mssql database i looking answers developers experience working either python ruby nodejs using interacting ms sql server what would recommended open source scripting language good support ms sql server ideas welcome p,1 it explained logging module howto you could create helper module included wherever perform logging import logging logginggetlogger yourtoplevelpackage addhandlerloggingnullhandler,i making extensive use logging module modules this works fine i create configuration logging module main routine but i want test one modules individually interactive shell logginggetloggerfoo executed i get error no handlers could found logger foo this makes sense course logging module configured yet when i call loggingbasicconfig modules logs printed python doc also says call basicconfig main thread so done cleanly can i check logging module already configured,1 isn ctrl c sigint anyway install handler appropriate signal handler set global flag instructs workers exit make sure check periodically put shutdown tokens queue workers exit pop magic token set flag instructs main thread push tokens make sure main thread checks flag etc mostly depends structure application interrupting,i start bunch threads working queue i want kill sending sigint ctrlc what best way handle targets queuequeue threadsnum threads threadsnum mythread tsetdaemontrue threadsappendt tstart targetsjoin,2 try change working directory calling dll in vba code chdircpython change workingdirectory python call dll call dll chdirapppath change back folder maybe want save current folder bevore change first time change back regards thomas,from vba vb i calling dll creates python interpreter if i set path environment variable point cpython pythonpath cpythonlib fine if i set path calling pyinitialise crashes xl vb app even i call pysetprogramname cpythonpythonexe first i like specify installation vbvba rather set environment i xl works ok vb,1 probably myapi myapi uri redirecting one you finetune behavior httpdocscherrypyorgdevrefmanlibcptoolshtmlcherrypylibcptoolstrailingslash,i developing web api using cherrypy the intent accessed javascript nslxmlhttprequest when i access api firefox though ordinaryvariety url following appears logs success ip sep get myapi http mozilla windows nt rv gecko firefox that success printed start code runs myapi page but i access javascript following appears logs ip sep get myapiargvalueampargvalue http requesting page mozilla windows nt rv gecko firefox arguments optional notice second case success never printed code never executed status code moved permanently any idea would cause cherrypy,2 it would better remove whitespace round brackets simply split comma,i would like convert mystring list input output mystring mystringresubr mystring remove whilespaces print mystring splitter recompiler d print splittersplitmystring in list first last element empty unwanted is better way thank,1 refindallr,i would like convert mystring list input output mystring mystringresubr mystring remove whilespaces print mystring splitter recompiler d print splittersplitmystring in list first last element empty unwanted is better way thank,3 do absolutely use pil if might able get want using pyqt builtin webkit control see httpnotesalexdongcomxhtmltopdfusingpyqtwebkitandheadless example converts htmlcss pdf without using separate browser the code pretty short i copied import sys pyqtqtcore import pyqtqtgui import pyqtqtwebkit import app qapplicationsysargv web qwebview webloadqurlhttpwwwgooglecom webshow printer qprinter printersetpagesizeqprintera printersetoutputformatqprinterpdfformat printersetoutputfilenamefilepdf def convertit webprintprinter print pdf generated qapplicationexit qobjectconnectweb signalloadfinishedbool convertit sysexitappexec,is way take screenshot using pil specified htmljavascript page resides server i want write script change parameters html page pil take screenshots any ideas examples would truly appreciated,1 go django elvis fans wrong or roll scratch you learn lot know everything site works better appreciate framework,the site complicated resemble modern blog users messages news similar features do i need use framework best pyramid django,1 depending need use x probably want ctypescreatestringbuffer x ctypescreatestringbuffer,how could i write definition copied bellow using ctypes unsigned char x new unsigned char thank,1 it depends kind website planning come if website going set static html files really need framework but website lots dynamic content get updated regular basis go framework that make life maintaining website much simpler django popular framework written python it good documentation strong community base,the site complicated resemble modern blog users messages news similar features do i need use framework best pyramid django,2 check chapter python manual does satisfy,what purpose python variables something eg name file i often see real python programs is list variables thank,1 pep covers in addition following special forms using leading trailing underscores recognized generally combined case convention singleleadingunderscore weak internal use indicator eg m import import objects whose name starts underscore singletrailingunderscore used convention avoid conflicts python keyword eg tkintertoplevelmaster class classname doubleleadingunderscore naming class attribute invokes name mangling inside class foobar boo becomes foobar boo see doubleleadingandtrailingunderscore magic objects attributes live usercontrolled namespaces eg init import file never invent names use documented the final bullet point pertinent is list variables i doubt official list double leading trailing underscore names i could say sure,what purpose python variables something eg name file i often see real python programs is list variables thank,3 they considered special magic the language prevent creating here good guide magic methods also special attributes normally pronounced dunder,what purpose python variables something eg name file i often see real python programs is list variables thank,1 did define immediatehttpresponse i it possible get symptom describing tastypie raising tastypieexceptionsimmediatehttpresponse unit test testing locally defined immediatehttpresponse if fix problem delete definition immediatehttpresponse put something like tastypieexceptions import immediatehttpresponse unit test instead,i python django unit test fail exception failing code try except block written exception a similar block handles exception directly raised this passes code catches directly raised immediatehttpresponse try raise immediatehttpresponseresponseauthresult selffail except immediatehttpresponse e selfasserttruetrue this immediately following fails fail try resp resourcedispatchlistrequest line selffail except immediatehttpresponse e selfasserttruetrue here trace traceback recent call last file webapptestsapitastypieauthenticationpy line testdispatchlistdiagnostic resourcedispatchlistrequest file librariesdjangotastypietastypieresourcespy line dispatchlist return selfdispatch list request kwargs file librariesdjangotastypietastypieresourcespy line dispatch selfisauthenticatedrequest file librariesdjangotastypietastypieresourcespy line isauthenticated raise immediatehttpresponseresponseauthresult immediatehttpresponse per trace dispatchlist call fails raises immediatehttpresponse exception but placing exception try block create similar failure why try except block handling one exception note test code copied library test code run expected i using library test code diagnose implementation failures,2 you certainly need webframework create simple website given new python interested building python website i imagine implies interested learning python if exclusively interested learning djangopython reason jump django ronak said course he right it lot documentation but make somewhat odd intro python if i shoes i either start making offline programs first consider ultralightweight framework many would advocate webpy pyramid ultralightweight i might consider going even lighter something like bottle less pairing functions urls this way least bit hackingtrialanderror instead launching right django it django use python tell many times fact python but adapted core used large business setting chicago something online think so enforces various rules helpful managing many different employees working project together you may may wish kind help it also means scale projects assumed large timehorizon limitless if want see python dictionary works may want spend long time configuring settings creating pseudostatictyping need database execute project see result i realize i automatically get downvoted i believe sound advice,the site complicated resemble modern blog users messages news similar features do i need use framework best pyramid django,3 please see httpcodedjangoprojectcomticket need cygwin try files httpsourceforgenetprojectsgettextfiles edit httpftpgnomeorgpubgnomebinarieswindependenciesgettexttoolszip httpftpgnomeorgpubgnomebinarieswindependenciesgettextruntimezip links thread httpgroupsgooglecomgroupdjangoinbrowsethreadthreadafdaefpli,running django windows i currently trying translate couple django templates using instructions found django book chapter i added translation tag template loaded in modified django settings then i run djangoadminpy makemessages l en create po files all folders created django terminates following error error errors happened running xgettext init py xgettext recognized internal external command operable program batch file reading problem i discovered django uses gnu gettext library unix based systems to remedy i installed cygwin downloaded installed gettext package version i added path sadly solve anything cygwin add xgettext files whatsoever my question is easy way tutorial install xgettext functionality django internationalization require windows without download ton assorted gnu packages django excellent far minimizing unnecessary hardships sudden difficulties characteristic django,3 import numpy np matricesnprandomrandom range npmaxnphstackmatrices will give maximum value n matrices this basically merges matrices matrices single array using nphstack takes max new array this assumes matrices number rows you also use npvstack npconcatenate achieve similar effect edit i reread question might actually want something like npmaxnpdstackmatricesaxis this stack matrices along third axis give max along direction returning x matrix case edit here timings in matrices nprandomrandom range in timeit npdstackmatricesmax loops best us per loop in timeit nparraymatricesmaxaxis loops best us per loop in timeit reducenpmaximum matrices loops best us per loop larger arrays in matrices nprandomrandom range in timeit npdstackmatricesmax loops best ms per loop in timeit nparraymatricesmaxaxis loops best ms per loop in timeit reducenpmaximum matrices loops best ms per loop steven wins,hey guys i like know best fatestoptimized way getting maximum values elementwised n matrices pythonnumpy for example import numpy np matricesnprandomrandom range function npmaximum numpy works two matrices maxmatrixnpmaximummatricesmatrices maxmatrixnpmaximummatrices error how would overcome problem,2 i run benchmark there difference c numpy machine do think approach fair unnecessary overheads i avoid it seems fair due difference results would expect result would show huge discrepancy c python approach both using shared objects calculations no since i would rather use python program could i increase performance calling blas lapack routines make sure numpy uses optimized version blaslapack libraries system,i would like write program makes extensive use blas lapack linear algebra functionalities since performance issue i benchmarking would like know approach i took legitimate i speak three contestants want test performance simple matrixmatrix multiplication the contestants numpy making use functionality dot python calling blas functionalities shared object c calling blas functionalities shared object scenario i implemented matrixmatrix multiplication different dimensions runs increment matricies set like numpyrandomrandiiastypenumpyfloat numpyrandomrandiiastypenumpyfloat numpy the code used looks like tnumpy timeittimernumpydotm import numpy main import rnumpyappendi tnumpyrepeat python calling blas shared object with function blaslib ctypescdllloadlibrarylibblasso def mulm r notrans ccharn n cinti one cfloat zero cfloat blaslibsgemmbyrefnotrans byrefnotrans byrefn byrefn byrefn byrefone mctypesdataasctypescvoidp byrefn mctypesdataasctypescvoidp byrefn byrefzero rctypesdataasctypescvoidp byrefn test code looks like r numpyzerosii numpyfloat tblas timeittimermulm r import numpy main import r mul rblasappendi tblasrepeat c calling blas shared object now c code naturally little longer i reduce information minimum i load function void handle dlopenlibblasso rtldlazy void func dlsymhandle sgemm i measure time gettimeofday like gettimeofdayampstart null fampnotrans ampnotrans ampdim ampdim ampdim ampone a ampdim b ampdim ampzero return ampdim gettimeofdayampend null dtimesj calctimestart end j loop running times i calculate time passed double calctimetimeval start timeval end double factor return doubleendtvsec factor doubleendtvusec doublestarttvsec factor doublestarttvusec factor results the result shown plot questions do think approach fair unnecessary overheads i avoid would expect result would show huge discrepancy c python approach both using shared objects calculations since i would rather use python program could i increase performance calling blas lapack routines download the complete benchmark downloaded jf sebastian made link possible,3 some general help instead fin open exampletxt you use open exampletxt r fin indent rest code version work l word fin it iterate word line if one word per line still newline end word wordrstrip clear whitespace end word if actually want one word time need two loops like line fin word linesplit put logic inside inner loop lenword lappendword with stripping whitespace add word five letters longer list word word lappendword word always equal word nothing if want eliminate duplicates make l set use laddword instead lappendword words want add list assuming order matter word xx lappendword if trying see ends xx use wordendswith xx instead word without otherwise comparing nexttolastletter rather whole thing word wordlower lappendword this adds word list word lowercase keep mind tests applied every word add word list test passes if want add use elif instead tests except first one your comments also imply somehow getting rid words adding list you keeping ones add list rest go away changing file way,every time i try run program python idle responds telling responding close any suggestions improve code make work way i want open text document filter words document appending empty list get rid words show get rid words lowercase get rid words end substring xx get rid words less characters print list fin open exampletxt l word fin lenword lappendword word word lappendword word xx lappendword word wordlower lappendword print l,2 use reduce reducenpmaximum matrices from docs reduce function iterable initializer apply function two arguments cumulatively items iterable left right reduce iterable single value for example reducelambda x xy calculates the left argument x accumulated value right argument update value iterable if optional initializer present placed items iterable calculation serves default iterable empty if initializer given iterable contains one item first item returned,hey guys i like know best fatestoptimized way getting maximum values elementwised n matrices pythonnumpy for example import numpy np matricesnprandomrandom range function npmaximum numpy works two matrices maxmatrixnpmaximummatricesmatrices maxmatrixnpmaximummatrices error how would overcome problem,3 cairo createfordata wants writeable buffer object string used buffer object writable supports bit per channel data rgba rgb followed one unused byte pil hand provides bpc rgb readonly buffer object i suggest tell pil add alpha channel convert pil buffer numpy array get writable buffer cairo im imageopenfilename imputalpha create alpha channel arr numpyarrayim height width channels arrshape surface cairoimagesurfacecreatefordataarr cairoformatrgb width height,i trying create cairo imagesurface pil image code i far im imageopenfilename imstr imtostring arrayarray b imstr height width imsize stride cairoimagesurfaceformatstrideforwidthcairoformatrgb width return cairoimagesurfacecreatefordataa cairoformatargb width height stride but giving typeerror buffer long enough i really understand perhaps i understand image formats well enough i using cairo,2 if i understand problem correctly want interact ie send commands read responses console application if may want check expectlike library like pexpect python httppexpectsourceforgenet it make life easier take care synchronization problem ddaa also describes see also httpwwwnoahorgwikipexpectqwhynotjustuseapipepopenf,i like execute multiple commands standalone application launched python script using pipes the way i could reliably pass commands stdin program using popencommunicate closes program command gets executed if i use popenstdinwrite command executes time work reliable what i wrong to elaborate bit i application listens stdin commands executes line line i like able run application pass various commands based users interaction gui this simple test example import os string subprocess import popen pipe command anapplication process popencommand shellfalse stderrnone stdinpipe processstdinwritedosomethingn processstdinflush processstdinwritedosomethingn processstdinflush i expect see result commands i get response if i execute one popenwrite lines multiple times occasionally works and i execute processcommunicatedosomething works perfectly application terminates,1 import def bywordsit pat recompile w line word patfindallline yield word def keepersit words set lens sslower sendswith xx wordsadds return listwords to get words war peace urllib import urlopen source urlopen httpwwwgutenbergorgebookstxtutf print keepersbywordssource prints raining divinely hordes nunnery parallelogram this take much memory war peace words fit criteria the iterators work small chunks,every time i try run program python idle responds telling responding close any suggestions improve code make work way i want open text document filter words document appending empty list get rid words show get rid words lowercase get rid words end substring xx get rid words less characters print list fin open exampletxt l word fin lenword lappendword word word lappendword word xx lappendword word wordlower lappendword print l,1 how import abcdelog myregexp recompiler dddw myregexpmatcha sresrematch object xbf mgroups abcde log,for example i string abcdelog i want check string matchs ddd dont think correct syntax get idea and i need split string parts abcdee log how i python thanks,1 there split method module work abcdelog resplit ddd abcde log if actually want date part returned list omit parentheses around regular expression capturing group resplit ddd abcde log be advised pattern matches ie one date filename split for example abcdefghijlog resplit ddd abcde fghij log if problem use maxsplit argument split split first occurrence date resplit ddd abcde fghijlog,for example i string abcdelog i want check string matchs ddd dont think correct syntax get idea and i need split string parts abcdee log how i python thanks,1 you looking method job different thread gui mainloop you could check start major gui frameworks wxpython pyqt methods run long running applications without freezing gui personally i prefer use directly python thread module,i little experience gui programming i writing gui application pyqt with application user open binary file editing when file opened i processing takes so user pick file press open button file open dialog gui frozen what best way achieve better user experience thanks,1 load background showing progress via gauge statusbar to initiate loading using qthread your thread class look follows assuming parent attribute progress qtfileloaderqtcoreqthread def initselfparentnone filepathnone qtcoreqthreadinitselfparent selfdata none selffilepath filepath def runself load data parts update progess par chunksize filesize todo get length file nparts intfilesizechunksize openselffilepath rb f rangenparts selfdata freadchunksize selfparentprogress the question whether use qthread trheadingthread discussed edit according hint nathan on parent timerfunction check say ms value selfparentprogress set progressbar accordingly this way progressbar set within main thread gui,i little experience gui programming i writing gui application pyqt with application user open binary file editing when file opened i processing takes so user pick file press open button file open dialog gui frozen what best way achieve better user experience thanks,1 start python run import tempfile print tempfilegettempdir cusersappdatalocaltemp go directory delete files start devappserver,i using google appengine python sdk windows project i get following error trying launch app running command cpythonpythonwexe cprogram filesgooglegoogleappenginedevappserverpy adminconsoleserver port eprogrammingpythonnotepyd warning urlfetchstubpy no ssl package found urlfetch able validate ssl certificates error devappservermainpy type exceptionseoferror process exited code this happened power failure how i fix,3 you need periodically ask application process events pending event queue you calling processevents method qapplication instance if intersperse calculations calls processevents gui progress bars update note making gui responsive to make gui responsive performing load need split load operation background thread you cannot perform gui operations background thread though background thread emit signals cross thread boundaries here article multithreaded pyqt programming,i little experience gui programming i writing gui application pyqt with application user open binary file editing when file opened i processing takes so user pick file press open button file open dialog gui frozen what best way achieve better user experience thanks,1 making copies parameters justincase bad idea end paying lousy performance keep track sizes arguments instead better get good understanding objects names python deals a good start article the importart point def modilistalist alistappend somelist modilistsomelist printsomelist exactly affect somelist samelist somelist samelistappend printsomelist function call copying arguments taking place creating pointers taking place taking place python saying alist somelist executing code function modilist in words python binding assigning another name object finally function going modify arguments want changes visible outside function usually shallow copy def dontmodilistalist alist alist make shallow copy alistappend now somelist alist two different list objects happen contain objects messing list object inserting deleting rearranging fine buf going go even deeper cause modifications objects list need deepcopy but keep track things code appropriately,a times i accidentally modified input function since python constant references i wondering coding techniques might help avoid making mistake often example class table def initself fields rawdata fields dictionary field names keys types value sometimes want delete elements fieldname datatype fieldsitems someconditionfieldname rawdata del fieldsfieldname another module fields already initialized dictionary table tablefields rawdata fields corrupted table init table tablefields rawdata of course fix make copy parameter i change def initself fields rawdata fields copycopyfields copycopy safer generally applicable copy but easy forget i half thinking make copy argument beginning every function unless argument potentially refers large data set may expensive copy unless argument intended modified that would nearly eliminate problem would result significant amount useless code start function in addition would essentially override python approach passing parameters reference presumably done reason,2 if run appdebug true serve media files images css js etc flask also count full requests if case please provide information setup,i added apploggererror test inside appbeforerequest noticed lines test log per request even abort i seem find could cause,2 there best practice python called unit testing the main point dynamic languages allows much rapid development even full unit tests unit tests much tougher safety net static typing as writes martin fowler the general argument static types catches bugs otherwise hard find but i discovered presence selftestingcode bugs static types would found easily tests,a times i accidentally modified input function since python constant references i wondering coding techniques might help avoid making mistake often example class table def initself fields rawdata fields dictionary field names keys types value sometimes want delete elements fieldname datatype fieldsitems someconditionfieldname rawdata del fieldsfieldname another module fields already initialized dictionary table tablefields rawdata fields corrupted table init table tablefields rawdata of course fix make copy parameter i change def initself fields rawdata fields copycopyfields copycopy safer generally applicable copy but easy forget i half thinking make copy argument beginning every function unless argument potentially refers large data set may expensive copy unless argument intended modified that would nearly eliminate problem would result significant amount useless code start function in addition would essentially override python approach passing parameters reference presumably done reason,1 you something like httpdconf namevirtualhost virtualhost servername myservercom serveradmin myemailgmailcom documentroot pathtohtmlroot errorlog pathtoapacheerrorlog customlog pathtoapacheaccesslog common options execcgi followsymlinks multiviews addhandler wsgiscript wsgi wsgidaemonprocess djangoapp wsgiprocessgroup djangoapp wsgiscriptalias pathtodjangoappwsgi alias static pathtostaticfiles directoryindex indexhtml indexcgi addhandler cgiscript cgi pl virtualhost namevirtualhost virtualhost servername myservercom serveradmin myemailgmailcom documentroot pathtohtmlroot errorlog pathtoapacheerrorlog customlog pathtoapacheaccesslog common options execcgi followsymlinks multiviews addhandler wsgiscript wsgi wsgidaemonprocess djangoapp wsgiprocessgroup djangoapp wsgiscriptalias pathtodjangoappwsgi alias static pathtostaticfiles directoryindex indexhtml indexcgi addhandler cgiscript cgi pl virtualhost and djangoappwsgidjangoappwsgi script define different django versions applications usrbinpython import os import sys syspathappend syspathappend pathtopythonsitepackages syspathappend pathtopythondistpackagesdjangopyegg etc syspathappend pathtodjangoappsrc osenviron djangosettingsmodule djangoappsettings osenviron pythoneggcache tmp import djangocorehandlerswsgi application djangocorehandlerswsgiwsgihandler,i using windows xp want know i create multiple django versions single apache service virtual hostof course i trying one instance python should create instance python django version django needs eggs work i several eggs one python version,1 i problem the solution move calls adminsiteregister adminpy with debug set false models lazily loaded registration calls always get made apparently adminpy always loaded init time however,we using django admin maintain data exported sites sometimes clicking standard changelist view get model edit form instead routed correct page getting django pagetemplate it happening somewhat sporatically could reproduce reloading three times first f second f third f object change form loads correctly but lately returning often it seems reduce odds returning bounce apache gracefully gets worse seemingly requests running django fastcgimysql x fwiw i reproduce problem vm i running modwsgi debugtrue set settings otherwise code database identical,2 method put django source anywhere want manually specify path django source managepy wsgipy import os ospathinsert pathtodjangosource you also use virtualenv virtualenv fixes paths console apps automatically however wsgipy still write path manually method use zcbuildout djangorecipe stuff including donwloads django download modules creates wsgipy projectdirbinwsgi creates managepy projectdirbindjangoexe all done single config file buildoutcfg list modules settings run command buildout n however buildout might good solution tight deadlines things need learn planning python apps i definitely recommend trying here examples djangobuildout setup httpwwwgoogleltsearchqdjangobuildouttemplateorskeleton an update comment you cannot install two django versions system wide what though either do install django drop djangobasedjango folder project path you compile internationalization files manually use cd djangoconf python managepy compilemessages or install django python setuppy install use extra arguments change installation destination python documentation covers different methods,i using windows xp want know i create multiple django versions single apache service virtual hostof course i trying one instance python should create instance python django version django needs eggs work i several eggs one python version,1 scrapy makes webcrawling easy it also great documentation scrapy startproject command build skeleton project,i want make little program use every single somethingmeaning word website it meant python i heard beautifulsoup i quite know use purpose little tutorial p or easy regex like recompile everything brackets newlines stuff already done thanx advance guys sorry minor english,1 mechanize python library allows perform http requests even provides ability parse html extract data looking it major feature act like browser handle things like authentication cookies regex ideal working xmlhtmlyou see you use beautifulsoup combination mechanize prefer parsing library learning things like xpath make life simpler well both mechanize beautifulsoup tutorials start reading code,i want make little program use every single somethingmeaning word website it meant python i heard beautifulsoup i quite know use purpose little tutorial p or easy regex like recompile everything brackets newlines stuff already done thanx advance guys sorry minor english,1 in cases rebinding one names bound different objects rebind doesn change x world rebind doesn change x in cases mutating object then names see changes object bappend mutates list b bound h hhh mutates dictionary x bound,x x changes transferred x x x hello x world changes transferred x world x hello b bappend changes b transferred b x x h hhh changes transferred x h hhh x h hhh question in cases value assigned variables affect value original variables python version python,2 you changing values variable write x you binding object name in example b you one object list two names bound object naturally mutating changes object reflected object accessed different name in example x x you objects play integers values when write simply rebinding name object the name x still bound,x x changes transferred x x x hello x world changes transferred x world x hello b bappend changes b transferred b x x h hhh changes transferred x h hhh x h hhh question in cases value assigned variables affect value original variables python version python,1 given code seem syntax errors likely issue amppyxpcomguiapptitle entity reference note xml parser used firefox always points end tag regardless line finds unknown entity either forgot include dtd file defining entity address dtd file wrong define entity named pyxpcomguiapptitle,i tried creating xulrunner app given tutorial httppyxpcomextmozdevorgnowraptutorialspyxulrunnerpythonxulrunnerabouthtml but i tried running app gave following error xml parsing error location chromepyxpcomguiappcontentpyxpcomguiappxul line number column persistscreenx screeny width height i getting went wrong content pyxpcomguiappxul window idpyxpcomguiapp xmlnshttpwwwmozillaorgkeymastergatekeeperthereisonlyxul titleamppyxpcomguiapptitle stylewidth px height px scripttypeapplicationxpython persistscreenx screeny width height this line number i windows,1 rangelenmylist mylisti mylisti in python replace range xrange,i list looks like mylist what i want record index items list changes value so list would i know using groupby like lenlistgroup key group groupbymylist result i want index group startsends rather number items groups i know i could start summing sucessive group count get index thought may cleaner way thoughts appreciated,2 just use enumerate generate indexes along list operator import itemgetter itertools import groupby mylist nextgroup key group groupbyenumeratemylist keyitemgetter this gives pairs startindex value group if really want use tuplegroup key group groupbyenumeratemylist keyitemgetter indexes nextgroup key group groupbyenumeratemylist keyitemgetter nextindexes indexes listindexes,i list looks like mylist what i want record index items list changes value so list would i know using groupby like lenlistgroup key group groupbymylist result i want index group startsends rather number items groups i know i could start summing sucessive group count get index thought may cleaner way thoughts appreciated,2 you consider variables python indeed pointers objects case when write x variable x pointer number object value x variable pointer object currently pointed x variable instead pointing another number object value this clearly effect object x pointing case when write x x pointing array object contains two pointers number objects value x pointing array x yappend affect variable key point alter object pointing array adding another element because x also pointing object change visible x,x x changes transferred x x x hello x world changes transferred x world x hello b bappend changes b transferred b x x h hhh changes transferred x h hhh x h hhh question in cases value assigned variables affect value original variables python version python,1 if define getflow inside heatdata class self first parameter def getflowself pressuredrop coeff edit seeking definition curvefit found prototype curvefitf xdata ydata pnone sigmanone kw first arg must callable called first argument independent variable try closure def setflowarrayself sets experimental flow rate heat exchanger flow selfflowdataflow pressuredrop selfflowdatapressuredrop def getflowpressuredrop coeff sets flow based coefficient pressure drop use selfwhatyouneed even call selfgetflowpressuredrop coeff method flow coeff pressuredrop return flow popt pcov spoptcurvefitgetflow pressuredrop flow selfexhflowcoeff popt selfexhflowarray selfexhflowcoeff selfexhpressuredrop,i attempting curve fitting within class instance method curvefit function giving class instance method many arguments the code class heatdatahxhx class handling data heat exchanger experiments several lines methods work fine function def getflowpressuredrop coeff sets flow based coefficient pressure drop flow coeff pressuredrop return flow curvefit function call def setflowarrayself sets experimental flow rate heat exchanger flow selfflowdataflow pressuredrop selfflowdatapressuredrop popt pcov spoptcurvefitselfgetflow pressuredrop flow selfexhflowcoeff popt selfexhflowarray selfexhflowcoeff selfexhpressuredrop gives error getflow takes exactly arguments given i make work defining getflow outside class calling like spoptcurvefitgetflow pressuredrop flow good really needs method within class versatile i want how i get work class instance method i also like able pass self getflow give parameters fit parameters used curvefit is possible,1 x mylist x enumeratemylist x x print x x,i list looks like mylist what i want record index items list changes value so list would i know using groupby like lenlistgroup key group groupbymylist result i want index group startsends rather number items groups i know i could start summing sucessive group count get index thought may cleaner way thoughts appreciated,1 yes hit problem large set fixtures the constant deserializationloading add test suite grows i would suggest writing utility functions create data need rather relying fixtures for instance might function create new authuser like def createuserdatanone data data defaults username getrandomstring email getrandomemail password getrandomstring defaultsupdatedata return userobjectscreateuserdefaults writing function generate random stringemail left exercise reader,i currently use single fixtures file per application projects grow tests taking far long i believe large fixtures loaded test class fault i avoided lots smaller fixtures concerns duplication maintenance i know think unavoidable before i go path though i thought i would ask others fixtures testing applicationsprojects,1 well color embarrassed for anyone else problem check doctemplate allowsplitting the default i changed mine reason facepalm,i pdf i generating using reportlab i using standard tableofcontents flowable trying split two columns fit first page content ever one level i worried oddlooking indentations right i pagetemplate using frames create columns first page i get layouterror flowable tableofcontents x framerightcol x large page frame rightcol x any ideas,1 using newer version distribute fixed problem distribute,edit i narrowed problem presence distribute line requirementstxt file removing line fixes problem run errors line yet i following tutorial httpdevcenterherokucomarticlesdjango everything going well i got part titled running worker i following requirementstxt file django amqplib anyjson celery distribute djangocelery djangokombu djangopicklefield gunicorn kombu psycopg pyparsing pythondateutil wsgiref and i added appropriate celery config end procfile settingspy indicated instructions when i deploy app i get following error relaunching traceback recent call last file string line module nameerror name install defined complete output command tmpbuildowdweodbbinpython c import setuptoolsfile tmpbuildowdweodbbuilddistributesetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record tmppiplitikrecordinstallrecordtxt installheaders tmpbuildowdweodbincludesitepython the full deploy log found httppastieorg anybody seen know fix,2 from docs on unix return value exit status process encoded format specified wait note posix specify meaning return value c system function return value python function systemdependent oswait wait completion child process return tuple containing pid exit status indication bit number whose low byte signal number killed process whose high byte exit status signal number zero high bit low byte set core file produced in case return value binary the high byte,consider python script errorpy import sys sysexit invoking python errorpy echo yields expected however consider runnerpy import os result ossystempython errorpy print result yields it seems somehow result python code leftshifted two situations different clear what going this occurring python,3 docs ossystem on unix return value exit status process encoded format specified wait oswait bit number whose low byte signal number killed process whose high byte exit status signal number zero highlow byte status signal specific code it safe result get actual exit status result system portable across platforms however import os result ossystempython errorpy print result,consider python script errorpy import sys sysexit invoking python errorpy echo yields expected however consider runnerpy import os result ossystempython errorpy print result yields it seems somehow result python code leftshifted two situations different clear what going this occurring python,3 if limited scilib check httpforgescilaborgindexphppsciscipy let everything scilib within python also solve problem considering using subprocess instead ossystem httpdocspythonorglibrarysubprocesshtmlmodulesubprocess,is possible run system process remotely ie background using python for eg i ave scilab installed system i something like xx ossystem scilabadvcli python console but fires actual scilab command line interface though i need something like xxadd function predefined scilab module whic invoking return can done,1 here thing actually really modify variable python variables names values you modify certain types value assign variables actually causes refer ie name different value integer string values cannot modified lists dictionaries writing code like bappend b initially refer list value causes name b used look list value modified append method called causes change since b refer value change seen writing code like b creates new value concatenated list causes b refer new value instead old one the value referred unaffected way calculate still calculation,x x changes transferred x x x hello x world changes transferred x world x hello b bappend changes b transferred b x x h hhh changes transferred x h hhh x h hhh question in cases value assigned variables affect value original variables python version python,1 i tested windows works future import printfunction subprocess import pipe popen threading import thread import sys try queue import queue empty except importerror queue import queue empty python x onposix posix sysbuiltinmodulenames def enqueueoutputout queue line iteroutreadline b line linedecodesysstdoutencoding queueputline outclose def main p popen cmainexe stdoutpipe bufsize closefdsonposix q queue threadtargetenqueueoutput argspstdout q tdaemon true thread dies program tstart initially queue empty stdout open stdout closed enqueueoutput finishes continue printing queue empty pstdoutclosed qempty try line qgetnowait except empty continue else printline end return name main sysexitmain output outputting outputting outputting outputting outputting outputting edit readline block program stdout buffer flushes may take long time data stream intermittent if edit source one option manually call fflushstdout instead disable buffering using setvbuf start program for example include stdioh int main setvbufstdout null ionbf file fh fopenoutputtxt w int printfoutputting dn fprintffh outputting dn sleep fclosefh return also look using unbuffer stdbuf modify output stream existing program,i read many questions related learned lot i still able solve problem i building wxpython app runs c executable displays stdout executable real time i run several strange results trying make work here current setupproblem testcc compiled testout gcc include stdioh int main file fh fopenoutputtxt w int printfoutputting dn fprintffh outputting dn fclosefh return wxpythonscriptpy running interpreter def runself selfexternalbinary subprocesspopen testout shellfalse stdoutsubprocesspipe selfwantabort line selfexternalbinarystdoutreadline wxposteventselfnotifywindow resulteventline resulteventevtstdoutid print subprocess still running print subprocess aborted smoothly if i run code subprocess takes long time complete even though write data exit however i run following completes quickly wxpythonscriptpy running interpreter def runself outfile open outputtxt r selfexternalbinary subprocesspopen testout shellfalse stdoutoutfile selfwantabort line selfexternalbinarystdoutreadline wxposteventselfnotifywindow resulteventline resulteventevtstdoutid print subprocess still running print subprocess aborted smoothly so basically whenever i redirect stdout subprocess pipe slows downhangs i write file redirect fine why,3 perhaps clear example unusual behaviour following print word word true print word word true false your example equivalent print word false this two boolean expressions combined intention allowing abbreviation x b longer equivalent expression x x b,going bit mental trying work python print word false why print false,3 just like chain operators x word false false evaluates false therefore whole result word false word false false false false,going bit mental trying work python print word false why print false,2 first paths wrong pythonpath tells python folders look python modules normally put python installation folder for keeping installation folder python different environment variable called pythonhome so instead pythonpathcpython pythonhomecpython you change path variable use pythonhome accordingly as set environment variables working virtualenv need anything virtualenv stores original values activated modifies environment variables needs modify restores original values deactivated you take look using python windows,i new virtualenv sure set paths my paths set something like pythonpathcpython pythonstartupcpythonscriptsstartuppy pathpythonpathpythonpathscripts should i remove paths virtualenv activate script work correctly if i keep paths i call scripts env activated do i call scripts explicitly running pythonexe instead simply typing script name alone python myscriptpy not sure handle paths i would appreciate little guidance,2 note iter available python even otherwise notice docs really need replacement you however use findall def iterpythonnode return node nodefindall,i code elementtree works well python i needed get nodes name a xy node xmletreeelementtree import elementtree verbosenode topnodefindxy nodes listverbosenodeitera however i tried run python i got error ioncalculateskewconstraintpy line getnodeswithattribute nodes liststartnodeiternodename attributeerror elementinterface instance attribute iter it looks like python elementtree node iter how i implement iter python,3 not sure looking iter appears around getiterator httpdocspythonorglibraryxmletreeelementtreehtmlxmletreeelementtreeelementgetiterator,i code elementtree works well python i needed get nodes name a xy node xmletreeelementtree import elementtree verbosenode topnodefindxy nodes listverbosenodeitera however i tried run python i got error ioncalculateskewconstraintpy line getnodeswithattribute nodes liststartnodeiternodename attributeerror elementinterface instance attribute iter it looks like python elementtree node iter how i implement iter python,3 just add mark byers great answer import dis disdislambda word false loadconst word buildlist duptop rotthree compareop jumpiffalseorpop loadglobal false compareop returnvalue rottwo poptop returnvalue disdislambda word false loadconst word loadconst compareop loadglobal false compareop returnvalue,going bit mental trying work python print word false why print false,1 i figured answer question i brought page since one actually suggested answer question i thought i post class k pass k k aclass k at point instances class class k,i need dynamically create instance class python basically i using loadmodule inspect module import load class class object i figure create instance class object please help,3 based docs current source answer also avscale also mentioned nipydevel mailing list since least last february it possible nipype already wraps something else perhaps matlab wrapper you could try opening issue asking mailing list as long trying use python nipype maybe philosophy nipype project use numpyscipy just guess i know functions replicate output tools it also possible one gotten around adding yet for uninitiated avscale takes affine matrix e yields similar output rotation amp translation matrix scales xyz skews xyxzyz average scaling determinant leftright orientation preserved forward half transform backward half transform,i trying use nipype analyze transformation matrixes created fsl fsl script called avscale analyzes transformation matrixes mat files i wondering whether nipype interface wrap script enable work output thanks,1 rematch implicitly adds start regex in words matches start string research retry positions generally speaking i recommend using research adding explicitly want httpdocspythonorglibraryrehtml,i hell time trying transfer experience javascript regex python i trying get work printrematch e test prints none if i printrematch e est it matches default match beginning string when match i use result how i make first one match is better documentation python site offers,3 docs clear think rematchpattern string flagsâ¶ if zero characters beginning string match regular expression pattern return corresponding matchobject instance return none string match pattern note different zerolength match,i hell time trying transfer experience javascript regex python i trying get work printrematch e test prints none if i printrematch e est it matches default match beginning string when match i use result how i make first one match is better documentation python site offers,3 you make ndarray nonhomogeneous array types stacking strarr fltarr work you could start converting fltarr array str something like npcharmodf fltarr array dtype s,one array strings array numbers like strarr nparray objectshort objectintermidiate objectlong fltarr nparray how i specified fmt npsavetxt text file object object object ie two arrays f respectively i really want use numpysavetxt directly specifying npsavetxtoutputtxt npvstackstrarr fltarrt fmt f seems doesnot work is doable savetxt i really prefer numpyarray based solution rather going spliting reformating using list comprehensions recarrays thanks,1 you put dollar sign instead percent sign ossystemsay v sangeeta speak this ossystemsay v sangeeta speak,first program basically says stuff loud different voices import os print hello welcome speaking program print copyright shameer shahab speak rawinputwhat would like sayn type rawinputwould liken normal voicen high pitchedn low pitchedn whispern indian voicen please choose n type ossystemsay speak type ossystemsay v good speak type ossystemsay v bad speak type ossystemsay v whisper speak type ossystemsay v sangeeta speak type ossystemecho option finish rawinputi done job pick optionn quitn new wordn change pitchn finish quit finish ossystemclear ossystempython speakpy finish type rawinputwould liken normal voicen high pitchedn low pitchednorn whisper voicenindian voicen type ossystemsay speak type ossystemsay v good speak type ossystemsay v bad speak type ossystemsay v whisper speak type ossystemsay v sangeeta speak else print that option ossystemclear ossystempython speakpy else print that option ossystemclear ossystempython speakpy finish rawinputi done job pick optionn quitn new wordn change pitchn finish ossystemlogout ossystemkillall terminal finish ossystemclear ossystempython speakpy finish type rawinputwould like n normal voicen high pitchedn low pitchedn whisper voicenindian voicen type ossystemsay speak type ossystemsay v good speak type ossystemsay v bad speak type ossystemsay v whisper speak type ossystemsay v sangeeta speak else print that option ossystemclear ossystempython speakpy error shameersmacbookprotest programs shameer python speakpy hello welcome speaking program copyright shameer shahab what would like say hello would like normal voice high pitched low pitched whisper indian voice please choose traceback recent call last file speakpy line module ossystemsay v sangeeta speak typeerror arguments converted string formatting please help i young need help will vote trying answer,3 you see browser dom inspector event listeners it anonymous function looks like function return typeof dundefinedampampdeventtriggereddeventhandleapplylelemargumentsb this looks like difficult website scrape might consider using selenium,to determine list topics quora i decided start scraping profile page many topics followed eg httpwwwquoracomcharliecheevertopics i scraped topics page i need scrape topics ajax page loaded click more button bottom page i trying find javascript function executed upon clicking more button luck yet here three snippets html page may relevant div classpagernext actionbutton idwmeaykrzmoremorediv morebutton meaykrz dpszd morebutton morebutton newpagedlistmorebuttonmeaykrzmorebuttonliveldcomjeclsaviewpagedlistpagedlistmorebuttontwwzfznftw does anyone guys know name javascript function executed clicking more button any help would appreciated the python script followed tutorial point looks like prints topics followed charlie cheevers st page usrbinpython import httplibtimere beautifulsoup import beautifulsoup scrapingconn httplibhttpcache def fetchurlmethodget return scrapingconnrequesturlmethod def extracttopics url httpwwwquoracom href topicname sfindchildrenstring return def fetchstories page fetchuhttpwwwquoracomcharliecheevertopics soup beautifulsouppage stories soupfindall topicname topics extracttopics stories topics print us sn topicname url stories fetchstories,1 why read wav it tells file wrong sampling rate instead requested sampling rate important speech recognition software why read devdsp in recent versions ubuntu pulseaudio framework used instead oss the version trying using oss need install osscompatibility package distribution bring oss support back you try newer julius pulseaudio support why appear able read devdsp react way audio input work properly has anyone else success open source speech recognizers especially linux sure check video example people cmusphinx httpwwwyoutubecomwatchvvfanliowsyk i suggest revisit cmusphinx package leading open source speech recognition engine there loads documents website need read remember speech recognition complex area get great results also need invest time understanding technology just like domain in short transcribe file cmusphinx need following simple steps take wav file resample khz bit mono file sox sox inputwav r c resampledwav install pocketsphinx aptget install pocketsphinx decode file pocketsphinxcontinuous samprate infile resampledwav the result printed standard output to supress logger add stderr redirection devnull pocketsphinxcontinuous infile resampledwav devnull,can anyone recommend reliable open source software transcribing english speech wav files the two main programs i researched sphinx julius i never able get either work documentation transcribing files sketchy best i developing bit ubuntu whose repos include sphinx julius well voxforge julius acoustic modal english i focussing transcribing files instead directly processing sound mic i given expecting projects like work ubuntu sound system this knock ubuntu i record sound mic perfectly using audacity neither system seems able access mic i hoping i simply configuration reading file i first tried sphinx ubuntu package sphinxbin even though sample sphinxdemo seemed work transcribing file virtually documentation configuration i sure i customize read arbitrary wav the audio file used demo undocumented k format indirectly referenced configuration files there brief blurb describing sphinxdemo running sphinxbatch inspecting script shows actually calling sphinxcontinuous even worse help docs script list dozen options mention required optional overall lack sphinx documentation poor quality existing documentation driving nuts i next tried julius ubuntu package surprisingly recent considering version used voxforge quickstart the package seems include slightly better documentation even example written python usrsharedocjuliusvoxforgeexamplescontrolapp after reading example docs i tried adapting read file creating file filelisttxt containing text hellowav referring file name containing recording someone saying hello placing directory i ran julius input file filelist filelisttxt c julianjconf getting response read waveform input error adinfile sampling rate error adinfile error parsing wav header hellowav error adinfile failed read speech data hellowav files processed retrying specifying absolute filenames filelisttxt hellowav produce error i also tried julius call used example record directly mic julius input mic c julianjconf i called several times response varied error cannot read devdsp stat adin thread created please speak in later case matter i say mic nothing happens i tell still unable read mic reading something simply unable transcribe audio i sure make the errors i getting leave much go why read wav why read devdsp why appear able read devdsp react way has anyone else success open source speech recognizers especially linux,3 if want write raw bytes use pack method struct type you could write md long long ints write byte sections httpdocspythonorglibrarystructhtml edit an example import struct bytes f byteasint intbytes packedstring structpack b byteasint if i got right trying pull text hex strings written convert binary format output if case code want it basically converts raw hex string int packs binary form byte string you could loop something like byte input string,trying md collision homework problem i sure write raw bytes python i gave shot ended bin file ascii here code filewriteobject openmdonebin wb filewriteobject openmdtwobin wb filereadobject open bytestxt r filereadobject open bytestxt r bytescontents filereadobjectreadlines bytescontents filereadobjectreadlines filereadobjectclose filereadobjectclose bytes bytescontents towrite rx bytes filewriteobjectwritetowritestrip bytes bytescontents towrite rx bytes filewriteobjectwritetowritestrip filewriteobjectclose filewriteobjectclose sample input dd c e ee c af f c f ca b i link input file seems mod removed it file hex byte written ascii line edit solved thanks circumflex i two different text files bytes ascii i converted binary wrote using struckpack got md collision,2 the problem extending timeout matter much longer set run limitations somewhere along line either web server browser geocode calls if something routinely fails n times request really make guarantees so rather client request hanging long running process extension risking server timeout use something like celery run geocode tasks clientside submit clientside request via javascript poll server answer via ajax get response,i running script python takes long time process the thing function takes long run guess nginx timeout configuration prevents somekind errors prevents function run completely i want know increse value timeout because tried commands file conf nginx uwsgiconnecttimeout uwsgisendtimeout uwsgireadtimeout keepalivetimeout none worked thks advance,1 the answer reinstall pil sagemiscpackageinstallpackagepil forcetrue it simple amp took minute reinstalling machine probably allowed find location libraries machine,i installed sage mac os x it looks like pil the following code gives ioerror import image imageopenpicjpg athumbnailint int this error i get ioerror traceback recent call last ipython console module sagelocallibpythonsitepackagespilimagepyc thumbnailself size resample selfdraftnone size selfload try sagelocallibpythonsitepackagespilimagefilepyc loadself e selftile imagegetdecoderselfmode selfdecoderconfig seeko try sagelocallibpythonsitepackagespilimagepyc getdecodermode decodername args extra return applydecoder mode args extra except attributeerror raise ioerrordecoder available decodername def getencodermode encodername args extra ioerror decoder jpeg available it seems find libjpeg i checked macports machine amp looks like jpeg package installed i also found libjpeg optlocallib i tried manipulating ldlibrarypath sage script amp sage using os library able get rid error i searched internet get pil find libjpeg i found involves modifying setuppy rebuilding pil sage seem include pil setuppy has anyone else encountered problem amp solved perhaps someone familiar w pil,1 rule rest objects not methods the rest resources become fragmented false always false rest resources independent they fragmented instead device resource i resources device devicestatus driver driverstatus while make sense restful point view normal lot sub resources map separate python class actually make sense hence question device thing restenvironmentsiddevicesdeviceid it status you consider providing status device information together single composite document describes device just relational database normalized mean restful objects need precisely normalized database while simpler many frameworks make simple may meaningful consider connection always existing hence use put would bad thing considering put idempotent connections always exist they may come go while relational database may manytomany association table update peculiar special case really make much sense outside world dba the connection two restful things rarely separate thing it attribute restful things it perfectly unclear connection thing you talk vaguely provide details lacking usable facts i guess connecting devices drivers kind devicedriver statusdriver relationship the connection device driver separate restful resource it easily attribute device driver actually separate visible restful resource again some frameworks like djangopiston make trivial simple expose underlying classes this may always appropriate however good rules tips inteligently define set resources set methods yes don resources methods pretty much if lot methods outside crud may data model issue you may classes things expressed relational model many stateful updates things stateful objects inherently evil need examined critically in cases put change status object perhaps post add history object the current state last thing posted also you trivialize resource class things you resources collections you post fairly complex document composite properly facade resource that complex document imply several crud operations database you wandering away simple restful your question remains intentionally murky method rich application core mean much without concrete examples impossible imagine api logic influencing application structure if somehow different probably creating needless novalue complexity good practice apply separation concerns always why ask lot seems come confusion map rather method rich api restfull one resources nouns verbs wise consider element rest resource a resource defined problem domain it usually something tangible the methods methodrich api usually irrelevant they crud create retrieve update delete operations if something essentially crud stop coding stop writing code rethink api make crudlike crud createretrieveupdatedelete maps rest postgetputdelete if recast problem domain terms stop coding stop coding get crud rules need able display list available driver types ie class names driver instance client would mean creating yet another resource like drivertypes correct they already part problem domain you already class defined you making available rest here point the problem domain realworld objects you class definitions they tangible things rest transfers state tangible things your software may intangible things like associations links connections junk part software solution this junk matter much it implementation detail not realworld things an association always visible two realworld restful resources one resource may foreignkey like reference allows client restful fetch another related object or resource may collection related objects single get retrieves object collection related objects either way realworld restful resources available the relationship merely implied even physical manytomany database table mean must exposed again some frameworks make trivially easy expose everything this always good,i currently running architectural problem python app using twisted uses rest api i looking feedback warning long post ahead lets assume following object hiearchy class deviceobject def init selfdriverdriver selfstatusstatus selftaskstaskmanager def getattrself attrname hasattrselftasks attrname return getattrselftasks attrname else raise attributeerrorattrname class driverobject def initself selfstatusdriverstatus def connectself code def disconnectself code class driverstatusobject def initself selfisconnectedfalse selfispluggedinfalse i also rather deep object hiearchy elements sub part so right gives following resources rest api know rest url hierarchy media types simplicity sake restenvironments restenvironmentsid restenvironmentsiddevices restenvironmentsiddevicesdeviceid restenvironmentsiddevicesdeviceiddriver restenvironmentsiddevicesdeviceiddriverdriverstatus i switched months back dirty soap type api rest i becoming unsure handle seems like added complexity proliferation rest resourcesmedia types example instead device resource i resources device devicestatus driver driverstatus while make sense resfull point view normal lot sub resources map separate python class mapping method rich application core restfull api rest resources nouns verbs good rules tips inteligently define set resources set methods the comprehensive example i found far seems article api logic influencing application structure application api logic least partially guide internal logic good practice apply separation concerns ie i intermediate layer resource objects job communicating application core map one one core classes how would one correctly handle following restfull way i need able display list available driver types ie class names driver instance client would mean creating yet another resource like drivertypes these rather long winded questions thanks patience pointers feedback criticism welcome to slott by fragmented resources meant lots different sub resources basically still apply server side entity for the connection so would modified version driverstatus resource i consider connection always existing hence use put would bad thing considering put idempotent you right stopping coding rethinking reason i asked questions putting things paper get better overview the thing right basic real world objects put make sense rest resources collections resources correctly manipulated via post get update delete i hard time getting head around rest approach things i instinctively view resources,2 i usually prefer settrace source way dev server reload addedremoved i need stop start for example def getitemrequest import pdb pdbsettrace when view accessed pdb kick,i quite new debugging directly pdb i issues debugging django application here i python pdb managepy runserver pdb b coreviewspy breakpoint usersraphaelcruzeirodocumentsprojectspdbtestcoreviewspy pdb c however execution passes directly breakpoint am i missing command the manual elaborate setting breakpoint anymore,2 i similar issues urllib working zimbra rest api end switched pycurl success ps operations loginnavigatepost i usually find mechanize useful easier use maybe give show,i test code part webapp uses urllib perform operation i would usually perform via browser log remote website move another page perform post filling form i created separate clean virtualenvs nositepackages different machines different versions python exact packages via pip requirements file code works two virtualenvs local development machine work either production vpss in failing cases i log successfully move correct page i submit form remote server replies telling error application server error page complete request webserver error i successfully log maneuver second page seem session cookie problem particular final post i perform operation particular machine exact headers data seem problem i requestingposting i trying code two separate vps rented different companies seem problem vps physical environment code works different python versions i imagine incompabilty problem i completely lost stage work i even turneditoffandturnitonagain i see problem could i think something final post coming vps remote server like i figure could i feel like something going hood urllib causing remote server dislike reply edit i installed exact python version vps working local copy work remotely must something originating vps how could effect http request is something lower level,1 i doubt much i also django eclipse pydev smart enough understand weird metaclass django uses transform father modelsforeignkey father relationtree whatever python really hard autocompleters parse pydev pylint seem completely give comes metaclasses pylint always complains model classes objects member,code completion eclipsepydev works decent however one thing work like i want consider following django model class reletiontreemodelsmodel mother modelsforeignkey relationtree blanktrue nulltrue father modelsforeignkey relationtree blanktrue nulltrue name modelscharfield rt relationtreeobjectsgetname mary assume unique mary now problem rt code complete give options motherfathername rtmother code complete motherfathername code complete isinstancertmother modelsforeignkey i think is way make pydev understand i want code complete foreign keys type points case relationtree modelsforeignkey thanks david,1 take look basic pattern recognition machine vision literature in order address question considerably detail needed is pattern binary image grayscale image color image how often need have looked python imaging library pil how big image want search a good course action look pil look convolution fourier space localize target regions relatively quickly finally good google search friend,i trying write python program take screen shot scan image specific combination pixels pattern for example takes screen shot web page scans whole image x pixel pattern it would also nice could record xy position image screen i searched internet hours solution found nothing i know basics python know begin program,1 using urllibrequestopen recommended dive python python default jul gcc based apple inc build llvm build darwin type help copyright credits license information import urllibrequest urlstr httpwwwpythonorg filehandle urllibrequesturlopenurlstr printfilehandleread b doctype html public wcdtd xhtml transitionalen httpwwwworgtrxhtmldtdxhtm,i quite bit trouble python documentation is anything like mozilla developer network i python puzzle website i need able read content page i saw following posted site import urllib urlstr httpwwwpythonorg try filehandle urlliburlopenurlstr str filehandleread filehandleclose print print html code url urlstr print except ioerror print cannot open url reading urlstr str error print str it keeps saying urllib module the python documentation says the urllib module split parts renamed python urllibrequest urllibparse urlliberror the tool automatically adapt imports converting sources also note urlliburlopen function removed python favor urlliburlopen i tried importing urllibrequest ssays urllib defined wtf going version,2 the documentation probably referencing python documentation urllib the documentation probably using python documentation urllibrequest,i quite bit trouble python documentation is anything like mozilla developer network i python puzzle website i need able read content page i saw following posted site import urllib urlstr httpwwwpythonorg try filehandle urlliburlopenurlstr str filehandleread filehandleclose print print html code url urlstr print except ioerror print cannot open url reading urlstr str error print str it keeps saying urllib module the python documentation says the urllib module split parts renamed python urllibrequest urllibparse urlliberror the tool automatically adapt imports converting sources also note urlliburlopen function removed python favor urlliburlopen i tried importing urllibrequest ssays urllib defined wtf going version,2 the documentation linked pil using google app engine images api documentation httpcodegooglecomappenginedocspythonimagesfunctionshtml,i using script resize images but i noticed resized image looses sharpness according page imageantialias best downsizing filter but i add filter code imagesresizehomepageoriginalimage imageantialias i get attributeerror type object image attribute antialias is way around thanks class imageresizewebapprequesthandler def getself q homepageall result qfetch item result firm itemfirmname id itemkeyid id homepage homepagegetbyidid homepage thumbnail imagesresizehomepageoriginalimage homepagethumbnail dbblobthumbnail homepageput,1 think effective way generate string using join method one write operation file,i want create text file contains table created lists but i want something like import string print textfile stringrjustlistname stringrjustlistname the following code demonstrates idea i would like work import string listname test test test range print textfile stringrjustlistnamei i would like output look exactly like test test test that i trying makes sense head obviously working i used join function print lists nicely i get spacing right table any ideas,1 open pickle file binary mode favoritecolor pickleloadopensavep rb,i currently online python puzzle series i gotten problem need unload pickled file i read documentation i kept getting typeerror str support buffer interface i search google arrive question so similar problem the answer points httpwikipythonorgmoinusingpickle i tried code example i getting problem i using python wtf complete traceback traceback recent call last file cfoopy line module test file cfoopy line test favoritecolor pickleload open savep typeerror str support buffer interface from example httpwikipythonorgmoinusingpickle i already successfully created savep file first code example tutorial,3 if i understanding problem correctly could def printtable headers one two three table test test test print joincolumnrjust column headers row table print joinstrcolumnrjust column row printtable one two three test test test no need string module integers index table i printed standard clarity write file easily,i want create text file contains table created lists but i want something like import string print textfile stringrjustlistname stringrjustlistname the following code demonstrates idea i would like work import string listname test test test range print textfile stringrjustlistnamei i would like output look exactly like test test test that i trying makes sense head obviously working i used join function print lists nicely i get spacing right table any ideas,1 what mean working first rjust going include characters string it looks like want rjust around get spacing looking strings like test second print comma end print one new line you probably want something like print textfile stringrjustlistnamei then loop need print newline print textfile now whitespace beginning line rjust first item list you actually probably want behavior columns line option use ljust some minor style suggestions nothing get overwritten item listname likely better range thing instead stringrjust call rjust string like listnameirjust if want slick join list comprehension could print textfile joinitemrjust item listname this rjust items joins together space could use empty string well,i want create text file contains table created lists but i want something like import string print textfile stringrjustlistname stringrjustlistname the following code demonstrates idea i would like work import string listname test test test range print textfile stringrjustlistnamei i would like output look exactly like test test test that i trying makes sense head obviously working i used join function print lists nicely i get spacing right table any ideas,1 are specifying username domainuserid indicated examples pythonntlm library also see answer,i using python suds lib access sharepoint web services i followed standard doc suds website for past days matter service i access remote service always returns forbidden i using suds builtin support accessing python ntlm let know anyone clue suds import transport suds import client sudstransporthttps import windowshttpauthenticated import logging loggingbasicconfiglevellogginginfo logginggetlogger sudsclient setlevelloggingdebug ntlm windowshttpauthenticatedusername userid password pass clists clientclienturl httpssharepointurlvtibinlistsasmxwsdl transportntlm clists clientclienturl httpssharepointurlvtibinspsearchasmxwsdl print clists listscollection clistsservicegetlistcollection,1 install postgresql mac httpwwwpostgresqlorgdownloadmacosx set path new postgresql location psycopg install pathpathlibrarypostgresqlbin sudo easyinstall psycopg,original message outdated after running python setuppy install i get following warning unable find pgconfig filebuilding psycopgpsycopg extension gcc arch ppc arch fnostrictaliasing fnocommon dynamic dndebug g o dpsycopgdefaultpydatetime dpsycopgversion dt dec ext pq dpsycopgextensions dpsycopgnewboolean dhavepqfreemem dhavepqprotocol ilibraryframeworkspythonframeworkversionsincludepython i c psycopgpsycopgmodulec buildtempmacosxfatpsycopgpsycopgmoduleo unable execute gcc no file directory error command gcc failed exit status there probably something screamingly obvious anyone knows first thing backend web programming unfortunately gobbledegook the psycopg documentation helpful update early june after updating software error message changed now i run python setuppy install i get following warning unable find pgconfig filebuilding psycopgpsycopg extension gcc arch ppc arch isysroot developersdksmacosxusdk fnostrictaliasing fnocommon dynamic dndebug g o dpsycopgdefaultpydatetime dpsycopgversion dt dec ext pq dpsycopgextensions dpsycopgnewboolean dhavepqfreemem dhavepqprotocol ilibraryframeworkspythonframeworkversionsincludepython i c psycopgpsycopgmodulec buildtempmacosxfatpsycopgpsycopgmoduleo followed long list error messages it may may relevant i put gcc terminal comes back iappledarwingcc input files update gmt june i thought macports installation worked i tried running site ended following error raise improperlyconfigurederror loading psycopg module e djangocoreexceptionsimproperlyconfigured error loading psycopg module no module named psycopg so i guess means psycopg installed properly so i back square one,1 try build maintained christoph gohlke to build pil need several libraries mentioned readme libjpeg zlib freetype littlecms read usagetxt zlibdllzip instructions linking zlib visual c mingw,i trying port python program os x windows this program processes png tkinter eg selflogoimg imagetkphotoimageimageopen growthpathlogopng the code failing ioerror decoder zip available i tried installing pip pypm then i try building pip at end build process reports support pngzlib i get errors pythonorg installation windows i stuck i skilled building c libraries neither i know pip works i gnu zlib library installed helping i visual c express installed least working pip compile things successfully,3 winfilegetosfhandle pywin library return want winfilegetosfhandleafileno returns thing msvcrtgetosfhandleafileno testing,i sure documented somewhere find my code getting python object another library modify need call win api functions python returns something oslevel handle filefileno guess gives msvcrt fileno ctypeswindllkernelcreatefilea test xlnone handle file test r fileno handle how convert real win handle,1 not sure help net sdk syntax used follows element overrides requestoverrides element override overridesappendelement overridesetelementfieldid best fperiod override overridesetelementvalue bf,in excel api bloomberg allows overrides allows specific periodicity bdhibm equitybest salesbest fperiod overridebf dayswfillcsortd in python import wincomclient datetime import datetime blp wincomclientdispatch bloombergdata ibmsalesblpblpgethistoricaldata ibm equity best sales datetime datetime how add overrides best fperiod overridebf,2 there concepts clarified qt signal amp slot vs python signal amp slot all predefined signals amp slots provided pyqt implemented qt c code whenever want customized signal amp slot python python signal amp slot hence four cases emits signal slot qt signal qt slot qt signal python slot python signal qt slot python signal python slot the code shows connect four different scnarios import sys pyqtqtcore import pyqtqtgui import class fooqtcoreqobject def initself parentnone superfoo selfinitparent dial qdial selfspinbox qspinbox qt signal amp qt slot option efficient selfconnectselfspinbox signalvaluechangedint dial slotsetvalueint option selfconnectselfspinbox signalvaluechangedint dialsetvalue qt signal amp python slot selfconnectselfspinbox signalvaluechangedint selfmyvalchanged python signal amp qt slot connect option efficient selfconnectself signalmysignal dial slotsetvalueint connect option selfconnectself signalmysignal dialsetvalue emit param selfemitsignalmysignal param python signal amp python slot connect selfconnectself signalmysignal selfmyvalchanged emit param selfemitsignalmysignal param def myvalchangedself print new spin val entered formatselfspinboxvalue conclusion signal signature python signal differentiate qt signal parenthesis passed python data types emit the python signal created emit for slot three forms signatures sconnectw signalsignalsignature functionname sconnectwsignalsignalsignature instancemethodname sconnectwsignalsignalsignature instance slotslotsignature number amp available python slot number amp available qt slot it clear besides qt predefined slot python callable functionmethods qulified python slot these points made summerfield article signals slots old style qt signal amp slot vs new style qt singal amp slot well description based old style pyqt signal amp slot as idan k suggested alternative newstyle things especially python signal refer,i writing first python app pyqt i mainwindow dialog class part mainwindow class selflogindialog logindialog i use slots signals here connection made mainwindow qtcoreqobjectconnectselflogindialog qtcoresignalaastr selflogin and i try emit signal inside dialog class i sure emitted selfemitqtcoresignalaa jacek unfortunately slot invoked i tried arguments well different styles emitting signal no errors warnings code what might problem,3 i wrote extension simplejson encoder instead serializing image base returns path image here snippet def encodedatetimeobj extended encoder function helps serialize dates images isinstanceobj datetimedate try return objstrftime ymd except valueerror e return isinstanceobj imagefieldfile try return objpath except valueerror e return raise typeerrorreprobj json serializable,i trying serialize one models imagefield the inbuilt serializer seem serialize therefore i thought writing custom serializer could tell i could serialize image use default json serializer django thanks,2 consider partial solution node simply add whatever use nodes whichever node becomes answer end contain set items used so time find new solution set list items list items new optimal solution repeat,i teaching basic programming principles i stuck dynamic programming problem let take infamous knapsack problem given set items weight value determine count item include collection total weight less equal given limit total value large possible let set weight limit let give two lists weights values i made i write code give maximum value given constraintthat problem but i want know values i actually ended using not total valuethe individual values so example maximum would objects weights total value i want answer read thoughi want output list like it might easy problem problem i working uses lists much bigger repeat numbers example multiple objects value let know anyone think anything as always much love appreciation community,1 you need use â¨â¨ â´â´ fancy characters,newbie disclaimer i new python started using idle play around python my problem interpreter recognize strings whether enclosed â¨â¨ â´â´ i configured idle use utf seem idle issue what i tried test string interpreter directly it work print â¨money⨠interpereter returns file stdin line print â¨money⨠syntaxerror invalid syntax can someone help i using new laptop running fedora international keyboard layout python version,3 you could format instead using strftime formatdmonth dday dyear python ddd dmonth dday dyear,if i datetime object would i get date string following format cannot leading the current way i replace digits etc seems inefficient cumbersome what would better way accomplish thank,2 consider f open inputtxt r l mapintlinesplit line f print l produces note split commas if blank lines change l mapintlinesplit line f l mapintlinesplit line f linestrip,text file contains matrix n m dimensions example inputtxt file contains following i need write python script import matrix my current python script f open inputtxt r l l linesplit line f print l output list comes like need fetch values int form if try type cast throws errors,3 you could try calling processstdinwriteexpression expression newline end call processstdinclose done espeak if work add processstdinflush call write,i wondering way access espeak might command line laptopespeak say line first say line second right ways i python process subprocesspopen espeak stdinsubprocesspipe followed either processcommunicateexpression processstdinwriteexpression processstdinclose the former blocks rest program espeak finished desirable behavior latter block allows possibility overlap say program calls espeak twice quickly i wondering way call espeak like command line i could quickly input multiple things speak would say second thing first completed example in particular examples shut espeak single expression is way avoid edit the answer given ed write newlines end flush process subprocesspopen espeak stdinsubprocesspipe processstdinwritesay line firstn processstdinflush processstdinwritesay line secondn processstdinflush processstdinclose,2 the following want l open inputtxt r f line f line linestrip lenline lappendmapint linesplit print l,text file contains matrix n m dimensions example inputtxt file contains following i need write python script import matrix my current python script f open inputtxt r l l linesplit line f print l output list comes like need fetch values int form if try type cast throws errors,1 this work n chunked isinstancen nltktreetree nnode np dosomethingwithsubtreen else dosomethingwithleafn,i using nltk regexpparser extract noungroups verbgroups tagged tokens how i walk resulting tree find chunks np v groups nltkchunk import regexpparser grammar np dtjjnn v v chunker regexpparsergrammar token some tokens pos tagger chunked chunkerparsetokens print chunked how i walk tree chunk chunked chunk np print chunk s np carriernn forin tissuejj andcc cellculturejj forin np thedt preparationnn ofin np implantsnns andcc np implantnn v containingvbg np thedt carriernn,3 the datetime object method strftime this would give flexibility use inbuilt format strings httpdocspythonorglibrarydatetimehtmlstrftimeandstrptimebehavior i used lstrip remove leading zero datetimedatetime dstrftimemdy dstrftimemdy dstrftimemdylstrip,if i datetime object would i get date string following format cannot leading the current way i replace digits etc seems inefficient cumbersome what would better way accomplish thank,1 it looks like search grammar inference grammar induction library,i seeking direction attempting label problem i attempting build simple inference engine better name python take string create list tokens simply creating list white space separated values categorise tokens using regular expressions use higher level set rules make decisions based categorisations example one token matches zipcode regex rule exists string containing zipcode causes certain behaviour occur three tokens regexs numerical value mathematical operators match rule exists numerical value followed mathematical operator followed another numerical value causes certain behaviour occur i struggling best step higher level set rules i sure framework must exist any ideas also would characterise problem rule based system expert system inference engine something else thanks,1 i actually think best kryo i aware alternatives offer less schema defining nonbinary protocols you mention pickle susceptible slowdowns bloat kryo gets without registering classes kryo still faster less bloated pickle even without registering classes see following microbenchmark obviously take grain salt i could easily python pickle import pickle import time class person def initself name age selfname name selfage age people personalex personbarbara personcharles persondavid personemily xrange output pickledumpspeople print lenoutput starttime timetime xrange output pickledumpspeople print timetime starttime outputs bytes seconds python bit linux scala kryo import comesotericsoftwarekryo import javaio class personval name string val age int object myapp extends app val people arraynew personalex new personbarbara new personcharles new persondavid new personemily val kryo new kryo kryosetregistrationoptionaltrue val buffer new objectbufferkryo val output new bytearrayoutputstream bufferwriteobjectoutput people printlnoutputsize val starttime systemnanotime val output new bytearrayoutputstream bufferwriteobjectoutput people printlnsystemnanotime starttime e outputs bytes ms kryo scala java hotspot jvm bit linux for comparison outputs bytes ms i register classes comparison kryo uses space time python pickle registering classes space time registering classes and always write custom serializer want control,is simple hasslefree approach serialization scalajava similar python pickle pickle deadsimple solution reasonably efficient space time ie abysmal care crosslanguage accessibility versioning etc allows optional customization what i aware java builtin serialization infamously slow bloated fragile also mark classes serializableannoying things clearly serializable annotation eg many pointd authors mark serializable scala bytepickle requires bunch boilerplate every type want pickle even work cyclic object graphs jserial unmaintained seem much fastersmaller default java serialization kryo cannot deserialize objects arg ctors severe limitation also register every class plan serialize else get significant slowdownsbloat even still faster pickle protostuff afaict register every class intend serialize advance schema kryo protostuff closest solutions i found i wondering anything else way use i aware please include usage examples ideally also include benchmarks,3 at end i could resolve problem i want create reproducible python environment requirements inside using buildout andor virtualenv i could work linux system virtualenv python c compiler installed it seems way use buildout cmmi recipes download build wxpython all dependencies this really painful way i time i decided use workaround i going work ubuntu laptop time i installed wxpython repositories use wxpth file make available virtual environment this good solution seems best till someone knows better solution please let know when python project mature i turn problem i probably try hard way thanks answers comments,i trying begin new python gui application i decided use wxpython gui i want multiplatform one the problem i want use virtualenv virtualenvwrapper isolate environment able reproduce machines i work cannot install wxpython i installed ubuntu machine via aptget enough i searched web solution found this page httpbatokgithubcomvirtualenvwxp explained way hack virtualenv environment use local installation wxpython not best solution would good workaround the problem explained mac i couldnt make work ubuntu also found page installing wxpython virtualenv linux someone ask something similar i tried build wxpython way success any help would appreciated in end i choose wxpython beacuse multiplatform use without license problems started yet change mind another easier install framework thanks in advance sorry delay thanks answers i tried install wxpython using buildout links given still problem it seems i need libgtkdev package able compile wxpython so way install package locally buildout environment thanks,2 i know python change days i sure could write something convert html say every hour serve html version that give one largest optimisations possible since home page processed script engine,it works i want make super fast the index page static really change days unless date updates map updates so possible optimize fast since change much i recently migrated hrd uri montaoprojectappspotcom i rewrote python django html data layer trip memcache other options reduce javascript i first made sure data layer touched def getself logo gethostfind br cookiedjangolanguage ptbr logo montao elif gethostfind allt selfrequestget hl logo cookiedjangolanguage sv elif gethostfind gralumo selfrequestget hl cookiedjangolanguage esar learn else logo cookiedjangolanguage selfrequestget hl edit cookiedjangolanguage cookiedjangolanguage unset del selfrequestcookies djangolanguage else selfrequestcookies djangolanguage cookiedjangolanguage translationactivatecookiedjangolanguage loginmsg user usersgetcurrentuser twittername none client oauthclient twitter self clientgetcookie info clientget accountverifycredentials twittername info screenname secondsvalid selfresponseheaders cachecontrol public maxaged secondsvalid logo montao selfrender u montao hostgethost twitternametwittername continueurlgethost loginmsgloginmsg formurlblobstorecreateuploadurl fileupload userurlapiuserscreatelogouturlselfrequesturi apiusersgetcurrentuser else apiuserscreateloginurlselfrequesturi adminusersiscurrentuseradmin userusersgetcurrentuser usersgetcurrentuser else logologo else selfrender u home hostgethost twitternametwittername continueurlgethost loginmsgloginmsg formurlblobstorecreateuploadurl fileupload latestadallfilter published trueorder modified get userurlapiuserscreatelogouturlselfrequesturi apiusersgetcurrentuser else apiuserscreateloginurlselfrequesturi adminusersiscurrentuseradmin guserusersgetcurrentuser usersgetcurrentuser else logologo,1 you could write method returns appropriate date car owner return birthday else return creationdate order model based method,i got model eg car foreign key eg owner may may blank the car creationdate i would like order cars date car owner date birth owner must taken instead creationdate car is possible,1 have look similar question good ways sort queryset django you use model meta ordering accepts one field httpsdocsdjangoprojectcomendevrefmodelsoptionsordering you use query orderby creationdate birthdate sorts birthdate creationdate so could write custom manager incorporate custom sort import operator class carmanagermodelsmanager def getquerysetself auths supercarmanager selfgetquerysetallorderby creation ordered sortedauths keyoperatorattrgetter birthday return ordered class carmodelsmodel sorted carmanager query carsortedall get queryset sorted car,i got model eg car foreign key eg owner may may blank the car creationdate i would like order cars date car owner date birth owner must taken instead creationdate car is possible,2 use conditional expression x x else x x alist math geek note also solve particular case x x x alist i prefer first option anyway,i list i want use certain function entries fulfills certain condition leaving entries unmodified example say i want multiply elements even alist wanted result alist but elem elem alist elem yields acted filter addition what correct way go,3 alist print elem elem else elem elem alist long list want modify place alist ielem enumeratealist elem alisti elem even elements modified,i list i want use certain function entries fulfills certain condition leaving entries unmodified example say i want multiply elements even alist wanted result alist but elem elem alist elem yields acted filter addition what correct way go,1 one way make cython create c files use pyxbld file for example create foopyxbld containing following def makeextmodname pyxfilename distutilsextension import extension return extensionnamemodname sourcespyxfilename language c,pyximport super handy i figure get engage c language options cython from command line run cython cplus foopyx how achieve equivalent pyximport thanks,3 have look serving static files development you need define staticurl staticfilesdirs let djangocontribstaticfiles know look files,i documentation make sense i ran collectstatic i set static directories app project directories i added staticurl staticroot settingspy file i idea know set correctly staticurl still rendering anything it seems like heck lot overkill connect html css i think i lost details could anyone supply highlevel breakdown static files idea i afraid i may mixed instructions production development setups more here relevant bit settingspy file installedapps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages uncomment next line enable admin djangocontribadmin uncomment next line enable admin documentation djangocontribadmindocs djangocontribstaticfiles dashboardbase templatecontextprocessors djangocorecontextprocessorsdebug djangocorecontextprocessorsin djangocorecontextprocessorsmedia djangocorecontextprocessorsstatic djangocontribauthcontextprocessorsauth djangocontribmessagescontextprocessorsmessages staticroot staticurl static staticfilesdirs cusersseandesktopwork itemsdashboardbasestatic and code i trying use template link relstylesheet href staticurl csscss ok i made changes everybody recommended here new urlspy djangoconfurlsdefaults import baseviews import showproject djangoconf import settings djangocontribstaticfilesurls import staticfilesurlpatterns uncomment next two lines enable admin djangocontrib import admin adminautodiscover urlpatterns patterns example r dashboard include dashboardfoourls uncomment admindoc line enable admin documentation r admindoc include djangocontribadmindocsurls uncomment next line enable admin r admin includeadminsiteurls showproject showproject settingsdebug urlpatterns patterns urlr mediappath djangoviewsstaticserve documentroot settingsmediaroot showindexes true urlr staticppath djangoviewsstaticserve documentroot settingsstaticroot showindexes true urlpatterns staticfilesurlpatterns am i missing something usually problems turn something really basic cs pros take granted i miss,1 the reason pass python indentation dependent expects one indented statement colon class function when statements case stubbed function class still needs least one indented statement use special pass statement placeholder you could easily put something effect like class loaf true also fine less clear using pass opinion,can explain concept stubbing functions classes taken article class loaf pass this class define methods attributes syntactically needs something definition use pass this python reserved word means “move along nothing see here” it statement nothing good placeholder stubbing functions classes thank,1 stubbing technique software development after planned module class example drawing uml diagram begin implementing as may implement lot methods classes begin stubs this simply means write definition function leave actual code later the advantage forget methods continue think design seeing code,can explain concept stubbing functions classes taken article class loaf pass this class define methods attributes syntactically needs something definition use pass this python reserved word means “move along nothing see here” it statement nothing good placeholder stubbing functions classes thank,1 stubbing functions classes this refers writing classes functions yet implementing for example maybe i create class class fooobject def barself pass def tankself pass i stubbed functions i yet implemented however i think great plan instead class fooobject def barself raise notimplementederror def tankself raise notimplementederror that way accidentally call method implemented get error nothing happening,can explain concept stubbing functions classes taken article class loaf pass this class define methods attributes syntactically needs something definition use pass this python reserved word means “move along nothing see here” it statement nothing good placeholder stubbing functions classes thank,3 a stub placeholder class function anything yet needs class function question defined the idea already use certain aspects put collection pass callback even though written implementation yet stubbing useful technique number scenarios including team development often lead programmer provide class skeletons filled method stubs comment describing method leaving actual implementation team members iterative development stubbing allows starting partial implementations code complete yet still compiles details filled course later iterations demonstrational purposes if content method class interesting purpose demonstration often left leaving stubs,can explain concept stubbing functions classes taken article class loaf pass this class define methods attributes syntactically needs something definition use pass this python reserved word means “move along nothing see here” it statement nothing good placeholder stubbing functions classes thank,2 the getkeys function calls listkeys back end considered expensive operation performs full scan key space depending riak back end could also involve full scan data stored disk innostore springs mind the default storage back end bitcask stores keys memory performance much problem the reason listkeys considered expensive formerly blocking operation involved basho developers refer fold keys listkeys uses snapshot bucket instead reading live key space makes lighter weight operation well this made easier upgrade riak if using leveldb back end enable secondary indexes bucket use key index automatically provided riak get list keys bucket as riak ship better implementation something like ask functionality in rdbms getting primary keys table involves full table scan in riak getting keys bucket requires scanning data every node shipping key names back originating node combining data sending calling client because riak distributed unordered state operation expensive matter slice there i outlined ways make better,according riak docs using python bindings getkeys extremely expensive suitable production my question whether simple map query suitable for instance using map stage function functionv return vkey going perform better getkeys riak ship implementation instead current version getkeys is better way i listing keys bucket,1 if want slice d list limits x x def getsubgridx x grid return itemxx item gridyy example grid print getsubgridgrid prints,how would get sublist bigger list gridx gridy grid gridx rangegridy subgrid none i want get subgrid given xy grid origin bottomleft xy subgrid size,2 the idea behind static files idea distribute development related media file cssjs etc perapp basis allow static files application manage collect resources various places so tell static files app look static files settings staticfilesdirs copy staticroot path access staticurl when run collectstatic search directories copies files finds static root the benefit manage static files finer leve projectappstaticcss these cssjs particular app projectappstaticcss projectappstaticcss projectstaticcss these might general cssjs whole project static this collectstatic command copy files collectstatic projectappstaticcss projectappstaticcss projectappstaticcss projectstaticcss staticappcss staticappcss staticappcss staticcss when put appsite production server let webserver apache nginx deal serving files telling serve media files static media directly passing requests application when developing though easier let development server to explicitly tell server request media static staticurl in urlspy put following similar djangoconf import settings settingsdebug urlpatterns patterns urlr mediappath djangoviewsstaticserve documentroot settingsmediaroot showindexes true urlr staticppath djangoviewsstaticserve documentroot settingsstaticroot showindexes true,i documentation make sense i ran collectstatic i set static directories app project directories i added staticurl staticroot settingspy file i idea know set correctly staticurl still rendering anything it seems like heck lot overkill connect html css i think i lost details could anyone supply highlevel breakdown static files idea i afraid i may mixed instructions production development setups more here relevant bit settingspy file installedapps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages uncomment next line enable admin djangocontribadmin uncomment next line enable admin documentation djangocontribadmindocs djangocontribstaticfiles dashboardbase templatecontextprocessors djangocorecontextprocessorsdebug djangocorecontextprocessorsin djangocorecontextprocessorsmedia djangocorecontextprocessorsstatic djangocontribauthcontextprocessorsauth djangocontribmessagescontextprocessorsmessages staticroot staticurl static staticfilesdirs cusersseandesktopwork itemsdashboardbasestatic and code i trying use template link relstylesheet href staticurl csscss ok i made changes everybody recommended here new urlspy djangoconfurlsdefaults import baseviews import showproject djangoconf import settings djangocontribstaticfilesurls import staticfilesurlpatterns uncomment next two lines enable admin djangocontrib import admin adminautodiscover urlpatterns patterns example r dashboard include dashboardfoourls uncomment admindoc line enable admin documentation r admindoc include djangocontribadmindocsurls uncomment next line enable admin r admin includeadminsiteurls showproject showproject settingsdebug urlpatterns patterns urlr mediappath djangoviewsstaticserve documentroot settingsmediaroot showindexes true urlr staticppath djangoviewsstaticserve documentroot settingsstaticroot showindexes true urlpatterns staticfilesurlpatterns am i missing something usually problems turn something really basic cs pros take granted i miss,1 i assume grid stored list lists that primary list second item if answer walk across lists start point endpoint sublist x rangestartx endx sublistappendoldlistxstartyendy,how would get sublist bigger list gridx gridy grid gridx rangegridy subgrid none i want get subgrid given xy grid origin bottomleft xy subgrid size,1 here mine setup it sounds like might missing static context processor staticroot staticurl in settingspy used development staticroot staticurl static and settingspy used production server staticurl staticmydomaincom staticroot homeuserpublichtmlstaticmydomaincom so static files located static on production server files static collected homeuserpublichtmlstaticmydomaincom served different web server nginx case django in words django application running apache never even receives requests static assets production context processor in order templates staticurl variable available need use djangocorecontextprocessorsstatic context processor also defined settingspy templatecontextprocessors context processors djangocorecontextprocessorsstatic context processors server static assets in development django get requests static assets production however development let django serve static content we use staticfilesurlpatterns urlspy tell django serve requests static djangocontribstaticfilesurls import staticfilesurlpatterns url patterns urlpatterns staticfilesurlpatterns,i documentation make sense i ran collectstatic i set static directories app project directories i added staticurl staticroot settingspy file i idea know set correctly staticurl still rendering anything it seems like heck lot overkill connect html css i think i lost details could anyone supply highlevel breakdown static files idea i afraid i may mixed instructions production development setups more here relevant bit settingspy file installedapps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages uncomment next line enable admin djangocontribadmin uncomment next line enable admin documentation djangocontribadmindocs djangocontribstaticfiles dashboardbase templatecontextprocessors djangocorecontextprocessorsdebug djangocorecontextprocessorsin djangocorecontextprocessorsmedia djangocorecontextprocessorsstatic djangocontribauthcontextprocessorsauth djangocontribmessagescontextprocessorsmessages staticroot staticurl static staticfilesdirs cusersseandesktopwork itemsdashboardbasestatic and code i trying use template link relstylesheet href staticurl csscss ok i made changes everybody recommended here new urlspy djangoconfurlsdefaults import baseviews import showproject djangoconf import settings djangocontribstaticfilesurls import staticfilesurlpatterns uncomment next two lines enable admin djangocontrib import admin adminautodiscover urlpatterns patterns example r dashboard include dashboardfoourls uncomment admindoc line enable admin documentation r admindoc include djangocontribadmindocsurls uncomment next line enable admin r admin includeadminsiteurls showproject showproject settingsdebug urlpatterns patterns urlr mediappath djangoviewsstaticserve documentroot settingsmediaroot showindexes true urlr staticppath djangoviewsstaticserve documentroot settingsstaticroot showindexes true urlpatterns staticfilesurlpatterns am i missing something usually problems turn something really basic cs pros take granted i miss,2 do separate tests code need keep two closely together it tests take much disk space memory and tests extremely instructive library users for library packages include buildoutcfg bootstrappy file package make running tests easy see example plonereload package note uses zcrecipetestrunner parts create test script autodiscover tests run this way ensure library packages always tested then app packages need test integration applicationspecific code again include tests package want forget tests working code use zcrecipetestrunner parts buildout discover run last least use mrdeveloper manage packages with mrdeveloper check packages work rely released versions need work code a larger project many dependencies many need tweaking code with mrdeveloper pull source code turn development eggs time release code dismiss checkout to see actual example project buildout look plone core development buildout the sourcescfg file contains long list scm locations various packages normally released versions eggs used explicitly activate packages plan work checkoutscfg lists packages checked default packages changes part next version plone yet released if work plone want around cannot ignore changes and testingcfg lists packages need test want test plone big list note plone sources come wide variety locations once start using buildout mrdeveloper manage packages free pull source code anywhere,i several python projects share common modules until i ahem keeping multiple copies common code synchronizing hand but i clearly prefer something else it looks zcbuildout maybe i need i guess i putting reusable component system separate egg using buildout assemble projects i also thinking particular module i put unittests separate package egg i also installing copies component unittests every project i want unittest place library developed used so maybe i want something like projects lib tests code lib tests code app tests appcode app tests appcode etc where app app independent applications code tests also including using lib lib and libtest libcode libtest libcode app app separate eggs does sound right however i get confused i assume i develop app i want buildout pull copies lib lib app separate working directory rather put copies libraries app directly but work svn sourcecontrol if working directory dynamically constructed buildout live svn directory i check changes back repository have i misunderstood buildout meant used would i better going completely different approach how mix sourcecontrol modulereuse projects update thanks two people currently answered question i experimenting,3 in first example b attributes c class object think static attributes and x attributes c instances so regular instance attributes in second example four attributes c instances in python declare attributes defined specific class means attribute definitions inherit begin more less i going muddle waters introducing slots you find method definitions searching def methodname method definitions inherited oo languages confusingly access class attributes instances class assign new value attribute new instance attribute created in class cobject in c c in ca out in cdict out in ca in cdict out in c c in ca out which let give instance attribute default values using class attributes i believe common thing though – i favour using default values init arguments,let say code class ccc b def initself selfx none selfy how i quickly find python attribute method defined if belongs ancestor class method class c you see attributes b x must belong class c ancestor classes when type assigned variable why rather use class ccc b x none thank,2 why rather use class ccc b x none this thing this four classlevel attributes shared objects class c this different it two classlevel attributes shared objects class c two instance variables unique object class c class ccc b def initself selfx none selfy your two code samples different they cannot compared to answer question use grep tools search source it easy,let say code class ccc b def initself selfx none selfy how i quickly find python attribute method defined if belongs ancestor class method class c you see attributes b x must belong class c ancestor classes when type assigned variable why rather use class ccc b x none thank,1 try xpath astartswithhref httplyricsindianetsongsshow,i trying select links type httplyricsindianetsongsshow html contains links likes hrefhttplyricsindianetsongsshow classllyricsindianet dhiimii hrefhttpsmriticomhindisongsdhiimiidhiimiibhiiniibhiiniiutf classldhiimii songs archivea i gone scrapy documentation able figure any ideas,2 because standard body must separated headers empty line a message consists header fields optionally body the body simply sequence lines containing ascii characters it separated headers null line ie line nothing preceding crlf email software conforms standards expects empty line body if empty line assumes text part headers usually email softwares hide headers default,the following piece code formatting email script correctly it placing subject body correct parts email my problem i figure needs two returns two newlines rnrn connect function display body email rest headers need one cr def messageself subject inputwhat subject line message headers selfsendfrom selfsendto subject subject contenttype texthtml headers rnjoinheaders msg inputtype message return headers msg def connectself headers msg selfserverstarttls selfserverloginselfusrnameselfpswd selfserversendmailselfsendfrom selfsendto headers rnrn msg printi sent email return selfserver thanks,2 your question somewhat incomplete comparing two different operations if need add two things together testing xy going get anywhere so presumably want compare sum sum it lot complex interpreted languages like python hardware test nonzero introduces branch expensive but i want say would faster without timing throw equation different performance characteristics different architectures another confounding factor as always best write code natural maintainable way first time if feel need extract performance use profiler find hot spots optimise,which cpu intensive ifxnum check sum xy,1 your success function take parameter jquery pass contents response ajax request try see happens script function send ajax type post url pythondbpy datausername william async false success functionbody alert response received body datatype json script ps why using async false that kind defeats point ajax,i trying understand i use python javascript i use postget commands i button sends request serverside python return value i understand print response i want pass value javascript variable instead print thing response for example javascript sends string python file using jquery post function script function send ajax type post url pythondbpy datausername william async false success function alert response received datatype json script then using python cgi module i print value username usrbinenv python import cgi print contenttype texthtml print form cgifieldstorage print formgetvalueusername however i receiving data way php echo function works is equivalent echo python cgi module i read question explains different python frameworks used communicate browser server moment i hoping keep things simple possible use cgi module i know best option,1 from sqlalchemy achieve using hybridproperty see docs httpwwwsqlalchemyorgdocsormextensionshybridhtml,i using sqlalchemy declarative base define model i defined property name computed one columns title class entrybase tablename blogentry id columninteger primarykeytrue title columnunicode property def nameself return resubr azaz selftitlereplace lower when trying perform query using name sqlalchemy throws error sessionqueryentryfilterentryname mynamefirst argumenterror filter argument must type sqlalchemysqlclauseelement string after investigating i found maybe comparableusing could help i find example shows comparator references another column table is even possible better approach,3 unfortunately original file problems tabs spaces look indentation expandlinks i fixed indentation problems changed regsubgsub resub eliminated string import using string type methods after script worked perfect pmwpy created before running freeze also copy following files cusersjoaquindesktoppmwsrcpmwpmwlibpmwbltpy cusersjoaquindesktoppmwsrcpmwpmwlibpmwcolorpy here corrected script usrbinenv python helper script freezing pmw applications it concatenates pmw megawidget files single file pmwpy current directory the script must called one argument path lib directory required version pmw to freeze pmw application also need copy following files application directory freezing pmwbltpy pmwcolorpy import os import import sys the order files significant files reference files must appear later files may deleted used files dialog timefuncs balloon buttonbox entryfield group labeledwidget mainmenubar menubar messagebar messagedialog notebook optionmenu panedwidget promptdialog radioselect scrolledcanvas scrolledfield scrolledframe scrolledlistbox scrolledtext historytext selectiondialog textdialog timecounter aboutdialog combobox comboboxdialog counter counterdialog set use pmwcolor functions needcolor set use pmwblt functions needblt def expandlinkspath ospathisabspath path ospathjoinosgetcwd path ospathislinkpath break dir ospathdirnamepath path ospathjoindir osreadlinkpath return path def mungefilefile read file modify bundled pmw files file pmw file py text openospathjoinsrcdir fileread text resub import pmw text text resub initopt pmwinitopt text text resub pmw text text n n file file n text return text work version bundled file sysargv file ospathnormpathfile file expandlinksfile dir ospathdirnamefile dir expandlinksdir dir ospathdirnamedir dir expandlinksdir dir ospathbasenamedir version dirreplace code import color module colorcode import pmwcolor color pmwcolor del pmwcolor code import blt module bltcode import pmwblt blt pmwblt del pmwblt code used linking pmwbltpy ignorebltcode bltimported bltbusyok code define functions normally supplied dynamic loader extracode loader functions version def setversionversion version version raise valueerror dynamic versioning available def setalphaversionsalphaversions alphaversions raise valueerror dynamic versioning available def versionalpha alpha return else return version def installedversionsalpha alpha return else return version noblt sysargv sysargvremove noblt needblt nocolor sysargv sysargvremove nocolor needcolor lensysargv print usage bundlepmwpy noblt nocolor pathtopmwpmwxxxlib sysexit srcdir sysargv ospathexists pmwpy print pmwpy already exists remove try sysexit outfile open pmwpy w needcolor outfilewritecolorcode needblt outfilewritebltcode outfilewriteextracode version specially handle pmwbasepy file text mungefile base text resub import pmwlogicalfont text text resub pmwlogicalfontfontinitialise fontinitialise text outfilewritetext needblt outfilewriteignorebltcode filesappend logicalfont file files text mungefilefile outfilewritetext print print pmwpy created needcolor needblt print before running freeze also copy following files needblt print ospathjoinsrcdir pmwbltpy needcolor print ospathjoinsrcdir pmwcolorpy,i unable make executable python program uses pmw python mega widgets i use cxfreeze gui backend guiexe searching pmw site i found caused pmw library checks modules ran work use pyexe similar programs libraries zip file more info found httppmwsourceforgenetdocdynamicloaderhtml so give solution page freezing pmw providing script generates single standalone pmw module easily freeze however script uses deprecated code work python i tried modify luck edit i like mention replacing regex work usrbinenv python helper script freezing pmw applications it concatenates pmw megawidget files single file pmwpy current directory the script must called one argument path lib directory required version pmw to freeze pmw application also need copy following files application directory freezing pmwbltpy pmwcolorpy import os import regsub import string import sys the order files significant files reference files must appear later files may deleted used files dialog timefuncs balloon buttonbox entryfield group labeledwidget mainmenubar menubar messagebar messagedialog notebook optionmenu panedwidget promptdialog radioselect scrolledcanvas scrolledfield scrolledframe scrolledlistbox scrolledtext historytext selectiondialog textdialog timecounter aboutdialog combobox comboboxdialog counter counterdialog set use pmwcolor functions needcolor set use pmwblt functions needblt def expandlinkspath ospathisabspath path ospathjoinosgetcwd path ospathislinkpath break dir ospathdirnamepath path ospathjoindir osreadlinkpath return path def mungefilefile read file modify bundled pmw files file pmw file py text openospathjoinsrcdir fileread text regsubgsub import pmw text text regsubgsub initopt pmwinitopt text text regsubgsub pmw text text n n file file n text return text work version bundled file sysargv file ospathnormpathfile file expandlinksfile dir ospathdirnamefile dir expandlinksdir dir ospathdirnamedir dir expandlinksdir dir ospathbasenamedir version stringreplacedir code import color module colorcode import pmwcolor color pmwcolor del pmwcolor code import blt module bltcode import pmwblt blt pmwblt del pmwblt code used linking pmwbltpy ignorebltcode bltimported bltbusyok code define functions normally supplied dynamic loader extracode loader functions version def setversionversion version version raise valueerror dynamic versioning available def setalphaversionsalphaversions alphaversions raise valueerror dynamic versioning available def versionalpha alpha return else return version def installedversionsalpha alpha return else return version noblt sysargv sysargvremove noblt needblt nocolor sysargv sysargvremove nocolor needcolor lensysargv print usage bundlepmwpy noblt nocolor pathtopmwpmwxxxlib sysexit srcdir sysargv ospathexists pmwpy print pmwpy already exists remove try sysexit outfile open pmwpy w needcolor outfilewritecolorcode needblt outfilewritebltcode outfilewriteextracode version specially handle pmwbasepy file text mungefile base text regsubgsub import pmwlogicalfont text text regsubgsub pmwlogicalfontfontinitialise fontinitialise text outfilewritetext needblt outfilewriteignorebltcode filesappend logicalfont file files text mungefilefile outfilewritetext print print pmwpy created needcolor needblt print before running freeze also copy following files needblt print ospathjoinsrcdir pmwbltpy needcolor print ospathjoinsrcdir pmwcolorpy,1 easyinstall b wherever easyinstall builddirectory wherever,i trying install python script packaged egg format using easyinstall the problem easyinstall downloads dependencies tmp however tmp dir mb free space i working nas drive set way is way specifying download directory help seem throw anything useful edit some details i running python setuputils c installed optware the nas arm based specifically dns funplug installed please let know like specific info when i use b option file still downloaded tmp it fact extraction process uses remaining space tmp easyinstall b mnthdhdaffphomeroot sqlalchemy searching sqlalchemy reading httppypipythonorgsimplesqlalchemy reading httpwwwsqlalchemyorg best match sqlalchemy downloading httppypipythonorgpackagessourcessqlalchemysqlalchemytargzmdbaaeedefdbbff processing sqlalchemytargz error no space left device i know file downloaded tmp running ls l tmp download happening ls l tmpeasyinstall total rwrr root root oct sqlalchemytargz df h output filesystem size used avail use mounted rootfs m m m devroot m m m devloop m m usrlocalmodules devmtdblock m k m usrlocalconfig devsda m m m mnthda devsdb m m m mnthdb devsda t g t mnthdhda devsdb t g t mnthdhdb devsda t g t opt thanks jack,2 well could use urlliburlopen get file contents memory extract second line immediately discard file memory wanted without ever hitting disk you going download contents internet though,i asked similar question yesterday i included code basically took question different tangent i intended so i shall try i rewriting python script crawls website find hundred text files i interest content text file beyond second line file previously i would download files loop extract second line i would like open file script discovers grab second line close without downloading harddrive opening so basically way i open file wwwexamplecomtxt take second line file copy array something without downloading opening,1 you could try something like urlliburlopen url readsplitlines i guess would download entire file memory,i asked similar question yesterday i included code basically took question different tangent i intended so i shall try i rewriting python script crawls website find hundred text files i interest content text file beyond second line file previously i would download files loop extract second line i would like open file script discovers grab second line close without downloading harddrive opening so basically way i open file wwwexamplecomtxt take second line file copy array something without downloading opening,1 instead refindallr dd mystring use refindallr mystring find pair want,i would like find match xy string is following seem good or better alternative suggest please note xy pairs several white spaces commas may exists mystring usrbinenv python import mystring tmp refindallr dd mystring print tmp v enumeratetmp v print match found thank,2 why search pair want also use match whitespace import def findpairx mystring return refindallr sdsds x mystring print findpair,i would like find match xy string is following seem good or better alternative suggest please note xy pairs several white spaces commas may exists mystring usrbinenv python import mystring tmp refindallr dd mystring print tmp v enumeratetmp v print match found thank,1 no regex needed astliteralevalmystringcount astliteralevalmystring print found,i would like find match xy string is following seem good or better alternative suggest please note xy pairs several white spaces commas may exists mystring usrbinenv python import mystring tmp refindallr dd mystring print tmp v enumeratetmp v print match found thank,1 your error line fileobjectappendoutput n traceback recent call last file stdin line module attributeerror file object attribute append use write method file object fileobjectwriteoutput n,i ask user output file append data whenever i try tells data append attribute i think i try open file seeing string actual file append data i tried multiple ways right i left outputfile strrawinputwhere would like save data fileobject openoutputfile fileobjectappendoutput n fileobjectclose the output i trying append list i earlier defined any help would greatly appreciated,2 file objects append method you looking write also strrawinput redundant rawinput already returns string,i ask user output file append data whenever i try tells data append attribute i think i try open file seeing string actual file append data i tried multiple ways right i left outputfile strrawinputwhere would like save data fileobject openoutputfile fileobjectappendoutput n fileobjectclose the output i trying append list i earlier defined any help would greatly appreciated,1 the error message pretty selfexplanatory this file objects append method you simply use write fileobjectwritestroutput n,i ask user output file append data whenever i try tells data append attribute i think i try open file seeing string actual file append data i tried multiple ways right i left outputfile strrawinputwhere would like save data fileobject openoutputfile fileobjectappendoutput n fileobjectclose the output i trying append list i earlier defined any help would greatly appreciated,1 you retrieve fist n lines perform line seek web server supports range header could retrieve first n bytes file byte seek if know maximum length line could import urllib maxlinelength nb terms bytes myheaders range bytes strmaxlinelength byte maxlinelength req urllibrequest httpwwwconstitutionorggrpericlesfuneralorationtxt headersmyheaders partial urlliburlopenreq partialreadline first line discarded yourvar partialreadline yourvar second line thucydides c bce rrn,i asked similar question yesterday i included code basically took question different tangent i intended so i shall try i rewriting python script crawls website find hundred text files i interest content text file beyond second line file previously i would download files loop extract second line i would like open file script discovers grab second line close without downloading harddrive opening so basically way i open file wwwexamplecomtxt take second line file copy array something without downloading opening,1 i guessing variables numpyarray numpymatrix for numpyarray defined elementwise multiplication in case use numpydot that give matrix multiplication or simply use numpymatrix operator matrix multiplication,i x matrix muitranspose x matrix covarianceiinverse the result multiplication x matrix output x matrix why how i get x matrix muitranspose muitransposeshape covarianceiinverse covarianceiinverseshape muitransposecovarianceiinverse muitransposecovarianceiinverseshape,3 scrap count tag create either model method counts fruit pass count via view method templates really intended business logic even simple counting,i trying make custom template tag increment variable that would used like fruit basket fruitisapple count apples endif endfor pthere apples apples basketp i came projectapptemplatetagscounterpy class counternodetemplatenode def initself varname selfvarname varname def renderself context selfvarname context contextselfvarname else contextselfvarname return registertag def counterparser token try tagname args tokencontentssplitnone except valueerror raise templatetemplatesyntaxerror counter node requires variable name return counternodeargs this works fine try use counter tag within loop the count variable increments inside loop gets reset variable called outside loop this render method templatedefaulttagsfornode class calls contextpop end i able grasp done dealt within custom template tag so question could i get counter tag increment even loops,2 use int constructor foo intfoo note use builtin abs function integer argument get integer result first place typeabs type int,if i want convert float integer python function i use the problem i use variable passed function mathfabs absolute value index list int function mathfabs returns float,2 probably looking round int foo intfoo introundfoo,if i want convert float integer python function i use the problem i use variable passed function mathfabs absolute value index list int function mathfabs returns float,1 i imagine loadmat filemat returns instance shelve class inherited dict class i assume using loadmat function scipyio scipyio import loadmat the scipy doc mentions loadmat returns dictionary guess returned object example open shelvefile longer access content closed might happen several reasons apart calling aclose mannually to prevent copy data real dictionary first loading data matdict matdictupdateloadmat filemat now retrieve keys values matdict matdict juncforwardc printashape work note valid solution long testing figuring matdict data in scriptmodelfunction would tipically load part shelve dict want close file explicitly f loadmat filemat f juncforwardc fclose i know statement works shelve support yet test handle closing even exception thrown loading loadmat filemat f f juncforwardc edit subclass numpy array add additional attributes import numpy np class matarraynparray def initself filepath f loadmatfilepath nparrayinitself f juncforwardc selfversion f version selfheader f header fclose want array resembling matlab structure matarray myfilemat aheader matlab matfile platform pcwin created wed sep ashape etc,i new matlab python need use values python matlab cell array i cell array integers execute line code print result get loadmat filemat print version header matlab matfile platform pcwin created wed sep juncforwardc array print continues could someone explain cell array arranged many dimensions i questions within cell array variables label coordinates assigned one arraycell dont know actual term use values bold i would like write python access values how i go to test i tried juncinfof aget juncforwardc try print juncinfof prints none why i puzzled previously tried works i could even print juncinfo i cannot even,1 create instance customlogger log module use singleton use imported instance rather class,hey i wondering implement global logger could used everywhere settings i class customloggerlogginglogger file formatters stuff the logger works perfectly i import module mainpy file create object like selflog logcustomloggerarguments but obviously cannot access object parts code am using wrong approach is better way,3 you pass string common substring first period the parts string separated period used different classes modules files etc like specifically logger logginggetloggerloggername part def getloggername logdirlogdirdefault levelloggingdebug logformatformat base ospathbasenamefile loggername ss base name logfilename ospathjoinlogdir slog loggername logger logginggetloggerloggername loggersetlevellevel ospathexistslogfilename osaccesslogfilename osrok oswok logfilename sslog logfilenamereplacelog strizfilllenstri try fh loggingfilehandlerlogfilename fh rotatingfilehandlerfilenamelogfilename modea maxbytes backupcount except ioerror exc errout unable createopen log file logfilename excerrno permission denied exception errout error permission denied errout elif excerrno no directory errout error no directory ospathsplitlogfilename errout elif excerrno too many open files errout error too many open files check open file descriptors procpidfd pid osgetpid else errout unhandled exception strexc errout raise logexceptionerrout else formatter loggingformatterlogformat fhsetlevellevel fhsetformatterformatter loggeraddhandlerfh return logger class mainthread def initself cfgdefaults configdir pidfile logdir testfalse selflogdir logdir loglevel loggingdebug logprefix mainthreadtest selftest else mainthread try selflogger getloggerlogprefix selflogdir loglevel format except logexception exc sysstderrwritesn exc sysstderrflush osexit else selfloggerdebug mainthread created starting init def runself selfloggerdebuginitializing reportthreads group cfg selfconfigitems selfloggerdebug group config group k v cfgitems selfloggerdebugs group k v try rt reportthreadself group cfg selflogdir selftest except logexception exc sysstderrwritesn exc sysstderrflush selfloggerexceptionexception creating reportthread group loggingshutdown osexit else selfthreadsappendrt selfloggerdebugthreads initialized jointname selfthreads selfthreads tstart selftest selfloop class reportthread def initself mainthread name config logdir test selfmainthread mainthread selfname name loglevel loggingdebug selflogger getloggermainthreadsreportthreads test selftest else selfname logdir loglevel format selfloggerinfoinit database selfinitdb etc name main mainthreadcfgdefaultsoptionscfgdefaults configdiroptionsconfigdir pidfileoptionspidfile logdiroptionslogdir testoptionstest,hey i wondering implement global logger could used everywhere settings i class customloggerlogginglogger file formatters stuff the logger works perfectly i import module mainpy file create object like selflog logcustomloggerarguments but obviously cannot access object parts code am using wrong approach is better way,2 use logginggetloggername create named global logger httpsdocspythonorglibrarylogginghtmllogginggetlogger mainpy import log logger logsetupcustomlogger root loggerdebug main message import submodule logpy import logging def setupcustomloggername formatter loggingformatterfmt asctimes levelnames modules messages handler loggingstreamhandler handlersetformatterformatter logger logginggetloggername loggersetlevelloggingdebug loggeraddhandlerhandler return logger submodulepy import logging logger logginggetlogger root loggerdebug submodule message output debug main main message debug submodule submodule message,hey i wondering implement global logger could used everywhere settings i class customloggerlogginglogger file formatters stuff the logger works perfectly i import module mainpy file create object like selflog logcustomloggerarguments but obviously cannot access object parts code am using wrong approach is better way,3 the issue simply defined eq class python idea compare something like would work class myuserobject def initself id selfid id def eqself return selfid otherid,i trying emulate django models in django djangocontribauthmodels import user userobjectsgetpk userobjectsgetusername root print true else print false true printed my implementation class myuser def initself id selfid id class user class objects staticmethod def getkwargs return myuser userobjectsgetpk userobjectsgetusername root print true else print false false printed how correct implementation get true how i achieve effect what change shall i,1 with double negative subtracting negative value ie adding positive value a clear explanation would look like selfbalance selfbalance intwithdrawamt therefore change selfbalanceselfbalance intwithdrawamt to selfbalanceselfbalance intwithdrawamt or better yet selfbalance intwithdrawamt,i newbie python i oops concept exploring python following account class class account def initselfbalance selfbalanceintbalance def depositselfdepositamt selfbalanceselfbalance intdepositamt def withdrawselfwithdrawamt withdrawamtintwithdrawamt selfbalanceselfbalance intwithdrawamt printselfbalance printsubtracting strwithdrawamt def getbalanceself returnselfbalance def strself returnthe balance account strselfgetbalance the accounttest program import account def main balanceamt inputenter balance amount newaccountaccountaccountintbalanceamt depositamtinputenter deposit amount newaccountdepositdepositamt printnewaccount withdrawamtinputenter withdraw amount newaccountwithdrawwithdrawamt printnewaccount main but i getting wrong output enter balance amount enter deposit amount the balance account enter withdraw amount subtracting the balance account when i withdraw i getting amount added instead subtracted what i wrong since i newbie i need suggestion programming practice is coding style appropriate,1 selfbalanceselfbalance intwithdrawamt actually parsed selfbalanceselfbalance intwithdrawamt say adding withdraw amount try single,i newbie python i oops concept exploring python following account class class account def initselfbalance selfbalanceintbalance def depositselfdepositamt selfbalanceselfbalance intdepositamt def withdrawselfwithdrawamt withdrawamtintwithdrawamt selfbalanceselfbalance intwithdrawamt printselfbalance printsubtracting strwithdrawamt def getbalanceself returnselfbalance def strself returnthe balance account strselfgetbalance the accounttest program import account def main balanceamt inputenter balance amount newaccountaccountaccountintbalanceamt depositamtinputenter deposit amount newaccountdepositdepositamt printnewaccount withdrawamtinputenter withdraw amount newaccountwithdrawwithdrawamt printnewaccount main but i getting wrong output enter balance amount enter deposit amount the balance account enter withdraw amount subtracting the balance account when i withdraw i getting amount added instead subtracted what i wrong since i newbie i need suggestion programming practice is coding style appropriate,1 wrap example function skip function call def example packagename import module moduleshowrealworldusage example doctest skip hello world,i got python module docstrings class methods realworld example module docstring the distinction methoddocstrings carefully crafted utterly repeatable tests realworld example copy n paste history linux shell happened invoke python interpreter eg realworld example python python releasemaint jul gcc prerelease debian linux type help copyright credits license information packagename import module moduleshowrealworldusage hello world class someclassobject def somemethodself true i want run doctest someclasssomemethod module docstrings doctest skip directive works per line would mean adding lines realworld example ugly is way make doctest skip entire block a bit like html,3 yes function called map def yx return x mapy the map function applies function every item returns list results,is way i give python list values like obtain function relates values like x something like i want plot anything i want substitute values function see result would edit way python calculate data related like i give list containing thousands values returns function adjusted values,1 based comments david heffernan answer i want know relation values i thousands values stored list i want know python tell related seems like trying regression analysis probably linear regression fit values you use numpy linear regression analysis python here sample numpy cookbook,is way i give python list values like obtain function relates values like x something like i want plot anything i want substitute values function see result would edit way python calculate data related like i give list containing thousands values returns function adjusted values,2 i assume want find sequences else pairs related linear function try plot see form somethign looks like straight line you also look correlation techniques check site basic statistic stuff look correlation basic statistics,is way i give python list values like obtain function relates values like x something like i want plot anything i want substitute values function see result would edit way python calculate data related like i give list containing thousands values returns function adjusted values,1 based revised question i going go ahead add answer no function i imagine unlikely find function comes close programming language your definitions tight enough anything reasonable yet if take simple case two input integers sorts relationships possible relationships def xy return def xy return def xy return repeat admittedly arbitrary valid relationships first second values array passed the possibilities solutions become even absurd ask relationship numbers,is way i give python list values like obtain function relates values like x something like i want plot anything i want substitute values function see result would edit way python calculate data related like i give list containing thousands values returns function adjusted values,1 did try using sudo like sudo easyinstall requests or specify install directory directory write privileges easyinstall installdirhomefoobar but really use pip instead easyinstall it much better lot features,i trying use easyinstall install module called requests easyinstall requests this worked fine week ago i using python today i installed python tried import requests one scripts failed i tried reinstalling requests easyinstall requests got error installdir usrlocallibpythondistpackages error create remove files install directory the following error occurred trying add remove files installation directory errno permission denied usrlocallibpythondistpackagestesteasyinstallpth the installation directory specified via installdir prefix distutils default setting usrlocallibpythondistpackages perhaps account write access directory if installation directory systemowned directory may need sign administrator root account if administrative access machine may wish choose different installation directory preferably one listed pythonpath environment variable for information options may wish consult documentation httppackagespythonorgdistributeeasyinstallhtml please make appropriate changes system try so i told go reinstall easyinstall i went httppypipythonorgpypisetuptools learned i delete setuptoolsegg setuptoolspth files system sitepackages directory syspath directories first so i i reinstalled setuptools setuptoolscpyegg it seemed successful i ran easyinstall requests i got basically error except directory pythondistpackages pythonsitepackages siddhionsiddhionlaptop easyinstall requests error create remove files install directory the following error occurred trying add remove files installation directory errno permission denied usrlocallibpythonsitepackagestesteasyinstallwritetest the installation directory specified via installdir prefix distutils default setting usrlocallibpythonsitepackages perhaps account write access directory if installation directory systemowned directory may need sign administrator root account if administrative access machine may wish choose different installation directory preferably one listed pythonpath environment variable for information options may wish consult documentation httppeaktelecommunitycomeasyinstallhtml please make appropriate changes system try also i easyinstall press tab i get options easyinstall easyinstall easyinstall how come easyinstall how i get easyinstall working,3 the data shipped basemap quite low resolution high resolution data takes quite lot space you load shapefiles display basemap i borrowed code tutorial the tutorial also links gadm download high resolution shapefiles country,i trying draw detailed coastline nyc area using basemap python using full resolution dataset manhattan looks like rectangle hudson show midtown here code i using any suggestions mpltoolkitsbasemap import basemap import matplotlibpyplot plt import numpy np basemapprojection merc llcrnrlaturcrnrlat llcrnrlon urcrnrlon lattsresolution f mdrawcoastlines mdrawrivers mfillcontinentscolor coral lakecolor aqua mdrawmapboundaryfillcolor aqua pltshow edit on exploration looks like issue rivers specifically i get detailed boundaries oceanic coastline still hudson river harlem river current code basemapprojection merc llcrnrlaturcrnrlat llcrnrlon urcrnrlon lattsresolution f mdrawmapboundaryfillcolor ad mdrawcoastlinescolor df linewidth mdrawriverscolor df linewidth mfillcontinentscolor white lakecolor ad pltshow,2 you wrapping jquery code documentready dom exist yet time trying attach handlers in general time need reference dom elements page opposed defining functions called later wrap ready callback run dom completely loaded try function ulthumb lihoverfunction function that work httpjsfiddlenetnrabinowitzgdsxh,i trying add jquery hover effect site instead downloading jquery i decided use google libraries api jquery i got key copied code goes header i copied jquery hover effect nothing happenning what i wrong this test page complete code handler class jquerytestwebapprequesthandler def getself selfresponseoutwritehtml selfresponseoutwritehead selfresponseoutwritescript typetextjavascript srchttpswwwgooglecomjsapikeygoogle libraries api keyscript selfresponseoutwritescript srchttpsajaxgoogleapiscomajaxlibsjqueryjqueryminjs ulthumb lihoverfunction thiscss zindex add higher zindex value image stays top thisfind img addclasshoverstop add class hover stop animation queue buildup animate margintop px the next lines vertically align image marginleft px top left width px set new width height px set new height padding px value speed fastslow hover animates function thiscss zindex set zindex back thisfind img removeclasshoverstop remove hover class stop animation queue buildup animate margintop set alignment back default marginleft top left width px set width back default height px set height back default padding px script selfresponseoutwritelink typetextcss relstylesheet hrefstylesheetsjquerycss selfresponseoutwritetitlejquery testtitle selfresponseoutwritehead selfresponseoutwritebody selfresponseoutwritediv classcontent selfresponseoutwrite ul classthumb lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlgifccww alt ali lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlgiygcww alt ali lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlgimcww alt ali lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlgmdcww alt ali lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlgmdcww alt ali lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlgiugcww alt ali lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlglrzcww alt ali lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlglwlcww alt ali lia hrefimg srchttptingappspotcomimageimgidagzawnltfyeasscehvbwvqywdlglwlcww alt ali ul selfresponseoutwritediv selfresponseoutwritebodyhtml,2 if keys values unique use bidirectional dictionary there one python package,i facing little performance problem one data structures used bigger project python basically i importing tabular delimited file using normal python open file iterator i splitting lines linesplitt now i want actual value column inserted sort dictionary returning id value and getting slow in general dictionary class looks like class dictionarylist def getbitlengthself iflenself return else return mathloglenself def insertvalueself value selfappendvalue return lenself def getvalueforvalueidself valueid return selfvalueid def getvalueidforvalueself value ifvalue self return selfindexvalue else return selfinsertvaluevalue the basic idea valueid index value dictionary list profiling program tells spend getvalueidforvalue function calls seconds ordered cumulative time list reduced due restriction dictionarypygetvalueidforvalue index the problem small test in real application environment function would called several million times would increase runtime large extend of course i could inherit python dict performance problem quite similar since i need get key given value case value already inserted dictionary since i python pro guys give tips make bit efficient best amp thanks help notec thanks guys performance bidict much better dictionarypygetvalueidforvalue dictionarypyinsertvalue best notec,1 unfortunately hash alone enough info reconstruct hash object the hash algorithm temporal depending internal structures input order generate hashes subsequent input hash small piece cross section algorithm data cannot alone used generate hashes additional data,i string sha hash i want pass python script convert sha object if i myhashedstring hashed string hashlibsha mupdate myhashedstring hash hash i want hash twiceit already hashed i want python parse original hashed string hash object how i,2 iterate list lists for list list lists compute new element append list,i list lists list good bad brown i would like add new element inner list summing two numbers so list look like list good bad brown how i add insert new element list adding column thanks help,2 in class based generic views request instance myview class here urlspy fooviews import aboutview r aboutviewasview urlspy imported per django thread this means calling asview create instance aboutview when request processed urlconf view method called aboutview instance created passing populating relevant data needed particular request using r aboutviewdispatch wrong cause requests share instance view including possible properties used different requests,in base class inside generic views django creates method view runtime attaches generic view class calls dispatch method class i understand purpose approach dispatch method called directly asview method class viewobject intentionally simple parent class views only implements dispatchbymethod simple sanity checking httpmethodnames get post put delete head options trace def initself kwargs constructor called urlconf contain helpful extra keyword arguments things go keyword arguments either save values instance raise error key value kwargsiteritems setattrself key value classonlymethod def asviewcls initkwargs main entry point requestresponse process sanitize keyword arguments key initkwargs key clshttpmethodnames raise typeerroruyou tried pass method name ukeyword argument don key clsname hasattrcls key raise typeerrorus received invalid keyword r clsname key def viewrequest args kwargs self clsinitkwargs return selfdispatchrequest args kwargs take name docstring class updatewrapperview cls updated possible attributes set decorators like csrfexempt dispatch updatewrapperview clsdispatch assigned return view def dispatchself request args kwargs try dispatch right method method exist defer error handler also defer error handler request method approved list requestmethodlower selfhttpmethodnames handler getattrself requestmethodlower selfhttpmethodnotallowed else handler selfhttpmethodnotallowed selfrequest request selfargs args selfkwargs kwargs return handlerrequest args kwargs def httpmethodnotallowedself request args kwargs allowedmethods selfhttpmethodnames hasattrself loggerwarning method not allowed requestmethod requestpath extra statuscode request selfrequest return httphttpresponsenotallowedallowedmethods,2 lst list lstappendlstlst,i list lists list good bad brown i would like add new element inner list summing two numbers so list look like list good bad brown how i add insert new element list adding column thanks help,2 part basics mock import mock mock object object kind dummy code want executed want know information number calls call arguments also might want specify return value code let us define simple function def foovalue return value value now ready create mock object mockfoo mockfoo returnvalue mock return value now check foo mockfoo mock return value and get information calls mockfoocalled true mockfoocallcount mockfoocallargs available attributes mock instance callargs funccode funcname callargslist funcdefaults methodcalls callcount funcdict sideeffect called funcdoc funcclosure funcglobals they quite selfexplanatory part patch decorator the patch decorator allows us easily create mock objects imported objects classes methods it useful writing unittests let us assume following module foopy class fooobject def foovalue return value value let us write test patch decorator we going patch method foo class foo module foo do forget imports mock import patch import foo patch foofoofoo def testmockfoo we assign return value mock object mockfooreturnvalue mock return value f foofoo return ffoo now run test mock return value voila our method successfully overridden,can give clear examples uses mock django unittests i want understand clearly update i figured things i share,3 use genex itertoolsislice n joinitertoolsislicetag tag tags tagstartswithtagfilter,i huge list tag strings filtered given tagfilter the returned joined string contain max tags n separated the code right looks like tags taggettags this returns list tags strings return n jointag tag tags tagstartswithtagfilter how i improve avoiding scan tags list tags matched i using python,2 see itertools recipies def taken iterable return first n items iterable list return listisliceiterable n case return n jointake tag tag tags tagstartswithtagfilter edit really list call unnecessary case join using islice ignacio answer adequate,i huge list tag strings filtered given tagfilter the returned joined string contain max tags n separated the code right looks like tags taggettags this returns list tags strings return n jointag tag tags tagstartswithtagfilter how i improve avoiding scan tags list tags matched i using python,1 after installed python install python version easyinstall pip the existing installations configured use python default may causing issue,i would like install module pip installing right directory i assume usrlocallibpythonsitepackages after i installed python today originally i installed modules successfully so i think something wrong python path how module installations go proper python directory szszlaptop pip install requests requirement already satisfied requests usrlocallibpythondistpackagesrequestspyegg installing collected packages requests successfully installed requests szszlaptop python python default oct gcc linux type help copyright credits license information import requests traceback recent call last file stdin line module importerror no module named requests z stopped python also python directories look like httppastieorg,3 there number ways use ssh within python the general approaches call local ssh binary using subprocesspopen similar suitable gathering results batch call control local ssh binary using pexpect similar pty psuedotty process control mechanism spawning interacting process terminal session automated manner use python modulelibrary like paramiko twisted conch implements ssh protocols either directly native python providing bindings underlying shared library dll sshcontroller second broad categories my humble utility classh first category your question suggests might best served exploring paramiko sounds like want set local variable state based results remote process execution i guessing want chance conflating sort local terminal output error messages remote command results in words sounds like want use ssh api rather ssh command utility this essential distinction the ssh command tries transparent unix analogous ms windows etc environments allow ssh opens connection remote system creates number channels remote job execution communicates so local ssh stdout remote commands stdout local ssh stderr mixture remote stderr ssh command error messages output debugging information see adding v verbose options ssh invocation similarly ssh command exit status normally reflect exit status remote shell however may also local ssh process exit code local error experience seems always value i know way could distinguish remote command exit value vs abend abnormal process end local process i suspect portable standard way my point using ssh command within code necessarily preclude separating output local processes ssh binary perhaps depending executing local shell emanated remote process perhaps shell intended remote process running ssh api on hand use something like paramiko establish session ssh protocol use reuse execute commands transfer files perform filesystem functions create tunnels in case create sshclient instance call execcommand method command execute remote host this conceptually similar making local function call raise exception command could executed reason results get stdout stderr cannot conflated possible output intermediary processes ssh binary executed case that i recommending approach it sounds like want execute several separate commands remote target way obviates possible complications arising running single call ssh utility without complications performance overhead making multiple calls ssh it sounds like code much simpler robust establish session use api,i need connect server via ssh using python execute comands assign result command differrent variables what simplest way i tried sshcontroller i think i screwed something prompt script waiting endlessly i grateful examples,3 you combine results generators created using generator expression single list itertoolschainfromiterable pickledumplistitertoolschainfromiterable mylistgeneratori range picklefile or rewrite generator include range call internally pickledumplistmylistgenerator picklefile,i function returns list via yield i use function follows mylist range mylist mylist listmylistgeneratori picklefile openmystuffdat wb pickledumpmylist picklefile picklefileclose i wondering efficient way pickle data i combine generators mylistgenerator mylistgenerator etc one generator used pickle sorry question sonds daft i new generators pickle thanks barry,3 if output want read simple largenum flush remaining output creadnonblockinglargenum csendline discard unwanted lines relevant line range nextc get answer case single line ans nextcstrip discard rest answer creadnonblockinglargenum you probably know highly dependent way scilab cli outputs data,i trying run scilab using pexpect module following code import pexpect cpexpectspawn scilabadvcli nb cexpect when i csendline plot plot shows but i csendline cexpect ans followed cbefore gives following put rn rn rn rnxbhxb rnxblxb how output sanitised obtain say,1 if willing upgrade version better take advantage concurrentfuturesprocesspoolexecutor i think improve performance popen method attempted precreate pool processes popen method creates new process every time you could write code thing earlier version move reason,i trying improve script scans files malicious code we list regex patterns file one pattern line these regex grep current implementation basically bash script findgrep combo the bash script takes seconds benchmark directory i able write python script seconds want improve first i post basecode tweaks i tried import os sys queue threading filelist rootdir sysargv class recurserthreadingthread def initself queue dir selfqueue queue selfdir dir threadingthreadinitself def runself selfaddtoqueueselfdir helper function for internal use only def addtoqueueself rootdir root subfolders files oswalkrootdir file files selfqueueputospathjoinrootfile selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput class scannerthreadingthread def initself queue patterns selfqueue queue selfpatterns patterns threadingthreadinitself def runself nextfile selfqueueget nextfile print trying nextfile selfscanfilenextfile nextfile selfqueueget helper function for internal ues only def scanfileself file fp openfile contents fpread patt selfpatterns selfpatternssearchcontents print match stri found file main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main filequeue queuequeue get shell scanner patterns patterns fpatt open rootpatterns giantre line fpatt patternsappendrecompilelinerstrip reignorecase giantre giantre linerstrip giantre giantre giantre recompilegiantre reignorecase start recursing directories recurser recurserfilequeuerootdir recurserstart print starting scanner start checking files scanner xrange scanner scannerfilequeue giantre scannerstart this obviously debuggingugly code mind million queueput i clean later some indentations showing properly paticularly scanfile anyway things i noticed using even threads scanner xrange make difference i still get seconds regardless i assume due python gil as opposed making giant regex i tried placing line pattern compilex re list iterating list scanfile function this resulted longer execution time in effort avoid python gil i tried thread fork grep helper function for internal ues only def scanfileself file subprocesspopengrep el filerootpatterns file stdout subprocesspipe output scommunicate output print matchfound file this resulted longer execution time any suggestions improving performance edit i post answers questions yet however answers several points raised david nehme just let people know i aware fact i million queueput blender to mark bottom queue my scanner threads keep dequeing hit bottom nextfile the processor cores however due gil using thread threads threads not make difference spawning subprocesses resulted significantly slower code sec vs ed yes slow findgrep combo actually slower indiscriminately greps file needed ron can upgrade must universal do think speed seconds the bash grepper seconds my python giant re method seconds w threads the popen method w thrads subprocesses ran seconds so far giant re python method clear winner far intuted here meat current findgrep combo not script it pretty simple there additional things like ls nothing result x slowdown even grep r slightly efficient x huge slowdown find target type f size szlimit exec grep eaq filehomepatterns ls tee homefoundtxt the python code efficient i know i experimentally tested i prefer python i already achieved speedup x python i would like get sped winner winner winner looks like winner intued shell script comes nd place seconds however steveha came first seconds due fact lot boxes python i cxfreeze i write shell script wrapper wget tar unpack i like intued simplicity however thanks help guys i efficient tool sysadmining,1 this one work reslist maplambda w w error elsed val list it fails block inside lambda expression i prefer list comprehension approach reslist error item else item item yourlist this generate errors if getting errors errors elsewhere program or perhaps indentation wrong post specific error message get also i advise use name list local variables hides builtin name,i list i need replace error others corresponding string i could code like reslist val list val reslistappenderror else reslistappendd val how i thing functional way i tried mapping reslist maplambda w w error elsed val list however compile syntax error what wrong,1 works error val else strval val list,i list i need replace error others corresponding string i could code like reslist val list val reslistappenderror else reslistappendd val how i thing functional way i tried mapping reslist maplambda w w error elsed val list however compile syntax error what wrong,1 the map work use python ternary operator correctly w lambda parameter consistently maplambda w error w else w list,i list i need replace error others corresponding string i could code like reslist val list val reslistappenderror else reslistappendd val how i thing functional way i tried mapping reslist maplambda w w error elsed val list however compile syntax error what wrong,1 i bit confused python script ended faster findgrep combo if want use grep way somewhat similar suggested ron smith answer something like find type f xargs n p n grep filerootpatterns launch grep processes process files exiting keeping processes active one time having process files make process startup overhead time one negligible note the n option xargs gnu extension work posixish systems it specifies elimiter filenames newline although technically filenames contain newlines practice nobody keeps jobs for compatibility nongnu xargs need add print option find use instead n xargs this arrange null byte hex x used delimiter find xargs you could also take approach first counting number files grepped numfilesfind type f wc l using number get even split among processes assuming bash shell find type f xargs n p n numfiles grep filerootpatterns i think might work better disk io find interfering disk io various grep i suppose depends part large files whether stored contiguously — small files disk seeking lot anyway matter much note also especially decent amount ram subsequent runs command faster files saved memory cache of course parameterize make easier experiment different numbers concurrent processes as ed mentions comments quite possible performance approach still less impressive singleprocess grep r i guess depends relative speed disk array number processors system etc,i trying improve script scans files malicious code we list regex patterns file one pattern line these regex grep current implementation basically bash script findgrep combo the bash script takes seconds benchmark directory i able write python script seconds want improve first i post basecode tweaks i tried import os sys queue threading filelist rootdir sysargv class recurserthreadingthread def initself queue dir selfqueue queue selfdir dir threadingthreadinitself def runself selfaddtoqueueselfdir helper function for internal use only def addtoqueueself rootdir root subfolders files oswalkrootdir file files selfqueueputospathjoinrootfile selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput class scannerthreadingthread def initself queue patterns selfqueue queue selfpatterns patterns threadingthreadinitself def runself nextfile selfqueueget nextfile print trying nextfile selfscanfilenextfile nextfile selfqueueget helper function for internal ues only def scanfileself file fp openfile contents fpread patt selfpatterns selfpatternssearchcontents print match stri found file main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main filequeue queuequeue get shell scanner patterns patterns fpatt open rootpatterns giantre line fpatt patternsappendrecompilelinerstrip reignorecase giantre giantre linerstrip giantre giantre giantre recompilegiantre reignorecase start recursing directories recurser recurserfilequeuerootdir recurserstart print starting scanner start checking files scanner xrange scanner scannerfilequeue giantre scannerstart this obviously debuggingugly code mind million queueput i clean later some indentations showing properly paticularly scanfile anyway things i noticed using even threads scanner xrange make difference i still get seconds regardless i assume due python gil as opposed making giant regex i tried placing line pattern compilex re list iterating list scanfile function this resulted longer execution time in effort avoid python gil i tried thread fork grep helper function for internal ues only def scanfileself file subprocesspopengrep el filerootpatterns file stdout subprocesspipe output scommunicate output print matchfound file this resulted longer execution time any suggestions improving performance edit i post answers questions yet however answers several points raised david nehme just let people know i aware fact i million queueput blender to mark bottom queue my scanner threads keep dequeing hit bottom nextfile the processor cores however due gil using thread threads threads not make difference spawning subprocesses resulted significantly slower code sec vs ed yes slow findgrep combo actually slower indiscriminately greps file needed ron can upgrade must universal do think speed seconds the bash grepper seconds my python giant re method seconds w threads the popen method w thrads subprocesses ran seconds so far giant re python method clear winner far intuted here meat current findgrep combo not script it pretty simple there additional things like ls nothing result x slowdown even grep r slightly efficient x huge slowdown find target type f size szlimit exec grep eaq filehomepatterns ls tee homefoundtxt the python code efficient i know i experimentally tested i prefer python i already achieved speedup x python i would like get sped winner winner winner looks like winner intued shell script comes nd place seconds however steveha came first seconds due fact lot boxes python i cxfreeze i write shell script wrapper wget tar unpack i like intued simplicity however thanks help guys i efficient tool sysadmining,3 according tornado documentation if error occurs fetch httpresponse given callback nonnone error attribute contains exception encountered request you call responserethrow throw exception callback tornadohttpclient import asynchttpclient tornadohttpclient import httprequest tornadostackcontext import exceptionstackcontext tornado import ioloop import traceback def handleexcargs print exception occured return true def handlerequestresponse responseerror none exceptionstackcontexthandleexc responserethrow else print handle request httpclient asynchttpclient httpclientfetch httpsomesitecom handlerequest httpclientfetch httpgooglecom handlerequest ioloopioloopinstancestart the message seeing console warning sent loggingwarning it harmless really bothers see logging module filter,i trying handle exception occurred asyncclientfetch way tornadohttpclient import asynchttpclient tornadohttpclient import httprequest tornadostackcontext import exceptionstackcontext tornado import ioloop def handleexcargs print exception occured return true def handlerequestresponse print handle request httpclient asynchttpclient exceptionstackcontexthandleexc httpclientfetch httpsomesitecom handlerequest ioloopioloopinstancestart see next output warningrootuncaught exception traceback recent call last file homecrchemistpythonlibpythonsitepackagestornadopyeggtornadosimplehttpclientpy line cleanup yield file homecrchemistpythonlibpythonsitepackagestornadopyeggtornadosimplehttpclientpy line init socketgaierror errno no address associated hostname handle request what i wrong,3 you say comments want want want that make sense the correct value calculating day modulo in math division gives remainder modulo what want number so need take day subtract get day instead add modulo add get back day result day that way always get correct number think special case,i difficulty working remainder zero modulo operator basically line code fday day i trying add day take remainder however user enters day result zero i want how i make operation return entered is better way update i trying take previously defined variable day add days value however user enters th day month i add i get days arent month that i trying use modulo operation give remainder instead works days one month thing another example if input would so works i trying add days value still keep output days month purposes i,2 i believe sublime provided dynamically call plugin via console remember import physical py file library inmemory representation i found decent reference confusions often related import little old i believe still relevant httpeffbotorgzoneimportconfusionhtm edit just confirm i checked python runtime embedded inside executable sublime sublime module defined inside,sublime text text editor extended via python scripts using modules import sublime sublimeplugin i searched computer found sublimepluginpy file but sublimepy,3 see documentation bitmap bitmapscaledtoheight qtsmoothtransformation,in pyqt based gui program i drawing png file qpixmap resize so basically happens bitmap qpixmap foopng bitmapscaletoheight original larger sceneadditemqgraphicspixmapitembitmap add graphics scene the problem afterwards bitmap rather ugly is way antialiasing way thanks,2 use filter function appropriate function list filterlambda x x x list demo in list good bad change in filterlambda x x x list out bad note good satisfy condition false even though said question if many elements might want use equivalent function itertools itertools import ifilter filtered ifilterlambda x x x list,i list lists word good freq bad freq changestatus list good bad change i would like delete list elements satisfy condition so changestatus badfreq i would like delete elements corresponding so list would modified list good bad how i selective,2 list good bad change list item item list item item you also use item item condition want,i list lists word good freq bad freq changestatus list good bad change i would like delete list elements satisfy condition so changestatus badfreq i would like delete elements corresponding so list would modified list good bad how i selective,3 i know pydev editors shifttab trick,i using pydev python development i facing issue removing indentation block statement if i add indentation i used press shift arrow key i reach end block statements i want indent press tab keythis used add indent block statements one step the issue i facing remove indent one step block statementfor example i loop block statement loop now i dont want loop want remove indent underlying loop statement block at present i going line press backspace remove indentation is easy way entire statement block,3 it looks like interactive process use somewhat memory compare malkovichmalkovichetc malkovichmalkovichetc python c import time timesleep amp malkovichmalkovichetc pidstat r p linux malkovich x cpu pm pid minflts majflts vsz rss mem command pm python malkovichmalkovichetc kill malkovichmalkovichetc terminated python c import time timesleep malkovichmalkovichetc python python r sep gcc linux type help copyright credits license information import time timesleep z stopped python malkovichmalkovichetc jobs p malkovichmalkovichetc pidstat r p linux malkovich x cpu pm pid minflts majflts vsz rss mem command pm python the rss resident memory usage value one interesting kb interactive process i would expect value difference increase somewhat significantly use command history niceties provided interactive session i think would ever significant difference may want run similar tests particular situation to background running interpretive session literally press z ctrlz but overall i think difference significant unless running embedded system mb ram note write code module import compiled bytecode saved this i believe reduce memory consumption also decrease startup time subsequent invocations you might want run tests get idea difference,is difference two modes terms resources especially memory i referring python title common explanation many interpreted languages octave etc would helpful thanks,1 are looking line enumerategrid print char line print char print,i come grief trying achieve following though i suspect simple fix temporarily leaked brain i need able print grid variable dimensions numbers lefthand side like grid composed nested lists using enumerate like line enumerategrid return line i get numbers left hand side however output appears lists untidy quite i moment i printing grid numbers using def printgridgrid line grid char line print char print is something else i ought using instead enumerate get numbers along side because grid set variable parameters i really hoping would way achieving printing rather modifying code i used construct grid i desperate tamper least break i search around internet found instances people numbers appearing base whatever picture drawing left hand side like no matter i stick enumerate statement printgrid function messes output,1 due quirk python call encode byte string ie text already encoded in case first tries convert unicode object decoding ascii so geturlcontents returning byte string line effectively geturlcontentsrdecode ascii encode ascii ignore in python byte strings encode method problem would cause attributeerror of course i know problem could related geturlcontents function but i described best guess,this line data geturlcontentsrencode ascii ignore produces error unicodedecodeerror ascii codec decode byte xc position ordinal range why i assumed i using ignore impossible decode errors saving output value string variable,2 you join list single string line enumerategrid print joinline,i come grief trying achieve following though i suspect simple fix temporarily leaked brain i need able print grid variable dimensions numbers lefthand side like grid composed nested lists using enumerate like line enumerategrid return line i get numbers left hand side however output appears lists untidy quite i moment i printing grid numbers using def printgridgrid line grid char line print char print is something else i ought using instead enumerate get numbers along side because grid set variable parameters i really hoping would way achieving printing rather modifying code i used construct grid i desperate tamper least break i search around internet found instances people numbers appearing base whatever picture drawing left hand side like no matter i stick enumerate statement printgrid function messes output,2 normally i recommend inverting page putting indexhtml staticfile well css js files making ajax request server fill dynamic bits static files load really fast you might still able pull using clientside javascript figure logo use getting file upload form rendered going slower since createuploadurl needs happen server side,it works i want make super fast the index page static really change days unless date updates map updates so possible optimize fast since change much i recently migrated hrd uri montaoprojectappspotcom i rewrote python django html data layer trip memcache other options reduce javascript i first made sure data layer touched def getself logo gethostfind br cookiedjangolanguage ptbr logo montao elif gethostfind allt selfrequestget hl logo cookiedjangolanguage sv elif gethostfind gralumo selfrequestget hl cookiedjangolanguage esar learn else logo cookiedjangolanguage selfrequestget hl edit cookiedjangolanguage cookiedjangolanguage unset del selfrequestcookies djangolanguage else selfrequestcookies djangolanguage cookiedjangolanguage translationactivatecookiedjangolanguage loginmsg user usersgetcurrentuser twittername none client oauthclient twitter self clientgetcookie info clientget accountverifycredentials twittername info screenname secondsvalid selfresponseheaders cachecontrol public maxaged secondsvalid logo montao selfrender u montao hostgethost twitternametwittername continueurlgethost loginmsgloginmsg formurlblobstorecreateuploadurl fileupload userurlapiuserscreatelogouturlselfrequesturi apiusersgetcurrentuser else apiuserscreateloginurlselfrequesturi adminusersiscurrentuseradmin userusersgetcurrentuser usersgetcurrentuser else logologo else selfrender u home hostgethost twitternametwittername continueurlgethost loginmsgloginmsg formurlblobstorecreateuploadurl fileupload latestadallfilter published trueorder modified get userurlapiuserscreatelogouturlselfrequesturi apiusersgetcurrentuser else apiuserscreateloginurlselfrequesturi adminusersiscurrentuseradmin guserusersgetcurrentuser usersgetcurrentuser else logologo,1 consider using functionality datetime module instead trying reinvent datetime import date timedelta month day start date month day later start timedeltadays print strstart strlater,i difficulty working remainder zero modulo operator basically line code fday day i trying add day take remainder however user enters day result zero i want how i make operation return entered is better way update i trying take previously defined variable day add days value however user enters th day month i add i get days arent month that i trying use modulo operation give remainder instead works days one month thing another example if input would so works i trying add days value still keep output days month purposes i,1 the deal sockets know exactly long message receiving plan keep using socket connection you seem idea qbytes rawinputenter number mbs transfer need know exactly nearest mb sometimes information sent front part data read first know stop reading the exception need connection anymore want one picture in case fine ask much data want get empty string back end as maxbytes argument recv one maximum another hardwaredependent maximum imposed us tests mb the code keeps asking data stops receives empty string data combines gathered data full string there many levels abstraction could built distance us complications code working irrelevant bits taken clientpy import sys os socket pygame pygamelocals import pygameinit sclient socketsocketsocketafinetsocketsockstream host porta tbytes sclientconnecthostintporta print conectado size width height screen pygamedisplaysetmodesize message true sclientrecvtbytes break else messageappends fulls joinmessage print string received size lenfulls image pygameimagefrombufferfulls size rgb image pygameimagefromstrings size rgb screenblitimage pygamedisplayflip event pygameeventget eventtype quit pygamequit osexit rawinput sclientclose serverpy import sys os socket pygame pygamelocals import socket socketsocketsocketafinet socketsockstream host port socketbindhost intport socketlisten socketclient socketaccept print client conectado strclient nporta usada strclient img imageopen tinyjpg resize imgtostring print size string lens socketsendalls socketclose edit as per mark correction len calls previously sizeof method calls sizeof returns size python object bytes number bytescharacters string,i created one program pygame imagegrab sockets work it take printscreen server imagegrab convert string send client however client upon receiving information converting image raises error image pygameimagefrombufferimg rgb valueerror buffer length equal format resolution size code server import sys os socket pygame pil import imagegrab pygamelocals import print streaming sever try socket socketsocketsocketafinet socketsockstream except socketerror print error creating socket sysexit host port rawinputport socketbindhost intport socketlisten socketclient socketaccept print client conectado strclient nporta usada strclient capture send true imgimagegrabgrabresize imgtostring socketsendallimg socketclose code client import sys os socket pygame pil import imagegrab pygamelocals import print streaming client pygameinit try sclient socketsocketsocketafinetsocketsockstream print streaming protocol started except socketerror print error creating socket sysexit host porta rawinputport qbytes rawinputenter number mbs transfer tbytes intqbytes try sclientconnecthostintporta except socketerror print error connecting host sysexit print conectado size width height screen pygamedisplaysetmodesize num true img sclientrecvtbytes image pygameimagefrombufferimg rgb screenblitimage pygamedisplayflip event pygameeventget eventtype quit pygamequit osexit recebimento sclientclose,1 text list strings that return true word line text you probably want iterate text check word lines of course multiple ways write see simple example,my simple script check certain word files seems failing i cannot seem explain documentation searching the code i believe i narrowed operator failing printing code finding word i looking if curious script find certain keywords quake source code since i rather look full source files any help would appreciated thanks import os def searchfilefilename word file openosgetcwd filename r text filereadlines debug code print text ifword text print yep else print nope,3 the reason failing checking word within text lines just use read method check iterate lines individually first method text fileread word text print yep second method goes line text checking useful want know line line enumeratefile word line print yep found line sword,my simple script check certain word files seems failing i cannot seem explain documentation searching the code i believe i narrowed operator failing printing code finding word i looking if curious script find certain keywords quake source code since i rather look full source files any help would appreciated thanks import os def searchfilefilename word file openosgetcwd filename r text filereadlines debug code print text ifword text print yep else print nope,3 that function method you need call method object p prac pfun read,i trying practice testing modules adding name main end module the idea run module script get output able import another script interactive python session i using python whole code class prac this module practice creating main within module def funself print testing function call name main fun,1 try pyapp pyapp python setuptools command allow make standalone application bundles plugins python scripts pyapp similar purpose design pyexe windows,is possible convert py script app works text box something thanks,2 the problem simplehttprequesthandler serves files directory execute you must override doget method want execute code,running python webserver using simple script httpserver import simplehttprequesthandler rh socketserver import tcpserver servername localhost onport print server running port tcpserverservername onport rhserveforever running good run indexhtml file run py file browser type httplocalhostmyfilepy show python codes write file execute code please help run python file py browser using webserver want use framework another webserver is way make virtual host python server like apache possible please suggest configuration file need configured thanx,1 the easiest way make copies lists add grid rangeheight gridappendline else boardappendlinerev,ok program previously i hit problem i anticipated grid variable width height constructed based code alternate symbols creates list lists stored grid nested lists section code making list called line odd numbered width necessary gridwidth rangegridwidth lineappend else lineappend edit sorry i want spam code lines put list grid grid rangeheight gridappendline else gridappendlinerev line appended grid rangeheight another block code handle alternating lines creates another list linerev problem grid created i try change value say turn grid changes along several rows grid grid etc referring list way avoid without using global variables deep copy drastically revising grid created any help would much appreciated,2 you might want check cgihttprequesthandler instead i briefly played linux based system cgi criteria file executable correct shabang i sure would work windows though even relevant concern with example code would need change rh import cgihttpservercgihttprequesthandler rh alternatively rd party library twisted concept rpy files mostly plain python logic httptwistedmatrixcomtracwikitwistedweb note just verified cgihttprequesthandler works caveats python files must cgibin subdir must valid shabang must executable must provide valid cgi output personally written c cgi scripts cgi route seems like path maddness check twisted cherrypy django three mostly cover python web spectrum possibilities,running python webserver using simple script httpserver import simplehttprequesthandler rh socketserver import tcpserver servername localhost onport print server running port tcpserverservername onport rhserveforever running good run indexhtml file run py file browser type httplocalhostmyfilepy show python codes write file execute code please help run python file py browser using webserver want use framework another webserver is way make virtual host python server like apache possible please suggest configuration file need configured thanx,1 not much module library twistedconch might better approach warned modules twisted conch one intimidating atleast imho,i writing program creates reverse tunnels ssh i using popen currently i receiving error i many arguments so question is python module supports lot tunnels preferably,1 just clarify answer install pip grab haystack djangohaystack likewise typogrify surely packages in words one installedapps correct hope helps,i recently created account slicehost made new slice i copied new project changed paths settings every file but try access admin interface i get error templatesyntaxerror admin caught importerror rendering no module named urls in template usrlocallibpythondistpackagesdjangocontribadmintemplatesadminbasehtml error line caught importerror rendering no module named urls anyone know,1 depending complexity code could look using weave part scipy it allows embed cc code python module there tutorial another option could look boostpython may bit complex use,i class methods i happy performance except one method we want port c however want spend much time porting whole class c single method is possible how i should blank class not class what i want try use c version failed os missing pyd load python version thank,1 i using stdio communication python process recently noticed python net httppythonnetgithubio works just copy dll labview project create net constructors using labview net quickly figure use library basically provides unmanaged python shared library wrapped net goodness,how i send data labview python get result back,1 yes use kwargs construct read parameters def myfunctionkwargs key value kwargsiteritems print key value myfunctionatest bstring,to avoid obvious bugs i like prevent use positional arguments functions is way achieve,1 you could define decorator using introspection causes error function decorates uses positional arguments this allows prevent use positional arguments functions allowing define functions wish as example def kwargsonlyf def newfkwargs return fkwargs return newf to use kwargsonly def abca b c return b c you cannot use thus type error abc you use thus abcabc a robust solution would use decorator module disclaimer late night answers guaranteed,to avoid obvious bugs i like prevent use positional arguments functions is way achieve,3 only python properly used python tag fine def function x z printxyz using kwargs let user input argument unless check later also hide real arguments names introspection kwargs answer problem testing program function traceback recent call last file pyshell line module function typeerror function takes exactly positional arguments given functionx z,to avoid obvious bugs i like prevent use positional arguments functions is way achieve,3 the fix i found add parameter nocookies appcfgpy update nocookies myprojectdirectory this happen upload appengine applications different google accounts computer,i unable upload appengine appcfg telling this application exist appidu xxx i developer appengine i testing i created new appengine i owner i still get message newly created appengine,3 i think rather using threading module using multiprocessing module python solution python threads run afoul gil gil problem simply multiple python processes going i think pool worker processes want by default pool default one process core system processor just call map method list filenames check function checking httpdocspythonorglibrarymultiprocessinghtml if faster threading implementation i think gil problem edit okay i adding working python program this uses pool worker processes open file search pattern when worker finds filename matches simply prints standard output redirect output script file list files edit i think slightly easier read version easier understand i timed searching files usrinclude computer it completes search half second using find piped xargs run grep processes possible takes seconds x speedup but i hate baroque weird language must use get find work properly i like python version and perhaps really big directories disparity would smaller part halfsecond python must startup time and maybe half second fast enough purposes import multiprocessing mp import os import import sys stat import sisreg uncomment really want hardcoded homepatterns file home osenvironget home patternsfile ospathjoinhome patterns target sysargv sizelimit intsysargv assert sizelimit patternsfile sysargv build spat string like foobarbaz this match subpatterns foo bar baz means python bother build match group openpatternsfile f spat r format joinlinestrip line f precompile pattern speed pat recompilespat def walkfilestopdir yield full pathname file tree topdir dirpath dirnames filenames oswalktopdir fname filenames pathname ospathjoindirpath fname yield pathname def filestosearchtopdir yield full pathname files want search fname walkfilestopdir try regular file big enough want search sr osstatfname sisregsrstmode srstsize sizelimit yield fname except oserror pass def workersearchfnfname openfname rt f read one line time file line f researchpat line found match print filename stdout printfname stop reading file return return mppoolmapworkersearchfn filestosearchtarget,i trying improve script scans files malicious code we list regex patterns file one pattern line these regex grep current implementation basically bash script findgrep combo the bash script takes seconds benchmark directory i able write python script seconds want improve first i post basecode tweaks i tried import os sys queue threading filelist rootdir sysargv class recurserthreadingthread def initself queue dir selfqueue queue selfdir dir threadingthreadinitself def runself selfaddtoqueueselfdir helper function for internal use only def addtoqueueself rootdir root subfolders files oswalkrootdir file files selfqueueputospathjoinrootfile selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput selfqueueput class scannerthreadingthread def initself queue patterns selfqueue queue selfpatterns patterns threadingthreadinitself def runself nextfile selfqueueget nextfile print trying nextfile selfscanfilenextfile nextfile selfqueueget helper function for internal ues only def scanfileself file fp openfile contents fpread patt selfpatterns selfpatternssearchcontents print match stri found file main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main main filequeue queuequeue get shell scanner patterns patterns fpatt open rootpatterns giantre line fpatt patternsappendrecompilelinerstrip reignorecase giantre giantre linerstrip giantre giantre giantre recompilegiantre reignorecase start recursing directories recurser recurserfilequeuerootdir recurserstart print starting scanner start checking files scanner xrange scanner scannerfilequeue giantre scannerstart this obviously debuggingugly code mind million queueput i clean later some indentations showing properly paticularly scanfile anyway things i noticed using even threads scanner xrange make difference i still get seconds regardless i assume due python gil as opposed making giant regex i tried placing line pattern compilex re list iterating list scanfile function this resulted longer execution time in effort avoid python gil i tried thread fork grep helper function for internal ues only def scanfileself file subprocesspopengrep el filerootpatterns file stdout subprocesspipe output scommunicate output print matchfound file this resulted longer execution time any suggestions improving performance edit i post answers questions yet however answers several points raised david nehme just let people know i aware fact i million queueput blender to mark bottom queue my scanner threads keep dequeing hit bottom nextfile the processor cores however due gil using thread threads threads not make difference spawning subprocesses resulted significantly slower code sec vs ed yes slow findgrep combo actually slower indiscriminately greps file needed ron can upgrade must universal do think speed seconds the bash grepper seconds my python giant re method seconds w threads the popen method w thrads subprocesses ran seconds so far giant re python method clear winner far intuted here meat current findgrep combo not script it pretty simple there additional things like ls nothing result x slowdown even grep r slightly efficient x huge slowdown find target type f size szlimit exec grep eaq filehomepatterns ls tee homefoundtxt the python code efficient i know i experimentally tested i prefer python i already achieved speedup x python i would like get sped winner winner winner looks like winner intued shell script comes nd place seconds however steveha came first seconds due fact lot boxes python i cxfreeze i write shell script wrapper wget tar unpack i like intued simplicity however thanks help guys i efficient tool sysadmining,3 this possible falling back sql carobjectsfilterextraselect odate ifownerid select dateofbirth ownertable idownerid creationdate orderby odate function mysqlspecific in case sqlite postgres use case statement,i got model eg car foreign key eg owner may may blank the car creationdate i would like order cars date car owner date birth owner must taken instead creationdate car is possible,2 abstract base classes abstract base classes useful want put common information number models you write base class put abstracttrue meta class this model used create database table instead used base class models fields added child class,i would like create modelsmodel class became part database interface models i want avoid repeating code something like class interfacemodelsmodel modelsintegerfield b modelstextfield class foointerface c modelsintegerfield class barinterface modelscharfieldmaxlength so database foo abc collumns bar abd table interface,3 not really all take advantage python relational operator chaining raddress value raddress rsize you could also define contains rangeclass allow use find instead class rangeclassobject def containsself val return selfaddress val selfaddress selfsize value r,i list many python objects like class rangeclassobject def initselfaddresssize selfaddressaddress selfsizesize attributes methods then i list rangelist rangeclass objects i need find within range given value i use code like r ragelist ifvalueraddress valueraddressrsize return r return none but i think faster way ranges arbitrary size assume overlap thank,1 specifying cvthreshotsu causes threshold value ignored from documentation also special value threshotsu may combined one values in case function determines optimal threshold value using otsu’s algorithm uses instead specified thresh the function returns computed threshold value currently otsu’s method implemented bit images this code reads frames camera performs binary threshold value include opencvcorecorehpp include opencvimgprocimgprochpp include opencvhighguihighguihpp using namespace cv int mainint argc const char argv videocapture cap ifargc capopenstringargv else capopen mat frame namedwindowvideo cap frame ifframedata break cvtcolorframe frame cvbgrgray thresholdframe frame threshbinary imshowvideo frame ifwaitkey break return,how convert grayscale opencv image black white i see similar question already asked i using opencv proposed solution longer seems work i trying convert greyscale image black white anything absolutely black white use mask surfdetect order ignore keypoints found edge black mask area the following python gets almost threshold value sent threshold appear effect if i set result pixels value becoming white everything else becoming black what i wrong import cv cv fn myfilejpg imgray cvimreadfn cvcvloadimagegrayscale imgraymat cvfromarrayimgray imbw cvcreateimagecvgetsizeimgraymat cvipldepthu imbwmat cvgetmatimbw threshold has no effect cvthresholdimgraymat imbwmat threshold cvcvthreshbinary cvcvthreshotsu cvimshow npasarrayimbwmat cvwaitkey,3 the problem results fact iteration file done linebyline whereas iteration string done characterbycharacter you want stringio cstringio python iostringio python thanks john machin pointing string treated filelike object python mystring abnbcn import cstringio csvio cstringiostringiomystring mycsv csvreadercsvio python mystring abnbcn import io csvio iostringiomystring newline mycsv csvreadercsvio both correctly preserve newlines inside quoted fields row mycsv printrow bnb c,i trying download csv content morningstar parse contents if i inject http content directly python csv parser result formatted correctly yet i save http content file tmptmpcsv import file python csv parser result correct in words def findownloadcodereport h httplibhttp cache url httpfinancialsmorningstarcomajaxreportprocesscsvhtmlt code ampregionausampcultureenusampreporttype report ampperiodampdatatypeaamporderascampcolumnyearamproundingampviewrawampproductcodeusaampdenominatorviewrawampnumber headers data hrequesturl return data balancesheet csvreaderfindownload fge row balancesheet print row return f r g e g r u etc instead forge group limited fge income statement,3 you convert hours variable number since rawinput gives string hours intrawinputhow many hours worked today the reason failing late defined string int multiplies string int argument so type prompt get hours minutes repeated times percentage repeated times so tries string number finally fails,i new python learning basics i would like know i getting error the code hours rawinput how many hours worked today minutes hours percentage minutes print today worked percentage,3 hours read string first convert integer hours intrawinput note hours works concatenates hours times but certainly want convert int first opportunity,i new python learning basics i would like know i getting error the code hours rawinput how many hours worked today minutes hours percentage minutes print today worked percentage,1 the key object boto represents object s used like iterator able something like import boto c botoconnects bucket clookup garnaatpub key bucketlookup scanjpg bytes key write bytes output stream or case example could shutilcopyfileobjkey rsobjectstream,i copying file s cloudfiles i would like avoid writing file disk the pythoncloudfiles library objectstream call looks i need i find equivalent call boto i hoping i would able something like shutilcopyfileobjsobjectstreamrsobjectstream is possible boto i suppose library,3 if many values test could use bisect module find range values quickly if number values test n lenrangelist looping values rangelist suggest would take omn time if use bisection must first sort starting addresses onlogn find value place rangelist omlogn so onlogn mlogn omn bisection wins for large n omlogn miniscule compared omn so inequality would true onlogn omn equivalently c logn constant c thus n large c logn might try something like import bisect class rangeclassobject def initselfaddresssize selfaddressaddress selfsizesize def strself return formatselfaddressselfaddressselfsize def ltselfother return selfaddressotheraddress rangelistsortedrangeclassi startsraddress r rangelist def findrangevalue startidxbisectbisectstartsvalue try rrangeliststartidx except indexerror return none startraddress endraddressrsize startvalueend return rangeliststartidx return none print joinstrr r rangelist value rfindrangevalue r print v r formatvvaluerstrr else print v range formatvvalue,i list many python objects like class rangeclassobject def initselfaddresssize selfaddressaddress selfsizesize attributes methods then i list rangelist rangeclass objects i need find within range given value i use code like r ragelist ifvalueraddress valueraddressrsize return r return none but i think faster way ranges arbitrary size assume overlap thank,2 implement comparison operator range range list sorted use bisect search range value belongs import bisect def findrangevalue index bisectbisectrangelist value index lenrangelist index return rangelistindex,i list many python objects like class rangeclassobject def initselfaddresssize selfaddressaddress selfsizesize attributes methods then i list rangelist rangeclass objects i need find within range given value i use code like r ragelist ifvalueraddress valueraddressrsize return r return none but i think faster way ranges arbitrary size assume overlap thank,1 this happened very simple fix you running code python software all gotta go programs accessories command prompt command prompt window opens type python expy first second third type python hit return get undefined message need follow httpdocspythonorgusingwindowshtml reset python executable path i idea path meant basically directing computer go type python,disclaimer i read thread located valueerror need value unpack none answers explained actually get code run i reading learn python hard way i exercise here code i attempting run idle thing know really called python sys import argv script first second third argv print the script called script print your first variable first print your second variable second print your third variable third when run i get error traceback recent call last file cpythonlpthwexampleslpthwexpy line script first second third argv valueerror need value unpack i tried running program windows command prompt avail i also run program typing python expy first nd rd idle command prompt also got error how i get code run heck i wrong edit john machin i made program exactly like one posted saved py went correct directory file saved ran program using python yourcodepy b c d i received following message python recognized internal external command when i run program typing name works programs besides one i get error saying syntaxerror invalid syntax line print lenargv reprargv edit with new code john machin i copied program word word gedit made py file usual i opened terminal command prompt typed python excpy b c d and received python recognized internal external command operable program batch file then i typed excpy and received r nov msc v bit intel cpythonlpthwexampleslpthwexcpy traceback recent call last file cpythonlpthwexampleslpthwexcpy line module b c argv valueerror need value unpack keep mind i running w bit zed teaching x i using entire book far every example worked right i started example i installed different book i start reading every time i use idle included perhaps possible i somehow inadvertently using trying code thanks bearing,1 the slice values start end characters slice start end points if want slice two elements stop must greater start inputii,i trying slice two characters string using loop instead grabbing two characters grabs one i tried inputii inputii neither seems work how i use variable slicing the full routine def stringtobytelistinput converts data string byte list written ascii input rlist range leninput rlistappendinputii return rlist,3 you use djangocsvimporter package httppypipythonorgpypidjangocsvimporter it works like django model mycsvmodelcsvmodel field integerfield field charfield etc class meta delimiter dbmodel product and csvmodelimportfromfilemy file that automatically create products,i csv data i want import django models using example csv data worm gear hrf ratio input shaft output shaft direction a color dark green worm gear hrf ratio input shaft output shaft direction a color dark green worm gear hrf ratio input shaft output shaft direction a color dark green worm gear hrf ratio input shaft output shaft direction a color dark green worm gear hrf ratio input shaft output shaft direction a color dark green i django models named product in product fields like name description price i want something like productproduct productname worm gear hrf productdescription input shaft output shaft direction a color dark green productprice,2 a nice way remember slice indexing think numbers labeling positions elements so example slice ba would use fruit when thinking way things longer seem counterintuitive easily avoid making offbyone errors code,i trying slice two characters string using loop instead grabbing two characters grabs one i tried inputii inputii neither seems work how i use variable slicing the full routine def stringtobytelistinput converts data string byte list written ascii input rlist range leninput rlistappendinputii return rlist,2 put comma end dictionary things start working can anyone explain going the comma makes tuple without single value brackets x brackets around dict x tuple x tuple brackets often appears brackets notation tuples appear together often that syntactic reasons often need brackets writing tuple when write links dictionary tuple python loops keys link string try index another string resulting exception,im curious happens im using mako templates iterate tuple contains number number dictionaries turn contain link information links path requestrouteurl home text home path httpwwwmicrosoftcom text microsoft send view everything works expected links displayed if remove second link however links path requestrouteurl home text home get exception typeerror string indices must integers str put comma end dictionary things start working can anyone explain going edit mako template snippet nav link links hreflink path link text endfor nav,3 instead trying exercise extra control backend create figures keep references shown highestrated answer first question the problem trying manipulate backend asking backend intended hand figures back intact looked normally backend job see matplotlib figures disappearing show savefig,in earlier question i learned behavior show dependent backend use matplotlib at time i looking way keep show deleting drawing elements figure concluding switching qtagg tkagg drawing elements would preserved even figures closed i would like increase superpowers learning possible configure qtagg backend behave desired,1 i think getpixel exactly need — going lots lookups need speed loop image creating dictionary coordinates color found make look like of course really counts need building histogram store integer dictionary entry instead whole list points if histogram method broke results specific color — looks like returns channel separately without regard combinations various color components appear together,i want create program loads rgb values pixel image saves kind listdictionarytuple i type value tells much pixels image value so far i read whole pil documentation trying find method could fit needs i tried several approaches example getpixel load function difficult save evaluate information pixel,1 load way go it works really efficiently allows get many pixels quickly widthheightimagesize pximageload col rangeheight x rangewidth cpxxy colccolgetc col look like rgbn,i want create program loads rgb values pixel image saves kind listdictionarytuple i type value tells much pixels image value so far i read whole pil documentation trying find method could fit needs i tried several approaches example getpixel load function difficult save evaluate information pixel,1 most web sites days use http authentication so returned fail log instead normal successful response returned text inside web page says log instead sites use cookies this means browser actually know sites logged finally provide successful password yahoo either changes cookie stored browser maybe even keeps cookie changes database record end associated cookie so http status codes generally useless process logging instead scrape text success page comes back see congratulates logging repeats form alternately might check url page get back see whether login form whether instead destination wanted visit,i thinking i access password protected site using python mechanism i would get unauthorized error needs authentication data so inside script i tried access yahoo mail box apparently needs username password i thought i would get i code yahoomail httpmailcnyahoocom br mechanizebrowser r bropenyahoomail print rinfo i got ok apparently brselectformnr select login form r brsubmit submit form without providing username password print rinfo i get question why i get without providing authinfo if mail box website give,3 use celery task queue djangoceleryemail django email backend dispatches email sending celery task,imagine situation user performs action website admins notified imagine admins notify by using normal methods sending emails django user wait emails sent able proceed how i send emails separate process user wait is possible,3 first want convert image rgb mode always get r g b tuples pixels even grayscalemonochrome images image imageconvertrgb then iterate getdata build histogram colors color imagegetdata colorscolor colorsgetcolor then use get retreive number pixels given color print colorsget no white pixels,i want create program loads rgb values pixel image saves kind listdictionarytuple i type value tells much pixels image value so far i read whole pil documentation trying find method could fit needs i tried several approaches example getpixel load function difficult save evaluate information pixel,3 on python x use repr see visually two strings print basically calls str see unprintable characters hard see differences whitespace so print reprcomputertargetnametostring print reprapprvgrpname find equivalent see john manchin comment use python x repr escape unicode characters,i trying compare two strings searching wsus groups update however comparison failing even though appear visually type since ironpython i debugger available komodo anyone know one ip anyway someone spot i wrong search matching patch group approve def wsusapproveapprvgrpname clraddreference microsoftupdateservicesadministration import microsoftupdateservicesadministration wsus microsoftupdateservicesadministrationadminproxygetupdateserver wsus false parentgroupcollection wsusgetcomputertargetgroups computertarget parentgroupcollection computertargetnametostring servers parent computertarget childgroupcollection parentgetchildtargetgroups computertarget childgroupcollection print typecomputertargetnametostring print typeapprvgrpname apprvgrpname computertargetnametostring print success computertargetnametostring else print computertargetnametostring print b apprvgrpname output equal type str type str tuesday b tuesday,1 see templetor docs expression enclosed explicit grouping so case img srcsfilenamepng,in webpy template indexhtml i wrote def withs img srcsfilenamepng sfilename value picuture i want print img srcpicturepng i tell webpy templating system use sfilenamepng use sfilename add png,3 the input name searchkey form a form comes form tag honestly searchbox appears part form simulate setting text input pressing,i need simulate process inputting item name clicking search button httpccclubcmbchinacomccclubnew i inspect directly html search form described name searchkey span classsearchinput input typetext namesearchkey idsearchkey maxlength span script import mechanize import cookielib browser br mechanizebrowser cookie jar cj cookieliblwpcookiejar brsetcookiejarcj browser options brsethandleequivtrue brsethandlegziptrue brsethandleredirecttrue brsethandlereferertrue brsethandlerobotsfalse follows refresh hangs refresh brsethandlerefreshmechanizehttphttprefreshprocessor maxtime want debugging messages brsetdebughttptrue brsetdebugredirectstrue brsetdebugresponsestrue braddheaders useragent mozilla x u linux enus rv gecko fedorafc firefox bropenhttpccclubcmbchinacomccclubnew i get brselectform searchkey traceback recent call last file input line module file buildbdistwineggmechanizemechanizepy line selectform raise formnotfounderrorno form matching description formnotfounderror form matching name searchkey brforms empty question mechanize cannot select form exists html possible solution handle thanks,1 a thread may possible solution i use threads intensively application haevy tasks this python file uses following encoding utf threading threading import thread class afegeixthreadthread def init selfusuari parameternone threadinitself selfparameter parameter def runself errors try selfparamenter except exception e n afegeixthread p nstart,imagine situation user performs action website admins notified imagine admins notify by using normal methods sending emails django user wait emails sent able proceed how i send emails separate process user wait is possible,2 from pydevorg page block indent dedent tab shifttab smart indent dedent enter backspace,i using pydev python development i facing issue removing indentation block statement if i add indentation i used press shift arrow key i reach end block statements i want indent press tab keythis used add indent block statements one step the issue i facing remove indent one step block statementfor example i loop block statement loop now i dont want loop want remove indent underlying loop statement block at present i going line press backspace remove indentation is easy way entire statement block,1 how using lxml beatifulsoup,i need simulate process inputting item name clicking search button httpccclubcmbchinacomccclubnew i inspect directly html search form described name searchkey span classsearchinput input typetext namesearchkey idsearchkey maxlength span script import mechanize import cookielib browser br mechanizebrowser cookie jar cj cookieliblwpcookiejar brsetcookiejarcj browser options brsethandleequivtrue brsethandlegziptrue brsethandleredirecttrue brsethandlereferertrue brsethandlerobotsfalse follows refresh hangs refresh brsethandlerefreshmechanizehttphttprefreshprocessor maxtime want debugging messages brsetdebughttptrue brsetdebugredirectstrue brsetdebugresponsestrue braddheaders useragent mozilla x u linux enus rv gecko fedorafc firefox bropenhttpccclubcmbchinacomccclubnew i get brselectform searchkey traceback recent call last file input line module file buildbdistwineggmechanizemechanizepy line selectform raise formnotfounderrorno form matching description formnotfounderror form matching name searchkey brforms empty question mechanize cannot select form exists html possible solution handle thanks,1 the issue self explanatory error specified two parameters call getkeywords implementation one parameter you change getkeywords implementation something like def getkeywordsfilepath mode openfilepath mode f line f yield linesplit then use following line without specific error keywords getkeywords relatedkeywordstxt r,i trying parse tweets data my data shape follows null null samplta hrefhttphelptwittercomindexphppgkbpageampampid relnofollowampgttxtampltaampgts thonda recalled k accordstraffic around gonna lightwint ajc nadrienne connern ud ud teastern time us ampamp canadat lgal null null samplta hrefhttpalexkingorgprojectswordpress relnofollowampgttwitter toolsampltaampgts tnew blog post honda recalls k cars airbag risk httpbitlywsmat madcitywi nmadcityn ud ud tcentral time us ampamp canadat lmadison wil i want get total numbers tweets numbers keyword related tweets i prepared keywords text file in addition i wanna get tweet text contents total number tweets contain mention retweetrt url i wanna save every url file so i coded like import time import os totaltweetcount relatedtweetcount rtcount mentioncount urls def getkeywordsfilepath openfilepath f line f yield linesplit line open nasminsutxt tweet linestrip totaltweetcount open relatedtweetstxt savefile keywords getkeywords relatedkeywordstxt r keywords line text linesplit split http text try url textsplit http split url http url url urls urlsurl urlsurlappend text savefile open urlsinrelatedtweetstxt print savefile urls except pass text mentioncount rt text rtcount relatedtweetcount print savefile text savefile open inforelatedtweetstxt w print savefile strtotaltweetcount srtrelatedtweetcount strmentioncount strrtcount savefileclose savefileclose savefileclose the keyword set likes happy hello together i think code many problem first error follws traceback recent call last file healthrelatedtweetspy line module keywords getkeywords publichealthrelatedwordstxt r typeerror getkeywords takes exactly argument given please help,2 i followed instructions the displayed page not encoded utf decoding using utf fails according experimental character set detector i muck occasionally encoded latinbased encoding one iso cp iso language appears es spanish fr french according looking spanish firefox view view encoding says iso so need experiment tools display saved files correctly if find one need transcode files utf ie datadecode iso encode utf find tool displays utf correctly shouldn hard firefox nut encoding display correctly encoding i thrown update request intuition in rd block code include input output the input code produce unicode objects ok however output code use str function assuming still unicode objects applying str would raise exception system default encoding ascii silently mangle data utf please publish contents result import sys print sysgetdefaultencoding see output file instead expected ã³ iglesia catã³lica ãƒâ³ actual bytes file use print reprthe data instead expected ã³ solved you say comment see iglesia cat√ã‰â¬â‰¥lica note four characters displayed instead one expected this symptomatic encoding utf twice the next puzzle displaying characters two mapped iso cp i tried old dos codepages cp cp still used windows command prompt window fit koir going fit either needs latinbased character set hmm macroman tada you sent doublyencoded guff stdout mac terminal see demonstration unicodedata import name oacute uxf print nameoacute latin small letter o with acute guff oacuteencode utf decode latin encode utf guff xcxxcxb c guffdecode macroman print namec square root latin capital letter e with acute not sign greaterthan or equal to inspecting saved file i saved web page file plus directory containin jpg css file etc using firefox save page try saved page publish results data open ghtm rb read uc datadecode utf traceback recent call last file stdin line module file cpythonlibencodingsutfpy line decode return codecsutfdecodeinput errors true unicodedecodeerror utf codec decode byte xb position invalid start byte pos datafindiglesia cat datapospos iglesia catxflicaa looks like one iso cousins note carefully if file encoded utf reading utf codec produce unicode if mangle data somehow parsing write parsed unicode utf codec not doubly encoded you need look carefully code instances str remember typo unicode encode decode utf utf etc do call rdparty library parsing what see print reprkey reprfieldkey writing output file this becoming tedious consider putting code saved page web somewhere look instead guessing html i realised guy blown inodes trying write many files folder vfat file system something like so manual save please publish code used save files,i working program reads downloaded webpage stored something html parses accordingly i trouble getting encoding decoding correct program it understanding webpages encoded iso i checked response page charset i given print rinfo contenttype texthtml charsetiso connection close cachecontrol nocache date sun feb gmt server apache red hat linux xaccelcachecontrol nocache however meta tags page declares utf encoding set meta httpequivcontenttype contenttexthtml charsetutf so python i tried number approaches read pages parse write utf including reading file normally writing normally open resultshtml r f page fread open parsedtxt w f key fieldd fwritekey fielddkey n i tried explicitly telling file encoding use read amp write process codecsopen resultshtml r utf f page fread codecsopen parsedtxt w utf f key fieldd fwritekey fielddkey n explicitly telling file read iso write utf codecsopen resultshtml r iso f page fread codecsopen parsedtxt w utf f key fieldd fwritekey fielddkey n as well permutations ideas including writing utf encoding string separately added dictionary erroneous ideas i sure best approach it seems i best luck using any encoding least result some text editors viewing results correctly emacs textwrangler i read couple posts regarding topic still seem make heads tails going thanks,1 i gonna guess problem string create large exist memory for something big write piece piece disk you could use pickle json xml something handle correctly,i looking around net far i found pickle explanation i wrong i trying write large data structure nested dictionarylist file using code i discovered problem might passed string large f open pathtofile w try fwritestrdatastructure except try fwrite abc except print even smaller strings abc not print file else print smaller strings abc did print file datastructure dictionary great deal clique information case around floating point values the whole reason i dumping everything single file instead saving subfiles i want exec single file load rather manually load dozen subsets file before i start saving clique neuron several different incoming clique files neuron looking indexed files i wondering file size actually problem problem must something else thanks,2 reasoning basis inbetween positions works lefttoright iteration li print forward slicing li li prints forward slicing li pos pos but work righttoleft iteration li print li print reverse slicing li li prints reverse slicing li we must think li element li far uncomprised element li say element li far li included that makes dangerous reverse slicing end li print li prints print li none prints print li prints li print li prints in case difficulty think like manner prevent errors write print listreversedli prints print listreversedli prints print listreversedli prints note way obtain reverse slicing far first element included print li stands print li none,i trying slice two characters string using loop instead grabbing two characters grabs one i tried inputii inputii neither seems work how i use variable slicing the full routine def stringtobytelistinput converts data string byte list written ascii input rlist range leninput rlistappendinputii return rlist,1 several errors package mentioned first one twill package handle google redirects correctly adding newurl newurlstrip twillotherpackagesmechanizedisthttppy newurl rfccleanurlnewurl latin fixes correct language set adsense english several problems orignal adsensescraper usrbinenv python scrapes google adsense data python using twill current canonical location module httpgithubcometrepumadsensescrapertreemaster usage adsensescraper import getadsense gettimeperiod b getadsense youradsenselogin youradsensepassword rows gettimeperiodb yesterday the summary data always first row channel print i earned much yesterday earningss rows requires htmllib twill import sys import pprint import decimal cstringio import stringio xmletree import celementtree try htmllib import htmlparser import twillcommands except importerror print sysstderr adsensescraper dependencies twill httptwillidyllorg htmllib httpcodegooglecomphtmllib try easyinstall twill htmllib raise systemexit version serviceloginboxurl httpswwwgooglecomaccountsserviceloginserviceadsenseamprmhideampfpuiampnuiampalwftrueampltmpladsenseamppassivetrueampcontinuehttpsaffwwwgooglecomfadsensefgaiaauthampfollowuphttpsaffwwwgooglecomfadsensefgaiaauthamphlenus overviewurl httpswwwgooglecomadsensereportoverviewtimeperiod timeperiods today yesterday thismonth lastmonth sincelastpayment def parsedecimals return int decimaldecimal given humanreadable number lightstripped sstripu uac stripped lightstrippedreplace rstrip lstrip try intstripped return lightstripped except valueerror pass try floatstripped return lightstripped except valueerror return decimaldecimalstripped def parsesummarytabledoc parse etree doc summarytable returns channel unicode impressions int clicks int ctr decimaldecimal ecpm decimaldecimal earnings decimaldecimal docfindall table tattribget id summarytable break else raise valueerrorsummary table found res fields impressions clicks ctr ecpm earnings row tfindall tr celltext c rowfindall td tail adsense inserts empty span row period get children find tail element append text cfind cfind getchildren tail cfind getchildrentail celltextappend ss ctext cfindtext strip tailstrip celltext filter lambda x x celltext lencelltext lenfields continue try valuecols mapparsedecimal celltext except decimalinvalidoperation continue resappenddictzipfields valuecols return res def getadsenselogin password returns twill browser instance logged adsense login password the returned browser appropriate cookies set may exact page want data b twillcommandsgetbrowser bgoserviceloginboxurl form bgetallforms try form email login form passwd password except valueerror continue else break else raise valueerrorcould find login form page bbrowserselectformpredicatelambda f f form bsubmit return b def gettimeperiodb period returns parsed summarytable time period period given b result getadsense call period must time period adsense supports today yesterday thismonth lastmonth sincelastpayment bgooverviewurl period the celementtree treebuilder work reliably enough use directly parse dump celementtree doc celementtreefromstringhtmlparserparsebgethtmltoxml return parsesummarytabledoc def main try login password sysargv except valueerror raise systemexitusage login password sysargv twillsetoutputstringio twillcommandsresetbrowser b getadsenselogin password data period timeperiods dataperiod gettimeperiodb period pprintpprintdata twillsetoutputnone return data name main data main,i need python script gets google adsense earnings i found adsense scraper httppypipythonorgpypiadsensescraper it uses twill htmllib scrape google adsense earnings data when i use i get error message traceback recent call last file adsensescraperpy line module data main file adsensescraperpy line main b getadsenselogin password file adsensescraperpy line getadsense bsubmit file cpythonlibsitepackagestwillpyeggtwillbrowserpy line submit selfjourney open request file cpythonlibsitepackagestwillpyeggtwillbrowserpy line journey r funcargs kwargs file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistmechanizepy line open return selfmechopenurl data file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistmechanizepy line mechopen response useragentbaseopenself request data file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistopenerpy line open response methreq response file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedisthttppy line httpresponse http request response code msg hdrs file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistopenerpy line error result applyselfcallchain args file cpythonliburllibpy line callchain result funcargs file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedisthttppy line httperror return selfparentopennew file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistmechanizepy line open return selfmechopenurl data file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistmechanizepy line mechopen response useragentbaseopenself request data file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistopenerpy line open response methreq response file cpythonlibsitepackagestwillpyeggtwillutilspy line httpresponse refresh msg hdrs file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistopenerpy line error result applyselfcallchain args file cpythonliburllibpy line callchain result funcargs file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedisthttppy line httperror return selfparentopennew file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistmechanizepy line open return selfmechopenurl data file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistmechanizepy line mechopen response useragentbaseopenself request data file cpythonlibsitepackagestwillpyeggtwillotherpackagesmechanizedistopenerpy line open response urlopenself req data file cpythonliburllibpy line open unknownopen req file cpythonliburllibpy line callchain result funcargs file cpythonliburllibpy line unknownopen raise urlerror unknown url type type urlliburlerror urlopen error unknown url type http so important thing urlliburlerror urlopen error unknown url type http can somebody tell error is even better way get data via python thanks,1 oauth installed applications besides probably want include actual consumerkey consumersecret example code,i started use oauth python django i need google apis i working localhost i register domain urlcallback i read google oauth could used anonymous domain can find i edit i view def authenticationrequest consumerkey xxxxx consumersecret xxxxx scopes httpsdocsgooglecomfeeds client gdatadocsclientdocsclientsource apiapp oauthcallbackurl httpsgetaccesstoken requestmetaget httphost requesttoken clientgetoauthtoken scopes oauthcallbackurl consumerkey consumersecretconsumersecret domain return httpresponseredirect requesttokengenerateauthorizationurlgoogleappsdomaindomain and error sorry reached login page domain using google apps please check web address try registered via httpscodegooglecomapisconsole edit consumerkey xxxxxxxxxxxxxxxxxxxxxxxxxxx consumersecret xxxxxxxxxxxxxxxxxxxxxxxxx scopes httpsdocsgooglecomfeeds domain localhost def authenticationrequest client gdatadocsclientdocsclientsource apiapp oauthcallbackurl httpsgetaccesstoken domain requesttoken clientgetoauthtokenscopes oauthcallbackurl consumerkey consumersecretconsumersecret return httpresponseredirect requesttokengenerateauthorizationurl def verifyrequest client gdatadocsclientdocsclientsource apiapp f open homeisshidrsa rsakey fread fclose oauthcallbackurl httpsgetaccesstoken domain requesttoken clientgetoauthtokenscopes oauthcallbackurl consumerkey rsaprivatekeyrsakey return httpresponseredirect requesttokengenerateauthorizationurlgoogleappsdomaindomain the error unable obtain oauth request token consumer cert xxxxxxxxxxxxxxxappsgoogleusercontentcom,1 assuming configured celeryresultbackend use redis see monitor application using variety methods i believe celeryctl suffice,how i get dataall i really need state task celery backend i using redis,1 joinf f f cpos example cpos print joinf f f cpos output,this small piece code i writing chemistry ab initio program i issues making cpos list number exactly digits decimal place i tried several methods decimal function far i luck position definition take matrix give numpy installed server class position def initself data selfdata data def reprself return reprselfdata def addself data start empty list j rangelenselfdata dataappendselfdataj otherdataj return positiondata deltaa set number steps numx numy numz carbon startpos l toposgetcwd lgeom rangenumx j rangenumy h rangenumz li j h shiftlistl shiftdist kdeltaa k shift cpospositioncarbonpositionshiftdistpositionstartpos ltempl c strcposstrip replace any suggestions eg the output needs c the number never surpass,1 there character limit filters regardless whether using get post anything longer result error the way around length limit use andor boolean logic here full explanation google rules filter expressions,when using google analytics data api python gdata library assembling get request per instructions documentation httpcodegooglecomapisanalyticsdocsgdatagdatareferencedatafeedhtml we running problems however as requests get longer occasionally getting error uri too large lot filters is way use post request gdata api otherwise get around edit just tried using post request get target feed readonly is way around restriction,1 try code without arguments return httpresponseredirectrequesttokengenerateauthorizationurl,i started use oauth python django i need google apis i working localhost i register domain urlcallback i read google oauth could used anonymous domain can find i edit i view def authenticationrequest consumerkey xxxxx consumersecret xxxxx scopes httpsdocsgooglecomfeeds client gdatadocsclientdocsclientsource apiapp oauthcallbackurl httpsgetaccesstoken requestmetaget httphost requesttoken clientgetoauthtoken scopes oauthcallbackurl consumerkey consumersecretconsumersecret domain return httpresponseredirect requesttokengenerateauthorizationurlgoogleappsdomaindomain and error sorry reached login page domain using google apps please check web address try registered via httpscodegooglecomapisconsole edit consumerkey xxxxxxxxxxxxxxxxxxxxxxxxxxx consumersecret xxxxxxxxxxxxxxxxxxxxxxxxx scopes httpsdocsgooglecomfeeds domain localhost def authenticationrequest client gdatadocsclientdocsclientsource apiapp oauthcallbackurl httpsgetaccesstoken domain requesttoken clientgetoauthtokenscopes oauthcallbackurl consumerkey consumersecretconsumersecret return httpresponseredirect requesttokengenerateauthorizationurl def verifyrequest client gdatadocsclientdocsclientsource apiapp f open homeisshidrsa rsakey fread fclose oauthcallbackurl httpsgetaccesstoken domain requesttoken clientgetoauthtokenscopes oauthcallbackurl consumerkey rsaprivatekeyrsakey return httpresponseredirect requesttokengenerateauthorizationurlgoogleappsdomaindomain the error unable obtain oauth request token consumer cert xxxxxxxxxxxxxxxappsgoogleusercontentcom,1 or give try httpforgescilaborgindexphppsciscipy,i trying run scilab using pexpect module following code import pexpect cpexpectspawn scilabadvcli nb cexpect when i csendline plot plot shows but i csendline cexpect ans followed cbefore gives following put rn rn rn rnxbhxb rnxblxb how output sanitised obtain say,1 converting list string really good idea how something like def getsubidxx l l lenx leny rangel xiil return,i list numbers l for example search pattern see present row order find sequence tried converting list str tried search pattern reason code isnt working import l research stristrip strip print pattern found missing something,3 l import l research stristrip strip print pattern found strlist return string spaces elements you look instead,i list numbers l for example search pattern see present row order find sequence tried converting list str tried search pattern reason code isnt working import l research stristrip strip print pattern found missing something,1 probably need imdecode function,i fetching images via http val ostream new bytearrayoutputstream imageiowriteimageurl imagetype ostream val istream new bytearrayinputstreamostreamtobytearray actually scala code using java libs scala specific magic then i pushing istream database case gridfs part mongodb and i need use image bytearray opencv w python bindings db connectionmyservermyportdb fs gridfsdb bytearray fsgetidread given i create mat use opencv functions,1 diff future today print diffdays diff timedelta object,i date what best way calculate using python much days left today till date datetime import today datetoday future date,3 subtract datetime import today datetoday future date strfuture today days future todaydays,i date what best way calculate using python much days left today till date datetime import today datetoday future date,1 note answer old longer valid after reading tom willis comment question also so question accepted answer i noticed webappwebapp looks promising there level commitment google it necessary create maintain versions existing sdk handlers there libraries created app engine mind based webapp would need port adapter work frameworks it used outside appengine unit testing easy setup documented,please note question answers old i want use existing python framework develop application google appengine it quick easy start support test driven development practices easy way can recommend stack what django additional information there several django ports stackoverflow questions already old there several djangoappengine solutions i know one currently leading this outdated see accepted answer also answers but also frameworks interesting django what also sounds good condition possibility run app framework appengine maybe later run self hosted nosql version framework maybe could django maybe somehting else,1 there way get property c code behind function function,i trying use inspect module however seems i use builtin native class else i misunderstood i using python tried python this working import inspect class c def initselfab selfsum b inspectgetargspeccinit argspecargs self b varargsnone keywordsnone defaults this working import inspect import ast inspectgetargspecastifinit traceback recent call last file stdin line module file systemlibraryframeworkspythonframeworkversionslibpythoninspectpy line getargspec raise typeerror r python function formatfunc typeerror slot wrapper init astast objects python function i wondering another technique get parameters automatically in case i think alternative would parse python grammar asdl file explain init ast nodes using code i saw pypy project source i wondering another way,3 you learn bytes vs characters python and use byte strings like b data post website,i written basic python function retrieve web page data i getting error message import urllibparse import urllibrequest def fetchweb url parparpar values sstorlsveeng data urllibparseurlencodevalues req urllibrequestrequesturldata response urllibrequesturlopenreq page responseread url httpwwwwordse fetchweburlstor when executing program i getting following error message typeerror post data bytes iterable bytes it cannot str any ideas misstake,1 someone appears opened python issue suggest follow along,is possible get lines continuation line traceback example usrbinenv python def functionwithlongnamefoo bar raise exception problem functionwithlongname veryimportantvalue meaninglessvalue output testpy traceback recent call last file testpy line module meaninglessvalue file testpy line functionwithlongname raise exception problem exception problem note prints last line continuation line i would like lines continuation line something like testpy traceback recent call last file testpy line module functionwithlongname veryimportantvalue meaninglessvalue file testpy line functionwithlongname raise exception problem exception problem is possible i looked traceback module values returns already truncated example usrbinenv python import traceback def functionwithlongnamefoo bar print tracebackextractstack functionwithlongname veryimportantvalue meaninglessvalue output testpy testpy module meaninglessvalue testpy functionwithlongname print tracebackextractstack,1 result the question mark makes preceding character optional,hi a rather simple question application webappwsgiapplication result result result result the difference trailing can i merge two url mapping one,1 the imp module help cleanly load python code chunks arbitrary files usrbinenv python equation equationonepy def eqnarg return arg usrbinenv python code import imp path equationonepy eqmod imploadsourceequation path openpath printoh nice stuff eqmod direqmod in custom function definition create file selector dialog get selected file path load code using imp return result function inside imported module,i python script signalgenpy plays audio using equations i would like able hard code file equation stored eqtxt choose file import equation the problems i how i hard code file path correctly play equation audio i get error traceback recent call last file signalgenpy line needdata v datum selfsiglevel typeerror multiply sequence nonint type float the specific block code i believe causing issue def equationimportfunctionselftf fileobjopenhomerateqtxtr eqdata fileobjread read whole file fileobjclose return mathtanmathpift return eqdata i line code eqtxt file mathtanmathpift how i add file open dialog box able choose file import equation ps i using ubuntu linux equations several pages long reason i would like import python text files here entire code want look i using seen pastebin includes line numbers httppastebincomhzgjhaw usrbinenv python coding utf copyright c paul lutus this program free software redistribute andor modify terms gnu general public license published free software foundation either version license option later version this program distributed hope useful without any warranty without even implied warranty merchantability fitness for a particular purpose see gnu general public license details you received copy gnu general public license along program write free software foundation inc temple place suite boston ma usa version date version import sys os import gobject gobjectthreadsinit import gst import gtk gtkgdkthreadsinit import time import struct import math import random import signal import webbrowser class icon icon c none c ae c c ac c c a c a amp c ccb c a c dba c aca c c fc c aaa c fda c bbb c deedd ampampampampampampamp ampampamp amp amp amp amp amp ampampampampamp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp ampampampamp amp ampampamp amp amp ampamp amp amp amp ampampamp ampampamp temporary hack class widgetfinder def localizewidgetsselfparentxmlfile unbelievable hack made necessary someone unwilling fix yearold bug openxmlfile f name refindall id fread research k name obj parentbuildergetobjectname setattrparentnameobj class configmanager def initselfpathdic selfpath path selfdic dic def readconfigself ospathexistsselfpath openselfpath f record freadlines se research ss recordstrip ifse keyvalue segroups key selfdic widget selfdickey typ typewidget iftyp list widget value eliftyp gtkentry widgetsettextvalue eliftyp gtkhscale widgetsetvaluefloatvalue eliftyp gtkwindow wh valuesplit widgetresizeintwinth eliftyp gtkcheckbutton typ gtkradiobutton typ gtktogglebutton widgetsetactivevalue true eliftyp gtkcombobox ifvalue widgetdatalist widgetdatalistindexvalue widgetsetactivei else print error reading cannot identify key type keytypewidget def writeconfigself openselfpath w f keywidget sortedselfdiciteritems typ typewidget iftyp list value widget eliftyp gtkentry value widgetgettext eliftyp gtkhscale value strwidgetgetvalue eliftyp gtkwindow wh widgetgetallocation value dd wh eliftyp gtkcheckbutton typ gtkradiobutton typ gtktogglebutton value false true widgetgetactive eliftyp gtkcombobox value widgetgetactivetext else print error writing cannot identify key type keytypewidget value error fwrites sn keyvalue def presetcomboboxselfboxv ifv boxdatalist boxdatalistindexv boxsetactivei else boxsetactive def loadcomboboxselfobjdata iflenobjgetcells create text cell renderer cell gtkcellrenderertext objpackstartcell objaddattribute cell text objgetmodelclear data objappendtextsstrip setattrobj datalist data class textentrycontroller def initselfparentwidget selfpar parent selfwidget widget widgetconnect scrollevent selfscrollevent widgetsettooltiptext enter number orn mouse wheel increasedecreasen shiftctrlalt faster change def scrolleventselfwevt q evtdirection gtkgdkscrollup magnify change shiftctrlalt pressed ifselfparmodkeyval amp q selfwidgetgettext v floats v q v maxv selfparformatnumv selfwidgetsettexts class signalgen mammfm range wsinewtrianglewsquarewsawtoothwequationimport range waveformstrings sine triangle square sawtooth equationimport rrrrrrr range samplerates def initself selfrestart false exit correctly system signals signalsignalsignalsigterm selfclose signalsignalsignalsigint selfclose precompile struct operator selfstructint structstruct selfmaxlevel selfgenfunctions selfsinefunction selftrianglefunction selfsquarefunction selfsawtoothfunction selfequationimportfunction selfmaincolor gtkgdkcolorparse c selfsigcolor gtkgdkcolorparse c selfmodcolor gtkgdkcolorparse c selfnoisecolor gtkgdkcolorparse cc selfpipeline false selfcount selfimod selfrate selfmodkeyval selfsigfreq selfmodfreq selfsiglevel selfmodlevel selfnoiselevel selfenable true selfsigwaveform signalgenwsine selfsigenable true selfsigfunction false selfmodwaveform signalgenwsine selfmodfunction false selfmodmode signalgenmam selfmodenable false selfnoiseenable false selfsamplerate signalgenr selfleftaudio true selfrightaudio true selfprogramname selfclassname selfconfigfile ospathexpanduser selfprogramname selfbuilder gtkbuilder selfxmlfile signalgenguiglade selfbuilderaddfromfileselfxmlfile widgetfinderlocalizewidgetsselfselfxmlfile selfkquitbuttonconnect clicked selfclose selfkhelpbuttonconnect clicked selflaunchhelp selfkmainwindowconnect destroy selfclose selfkmainwindowseticongtkgdkpixbufnewfromxpmdataiconicon selftitle selfprogramname version selfkmainwindowsettitleselftitle selftooltips selfksampleratecombobox change data sampling rate selfkleftcheckbutton enable left channel audio selfkrightcheckbutton enable right channel audio selfksigwaveformcombobox select signal waveform selfkmodwaveformcombobox select modulation waveform selfkmodenablecheckbutton enable modulation selfksigenablecheckbutton enable signal selfknoiseenablecheckbutton enable white noise selfkmodamradiobutton enable amplitude modulation selfkmodfmradiobutton enable frequency modulation selfkquitbutton quit selftitle selfkenablecheckbutton enable output selfkhelpbutton visit web page selftitle kv selftooltipsiteritems ksettooltiptextv selfconfigdata samplerate selfksampleratecombobox leftchannelenabled selfkleftcheckbutton rightchannelenabled selfkrightcheckbutton signalwaveform selfksigwaveformcombobox signalfrequency selfksigfreqentry signallevel selfksiglevelentry signalenabled selfksigenablecheckbutton modulationwaveform selfkmodwaveformcombobox modulationfrequency selfkmodfreqentry modulationlevel selfkmodlevelentry modulationenabled selfkmodenablecheckbutton amplitudemodulation selfkmodamradiobutton frequencymodulation selfkmodfmradiobutton noiseenabled selfknoiseenablecheckbutton noiselevel selfknoiselevelentry outputenabled selfkenablecheckbutton selfcm configmanagerselfconfigfileselfconfigdata selfcmloadcomboboxselfksigwaveformcomboboxselfwaveformstrings selfksigwaveformcomboboxsetactiveselfsigwaveform selfcmloadcomboboxselfkmodwaveformcomboboxselfwaveformstrings selfkmodwaveformcomboboxsetactiveselfmodwaveform selfcmloadcomboboxselfksampleratecomboboxselfsamplerates selfksampleratecomboboxsetactiveselfsamplerate selfksigfreqentrysettextselfformatnumselfsigfreq selfksiglevelentrysettextselfformatnumselfsiglevel selfkmodfreqentrysettextselfformatnumselfmodfreq selfkmodlevelentrysettextselfformatnumselfmodlevel selfknoiselevelentrysettextselfformatnumselfnoiselevel selfkmainviewportbordermodifybggtkstatenormalselfmaincolor selfksigviewportbordermodifybggtkstatenormalselfsigcolor selfkmodviewportbordermodifybggtkstatenormalselfmodcolor selfknoiseviewportbordermodifybggtkstatenormalselfnoisecolor selfsigfreqcont textentrycontrollerselfselfksigfreqentry selfsiglevelcont textentrycontrollerselfselfksiglevelentry selfmodfreqcont textentrycontrollerselfselfkmodfreqentry selfmodlevelcont textentrycontrollerselfselfkmodlevelentry selfnoiselevelcont textentrycontrollerselfselfknoiselevelentry selfkmainwindowconnect keypressevent selfkeyevent selfkmainwindowconnect keyreleaseevent selfkeyevent selfkenablecheckbuttonconnect toggled selfupdatevalues selfksigfreqentryconnect changed selfupdateentryvalues selfksiglevelentryconnect changed selfupdateentryvalues selfksigenablecheckbuttonconnect toggled selfupdatecheckbuttonvalues selfkmodfreqentryconnect changed selfupdateentryvalues selfkmodlevelentryconnect changed selfupdateentryvalues selfknoiselevelentryconnect changed selfupdateentryvalues selfksampleratecomboboxconnect changed selfupdatevalues selfksigwaveformcomboboxconnect changed selfupdatevalues selfkmodwaveformcomboboxconnect changed selfupdatevalues selfkleftcheckbuttonconnect toggled selfupdatecheckbuttonvalues selfkrightcheckbuttonconnect toggled selfupdatecheckbuttonvalues selfkmodenablecheckbuttonconnect toggled selfupdatecheckbuttonvalues selfknoiseenablecheckbuttonconnect toggled selfupdatecheckbuttonvalues selfkmodamradiobuttonconnect toggled selfupdatecheckbuttonvalues selfcmreadconfig selfupdateentryvalues selfupdatecheckbuttonvalues selfupdatevalues def formatnumselfv return f v def getwidgettextselfw typ typew iftyp gtkcombobox return wgetactivetext eliftyp gtkentry return wgettext def getwidgetnumselfw try return floatselfgetwidgettextw except return def restarttestselfwpv nv wgetactive selfrestart nv pv return nv def updateentryvaluesselfargs selfsigfreq selfgetwidgetnumselfksigfreqentry selfsiglevel selfgetwidgetnumselfksiglevelentry selfmodfreq selfgetwidgetnumselfkmodfreqentry selfmodlevel selfgetwidgetnumselfkmodlevelentry selfnoiselevel selfgetwidgetnumselfknoiselevelentry def updatecheckbuttonvaluesselfargs selfleftaudio selfkleftcheckbuttongetactive selfrightaudio selfkrightcheckbuttongetactive selfmodenable selfkmodenablecheckbuttongetactive selfsigenable selfksigenablecheckbuttongetactive selfmodmode signalgenmfmsignalgenmamselfkmodamradiobuttongetactive selfnoiseenable selfknoiseenablecheckbuttongetactive def updatevaluesselfargs selfrestart selfsigfunction selfsamplerate selfrestarttestselfksampleratecombobox selfsamplerate selfenable selfrestarttestselfkenablecheckbuttonselfenable selfmodwaveform selfkmodwaveformcomboboxgetactive selfmodfunction selfgenfunctionsselfmodwaveform selfsigwaveform selfksigwaveformcomboboxgetactive selfsigfunction selfgenfunctionsselfsigwaveform selfksampleratecomboboxsetsensitivenot selfenable ifselfrestart selfinitaudio def makeandchainselfname target gstelementfactorymakename selfchainappendtarget return target def unlinkgstself ifselfpipeline selfpipelinesetstategststatenull selfpipelineremovemanyselfchain gstelementunlinkmanyselfchain item selfchain item false selfpipeline false timesleep def initaudioself selfunlinkgst ifselfenable selfchain selfpipeline gstpipelinemypipeline selfsource selfmakeandchainappsrc rs signalgensampleratesselfsamplerate selfrate floatrs selfinterval selfrate caps gstcaps audioxrawint endiannessint channelsint widthint depthint signedbooleantrue rateints rs selfsourcesetproperty caps caps selfsink selfmakeandchainautoaudiosink selfpipelineaddselfchain gstelementlinkmanyselfchain selfsourceconnect needdata selfneeddata selfpipelinesetstategststateplaying def keyeventselfwevt cn gtkgdkkeyvalnameevtkeyval ifresearch shift cn none mod elifresearch control cn none mod elifresearch altmeta cn none mod else return ifevttype gtkgdkkeypress selfmodkeyval mod else selfmodkeyval amp mod def sinefunctionselftf return mathsinmathpift def trianglefunctionselftf q mathfmodtf q qqq return qqq def squarefunctionselftf iff return q mathfmodtf return q def sawtoothfunctionselftf return mathfmodtf def equationimportfunctionselftf fileobjopenhomerateqtxtr eqdata fileobjread read whole file fileobjclose return mathtanmathpift return eqdata def needdataselfsrclength bytes sending two channels divide requested length ld length tt rangeld selfcount tt selfinterval ifnot selfmodenable datum selfsigfunctiontselfsigfreq else mod selfmodfunctiontselfmodfreq am mode ifselfmodmode signalgenmam datum selfsigfunctiontselfsigfreq mod selfmodlevel fm mode else selfimod mod selfmodlevel selfinterval datum selfsigfunctiontselfimodselfsigfreq v ifselfsigenable v datum selfsiglevel ifselfnoiseenable noise randomrandom v noise selfnoiselevel v selfmaxlevel v maxselfmaxlevelv v minselfmaxlevelv left vselfleftaudio right vselfrightaudio bytes selfstructintpackleft bytes selfstructintpackright selfcount ld srcemit pushbuffer gstbufferbytes def launchhelpselfargs webbrowseropenhttparachnoidcompythonsignalgenprogramhtml def closeselfargs selfunlinkgst selfcmwriteconfig gtkmainquit appsignalgen gtkmain,1 i would suggest keeping simple create database table store events insert table appropriate implement simple ajax polling technique hit server every x seconds client side i concerns solutions considering using pushnotification approach using nosql data store it whole lot complicated traditional pullnotification system using tools built django framework except rare exceptions overkill unless specifically require strict realtime solution keep simple use tools already exist framework people objections based database network performance i say premature optimization root evil build model contains recent activity data specific application whenever application something log new activity insert table your view would simply like view pulling top x rows recentactivity table optionally based query parameters whatever then client side simple ajax poller hitting view every x seconds there shortage complicated plugins technologies use writing complicated either function simplepoll getyoururl queryparameters functiondata stuff data replacing div updating json whatever settimeoutsimplepoll delay my opinion performance issues really issues site successful enough issue a traditional relational database scale fairly well start reaching level success like twitter google etc most us level,i need develop realtime recent activity feed django ajax longpolling i wondering best strategy serverside pseudocode def recentactivitypostsave notifyview view newactivity sleep return httpresponsenewactivity the first thing comes mind querying db every second not feasible other options using cache notification service using specialized tool like celery i rather seems like overkill what best way go,3 autotask ancient api iis deal microsoft crapstack escape xml push cdata here worked soap body within insquery tags inssxml cdataqueryxml entitycontactentity query fieldphoneexpression op equals phoneexpressionfield query queryxml inssxml,so i trying api call via xml soap post error i getting object reference set instance object site httpswebservicesautotasknetatservicesatwsasmx data xml version encodingutf soapenvelope xmlnssoaphttpschemasxmlsoaporgsoapenvelope xmlnsxsihttpwwwworgxmlschemainstance xmlnsxsdhttpwwwworgxmlschema soapbody queryxml entitycontactentity query fieldfirstnameexpression opequalsgeorgeexpression field query queryxml soapbody soapenvelope headers contenttype applicationsoapxml charsetutf host webservicesautotasknet contenttype textxml charsetutf contentlength lendata soapaction httpautotasknetatwsvquery site httpswebservicesautotasknetatservicesatwsasmx authhandler urllibhttpbasicauthhandler authhandleraddpasswordrealm webservicesautotasknet urisite user user passwd pw opener urllibbuildopenerauthhandler urllibinstallopeneropener page urlliburlopensite printdata req urllibrequestsite data headers response urlliburlopenreq thepage responseread printthepage the auth works i done succesfull calls code thing diffrent data xml soap post i try suds no traceback web server error print xml soap post i sending xml version encodingutf soapenvelope xmlnssoaphttpschemasxmlsoaporgsoapenvelope xmlnsxsihttpwwwworgxmlschemainstance xmlnsxsdhttpwwwworgxmlschema soapbody queryxml entitycontactentity query fieldfirstnameexpression opequalsgeorgeexpression field query queryxml soapbody soapenvelope the response xml version encodingutfsoapenvelope xmlnssoaphttpschemasxmlsoaporgsoapenvelope xmlnsxsihttpwwwworgxmlschemainstance xmlnsxsdhttpwwwworgxmlschemasoapbodyqueryresponse xmlnshttpautotasknetatwsvqueryresultreturncodereturncodeentityresults entityresulttype errorsatwserrormessageobject reference set instance objectmessageatwserroratwserrormessageerror reading query xmlmessageatwserrorerrorsentityreturninforesults queryresultqueryresponsesoapbodysoapenvelope any ideas george,3 a regular expression able achieve i give examples variable could come strict expression to match something like following import match etc timex recompile dd pm nst match timexmatchtext remres variable matchgroups edit code actually work unlike first attempt import match etc timex recompile dd pm nst match timexsearchtext match variable matchgroups,i currently code goes url fetches source code i trying get return variable string so i created changetime refreshsourcefind variable pm nst but find area string word variable something else how would i retrieve constantly changing variable string,1 you setting cc cxx environment suitable wrapper around compiler example colorgcc,i currently using colorama package color messages generated build scripts i also used scolorizer replaces build commands custom colored messages using strfunction scons this sure makes build output less verbose warnings easier spot however i often prefer see full command lines building is mechanism scons capture compiler output giving opportunity inject terminal colors printing,1 if pattern really simple seems typical case regular expressions comes quite handy note new regular expressions may want use introduction like httpwwwregularexpressionsinfo on hand pattern complex may want use html parser like instance beautifulsoup,i currently code goes url fetches source code i trying get return variable string so i created changetime refreshsourcefind variable pm nst but find area string word variable something else how would i retrieve constantly changing variable string,1 fixed breaking query file two using blast instead,i asked question bioinformatics version stackexchange since i think computer problem i thought i try luck when running local blast v big database human proteins i get following error proteinsapplicationerror command blastbinblastpexe query queryfasta db humanproteinsfasta blastoutputxml evalue outfmt returned nonzero exit status blast database error cseqdbatlasmapmmap while mapping file humanproteinsfastapsq bytes allocated caught exception when googling i got source code seqdbatlas httpwwwncbinlmnihgoviebtoolboxcppdoclxrsourcesrcobjtoolsblastseqdbreaderseqdbatlascpp i found exptlength for i memory map file i revert old way malloc chunk core copy data exptfind cannot allocate memory exptnpos expt stringcseqdbatlasmapmmap while mapping file mfname nstruinttostringatlasgetcurrentallocationtotal bytes allocated caught exception expt seqdbthrowexceptioncseqdbexceptionefileerr expt my knowledge c limited i get enough memory pc run blast size database is correct way run blast without getting computer bigger memory if correct error i getting thanks advance niek,1 flaskmail documentation says flaskmail requires use lamson library unfortunately dependencies work windows you install flaskmail lamson libraries dependencies option easyinstall n lamson chardet flaskmail source httppackagespythonorgflaskmailwindowsissues,a little new python wonderful world flask i trying install flaskmail httppackagespythonorgflaskmail coming bit wall using virutalenv windows i get flaskmail install time i recieve no module named resource i using pip install ideas,2 i commenting i stared code long enough kinda realized trying easier post answer please refer cj zougloubs answer i expand suggestion use imp module your equation files implement common interface equationpy def eqnargs return sumargs then would load using cj zougloubs suggestion common interface pythonrtpy def equationimportfunctionself args filepath filepath file chooser dialog eqmod imploadsourceequation filepath eqdata eqmodeqnargs return eqdata now function main code takes number arguments asks user pick equation file gets result edit to address comment specifically equationpy import math def eqnargs f args args return mathtanmathpift and main tool would use imploadsource bring wherever needed equation audio could eqmodeqnf,i python script signalgenpy plays audio using equations i would like able hard code file equation stored eqtxt choose file import equation the problems i how i hard code file path correctly play equation audio i get error traceback recent call last file signalgenpy line needdata v datum selfsiglevel typeerror multiply sequence nonint type float the specific block code i believe causing issue def equationimportfunctionselftf fileobjopenhomerateqtxtr eqdata fileobjread read whole file fileobjclose return mathtanmathpift return eqdata i line code eqtxt file mathtanmathpift how i add file open dialog box able choose file import equation ps i using ubuntu linux equations several pages long reason i would like import python text files here entire code want look i using seen pastebin includes line numbers httppastebincomhzgjhaw usrbinenv python coding utf copyright c paul lutus this program free software redistribute andor modify terms gnu general public license published free software foundation either version license option later version this program distributed hope useful without any warranty without even implied warranty merchantability fitness for a particular purpose see gnu general public license details you received copy gnu general public license along program write free software foundation inc temple place suite boston ma usa version date version import sys os import gobject gobjectthreadsinit import gst import gtk gtkgdkthreadsinit import time import struct import math import random import signal import webbrowser class icon icon c none c ae c c ac c c a c a amp c ccb c a c dba c aca c c fc c aaa c fda c bbb c deedd ampampampampampampamp ampampamp amp amp amp amp amp ampampampampamp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp amp ampampampamp amp ampampamp amp amp ampamp amp amp amp ampampamp ampampamp temporary hack class widgetfinder def localizewidgetsselfparentxmlfile unbelievable hack made necessary someone unwilling fix yearold bug openxmlfile f name refindall id fread research k name obj parentbuildergetobjectname setattrparentnameobj class configmanager def initselfpathdic selfpath path selfdic dic def readconfigself ospathexistsselfpath openselfpath f record freadlines se research ss recordstrip ifse keyvalue segroups key selfdic widget selfdickey typ typewidget iftyp list widget value eliftyp gtkentry widgetsettextvalue eliftyp gtkhscale widgetsetvaluefloatvalue eliftyp gtkwindow wh valuesplit widgetresizeintwinth eliftyp gtkcheckbutton typ gtkradiobutton typ gtktogglebutton widgetsetactivevalue true eliftyp gtkcombobox ifvalue widgetdatalist widgetdatalistindexvalue widgetsetactivei else print error reading cannot identify key type keytypewidget def writeconfigself openselfpath w f keywidget sortedselfdiciteritems typ typewidget iftyp list value widget eliftyp gtkentry value widgetgettext eliftyp gtkhscale value strwidgetgetvalue eliftyp gtkwindow wh widgetgetallocation value dd wh eliftyp gtkcheckbutton typ gtkradiobutton typ gtktogglebutton value false true widgetgetactive eliftyp gtkcombobox value widgetgetactivetext else print error writing cannot identify key type keytypewidget value error fwrites sn keyvalue def presetcomboboxselfboxv ifv boxdatalist boxdatalistindexv boxsetactivei else boxsetactive def loadcomboboxselfobjdata iflenobjgetcells create text cell renderer cell gtkcellrenderertext objpackstartcell objaddattribute cell text objgetmodelclear data objappendtextsstrip setattrobj datalist data class textentrycontroller def initselfparentwidget selfpar parent selfwidget widget widgetconnect scrollevent selfscrollevent widgetsettooltiptext enter number orn mouse wheel increasedecreasen shiftctrlalt faster change def scrolleventselfwevt q evtdirection gtkgdkscrollup magnify change shiftctrlalt pressed ifselfparmodkeyval amp q selfwidgetgettext v floats v q v maxv selfparformatnumv selfwidgetsettexts class signalgen mammfm range wsinewtrianglewsquarewsawtoothwequationimport range waveformstrings sine triangle square sawtooth equationimport rrrrrrr range samplerates def initself selfrestart false exit correctly system signals signalsignalsignalsigterm selfclose signalsignalsignalsigint selfclose precompile struct operator selfstructint structstruct selfmaxlevel selfgenfunctions selfsinefunction selftrianglefunction selfsquarefunction selfsawtoothfunction selfequationimportfunction selfmaincolor gtkgdkcolorparse c selfsigcolor gtkgdkcolorparse c selfmodcolor gtkgdkcolorparse c selfnoisecolor gtkgdkcolorparse cc selfpipeline false selfcount selfimod selfrate selfmodkeyval selfsigfreq selfmodfreq selfsiglevel selfmodlevel selfnoiselevel selfenable true selfsigwaveform signalgenwsine selfsigenable true selfsigfunction false selfmodwaveform signalgenwsine selfmodfunction false selfmodmode signalgenmam selfmodenable false selfnoiseenable false selfsamplerate signalgenr selfleftaudio true selfrightaudio true selfprogramname selfclassname selfconfigfile ospathexpanduser selfprogramname selfbuilder gtkbuilder selfxmlfile signalgenguiglade selfbuilderaddfromfileselfxmlfile widgetfinderlocalizewidgetsselfselfxmlfile selfkquitbuttonconnect clicked selfclose selfkhelpbuttonconnect clicked selflaunchhelp selfkmainwindowconnect destroy selfclose selfkmainwindowseticongtkgdkpixbufnewfromxpmdataiconicon selftitle selfprogramname version selfkmainwindowsettitleselftitle selftooltips selfksampleratecombobox change data sampling rate selfkleftcheckbutton enable left channel audio selfkrightcheckbutton enable right channel audio selfksigwaveformcombobox select signal waveform selfkmodwaveformcombobox select modulation waveform selfkmodenablecheckbutton enable modulation selfksigenablecheckbutton enable signal selfknoiseenablecheckbutton enable white noise selfkmodamradiobutton enable amplitude modulation selfkmodfmradiobutton enable frequency modulation selfkquitbutton quit selftitle selfkenablecheckbutton enable output selfkhelpbutton visit web page selftitle kv selftooltipsiteritems ksettooltiptextv selfconfigdata samplerate selfksampleratecombobox leftchannelenabled selfkleftcheckbutton rightchannelenabled selfkrightcheckbutton signalwaveform selfksigwaveformcombobox signalfrequency selfksigfreqentry signallevel selfksiglevelentry signalenabled selfksigenablecheckbutton modulationwaveform selfkmodwaveformcombobox modulationfrequency selfkmodfreqentry modulationlevel selfkmodlevelentry modulationenabled selfkmodenablecheckbutton amplitudemodulation selfkmodamradiobutton frequencymodulation selfkmodfmradiobutton noiseenabled selfknoiseenablecheckbutton noiselevel selfknoiselevelentry outputenabled selfkenablecheckbutton selfcm configmanagerselfconfigfileselfconfigdata selfcmloadcomboboxselfksigwaveformcomboboxselfwaveformstrings selfksigwaveformcomboboxsetactiveselfsigwaveform selfcmloadcomboboxselfkmodwaveformcomboboxselfwaveformstrings selfkmodwaveformcomboboxsetactiveselfmodwaveform selfcmloadcomboboxselfksampleratecomboboxselfsamplerates selfksampleratecomboboxsetactiveselfsamplerate selfksigfreqentrysettextselfformatnumselfsigfreq selfksiglevelentrysettextselfformatnumselfsiglevel selfkmodfreqentrysettextselfformatnumselfmodfreq selfkmodlevelentrysettextselfformatnumselfmodlevel selfknoiselevelentrysettextselfformatnumselfnoiselevel selfkmainviewportbordermodifybggtkstatenormalselfmaincolor selfksigviewportbordermodifybggtkstatenormalselfsigcolor selfkmodviewportbordermodifybggtkstatenormalselfmodcolor selfknoiseviewportbordermodifybggtkstatenormalselfnoisecolor selfsigfreqcont textentrycontrollerselfselfksigfreqentry selfsiglevelcont textentrycontrollerselfselfksiglevelentry selfmodfreqcont textentrycontrollerselfselfkmodfreqentry selfmodlevelcont textentrycontrollerselfselfkmodlevelentry selfnoiselevelcont textentrycontrollerselfselfknoiselevelentry selfkmainwindowconnect keypressevent selfkeyevent selfkmainwindowconnect keyreleaseevent selfkeyevent selfkenablecheckbuttonconnect toggled selfupdatevalues selfksigfreqentryconnect changed selfupdateentryvalues selfksiglevelentryconnect changed selfupdateentryvalues selfksigenablecheckbuttonconnect toggled selfupdatecheckbuttonvalues selfkmodfreqentryconnect changed selfupdateentryvalues selfkmodlevelentryconnect changed selfupdateentryvalues selfknoiselevelentryconnect changed selfupdateentryvalues selfksampleratecomboboxconnect changed selfupdatevalues selfksigwaveformcomboboxconnect changed selfupdatevalues selfkmodwaveformcomboboxconnect changed selfupdatevalues selfkleftcheckbuttonconnect toggled selfupdatecheckbuttonvalues selfkrightcheckbuttonconnect toggled selfupdatecheckbuttonvalues selfkmodenablecheckbuttonconnect toggled selfupdatecheckbuttonvalues selfknoiseenablecheckbuttonconnect toggled selfupdatecheckbuttonvalues selfkmodamradiobuttonconnect toggled selfupdatecheckbuttonvalues selfcmreadconfig selfupdateentryvalues selfupdatecheckbuttonvalues selfupdatevalues def formatnumselfv return f v def getwidgettextselfw typ typew iftyp gtkcombobox return wgetactivetext eliftyp gtkentry return wgettext def getwidgetnumselfw try return floatselfgetwidgettextw except return def restarttestselfwpv nv wgetactive selfrestart nv pv return nv def updateentryvaluesselfargs selfsigfreq selfgetwidgetnumselfksigfreqentry selfsiglevel selfgetwidgetnumselfksiglevelentry selfmodfreq selfgetwidgetnumselfkmodfreqentry selfmodlevel selfgetwidgetnumselfkmodlevelentry selfnoiselevel selfgetwidgetnumselfknoiselevelentry def updatecheckbuttonvaluesselfargs selfleftaudio selfkleftcheckbuttongetactive selfrightaudio selfkrightcheckbuttongetactive selfmodenable selfkmodenablecheckbuttongetactive selfsigenable selfksigenablecheckbuttongetactive selfmodmode signalgenmfmsignalgenmamselfkmodamradiobuttongetactive selfnoiseenable selfknoiseenablecheckbuttongetactive def updatevaluesselfargs selfrestart selfsigfunction selfsamplerate selfrestarttestselfksampleratecombobox selfsamplerate selfenable selfrestarttestselfkenablecheckbuttonselfenable selfmodwaveform selfkmodwaveformcomboboxgetactive selfmodfunction selfgenfunctionsselfmodwaveform selfsigwaveform selfksigwaveformcomboboxgetactive selfsigfunction selfgenfunctionsselfsigwaveform selfksampleratecomboboxsetsensitivenot selfenable ifselfrestart selfinitaudio def makeandchainselfname target gstelementfactorymakename selfchainappendtarget return target def unlinkgstself ifselfpipeline selfpipelinesetstategststatenull selfpipelineremovemanyselfchain gstelementunlinkmanyselfchain item selfchain item false selfpipeline false timesleep def initaudioself selfunlinkgst ifselfenable selfchain selfpipeline gstpipelinemypipeline selfsource selfmakeandchainappsrc rs signalgensampleratesselfsamplerate selfrate floatrs selfinterval selfrate caps gstcaps audioxrawint endiannessint channelsint widthint depthint signedbooleantrue rateints rs selfsourcesetproperty caps caps selfsink selfmakeandchainautoaudiosink selfpipelineaddselfchain gstelementlinkmanyselfchain selfsourceconnect needdata selfneeddata selfpipelinesetstategststateplaying def keyeventselfwevt cn gtkgdkkeyvalnameevtkeyval ifresearch shift cn none mod elifresearch control cn none mod elifresearch altmeta cn none mod else return ifevttype gtkgdkkeypress selfmodkeyval mod else selfmodkeyval amp mod def sinefunctionselftf return mathsinmathpift def trianglefunctionselftf q mathfmodtf q qqq return qqq def squarefunctionselftf iff return q mathfmodtf return q def sawtoothfunctionselftf return mathfmodtf def equationimportfunctionselftf fileobjopenhomerateqtxtr eqdata fileobjread read whole file fileobjclose return mathtanmathpift return eqdata def needdataselfsrclength bytes sending two channels divide requested length ld length tt rangeld selfcount tt selfinterval ifnot selfmodenable datum selfsigfunctiontselfsigfreq else mod selfmodfunctiontselfmodfreq am mode ifselfmodmode signalgenmam datum selfsigfunctiontselfsigfreq mod selfmodlevel fm mode else selfimod mod selfmodlevel selfinterval datum selfsigfunctiontselfimodselfsigfreq v ifselfsigenable v datum selfsiglevel ifselfnoiseenable noise randomrandom v noise selfnoiselevel v selfmaxlevel v maxselfmaxlevelv v minselfmaxlevelv left vselfleftaudio right vselfrightaudio bytes selfstructintpackleft bytes selfstructintpackright selfcount ld srcemit pushbuffer gstbufferbytes def launchhelpselfargs webbrowseropenhttparachnoidcompythonsignalgenprogramhtml def closeselfargs selfunlinkgst selfcmwriteconfig gtkmainquit appsignalgen gtkmain,1 this matter latency speed python always performs memory allocation release data reused memory reused c library so os c library udpip stack impact python i really think use serial port rtos machine use c code preallocated buffers,i infrared cameratracker i communicating via serial port i using pyserial module moment the camera updates position tracked object rate hz in order get position tracked object i execute one pyserialwrite listen incoming reply pyserialreadserialobjinwaiting once replyposition received loop reentered my question reliability speed approach i need position gotten computer rate least hz position sent via udp realtime os is something pyserialpython capable i look alternative cbased approaches thanks luke,1 it looks like problem create msg append files msg send append files files attached send second message twice large first append files bringing total send getting pretty huge and forth when start fresh msg object instead continuing append files old one alternately could try removing attachments already attaching new ones starting might simpler since already code place start new message right headers — needs refactoring little “start new message” function,code import smtplib emailmimemultipart import mimemultipart emailmimebase import mimebase emailmimetext import mimetext emailutils import commaspace formatdate email import encoders import os def sendmailto subject text filesserversmtpgmailcom assert typetolist assert typefileslist fro psaoflamandlivecom msg mimemultipart msg from fro msg to commaspacejointo msg date formatdatelocaltimetrue msg subject subject msgattach mimetexttext username psaoflamandgmailcom password pass the actual mail send smtp smtplibsmtpserver smtpstarttls smtploginusernamepassword file files print part mimebase application octetstream partsetpayload openfilerbread encodersencodebasepart partaddheader contentdisposition attachment filenames ospathbasenamefile msgattachpart smtpsendmailfro msgasstring print sent smtpquit sendmail psaoflamandlivecom hellocheers thousands one megabyte files code sends files time avoid going limit gmail messages but probleme data mimebase stays question way delete data mimebase im sorry indentation wrong,1 url httpabsysabwebpcgixidgaccdct data urlliburlopenurlread data iglesiacatflicaiglesia catxflica datadecode latin u iglesiacatflicaiglesia catxflica datadecode latin encode utf iglesiacatflicaiglesia catxcxblica what get,i working program reads downloaded webpage stored something html parses accordingly i trouble getting encoding decoding correct program it understanding webpages encoded iso i checked response page charset i given print rinfo contenttype texthtml charsetiso connection close cachecontrol nocache date sun feb gmt server apache red hat linux xaccelcachecontrol nocache however meta tags page declares utf encoding set meta httpequivcontenttype contenttexthtml charsetutf so python i tried number approaches read pages parse write utf including reading file normally writing normally open resultshtml r f page fread open parsedtxt w f key fieldd fwritekey fielddkey n i tried explicitly telling file encoding use read amp write process codecsopen resultshtml r utf f page fread codecsopen parsedtxt w utf f key fieldd fwritekey fielddkey n explicitly telling file read iso write utf codecsopen resultshtml r iso f page fread codecsopen parsedtxt w utf f key fieldd fwritekey fielddkey n as well permutations ideas including writing utf encoding string separately added dictionary erroneous ideas i sure best approach it seems i best luck using any encoding least result some text editors viewing results correctly emacs textwrangler i read couple posts regarding topic still seem make heads tails going thanks,1 the problem referring imported import somemodule x somemoduleclassb,i trouble class inheritance python x i hoping get help i class called classa i trying create another class called classb inherits classa here code i written myfile import classa class classbclassa def initself superclassb selfinit when i try create instance classb i get error x classb traceback recent call last file stdin line module nameerror name classb defined can anyone explain problem thanks advance help,2 you need second form unless somehow basicelement class init takes argument class aobject def initself print inside class a init class ba def initself superb selfinit print inside class b init b b inside class a init inside class b init or classes need init arguments class aobject def initself arg print inside class a init arg arg class ba def initself superb selfinitfoo print inside class b init b b inside class a init arg foo inside class b init,a super basicelement self init b super basicelement self init self what difference a b most examples i run across use a i running issue a calling parent init function b why might which used cases,3 if mean syntax regexp work import rematchafafaf xlower accepts hex digits either separators pairs separator must uniform either separators this explanation af means hexadecimal digit means want two means either dash colon note dash first char mean range means this atom enclosed parenthesis reused later back reference af another pair hexadecimal digits means want match expression matched separator this guarantees uniformity note regexp syntax i using regular string backslash must escaped doubling af another pair hex digits previous parenthesized block must repeated exactly times giving total pairs digits pair sep pair samesep pair the string must end right,what best way validate mac address entered user the format hhhhhhhhhhhh h hexadecimal character for instance ea valid ea invalid,3 how supposing items namespace passed code template ul talblock repeatitem items lia href talattributeshref item talcontentitemitemali talblock ul you put talrepeat li element i personally like use dedicated tag using element tal namespace idiomatic choice talblock also see httpdrdobbscomwebdevelopment,i trying loop list get output like python items item item item return dictitemsitems html ul lia hrefitemitemali lia hrefitemitemali lia hrefitemitemali ul i get list part right adding anchor going well,1 there couple observations several pieces code help way first python execute code form like perl cat codepy python rest pipe story findperl clever code template emits perl function based template find therefor replicate template hundreds permutations perceiving second results findperl perfect potentially differences versions find gnu bsd third default oswalk bottom find top this makes different results underlying directory tree changing recurse there two projects python may help twander dupfinder each strives os independent recurses file system like find if template general find like function python set oswalk recurse top use glob replicate shell expansion use code find two projects replicate findperl without much difficulty sorry i could point something ready go needs,perl lovely little utility called findperl translate quite faithfully command line unix find utility perl script if find command like find usr xdev type name share name shell expansion share directory file do go external file systems usr directory could multiple directories it finds directories ending share usr now run findperl usr xdev type name share emit perl script you modify script use python oswalk certainly needed functionality recursive directory listing big differences take simple case find type f print find print files current directory a naã¯ve implementation using oswalk would path dirs files oswalkroot files file files print ospathjoinpathfile however produce different results typing find type f print shell i also testing various oswalk loops create pipe find commands arg root findcmd find type f root argsshlexsplitfindcmd psubprocesspopenargsstdoutsubprocesspipe outerrpcommunicate outoutrstrip remove terminating n line outsplitlines print line the difference oswalk counts links files find skips so correct implementation file type f print becomes path dirs files oswalkroot files file files pospathjoinpathfile ospathisfilep ospathislinkp printp since hundreds permutations find primaries different side effects becomes time consuming test every variant since find gold standard posix world count files tree way python important so equivalent findperl used python so far i using findperl manually translating perl code this hard perl file test operators different python file tests ospath times,1 security security security just wanted get way what seem trying sounds pretty scary foot shoot also seem trying mix two different serverside languages unless implementation python runs top php i aware phpython if willing php code invoke python way able pretty easily something like eval exec see input python code run time execute as wrapping php classes i sure accomplish exactly you could mirror php classes python classes use something like json transport data two,i developing web based application written php basically ui top database to give users flexible tool i want embed scripting language complex things like fire sql queries loops store data variables in business domain python widely used scripting i also thinking making simple domain specific language the script wrap existing php classes i seeking advise approach development task update i try scripting database using plpgsql postgresql this i use php classes way lua approach appealing seems i want besides python,1 you need finish errors exceptions section tutorial try possiblyfail except handleexception else noexceptions finally alwaysrunthis,i following code part email class i use programs currently i running quit function whether connection smtp server made connect function i know i could put quit function inside try statement email sent i would like figure write code say equivalent connection server open close what best way write python thanks def connectself headers msg try selfserverstarttls try selfserverloginselfusrnameselfpswd try selfserversendmailselfsendfrom selfsendto headers rnrn msg except exception sendmailfail printsendmailfail except exception emailfail print emailfail except exception error printerror def quitself selfserverquit printthe smtp connection closed first gmailsmpt x z zz x firstmessage firstconnectxy firstquit,2 all generate generating trigram model none exists calling text selftrigrammodelgeneratelength wrapping printing just take parts want possibly line self replaced instance name possibly whole thing final print replaced return def generateself length trigrammodel selfdict estimator lambda fdist bins lidstoneprobdistfdist selftrigrammodel ngrammodel self estimator text selftrigrammodelgeneratelength return tokenwraptext text want wrap and call manually passed instance first argument,i python noob bear i trying work nltk library particular generate function it looks like documentation function simply prints result httpnltkgooglecodecomsvntrunkdocapinltktextpysrchtml i would like manipulate resulting text prior printing screen i seem figure get function return text how would i go getting output function do i change function return result instead printing update i found link kinda feels pretty darn hacky httpnorthernplanetsblogspotcomcapturingoutputofprintinpythonhtml is best i hope,1 you could check code python audiotools project it collection commandline utilities make use common python package there utility included audiotools trackcat concatenate two audio tracks another tracksplit split audio track using cue file these well numerous included utilities work audio files various encodings including mp,i would like basic audio mixing python to give example i would like take two mp files add together return one mp file another example i would like take first ten seconds one mp file add beginning another mp file what best way accomplish tasks i would like use built python functions like audioop find good tutorials sample code using built functions i going docs i pretty confused cannot figure things like i even sure python libraries like mp most stuff i looked seem refer wav files so case i guess follow question would easy way convert mp wav manipulation back,1 indeed http servers provided standard python library meant light duty use for moderate scaling concurrent connections modwsgi apache great choice if needs greater concurrent connections you want look asynchronous framework twisted tornado the general structure asynchronous application quite different think likely need go route definitely start project one frameworks start,i lot studying basehttpserver found good multiple requests i went article httpmetachrisorgscalingpythonserverswithworkerprocessesandsocketduplicationpython i wanted know best way building http server multiple requests my requirements http server simple support multiple requests request may run long python script till i following options basehttpserver thread good modpython apache intergration cherrypy any,1 you probably using pip linked python instead if installed pip properly python pip install requests if try installing way curl o httppythondistributeorgdistributesetuppy sudo python distributesetuppy curl o httpsrawgithubcompypapipmastercontribgetpippy sudo python getpippy,i would like install module pip installing right directory i assume usrlocallibpythonsitepackages after i installed python today originally i installed modules successfully so i think something wrong python path how module installations go proper python directory szszlaptop pip install requests requirement already satisfied requests usrlocallibpythondistpackagesrequestspyegg installing collected packages requests successfully installed requests szszlaptop python python default oct gcc linux type help copyright credits license information import requests traceback recent call last file stdin line module importerror no module named requests z stopped python also python directories look like httppastieorg,3 the error occurs file cmemcachedimpc must compiled step first edit file cmemcachedimppyx fix typo line instead sysstderrwritecmemcacheds support string cmd key say sysstderrwritecmemcacheds support string cmd keys then install cython execute cython cmemcachedimppyx cython silently generate file cmemcachedimpc while fix immediate error may also need replace extmodulesextension cmemcachedimp cmemcachedimppyx splitmcc setuppy extmodulesextension cmemcachedimp cmemcachedimpc splitmcc in response edit if follow instructions verbatim additionally need libmemcached local directory execute ln pwdlibmemcachedlibmemcached pythonlibmemcached achieve,while trying follow pythonlibmemcached instructions httpcodegooglecomppythonlibmemcached i run trouble step python setuppy install gigmashvenvmpythonlibmemcached matthewparrilla python setuppy build running build running buildpy creating build creating buildlibmacosxfat copying cmemcachedpy buildlibmacosxfat running buildext building cmemcachedimp extension creating buildtempmacosxfat gcc fnostrictaliasing fnocommon dynamic isysroot developersdksmacosxusdk arch ppc arch g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c cmemcachedimpc buildtempmacosxfatcmemcachedimpo powerpcappledarwingcc cmemcachedimpc no file directory powerpcappledarwingcc input files iappledarwingcc cmemcachedimpc no file directory iappledarwingcc input files lipo figure architecture type varfoldersoohtrmjfrpijtdbegzetitmpccxqqqout error command gcc failed exit status i next idea means i multiple versions gcc comp gleaned enough googling might matter totally lost otherwise thanks advance edit after following phihag instructions i receiving altogether different though still confusing error gigmashvenvmpythonlibmemcached matthewparrilla python setuppy build running build running buildpy running buildext building cmemcachedimp extension gcc fnostrictaliasing fnocommon dynamic isysroot developersdksmacosxusdk arch ppc arch g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c cmemcachedimpc buildtempmacosxfatcmemcachedimpo cmemcachedimpccmemcachedimpc error error libmemcachedmemcachedh no file directory libmemcachedmemcachedh no file directory in file included cmemcachedimpc splitmch warning ‘struct memcachedst’ declared inside parameter list splitmch warning scope definition declaration probably want splitmch warning ‘struct memcachedst’ declared inside parameter list in file included cmemcachedimpc splitmch warning ‘struct memcachedst’ declared inside parameter list goes many many lines,2 i good luck cherrypy web server one oldest solid purepython web servers just write application wsgi callable easy run cherrypy multithreaded server httpwwwcherrypyorg,i lot studying basehttpserver found good multiple requests i went article httpmetachrisorgscalingpythonserverswithworkerprocessesandsocketduplicationpython i wanted know best way building http server multiple requests my requirements http server simple support multiple requests request may run long python script till i following options basehttpserver thread good modpython apache intergration cherrypy any,1 use celery back end service runs root having web application process run root security problem waiting happen this modwsgi blocks running daemon processes root sure could hack code disable exclusion i tell,i currently writing web application using django apache modwsgi provides freebsd server management configuration features including common firewall operations my pythonc library uses raw sockets interact directly firewall works perfectly fine running root raw socket operations allowed root at point thing i think install use sudo explicitly allow www user access sbinipfw ideal since i would prefer use raw socket library operations rather subprocess call i suppose another option would write local domain sockets use existing job system celery runs root handles requests or perhaps wsgi daemon mode trickery i unaware i sure issue encountered any advice best way handle,1 you use ado read data accesshere connection strings access accdb files access mdb files use excel rangecopyfromrecordset methodassuming using excel via com copy entire recordset excel,i spending better part weekend trying figure best way transfer data ms access table excel sheet using python i found modules may help execsql pythonexcel limited knowledge modules i use create certain data i gis professional i creating spatial data using arcgis arcpy module access table i sure best approach all i need copy columns data access excel format excel i formatting part solved should i iterate rows using cursor somehow load rows excel copy columns access excel export whole access table sheet excel thanks suggestions,1 the best approach might use python task you could use macro recorder excel record import external data excel after starting macro recorder click data get external data new database query enter criteria once data import complete look code generated replace hard coded search criteria variables,i spending better part weekend trying figure best way transfer data ms access table excel sheet using python i found modules may help execsql pythonexcel limited knowledge modules i use create certain data i gis professional i creating spatial data using arcgis arcpy module access table i sure best approach all i need copy columns data access excel format excel i formatting part solved should i iterate rows using cursor somehow load rows excel copy columns access excel export whole access table sheet excel thanks suggestions,1 you likely want run script windows service to need pythonwin library this question good description go well bunch links related resources this question may also use a windows service want wrap script needs run continuously windows they configured automatically start boot handle failures nothing going stop anyone killing process handle potential situation create bat file use sc command pole service see running restart service just schedule bat file run every seconds whatever reasonable script potentially,i need run python script sure restart terminates i know unix solution called supervisord but unfortunately server script run windows do know tool useful thanks,3 you could key tel num telkey print joinstrn n num for example prints,i following code tel telvalues joinmapstri print the dictionary tel consists keys number keys valuehere lists binary the key values one case what print values belong key line line my goal i want print string version value in example i want output how would i accomplish,1 using splitlines split newline character strip remove unnecessary white spaces names apple ball cat names n applen balln cat nameslist xstrip x namessplitlines xstrip used remove empty lines nameslist apple ball cat,i extracted set data html page copied variable the variable looks like names apple ball cat now i like join line list i access line i want is way python,3 namessplitlines give,i extracted set data html page copied variable the variable looks like names apple ball cat now i like join line list i access line i want is way python,1 x telvalues x print joinstrz z,i following code tel telvalues joinmapstri print the dictionary tel consists keys number keys valuehere lists binary the key values one case what print values belong key line line my goal i want print string version value in example i want output how would i accomplish,1 definitely use celery you run amqp server i think sue database queue messages it allows run tasks background use multiple worker machines processing want it also cron jobs database based use djangocelery it simple run task background task def addx return x in project i distributing work machines works great,i working fairly simple cgi python i put django etc the overall setup pretty standard server side ie computation done server user uploads data files clicks run button server forks jobs parallel behind scenes using lots ram processor power minutes later average use case program terminates created file output png figure files server displays web page figures summary text i think going hundreds thousands people using however computation going takes fair amount ram processor power instance forks cpuintensive task using python pool i wondered know whether would worth trouble use queueing system i came across python module called beanstalkc page said inmemory queueing system what inmemory mean context i worry memory cpu time i want ensure one job runs held ram whether receives cpu time time also i trying decide whether result page served cgi tell position queue runs displays actual results page or user submit email address cgi email link results page complete what think appropriate design methodology light traffic cgi problem sort advice much appreciated,1 don post entire thing that much time first error enough geventlibeventh error eventh no file directory this means library provides eventh header installed the library called libevent website in general compilation errors like flaw build scripts the build script give error message libevent installed bug to get libevent macports manually tell compiler cflags environment variable find eventh libevent running pip sudo port install libevent cflagsi optlocalinclude l optlocallib pip install gevent you also use homebrew installing libevent brew install libevent david wolever comment,python library gevent version current version pypi pip install os x lion python probably others it works fine snow leopard how i get library installed bonus points done using pip install rather manual custom process play nicely automated builds here pip install output pip install gevent downloadingunpacking gevent running setuppy egginfo package gevent requirement already satisfied use upgrade upgrade greenlet tlenvlibpythonsitepackages gevent installing collected packages gevent running setuppy install gevent building geventcore extension gcc fnostrictaliasing fnocommon dynamic isysroot developersdksmacosxsdk arch arch x g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c geventcorec buildtempmacosxintelgeventcoreo in file included geventcorec geventlibeventh error eventh no file directory geventlibeventh error evhttph no file directory geventlibeventh error evdnsh no file directory geventcorec error field ‘ev’ incomplete type geventcorec warning parameter names without types function declaration geventcorec in function ‘pyxfgeventcoreeventhandler’ geventcorec error ‘evread’ undeclared first use function geventcorec error each undeclared identifier reported geventcorec warning assignment makes pointer integer without cast lines compiler errors geventcorec error dereferencing pointer incomplete type geventcorec in function ‘pyxpfgeventcorehttpinit’ geventcorec warning assignment makes pointer integer without cast geventcorec at top level geventcorec error expected ‘’ ‘val’ lipo figure architecture type varfoldersstknphdgxzxsprpggqtcczkqout error command gcc failed exit status complete output command usersjacobcodetopleveltlenvbinpython c import setuptoolsfile usersjacobcodetopleveltlenvbuildgeventsetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record varfoldersstknphdgxzxsprpggqtpipshpdrecordinstallrecordtxt installheaders usersjacobcodetopleveltlenvbinincludesitepython running install running build running buildpy running buildext building geventcore extension gcc fnostrictaliasing fnocommon dynamic isysroot developersdksmacosxsdk arch arch x g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c geventcorec buildtempmacosxintelgeventcoreo,3 thank everyone i actually using method proposed unutbu moreover i add another optimization ifvalue firstrangevalue value lastrangevalue return none where firstrangevalue lastrangevalue computed smallest raddress value largest raddressrsize value this worthing application really depends distribution ranges values,i list many python objects like class rangeclassobject def initselfaddresssize selfaddressaddress selfsizesize attributes methods then i list rangelist rangeclass objects i need find within range given value i use code like r ragelist ifvalueraddress valueraddressrsize return r return none but i think faster way ranges arbitrary size assume overlap thank,1 month janfebmaraprmayjunjulaugsepnovdecaz regexstrings month monthday year month day month year dw month mon dayth year month day month ddd monthdayyear ddd monthdayyear,what best way get datestrings website using python the datestrings example forms april st april nd april would ton regex what elegant solution,1 on following line hwnd selfpanelgetid you want use gethandle instead getid edit this originally posted comment i suppose would appropriate repost answer regarding edit question if works i guess problem anymore okay seriously though ints longs unified python i guess comtypes might coercion background i know necessary worry details dealing comtypes general seem matter much case now i experience pyqt python define special methods objects int long emulate well ints longs if i guess object getting pyqt defines one methods,for brevity sake i trying implement wxpython i struggling fit code script based wxpython my simple pyqt test code works fine here pyqt import qtgui threading import thread import time import sys import comtypesclient cc import comtypesgentaskbarlib tbl tbpfnoprogress tbpfindeterminate x tbpfnormal x tbpferror x tbpfpaused x ccgetmoduletaskbartlb taskbar cccreateobjectfdffdddaca interfacetblitaskbarlist class mainwindowqtguiqmainwindow def initself parentnone qtguiqmainwindowinitself parent selfsetwindowtitletest selfprogressbar qtguiqprogressbarself selfsetcentralwidgetselfprogressbar selfprogressbarsetrange selfprogress selfshow thread threadtargetselfcounter threadsetdaemontrue threadstart def counterself true selfprogress selfprogress selfprogress timesleep selfprogressbarsetvalueselfprogress taskbarhrinit hwnd selfwinid taskbarsetprogressstatehwnd tbpferror taskbarsetprogressvaluehwnd selfprogress app qtguiqapplicationsysargv ui mainwindow sysexitappexec but i try execute wxpython counterpart taskbar work expected here wxpython code import wx import time import comtypesclient cc import comtypesgentaskbarlib tbl threading import thread tbpfnoprogress tbpfindeterminate x tbpfnormal x tbpferror x tbpfpaused x ccgetmoduletaskbartlb taskbar cccreateobjectfdffdddaca interfacetblitaskbarlist class mainwindowwxframe def initself parent id title wxframeinitself parent id title selfpanel wxpanelself selfgauge wxgaugeselfpanel selfgaugesetvalue selfprogress selfshow thread threadtargetselfcounter threadsetdaemontrue threadstart def counterself true selfprogress selfprogress selfprogress timesleep selfgaugesetvalueselfprogress taskbarhrinit hwnd selfgethandle taskbarsetprogressstatehwnd tbpferror taskbarsetprogressvaluehwnd selfprogress app wxpysimpleapp frame mainwindownone wxidany test appsettopwindowframe appmainloop in particular i think issue due wxwindow window handle hwnd method differ qt equivalent former returning integer latter sipvoidptr object the problem i already wrote whole code lines wxpython thus rewrite use qt talk different licenses what think should i give thanks lot advance edit thanks robert o connor works however i still get gethandle returns integer winid returns object in idl file argument hwnd declared long function definitions maybe simple question any ideas,1 first fastest execution prevent user waiting means kind deferred processing once decide defer processing user see choice flatfile database essentially irrelevant respect enduserwait time second databases slow flat files fast since going use celery avoid enduserwait time however distinction flat file database becomes irrelevant store source data ascii file system post process later processingdatadaemon this fastest celery load flat files,to analyze large number websites financial data pull parametric data optimal strategies i classifying following strategies either onthefly deferred which best onthefly process data onthefly store parametric data database deferred store source data ascii file system post process later processingdatadaemon deferred store pages blob database postprocess later processingdatadaemon number simplest especially single server can efficient single server see power multiple servers are python projects already geared toward kind analysis edit best i mean fastest execution prevent user waiting ease programming secondary,1 i huge amount experience urllib python general i doubt easy clicking button urllib get page act like browser it way interact page acts medium server get page you submit form making another call based information form,i want click button python info form automatically filled webpage html code sending request button input typesubmit valueplace bid how would i go is possible click button urllib urllib or i need use something like mechanize twill,1 using urlliburlopen could send values form data parameter page specified form tag but automate browser get form values way first,i want click button python info form automatically filled webpage html code sending request button input typesubmit valueplace bid how would i go is possible click button urllib urllib or i need use something like mechanize twill,1 you may want take look ironwatin httpsgithubcomrtylerironwatin fill form click button using code,i want click button python info form automatically filled webpage html code sending request button input typesubmit valueplace bid how would i go is possible click button urllib urllib or i need use something like mechanize twill,1 use form target send input post data like form targethttpmysitecomblahphp methodget input typetext namein valueabc input typesubmit valueplace bid form python parse page html form get form target input names values except submit reset button you use xmldomminidom htmlparser formtarget gets parsed httpmysitecomblahphp inputname gets parsed inputvalue gets parsed abc formurl formtarget inputname inputvalue formurl value httpmysitecomblahphpinabc then open new url clicking submit button urlliburlopenformurl you parse html htmlparser and forget urlencode post data urlliburlencodequery,i want click button python info form automatically filled webpage html code sending request button input typesubmit valueplace bid how would i go is possible click button urllib urllib or i need use something like mechanize twill,3 see post john wright ran problem httpmailscipyorgpipermailnumpydiscussionjulyhtml basically numpy using python c api way incompatible jep jep uses sub interpreters allow multiple interpreter environments it could possible change jep uses gil state functions would really limit jep functionality java,i embedding cpython jvm using jepp i run import numpy numpyfinfofloat process hangs gdb says something blocking semaphorelock acquisition stack trace suggests something floating pointrelated ldpreloadusrliblibpythonso gdb args java jar jeppjar tmpgopy gnu gdb gdb ubuntu copyright c free software foundation inc license gplv gnu gpl version later httpgnuorglicensesgplhtml this free software free change redistribute there no warranty extent permitted law type show copying show warranty details this gdb configured xlinuxgnu for bug reporting instructions please see httpwwwgnuorgsoftwaregdbbugs reading symbols usrbinjavano debugging symbols founddone gdb r starting program usrbinjava jar jeppjar tmpgopy thread debugging using libthreaddb enabled process executing new program usrlibjvmjavasunjrebinjava thread debugging using libthreaddb enabled new thread xfffffd lwp new thread xffffca lwp new thread xffffc lwp new thread xffffc lwp new thread xffffc lwp new thread xffffbf lwp new thread xffffaf lwp new thread xfffff lwp new thread xffffb lwp new thread xffffb lwp new thread xffffb lwp new thread xffffb lwp new thread xffffaf lwp import numpy numpyfinfofloat c program received signal sigint interrupt xffffd pthreadjoin liblibpthreadso gdb bt xffffd pthreadjoin liblibpthreadso xc continueinnewthread xef main gdb threads thread xffffaf lwp xffffabc pthreadcondtimedwaitglibc liblibpthreadso thread xffffb lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xffffb lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xffffb lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xffffb lwp xffffcb semwait liblibpthreadso thread xfffff lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xffffaf lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xffffbf lwp xffffabc pthreadcondtimedwaitglibc liblibpthreadso thread xffffc lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xffffc lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xffffc lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xffffca lwp xffffac pthreadcondwaitglibc liblibpthreadso thread xfffffd lwp xffffcb semwait liblibpthreadso thread xffffed lwp xffffd pthreadjoin liblibpthreadso gdb thread switching thread thread xfffffd lwp xffffcb semwait liblibpthreadso gdb bt xffffcb semwait liblibpthreadso xffffadb pythreadacquirelock usrliblibpythonso xffffacbb pyevalrestorethread usrliblibpythonso xffffa pygilstateensure usrliblibpythonso xfffebeff errorhandler method errobjx errtypex retstatus firstx numpycoresrcumathufuncobjectc xfffebe pyufunchandlefperr errmask errobjxfffec retstatus firstxfffffafc numpycoresrcumathufuncobjectc xfffebecd pyufuncgenericfunction selfvalue optimized argsvalue optimized kwdsvalue optimized opxfffffaaa numpycoresrcumathufuncobjectc xfffebeff ufuncgenericcall selfxfffecdf argsvalue optimized kwdsvalue optimized numpycoresrcumathufuncobjectc xffffce pyobjectcall usrliblibpythonso xffffedf pyobjectcallfunctionsizet usrliblibpythonso xffffcaa usrliblibpythonso xffffd pynumbermultiply usrliblibpythonso xffffafbc pyevalevalframeex usrliblibpythonso xffffa pyevalevalframeex usrliblibpythonso xffffad pyevalevalcodeex usrliblibpythonso xffffad usrliblibpythonso xffffce pyobjectcall usrliblibpythonso xffffdcef usrliblibpythonso xffffce pyobjectcall usrliblibpythonso xffffecd usrliblibpythonso xffffdf usrliblibpythonso xffffce pyobjectcall usrliblibpythonso xffffa pyevalevalframeex usrliblibpythonso xffffad pyevalevalcodeex usrliblibpythonso xffffaab pyevalevalframeex usrliblibpythonso xffffad pyevalevalcodeex usrliblibpythonso xffffad usrliblibpythonso xffffce pyobjectcall usrliblibpythonso xffffdd usrliblibpythonso xffffdf usrliblibpythonso xffffce pyobjectcall usrliblibpythonso xffffa pyevalevalframeex usrliblibpythonso xffffad pyevalevalcodeex usrliblibpythonso xffffae pyevalevalcode usrliblibpythonso xffffadc pyrunstringflags usrliblibpythonso xffffde pyembedeval envxd jepthread strxfffec import numpy numpyfinfofloat pyembedc xffffca javajepjepeval envxd type return continue q return quit objvalue optimized tstate jstrxfffffbdf jepc xffffade x gdb thr switching thread thread xffffb lwp xffffcb semwait liblibpthreadso gdb bt xffffcb semwait liblibpthreadso xffffeea checkpendingsignalsbool usrlibjvmjavasunjrelibamdserverlibjvmso xffffc signalthreadentryjavathread thread usrlibjvmjavasunjrelibamdserverlibjvmso xfffff javathreadrun usrlibjvmjavasunjrelibamdserverlibjvmso xffffeadf javastartthread usrlibjvmjavasunjrelibamdserverlibjvmso xffffca startthread liblibpthreadso xffffed clone liblibcso x from delta debugging appears following loop runs times run maxitern times things halt temp zt line xrangemaxitern z z yy zone check underflow temp zt anyaa zero anyabszy break temp temp betain anytempbeta z break k k k else print baz raise runtimeerror msg onedtype any ideas to fully reproduce mkdir tmptest cd tmptest wget httpsourceforgenetprojectsnumpyfilesnumpynumpytargz tar xzf numpytargz cd numpy python setuppy install prefixtmptestenv cd git clone httpsgithubcommrjjeppgit cd jeppjep export javahomeusrlibjvmjavasun configure prefixtmpjepp ampamp make ampamp make install touch tmpgopy pythonpathtmptestenvlibpythonsitepackages ldpreloadusrliblibpythonso java jar jeppjar tmpgopy import numpy numpyfinfofloat i able reproduce machines ubuntu x boxes it iirc i experience ubuntu numpy package fromsource build instructed thanks advance this driving wall,1 collectionsdefaultdictlist line l name value linersplit dnameappendvalue dict like bananas apples apples oranges x z so need format keys values key joinvalues key values ditems and result bananas apples apples oranges x z,i list following format l apples oranges x bananas apples apples oranges z for every item l itemsplit matches another itemsplit ie apples oranges matches apples oranges i need output single itemsplit followed tags recording origin partially duplicated line the tags come index item ie x z so output l would l l apples oranges x z bananas apples any ideas,2 pgconfig part postgresql installation it bin directory local installation eg cprogram files xpostgresqlbin add directory search path try build,i trying install psycopg cygwin succeeded yet the error gauravgauravpc fieldagentwebfieldagentweb easyinstall psycopg searching psycopg reading httppypipythonorgsimplepsycopg reading httpinitdorgpsycopg reading httpinitdorgprojectspsycopg best match psycopg downloading httpinitdorgpsycopgtarballspsycopgpsycopgtargz processing psycopgtargz running psycopgsetuppy q bdistegg distdir tmpeasyinstallqbypxh psycopgeggdisttmpgclaf error pgconfig executable found please add directory containing pgconfig path specify full executable path option python setuppy buildext pgconfig pathtopgconfig build pgconfig option setupcfg error directory empty builtin function rmdir tmpeasyinstallqbypxhps ycopgtests after trying get pgconfig file find net,2 in case i would go list appending concatenation why well strings immutable python that means every time use basically creating two new strings reading third if create list append hand halve number strings created do really need call select multiple times my understanding really care process threadblocking since select less wrapper around c method name select pselect allow program monitor multiple file descriptors waiting one file descriptors become ready class io operation eg input possible a file descriptor con‐ sidered ready possible perform corresponding io operation eg read without blocking you listening sockettimeout exception code writing stdoutthe file system expensive yet logging every single line returned recv can move log line have considered handling reading channel manually the code technically need try nbspnbspnbspnbspnbsp selfinbufferreadnbytes selftimeout except pipetimeout e nbspnbspnbspnbspnbsp something error it guaranteed cut extra processing,hi i problems executing command performs wget mb file ubuntu server shorter commands work fine except the class contains i use paramiko different tries overcoming problem see different run exec methods in case execcmd execution hangs line selfinbufferreadnbytes selftimeout recv method channelpy module paramiko the wget command works perfectly shell using normal ssh utility mac management ssh connections import logging import os import paramiko import socket import time import stringio class sshclient def initself selfsshclient paramikosshclient selfsshclientloadsystemhostkeys selfsshclientsetmissinghostkeypolicyparamikoautoaddpolicy selftimeout selfwait def connectself hostname user pkey retry selftimeout selfhostname hostname logginginfoconnecting tos users keys hostname user pkey retry try selfsshclientconnecthostname usernameuser keyfilenameospathexpanduserpkey timeoutselftimeout return except socketerror valuemessage value value loggingwarning ssh connection refused retry seconds timesleepselfwait retry selfwait else raise except paramikobadhostkeyexception loggingwarnings entry sshknownhosts match selfserverhostname loggingwarning edit file remove entry try retry except eoferror loggingwarning unexpected error ssh connection retry seconds timesleepselfwait retry selfwait loggingerror could establish ssh connection def existsself path status selfrun echo false path statusstartswith false return return def shellself start interactive shell session remote host channel selfsshclientinvokeshell interactiveshellchannel def runself command execute command remote host return tuple containing integer status string containing output command logginginfo runnings command selfhostname logfp stringiostringio status try selfsshclientexeccommandcommand except paramikosshexception loggingerrorerror executing command command status logfpwritetread logfpwritetread tclose tclose tclose logginginfo output logfpgetvalue return status logfpgetvalue def runptyself command execute command remote host pseudoterminal returns string containing output command logginginfo runnings command selfhostname channel selfsshclientgettransportopensession channelgetpty status try channelexeccommandcommand except loggingerrorerror executing command command status return status channelrecv def closeself transport selfsshclientgettransport transportclose def runremoteself cmd checkexitstatustrue verbosetrue usesudofalse logginginfo runnings cmd selfhostname ssh selfsshclient chan sshgettransportopensession stdin chanmakefile wb stdout chanmakefile rb stderr chanmakefilestderr rb processedcmd cmd usesudo processedcmd sudo s bash c cmdreplace chanexeccommandprocessedcmd result stdout stderr exitstatus chanrecvexitstatus result exitstatus exitstatus def printoutput line stdout result stdout appendline logginginfoline line stderr result stderr appendline logginginfoline verbose print processedcmd printoutput return exitstatusresult def execcmdself cmd import select ssh selfsshclient channel sshgettransportopensession end cmdepilogqwkjidksjkdskhjdksjkdsl cmd echo end logginginfo runnings cmd selfhostname channelexeccommandcmd buf end buf rl wl xl selectselectchannel lenrl must stdout buf channelrecv logginginfobuf buf return,1 i wish better answer way get current active reactor twisted application twistedinternet import reactor the important thing place near top application code easily replace reactor testing purposes modify behavior ways example could potentially change connecttcp go proxy that agent takes reactor parameter rather importing current one,my application uses twistedwebclientagent get web content but agent class requires reactor instance initiate if i start application using twistd reactorrun so i get reactor instance,3 i difficulty getting python sequence pointer objects automatically convert stdvector pointer objects i currently stuck using swig ymmv using swig the trick instantiate swig interface file template vector object pointer objects also include stdvectori templatemyobjectt namespaceofmyobjectt templatemyobjectptrt boostsharedptrnamespaceofmyobjectt templatemyobjectvectort stdvectorboostsharedptrnamespaceofmyobjectt without myobjectptrt swig seem know enough convert python sequence pointers myobjectt myobjectvectort update for reason i yet able figure leads able call methods myobjectt myobjectptrt even though i also used swigsharedptrmyobjectt myobjectt,edit solved mistake explained answer i stdvector boostsharedptr entity entities i try expose swig like include boostsharedptri include stdvectori sharedptrentity include entityh namespace std templateentityvector vectorboostsharedptrentity include thefilewithentitiesh however python entities ends tuple import mymodule print typemymodulecvarentities output type tuple i googled could find concrete examples wrap one page gave small example wrapping c help case any help greatly appreciated,1 i understand question i url i want go corresponding store company user you using urlmappingobjectsgeturluser urlmappingobjectsgeturlstore urlmappingobjectsgeturlcompany clearly give error know maps seems like really looking really use generic foreign keys so able urlmappingobjectsgeturl corresponding user company store model,now i working one url mapping let say i three classes company user store goal urls hierarchy since hierarchy urls i create class urlmapping ensure duplicate name let give concrete problem i class companymodelsmodel companyname modelscharfieldmaxlength urlmapping modelsonetoonefieldurlmapping class usermodelsmodel username modelscharfieldmaxlength urlmapping modelsonetoonefieldurlmapping class storemodelsmodel storename modelscharfieldmaxlength urlmapping modelsonetoonefieldurlmapping class urlmappingmodelsmodel url modelscharfieldmaxlength now visitor access site certain url i match url urlmapping class reverse lookup see type url company user store since user store company different view function possible quickly redirectly corresponding view function quickly using reverse lookup or i add another field urlmapping saying url type the example httpwwwexamplecomlevis handle brandviews httpwwwexamplecomdavid handle userviews httpwwwexamplecommancy handle storeviews in database urlmapping id namelevis id namedavid id namemancy user id namedavid urlmapping brand id namelevis urlmapping store id name mancy urlmapping where urlmapping onetoonefield don know quickly look urlmapping class thank,2 the builtin library unittest provides functionality seek you find list assert methods useful making specific assertions unittest import testcase class sometesttestcase def setupself selfvalue def testmyvalueself selfassertequalselfvalue this somewhat different constraints nunit easy adapt quite powerful,is constraintbased unit testing framework cpython much like beloved nunit i roll edit this i mean constraintbased httpwwwnunitorgindexphppconstraintmodelampr ie instead assertzcount like assertthatzcount isgreaterthan,1 i finally solved problem suite method import os import doctest djangoutils import unittest jquerypyproxy import base utils optionflags doctestellipsis doctestnormalizewhitespace testmods base base utils utils testfiles readme readmerst django djangotxt def suite return unittesttestsuite doctestdoctestsuitemod optionflags optionflags mod testmodsvalues doctestdocfilesuitef optionflags optionflags f testfilesvalues apparently problem calling doctesttestfile doctesttestmod tests directly ran using doctestsuitedocfilesuite builds list test runner runs,i small problem test suite django i working python package run django plone httppypipythonorgpypijquerypyproxy all tests written doctests either python code separate docfiles example readmetxt i tests running fine django count vincent buildoutstestsdjangopyproxy bindjango test pyproxy creating test database alias default ran tests ok but i failing test appear correctly vincent buildoutstestsdjangopyproxy bindjango test pyproxy failed example expected nothing got items failures readmerst test failed failures creating test database alias default ran tests ok this test suite declared right import os import doctest unittest import testsuite jquerypyproxy import base utils optionflags doctestellipsis doctestnormalizewhitespace test base doctesttestmod mbase optionflagsoptionflags utils doctesttestmod mutils optionflagsoptionflags readme doctesttestfile readmerst optionflagsoptionflags django doctesttestfile djangotxt optionflagsoptionflags i guess i something wrong declaring test suite i clue exactly thanks help vincent,1 it possible case easier focus want html tags br phone numbers everything parenthesis each matched easily simple regular expressions making easy construct one match rest presumably address,alright one bit pain i scraping python trying get address lines poorly tagged html here sample format br fake ave sbr gotham lower wardbr i like retrieve fake ave s gotham any ideas i regex night brain mush edit more detail possible scenarios data arrive sometimes first line sometimes all addresses i seen ave way st although i would prefer use factor selection i certain always way the second third line alphone possible email website what i mind something selects everything nd last line second line three lines first line two phone number selects everything last line parentheses combine nd last line last line adding two i using scrapy acquire html code the address div i want use regex break data appropriate sections now i unable figure edit as per ofir comment i mention i already made expressions isolate phone number parentheses section phone possible email website awwwwwwcomnetorgus parentheses i sure use construct everythingbutthese statement,1 you make little function calculates alignment ax def alignyaxisax v ax v adjust ax ylimit v ax aligned v ax axtransdatatransform v axtransdatatransform v inv axtransdatainverted dy invtransform invtransform yy miny maxy axgetylim axsetylimminydy maxydy using alignyaxis align axes quickly code adjustment origin aligned width left group axsetylim alignyaxisax npmeangrp ax pltshow,when plotting several axis matplotlib way specify align origin andor ytick labels right axis specific value left axis here problem i would like plot two set data well difference basically i trying reproduce kind graph i reproduce i manually adjust ylim right axis origin aligned value i want left axis i putted example simplified version code i use as see i manually adjust scale right axis align origin right axis well square import numpy np import scipy sp import matplotlibpyplot plt grp nparray grp nparray fig pltfigurefigsize ax figaddaxes remove top right spines turn ticks spine axspines right setcolor none axspines top setcolor none axspines bottom setcolor none axxaxissetticksposition none axyaxissetticksposition left postition tick axtickparamsaxis direction width length labelsize pad axspines left setlinewidth plot groups vs random numbers create dot plot axplotnprandomnormal grpsize grp ok markersize axplotnprandomnormal grpsize grp ok markersize axerrorbar npmeangrp fmt r markersize markeredgewidth axerrorbar npmeangrp fmt r markersize markeredgewidth axsetxlim axsetylim create right axis ax figaddaxesaxgetposition sharexax frameonfalse axspines left setcolor none axspines top setcolor none axspines bottom setcolor none axxaxissetticksposition none axyaxissetticksposition right postition tick axtickparamsaxis direction width length labelsize pad axspines right setlinewidth axsetxticks axsetxticklabels gr gr d axhlines linestyle dotted axhlinesnpmeanadultnpmeannrvm linestyle dotted axplot npmeangrpnpmeangrp sk markersize manual adjustment origin aligned width left group axsetylim axsetxlim pltshow,3 you likely raising error handler i guess setting requesterrorresponse cherrypy config like error responsebody check probably using wrong body template edit comments def errorpagestatus message traceback version tmpl tplgettemplatemako return tmplrenderstatstatus msgmessage cherrypyconfigupdate errorpage errorpage the render method specify function behavior keyword arguments could also little flexible specify function like def errorpagestatus message traceback version tmpl tplgettemplatemako args stat status msg message return tmplrenderargs it make easier expand arguments template i usually use args render calls but basically problem pointed calling render nonkeyword arguments expected input keyword arguments template,trying display template rendered mako errors still displays standart error page cherrypy footer additional message in addition custom error page failed typeerror renderbody takes exactly argument given the code def errorpagestatus message traceback version tmpl tplgettemplatemako return tmplrenderstatus message cherrypyconfigupdate errorpage errorpage need help how display completely custom error pages layoutmako template full code import sys sysstdout sysstderr import os atexit import threading import cherrypy makotemplate import template makolookup import templatelookup cherrypyconfigupdate environment embedded cherrypyenginestate cherrypyenginestartblockingfalse atexitregistercherrypyenginestop localdir ospathdirnamefile absdir ospathjoinosgetcwd localdir path ospathjoinabsdir files templpath ospathjoinabsdir html tpl templatelookupdirectoriestemplpath inputencoding utf outputencoding utf encodingerrors replace def errorpagestatus message traceback version tmpl tplgettemplatemako return tmplrenderstatus message cherrypyconfigupdate errorpage errorpage class root def indexself tmpl tplgettemplateindexmako return tmplrendertext some text url cherrypyurl indexexposed true application cherrypyapplicationroot none import posixpath def applicationenviron startresponse environ scriptname posixpathdirnameenviron scriptname environ scriptname environ scriptname return applicationenviron startresponse,1 calling shell generally required i know experince part ffmpeg output comes stderr stdout if want print output line like example simply import subprocess cmd ffmpeg filemp fileavi args cmdsplit p subprocesspopenargs note line ffmpeg chat terminated r overwrite line i think means iterate lines pstderr rsync example to build progress bar may need handle reading get started p subprocesspopenargs stderrsubprocesspipe true chatter pstderrread printoutput chatterrstrip,i looked number questions still quite figure i using pyqt hoping run ffmpeg filemp fileavi get output streams i create progress bar i looked questions can ffmpeg show progress bar httpstackoverflowcomquestionscatchingstdoutinrealtimefromsubprocess i able see output rsync command using code import subprocess time os sys cmd rsync vaz p source dest p line true start p subprocesspopencmd shelltrue bufsize stdinsubprocesspipe stderrsubprocesspipe stdoutsubprocesspipe line pstdout printoutput strlinerstrip pstdoutflush but i change command ffmpeg filemp fileavi i receive output i guessing something stdout output buffering i stuck read line looks like frame fps q lsize kb time bitratekbitss which i could use figure progress can someone show example get info ffmpeg python without use pyqt possible edit i ended going jlp solution code looked like usrbinpython import pexpect cmd ffmpeg filemts fileavi thread pexpectspawncmd print started cmd cpl threadcompilepatternlist pexpecteof frame true threadexpectlistcpl timeoutnone eof print sub process exited break elif framenumber threadmatchgroup print framenumber threadclose elif unknownline threadmatchgroup print unknownline pass which gives output started ffmpeg filemts fileavi frame frame frame frame frame frame frame frame frame frame frame frame frame frame sub process exited perfect,1 try azbetacromebeta word beta preceded letter full word cromebeta i add quote httpdocspythonorglibraryrehtml explain first part matches current position string preceded match this called negative lookbehind assertion similar positive lookbehind assertions contained pattern must match strings fixed length patterns start negative lookbehind assertions may match beginning string searched,i want check string product name contains word beta since i good regex writing eg crome beta cromebeta crome beta cromebetaversion crome beta cromeberta beta crome so i raise error valid product name product version wrote regex able cought strings parsebeta recompile beta rei researchparsedata productname logging error invalid product name but product name contains word substring beta init like tibetans product regex parsing beta raising error want handle caseany one suggest regex thanks lot,1 using partition method readable cases string firstpart middle lastpart stringpartition result lastpartstrip,i string v i would like part strip everything including the problem string fixed could i specify strip everything characters i need search strip everything,3 strpartition built exactly kind problem in v in vpartition out in vpartition out,i string v i would like part strip everything including the problem string fixed could i specify strip everything characters i need search strip everything,2 all need tokenizer have look nltk especially wordpuncttokenizer,i wondering implement function getwords returns words string list stripping away punctuation how i would like implemented replace non stringasciiletters return split def getwordstext the function take one argument string returns textsplit for example getwords hello world name isjames returns hello world name james,1 try use w w resplit w hello world name isjames w hello world name james although i sure catch use cases if want solve another way may specify characters want result refindall stringasciiletters hello world name isjames hello world name james,i wondering implement function getwords returns words string list stripping away punctuation how i would like implemented replace non stringasciiletters return split def getwordstext the function take one argument string returns textsplit for example getwords hello world name isjames returns hello world name james,3 this nothing splitting punctuation care letters numbers want regular expression import def getwordstext return recompile w findalltext demo recompile w findall hello world name isjames nd hello world name james nd if care numbers replace w azaz letters i almost answered question python strings split multiple separators but question actually underspecified do want example split example example i assumed first case example want method without importing regex if replace non asciiletters splitting string words list would work – james smith mins ago the regexp elegant yes could follows def getwordstext returns list words word defined maximally connected substring uppercase lowercase alphabetic letters defined aisalpha getwords hello world name ã‰lise works python hello world name ã‰lise return joinc cisalnum else c textsplit isalpha sidenote you could also following though requires importing another standard library itertools import groupby generally always overkill makes unreadable code fun def getwordstext return joinchars iswordchars groupby my name test lambda ccisalnum isword if homework probably looking imperative thing like twostate finite state machine state last character letter state changes letternonletter output word don good way program though sometimes abstraction useful,i wondering implement function getwords returns words string list stripping away punctuation how i would like implemented replace non stringasciiletters return split def getwordstext the function take one argument string returns textsplit for example getwords hello world name isjames returns hello world name james,3 perhaps rtmplite could help,i looking proper rtmp python client python code example could least following properly handshake flash server send properly encoded amf amf connect message server process result send properly encoded subscribe message process result i investigating rtmpy rtmplite fmspy libraries gotten anything work yet the amf encoding capabilities rtmplite seem good though can anyone point right direction,1 you modify file inplace like files support insertion you read write you line line wish but case need write temporary file replace original so small enough files simpler one go like open ampotxt r f lines freadlines lines edf line line lines open ampotxt w f fwritelineslines,how insert string beginning line text file following code f open ampotxt r open ampotxt infile line infile finsert edf fclose get following error file object attribute insert please note im complete programming nb,3 you completely crazy pythonmode integrate eldocmode display arg spec function calling point just mx eldocmode python file turn start working it talks inferior python buffer inspect functions directly always decently accurate you turn automatically new pythonmode buffers addhook pythonmodehook lambda eldocmode emacs startup file now point i say i regular python programming i tried work i spent minutes poking around source code everything seems place code runs inferior process returning empty string perhaps setup perhaps i reading wrong source files hard say emacs provides several different types expansionautocompletion by default access dabbrevexpand hitting m this fairly simple form completion meant work old file happen edit more sophisticated hippieexpand even anything pythonspecific the documentation says integrate hippieexpand exact completions might lie i figure works a little poking around shows several related solutions seem rely pymacs if i going lot python programming already fairly complicated emacs set i probably start installing emacsforpython it looks pretty complete setup even claims live warningerror detection in spirit helping others help i like point i came upon information my first step open file pythonmode i actually python code available i went scratch buffer made python buffer mx pythonmode then i asked help strange new mode ch see could it author kindly put brief summary mode mentions eldocmode imenu outlinemode hippieexpand rlcompleter abbrev tables bunch things from i started looking source code for instance integrate eldocmode defines function called pythoneldocfunction gives eldoc module use python buffers reading code shows interacts inferior buffer etc i hope helps,i using bpython python interpreting needs it delightful particularly using unfamiliar new libraries libraries multitude functions in case nice bpython interpreter running alongside i even better i autocompletelike feature parameter description manner bpython i editing code emacs am i completely crazy does anyone idea thanks bradley powers,3 i know thing exists python unit testing tools seems like something solved quite easily roll using python functional capabilities for example let function called assertthat follows def assertthatval constraint assertconstraintval constraint could defined way def equaltestval def cval return testval val then use like assertthatmyval equal expect that start i suspect decorators operator module afternoon could create pretty comprehensive set useful constraint functions,is constraintbased unit testing framework cpython much like beloved nunit i roll edit this i mean constraintbased httpwwwnunitorgindexphppconstraintmodelampr ie instead assertzcount like assertthatzcount isgreaterthan,1 python comes batteries included import fileinput import sys line fileinputinput ampotxt inplacetrue sysstdoutwrite edf l formatlline unlike solutions already posted also preserves file permissions,how insert string beginning line text file following code f open ampotxt r open ampotxt infile line infile finsert edf fclose get following error file object attribute insert please note im complete programming nb,3 simply calling noderecursegenerator recursively enough yield results def noderecursegeneratornode yield nodevalue n nodechildelements rn noderecursegeneratorn yield rn,class nodeobject def initself lst typelst list selfvalue lst selfchildren lst else selfvalue lst selfchildren property def childelementsself return nodea selfchildren property def getvalueself return selfvalue def noderecursegeneratornode yield nodevalue n nodechildelements noderecursegeneratorn node simple tree like data structure the list first element always value node elements children if node initiated something list value children empty list node listnoderecursegeneratora now would great recursive iterator elements generator yields first element why happening,3 you might want look flumotion wwwflumotionorg it python based streaming server using gstreamer might able get implementation ideas terms application it relies heavily python library twisted network handling,i working audio mixing program daw web app considering using python python gstreamer backend i understand i contain audio tracks single music project gstpipeline bin playback also appears controlled pipeline is possible create several views pipeline representing project so one client grab audio stream pipeline ability time seek if better platformlibrary use i appreciate advice i prefer sticking python though team members already researching python parts project thanks much,1 had dig quite bit solve issue exposed friendly manner pythongearmanapi you however solve creating appropriate instances gearmanjob gearmanjobrequest here small example import gearman client gearmangearmanclient localhost result clientsubmitjob reverse string backgroundtrue you want keep track server got handle job one gearman server handling tasks handle task the connection information available resultjobconnection gearmanhost gearmanport handle available resultjobhandle to check status currently running job create gearmanclient supply server want query current state client gearmangearmanclient localhost configure job request status last four needed status requests j gearmanjobgearmanjobclientconnectionlist resultjobhandle none none none none create job request jr gearmanjobgearmanjobrequestj jrstate created request state gearmand res clientgetjobstatusjr res structure filled status information task printstrresstatusnumerator strresstatusdenominator hopefully helps,i need get status gearman jobs uniq id open handlers desribed every place i seen is possible using pythongearman v thanks assistance,3 debug function take string change take format string arguments debuglambdaworking formatcurrentitem becomes debugworking currentitem debug def debugformat values print formatformatvalues else def debugformat values pass advantages first option without need lambda debug moved function tested containing module loaded overhead statement one function call,python ways printing trace output print import logging stdoutwrite used print debugging info one drawback even logger threshold high stream closed python still evaluate arguments print statement strict evaluation this could cost string format the obvious fix put stringcreating code lambda use logging function call lambda conditionally one checks debug builtin variable set false whenever python started o optimizations def debugf debug print f stdoutwritef loggingdebugf currentitem allitems debuglambdaworking formatcurrentitem the advantage calling strcurrentitem stringformat release builds disadvantage type lambda every logging statement python assert statement treated specially python compiler if python run o assert statements discarded without evaluation you exploit make another conditionallyevaluated logging statement assertloggingdebugworking formatcurrentitem true this line evaluated python started o the shortcircuit operators even used debug loggingdebugworking formatcurrentitem but characters plus code output string the question i getting are standard python statements functions conditionalevaluation properties assert statement or anyone alternatives methods presented,2 you need actually substitute eachkeyword regular expression at moment literally trying match eachkeyword eachkeyword keywords research b eachkeyword b text rei relatedtweetcount print relatedtweetcount relatedtweetcount print text,i want calculate many lines contain word matched keywords i chosen so i coded like eachkeyword keywords eachkeyword text relatedtweetcount print relatedtweetcount relatedtweetcount print text it performed well but problem for example i keyword flu gives flu also influence to solve problem i searched match word examples fixed code like eachkeyword keywords research beachkeywordb text rei relatedtweetcount print relatedtweetcount relatedtweetcount print text but work please help,3 you must pass dict argument aupdate,playlist playlistupdateposition title position title two strings i getting following error typeerror update expected arguments got could please help thanks,2 dictupdate expects dictionary playlist playlistupdateposition title if want set single key use update use bracket notation instead playlistposition title,playlist playlistupdateposition title position title two strings i getting following error typeerror update expected arguments got could please help thanks,3 you update dict another dictionnary could also give iterable tuples key value playlist item value playlistupdateposition title print playlist item value position title playlistupdateitem value print playlist item value position title item value,playlist playlistupdateposition title position title two strings i getting following error typeerror update expected arguments got could please help thanks,3 use playlistposition title playlistupdate used dictionary argument playlistupdateposition title,playlist playlistupdateposition title position title two strings i getting following error typeerror update expected arguments got could please help thanks,1 playlistposition title this way update handy try copy elements one dict another one,playlist playlistupdateposition title position title two strings i getting following error typeerror update expected arguments got could please help thanks,2 looks like googlesearchgoogleparam already returns unicode unicodeu foo utf traceback recent call last file pyshell line module unicodeu foo utf typeerror decoding unicode supported so want result googlesearchgoogleparamencodeutf as side note code expects return utf encoded string point decoding using unicode encoding back using encode using encoding,i problem encoding python i tried different methods i seem find best way encode output utf this i trying result unicodegooglesearchgoogleparam utfencodeutf searchgoogle returns first google result param this error i get exceptionstypeerror decoding unicode supported does anyone know i make python encode output utf avoid error,3 the mapper seems add init method so following mapper statement makes work del pointinit i sure using mapper type thing right idea the mapper likely need primary key order work correctly nametuple currently space,i trying get namedtuple work sqlalchemy avail web search illuminating i new python sqlalchemy i really sure i chasing windmills the basic idea i namedtuple ie pointnamedtuple point x basically creates class pointtuple i correct this works fine first i create objects like ppoint but i create engine etc call mapper i create objects without getting error traceback recent call last file pyshell line module fpoint typeerror init takes exactly argument given any ideas happens does anyone know make namedtuple work sqlalchemy of course i define point class i obsessing making namedtuple work i using python sqlalchemy sqlite engine example i trying something like sqlalchemy import sqlalchemyorm import collections import namedtuple pointnamedtuple point x verbosetrue ppoint dbcreateengine sqlitepointtestdb metadatametadata pointxytable pointxy metadata column integerprimarykeytrue column x integer column integer sqliteautoincrementtrue metadatacreatealldb mmapperpoint pointxy sessionsessionmakerbinddb sessionsession fpoint the main idea i want named collection stuff easily stored database so class bunch init lambda self kw setattrself dict kw going work sqlalchemy i think i create bunch class i know beforehand many ints i want store collection i set i create database i hope i making sense,1 this attempts isolate last two lines string sbr fake ave sbr gotham lower wardbr researchr brbrnbrbr print mgroup fake ave s trimming parentheses probably best left separate line code rather complicating regular expression,alright one bit pain i scraping python trying get address lines poorly tagged html here sample format br fake ave sbr gotham lower wardbr i like retrieve fake ave s gotham any ideas i regex night brain mush edit more detail possible scenarios data arrive sometimes first line sometimes all addresses i seen ave way st although i would prefer use factor selection i certain always way the second third line alphone possible email website what i mind something selects everything nd last line second line three lines first line two phone number selects everything last line parentheses combine nd last line last line adding two i using scrapy acquire html code the address div i want use regex break data appropriate sections now i unable figure edit as per ofir comment i mention i already made expressions isolate phone number parentheses section phone possible email website awwwwwwcomnetorgus parentheses i sure use construct everythingbutthese statement,1 i use following anpnewaxis an alternative perhaps slightly less clear way write thing anone all including version constanttime operations,i like cast numpy ndarray object shape n one shape n the best i come roll tocol function def tocola return areshapeasize but hard believe ubiquitous operation already built numpy syntax i figure i able hit upon right google search find,3 django amazing documentation queryset api httpsdocsdjangoprojectcomendevrefmodelsquerysets get returns exactly queryset if queryset found queryset returned error raised to catch particular error specify except usermultipleobjectsreturned,here thing i model called user attribute counter counts number page access so user already exists i query db user increase counter otherwise create new user i annoying error get method how i surpass requestmethod post form userformrequestpost formisvalid u formsave try obj userobjectsgetuseruuser objcounter objipaddress requestmeta remoteaddr objsave except statisticdoesnotexist ip requestmeta remoteaddr obj useruseruuser counter ipaddressip objsave return status ok else return errors formerrors return status not ok get method here error get returned one user returned lookup parameters,2 i would use slugfield model company user store identifier theoretically need url mapping tables view handles requests extract last part url slug identifying company user store search company user store models given slug stop find object improve speed create auxiliary model like use genericforeignkey relation lakshman prasad suggested in auxiliary model i would use slugfield identifier and use need slugs main models i personally think bad design first i doubt urls restful second work slugs main models unique across three models ensured external mechanism cannot use unique constraint your urlmapping model simply one mechanism it basically stores slugs three models outside models add unique constraint slugfield urlmapping makes sure slugs unique across main models,now i working one url mapping let say i three classes company user store goal urls hierarchy since hierarchy urls i create class urlmapping ensure duplicate name let give concrete problem i class companymodelsmodel companyname modelscharfieldmaxlength urlmapping modelsonetoonefieldurlmapping class usermodelsmodel username modelscharfieldmaxlength urlmapping modelsonetoonefieldurlmapping class storemodelsmodel storename modelscharfieldmaxlength urlmapping modelsonetoonefieldurlmapping class urlmappingmodelsmodel url modelscharfieldmaxlength now visitor access site certain url i match url urlmapping class reverse lookup see type url company user store since user store company different view function possible quickly redirectly corresponding view function quickly using reverse lookup or i add another field urlmapping saying url type the example httpwwwexamplecomlevis handle brandviews httpwwwexamplecomdavid handle userviews httpwwwexamplecommancy handle storeviews in database urlmapping id namelevis id namedavid id namemancy user id namedavid urlmapping brand id namelevis urlmapping store id name mancy urlmapping where urlmapping onetoonefield don know quickly look urlmapping class thank,1 had issue upgrading ubuntu turns apt installed pythonvirtualenv old i removed deb package used pip install instead worked fine pip install virtualenv,newbie kind the day i sudo aptget install pythonvirtualenv and i following instructions virtualenv env and ubuntu like traceback recent call last file usrlocalbinvirtualenv line module pkgresources import loadentrypoint file usrlibpythondistpackagespkgresourcespy line module parserequirementsrequires environment file usrlibpythondistpackagespkgresourcespy line resolve raise distributionnotfoundreq pkgresourcesdistributionnotfound virtualenv what gives,3 i recommend use wxglade design guis it fast effective experience things manually wxglade wxlib widgets suchs checklistctrlmixin listctrlautowidthmixin using combinations class checklistctrl in order able use fill temporarily slot gui available widget pe wxpanel later generating code substitute manually wxpanel instantiation special custom class finally code major problems produce exceptions wxframe wxframe bad indentation undefined testlist your maingui class init method neither initialize parent wxframe also bottompanel added hbox sizer toppanel the organization wrote produce gui structure describe two panels several widgets to closer description need least add couple additional sizers use wxglade everything here wxglade generated code design like substitute wxlistctrl checklistctrl usrbinenv python coding iso generated wxglade hg tue oct import wx begin wxglade extracode end wxglade class mainguiwxframe def initself args kwds begin wxglade mainguiinit kwdsstyle wxdefaultframestyle wxframeinitself args kwds selfbutton wxbuttonself select all selfbutton wxbuttonself deselectall selflistctrl wxlistctrlself stylewxlcreportwxsunkenborder selftextctrl wxtextctrlself stylewxtemultiline selfbutton wxbuttonself refresh selfbutton wxbuttonself execute selftextctrl wxtextctrlself stylewxtemultiline selfsetproperties selfdolayout end wxglade def setpropertiesself begin wxglade mainguisetproperties selfsettitleframe selfsetbackgroundcolourwxcolour selflistctrlsetminsize end wxglade def dolayoutself begin wxglade mainguidolayout sizer wxboxsizerwxvertical sizer wxboxsizerwxhorizontal sizer wxboxsizerwxvertical sizer wxboxsizerwxhorizontal sizeraddselfbutton wxall sizeraddselfbutton wxall sizeradd wxexpand sizeraddsizer wxexpand sizeraddselflistctrl wxallwxexpand sizeraddselftextctrl wxallwxexpand sizeraddselfbutton wxall sizeraddselfbutton wxall sizeraddsizer wxexpand sizeraddsizer wxexpand sizeraddselftextctrl wxallwxexpand selfsetsizersizer sizerfitself selflayout end wxglade end class maingui name main app wxpysimpleapp wxinitallimagehandlers frame mainguinone appsettopwindowframe frameshow appmainloop and look note said answer need putting widgets panels widgetpanel panels sizers it works better simply put widgets child frame widgetself sizers sizerxaddwidget sizers sizers sizeryaddsizerx build structure normally modify code you subclass instead add functionality whatever fancy addition need in way always use wxglade make changes position widgets ot add additional widgets sizers regenerate full file,background as newbie python well gui programming i would like create wxpython based gui application this gui run series tests the tests written text files running steps displayed window for selecting particular testclick checkbox checklistctrl figure particular test the result test displayed mulilinetextctrllog the window like my ascii art good anyways window titlexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxselectallxxxxxxdeselectallxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx checklistctrl multilinetextctrlxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxrefreshxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxexecutexxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxmulilinetextctrllogxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx i trouble creating boxsizers window i trouble visualizing creation panels testlist test testdescription base test testdescription base test testdescription base class checklistctrlwxlistctrl checklistctrlmixin listctrlautowidthmixin def initself parent wxlistctrlinitself parent stylewxlcreport wxsunkenborder checklistctrlmixininitself listctrlautowidthmixininitself class mainguiwxframe panel wxpanelself vbox wxboxsizerwxvertical hbox wxboxsizerwxhorizontal toppanel wxpanelpanel toppanel wxpanelpanel pos bottompanel wxpanelpanel pos selflog wxtextctrlbottompanel stylewxtemultiline selflist checklistctrlbottompanel selflistinsertcolumn testid width selflistinsertcolumn testdescription testlist index selflistinsertstringitemsysmaxint selflistsetstringitemindex selflistsetstringitemindex vbox wxboxsizerwxvertical sel wxbuttontoppanel select all size des wxbuttontoppanel deselect all size refresh wxbuttonbottompanel refresh size apply wxbuttonbottompanel execute size selfbindwxevtbutton selfonselectall idselgetid selfbindwxevtbutton selfondeselectall iddesgetid selfbindwxevtbutton selfonrefresh idrefreshgetid selfbindwxevtbutton selfonexecute idapplygetid vboxaddsel wxtop vboxadddes vboxaddapplywxright vboxaddrefresh toppanelsetsizervbox vboxaddselflist wxexpand vboxadd vboxaddselflog wxexpand vboxadd bottompanelsetsizervbox hboxaddbottompanel wxexpand wxright panelsetsizerhbox selfcentre selfshowtrue def onselectallself event num selflistgetitemcount rangenum selflistcheckitemi def ondeselectallself event num selflistgetitemcount rangenum selflistcheckitemi false def onrefreshself event num selflistgetitemcount rangenum selflogclear selflistischeckedi selflogappendtextselflistgetitemtexti n def onexecuteself event num selflistgetitemcount rangenum selflogclear selflistischeckedi selflogappendtextselflistgetitemtexti n app wxapp mainguinone tester appmainloop,1 just clear use web application flow localhost developing either oauth oauth oauth preferred mechanism focussed the user experience oauth going substantially better there nothing stopping using localhost callback url i time you need make sure callback url matches exactly including port numbers deploy application way obvious reasons installed applications complicated something django possible take advantage fact oauth bearertoken system as long keeping refresh token serverside authenticate application outofband send bearer token installed application your installed application roughly onehour window make calls need repeat process this happen transparently user cases transmission bearer token happen encrypted channel,i started use oauth python django i need google apis i working localhost i register domain urlcallback i read google oauth could used anonymous domain can find i edit i view def authenticationrequest consumerkey xxxxx consumersecret xxxxx scopes httpsdocsgooglecomfeeds client gdatadocsclientdocsclientsource apiapp oauthcallbackurl httpsgetaccesstoken requestmetaget httphost requesttoken clientgetoauthtoken scopes oauthcallbackurl consumerkey consumersecretconsumersecret domain return httpresponseredirect requesttokengenerateauthorizationurlgoogleappsdomaindomain and error sorry reached login page domain using google apps please check web address try registered via httpscodegooglecomapisconsole edit consumerkey xxxxxxxxxxxxxxxxxxxxxxxxxxx consumersecret xxxxxxxxxxxxxxxxxxxxxxxxx scopes httpsdocsgooglecomfeeds domain localhost def authenticationrequest client gdatadocsclientdocsclientsource apiapp oauthcallbackurl httpsgetaccesstoken domain requesttoken clientgetoauthtokenscopes oauthcallbackurl consumerkey consumersecretconsumersecret return httpresponseredirect requesttokengenerateauthorizationurl def verifyrequest client gdatadocsclientdocsclientsource apiapp f open homeisshidrsa rsakey fread fclose oauthcallbackurl httpsgetaccesstoken domain requesttoken clientgetoauthtokenscopes oauthcallbackurl consumerkey rsaprivatekeyrsakey return httpresponseredirect requesttokengenerateauthorizationurlgoogleappsdomaindomain the error unable obtain oauth request token consumer cert xxxxxxxxxxxxxxxappsgoogleusercontentcom,3 the itertools examples provides window function itertools import islice def windowseq n returns sliding window width n data iterable sssn sssn iterseq result tupleisliceit n lenresult n yield result elem result result elem yield result example usage joinx x window,i string digits like digit now i want split string way output moving window digits time so i get how would approach straightforward way put forloop iterate but i feel inbuilt python string function less code know approach,3 sii rangelens,i string digits like digit now i want split string way output moving window digits time so i get how would approach straightforward way put forloop iterate but i feel inbuilt python string function less code know approach,2 you really need extra panels in fact rarely need one except wxnotebooks like instead i find easiest way visualize sort thing sketch piece paper draw rectangles around stuff for i would main boxsizer vertically oriented then i use two horizontal boxsizers buttons next controls if position three single widgets way probably want boxsizers spacers anyway widgets various boxsizers add mainsizer done or could use gridsizer spacers last three,background as newbie python well gui programming i would like create wxpython based gui application this gui run series tests the tests written text files running steps displayed window for selecting particular testclick checkbox checklistctrl figure particular test the result test displayed mulilinetextctrllog the window like my ascii art good anyways window titlexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxselectallxxxxxxdeselectallxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx checklistctrl multilinetextctrlxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxrefreshxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxexecutexxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxmulilinetextctrllogxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx i trouble creating boxsizers window i trouble visualizing creation panels testlist test testdescription base test testdescription base test testdescription base class checklistctrlwxlistctrl checklistctrlmixin listctrlautowidthmixin def initself parent wxlistctrlinitself parent stylewxlcreport wxsunkenborder checklistctrlmixininitself listctrlautowidthmixininitself class mainguiwxframe panel wxpanelself vbox wxboxsizerwxvertical hbox wxboxsizerwxhorizontal toppanel wxpanelpanel toppanel wxpanelpanel pos bottompanel wxpanelpanel pos selflog wxtextctrlbottompanel stylewxtemultiline selflist checklistctrlbottompanel selflistinsertcolumn testid width selflistinsertcolumn testdescription testlist index selflistinsertstringitemsysmaxint selflistsetstringitemindex selflistsetstringitemindex vbox wxboxsizerwxvertical sel wxbuttontoppanel select all size des wxbuttontoppanel deselect all size refresh wxbuttonbottompanel refresh size apply wxbuttonbottompanel execute size selfbindwxevtbutton selfonselectall idselgetid selfbindwxevtbutton selfondeselectall iddesgetid selfbindwxevtbutton selfonrefresh idrefreshgetid selfbindwxevtbutton selfonexecute idapplygetid vboxaddsel wxtop vboxadddes vboxaddapplywxright vboxaddrefresh toppanelsetsizervbox vboxaddselflist wxexpand vboxadd vboxaddselflog wxexpand vboxadd bottompanelsetsizervbox hboxaddbottompanel wxexpand wxright panelsetsizerhbox selfcentre selfshowtrue def onselectallself event num selflistgetitemcount rangenum selflistcheckitemi def ondeselectallself event num selflistgetitemcount rangenum selflistcheckitemi false def onrefreshself event num selflistgetitemcount rangenum selflogclear selflistischeckedi selflogappendtextselflistgetitemtexti n def onexecuteself event num selflistgetitemcount rangenum selflogclear selflistischeckedi selflogappendtextselflistgetitemtexti n app wxapp mainguinone tester appmainloop,1 nothing remote python script able kill loop unless done set e local bash first make sensitive command failure — case would die eol says remote script hitting exception returning nonzeroerror value ssh die nonzeroerror code locally what happens replace srv echo srv get printout commands think running do see several srv command lines get printed arguments expect oh using open allocate new linux virtual terminal every single run command you run virtual terminals way,i using bash script loop configuration file based call python script via ssh unfortunately python script job i call quit bash script also gets closed therefore calling bash script loop terminated prematurely here bash script target grep srv read l srv l ssh done srv ssh srvecho awk f print statusecho awk f print open ssh srv srv status remote machine python script called name main redirect serverlog false conn sysargv srv serverstatesysargv sysargv quit so looks like quit also interrupting script,1 works fine starting server use stop localhostlocaldomain oct get http simplescript localhostlocaldomain oct get http simplescript mon oct mon oct mon oct mon oct mon oct mon oct mon oct mon oct mon oct mon oct mon oct mon oct,my code simple using basehttpserver threadinmix i want run python script scriptpy every request made simultaneously my code subprocess import pipe popen socketserver import threadingmixin basehttpserver import httpserver basehttprequesthandler import time def simplescriptself print simplescript popen cpythonpython cscriptpy shelltrue stdoutpipe stderrpipe err scommunicate print err selfwfilewriteout class handlerbasehttprequesthandler def dogetself selfsendresponse selfendheaders selfwfilewrite n formattimeasctime simplescriptself return class threadedhttpserverthreadingmixin httpserver pass name main server threadedhttpserver handler print starting server use ctrlc stop serverserveforever cscriptpy import time sys timetime true timetime intsysargv break else timesleep print timeasctime i found with url httplocalhost if i open multiple tabsbrowsers ie works just fine but if i open multiple tabspages chrome firefox pages wait previous page this imply threading chrome firefox any help thanks,1 another idea important formatting part if ditch formatting output data csv excel open csv files csv format much simpler excel format simple write directly python like text file way need mess office com objects,i spending better part weekend trying figure best way transfer data ms access table excel sheet using python i found modules may help execsql pythonexcel limited knowledge modules i use create certain data i gis professional i creating spatial data using arcgis arcpy module access table i sure best approach all i need copy columns data access excel format excel i formatting part solved should i iterate rows using cursor somehow load rows excel copy columns access excel export whole access table sheet excel thanks suggestions,1 yes since methods bound methods objects in code forgot function i think wanted write somthing like class someclass def initself selfmystring hello selfmymap somestring selffunctioninclass def functioninclassself pass,in words giving errors purely impossible actually i writing wrong class someclass selfmystring hello selfmymap somestring selffunctioninclass so functioninclass takes argument i want call like anywhere inside class selfmymapselfmystringtheargument this yields nameerror name self defined any help would appreciated,2 there good recipe pairwise itertools docs modernizing bit n elements group i made code itertools import tee izip def windowiterable n els teeiterable n el enumerateels xrangei nextel none return izipels printjoini window python,i string digits like digit now i want split string way output moving window digits time so i get how would approach straightforward way put forloop iterate but i feel inbuilt python string function less code know approach,2 this perfectly valid def f print test df f df test this test code use class thing done class the error shows self defined nothing functions dictionary,in words giving errors purely impossible actually i writing wrong class someclass selfmystring hello selfmymap somestring selffunctioninclass so functioninclass takes argument i want call like anywhere inside class selfmymapselfmystringtheargument this yields nameerror name self defined any help would appreciated,1 why basesubclass inherit so based example class basesubclassmodelsmodel base genericgenericrelationbase class meta abstract true property def baseself return selfbaseall class subclassbasesubclass fields,i trying emulate inheritance model using django generic relations so far i come class basemodelsmodel contenttype modelsforeignkeycontenttype objectid modelspositiveintegerfield contentobject genericgenericforeignkey stuff class meta uniquetogether contenttype objectid class subclassmodelsmodel properties class base genericgenericrelationbase property def baseself return selfbaseall from see hopefully least subclass onetoone relationship base i went work creating base field covering base property having generic relation automagically wire cascading deletes i want i postdelete signal wire delete direction there could number subclasses base thing makes feel gross copyamppaste base covering property i also got custom object manager goes potentially things essentially behave within subclass base is good way go encapsulating common functionality i copyamppaste sub class,1 i see authentication attributes connection strings try i using windows authentication conn pyodbcconnect trustedconnectionyes driver sql server server localhost database test cursor conncursor assuming tags table dbo schema cursorexecuteselect from dbotags,i local db machine called test contains table called tags i able access db query table sql server management studio however using pyodbc i keep running problems using conn pyodbcconnect driversql serverserverlocalhostdatabasetest yields error pyodbcerror microsoftodbc sql server driverdbnetlibinvalid connection sqldriverconnectw microsoftodbc sql server driverdbnetlibconnectionopen invalid instance without specifying port trying alternative connection string conn pyodbcconnect driversql serverserverlocalhosttest yields error cur conncursor curexecuteselect from tags yields error pyodbcprogrammingerror s s microsoftodbc sql server driversql serverinvalid object name tags sqlexecdirectw why could thanks,1 i think could done i done quick search sla documentation api register broadcast receiver and android widgets bunch views code broadcastreceiver and far i know sla way use python android ui interaction,is way make widgets python android i mean i know python html dom js maybe jquery nothing c java something maybe simple i honestly searched stackoverflow search returned answers help please give hope,1 please check links httpcodegooglecompandroidscripting httpgoogleopensourceblogspotcomintroducingandroidscriptinghtml remember python implementation jvm called jython edit in terms android development say jythonroid,is way make widgets python android i mean i know python html dom js maybe jquery nothing c java something maybe simple i honestly searched stackoverflow search returned answers help please give hope,1 how following in join randomrandom else xrange out this gives tencharacter binary string chopping leading zeroes if need vary digit probability slightly concise version in joinrandomchoice xrange out,for reason i heck time figuring python i trying represent binary string string variable i want however matter i try format string python always chops leading zeroes giving headache trying parse i hoped question would helped really is way force python stop autoconverting string integer i tried following val randomrandom val val else val val val randomrandom val val else val val i stuck array previously ran issues inserting array another array i figured would easier parse string any thoughts get leading zeroes back the string supposed fixed length bits helps edit the code def createstringx xrange random populations j xrangeintx population size v joinchoice range arrij v return arr createstring print hopefully output i seeing show i issues the issue printing i also need able manipulate perelement basis so i go play first element returns first element,1 if i understood right could way b b formata the output python it uses string format method this answer want represent binary string leading zeros if trying generate random string binary could way random import choice joinchoice range update unswering update i made code different output compared random import choice pprint import pprint arr def createstringx xrange random populations arrappend j xrangex population size v joinchoice range arrappendv return arr createstring pprinta the output is looking,for reason i heck time figuring python i trying represent binary string string variable i want however matter i try format string python always chops leading zeroes giving headache trying parse i hoped question would helped really is way force python stop autoconverting string integer i tried following val randomrandom val val else val val val randomrandom val val else val val i stuck array previously ran issues inserting array another array i figured would easier parse string any thoughts get leading zeroes back the string supposed fixed length bits helps edit the code def createstringx xrange random populations j xrangeintx population size v joinchoice range arrij v return arr createstring print hopefully output i seeing show i issues the issue printing i also need able manipulate perelement basis so i go play first element returns first element,3 i highly suggest using something like python standard library curses module don reinvent wheel using existing library help avoid corner cases also save time plus curses interface familiar one nix users make like,i writing python script print displayable user interface the problem every linux user would unique terminal size this cause hardcoded user interface go format if lot example terminal looks crazy example script i print print format goes well terminal when terminal smaller print format run format become so i thinking when user run script i auto change linux terminal size declare size can i get width length user terminal size using python terminal display flexible i would like hear better solution around world solve terminal display problem i would strongly prefer recommendation python,3 as amber suggested use library like curses still could get width terminal using something like import subprocess intsubprocesspopen tput cols stdoutsubprocesspipestdoutread,i writing python script print displayable user interface the problem every linux user would unique terminal size this cause hardcoded user interface go format if lot example terminal looks crazy example script i print print format goes well terminal when terminal smaller print format run format become so i thinking when user run script i auto change linux terminal size declare size can i get width length user terminal size using python terminal display flexible i would like hear better solution around world solve terminal display problem i would strongly prefer recommendation python,1 perhaps could speed maintaining indexes keys essentially something like selfindices would contain set keys third position key then could simply set intersection relevant index entries get set keys matchingkeys none rangeselforder keywordsi none matchingkeys none matchingkeys selfindicesikeywordsi else matchingkeys amp selfindicesikeywordsi matchingkeys listmatchingkeys matchingkeys else,i dictionary uses tuple key i need find keys dictionary partially match tuple i code slow needs optimizing here i keys match none none result current code def gettuplesself keywords tuples k selfchainiterkeys match true rangeselforder keywordsi none keywordsi ki match false break match true tuplesappendk return tuples keywords list containing values i want match selfchain dictionary selforder size tuple lenkeywords always lenk none considered wild card the dictionary pretty huge method taking ms run mb space also consideration i basically looking either optimizations method better way storing data,2 two options you could try using subprocess call system ls du command aware extended attributes you could install xattr package read resource fork addition extended attributes accessed via xattrxattrresourceforkname something like might work import xattr x xattrxattrpathtomyfile size attribute x size lenxattribute print size you might need play around little format extended attributes returned strings might binary if provide minimal almost working example code i might able play little,i written small utility creating xml folder structure comparison folders via generated xml supports win mac platforms however mac recursively calculating folder size adds total size on investigation came due extended attributes resource forks present certain files can anybody know i determine extended attributes resource forks size preferably python currently i using ospathgetsize determine size file adding files size determine folder size eventually,1 riffing amber answer collections import defaultdict index defaultdictlambdadefaultdictset keys key keys val enumeratekey indexivaladdkey def matchgoal res val enumerategoal val none resappendindexival return reducesetintersection res match none none set,i dictionary uses tuple key i need find keys dictionary partially match tuple i code slow needs optimizing here i keys match none none result current code def gettuplesself keywords tuples k selfchainiterkeys match true rangeselforder keywordsi none keywordsi ki match false break match true tuplesappendk return tuples keywords list containing values i want match selfchain dictionary selforder size tuple lenkeywords always lenk none considered wild card the dictionary pretty huge method taking ms run mb space also consideration i basically looking either optimizations method better way storing data,1 what using database i prefer sqlite sqlalchemy even simple projects plain sqlite might gentler learning curve putting index key column take care speed issues,i dictionary uses tuple key i need find keys dictionary partially match tuple i code slow needs optimizing here i keys match none none result current code def gettuplesself keywords tuples k selfchainiterkeys match true rangeselforder keywordsi none keywordsi ki match false break match true tuplesappendk return tuples keywords list containing values i want match selfchain dictionary selforder size tuple lenkeywords always lenk none considered wild card the dictionary pretty huge method taking ms run mb space also consideration i basically looking either optimizations method better way storing data,2 for d graphics might want use opengl game framework pygame pyglet use matplotlib tjd suggested answer as gui frameworks generally help much d graphics pyqt one choice i see already question tags pyside similar pyqt nicer licence then tkinter standard library wxpython pygtk – i hear good though i know personally pick one stay it take time learn experienced expect results soon,i project i show sort changing bar graph results function this bar graph colour i want look good since open source educational program teaches user different voting systems effect outcome election i would like use python i idea using gui frameworks since work python command line based your help appreciated,2 you might want look matplotlib probably widely used library graphs including d,i project i show sort changing bar graph results function this bar graph colour i want look good since open source educational program teaches user different voting systems effect outcome election i would like use python i idea using gui frameworks since work python command line based your help appreciated,1 that command prints sql statements if want create schema sqlite file run python managepy syncdb if trying export sql statements text file python managepy sql myapp myfilesql,i trying run first django application sqlite database when i run python managepy sql myapp outputs sql queries sqlite file empty what could reason,1 the profiler receives string tries interpret your string profilerun factintx print x variable inside part string cannot resolved variable you copy value string make work try profilerun factints print x profilerun factmemoizedints print x,i wrote couple modules python generating factorials i want test running time i found example profiling i used template profile modules import profile fact def main x rawinputenter number profilerun factintx print profilerun factmemoizedintx print def factx x return elif x return x else return x factx def factmemoizedx x return elif x return x dict dict dict dict range x dicthaskeyi pass else dicti dicti return dictx name main main however i get following error enter number traceback recent call last file factpy line module main file factpy line main profilerun factintx x file cpythonlibprofilepy line run prof profrunstatement file cpythonlibprofilepy line run return selfrunctxcmd dict dict file cpythonlibprofilepy line runctx exec cmd globals locals file string line module nameerror name x defined any idea i wrong tia craig,3 edit removed answer petr viktorin makes much better sense but leaving explanation work op expected looking code profilepy python i see following methods class profile def runself cmd import main dict maindict return selfrunctxcmd dict dict def runctxself cmd globals locals selfsetcmdcmd syssetprofileselfdispatcher try exec cmd globals locals finally syssetprofilenone return self the exec statement runctx fed maindict global local dictionaries profilerun able resolve variables defined top level dictionary running app,i wrote couple modules python generating factorials i want test running time i found example profiling i used template profile modules import profile fact def main x rawinputenter number profilerun factintx print profilerun factmemoizedintx print def factx x return elif x return x else return x factx def factmemoizedx x return elif x return x dict dict dict dict range x dicthaskeyi pass else dicti dicti return dictx name main main however i get following error enter number traceback recent call last file factpy line module main file factpy line main profilerun factintx x file cpythonlibprofilepy line run prof profrunstatement file cpythonlibprofilepy line run return selfrunctxcmd dict dict file cpythonlibprofilepy line runctx exec cmd globals locals file string line module nameerror name x defined any idea i wrong tia craig,2 as john gaines jr said profilerun scoping problems however use runctx globals locals provide context explicitly profilerunctx factintx print globals locals explicit better implicit,i wrote couple modules python generating factorials i want test running time i found example profiling i used template profile modules import profile fact def main x rawinputenter number profilerun factintx print profilerun factmemoizedintx print def factx x return elif x return x else return x factx def factmemoizedx x return elif x return x dict dict dict dict range x dicthaskeyi pass else dicti dicti return dictx name main main however i get following error enter number traceback recent call last file factpy line module main file factpy line main profilerun factintx x file cpythonlibprofilepy line run prof profrunstatement file cpythonlibprofilepy line run return selfrunctxcmd dict dict file cpythonlibprofilepy line runctx exec cmd globals locals file string line module nameerror name x defined any idea i wrong tia craig,3 stepbystep answer similar one refer using new cv python bindings read grayscale image import cv imgray cvimread grayscaleimagepng cvcvloadimagegrayscale convert grayscale image binary thresh imbw cvthresholdimgray cvthreshbinary cvthreshotsu determines threshold automatically image using otsu method already know threshold use thresh imbw cvthresholdimgray thresh cvthreshbinary save disk cvimwrite bwimagepng imbw,how convert grayscale opencv image black white i see similar question already asked i using opencv proposed solution longer seems work i trying convert greyscale image black white anything absolutely black white use mask surfdetect order ignore keypoints found edge black mask area the following python gets almost threshold value sent threshold appear effect if i set result pixels value becoming white everything else becoming black what i wrong import cv cv fn myfilejpg imgray cvimreadfn cvcvloadimagegrayscale imgraymat cvfromarrayimgray imbw cvcreateimagecvgetsizeimgraymat cvipldepthu imbwmat cvgetmatimbw threshold has no effect cvthresholdimgraymat imbwmat threshold cvcvthreshbinary cvcvthreshotsu cvimshow npasarrayimbwmat cvwaitkey,3 for came looking way detect cygwin python opposed detecting windows example return values osname platformsystem different platforms osbuild osname platformsystem win native nt windows win cygwin posix cygwinnt win native nt windows win cygwin posix cygwinntwow linux posix linux from point distinguish windows native cygwin obvious although i convinced future proof version numbers xp win respectively rely,i working couple linux tools need prevent installation windows since depends fhs thus rendered useless platform the platformplatform function comes close returns string unfortunately i know search string yield reliable result does anyone know search anyone know another function i missing,3 redefinition class nothing original class assigns whole new class name checking easy – save original see name still refers class someclassobject x save original mysavedclass someclass class someclassobject x check someclass mysavedclass print someclass redefined,i looking way somehow detect python function class redefined even defined twice one definition erases can done reflection somehow maybe function class somehow,2 have looked pyserial it years since i used quite good handling rs communications looks like compatible python x,i testing piece hardware hosts ftp server i connect server order configure hardware question my test environment written python to start ftp server i need launch special proprietary terminal application pc i must use software far i know i help files i however know use launch ftp server i need when i start app i go menu open dialog i select com portspeed hardware connected i enter command launch ftp server console like window within application i prompted admin code hardware i enter when i finished configuring device i issue command restart hardware software in order fully automate tests i need remove manual starting ftp server test as far i know i two options windows gui automation save stream data sent com port using application i tried find gui automater pywinauto supporting python any options i look any suggestions i monitor com port question save traffic thanks barry,1 use b entity regular expressions match word boundaries researchr bthis isb i think isnt right,i trying search whole words string sure str str i think isnt right str str gives true i want return false how i thank i tried strfindstr researchstrstr i getting return nothing false please help thanks,2 if install python etc inside wine cxfreeze run misses key dlls so if building windows option work dlls requires manually copy build directory running cxfreeze technical note if anyone knowhow work wine i believe bindimageex function imagehlpdll needs implemented work,is possible cxfreeze tool purpose cross build binaries ie build windows binary linux pc or much ask i tried cxfreeze got following cxfreezefreezerconfigerror base named wingui thanks,1 another way using sets without regular expression set issubsetset i think isnt right split if string really long going keep evaluating words set could efficient for example words set i think isnt right split words set i isnt right think words true words false,i trying search whole words string sure str str i think isnt right str str gives true i want return false how i thank i tried strfindstr researchstrstr i getting return nothing false please help thanks,1 if string use split separate string mike kevin angel l stringsplit print reprl reprintl mike kevin angel,here input specification the program read lines inputs each line consist space separated values first one name second age an example input mike kevin angel how read kind input python if use rawinput name age read variable update i going respecify question we already know read formatted input python is way read formatted input python if yes,3 thestring rawinput name age thestringsplit,here input specification the program read lines inputs each line consist space separated values first one name second age an example input mike kevin angel how read kind input python if use rawinput name age read variable update i going respecify question we already know read formatted input python is way read formatted input python if yes,3 you want sort list yourlistsort,following program used sort list rangelenq j rangelenq qi qj qi qi qj qj contents q the output i get one empty number like ie extra number empty what i wrong,2 this error bad local file header seems say file header usually determines filetype passing python test it could zipping program used try zip free different program creating egg i made i think even way plain ol python,i created two eggs using bdist egga defines dependency eggb i check egg using command unzip ok however i try insall egg using easyinstall i get following stack trace installed cvirtualenvlibsitepackagespymarketdatapyegg reading filecpythonnest processing dependencies pymarketdata zipimportzipimporterror bad local file header cyoanyoyolibsitepackagespymarketdatapyegg any idea could come,1 call method schedule command run future it perfectly legal command also call schedule run future for example shows label getting text updated every second see answer another question so,i currently using pil tkinter display images i streaming images network want update window automatically come much like picture slideshow my code displaying images works however click x button display window photo update i want window automatically update new photo comes least run loop like every seconds window either closes new photo appears photo changes window my code i database photos want display one one imimageopencurrentphoto roottk canvas photoimagetkphotoimageim itemcanvascreateimageanchornwimagephoto rootmainloop want display next photo either comes every seconds whichever easier first method preferred this code works,1 you correct getpixel accept integer coordinates you linear interpolation mind slow def lerpa b coord isinstancea tuple return tuplelerpc coord cd zipab ratio coord mathfloorcoord return introunda ratio b ratio def bilinearim x x intfloorx intfloory x x left lerpimgetpixelx imgetpixelx right lerpimgetpixelx imgetpixelx return lerpleft right x a robust implementation bilinear would also include bounds checking coordinates go image,i read image python using image module converted numpy array follows imimageopeninfile imdata scipymiscfromimageim after processing i get integer coordinates real values it important note rgb image i want get color value bilinearly interpolated value there method image imgetpixelxy i sure give real values coordinates if numpy array bilinear interpolation separate every channel i correct thanks,2 fromimage docs state returned numpy array dimension width height nrchannels nrchannels different colour bandschannels stored third dimension greyimage mxn rgbimage mxnx rgbaimage mxnx get pixel x indeed rowx heighty array would pix axy eg rgb pix imgetpixel gets pixel location xy tupleeg rgb image rgb bands note method rather slow need process larger parts image python either use pixel access objects retried via imload imgetdata method,i read image python using image module converted numpy array follows imimageopeninfile imdata scipymiscfromimageim imgetpixelxy first question x belong row number column number is visual order see screen order saved disk something else how work accessing pixels values using numpy array does give pixel imgetpixel different pixel location third question saving image disk eg png what order accessing writing files thanks lot thanks,1 try def fetchweb name par â â fetch web data defined name return string web page â â name granska â â â â url httpskruttennadakthsescrutsvesve â â â â values textparxmloutonxgranskaurl â â â â code iso â â data urllibparseurlencodevalues â â data dataencodecode fullurl ss url data â â req urllibrequestrequestfullurl â â response urllibrequesturlopenreq â â page responseread â â return pagedecodeiso print fetchwebgranskag㥠there may issues caused lack file name end url i experienced thing past several scrips add url post data trailing end url i think bug urllibrequest class since i found workaround i putting looking bug report exists also name granska going get exception url values undefined variables used data lines,if i enter url i get xml formatted text response httpskruttennadakthsescrutsvesvetextgeampurlampxmloutonampxgranska now i try write python function post message web page i get information however i getting less information web page it seems data seentext i get error messages for instance i sure i handling coding correct way i tried utf difference any suggestions misstake def fetchweb name par fetch web data defined name return string web page name granska url httpskruttennadakthsescrutsvesve values textparxmloutonxgranskaurl code iso data urllibparseurlencodevalues data dataencodecode req urllibrequestrequesturldata response urllibrequesturlopenreq page responseread return pagedecodeiso print fetchwebgranskagã¥,2 import datetime jan jan jan jan jan jan row ssplit n prefix row sdate row suffix row sdate offset datetimetimedelta sdate sdate sdate else offset datetimetimedelta dt datetimedatetimestrptimesdate b y hm offset print prefix dtstrftime dmy hms suffix result,i hydrologic model text file output exporttxt looks like units cfs type instval jan jan jan jan jan and python coded following format input optimization process import oopencdocuments settingscmjawdydesktoppyouttxtw dataopencdocuments settingscmjawdydesktopexporttxtread stepresubdata stepresub jan step stepresubstep findidsrecompilesrem stepresubfindidssitexxx step owritestep oclose yielding units cfs type instval sitexxx sitexxx sitexxx sitexxx sitexxx the problem optimization software take hour rather must take hour following day so i need convert day x day x maintaining format it looks though strptimestrftime take either these absolute first lines computer language i find elegant way convert text,2 assuming space integer words regluar python list asortkey lambda intssplit not sure equivalent numpy see specify key one possibility convert list back array,i problem sorting numpy array numbers strings i need keep strings words integers it sorting negative numbers reverse order import numpy np nparray asort array dtype s i would expected output array dtype s any suggestions,1 you could use natural sorting import numpy np import def atoitext try return inttext except valueerror return text def naturalkeystext alistsortkeynaturalkeys sorts human order httpnedbatcheldercombloghumansortinghtml return atoic c resplit text nparray word printsortedakeynaturalkeys word nparray word word printsortedakeynaturalkeys word word,i problem sorting numpy array numbers strings i need keep strings words integers it sorting negative numbers reverse order import numpy np nparray asort array dtype s i would expected output array dtype s any suggestions,3 instead using shebang first bytes file usrbinpython use shebang usrbinenv python edit i second noufal suggestion use virtualenv,on centos server i python required yum work i sure happened suddenly system gets confused every time i try run file whose modules loaded sitepackages directory i checked pythonpathsyspath looks like everything overwritten environment data instead it used i simply declared usrbinpython usrbinpython shebang statement beginning script always found correct modules fine is way pythonpath variable dynamic load different paths based python interpreter running otherwise i going manually edit path every application seems like overkill it started installing webpy i love way traceback as someone commented i changed shebang usrbinenv python program traceback recent call last file usrbinlinkchecker line import codecs file usrlibpythoncodecspy line return b another example trying use yum traceback recent call last file usrbinyum line import yum file usrlibpythonsitepackagesyuminitpy line import os file usrlibpythonospy line bs b i noticed couple programs confounded b syntax programs meant use reason using if i try make program use interpreter able understand syntax find modules sitepackages directory i know syntax written modules i got sourceforge however working last week i sure changed thanks tom,1 it seems like might trying write data subprocess via stdin well read output via stdout interactively as mentioned answer so question nono you could use popencommunicate blocking call wait communication finish poll example,very puzzled when using popen using stdout stderr following code works def runself selfexternalprocess subprocesspopen externalprocessout amp shelltrue stderrsubprocesspipe selfexternalbinarypoll none print still running print done running i using stderr file descriptor i monitoring process output real time gui stderr unbuffered see question background mess python capture stdout subprocess line line the problem i soon i add stdin allow user input passed external process starts acting though stdout buffered def runself selfexternalprocess subprocesspopen externalprocessout amp shelltrue stderrsubprocesspipe stdinsubprocesspipe selfexternalbinarypoll none print still running print done running my question stdin appear affecting stdout stderr,1 first use virtualenv isolate packages multiple python installations most problems go away immediately second ibp recommended answer change shebang line use currently active python binary work across multiple interpreters,on centos server i python required yum work i sure happened suddenly system gets confused every time i try run file whose modules loaded sitepackages directory i checked pythonpathsyspath looks like everything overwritten environment data instead it used i simply declared usrbinpython usrbinpython shebang statement beginning script always found correct modules fine is way pythonpath variable dynamic load different paths based python interpreter running otherwise i going manually edit path every application seems like overkill it started installing webpy i love way traceback as someone commented i changed shebang usrbinenv python program traceback recent call last file usrbinlinkchecker line import codecs file usrlibpythoncodecspy line return b another example trying use yum traceback recent call last file usrbinyum line import yum file usrlibpythonsitepackagesyuminitpy line import os file usrlibpythonospy line bs b i noticed couple programs confounded b syntax programs meant use reason using if i try make program use interpreter able understand syntax find modules sitepackages directory i know syntax written modules i got sourceforge however working last week i sure changed thanks tom,1 sudo allows limit arguments passed program from man sudoers john alpha usrbinsu usrbinsu root on alpha machines user john may su anyone except root allowed specify options su command so use sudo of course need extra careful root access – make sure root modify script parent directories script safe absolute minimum needs run root,i quick one task python script i like call django www user going need root privileges at first i thought i would could use python osseteuid set setuid bit script i realized i would set setuid bit python i assume big from i tell would also case using sudo i really would like avoid at point i considering writing c wrapper uses seteuid calls python script root passing necessary arguments is correct thing i looking something else,1 the correct thing called privilege separation clearly identify minimal set tasks done elevated privileges write separate daemon much limited possible way communicating task run daemon another user elevated privileges a bit work also secure edit using setuidable wrapper also satisfy concept privilege separation although i recommend web server chrooted mounting chrooted file system nosuid would defeat,i quick one task python script i like call django www user going need root privileges at first i thought i would could use python osseteuid set setuid bit script i realized i would set setuid bit python i assume big from i tell would also case using sudo i really would like avoid at point i considering writing c wrapper uses seteuid calls python script root passing necessary arguments is correct thing i looking something else,2 sudo require setuid bit python you enable sudo one command arguments www allall nopasswd rootbinreloadstuffpy this would secure script take arguments cannot overridden www user sudo envreset default distros you accept arguments careful take output filenames make sure verify inputs in case remove end sudo line,i quick one task python script i like call django www user going need root privileges at first i thought i would could use python osseteuid set setuid bit script i realized i would set setuid bit python i assume big from i tell would also case using sudo i really would like avoid at point i considering writing c wrapper uses seteuid calls python script root passing necessary arguments is correct thing i looking something else,3 i wonder much call loggingdebug impacts performance handlers however debug statement evaluated even body function python o python r dec gcc linux type help copyright credits license information import dis import logging def debuga kw debug loggingdebuga kw disdisdebug loadconst none returnvalue logger format message using string formatting operator here slightly modified example taken loggingdebug documentation format asctimes clientips users messages loggingbasicconfigformatformat clientip user fbloggs debug protocol problem connection reset extrad in case message string never evaluated optimizations turned,python ways printing trace output print import logging stdoutwrite used print debugging info one drawback even logger threshold high stream closed python still evaluate arguments print statement strict evaluation this could cost string format the obvious fix put stringcreating code lambda use logging function call lambda conditionally one checks debug builtin variable set false whenever python started o optimizations def debugf debug print f stdoutwritef loggingdebugf currentitem allitems debuglambdaworking formatcurrentitem the advantage calling strcurrentitem stringformat release builds disadvantage type lambda every logging statement python assert statement treated specially python compiler if python run o assert statements discarded without evaluation you exploit make another conditionallyevaluated logging statement assertloggingdebugworking formatcurrentitem true this line evaluated python started o the shortcircuit operators even used debug loggingdebugworking formatcurrentitem but characters plus code output string the question i getting are standard python statements functions conditionalevaluation properties assert statement or anyone alternatives methods presented,1 sha hashing algorithm hashing oneway means recover input output nontrivial hash function this picture demonstrates hashing somewhat as see john smith sandra dee mapped this means recover name hashed given hashing used basically due principle if hasha hashb really good chance a b hashing maps large data sets like whole database tiny output like character string if move database hash input output pretty sure database intact that seen image the long names mapped digit numbers,i cant find decode string encoded sha i suprised find simple function python docs google sha decoding i give i need help,3 the results database string list tuples what probably want build list ids check numeric value list for example fileids row row cursorfetchall isinlist testid fileids isinlist print true,i writing script run every minutes looks files download i want check i already dowloaded file first code executes command cursorexecuteselect fileid from reports fileids listcursorfetchall fileids longer version i wrote function check i already downloaded file def newfilefile file file file fileids print true else print false when i try test function file newfilefile it prints false consistently what i wrong i know i could run mysql statement fileid see i file already since thousands files check i assumed would faster if i wrong please feel free correct,1 shapely provides nice api import shapely shapelywkt import dumps loads pt loads point pt shapelygeometrypointpoint object xd dumpspt point pt shapelygeometrypointpoint dumpspt point,i get easily latlong pair google maps api googlemaps import googlemaps gmaps googlemapsgooglemapsapikey gmapsaddresstolatlng jose javier diaz cordoba argentina and i model like django import models class maappointmodelsmodel geom modelspointfieldsriddefaultsrid but i find way get wkt latlng returned gmaps any pointer,2 i sure i understand asking might missing something your posted code replete syntax errors undefined functions however i think asking different results operator import mul a apple bear crab b apple bear crab c areducemulareducemulb ab zipab c apple bear crab additionally or i dropped matrix b altogether c apple row would equal proda areducemula a proda apple bear crab and how would i modify obtain product row a element divided paired b element ie c apple row would equal apple abyb xij ij x x zipab ab zipab abyb apple bear crab prodabyb xreducemulx x abyb prodabyb apple bear crab each value row a divided b product row product row a divided product row b,i trying build specific list comprehension take data list listsmatrix a matrix b generate third matrix c i annotated code provided expected outcome written list comprehension expected expressed elegant code i attempted xttransposed matrix x xssorted matrix x matrix a row headings values a apple bear crab matrix b row headings values b apple bear crab transpose matrix a b atzipa btzipb generate new empty matrix c give heading labels a b ctat delete heading labels transposed matrices a b del at del bt list comprehension code multiply numbers row x ie apples matrix a apple product a multiply numbers row x matrix b apple product b a matrix row x product b matrix row x product b apple value matrix c append apple value apple heading bear rows crab rows ctappendprodx x zipatprodx x zipbt untranspose matrix c match heading value configuration original matrices czipct sort matrix c rows descending order based comprehension values cs matrixsortedc keylambda item item reversetrue the final output look like matrix cs based current values matrix a b apple matrix a apple row product matrix b apple row product crab matrix a crab row product matrix b cat row product bear matrix a bear row product matrix b bear row product,1 how far back need to fetch historical data might want keep stream indefinitely stream api allows store stream locally retrieve historical data db i also use tweepy live streamfiltering works well the latency typically tweepy able handle large volume streams,i need fetch twitter historical data given set keywords twitter search api returns tweets days old i currently using tweepy library httpcodegooglecomptweepy call streaming api working fine except fact slow for example i run search goog sometimes takes hour two results there definitely tweets containing keyword returning result fast enough what problem is streaming api slow problem method accessing is better way get data free cost,1 another python executable must path are sudo python file usrbinenv python line anything try python v python figure python actually using are running venvbinpython,i created new virtual environment virtualenv nositepackages venv pythonpython then i activate virtual environment install packages source venvbinactivate pip install termcolor python termcolor this works fine i install project called hermes uses termcolor python setuppy install but i run executable installed virtualenv bin directory i get error importerror module named termcolor how i install termcolor,1 using csv module import csv ids vals open tmptestcsv w f writercsvwriterf delimiter lineterminator n writerwriterow ids irow enumeratezipitervals writerwriterowirowi this creates lower triangular matrix the grouper recipe zipitervals used group vals tuples,i using python write comparison value mentioned ids vals ids idnumber int chemical compounds derived database vals comparison values others i want ids vals to be written into a csv file like only upper or lower tringular matrix wriiten into csv will be better,3 may answer looking i used lxml requests libraries together automated anchor fetching relevant lxml examples httplxmldelxmlhtmlhtmlexamples replace urllib requests and requests library homepage httpdocspythonrequestsorgenlatestindexhtml it compact mechanize offer control,i browser instance opened page i would like download save links pdfs does someone know thx,1 i realise sender optional parameter connect i following def presavehandlerkwargs instance kwargs instance hasattrinstance presave instancepresave presaveconnectpresavehandler this allows write per model presave methods turn call base class versions exists any better solutions,in following sample code djangodb import models djangodbmodelssignals import presave create models class parentmodelsmodel name modelscharfieldmaxlength def saveself kwargs print parent save superparent selfsavekwargs def presaveparentkwargs print presaveparent presaveconnectpresaveparent parent class childparent color modelscharfieldmaxlength def saveself kwargs print child save superchild selfsavekwargs def presavechildkwargs print presavechild presaveconnectpresavechild child presaveparent fire i child created child modelschildobjectscreatecolorred is expected behaviour,1 import urllib urllibcookielib httpwwwcrummycomsoftwarebeautifulsoup required beautifulsoup import beautifulsoup host httpswwwadobecom cj cookielibcookiejar opener urllibbuildopenerurllibhttpcookieprocessorcj req openeropen host pdf responce reqread soup beautifulsoup responce pdfs soupfindallname attrs href recompile pdf pdf pdfs https pdf href url host pdf href else url pdf href try httpdocspythonorglibraryurllibhtmlurlliburlretrieve urlliburlretrieveurl except exception e print cannot obtain url url print href pdf href print e else print downloaded file print url,i browser instance opened page i would like download save links pdfs does someone know thx,2 there open ticket your workaround looks fine here two others suggested ticket benbest alexr respectively listen child class signal send parent signal def callparentpresavesender instance created kwargs presavesendsenderparent instanceparentobjectsgetidinstanceid createdcreated kwargs presaveconnectcallparentpresave senderchild do specify sender connecting signal check subclasses parent def presaveparentsender kwargs isinstanceinstance parent return normal signal stuff print presaveparent presaveconnectpresaveparent,in following sample code djangodb import models djangodbmodelssignals import presave create models class parentmodelsmodel name modelscharfieldmaxlength def saveself kwargs print parent save superparent selfsavekwargs def presaveparentkwargs print presaveparent presaveconnectpresaveparent parent class childparent color modelscharfieldmaxlength def saveself kwargs print child save superchild selfsavekwargs def presavechildkwargs print presavechild presaveconnectpresavechild child presaveparent fire i child created child modelschildobjectscreatecolorred is expected behaviour,3 the way i found get dynamic feedbackoutput child process use something like pexpect usrbinpython import pexpect cmd foosh thread pexpectspawncmd print started cmd cpl threadcompilepatternlistpexpecteof waited true threadexpectlistcpl timeoutnone eof print sub process exited break elif waitedtime threadmatchgroup print sub process waited seconds intwaitedtime threadclose called sub process foosh waits random amount time seconds code binsh n n gt nsdate n pexpr ns sleep p echo waited p nexpr n done you want use regular expression matches output getting ffmpeg kind calculation show progress bar least get unbuffered output ffmpeg,i looked number questions still quite figure i using pyqt hoping run ffmpeg filemp fileavi get output streams i create progress bar i looked questions can ffmpeg show progress bar httpstackoverflowcomquestionscatchingstdoutinrealtimefromsubprocess i able see output rsync command using code import subprocess time os sys cmd rsync vaz p source dest p line true start p subprocesspopencmd shelltrue bufsize stdinsubprocesspipe stderrsubprocesspipe stdoutsubprocesspipe line pstdout printoutput strlinerstrip pstdoutflush but i change command ffmpeg filemp fileavi i receive output i guessing something stdout output buffering i stuck read line looks like frame fps q lsize kb time bitratekbitss which i could use figure progress can someone show example get info ffmpeg python without use pyqt possible edit i ended going jlp solution code looked like usrbinpython import pexpect cmd ffmpeg filemts fileavi thread pexpectspawncmd print started cmd cpl threadcompilepatternlist pexpecteof frame true threadexpectlistcpl timeoutnone eof print sub process exited break elif framenumber threadmatchgroup print framenumber threadclose elif unknownline threadmatchgroup print unknownline pass which gives output started ffmpeg filemts fileavi frame frame frame frame frame frame frame frame frame frame frame frame frame frame sub process exited perfect,3 i use openssl direct wrapper around library like ruby openssl library openssl powerful trusted toolkit additional advantage call way scripting language using openssl commandline tools advantage interact commandline help debug script also manually generate certs outside script using ca,i looking librarymodulepackage i could create sign x certificates ability conditionally add custom v extensions ndash fairly complicated example bletchful opensslcnf snippet used kerberos pkinit represent fooexampleorg vextensions subjectaltname emailfooexampleorg othernamepkinitsansequencekrbprincname krbprincname realm exp generalstringexampleorg principalname exp sequencekrbprincseq krbprincseq nametype exp integer namestring exp sequencekrbprincipal krbprincipal princ generalstringfoo out everything i found languages i know perl python ruby php bash c using openssl command line automatically generated cnf files ugly process is better way ruby openssl looked nice first i got pkinit,1 nfs mount filesystem systems access files local otherwise could use sockets,i trying move log file computer operation performed another computer get log file process returning document result analysis i using python job i open options i run copy via console osx due fact work done shell scripting cannot use visual solution anything launched via script would work suggestion welcome since i really favorite way trying less problematici need security encryption since computers internal network communication outside performed hope someone point right solution thanks advance,1 check message httpgroupsgooglecomgroupcomplangpythonmsgbabf,is showcase demo application tkinter tix features widgets for example wxpython download includes wxpython demo application demonstrates widgets also provides source code comments i liked lot but i stick tkinter tix real good documentation even patterns explained showcase i could find i basically copypaste lots code docs sample app understand looks like real ps tix really wanted tkinter,1 you compress data bzip future import withstatement only python import bzjsoncontextlib hugedata key x contextlibclosingbzbzfile datajsonbz wb f jsondumphugedata f load like future import withstatement only python import bzjsoncontextlib contextlibclosingbzbzfile datajsonbz rb f hugedata jsonloadf you also compress data using zlib gzip pretty much interface however zlib gzip compression rates lower one achieved bzip lzma,i recently asked question regarding save large python objects file i previously run problems converting massive python dictionaries string writing file via write now i using pickle although works files incredibly large gb i little experience field large files i wanted know would faster even possible zip pickle file prior storing memory,3 faster even possible zip pickle file prior writing of course possible reason try make explicit zipped copy memory might fit writing automatically cause zipped written builtin standard library functionality see httpdocspythonorglibrarygziphtml basically create special kind stream gzipgzipfileoutput file name wb use exactly like ordinary file created open file matter,i recently asked question regarding save large python objects file i previously run problems converting massive python dictionaries string writing file via write now i using pickle although works files incredibly large gb i little experience field large files i wanted know would faster even possible zip pickle file prior storing memory,1 disclaimer i maintainer gmpy gmpy i able test tonight but couple comments questions instead using m use pows m it faster what happens use gmpympz instead gmpyxmpz are running bit version python gmpy i assume i want confirm regarding range vs xrange python x range replaced xrange edit additional information the cause crash due overflow internal structures bit build using bit version python gmpy gmpy proper fix the unpackxn function similar split string divides number series nbit values it equivalent much faster def unpackxn r n x x temp divmodxm rappendtemp return r some documentation available via helpgmpyunpack better documentaion todo list the reason unpack used eliminate operation adding digits base number check divisibility in case unpack creates pbit numbers dividing p here test code import gmpy import time def mersennep primality test mersenne prime p uses native python longs does verify p prime m p rangep ss m return false else true def mersennep primality test mersenne prime p uses gmpympz does verify p prime gmpympz m gmpympzp rangep ss m return false else true def mersennep primality test mersenne prime p uses gmpympz mod does verify p prime gmpympz m gmpympzp rangep ss sumgmpyunpacks p sumgmpyunpacks p m else return false else true name main p start timetime result mersennep printelapsed time fformattimetime start start timetime result mersennep printelapsed time fformattimetime start start timetime result mersennep printelapsed time fformattimetime start result result result printall three tests equal else printoops something gone wrong and running times cxpythonpythonexe mersennepy elapsed time elapsed time elapsed time all three tests equal,i recommended use gmpy assist calculating large numbers efficiently before i using python script ran day two ran memory sure happened program memory usage basically constant throughout maybe memory leak anyways i keep getting weird error running program couple seconds mpallocate fatal python error mpallocate failure this application requested runtime terminate unusual way please contact application support team information also python crashes windows gives generic pythonexe stopped working dialog this happening using standard python integers now i switch gmpy i getting error seconds running script i thought gmpy specialized dealing large number arithmetic for reference sample program produces error import gmpy p gmpyxmpz gmpyxmpz m sp x rangep m i gigs ram without gmpy script ran days without running memory still sure happened considering never really gets larger anyone ideas edit forgot mention i using python,3 it looks like want use regular expressions using ordinary string methods you need use methods module import researchazstraz str researchazstraz str sresrematch object xc,i trying substring search str str researching str researching azstraz str false azstraz str false i wanted true looking str i wrong,1 you want python module import regex recompilersthiss whitespace or regex recompilerwthisw w word character azaz w anything word character str researching str researching boolregexsearchstr false regexsearchstr sresrematch object xeb boolregexsearchstr true i hunch actually looking word nonword characters around in case using word boundary escape sequence b,i trying substring search str str researching str researching azstraz str false azstraz str false i wanted true looking str i wrong,2 how create go back point command you programming structure python programming languages really work way you need think problem differently you create loops nested broken remember kind program state represents in programming able distinguish many kinds context current line execution well got returning function return value context called to answer question useful way requires much concrete example,i new coding python know header search problem python my question how create go back point command you know like menus open tab want press back also whenever i search i always find questions explanations exceptions what anything first question,1 as djangoadmin mainly matter templates needed redefine templates djangoadmintools parts i idea the pagination modules django like linarodjangopagination endlesspagination provide template tags paginate anything given iterable if could find template charge displaying inline models could copy project try adding load paginationtags paginate inlines i tested thought thoroughly except validation i see could fail just test tell us,i simple django model consisting sensor values specific sensor the number values per pyranometer high k is somehow possible paginate pyranometervalues specific day generell apply paginator admin inline view class pyranometermodelsmodel name modelscharfieldmaxlength class pyranometervaluesmodelsmodel timestamp modelsdatetimefield value modelsdecimalfieldmaxdigitsdecimalplaces sensor modelsforeignkey pyranometer,1 flow control might good thing search as learn python vernacular see everything need without goto type command reaching depending trying might want use looping construct like or might write reusable function class use different contexts as exceptions fancy word certain types errors learn read carefully tell exactly wrong have fun python great way learn program i found how think like computer scientist great asset i learning,i new coding python know header search problem python my question how create go back point command you know like menus open tab want press back also whenever i search i always find questions explanations exceptions what anything first question,2 python code would extremely slow comes implementing data serialization if try create equivalent pickle pure python see super slow fortunately builtin modules perform quite good apart cpickle find marshal module lot faster but needs real file handle filelike object you import marshal pickle see difference i think make custom serializer lot faster here actual old serious benchmark python serializers,i recently asked question regarding save large python objects file i previously run problems converting massive python dictionaries string writing file via write now i using pickle although works files incredibly large gb i little experience field large files i wanted know would faster even possible zip pickle file prior storing memory,2 this looks like right track i using pypubsub wxpython app bit ended implementing simple version root looks similar done except bells whistles probably end implementing fill requirements the answer given also lot like done well this answer goes examples bit different approach there number existing libraries besides pypubsub pydispatch blinker might worth looking reference ideas,in twisted application i series resource controllermanager classes interact via observable pattern generally observers subscribe specific channel ex foobarentity cases i like know event specific channel ex foo i wrote something like following collections import defaultdict class simplepubsubobject def initself selfsubjects defaultdictlist def subscribeself subject callbackstr brevity callbackstr would valid python function bound method string selfsubjectssubjectappendcallbackstr def fireself subject again brevity fire would args kwargs additional message arguments subject selfsubjects print firing callback subject callback selfsubjectssubject print callback callback pubsub simplepubsub pubsubsubscribe foobar foobar pubsubsubscribe foofoo foofoo pubsubsubscribe fooichtier fooichtier pubsubsubscribe fooichtier fooichtier pubsubsubscribe fooichtier fooichtier find everything starts foo say foobar fired firedsubject foobar pubsubfirefiredsubject outputs firing callback foobar callback foobar let say i want add callback everything undr fooich class globalpubsubsimplepubsub def initself selfglobals defaultdictlist superglobalpubsub selfinit def subscribeself subject callback subjectfind assumes global suscriptions would like subjectfoo want catch subjectfoo selfglobalssubjectappendcallback else superglobalpubsub selfsubscribesubject callback def fireself subject superglobalpubsub selffiresubject selfglobals key selfglobalsiterkeys subjectstartswithkey callback selfglobalskey print global callback says callback print now global subscriptions print pubsub globalpubsub pubsubsubscribe foobar foobar pubsubsubscribe foofoo foofoo pubsubsubscribe fooichtier fooichtier pubsubsubscribe fooichtier fooichtier pubsubsubscribe fooichtier fooichtier pubsubsubscribefooich all ichs time find everything starts fooich firedsubject fooichtier pubsubfirefiredsubject outputs firing callback foobar callback foobar now global subscriptions firing callback fooichtier callback fooichtier global callback says all ichs time is good gets without resorting sort exotic construct tries example i looking affirmation i right track better alternative suggestion global subscription handler pure python external libraries services,1 i use time home i keep file sharing daemons running constantly python simplehttpserver on client machine use browser wget in fact i use often i made script prints ip address also named serv feel free hack needs just cd folder serv usrbinenv python import subprocess sub import basehttpserver import simplehttpserver httpd override method speed connection def bareaddressstringself host port selfclientaddress return host basehttpserverbasehttprequesthandleraddressstring bareaddressstring get ip address print info subpopen sbinifconfig stdoutsubpipecommunicate tokens line infosplit n inet line line tokens linesplit print print tokensreplace n start server try httpdtest except keyboardinterrupt print xxkilled,i trying move log file computer operation performed another computer get log file process returning document result analysis i using python job i open options i run copy via console osx due fact work done shell scripting cannot use visual solution anything launched via script would work suggestion welcome since i really favorite way trying less problematici need security encryption since computers internal network communication outside performed hope someone point right solution thanks advance,2 you use dynamic parameters alright the function signature directtotemplate def directtotemplaterequest template extracontextnone mimetypenone kwargs you call like args request template kwargs extracontent b mimetype applicationjson additional another keyword argument directtotemplateargs kwargs,i writing pretty simple function use django project display number pages application debug mode in as essentially apply methods parameters another methods using method call apply method let demonstrate public function securecallargumentsvoid secure true reference call method callapplythis arguments else throw new illegalaccesserror public function callastring bint othersvoid something important is way python i essentially want following djangoviewsgenericsimple import directtotemplate def dtodebugargs myappsettingsdebug directtotempateapplyargs else raise http,2 when defining function use notation def takesanyargsargs kwargs pass args tuple positional arguments kwargs dict keyword arguments you call another function arguments like somefunctionargs kwargs you omit either args kwargs want pass positional keyword arguments respectively you course create tupledict come def statement,i writing pretty simple function use django project display number pages application debug mode in as essentially apply methods parameters another methods using method call apply method let demonstrate public function securecallargumentsvoid secure true reference call method callapplythis arguments else throw new illegalaccesserror public function callastring bint othersvoid something important is way python i essentially want following djangoviewsgenericsimple import directtotemplate def dtodebugargs myappsettingsdebug directtotempateapplyargs else raise http,2 that looks like format csv module would helpful then write regex,i working project euler problem fun it comes kb txt file containing line list names format like mariasusanangelajack my plan write method extract every name append python list is regular expression best weapon tackle problem i looked python doc hard time figuring right regex,2 you really using select poll eg via asyncore select twisted prefer reading socket never know much receive read you could receive several messages one go one message split many reads you always collect data buffer make use remove data used buffer leave data used yet since know input makes sense line line receive loop look something like true append new data buffer look eols process remove complete lines,so i working python irc framework i using python socket module do i feel like using twisted no really anyway i infinite loop reading processing data socketrecvxxxx xxxx really irrelevant situation i split received data messages using strsplitrn process one one my problem i set specific read size socketrecv define much data read socket when i receive burst data example i connect irc server receive motdetc always message spans two reads socket ie part line read one socketrecv rest read next iteration infinite loop i process halfreceived messages i sure even way detecting in ideal situation i receive everything buffer look like socket provides method any help,2 for seo reasons usually better choose one url handle redirect chosen one otherwise search engines see duplicate content for example something like class redirecthandlerwebapprequesthandler def getself selfredirectresult true application webappwsgiapplication result redirecthandler result result,hi a rather simple question application webappwsgiapplication result result result result the difference trailing can i merge two url mapping one,1 if format file say ie it single line the format like mariasusanangelajack then work import csv lines csvreaderopen wordstxt r delimiter words linesnext words maria susan angela jack,i working project euler problem fun it comes kb txt file containing line list names format like mariasusanangelajack my plan write method extract every name append python list is regular expression best weapon tackle problem i looked python doc hard time figuring right regex,2 since class instance metaclass one way use custom metaclass meta type meta type repr lambda cls class a a meta a object repr lambda self instance class a a class a a instance class a,it pretty easy implement lenself method python handles leninst calls like one class aobject def lenself return a lena gives us and plenty alike methods define eq str repr etc i know python classes objects well my question i somehow define example len following works lena makes sense gives predictable result,2 what looking called metaclass like instance class a a instance class well referred metaclass by default python classes instances type class exception python legacy old style classes inherit object you check typea return type yes object overloaded little bit metaclasses powerful braintwisting enough deserve quick explanation i write good starting point would stackoverflow question what metaclass for particular question python following creates metaclass aliases lena invoke class method a class lengthmetaclasstype def lenself return selfclslength class aobject metaclass lengthmetaclass classmethod def clslengthcls return print lena python works similarly would use class aobject metaclasslengthmetaclass instead metaclass lengthmetaclass the reason lengthmetaclasslen affect instances a attribute resolution python first checks instance dict walks class hierarchy a object never consults metaclasses whereas accessing alen first consults instance a walks class hierarchy consists lengthmetaclass type,it pretty easy implement lenself method python handles leninst calls like one class aobject def lenself return a lena gives us and plenty alike methods define eq str repr etc i know python classes objects well my question i somehow define example len following works lena makes sense gives predictable result,3 although question how i get control early enough issue error message exit the question i answer how i get control early enough issue error message starting app i answer lot differently posts seems answers far trying solve question within python i say version checking launching python i see path linux unix however i offer windows script i image adapting linux scripting syntax hard here dos script version echo off rem see httpsscomntforfhtml for f tokens g in pythonexe v amp do echo h find nul if not errorlevel goto python echo must use python greater goto eof python pythonexe ternpy goto eof eof this run part application therefore raise python exception it create temp file add os environment variables and end app exception due different version syntax rules that three less possible security points access the for f line key for f tokens g in pythonexe v amp do echo h find nul for multiple python version check check url httpwwwfpschultzedemodulessmartfaqfaqphpfaqid and hack version ms script python version check prelaunch python module httppastebincomaaujfq,if i python script requires least particular version python correct way fail gracefully earlier version python used launch script how i get control early enough issue error message exit for example i program uses ternery operator new blocks new i wrote simple little interpreterversion checker routine first thing script would call except get far instead script fails python compilation routines even called thus user script sees obscure synax error tracebacks pretty much require expert deduce simply case running wrong version python i know check version python the issue syntax illegal older versions python consider program import sys sysversioninfo raise must use python greater else syntax error ok x true else print x when run i want result binpython ternpy must use python greater result binpython ternpy file ternpy line x true else syntaxerror invalid syntax channeling coworker,3 a regexp get job done would inefficient using csv would work might handle cells single line well at least load whole file maintain entire list names memory might problem small amount data if want iterator relatively large files much larger names state machine trick def parsechunksiter quote delim escape inquote false inescaped false buffer chunk iter byte chunk inescaped done escape char add buffer buffer byte inescaped false elif byte escape the next charachter added literally parsed inescaped true elif inquote byte quote inquote false else buffer byte elif byte quote inquote true elif byte n r ignore whitespace outside quotes pass elif byte delim done block text yield buffer buffer else buffer byte inquote raise valueerror found unbalanced quote char r quote elif inescaped raise valueerror found unbalanced escape char r escape yield last bit buffer yield buffer data r mariasusan ang elajacktedjoe print listparsechunksdata maria susan angnela jack ted joe use fixed buffer size know file one long line care line parsing buffersize open myfiletxt r buffersize file name parsechunksfile print name,i working project euler problem fun it comes kb txt file containing line list names format like mariasusanangelajack my plan write method extract every name append python list is regular expression best weapon tackle problem i looked python doc hard time figuring right regex,1 if simpler simpler no need use csv module i think names kb enough worry names f opennamestxt r in case one line line freadlines names xstripreplace x linesplit print names print name,i working project euler problem fun it comes kb txt file containing line list names format like mariasusanangelajack my plan write method extract every name append python list is regular expression best weapon tackle problem i looked python doc hard time figuring right regex,1 from sound callduring nothing simply calling whatever function want it get called exactly call is reason calling directly solve problem however telling program sleep no amount call help since putting whole app sleep maybe think sleep good simulation real code you actually telling program stop processing includes screen updates the crux problem allowing event loop process redraw events you might try calling wxyield loop large longrunning loop main thread gui program code smell there almost certainly better way approach problem the best advice i give search wxpython long running task most likely first hit wxpywiki page titled long running tasks might find helpful,i found wxcallafter wxcalllater documentation neither solves problem what i trying update status bar task wxcallafter wxcalllater updates task example usrbinenv python coding utf generated wxglade fri sep import wx import time begin wxglade extracode end wxglade class myframewxframe def initself args kwds begin wxglade myframeinit kwdsstyle wxdefaultframestyle wxframeinitself args kwds selfframestatusbar selfcreatestatusbar selfsetproperties selfdolayout end wxglade def setpropertiesself begin wxglade myframesetproperties selfsettitleframe selfframestatusbarsetstatuswidths statusbar fields framestatusbarfields foo rangelenframestatusbarfields selfframestatusbarsetstatustextframestatusbarfieldsi end wxglade def dolayoutself begin wxglade myframedolayout selflayout end wxglade def testself timesleep range timesleep txti stack exchange x str wxcallafterselfframestatusbarsetstatustexttxt wxcallafterselfupdate print txt end class myframe name main app wxpysimpleapp wxinitallimagehandlers frame myframenone appsettopwindowframe frameshow wxcallafterframetest appmainloop,2 actually python much elegant ab ba you call function and yes per comments parentheses unnecessary i still prefer since i believe make intent clearer following edit is way employing assignment using possibly though i know one i imagine would simpler readable basic way shown if looking complicated way things done simply might i suggest wrong mindset,about swap c swap two stdswapx x passed swap reference but python also write swap function swap way c the python version swap i implemented kinda stupid def swapinpythonx return x swapping b i usually like b swapinpythona b this really cumbersome pass reference pointer c right edit is way employing assignmentnot using,3 python passes pointer simpler swap x x,about swap c swap two stdswapx x passed swap reference but python also write swap function swap way c the python version swap i implemented kinda stupid def swapinpythonx return x swapping b i usually like b swapinpythona b this really cumbersome pass reference pointer c right edit is way employing assignmentnot using,1 you could directly write b b,about swap c swap two stdswapx x passed swap reference but python also write swap function swap way c the python version swap i implemented kinda stupid def swapinpythonx return x swapping b i usually like b swapinpythona b this really cumbersome pass reference pointer c right edit is way employing assignmentnot using,1 mb lot data load devappserver designed large even medium datasets built entirely smallscale local testing your best bet would reduce size test dataset try usesqlite command line flag use new sqlitebased local datastore scalable,i developing application google app engine using current django nonrel default high replication datastore i currently trying bulk load mb csv file locally dev instance following command appcfgpy uploaddata configfilebulkloaderyaml filenamemydatacsv kindplace numthreads urlhttplocalhostahremoteapi rpslimit bulkloaderyaml pythonpreamble import base import import googleappengineextbulkloadtransform import googleappengineextbulkloadbulkloaderwizard import googleappengineextdb import googleappengineapidatastore import googleappengineapiusers transformers kind place connector csv connectoroptions encoding utf columns fromheader propertymap property key externalname appenginekey exporttransform transformkeyidornameasstring property name externalname name the bulk load actually successful truncated record version csv full set eventually bogs starts erroring backing waiting longer longer the bulkloaderlog i actually tail reveal anything helpful either server stderr any help understanding bulk load process would appreciated my plans able eventually load big data sets google data store promising,1 there lot going i try brief class investorobject reports data def initself lastname firstname date gender title rid following two lines define variables exist inside init basically gotten rid reports data need initialized actually creating new list constructor bad unless want one report per instance later sure add self instead adding local vars selfaddself classmethod def reportself result x selfreports just use join mean anyway result joinx n result nn i think mean owriteresult owriteresult n classmethod def loadself f selfreports selfdata file openf extra readline filereadline list line filereadline need get rid trailing whitespace items linesplit line break else self refers class use constructor well use make list argument list selfitems no need add value added end init things stand class agentinvestor reports data def initself commission lastname firstname date gender title rid superagent selfinitself lastname firstname date gender title rid selfcommission commission def strself be lazy use super return superagentselfstr selfcommission thing parent class def reprself the classmethod methods needed unless want redefine behavior child class classmethod def addself if change something though make sure use super well superagent selfaddi i believe take care issues if want format investor flintstone fred datetimedate male mr need include name quote properties def reprself notice return selfname strselfrid selfname selfdateofbirth selfgender in agent need use substring get need def reprself remove agent add commission front superagentselfstr return selfname selfcommission slenselfname,this homework question see i written code already what i trying happen agent object inherits methods investor object agent object methods suppose basically the different constructors investor takes parameters agent takes you see parameters also basically investorload investorreport work part expected the inherited methods agent see my main issues when i run reporto investor output slightly messed it little paragraph symbols end line rather carriage return i developing linux when i run load report agent populate arrays reports data because report prints nothing how i set class variables work way i want thanks will readd turnin date here code should function sys import stdout import datetime hedgefunds import investor flintstone fred datetimedate male mr investor flintstone fred datetimedate male mr repri investor flintstone fred datetimedate male mr irepr this controls previous two lines investor flintstone fred datetimedate male mr evalrepri object can be recreated from its repr string investor flintstone fred datetimedate male mr notice one additional bit of data we didn t specify investor flintstone fred datetimedate male mr the at the end is the record id rid the repr string includes all data so you see it the investor class should assign a rid if one is not passed into the construtor print mr fred flintstone male istr this controls previous line mr fred flintstone male note the name is nicely put together and and rid is at the start note datetimedateyyyy mm dd but we print in mmddyyyy format now let s look at our investor object s attributes ilastname flintstone ifirstname fred idob datetimedate idateofbirth igender male ititle mr iname mr fred flintstone irid but we re gonna need somehwere to store multiple investor objects so as well as creating investor objects the investor class must act like a recordset investorreporto was set to stdout at the top of this trace but could be any file investoraddi no records so let s add one investorreporto now we have something to report mr fred flintstone male investoraddinvestor flintstone wilma datetimedate female mrs investorreporto mr fred flintstone male mrs wilma flintstone female we could continue adding investors manually but since we ve got a file full of them investorload investorscsv investorreporto mr charles creed male miss sheila geller female mr fred kenobi male miss rachel geller female mr charles rubble male mrs leah skywalker female mr bill balboa male dr sheila barkley female you should see records our two manually added records are gone agents agent rubble barney datetimedate male mr agent rubble barney datetimedate male mr repra agent rubble barney datetimedate male mr evalrepra agent rubble barney datetimedate male mr print mr barney rubble male alastname rubble afirstname barney adob datetimedate adateofbirth agender male atitle mr aname mr barney rubble arid acommission agentadda agentreporto mr barney rubble male agentload agentscsv agentreporto mr barney flintstone male miss rachel rubble female dr ted geller male miss phoebe creed female mr luke kenobi male dr megan creed female mr ted rubble male mrs monica balboa female,1 i believe possible simply implement equivalent c swap python this due fundamental differences c object model python object model in python variables reference objects with swap implemented happens objects referred two variables exchanged the objects untouched nothing referring existing objects see change in c stdswap values two objects exchanged expression denoting either objects swapped see changes c hello world c b b swapinpythona b c hello world vs stdliststdstring c cpushbackhello cpushbackworld stdliststdstring ampa c ampb stdswap b c empty hello world,about swap c swap two stdswapx x passed swap reference but python also write swap function swap way c the python version swap i implemented kinda stupid def swapinpythonx return x swapping b i usually like b swapinpythona b this really cumbersome pass reference pointer c right edit is way employing assignmentnot using,1 it really solution perse release new python runtime python includes updated versions libraries including webob perhaps could target app instead runtime,i trying run pyramid gae following steps outlined everything works fine dev server deployed google servers following error occurs type exceptionsimporterror cannot import name baserequest traceback recent call last file basedatahomeappsmainpy line module pyramidconfig import configurator file basedatahomeappslibdistpyramidinitpy line module pyramidrequest import request file basedatahomeappslibdistpyramidrequestpy line module webob import baserequest this probably caused fact gae uses webob pyramid uses webob resides libdistwebob project since baserequest missing in mainpy file fragment syspathinsert libdist seems help dev server case i way force gae runtime use version included application,1 i currently use xlrd module suck data excel spreadsheet insert cursor create feature class works well you able use search cursor iterate feature class records use xlwt python module httpwwwpythonexcelorg write records excel,i spending better part weekend trying figure best way transfer data ms access table excel sheet using python i found modules may help execsql pythonexcel limited knowledge modules i use create certain data i gis professional i creating spatial data using arcgis arcpy module access table i sure best approach all i need copy columns data access excel format excel i formatting part solved should i iterate rows using cursor somehow load rows excel copy columns access excel export whole access table sheet excel thanks suggestions,1 just moment ignoring idea creating custom plugin order describe ie render page placeholders programatically following might viable alternative depending exactly trying achieve you able template outer cms page ie page within want display contents another cms page get access current page like requestcurrentpage this virtue cms page middleware so taking step able access page placeholders like placeholder requestcurrentpageplaceholders placeholderrender endfor that one way could go rendering page placeholders inside another page,im trying render cms page within another page using custom cms plugin the plugin class class pageindivcmsplugin pagediv modelsforeignkeypage verbosename page def unicodeself return selfpagedivgettitle see link plugin page cmspluginspy class pageindivplugincmspluginbase model pageindiv name page div rendertemplate pagehtml adminpreview false def renderself context instance placeholder temp loadergettemplateinstancepagedivgettemplate html temprendercontext contextupdate html html title instancepagedivgettitle placeholder placeholder return context see pass html provided page plugin template plugin template rendered within page thats hosting plugin the problem placeholder content page thats selected via foreignkey rendered displayed so question way render pages placeholders programatically,1 python print feature convert tabs spaces outputs literal tab the way appears depends program use view,is possible redefine space width tab printing character python,3 the existing answers correct pythonic way usually tryexcept ie eafp however really want validation could remove exactly decimal point using isdigit replace isdigit true replace isdigit true replace isdigit false replace isdigit false notice treat floats different ints however you could add check really need though,i trying evaluate string one textbox interface number ie text anything else in python method called isdigit return true string contains digits negative signs decimal points is another way i could evaluate string rational number ex example code selfcomponentstxtzoompostextisdigit step intselfcomponentstxtzoompostext,1 the existing answers correct pythonic way usually tryexcept ie eafp however really want validation could remove exactly decimal point using isdigit replace isdigit true replace isdigit true replace isdigit false replace isdigit false notice treat floats different ints however you could add check really need though,rawinput how much share company aisdigit print you need write numbern rawinput how much share company this works user enters int i want work even enter float enter str so user able enter abc how i,3 all functions part module builtins fire python shell check help helpbuiltins,what default modules python automatically imported python compiler launched these example print addition mathematical functions they must defined somewhere python i guessed extract information finding example print function come know information get module come,3 i found information plan deploy site https httpwwwredrobotstudioscomblogsecuringdjangowithssl,i writing site i require data transmitted encryption last night i considering encrypting form data posting i created django form login realised using action field send data back server unencrypted form methodpost action csrftoken div idloginboxuserloginformusernamediv div idloginboxpassloginformpassworddiv div idloginboxsbmtinput idsubmitbutton namesubmit valuelogin typesubmit div form i thinking order get around i would need javascript function action encode sending javascript submit button at time i thinking ssl currently server running i able connect ssl certificate use developmenttesting the way i understand using ssl data transmitted would encrypted i wondering worth effort encrypting everything i plan get ssl certificate using ssl domain site,1 encryption javascript useless explained so ssl option,i writing site i require data transmitted encryption last night i considering encrypting form data posting i created django form login realised using action field send data back server unencrypted form methodpost action csrftoken div idloginboxuserloginformusernamediv div idloginboxpassloginformpassworddiv div idloginboxsbmtinput idsubmitbutton namesubmit valuelogin typesubmit div form i thinking order get around i would need javascript function action encode sending javascript submit button at time i thinking ssl currently server running i able connect ssl certificate use developmenttesting the way i understand using ssl data transmitted would encrypted i wondering worth effort encrypting everything i plan get ssl certificate using ssl domain site,3 try pydoc stringexpandtabs i think want,is possible redefine space width tab printing character python,3 the builtins module contains print function well many functions classes in shell helpbuiltins give almost absurdlydetailed list functions classes classes functions using dirbuiltins may useful simply returns list names included functions classes,what default modules python automatically imported python compiler launched these example print addition mathematical functions they must defined somewhere python i guessed extract information finding example print function come know information get module come,1 as turns i added exactly information documentation ruby published today james britt look documentation opensslxcertificate answer questions modifying examples generate particular extensions listed example straightforward particular extension supported openssl for complicated cases eg custom othername example may still use opensslxextension documented yet unfortunately the opensslasn module needed custom extensions hand documented codeadvice presented applicable well you could also use asn module create multivalued version subjectaltname,i looking librarymodulepackage i could create sign x certificates ability conditionally add custom v extensions ndash fairly complicated example bletchful opensslcnf snippet used kerberos pkinit represent fooexampleorg vextensions subjectaltname emailfooexampleorg othernamepkinitsansequencekrbprincname krbprincname realm exp generalstringexampleorg principalname exp sequencekrbprincseq krbprincseq nametype exp integer namestring exp sequencekrbprincipal krbprincipal princ generalstringfoo out everything i found languages i know perl python ruby php bash c using openssl command line automatically generated cnf files ugly process is better way ruby openssl looked nice first i got pkinit,2 module particular meaning python neither print addition module mathematical functions operators etc keywords functions going builtins if actually want know modules loaded start python look sysmoduleskeys python python default jun msc v bit intel win type help copyright credits license information import sys sysmoduleskeys copyreg srecompile locale sre functools encodings site builtin sysconfig operator main types encodingsencodings abc weakrefset errno encodingscodecs sreconstants abcoll ntpath codecs nt warnings genericpath stat zipimport encodingsbuiltin warnings userdict encodingscp sys codecs ospath functools locale signal traceback linecache encodingsaliases exceptions sreparse os weakref,what default modules python automatically imported python compiler launched these example print addition mathematical functions they must defined somewhere python i guessed extract information finding example print function come know information get module come,3 each gmapsaddresstolatlng call sends request google server make limited number google docs usage limits use google geocoding api subject query limit geolocation requests per day additionally enforce request rate limit prevent abuse service and docs ggeotoomanyqueries the given key gone requests limit hour period submitted many requests short period time if sending multiple requests parallel tight loop use timer pause code make sure send requests quickly so tell import time and loop pause timesleep adjust „“ appropriate number seconds run allowed requests,i written script send address google maps api receive back lat lng however i receiving error messages i exceeded google rate limit queries is something i considering i appreciate help i new using api better understanding i hitting rate limit would helpful after reading addresses csv file named location relevant code row locations address xxx new haven ct first research row address resub xxx firstgroup address lat lng gmapsaddresstolatlngaddress and error message traceback recent call last file input line module file usrlocalcellarpythonlibpythonsitepackagesgooglemaps pyegggooglemapspy line addresstolatlng return tupleselfgeocodeaddress placemark point coordinates file usrlocalcellarpythonlibpythonsitepackagesgooglemaps pyegggooglemapspy line geocode raise googlemapserrorstatuscode url response googlemapserror error ggeotoomanyqueries,3 you use fromarrays method numpycorerecords see documentation nprecfromarraystestt mytype out recarray dtype u b u c u the array transposd first functions regards rows array columns structured array output see also question converting d numpy array structured array,i made dtype mytype npdtype npuint b npuint c npuint array using dtype test npzeros dtypemytype test array dtype u b u c u now i test test nparray when i use testastypemytype result i want array dtype u b u c u i want result array dtype u b u c u is way thanks,3 to fix install python windows extensions pywin register python cyourpythonversionlibsitepackageswincomextaxscriptclientpyscriptpy,i installed activepython i trying execute pys script via console wscriptcscript ie activepython pythonscript pys extension microsoft wshwindows scripting host trying wscript i get two errors the program cannot start msvcrdll missing computer try reinstalling program fix problem can find script engine python script i googling also downloaded installed microsoft visual c redistributable package x httpwwwmicrosoftcomdownloadenconfirmationaspxid avail i tried pythonw cpythonlibsitepackageswincomextaxscriptclientpyscriptpy register python any help would greatly appreciated i running win x,2 you use execfile execfilepathexamplepy examplepy def examplefunc return test print examplefunc test edit in case want execute unsecure code try sandbox way although probably safe anyway def execfilesandboxfilename copy import copy loc globals bi locbuiltins isinstancebi dict bi bidict bi copybi files del bifile definitely import del biimport delete builtin functions want deny access newlocals dict newlocalsbuiltins bi execfilefilename newlocals newlocals usage try execfilesandboxpathexamplepy except handle exception errors like import error pass,if i text file contains python function definition i make function call another python program ps the function defined python program call ways done consider python function module call constraint i convert python bare function module would give errors insert codefunction code program calls function which would better way go edit thank replies have shed lot light initial confusion i another doubt would personobviously written ossystemrm rf and i end executing that would mean doomsday right edit as lot asked use exec i would like point thread particularly namespace problem it gives user lot chances circumvent python don think,1 compile eval trick code compile def fooa return string exec evalcode foo function foo xff foo file openfilename source evalcompilesourceread filename exec,if i text file contains python function definition i make function call another python program ps the function defined python program call ways done consider python function module call constraint i convert python bare function module would give errors insert codefunction code program calls function which would better way go edit thank replies have shed lot light initial confusion i another doubt would personobviously written ossystemrm rf and i end executing that would mean doomsday right edit as lot asked use exec i would like point thread particularly namespace problem it gives user lot chances circumvent python don think,1 you looking exec keyword mycode print hello world exec mycode hello world so read text file text assuming contains function like testtxt def print testpy mycode open testtxt read exec mycode execute code textfile thus define function call function python file link doc httpdocspythonorgreferencesimplestmtshtmlgrammartokenexecfstmt you may want look compile statement,if i text file contains python function definition i make function call another python program ps the function defined python program call ways done consider python function module call constraint i convert python bare function module would give errors insert codefunction code program calls function which would better way go edit thank replies have shed lot light initial confusion i another doubt would personobviously written ossystemrm rf and i end executing that would mean doomsday right edit as lot asked use exec i would like point thread particularly namespace problem it gives user lot chances circumvent python don think,3 a way like reflection java if python module named imp provide foopy def foo return return function foo file foopy code anywhere modes impgetsuffixes got modes explained link mode modes i want load py file openfoopy file imploadmodulename file foopy mode printmfoo mode modes impgetsuffixes impgetsuffixes cpythonmso rb modulecpythonmso rb abiso rb moduleabiso rb rb moduleso rb py u pyc rb output python default aug gcc based apple inc build llvm build darwin type help copyright credits license information import imp openfoopy file imploadmodulefoo file foopy py u mfoo return function foo file foopy check httpdocspythonorgpyklibraryimphtml both python python works python r jun gcc based apple inc build llvm build darwin type help copyright credits license information import imp impgetsuffixes rb moduleso rb py u pyc rb openfoopy file imploadmodulefoo file foopy py u mfoo return function foo file foopy,if i text file contains python function definition i make function call another python program ps the function defined python program call ways done consider python function module call constraint i convert python bare function module would give errors insert codefunction code program calls function which would better way go edit thank replies have shed lot light initial confusion i another doubt would personobviously written ossystemrm rf and i end executing that would mean doomsday right edit as lot asked use exec i would like point thread particularly namespace problem it gives user lot chances circumvent python don think,1 django provides lazy variants translation functions example ugettextlaxy ark strings translations access time opposed translation function called it documented details httpsdocsdjangoprojectcomentopicsintranslationlazytranslation,i baseform fields then i forms inheriting form passing parameter called fields baseform uses delete fields best explain via example class baseformformsform reportid formshiddeninput fromdate formsdatefieldlabelfrom widgetwidgetsadmindatewidget todate formsdatefieldlabelto widgetwidgetsadmindatewidget sortby formschoicefieldlabelsort choices def initself args kwargs fields kwargspop fields pseudo del selffieldsfield field fields class subformformsform def initself args kwargs fields reportid todate supersubform selfinitfieldsfields args kwargs the resulting form would look like class subformformsform reportid formshiddeninput todate formsdatefieldlabelto widgetwidgetsadmindatewidget my problem baseform initialized first time labels bound fields active language another user logs another language setting current user changes languages field labels update i come solution using dict like labels todate lambda to fromdate lambda from initializing baseform looping fields setting selffieldsfieldwidgetlabel labelsfield do i nicer read pythonic way achieving,3 try backgroundfff urlimagesimagesbgjpg repeatx the url without single quotes btw two images directories nested,i folder structure django site theme index file load stylecss stylecss load bgjpgi stylecss body backgroundfff url imagesimagesbgjpg repeatx workive tryed thistoo body backgroundfff url sitestaticimagesimagesbgjpg repeatx css url sitestaticcssstylecss image url sitestaticimagesimagesbgjpg i load picture via stylecss,1 use argparse module,what best way documenting creating kind mini manual python script eg script h display run any templates,1 create new file osrename existing file this atomic platforms conditions,what recommended way replace file atomically python ie python script interrupted power outage etc files high probability ending inconsistent state half written disk a solution linuxunix platforms preferred i know getting atomic operations might depend file system least make chances corruption low,3 python builtin library exactly if targeting python use optparse use argparse the optparse module works shown you specify arguments script accept call parseargs this processes arguments prints help message h passed the argparse module works similarly optparse import optionparser parser optionparser parseraddoptionf file destfilename helpwrite report file metavarfile parseraddoptionq quiet actionstorefalse destverbose defaulttrue helpdon print status messages stdout options args parserparseargs,what best way documenting creating kind mini manual python script eg script h display run any templates,2 esc ctrl b works alt b it right emacs keymap strange first i think problem alt b mapped character ∫ rather 㟠case pycharm see keymodifier pair single character switching different international keyboard map change combinations work i suggest sending bug report pycharm something fix alternatively hack keyboard mapping somehow to answer question i think way go matching parenthesis least i never found one,i trying use emacs keybindings pycharm os x they work except alt b inserts beta symbol rather moving back word it puzzling since alt f correctly move forward word also i wondering pycharm support moving matching parentheses brackets like controlmetaf emacs i see option pycharm keybindings preference pane thanks,1 if mind external dependency i found httppypipythonorgpypiplac great from documentation def maindsn do something database printdsn name main import plac placcallmain,what best way documenting creating kind mini manual python script eg script h display run any templates,2 maybe like targetfilter class filterargs targetfilter searchresult aaaobjectsfilterfilterargscount,db table select aaa id name class grade john a jane b joon a josh c code django searchresult aaaobjectsfiltergrade b count print searchresult searchresult i want change grade class value django targetfilter class searchresult aaaobjectsfiltertargetfilter count searchresult q how i complete code is possible,1 you may want read documentation manage static files django,i folder structure django site theme index file load stylecss stylecss load bgjpgi stylecss body backgroundfff url imagesimagesbgjpg repeatx workive tryed thistoo body backgroundfff url sitestaticimagesimagesbgjpg repeatx css url sitestaticcssstylecss image url sitestaticimagesimagesbgjpg i load picture via stylecss,1 update i rerun benchmark new hpc both hardware well software stack changed setup original answer i put results google spreadsheet contains also results original answer hardware our hpc two different nodes one intel sandy bridge cpus one newer ivy bridge cpus sandy mkl openblas atlas cpu x intelr xeonr e sandy bridge ghz cores ram gb ivy mkl openblas atlas cpu x intelr xeonr e v ivy bridge ghz cores ht cores ram gb software the software stack nodes sam instead gotoblas openblas used also multithreaded atlas blas set threads hardcoded os suse intel compiler ictce numpy openblas atlas dotproduct benchmark benchmarkcode however new machines i also ran benchmark matrix sizes the table includes benchmark results original answer renamed mkl nehalem mkl netlib blas nehalem netlib blas etc single threaded performance multi threaded performance threads threads vs matrix size ivy bridge mkl benchmark suite single threaded performance multi threaded threads performance conclusion the new benchmark results similar ones original answer openblas mkl perform level exception eigenvalue test the eigenvalue test performs reasonably well openblas single threaded mode in multithreaded mode performance worse the matrix size vs threads chart also show although mkl well openblas generally scale well number coresthreadsit depends size matrix for small matrices adding cores improve performance much there also approximately performance increase sandy bridge ivy bridge might either due higher clock rate ghz andor better architecture original answer some time ago i optimize linear algebra calculationsalgorithms written python using numpy blas i benchmarkedtested different numpyblas configurations specifically i tested numpy atlas numpy gotoblas numpy mkl numpy accelerate framework mac os x i run two different benchmarks simple dot product matrices different sizes benchmark suite found here results machines linux mkl atlas nomkl gotoblas os ubuntu lucid bit cpu x intelr xeonr e ghz cores ram gb intel compiler scipy numpy mac book pro accelerate framework os mac os x snow leopard cpu intel core duo ghz cores ram gb scipy numpy mac server accelerate framework os mac os x snow leopard server cpu x intelr xeonr e ghz cores ram gb scipy numpy dot product benchmark code import numpy np nprandomrandomsamplesizesize b nprandomrandomsamplesizesize timeit npdotab results system size size size netlib blas ms ms ms atlas cpu ms ms ms mkl cpus ms ms ms mkl cpus ms mkl cpus ms ms ms gotoblas cpu ms ms ms gotoblas cpus ms ms ms gotoblas cpus ms ms ms mac os x cpu ms ms ms mac server cpu ms ms ms benchmark suite code for additional information benchmark suite see results system eigenvalues svd det inv dot netlib blas ms ms ms ms ms atlas cpu ms ms ms ms ms mkl cpus ms ms ms ms ms mkl cpus ms ms ms ms ms mkl cpus ms ms ms ms ms gotoblas cpu ms ms ms ms ms gotoblas cpus ms ms ms ms ms gotoblas cpus ms ms ms ms ms mac os x cpu ms ms ms ms ms mac server cpu ms ms ms ms ms installation installation mkl included installing complete intel compiler suite pretty straight forward however bugsissues configuring compiling numpy mkl support bit hassle gotoblas small package easily compiled shared library however bug recreate shared library building order use numpy in addition building multiple target plattform work reason so i create file platform want optimized libgotoso file if install numpy ubuntu repository automatically install configure numpy use atlas installing atlas source take time requires additional steps fortran etc if install numpy mac os x machine fink mac ports either configure numpy use atlas apple accelerate framework you check either running ldd numpycoredotblas file calling numpyshowconfig conclusions mkl performs best closely followed gotoblas in eigenvalue test gotoblas performs surprisingly worse expected not sure case apple accelerate framework performs really good especially single threaded mode compared blas implementations both gotoblas mkl scale well number threads so deal big matrices running multiple threads help lot in case use default netlib blas implementation way slow serious computational work on cluster i also installed amd acml performance similar mkl gotoblas i numbers tough i personally would recommend use gotoblas easier install free if want code cc also check eigen supposed outperform mklgotoblas cases also pretty easy use,i would like write program makes extensive use blas lapack linear algebra functionalities since performance issue i benchmarking would like know approach i took legitimate i speak three contestants want test performance simple matrixmatrix multiplication the contestants numpy making use functionality dot python calling blas functionalities shared object c calling blas functionalities shared object scenario i implemented matrixmatrix multiplication different dimensions runs increment matricies set like numpyrandomrandiiastypenumpyfloat numpyrandomrandiiastypenumpyfloat numpy the code used looks like tnumpy timeittimernumpydotm import numpy main import rnumpyappendi tnumpyrepeat python calling blas shared object with function blaslib ctypescdllloadlibrarylibblasso def mulm r notrans ccharn n cinti one cfloat zero cfloat blaslibsgemmbyrefnotrans byrefnotrans byrefn byrefn byrefn byrefone mctypesdataasctypescvoidp byrefn mctypesdataasctypescvoidp byrefn byrefzero rctypesdataasctypescvoidp byrefn test code looks like r numpyzerosii numpyfloat tblas timeittimermulm r import numpy main import r mul rblasappendi tblasrepeat c calling blas shared object now c code naturally little longer i reduce information minimum i load function void handle dlopenlibblasso rtldlazy void func dlsymhandle sgemm i measure time gettimeofday like gettimeofdayampstart null fampnotrans ampnotrans ampdim ampdim ampdim ampone a ampdim b ampdim ampzero return ampdim gettimeofdayampend null dtimesj calctimestart end j loop running times i calculate time passed double calctimetimeval start timeval end double factor return doubleendtvsec factor doubleendtvusec doublestarttvsec factor doublestarttvusec factor results the result shown plot questions do think approach fair unnecessary overheads i avoid would expect result would show huge discrepancy c python approach both using shared objects calculations since i would rather use python program could i increase performance calling blas lapack routines download the complete benchmark downloaded jf sebastian made link possible,3 try listitem item ssplit it give g f n c quite asked probably meant,i string like g fmnc wms bgblr rpylqjyrc gr zw fylb i use split function python get g fmnc wms bgblr rpylqjyrc gr zw fylb now i want split elements seperated lists like g f n c my problem split element abcbd b c b,2 sample g fmnc wms bgblr rpylqjyrc gr zw fylb listx x samplesplit g f n c w b g b l r r p l q j r c g r z w f l b,i string like g fmnc wms bgblr rpylqjyrc gr zw fylb i use split function python get g fmnc wms bgblr rpylqjyrc gr zw fylb now i want split elements seperated lists like g f n c my problem split element abcbd b c b,1 couldn oldnamereplace of course assumption always symbols simple best way go i say works need use module,oldname old i want convert serial number example case oldname old possible pythonic way,2 try string formatting number serialnumber oldd number,oldname old i want convert serial number example case oldname old possible pythonic way,1 an alternative run python code jython normal c based python run time jython converts python code jvm language it cannot therefore call python extensions use c call java classes including jena tdb pure python modules,is possible run jena tdb database python app store large amount rdf data what would native alternative python,1 oldname oldserialnumber oldnameformatserialnumer of course assumes really use,oldname old i want convert serial number example case oldname old possible pythonic way,1 unpack data struct import struct data xxx structunpack bbb data,i using pyserial talk msp module this module transmitting serial i using pyserial read comread but type pyserial receives ascii so i send x msp receives given string something like ☺ x x x how i retrieve data array format i intend the next step plot using pylab,1 the issue i see signature setdata setdataindex value role neither code snippet description problem verbose enough say anything else edit indeed looking qt sources i stand corrected unlike i stated edit return value setdata actually used view the data committed model setmodeldata delegate normally qt uses qstyleditemdelegate whose setmodeldata method actually ignores return value setdata thus view indeed care whether data successfully set when editor cell view closed view displays whatever value cell retrieved data however return value setdata still important wellbehaving models take care return proper value models generally abstract data sources independent views thus models also accessed directly case caller needs check return value setdata know whether operation successful,i qtreeview gui based editabletreemodepy pyqt examples inside model i reimplemented setdata need outofbound value i returning false otherwise returns true def setdataself index value roleqtcoreqteditrole role qtcoreqteditrole return false item selfgetitemindex result itemsetdataindexcolumn value result selfdatachangedemitindex index selfmodified true print setdata returning result return result problem even setdata returning false gui still accepts changed value so i inconsistent data model view what would make sense setdata return false reject value view revert back old value is possible solved actually return value setdata seem matter the qtreeview seem call data reretrieve value afterwards anyway the problem i setdata changed internal data even though returned false if somebody could explain return value setdata used great,1 if requirement print oldd format if need way compute format string import name old fmt resubr lambda r formatlenmgroupname print name print fmt range print fmtformati output old oldd old old old old old,oldname old i want convert serial number example case oldname old possible pythonic way,1 python hash function designed speed maps bit space due birthday paradox means likely get collision billion entries probably way earlier since hash function cryptographical also precise definition hash python implementation may architecture even machinespecific don use want result multiple machines md designed cryptographic hash function even slight perturbations input totally change output it also maps bit space makes unlikely ever encounter collision unless specifically looking one if handle collisions ie test equality members bucket possibly using cryptographic algorithm like md sha python hash function perfectly fine one thing to save space store data binary form write disk ie structpack q hash abc hashlibmd abc digest as side note equivalent python you mean,i need compare large chunks data equality i need compare many per second fast every object guaranteed size possiblelikely may slightly different unknown positions i seen interactive session using operator byte strings slower differences towards end string fast difference near start i thought might way speed things using sort hash course computing md hash comparing fair whack slower python inbuilt hash seem speed things significantly however i idea implementation details hash really hashlike i comfortable hasha hashb b likely i happy incorrect results hash collision reasonably rare rare sense needing array pss several hours make collision in import hashlib in open devurandom f spam fread in spama spam a in aspam a spam in spamb spam b in timeit spama spamb loops best ms per loop in timeit spama aspam loops best ns per loop in timeit hashlibmdspama hashlibmdspamb loops best ms per loop in timeit hashlibmdspama hashlibmdaspam loops best ms per loop in timeit hashspama hashspamb loops best ns per loop in timeit hashspama hashaspam loops best ns per loop,3 you optimize store data plain dictionary since provide anything faster sequential access elements dictionary unpredictable order this means solution faster on now databases database universal solution complex enough problem can reliably estimate speedcomplexity lookups database if scroll bottom reply see large data sets database performance much worse smart data structure what need handcrafted data structure there number choices strongly depends stuff data for example keep n sets sorted lists keys sorted n th tuple element then quickly select n sorted sets elements matching one tuple element position n find intersection get results this would give average performance olog nom average number elements one subset or store items kd tree means pay olog n insertion price queries like one olog n time here example python using kd tree implementation scipy scipyspatial import kdtree import itertools import random randomseed data listitertoolspermutationsrange randomshuffledata data datalendata tree kdtreekdtreedata def matcha b assert lena lenb v enumeratea v bi v none bi none return false return true def findlikekdtree needle assert lenneedle kdtreem def dofindtree needle hasattrtree idx return listitertoolsifilterlambda x matchneedle x kdtreedatatreeidx needletreesplitdim none return dofindtreeless needle dofindtreegreater needle needletreesplitdim treesplit return dofindtreeless needle else return dofindtreegreater needle return dofindkdtreetree needle def findlikebfkdtree needle assert lenneedle kdtreem return listitertoolsifilterlambda x matchneedle x kdtreedata import timeit print kd tree print f sec timeittimeitfindliketree none none main import findlike tree number print brute force print f sec timeittimeitfindlikebftree none none main import findlikebf tree number and test run results python lookuppy kd tree sec brute force sec just fun also added databasebased solution benchmark the initialization code changed randomseed data listitertoolspermutationsrange randomshuffledata now database implementation import sqlite db sqliteconnectmemory dbexecutecreate table x integer x integer x integer x integer dbexecutecreate index x on ax dbexecutecreate index x on ax dbexecutecreate index x on ax dbexecutecreate index x on ax dbexecutemanyinsert into values intx x value value treedata def dbtest cur dbcursor curexecuteselect from where x and x return curfetchall print sqlite db print f sec timeittimeitdbtest main import dbtest number and test results reduced runs per benchmark resulting element set keys python lookuppy building tree done sec building db done sec kd tree sec sqlite db sec it also worth mentioning building tree took almost twice less time inserting test data set database complete source httpsgistgithubcom,i dictionary uses tuple key i need find keys dictionary partially match tuple i code slow needs optimizing here i keys match none none result current code def gettuplesself keywords tuples k selfchainiterkeys match true rangeselforder keywordsi none keywordsi ki match false break match true tuplesappendk return tuples keywords list containing values i want match selfchain dictionary selforder size tuple lenkeywords always lenk none considered wild card the dictionary pretty huge method taking ms run mb space also consideration i basically looking either optimizations method better way storing data,2 here basic example using standard libraries import socketserver import threading class handlersocketserverstreamrequesthandler def handleself print selfclientaddress connected selfserveraddclientselfrequest data selfrequestrecv data break selfserversendselfrequestdata selfserverremoveclientselfrequest class serversocketserverthreadingtcpserver def initselfargskwargs socketserverthreadingtcpserverinitselfargskwargs selfclients selflock threadinglock def addclientselfc selflock selfclientsappendc def removeclientselfc selflock selfclientsremovec def sendselfsenderdata selflock c selfclients c sender csendalldata server handler sserveforever,i looking short example python tcp server passing incoming client message another new client all i could find examples echo serverclients cheers dhpizza,2 so i figured thanks cyraxjoe here code import sys sysstdout sysstderr import os atexit import threading import cherrypy makotemplate import template makolookup import templatelookup cherrypyconfigupdate environment embedded cherrypyenginestate cherrypyenginestartblockingfalse atexitregistercherrypyenginestop localdir ospathdirnamefile absdir ospathjoinosgetcwd localdir path ospathjoinabsdir files templpath ospathjoinabsdir html tpl templatelookupdirectoriestemplpath inputencoding utf outputencoding utf encodingerrors replace def errorpagestatus message traceback version tmpl tplgettemplatemako return tmplrenderstatus message cherrypyconfigupdate errorpage errorpage class root cpconfig errorpage errorpage def indexself tmpl tplgettemplateindexmako return tmplrendertext some text url cherrypyurl indexexposed true application cherrypyapplicationroot none import posixpath def applicationenviron startresponse environ scriptname posixpathdirnameenviron scriptname environ scriptname environ scriptname return applicationenviron startresponse,trying display template rendered mako errors still displays standart error page cherrypy footer additional message in addition custom error page failed typeerror renderbody takes exactly argument given the code def errorpagestatus message traceback version tmpl tplgettemplatemako return tmplrenderstatus message cherrypyconfigupdate errorpage errorpage need help how display completely custom error pages layoutmako template full code import sys sysstdout sysstderr import os atexit import threading import cherrypy makotemplate import template makolookup import templatelookup cherrypyconfigupdate environment embedded cherrypyenginestate cherrypyenginestartblockingfalse atexitregistercherrypyenginestop localdir ospathdirnamefile absdir ospathjoinosgetcwd localdir path ospathjoinabsdir files templpath ospathjoinabsdir html tpl templatelookupdirectoriestemplpath inputencoding utf outputencoding utf encodingerrors replace def errorpagestatus message traceback version tmpl tplgettemplatemako return tmplrenderstatus message cherrypyconfigupdate errorpage errorpage class root def indexself tmpl tplgettemplateindexmako return tmplrendertext some text url cherrypyurl indexexposed true application cherrypyapplicationroot none import posixpath def applicationenviron startresponse environ scriptname posixpathdirnameenviron scriptname environ scriptname environ scriptname return applicationenviron startresponse,1 python three scopes local global builtin if executing following function def foo print bar python looks print function scopes toptobottom first checks local variable foo named print then fails print global scriptmodule object example foo function object if fails well looks builtin module the builtin module functions like print defined it also contains builtin exception classes addition operators different work objects every object type example integer type int the int type defines two integers added result in cpython python pythonorg builtin module basic types int str list etc written c part core python executable file there modules written way notably sys module you find syspy python standard library,what default modules python automatically imported python compiler launched these example print addition mathematical functions they must defined somewhere python i guessed extract information finding example print function come know information get module come,1 there way i know using orm query api but drop level lower use exists sqlalchemysqlexpression sqlalchemysqlexpression import select exists usersexistsselect selectexistsusersquerystatement print engineexecuteusersexistsselectscalar,how check data query exists for example usersquery userqueryfilterbyemail xxcom how i check users email exists now check usersquerycount want check exists thanks,3 you use itertoolsstarmap itertoolsstarmaplambda xy xy zipitertoolsrepeatx lista get desired output btw itertoolsimap python map accept following itertoolsimaplambda xy xy itertoolsrepeatx the default python map stop end insert none but comprehension much better x num num,what would elegant way map two parameter lambda function list values first parameter constant second taken list example lambda xy xy x expected result notes this example actual lambda function complicated assume i use list comprehension,3 python x itertools import repeat maplambda x x ziprepeatx python x maplambda xy joinxy ziprepeatx,what would elegant way map two parameter lambda function list values first parameter constant second taken list example lambda xy xy x expected result notes this example actual lambda function complicated assume i use list comprehension,3 def prependconstantx return maplambda yel x yel,what would elegant way map two parameter lambda function list values first parameter constant second taken list example lambda xy xy x expected result notes this example actual lambda function complicated assume i use list comprehension,3 also could use closure x f lambda xy mapf,what would elegant way map two parameter lambda function list values first parameter constant second taken list example lambda xy xy x expected result notes this example actual lambda function complicated assume i use list comprehension,3 x x really need callable def fx return x f x x,what would elegant way map two parameter lambda function list values first parameter constant second taken list example lambda xy xy x expected result notes this example actual lambda function complicated assume i use list comprehension,2 i assume mean vertical box sizer like wxboxsizer szr new wxvertical the following call add pixels vertical gap szraddspacer in python i guess would look something like szr wxboxsizer wxvertical add stuff gap szraddspacer add stuff gap,how i set gap vertical boxsizer what vertival boxsizer similar alternative method setvgap sets vertical gap pixels cells sizer gridsizer,3 may also interesting find title wxboxsizer httpzetcodecomwxpythonlayout,how i set gap vertical boxsizer what vertival boxsizer similar alternative method setvgap sets vertical gap pixels cells sizer gridsizer,1 configpy applicable leave blank templates path fullpathtotemplate configparsepy class configobject def initself selfconfig configparserconfigparser selfconfigread configpy def getpathself return selfconfigget templates path name main c config print cgetpath trick,i config file want load options dynamicaly entering section options name for instance config file contents templates path fullpathtotemplate configpy file class configobject def initself selfconfig configparserconfigparser selfconfigread configini section selfconfigsections selfdictsection dict k v selfconfigitemssection selfdictsectionk v def fromoptionsself section option section selfdict option selfdictsection return selfdictsectionoption name main c config print cfromoptions templates path edit the question pythonic right way,2 do use lambda x mapxadd,what would elegant way map two parameter lambda function list values first parameter constant second taken list example lambda xy xy x expected result notes this example actual lambda function complicated assume i use list comprehension,1 because written stderr stdout try def runprocesscommand parameters process popencommandparameters stdoutpipestderrpipe return processcommunicate outerr runprocess python managepy test coffeebean print own output printout print own error output printerr,i trying run python script capture output it seems like first output line redirects console instead string managepy commandline utility managing django projects like starting production server running unit tests this code import os string datetime subprocess import popen pipe def runprocesscommand parameters process popencommandparameters stdoutpipe outputprocesscommunicate return output teststatusrunprocess python managepy test coffeebean print own output printteststatus this output ran test ok own output creating test database alias default destroying test database alias default why first lines catched best regards daniel,2 you need parentheses sub allen your code evaluated sub allen that work subtract int string,hello reading python book one exercises says write function named rightjustify takes string named parameter prints string enough leading spaces last letter string column display ok following code prints spaces string allen def rightjustifys print rightjustify allen try subtract number spaces string allen sub len allen def rightjustifys print rightjustify sub allen get unsupported operand types str int work without sub variable i checked type sub comes int,3 as mark says need parentheses around subtraction also work rightjustify argument pass the function simply prints give moment you pass string let rightjustify work string ie work length add appropriate number white space prior printing something like def rightjustifys sub lens news sub print news rightjustify allen,hello reading python book one exercises says write function named rightjustify takes string named parameter prints string enough leading spaces last letter string column display ok following code prints spaces string allen def rightjustifys print rightjustify allen try subtract number spaces string allen sub len allen def rightjustifys print rightjustify sub allen get unsupported operand types str int work without sub variable i checked type sub comes int,3 as far i understood question range a b queries form assign particular range category eg r r c r r c query range total number items particular categories eg find count categories r r a simple implementation using dictionaries given would work i describe example suppose range make assignment follows c c c c now make following assignment c this make updationchangesdeletion previously assigned ranges ranges on n maximum size range b a d category setofalltherangesyouhaveincategory in case deletion previous ranges corresponding sets categories ccc needed last assignment c or stop category c stop category c here updation category starting value required last assignment c a better option make updation ranges olg n would segment trees httpenwikipediaorgwikisegmenttree for example segment tree look something like the leaf nodes ranges you assign value category node given interval traverse tree dividing interval appropriately eg divide proceed directions nodes matching ranges found now interesting thing update children nodes need for example proceed updating children immediately assignments like c this thing called lazy propagation learn httpwwwspojplforumviewtopicphpfampt now query part if number categories small maintain frequency table node update ranges required lazy propagate needed otherwise traverse whole tree leaf node counting complexity become on i think better solution querying may exist it coming mind update lets take small example range categories allowed c c each node fields category categorycounts childrenupdaterequired false c query get divided nodes category set c childrenupdaterequired set true children updated remember update required lazy propagation also node category set c c query propagate along tree towards process reach categories updated c childrenupdaterequired set false childrenupdaterequired set true update category c according current requirement next set childrenupdate required true future updation children already set caseno harm done,suppose large range consecutive integers memory belongs exactly one category two operations must olog n moving range one category another finding category counts given range i pretty sure second operation solved trivially given correct implementation first operation each integer begins category i started set balanced bsts moving subtree one bst another eg moving range different category runtime equivalent merging two bsts on n this slow python c option i figure way take advantage data inherent structure create efficient bst merge operation i looking avl redblack interval trees binary heaps treaps comparing properties overwhelming which structure i use edit problem clarification i flexible i store values create data structures i inflexible i receive input comes another application looks like following categorycat i j my current solution creates tree node integer range this slow size dataset i happy rearchitect given better method any given request move possible range integers category in words ranges overlapping sense categorycat followed categorycat nonoverlapping sense every integer exactly one category given time,1 it means says python strings unicode default post unicode use bytestring this work msg btest post,in code i getting error raise typeerrorpost data bytes typeerror post data bytes iterable bytes it cannot str what i wrong i using python below code msg test post passwordmanager urllibrequesthttppasswordmgr passwordmanageraddpasswordtwitter api httptwittercomstatuses sampleusername password httphandler urllibrequesthttpbasicauthhandlerpasswordmanager pageopener urllibrequestbuildopenerhttphandler urllibrequestinstallopenerpageopener params urllibparseurlencode status msg resp urllibrequesturlopenhttptwittercomstatusesupdatejson params respread,2 short answer not usually long answer it take time load module this may noticeable loading python network drive slow source but running directly hard drive never notice as wrar points importing module execute amount code you whatever code want executed module startup however modules avoid executing unreasonable amounts code startup so probably huge cause however importing large modules especially also result importing large number c modules take time so importing take time per module imported if import modules top modules opposed functions applies startup time anyways basically going get much optimisation mileage avoiding importing modules,i running website using django i import ipdb beginning almost scripts make debugging easier however time i never use functions module i debugging just wondering decrease performance it i want create breakpoint i prefer write ipdbsettrace opposed import ipdb ipdbsettrace but i seen second example done several places makes wonder efficient i know importing python modules relates efficiency assuming using module methods within script,1 there gap parameter wxboxsizer gridsizers said the way create gap setting border widgets this done styles wxall wxbottom andor wxtop for example szr wxboxsizerwxvertical szraddselfbutton wxtopwxbottomwxaligncenterhorizontal add centered widget button code box points border top bottom show write vgap szr wxboxsizerwxvertical szraddselfbutton wxtop vgap szraddselfbutton wxtop vgap szraddselfbutton wxtop vgap get buttons gapped similarly would setvgap aswell control separation slots setting vgap as answers indicate also insert separators widgets obtain effect seems cleaner addditional sizeradd lines want something equivalent grids vgap,how i set gap vertical boxsizer what vertival boxsizer similar alternative method setvgap sets vertical gap pixels cells sizer gridsizer,1 as wrar mentioned loading module may imply executing amounts code take amount time on hand module loaded subsequent attempt import find module present ossysmodules reference in django environment debuging mode modules removed django appcache actually reimported changed probably ipdb case issue however cases would issue ways around suppose custom module use load anyway add function imports ipdb require much used module mymodule def settrace import ipdb ipdbsettrace module want use ipdbsettrace import mymodule mymodulesettrace top module use crossmodule debug variable debug ipdp import settrace else def settrace return,i running website using django i import ipdb beginning almost scripts make debugging easier however time i never use functions module i debugging just wondering decrease performance it i want create breakpoint i prefer write ipdbsettrace opposed import ipdb ipdbsettrace but i seen second example done several places makes wonder efficient i know importing python modules relates efficiency assuming using module methods within script,2 modelaobjectsfiltermodelbisnulltrue should work,i two model class modelamodelsmodel fieldmodelscharfieldmaxlength fieldmodelscharfieldmaxlength class modelbmodelmodel fieldmodelsforeignkeymodela fieldmodelscharfieldmaxlength i want get modela modelb modela queryset result how thinks,1 you probably call close followed wait pool object httpdocspythonorglibrarymultiprocessinghtmlmodulemultiprocessingpool join wait worker processes exit one must call close terminate using join,i encountered weird problem using python multiprocessing library my code sketched i spawn process symbol date tuple i combine results afterwards i expect process done computing symbol date tuple release memory apparently case i see dozens processes though i set process pool size suspendedâ¹ machine they consume cpu release memory how i let process release memory done computation thanks â¹ suspended i mean status ps command shown s def doonesymbol symbol alldatestrings pool poolprocesses results date alldatestrings res poolapplyasyncwork symbol date resultsappendres gg mm ss res results g resget gg g mm ss,2 did try close pool using poolclose wait process finish pooljoin parent process keeps running wait child processes become zombies,i encountered weird problem using python multiprocessing library my code sketched i spawn process symbol date tuple i combine results afterwards i expect process done computing symbol date tuple release memory apparently case i see dozens processes though i set process pool size suspendedâ¹ machine they consume cpu release memory how i let process release memory done computation thanks â¹ suspended i mean status ps command shown s def doonesymbol symbol alldatestrings pool poolprocesses results date alldatestrings res poolapplyasyncwork symbol date resultsappendres gg mm ss res results g resget gg g mm ss,3 as general rule whenever trying figure program stalled either launch strace strace myprogpy run strace pid strace p pidnum example ipython pid i run strace po i run con mysqldbconnect xxxxxxxxxxxx user database i see strace produce successful connections setsockopt solsocket sorcvtimeo setsockopt solsocket sosndtimeo setsockopt solip iptos setsockopt soltcp tcpnodelay setsockopt solsocket sokeepalive i sure works pagoda box normal terminal session i would start,i trying use mysqldb python connect database i established pagoda box application first i open pagoda tunnel database pagoda tunnel appname returns tunnel successfully opened connection available i run following commands python idle import mysqldb conn mysqldbconnecthost portuser user passwd pass idle screen freezes ie stuck current command infinite loop it seems hung connect method connectionspy i sure fix any guidance may greatly appreciated update i let script run longer i additionally tried connect using phpmyadmin well simple mysqliconnect script local computer all returned mysql error “lost connection mysql server reading initial communication packet system error ” this seems root problem is configuration i fix pc eliminate issue,1 look so question example objectqueryset conventioncardobjectsfilterowneruser user data serializersserialize json listobjectqueryset fields filename id django serializers serialize queryset values return queryset rather valuesqueryset object,i model many fields however problem i need fields when i try serialize values set i get exception queryset mymodelobjectsfilterfooicontainsbarvalues f f f serializedq serializersserialize json queryset ensureasciifalse,3 there several ways add blank space sizer sizer wxboxsizerwxvertical sizeraddwidget proportion stylewxall border the code add widget pixel border sides if want put space two widgets one following sizer wxboxsizerwxvertical sizeraddwidget proportion stylewxall border sizeraddspacer sizeradd sizeraddanotherwidget proportion stylewxall border the nice thing sizeradd add proportion one want push following widgets bottom i use give little control widget placement see also httpwwwwxpythonorgdocsapiwxsizerclasshtml,how i set gap vertical boxsizer what vertival boxsizer similar alternative method setvgap sets vertical gap pixels cells sizer gridsizer,3 i solved problem version python interpreter reads first line removing version numbers ie usrbinpython usrbinpython,scriptsreplacemdsumspy bash scriptsreplacemdsumspy permission denied replacemdsumspy chmod ls l scriptsreplacemdsumspy rw ubuntu ubuntu scriptsreplacemdsumspy,1 general edit there thingblahthingblahthingblahthing question anymore moreover i remarked r so i completely rewrite answer thingblahthingblahthingblahthing thingblahthingblahthingblahthing displays strings i suppose import ss thingblahthingblahthingblahthing regx recompile def replmat ri recompile return risub matgroup print ss print reprss print print regxsubrepl ss print reprregxsubrepl ss result thingblahthingblahthingblahthing thingblahthingblahthingblahthing thingblahthingblahthingblahthing thingblahthingblahthingblahthing,i need regex search replace commas found inside quote blocks ie thingblahthingblahthingblahthing needs become thingblahthingblahthingblahthing code infile openinfilename r infilerl infilereadlines infileclose p recompiler line infilerl pg psearchline found comment block pg q recompiler found comma within comment block qg qsearchpggroup qg here i want reconstitute line print replaced text print resubr r pggroup i need filter columns i want based regex filter regex replace reconstitute line back how i python,1 you trying assign one client manytomany field this would work foreignkey client manytomany something like tempclientaddclient note temp saved first assign clients this table django uses mapping clients files file first exist add row w null key looking table structure django generates help clear things,i able save mm relationships forms past i currently problems following i understand modelspy class filemodelsmodel client modelsmanytomanyfieldclient product modelsforeignkeyproduct relatedname itemproduct created modelsdatetimefielddefaultdatetimenow createdby modelsforeignkeyuser formspy class fileformmodelform class meta model file exclude client def customsaveselfproductclientuser temp selfsavecommitfalse tempproduct product tempclient client tempcreatedby user tempsave tempsavemm return temp viewspy def newclientviewrequest requestmethod post try iproduct intrequestpost product except valueerror raise http get product post data p productobjectsgetidiproduct formfile fileformp requestpost autoid fs formitemdata itemdataformp requestpost autoid formfileisvalid formitemdataisvalid c client csave tempfile formfilecustomsavepcrequestuser tempitem itemformcustomsavetempfilerequestuser formitemdatacustomsavetempitemrequestuser return redirectclientview cid else return rendertoresponse newclienthtml error the form valid contextinstancerequestcontextrequest else return rendertoresponse newclienthtml contextinstancerequestcontextrequest when i try i get file instance needs primary key value manytomany relationship used and django indicates error comes tempclient client i tried various permutations customsave without much success any ideas,2 you trying save mm relationship object saved commitfalse to create relationship client file file needs saved first see django instance needs primary key value manytomany relationship,i able save mm relationships forms past i currently problems following i understand modelspy class filemodelsmodel client modelsmanytomanyfieldclient product modelsforeignkeyproduct relatedname itemproduct created modelsdatetimefielddefaultdatetimenow createdby modelsforeignkeyuser formspy class fileformmodelform class meta model file exclude client def customsaveselfproductclientuser temp selfsavecommitfalse tempproduct product tempclient client tempcreatedby user tempsave tempsavemm return temp viewspy def newclientviewrequest requestmethod post try iproduct intrequestpost product except valueerror raise http get product post data p productobjectsgetidiproduct formfile fileformp requestpost autoid fs formitemdata itemdataformp requestpost autoid formfileisvalid formitemdataisvalid c client csave tempfile formfilecustomsavepcrequestuser tempitem itemformcustomsavetempfilerequestuser formitemdatacustomsavetempitemrequestuser return redirectclientview cid else return rendertoresponse newclienthtml error the form valid contextinstancerequestcontextrequest else return rendertoresponse newclienthtml contextinstancerequestcontextrequest when i try i get file instance needs primary key value manytomany relationship used and django indicates error comes tempclient client i tried various permutations customsave without much success any ideas,1 simply use mindate minttransactiondate transactions below explanation code working let say transactions three named tuples by definition reduce code reducelambda xy minxtransactiondate ytransactiondate transactions equivalent minminttransactiondate ttransactiondatetransactiondate ttransactiondate clearly inner min returns timestructtime instead named tuple reduce tries apply transactiondate fails there ways fix make use reduce problem however seems little point given direct application min job eye lot clearer anything involving reduce,i log file formatted following way datetimestring username transactionname rn i attempting run stats dataset i following code import time import collections file open logtxt r transactiondata collectionsnamedtuple transactiondata transactiondate user transactionname transactions list line file fields linesplit transactiondate timestrptimefields ymd hms user fields transactionname fields transdata transactiondatatransactiondate user transactionname transactionsappendtransdata fileclose mindate reducelambda xy minxtransactiondate ytransactiondate transactions print mindate i want define class simple dataset i used name tuple when i attempt run i get error traceback recent call last file inquiriesstatpy line module mindate reducelambda xy minxtransactiondate ytransactiondate transactions file inquiriesstatpy line lambda mindate reducelambda xy minxtransactiondate ytransactiondate transactions attributeerror timestructtime object attribute transactiondate it appears lambda function operating transactiondate property directly instead passing full tuple if i change lambda lambda xy minx it works i would expect any ideas would case,3 the csv module perfect parsing data like csvreader default dialect ignores quoted commas csvwriter reinserts quotes due presence commas i used stringio give file like interface string import csv import stringio thingblahthingblahthingblah thingblahthingblahthingblah source stringiostringios dest stringiostringio rdr csvreadersource wtr csvwriterdest row rdr wtrwriterowitemreplace replace item row print destgetvalue result thingblahthingblahthingblah thingblahthingblahthingblah,i need regex search replace commas found inside quote blocks ie thingblahthingblahthingblahthing needs become thingblahthingblahthingblahthing code infile openinfilename r infilerl infilereadlines infileclose p recompiler line infilerl pg psearchline found comment block pg q recompiler found comma within comment block qg qsearchpggroup qg here i want reconstitute line print replaced text print resubr r pggroup i need filter columns i want based regex filter regex replace reconstitute line back how i python,2 of course write binding call c code python ctypes example write tests python really possible easy way smart tests example write dummy c library foolibc int mysumint int int mysumint int b return b compile shared library gcc shared wlsonamefoolib foolibso fpic foolibc write wrapper ctypes foolibtestpy import ctypes import unittest class foolibtestcaseunittesttestcase def setupself selffoolib ctypescdll fullpathtofoolibso def testaself test easy way selffailunlessequal foolibmysum and running test nose nice test c code,python based unit test frameworks like nose lot rich features wonder leverage test c code,3 in etcsudoers file add user allnopasswd somecommand user sudo user somecommand command want run fabric fabric script run sudo shellfalse sudo somecommand shellfalse works,i using fabric run commands remote server the user i connect server sudo privileges require password use privileges when ssh ing server i run sudo blah command executes without prompting password when i try run command via fabric sudo function i get prompted password this fabric builds command following manner using sudo sudo s p sudoprompt binbash l c command obviously user permission execute binbash without password i worked around problem using runsudo blah instead sudoblah i wondered better solution is workaround issue,3 try opennewtab webbrowseropennewtaburl open url new page “tab” default browser possible otherwise equivalent opennew from docs httpdocspythonorglibrarywebbrowserhtml,i’m using webbrowser python module open images internet explorer specifically i’m using webbrowseropen c new command however even though i say new url always opened new browser window what i link opened alreadyopen browser window thank help,1 you get day week like import time timestrftime a tuesday in case ought trick import time dayofweek timestrftime a oschdirmtrsrvcreativechargermonitorout dayofweek,i trying automate ftp upload files folders based day week since today tuesday i would like script go serverfoldertuesday folder upload files folder i oschdirmtrsrvcreativechargermonitorout cwd osgetcwd print cwd gets folder right day folder i need get mtrsrvcreativechargermonitorouttuesday whatever today date ideas,3 i eventually found way i thought i post code anyone may run situation i use gis files set variable directory path instead using envworkspace use cursor search instead arcpysearchcursor function doable import arcpy xlwt arcpy import env xlwt import workbook set workspace location feature class dbf file i used dbf file envworkspace cdata use row object get set field values cur arcpysearchcursorsmuareasdbf set workbook sheet book workbook sheet bookaddsheet sheet bookaddsheet sheet set counter rowx loop rows dbf file row cur rowx write row sheet workbook set column index sheet column dbf sheetwriterowxrowid sheetwriterowxrowshapearea booksave cdatamyexcelxls del cur row,i spending better part weekend trying figure best way transfer data ms access table excel sheet using python i found modules may help execsql pythonexcel limited knowledge modules i use create certain data i gis professional i creating spatial data using arcgis arcpy module access table i sure best approach all i need copy columns data access excel format excel i formatting part solved should i iterate rows using cursor somehow load rows excel copy columns access excel export whole access table sheet excel thanks suggestions,1 import datetime dayname datetimedatetimenowstrftime a oschdirmtrsrvcreativechargermonitorouts dayname cwd osgetcwd print cwd,i trying automate ftp upload files folders based day week since today tuesday i would like script go serverfoldertuesday folder upload files folder i oschdirmtrsrvcreativechargermonitorout cwd osgetcwd print cwd gets folder right day folder i need get mtrsrvcreativechargermonitorouttuesday whatever today date ideas,1 for debian prebuilt package available see you able install aptget something similar,i relatively new linux trying install pygame dev environment python when i run setuppy says i need install following dependencies one i found installed sdl however others elusive hunting dependencies sh smpegconfig command found warning smpegconfig failed sdl found font found image found mixer found smpeg found png found jpeg found scrap found portmidi found porttime found if could give guidance i would appreciate thank,3 if run one supported linux distributions see unix distributions section install pygame repository dependencies installed generally need sdl libsdl friends python numpy,i relatively new linux trying install pygame dev environment python when i run setuppy says i need install following dependencies one i found installed sdl however others elusive hunting dependencies sh smpegconfig command found warning smpegconfig failed sdl found font found image found mixer found smpeg found png found jpeg found scrap found portmidi found porttime found if could give guidance i would appreciate thank,1 i incorrect adding hack setup teardown methods individual class work going reach community find actual bug,i issue getting djangocontribauth unit tests shipped django squeeze pass authenticationbackends set there posts unit testing remote authentication how unit test different settings django regards fixing however tests still failing suggestions i tried adding following setup teardown methods get around djangoconf import settings def setupself selfoldbackend settingsauthenticationbackends settingsauthenticationbackends none def teardownself settingsauthenticationbackends selfoldbackend anyone suggestions getting around thanks advance here paste tracebacks httppastebincomxxdmuzr,1 every entity gae datastore key key id string when creating entity specify value key using keyname atribute example athletegetorinsertkeynamename you remove keyname put model use one comes box query entity using keyname use athletegetbykeynamename due notice key case sensitive probbely need make canonical lower casing also probably url decoding,i form user logs google account makes updates profile google app engine i want use form field contains email address automatically filled user info google new entry key this way i easily update entries since long email entry here form model page post get methods i modify set key class athletedbmodel fields added form norsekey dbuserproperty keyname norsekey firstname dbstringproperty lastname dbstringproperty schoolclass dbstringproperty sex dbstringproperty homeaddress dbstringproperty city dbstringproperty state dbstringproperty zip dbintegerproperty residence dbstringproperty spo dbintegerproperty cell dbintegerproperty sport dbstringproperty sport dbstringproperty sport dbstringproperty class athleteformdjangoformsmodelform class meta model athlete class athleteformpagewebapprequesthandler def getself user usersgetcurrentuser selfresponseoutwriteuser query dbgqlqueryselect from athlete where norsekey user item none item query selfresponseoutwritessbr itemnorsekeyitemfirstname selfresponseoutwrite div stylefloatrighta hrefslog outa div userscreatelogouturl selfresponseoutwrite html body hrefsubmit a treatment loga form methodpost actionathleteformpagehtml table item none selfresponseoutwriteathleteforminitial norsekey itemnorsekey firstname itemfirstname else selfresponseoutwriteathleteforminitial norsekey user selfresponseoutwrite table input typesubmit form body html def postself data athleteformdataselfrequestpost dataisvalid save data redirect view page entity datasavecommitfalse entityaddedby usersgetcurrentuser entityput selfredirect athleteshtml else reprint form selfresponseoutwrite htmlbody form methodpost actionathleteformpagehtml table selfresponseoutwritedata selfresponseoutwrite table input typesubmit formbodyhtml,1 there problem repr looks like value it,i using ujson convert dictionary json i run following line ujsondumps key val i get following result key val i expectwant key val idea,3 i assume prefer change cli programs instead wish catch exception raised sysexit instead gui here import os try ossysexit except systemexit err print caught ya,i program developed python amp reads three files generates code based files in code i several input file checks capture input errors user if program catches input error i used ossysexit command stop processing issue error message i primarily using idle process worked fine now i developed gui program deployment using pyqt the user uses gui input necessary input files conditions gui calls earlier code i generated necessary arguments however i finding user makes error input files earlier code catches errors ossysexit executed gui shutdown completely good i introduced checks input files gui caught treated within gui code but certain processing checks happen inside code gui access the question is way make called code stop running print error message log file example i already use without causing gui quit altogether thanks note the code large point integrate gui class,2 here way using beautifulsoup import beautifulsoup somehtml htmltitleheytitlebodypblahpdivpsomethingpdivbodyhtml soup beautifulsoupbeautifulsoupsomehtml p soupfindall p pparentstring none lenpparentcontents pparentstring pstring pextract soup htmltitleheytitlebodypblahpdivsomethingdivbodyhtml this searches p elements parent content one child p element copies contents p element parent removes p element,i need remove p need such convert divpxxxxpdiv divxxxxdiv how i dom if div one p inside assign p text div remove p i rether regex people say bad i imagine done dom text divpxxxxpdiv is possible solve dom or good old regex better case python javascript,2 this works xmldom import minidom text divpxxxxpdiv doc minidomparsestringtext for div root document tag docchildnodes if p one lentagchildnodes tagchildnodestagname p pnode pxxxp pnode tagchildnodes ptextnode xxx ptextnode pnodechildnodes value pnodenodevalue delete pxxxp pnodeparentnoderemovechildpnode set divdiv divxxxdiv tagappendchildptextnode print doctoxml yields xml version divxxxxdiv i hope accept answer i gave question since i put work,i need remove p need such convert divpxxxxpdiv divxxxxdiv how i dom if div one p inside assign p text div remove p i rether regex people say bad i imagine done dom text divpxxxxpdiv is possible solve dom or good old regex better case python javascript,3 well convert float immediately also dowhile loop python true data input enter number enter quit data break data floatdata this way duplicate code prolong life data name unnecessarily,the purpose program display sum average max min use based input count sum average datafloatinputenter number enter quit mindata maxdata data count numberfloatdata sumnumber averagesumcount datamin mindata datamax maxdata datafloatinputenter number enter quit printcountnumbers entered printsumsum printaverageaverage printminmin printmaxmax the problem line datafloatinputenter number enter quit when press enter end loop says unable convert string float errors what i wrong,2 import time use timesleep import time process getprocess process none â â something else â â wait process end â â isrunningprocess â â â â timesleep i also exact function several scrips read proccmdline check pid,i def getprocess pids process none oslistdir proc iisdigit pidsappendi pid pids proc openospathjoin proc pid cmdline r readline proc something process pid return process def isrunningpid return ospathexistsprocs strpid then process getprocess process none something else wait process end isrunningprocess pass i think best way wait process terminate must function wait something find disclaimer the process child process,1 perpetualtimer repeating version threadingtimer what really want use cherrypyprocesspluginsmonitor little way run separate thread you use plugs cherrypyengine governs start stop behavior cherrypy servers if run thread going want stop cp shuts anyway monitor class already knows it uses perpetualtimer hood recent versions replaced backgroundtask class mytaskrunner monitorcherrypyengine mytask frequency mytaskrunnersubscribe,i using cherrypy receive requests rest api apart handling requests application also resource management every seconds what easiest way run separate thread cherrypyprocesspluginsperpetualtimer sure use looks like heavy resources way the solution separate thread fine i wondering nicer way note cherrypy requirement i decided use primarily project looks alive supports multiple simultaneous connections words i open alternatives,2 read returns string need decode get binary data you could use struct module decoding something along following lines trick import struct fmt cid char int double data inputreadstructcalcsizefmt rev filesize highpoint structunpackfmt data you may deal endianness issues struct makes pretty easy,i file encoded strange pattern for example char byte integer bytes double bytes etc so far i wrote code i able figure still shows garbage screen any help greatly appreciated brkfile commandsbrk input openbrkfile rb rev inputread filesize inputread highpoint inputread inputread print revision rev print file size filesize print high point highpoint print which true opcode inputread print opcode opcode opcode break elif opcodes,3 since method would work linux linuxosx support could import time import os def isrunningpid stat ossystemps p amp devnull pid return stat pid isrunningpid timesleep edit per tmc comment excessive processes referencing check pid use python wouldn use less resources i havent tested listing filesystem opening fds results import time import os def isrunningpid try oskillpid except oserror return false return true pid isrunningpid timesleep,i def getprocess pids process none oslistdir proc iisdigit pidsappendi pid pids proc openospathjoin proc pid cmdline r readline proc something process pid return process def isrunningpid return ospathexistsprocs strpid then process getprocess process none something else wait process end isrunningprocess pass i think best way wait process terminate must function wait something find disclaimer the process child process,1 money portfolio apparently strings cast ints money int floatmoneyfloatportfolio,money portfolio value valueyahoostockgetprice rilbo portfoliovalue print idportfolio print idvalue money moneyportfolio i getting error traceback recent call last file homedeedeepy line module money valueportfolio typeerror unsupported operand types str str since money integer portfolio i cant solve problemanyone help,2 just expand eos answer bit fix problem well judging comment line sounds like added workaround windows bug workaround apparently causing trouble here bit end initpy xxx whatever reasons creating first instance callback function needed unittests win succeed this may compiler bug since problem occurs ctypes compiled ms sdk compiler or uninitialized variable cfunctypecintlambda none it looks like safe remove fwiw issue showed centos x box using python installed parallel python epel the file found usrlibpythonctypesinitpy also note exception shows memoryerror according strace results segmentation fault immediately though perhaps coincidentally call munmap shows running fastcgi,i trying run django shared hosting bluehost i using functionality requires pil pil imports works interactive shell fcgi process crashes memoryerror pil import image any help might failing inside fcgi would much appreciated environment info python local installs libjpg zlib freetype lcms virtualenv django pil flup etc stack trace file feincmsthumbnailpy line module pil import image file pilimagepy line module importfixtk file pythonlibtkfixtkpy line module import ctypes file pythonctypesinitpy line module cfunctypecintlambda none fcgi language python setup paths set djangosettingsmodule osenviron djangocoreserversfastcgi import runfastcgi runfastcgimethodthreaded daemonizefalse,1 as error message clearly states string cast intvar note let see decude error message portfolio must string str means value also string like aaaaaaaaaaaaaaaa apparently missed post relevant code error message tells money str well,money portfolio value valueyahoostockgetprice rilbo portfoliovalue print idportfolio print idvalue money moneyportfolio i getting error traceback recent call last file homedeedeepy line module money valueportfolio typeerror unsupported operand types str str since money integer portfolio i cant solve problemanyone help,1 i think problem assuming initialised variables integer values remain integers python work way assigning value binds name value without paying attention type for example int spam str i assume yahoostockgetprice like many functions get data websites returns string you need convert using int maths,money portfolio value valueyahoostockgetprice rilbo portfoliovalue print idportfolio print idvalue money moneyportfolio i getting error traceback recent call last file homedeedeepy line module money valueportfolio typeerror unsupported operand types str str since money integer portfolio i cant solve problemanyone help,1 valueyahoostockgetprice rilbo apparently returns string number convert number valueintyahoostockgetprice rilbo also signaltonoise ratio high you lots need you assign variable replace next line you make code nicer like money value intyahoostockgetprice rilbo portfolio value print idportfolio print idvalue money portfolio,money portfolio value valueyahoostockgetprice rilbo portfoliovalue print idportfolio print idvalue money moneyportfolio i getting error traceback recent call last file homedeedeepy line module money valueportfolio typeerror unsupported operand types str str since money integer portfolio i cant solve problemanyone help,3 questions like usually frowned upon broad already abundance answers search google you use urllib mechanize library make http post request megaupload looks form values login redir username password post values httpmegauploadcomclogin set username password correct values,it first question today i done little application using wxpython simple megaupload downloader yet support premium accounts now i would like know download mu login free premium user i new python please specific professional i used download files urlretrieve way pass arguments something able log premium user thank d edit news new help needed xd after trying pycurl htmllib mechanize i done login urllib cookiejar requested html says username but i start download file surely server keep login fact downloaded file seems corrupted i changed wait time seconds how i download file megaupload keeping previously done login thanks patient d,1 for logging using python follow following steps find list parameters sent post request url request made viewing source login form you may use browser inspect element feature find easily parameter name examples userid password just check tags name attribute most sites set cookie logging cookie sent along subsequent requests to handle download httllib httpcodegooglecomphttplib read wiki page link given it shown login examples now make subsequent requests files cookies etc handled automatically httplib,it first question today i done little application using wxpython simple megaupload downloader yet support premium accounts now i would like know download mu login free premium user i new python please specific professional i used download files urlretrieve way pass arguments something able log premium user thank d edit news new help needed xd after trying pycurl htmllib mechanize i done login urllib cookiejar requested html says username but i start download file surely server keep login fact downloaded file seems corrupted i changed wait time seconds how i download file megaupload keeping previously done login thanks patient d,1 assuming c d means set c d python version supports dict comprehension set comprehension ugly working solution tr b c c tr b b x x tr x tr set set as example x a b c a b d b c c x b b x x x x x a b set c d but please use realworld application update one works arbitrary depths def todictlst print lst lenlst return return ad todictx x x xd ad lst todictx a b c d,need turn x x a b c a b d into y y a b c d more specifically i need create tree folders files list absolute paths looks like paths xyzfiletxt abcotherfiletxt path split per a b c pseudo example as represents files folders obviously level index array name strings repeat,2 this pretty close need def pathtodictpath parts pathsplit def packparts lenparts return parts elif lenparts return parts packparts return parts return packparts name main paths xyzfiletxt abcotherfiletxt path paths print path pathtodictpath results xyzfiletxt xyz filetxt abcotherfiletxt abc otherfiletxt,need turn x x a b c a b d into y y a b c d more specifically i need create tree folders files list absolute paths looks like paths xyzfiletxt abcotherfiletxt path split per a b c pseudo example as represents files folders obviously level index array name strings repeat,1 alot web stuff python perfer using pycurl get simple post data login curl used accross many languages php python c hope helps,it first question today i done little application using wxpython simple megaupload downloader yet support premium accounts now i would like know download mu login free premium user i new python please specific professional i used download files urlretrieve way pass arguments something able log premium user thank d edit news new help needed xd after trying pycurl htmllib mechanize i done login urllib cookiejar requested html says username but i start download file surely server keep login fact downloaded file seems corrupted i changed wait time seconds how i download file megaupload keeping previously done login thanks patient d,1 x a b c a b d w x w y z path x currentlevel part path part currentlevel currentlevelpart currentlevel currentlevelpart this leaves us containing a b c d w y z x any item containing empty dictionary either file empty directory,need turn x x a b c a b d into y y a b c d more specifically i need create tree folders files list absolute paths looks like paths xyzfiletxt abcotherfiletxt path split per a b c pseudo example as represents files folders obviously level index array name strings repeat,3 pearson correlation coefficient two variables defined covariance two variables divided product standard deviations so covariance standard deviation times standard deviation the standard deviation zero so covariance standard deviation times zero so covariance zero anything divided zero nan the value covariance irrelevant,maybe i made mistake if i sorry ask i want calculate pearson correlation coefficent using scipy pearsonr function scipystatsstats import pearsonr x y pearsonrx y i get error runtimewarning invalid value encountered doublescalars the reason i get error ex excepted value x i look code pearsonr function scpystatsstatspy some part pearsonr function follows mx xmean ymean necessary xm ym xmx ymy xm rnum nnpaddreducexmym rnum xmym x zero vector rden nnpsqrtssxmssym rden r rnum rden invalid value encountered doublescalars at end pearsonr returns nan should pearsonr return i think vector value every rowcolumn covariance zero thus pearson correleation coefficient also zero definition pcc pearson correlation coefficient two variables defined covariance two variables divided product standard deviations is bug i make mistake,3 i really python programmer apparently python oswaitpid that consume less cpu time provide much faster response say trying kill process quartersecond intervals addendum as niko points oswaitpid may work process child current process in case using oskillpid may indeed best solution note general three likely outcomes calling oskill process if process exists belongs call succeeds if process exists belong another user throws oserror errno attribute set errnoeperm if process exist throws oserror errno attribute set errnoesrch thus reliably check whether process exists something like def isrunningpid try oskillpid except oserror err errerrno errnoesrch return false return true,i def getprocess pids process none oslistdir proc iisdigit pidsappendi pid pids proc openospathjoin proc pid cmdline r readline proc something process pid return process def isrunningpid return ospathexistsprocs strpid then process getprocess process none something else wait process end isrunningprocess pass i think best way wait process terminate must function wait something find disclaimer the process child process,3 without getting too much detail phonon package works quick snippet pyqtphonon import phonon source phononmediasourcehttpvsyamuzikanarodrutvistrockaroundtheclockmp selfuivideoplayermediaobjectsetcurrentsourcesource selfuivideoplayerplay you create list mediasource objects swap player,here link ui file and code start gui import sys pyqt import qtcore qtgui gui import uiform class startqtqtguiqmainwindow def initself parentnone qtguiqwidgetinitself parent selfui uiform selfuisetupuiself name main app qtguiqapplicationsysargv myapp startqt myappshow sysexitappexec py and gui class code py coding utf form implementation generated reading ui file finalguiui created mon oct pyqt ui code generator warning all changes made file lost pyqt import qtcore qtgui try fromutf qtcoreqstringfromutf except attributeerror fromutf lambda class uiformobject def setupuiself form formsetobjectnamefromutfform formresize formsetwindowtitleqtguiqapplicationtranslateform form none qtguiqapplicationunicodeutf selftabwidget qtguiqtabwidgetform selftabwidgetsetgeometryqtcoreqrect selftabwidgetsetobjectnamefromutftabwidget selfintro qtguiqwidget selfintrosetobjectnamefromutfintro selfframe qtguiqframeselfintro selfframesetgeometryqtcoreqrect selfframesetframeshapeqtguiqframestyledpanel selfframesetframeshadowqtguiqframeraised selfframesetobjectnamefromutfframe selftextbrowser qtguiqtextbrowserselfframe selftextbrowsersetgeometryqtcoreqrect selftextbrowsersethtmlqtguiqapplicationtranslateform doctype html public wcdtd html en httpwwwworgtrrechtmlstrictdtdn htmlheadmeta nameqrichtext content style typetextcssn p li whitespace prewrap n styleheadbody style fontfamily ms shell dlg fontsizept fontweight fontstylenormaln p aligncenter style margintoppx marginbottompx marginleftpx marginrightpx qtblockindent textindentpxspan style fontsizept fontweight textdecoration underlinerevolution musicspanpn p aligncenter style margintoppx marginbottompx marginleftpx marginrightpx qtblockindent textindentpxspan style fontsizept fontweight textdecoration underline verticalalignsubby casey calebspanpn p aligncenter style margintoppx marginbottompx marginleftpx marginrightpx qtblockindent textindentpxspan style fontsizept verticalalignsubcoded pythonspanpn p aligncenter style margintoppx marginbottompx marginleftpx marginrightpx qtblockindent textindentpxspan style fontsizept fontweight verticalalignsubinsert introduction paragrahspanpn p aligncenter styleqtparagraphtypeempty margintoppx marginbottompx marginleftpx marginrightpx qtblockindent textindentpx fontsizept verticalalignsubpn p aligncenter style margintoppx marginbottompx marginleftpx marginrightpx qtblockindent textindentpximg srcmusicpiccurrentmusicjpg pbodyhtml none qtguiqapplicationunicodeutf selftextbrowsersetobjectnamefromutftextbrowser selfcheckbox qtguiqcheckboxselfframe selfcheckboxsetgeometryqtcoreqrect selfcheckboxsettextqtguiqapplicationtranslateform project idea none qtguiqapplicationunicodeutf selfcheckboxsetobjectnamefromutfcheckbox selfcheckbox qtguiqcheckboxselfframe selfcheckboxsetgeometryqtcoreqrect selfcheckboxsettextqtguiqapplicationtranslateform research none qtguiqapplicationunicodeutf selfcheckboxsetobjectnamefromutfcheckbox selfcheckbox qtguiqcheckboxselfframe selfcheckboxsetgeometryqtcoreqrect selfcheckboxsettextqtguiqapplicationtranslateform written none qtguiqapplicationunicodeutf selfcheckboxsetobjectnamefromutfcheckbox selfcheckbox qtguiqcheckboxselfframe selfcheckboxsetgeometryqtcoreqrect selfcheckboxsettextqtguiqapplicationtranslateform done none qtguiqapplicationunicodeutf selfcheckboxsetobjectnamefromutfcheckbox selftextbrowser qtguiqtextbrowserselfframe selftextbrowsersetgeometryqtcoreqrect selftextbrowsersethtmlqtguiqapplicationtranslateform doctype html public wcdtd html en httpwwwworgtrrechtmlstrictdtdn htmlheadmeta nameqrichtext content style typetextcssn p li whitespace prewrap n styleheadbody style fontfamily ms shell dlg fontsizept fontweight fontstylenormaln p aligncenter style margintoppx marginbottompx marginleftpx marginrightpx qtblockindent textindentpxspan style fontsizept fontweightproject goalsspanpbodyhtml none qtguiqapplicationunicodeutf selftextbrowsersetobjectnamefromutftextbrowser selfline qtguiqframeselfframe selflinesetgeometryqtcoreqrect selflinesetframeshapeqtguiqframevline selflinesetframeshadowqtguiqframesunken selflinesetobjectnamefromutfline selfcheckbox qtguiqcheckboxselfframe selfcheckboxsetgeometryqtcoreqrect selfcheckboxsettextqtguiqapplicationtranslateform learn pyqt none qtguiqapplicationunicodeutf selfcheckboxsetobjectnamefromutfcheckbox selfcheckbox qtguiqcheckboxselfframe selfcheckboxsetgeometryqtcoreqrect selfcheckboxsettextqtguiqapplicationtranslateform code program none qtguiqapplicationunicodeutf selfcheckboxsetobjectnamefromutfcheckbox selfcheckbox qtguiqcheckboxselfframe selfcheckboxsetgeometryqtcoreqrect selfcheckboxsettextqtguiqapplicationtranslateform compile none qtguiqapplicationunicodeutf selfcheckboxsetobjectnamefromutfcheckbox selfcheckbox qtguiqcheckboxselfframe selfcheckboxsetgeometryqtcoreqrect selfcheckboxsettextqtguiqapplicationtranslateform finished none qtguiqapplicationunicodeutf selfcheckboxsetobjectnamefromutfcheckbox selftabwidgetaddtabselfintro fromutf selfvidtest qtguiqwidget selfvidtestsetobjectnamefromutfvidtest selfvideoplayer phononphononvideoplayerselfvidtest selfvideoplayersetgeometryqtcoreqrect selfvideoplayersetobjectnamefromutfvideoplayer selfseekslider phononphononseeksliderselfvidtest selfseekslidersetgeometryqtcoreqrect selfseekslidersetobjectnamefromutfseekslider selfvolumeslider phononphononvolumesliderselfvidtest selfvolumeslidersetgeometryqtcoreqrect selfvolumeslidersetobjectnamefromutfvolumeslider selfpushbutton qtguiqpushbuttonselfvidtest selfpushbuttonsetgeometryqtcoreqrect selfpushbuttonsettextqtguiqapplicationtranslateform pause none qtguiqapplicationunicodeutf selfpushbuttonsetobjectnamefromutfpushbutton selfpushbutton qtguiqpushbuttonselfvidtest selfpushbuttonsetgeometryqtcoreqrect selfpushbuttonsettextqtguiqapplicationtranslateform stop none qtguiqapplicationunicodeutf selfpushbuttonsetobjectnamefromutfpushbutton selfradiobutton qtguiqradiobuttonselfvidtest selfradiobuttonsetgeometryqtcoreqrect selfradiobuttonsettextqtguiqapplicationtranslateform play none qtguiqapplicationunicodeutf selfradiobuttonsetobjectnamefromutfradiobutton selftabwidgetaddtabselfvidtest fromutf selfbillhaley qtguiqwidget selfbillhaleysetobjectnamefromutfbillhaley selftextbrowser qtguiqtextbrowserselfbillhaley selftextbrowsersetgeometryqtcoreqrect selftextbrowsersethtmlqtguiqapplicationtranslateform doctype html public wcdtd html en httpwwwworgtrrechtmlstrictdtdn htmlheadmeta nameqrichtext content style typetextcssn p li whitespace prewrap n styleheadbody style fontfamily ms shell dlg fontsizept fontweight fontstylenormaln p styleqtparagraphtypeempty margintoppx marginbottompx marginleftpx marginrightpx qtblockindent textindentpx fontsizeptpbodyhtml none qtguiqapplicationunicodeutf selftextbrowsersetobjectnamefromutftextbrowser selfframe qtguiqframeselfbillhaley selfframesetgeometryqtcoreqrect selfframesetframeshapeqtguiqframestyledpanel selfframesetframeshadowqtguiqframeraised selfframesetobjectnamefromutfframe selfgraphicsview qtguiqgraphicsviewselfframe selfgraphicsviewsetgeometryqtcoreqrect selfgraphicsviewsetobjectnamefromutfgraphicsview selfpushbutton qtguiqpushbuttonselfframe selfpushbuttonsetgeometryqtcoreqrect selfpushbuttonsettextqtguiqapplicationtranslateform source none qtguiqapplicationunicodeutf selfpushbuttonsetobjectnamefromutfpushbutton selftabwidgetaddtabselfbillhaley fromutf selftab qtguiqwidget selftabsetobjectnamefromutftab selftabwidgetaddtabselftab fromutf selfretranslateuiform selftabwidgetsetcurrentindex qtcoreqobjectconnectselfpushbutton qtcoresignalfromutfclicked selfvideoplayerpause qtcoreqobjectconnectselfpushbutton qtcoresignalfromutfclicked selfvideoplayerstop qtcoreqobjectconnectselfradiobutton qtcoresignalfromutftoggledbool selfvideoplayerplay qtcoreqmetaobjectconnectslotsbynameform def retranslateuiself form selftabwidgetsettabtextselftabwidgetindexofselfintro qtguiqapplicationtranslateform introduction none qtguiqapplicationunicodeutf selftabwidgetsettabtextselftabwidgetindexofselfvidtest qtguiqapplicationtranslateform video test none qtguiqapplicationunicodeutf selftabwidgetsettabtextselftabwidgetindexofselfbillhaley qtguiqapplicationtranslateform bill haley none qtguiqapplicationunicodeutf selftabwidgetsettabtextselftabwidgetindexofselftab qtguiqapplicationtranslateform blank p none qtguiqapplicationunicodeutf pyqt import phonon my question i get video player load url i toggle radio button labeled play start music sorry i novice really need done please explain since i need implement lot tabs later also scaling pyqt designer just need know i make right dimensions picture,1 your list comprehension looks little weird you using variable iterable item this approach seems work def averagelst return sumlst lenlst b averagea a i created function average readability it matches expected values i think want although use mul suggests i may missing something,this offshoot previous question started snowball if i matrix a i want use meanaverage row values create another matrix b keep row headings intact would i i included matrix a attempt cobbling together list comprehension expected result operator import sumlen matrix a row headings values a apple bear crab list comprehension b asumalena a a expected outcome b apple bear crab,3 i think question makes sense indentation syntax python it make sense ide autoindent code if indented properly already work ide know indentation blocks begin end take example valid code range b j rangeb c j also valid code range b j rangeb c j there possible way ide know correct version intent if going write python code going learn manage indentation there way avoid expecting ide magically clean still get desired result pretty much impossible further example valid code outputdata range outputdataappendstri print joinoutputdata again also valid code wildly different behavior outputdata range outputdataappendstri print joinoutputdata the first produce list strings print joined result console time the second still produce list strings prints cumulative joined result iteration loop print statements the two syntactically correct there problem either could developer wanted an ide know correct it could easily incorrectly change first version second version because language uses indentation syntax way configure ide perform kind formatting,i newbie eclipse i want indent lines code formatting open file pressing shortcut something like i know ctrlshiftf actually work pydev i searching hours success is way eclipse kind like ctrlkd visual studio formats indents source code lines automatically,3 that want class actionregistrytype registry def initcls name bases dic regex dic clsregistrydic regex cls superactionregistry clsinitname bases dic class actionobject metaclass actionregistry class singaction regex r sing class danceaction regex r dance,i base class several subclasses each sub class attribute called regex containing string module level dictionary actiontypes class action regex classmethod def registeractioncls actiontypesclsregex cls class singaction regex r sing singregisteraction class danceaction regex r dance danceregisteraction i want register sub classes actiontypes dictionary using classes regex key i want logic register class confined base class the example work i believe dance sing variables yet available namespace used is way register sub classes dictionary class initialization,3 blog post serial rs connections python import time import serial configure serial connections parameters differs device connecting ser serialserial port devttyusb baudrate parityserialparityodd stopbitsserialstopbitstwo bytesizeserialsevenbits serisopen print enter commands belowrninsert exit leave application input get keyboard input input rawinput python users input input input exit serclose exit else send character device note i happend rn carriage return line feed characters requested device serwriteinput rn let wait one second reading output let give device time answer timesleep serinwaiting serread print,can someone please show full python sample code uses pyserial package wondering send at commands read back,3 scan source matrix generate result matrix onetoone randommatrix generaterandommatrix way want result row randommatrix resultrow value row resultrowappendvalue randomdate resultappendresultrow print result whatever a shorter cryptic way would using comprehensions result value randomdate value row row geneneraterandommatrix,input intended output day day day day day day day day day day day day day day day day day day day day day day day day day related here function generate random days proportion here function generate random valuation matrix,1 getcolisnumeric missing return statement returns none also next time try posting actual functionsmethods involved rather whole class,so i got ginormous humungous class relevant code def getcolisnumericself colname returns iterator cell length named column minselfgetcoliterisnumericcolname i loaded values dict csv file problem csvdictreadercolgetcolisnumeric annpayrll returns none even though values column numbers why yield generate none value,3 i think hit problem different method priori knowledge array would really help the kind thing x probability finding answer first y percent data the splitting problem hope getting lucky python nested list comprehension something writing c function brute force hard using ctypes either the c code i hacked together indexc long indexlong val long data long length long ans foriilengthi datai val returni return python compile mac gcc shared indexc indexdylib import ctypes lib ctypescdll indexdylib libindexrestype ctypesclong libindexargtypes ctypesclong ctypespointerctypesclong ctypesclong import numpy np nprandomseed nprandomrandomintegers print libindex actypesdataasctypespointerctypesclong lena i get wrap python proper function go the c version lot x faster seed warning i good timeit import timeit timeittimer npwherea import numpy np nprandomseed nprandomrandomintegers ttimeit timeittimer libindex actypesdataasctypespointerctypesclong lena import numpy np nprandomseed nprandomrandomintegers import ctypes lib ctypescdllindexdylib libindexrestype ctypesclong libindexargtypes ctypesclong ctypespointerctypesclong ctypesclong ttimeit,how i find index first occurrence number numpy array speed important i interested following answers scan whole array stop find first occurrence itemindex numpywherearrayitem nonzeroarray item note none answers question seem relevant python numpy array help is function return index something array note using ccompiled method preferred python loop,3 i learning python found struggling similar problem one unit tests methods output my passing unit test foo module ended looking like import sys import unittest foo import foo stringio import stringio class footest unittesttestcase def setupself selfheld sysstdout sysstdout stringio def testfooself foo selfassertequalsysstdoutgetvalue hello worldn,i writing tests function like next one def foo print hello world so i want test function code like import sys foomodule import foo def testfoo foo output sysstdoutgetlinestrip stdout stringio instance assert output hello world but i run nosetests parameter test crashes how i catch output unittest nose module,3 i problem i written scripting library supports jsr submited httpbugsjythonorgissue python python r sep gcc linux type help copyright credits license information xbr xbr at least evalxnx seems like would get value back,i using jython jsr ie javaxscript package i expect last line python script returned for example evaluating script class multiplier def multiplyself x return x multipliermultiply i get back i get null instead in hand works test what i wrong here java code public static void mainstring args throws exception scriptengine engine new scriptenginemanagergetenginebynamepython filereader f new filereadermultiplierpy object result engineevalf assertresult ps it works fine jruby groovy rhino ie last line always returned thanks advance,1 i sure i understood correctly saying view get called if set middleware classes normal flow handles request passes middleware gets view here documentation httpsdocsdjangoprojectcomendevtopicshttpmiddlewarefromolddocs inside middleware class able see view function going get called url resolver gets method processviewself request viewfunc viewargs viewkwargs please let know i quite understand question,the url im trying match httpdomaingamesgetdatagenres this request made via ajax get json data external api i cant get make match keeps going middleware handler set im sure fix pretty obvious ive staring way long urlspy djangoconf import settings djangoconfurlsdefaults import patterns include djangocontrib import admin adminautodiscover urlpatterns patterns r blogviewsindex r games giantbombgamesviewsindex r gamesgetdatapresourcew giantbombgamesviewsgetdata r grappelli include grappelliurls r adminfilebrowser include filebrowserurls r admin includeadminsiteurls viewspy def getdatarequest resource url ssapikeysampformats apiurl resource apikey requestformat print url r requestsgeturl return rcontent pagemiddlewarepy djangohttp import http djangoconf import settings pageviews import sitepage class sitepagefallbackmiddlewareobject def processresponseself request response responsestatuscode return response no need check flatpage non responses try return sitepagerequest requestpathinfo return original response errors happened because middleware assume errors caught elsewhere except http return response except settingsdebug raise return response django error traceback recent call last file varwwwhtmltoptopextdjangocoreserversbasehttppy line run selfresult applicationselfenviron selfstartresponse file varwwwhtmltoptopextdjangocoreserversbasehttppy line call return selfapplicationenviron startresponse file varwwwhtmltoptopextdjangocorehandlerswsgipy line call response middlewaremethodrequest response file varwwwhtmltoptoppagemiddlewarepy line processresponse responsestatuscode attributeerror str object attribute statuscode thank advance,1 note code works fine pypy really distinction two function types pypyfijalhelmut python class cpython fecd sep pypy dev gcc linux type help copyright credits license information welcome rlcompleter nice experiences hit tab multiple times and something completely different pypy needs justintime jit class c def initself b pass import inspect inspectgetargspeccinit argspecargs self b varargsnone keywordsnone defaults,i trying use inspect module however seems i use builtin native class else i misunderstood i using python tried python this working import inspect class c def initselfab selfsum b inspectgetargspeccinit argspecargs self b varargsnone keywordsnone defaults this working import inspect import ast inspectgetargspecastifinit traceback recent call last file stdin line module file systemlibraryframeworkspythonframeworkversionslibpythoninspectpy line getargspec raise typeerror r python function formatfunc typeerror slot wrapper init astast objects python function i wondering another technique get parameters automatically in case i think alternative would parse python grammar asdl file explain init ast nodes using code i saw pypy project source i wondering another way,2 have considered using biopython they sequence reader read fasta files and interested coding one take look biopython code edit code added def readfastafp name seq none line fp line linerstrip linestartswith name yield name joinseq name seq line else seqappendline name yield name joinseq open ffasta fp name seq readfastafp printname seq,i trying parse large fasta file i encountering memory errors some suggestions improve data handling would appreciated currently program correctly prints names however partially file i get memoryerror here generator def readfastaentry fp name seq line fp linestartswith tmp tmpappend name tmpappend seq name line seq yield tmp else seq seqjoin line caller stub added part works fp open sysargv r seq readfastaentry fp print seq for fimilar fasta format example pb aatatattcaatatggagagaataaaagaactaagagatctaatgtcacagtctcgcactcgcgagatac tcaccaaaaccactgtggaccacatggccataatcaaaaagtacacatcaggaaggcaagagaagaaccc tgcactcaggatgaagtggatgatg pb aaccatttgaatggatgtcaatccgactttacttttcttgaaagttccagcgcaaaatgccataagcacc acatttccctatactggagaccctcc entry starts stating name etc next n lines data there defined ending data next line beginning,3 getdata view returns string response instead httpresponse object processresponse middleware gets string string statuscode method change view def getdatarequest resource return httpresponsercontent mimetypetextplain,the url im trying match httpdomaingamesgetdatagenres this request made via ajax get json data external api i cant get make match keeps going middleware handler set im sure fix pretty obvious ive staring way long urlspy djangoconf import settings djangoconfurlsdefaults import patterns include djangocontrib import admin adminautodiscover urlpatterns patterns r blogviewsindex r games giantbombgamesviewsindex r gamesgetdatapresourcew giantbombgamesviewsgetdata r grappelli include grappelliurls r adminfilebrowser include filebrowserurls r admin includeadminsiteurls viewspy def getdatarequest resource url ssapikeysampformats apiurl resource apikey requestformat print url r requestsgeturl return rcontent pagemiddlewarepy djangohttp import http djangoconf import settings pageviews import sitepage class sitepagefallbackmiddlewareobject def processresponseself request response responsestatuscode return response no need check flatpage non responses try return sitepagerequest requestpathinfo return original response errors happened because middleware assume errors caught elsewhere except http return response except settingsdebug raise return response django error traceback recent call last file varwwwhtmltoptopextdjangocoreserversbasehttppy line run selfresult applicationselfenviron selfstartresponse file varwwwhtmltoptopextdjangocoreserversbasehttppy line call return selfapplicationenviron startresponse file varwwwhtmltoptopextdjangocorehandlerswsgipy line call response middlewaremethodrequest response file varwwwhtmltoptoppagemiddlewarepy line processresponse responsestatuscode attributeerror str object attribute statuscode thank advance,1 the timetimeintts function wrong try one timectime timegtime timelocaltime functions achieve want python docs time,here code given unix timestamp milliseconds ts return humanreadable date time hrdt def parsetsts hrdt timestrftimea b y hms timetimeintts return strhrdt i getting error typeerror time takes arguments given update this worked hrdt datetimedatetimefromtimestampintts return hrdt,2 i wanted family tree display program python looked pil pyx pyx vastly superior far i tell it functions advertised kind application capabilities complete the documentation little thin definitely newbie programmer hey using python bring interactive console find something works or read module code clean concise the problem i still struggling reaches certain output file size displays blank page the cutoff quite precise one graphic element pushes edge but i talking boxes lines text per box kinds interconnecting lines relatives tended divorce remarry often if building output size i definitely recommend pyx and i hope figure going post answer,i script uses pyx python graphics package quoted httppyxsourceforgenet pyx python package creation postscript pdf files it combines abstraction postscript drawing model texlatex interface complex tasks like plots publicationready quality built primitives however latest news back i wondering pyx still active if best among available python packages similar functionalities thanks regards,1 two popular options producing pdfs python code reportlab producing actual typeset documents matplotlib producing publicationready diagrams numeric inputs like numpy arrays normal python lists,i script uses pyx python graphics package quoted httppyxsourceforgenet pyx python package creation postscript pdf files it combines abstraction postscript drawing model texlatex interface complex tasks like plots publicationready quality built primitives however latest news back i wondering pyx still active if best among available python packages similar functionalities thanks regards,1 i like i guessing iswhatiwant something supposed replace field inplace import csv def handlecsvfileinfilename outfilename openinfilename rb infile openoutfilename wb outfile reader csvreaderinfile lineterminator n writer csvwriteroutfile lineterminator n row reader fieldindex field enumeraterow iswhatiwantfield rowfieldindex parsefield writerwriterowrow this sort pattern occurs lot results really long lines it sometimes helpful break logic opening files different function like import csv def loadsavecsvfileinfilename outfilename openinfilename rb infile openoutfilename wb outfile reader csvreaderinfile lineterminator n writer csvwriteroutfile lineterminator n readwritecsvfilereader writer def readwritecsvfilereader writer row reader fieldindex field enumeraterow iswhatiwantfield rowfieldindex parsefield writerwriterowrow this modularizes code making easier change way files formats handled logic independently additional hints don name variables file builtin function shadowing names bite least expect delimiter default need specify explicitly,i already written i need identifying parsing value i seeking i need help writing column csv file new csv file parsed value here pseudocode somewhat realistic python code i trying given csv file function creates new csv file values parsed def handlecsvfilecsvfile opencsvfile rb file reader csvreaderfile delimiter lineterminator n row reader field row iswhatiwantfield parsedvalue parsefield write new column row containing parsed value i already written iswhatiwant parse functions if i need write completely new csv file i sure open simultaneously read write one,2 everything public python suggestion convention use function implementation detail this enforced language runtime way names decorated semiobfuscated way still public still visible code tries use idiomatic python use getset accessors duplication effort since private scope you use accessors want indirect access member variable code around mark member variable start name provide function actual name you could go great lengths writing reams code try protect user using descriptors meta programming end end code test maintain still guarantee bad things happen worry python survived years way far big deal,i recently posted question stackoverflow i got resolution some one suggested coding style i received input i following question reference prior query how declare private variables inside class python i thought using double underscore variable treated private please correct as per suggestion received use getter setter method shouldn use getter setter please let know suggestion one,3 pep httpwwwpythonorgdevpepspep section designing inheritance address concerns to quote we use term private since attribute really private python without generally unnecessary amount work also if class intended subclassed attributes want subclasses use consider naming double leading underscores trailing underscores if read entire section i would encourage update to answer question title changed the pythonic way use private variables use private variables trying hide something python seldom seen pythonic,i recently posted question stackoverflow i got resolution some one suggested coding style i received input i following question reference prior query how declare private variables inside class python i thought using double underscore variable treated private please correct as per suggestion received use getter setter method shouldn use getter setter please let know suggestion one,2 you use python properties instead getters setters just use instance attribute need something complex make attribute property without changing much code httpadamgomaausblogaugthepythonpropertybuiltin,i recently posted question stackoverflow i got resolution some one suggested coding style i received input i following question reference prior query how declare private variables inside class python i thought using double underscore variable treated private please correct as per suggestion received use getter setter method shouldn use getter setter please let know suggestion one,1 collections import defaultdict import itertools defaultdictlist ij itertoolschainfromiterabledatas isinstancej str diappendj dict like so format later tuples ditems note validated quite easy inside loop,input datas no intended output update i asked real data examples messy codes history a b c if i unpacked a b would contain values if i unpacked a b c would contain every date must much values files ie columns a b c,2 this code written work equally well python x python x i tested python python collections import defaultdict datas no def wantvalueval return true val value want keep try detect numbers trying add val exception means number want return true except typeerror exception means wrong type string whatever return false result defaultdictlist lst datas date val lst wantvalueval resultdateappendval finalresult listresultitems printfinalresult,input datas no intended output update i asked real data examples messy codes history a b c if i unpacked a b would contain values if i unpacked a b c would contain every date must much values files ie columns a b c,1 taking recursive steven rumbalski def averagelst return sumlst lenlst a apple bear crab b key averagevalues key values aiteritems b apple bear crab,this offshoot previous question started snowball if i matrix a i want use meanaverage row values create another matrix b keep row headings intact would i i included matrix a attempt cobbling together list comprehension expected result operator import sumlen matrix a row headings values a apple bear crab list comprehension b asumalena a a expected outcome b apple bear crab,1 you use dict keyword arguments feature python targetfield bbb newdataset testdbtargetfield newdatasetsave,db table null ok select testdb id aaa bbb ccc django code newdataset testdbbbb newdatasetsave i want change code like targetfield bbb newdataset testdb targetfield newdatasetsave how i complete code,1 you write key function selfdata sortedselfdata key lambda w wwordlower,selfdata sortedselfdata keyattrgetter word selfdata list word objects word objects word definition example difficulty attributes i want sort word strings word object code except case insensitive how would i go making sorting case insensitive i tried solutions another question asked i tried said typeerror word object subscriptable what could i make work thanks,1 time calculations tricky months days example hours minutes seconds numbered starting days months numbered starting creating offbyone bugs calculations hint ask month subtract one calculations add one displaying you accounting leap years either best use builtin tools check eventual homework answer although looks like teacher said assume day months import datetime birthday datetimedatetime billion birthday datetimetimedeltaseconds billionctime mon jul,i trying find someone turn billion seconds old user inputs born these values converted seconds i add billion seconds convert back date however i enter certain dates python seems mess such example python says user turn th month note i cant use ifelse datetime heres code yearsec monthsec daysec hoursec minutesec yearintinputplease enter year born monthintinputplease enter month born dayintinputplease enter day born hourintinputplease enter hour born minuteintinputplease enter minute born secondintinputplease enter second born yearcalcyearyearsec monthcalcmonthmonthsec daycalcdaydaysec hourcalchourhoursec minutecalcminuteminutesec syearcalcmonthcalcdaycalchourcalcminutecalcsecond yearnumintsyearsec ssyearnumyearsec monthnumintsmonthsec ssmonthnummonthsec daynumintsdaysec ssdaysecdaynum hournumintshoursec sshoursechournum minutenumintsminutesec ssminutesecminutenum printyou turn seconds old ddd ddd yearnummonthnumdaynumhournumminutenums,1 try something like selfdata sortedselfdata keylambda w attrgetter word wlower though would probably much better simply using selfdata sortedselfdata keylambda w wwordlower,selfdata sortedselfdata keyattrgetter word selfdata list word objects word objects word definition example difficulty attributes i want sort word strings word object code except case insensitive how would i go making sorting case insensitive i tried solutions another question asked i tried said typeerror word object subscriptable what could i make work thanks,1 though i test i think get dec day you plus daynum monthnum cause month day start printyou turn seconds old ddd ddd yearnummonthnumdaynumhournumminutenums,i trying find someone turn billion seconds old user inputs born these values converted seconds i add billion seconds convert back date however i enter certain dates python seems mess such example python says user turn th month note i cant use ifelse datetime heres code yearsec monthsec daysec hoursec minutesec yearintinputplease enter year born monthintinputplease enter month born dayintinputplease enter day born hourintinputplease enter hour born minuteintinputplease enter minute born secondintinputplease enter second born yearcalcyearyearsec monthcalcmonthmonthsec daycalcdaydaysec hourcalchourhoursec minutecalcminuteminutesec syearcalcmonthcalcdaycalchourcalcminutecalcsecond yearnumintsyearsec ssyearnumyearsec monthnumintsmonthsec ssmonthnummonthsec daynumintsdaysec ssdaysecdaynum hournumintshoursec sshoursechournum minutenumintsminutesec ssminutesecminutenum printyou turn seconds old ddd ddd yearnummonthnumdaynumhournumminutenums,1 unlucky case maybe bug curvefit curvefit uses inspect determine number starting values gets confused misled extra self so giving starting value avoid problem i thought however also isscalarp condition i idea i think would good report problem bug p none isscalarp determine number parameters inspecting function import inspect args varargs varkw defaults inspectgetargspecf edit avoiding scalar starting value npisscalar false means example parameter works starting value defined egsimilar example mcoptimize an example two arguments given starting value avoids inspect call everything fine import numpy np scipyoptimize import curvefit class myclassobject def getflowself pressuredrop coeff coeff sets flow based coefficient pressure drop flow coeff pressuredrop coeff return flow def optimizeself startvaluenone coeff pressuredrop nparange flow coeff pressuredrop nprandomrandn return curvefitselfgetflow pressuredrop flow pstartvalue mc myclass print mcoptimize import inspect args varargs varkw defaults inspectgetargspecmcgetflow print args lenargs edit this bug fixed bound methods passed first argument curvefit sufficiently new version scipy commit bug fix submission github,i attempting curve fitting within class instance method curvefit function giving class instance method many arguments the code class heatdatahxhx class handling data heat exchanger experiments several lines methods work fine function def getflowpressuredrop coeff sets flow based coefficient pressure drop flow coeff pressuredrop return flow curvefit function call def setflowarrayself sets experimental flow rate heat exchanger flow selfflowdataflow pressuredrop selfflowdatapressuredrop popt pcov spoptcurvefitselfgetflow pressuredrop flow selfexhflowcoeff popt selfexhflowarray selfexhflowcoeff selfexhpressuredrop gives error getflow takes exactly arguments given i make work defining getflow outside class calling like spoptcurvefitgetflow pressuredrop flow good really needs method within class versatile i want how i get work class instance method i also like able pass self getflow give parameters fit parameters used curvefit is possible,1 outputappendd number this uses python string formatting operations left zero padding,write python program ask user enter string lowercase characters print corresponding twodigit code for example input home output currently i code working make list number i cannot get add front single digit numbers def word output input rawinputplease enter string lowercase characters character input number ordcharacter outputappendnumber print output this output i get word please enter string lowercase characters abcdefghijklmnopqrstuvwxyz i think i may need change list string integers i sure,3 output n n output print output python string formatting operation docs works much like sprintf c languages you give data well string representing format want data in case format string represents integer padded two characters if want display digits nothing else use string join docs method create simple string print joinoutput,write python program ask user enter string lowercase characters print corresponding twodigit code for example input home output currently i code working make list number i cannot get add front single digit numbers def word output input rawinputplease enter string lowercase characters character input number ordcharacter outputappendnumber print output this output i get word please enter string lowercase characters abcdefghijklmnopqrstuvwxyz i think i may need change list string integers i sure,2 i found solution jetbrains forum the forum post includes keymap attachment globally disables alt keys generating symbols quoting forum so digging around i figured option key maps relatively unused symbols take precedence operating system using httpscriptssilorgcmsscriptspagephpsiteidnrsiampidukelele ukelele i able generate optimized emacs keyboard layout you take put librarykeyboard layouts folder reboot switch use keyboard layout mac osx toolbar option key free hotkeying pycharm i write blog post later hope helps,i trying use emacs keybindings pycharm os x they work except alt b inserts beta symbol rather moving back word it puzzling since alt f correctly move forward word also i wondering pycharm support moving matching parentheses brackets like controlmetaf emacs i see option pycharm keybindings preference pane thanks,2 npexpanddims favorite i want add arbitrary axis none npnewaxis good code need flexible axis aix answer npexpanddimsnparange shape npexpanddimsnparange shape example usage demean array given axis x nprandomrandn x xmean traceback recent call last file stdin line module valueerror shape mismatch objects cannot broadcast single shape ax x npexpanddimsxmeanax ax array ax x npexpanddimsxmeanax ax array,i like cast numpy ndarray object shape n one shape n the best i come roll tocol function def tocola return areshapeasize but hard believe ubiquitous operation already built numpy syntax i figure i able hit upon right google search find,1 or use built function designed zfill def word could use str need list â â output â â input rawinputplease enter string lowercase characters strip â â character input â â â â number ordcharacter append character code output string â â â â output strnumberzfill â â print output return output print word please enter string lowercase characters home,write python program ask user enter string lowercase characters print corresponding twodigit code for example input home output currently i code working make list number i cannot get add front single digit numbers def word output input rawinputplease enter string lowercase characters character input number ordcharacter outputappendnumber print output this output i get word please enter string lowercase characters abcdefghijklmnopqrstuvwxyz i think i may need change list string integers i sure,3 note release python using formatting operations way according python standard library docs here docs string methods look strformat the new way outputappendformatnumber,write python program ask user enter string lowercase characters print corresponding twodigit code for example input home output currently i code working make list number i cannot get add front single digit numbers def word output input rawinputplease enter string lowercase characters character input number ordcharacter outputappendnumber print output this output i get word please enter string lowercase characters abcdefghijklmnopqrstuvwxyz i think i may need change list string integers i sure,2 as far i know npany npall boolean arrays shortcircuited in case numpy go entire array twice create boolean condition second time find indices my recommendation case would use cython i think easy adjust example case especially need much flexibility different dtypes shapes,how i find index first occurrence number numpy array speed important i interested following answers scan whole array stop find first occurrence itemindex numpywherearrayitem nonzeroarray item note none answers question seem relevant python numpy array help is function return index something array note using ccompiled method preferred python loop,1 pure numpy solution lili npnannpones ynptrilindices npconcatenatelili array nan nan nan nan nan nan array nan nan nan nan nan nan i sure triangular array want also nptriuindices maybe always faster easy read,any flag please see intended numpycolumnstack traceback recent call last file stdin line module file usrlibpymodulespythonnumpylibshapebasepy line columnstack return nxconcatenatearrays valueerror array dimensions must agree except input intended output na in general nnnnnn na na na na na na nnnnn columns may triangluar zero matrix initially yes understand term na none i got triangular matrix almost lena aa nlenaa keyboardinterrupt nlena aa nlenaa aa transposeaa nlenaa aa array dtype s,1 someone must compiler make python a compiler required get pysqlite working you may able use dbanydbm module instead use flavour dbm pure python alternative this give sql database give key value store likely good enough needs,i digi connectport x i going run simple web server serve information zigbee network attached the httpbaseserver subclasses pure python classes i also want kind database running device as i need complex functionality i thought i would try get pysqlite running embedded box however turns i cannot use gcc box possibiliy get kind database functionality box or i miss possibility get sqlite adapter box,1 you could try using sockets communicate httpdownloadoraclecomjavasetutorialnetworkingsocketsclientserverhtml,in android project i reading xml file continuously updated one python script update data i continuosly reading xml file whenever data updated xml file python script i used app but problem python script android project continuosly accessing one xml file one resource i think concurrency problem takes much time get data xml file write data xml file python script so is simply way communicate python script android app i avoid use xml file directly used data send python script and also gives faster execution i tried this android code accessing xml file public void getdata throws exception try whileisstop isstopparsexmldata catchexception e eprintstacktrace private boolean parsexmlfile get factory documentbuilderfactory dbf documentbuilderfactorynewinstance boolean flagfalse try using factory get instance document builder documentbuilder db dbfnewdocumentbuilder parse using builder get dom representation xml file file filenew filemntsdcardxmldataxml fileinputstream finnull iffileisfile try finnew fileinputstreamfile catchexception e dom dbparsefin flag parsedocument i getting last xml value stop returns true loop i exited catchparserconfigurationexception pce pceprintstacktrace catchsaxexception se seprintstacktrace catchioexception ioe ioeprintstacktrace return flag edit in mind i three options using pipe socket communication aidl so one better if am going wrong please guide thanks,1 since dictionary contain duplicate values ie a b a way find key value iterate dictionary describe or build opposite dictionary recreate modification original dictionary or write class maintains bothways dictionary you manage situations duplicate value appears,fairly new python still struggling much information all documentation i seen dictionaries explain various ways getting value via key i looking pythonic way opposite get key via value i know i loop keys inspect values i find value i looking grab key i looking direct route,3 you could modify approach number ways create list values join blank string printing data outappenddata data print joinmapstr you could skip whole integer conversion step reverse incoming string data print data you could skip integer step join result reversed data print joinreverseddata you could add backspace print commands numbers data print bd data data hopefully one fits requirements,i new python i using v filenamereversenumberpy dataintrawinputenter number print reverse number data adata print datadata so output come like enter number reverse number instead second line printing one extra space every number how overcome,2 there direct route it pretty easy list comprehensions though k k v diteritems v desiredvalue if need occasionally think worth indexing way well could something like class bidictdict def keywithvalueself value defaultnone k v selfiteritems v value return v return default def keyswithvalueself value defaultnone return v k v selfiteritems v value then dkeywithvalue would behave rather like dget except way round you could also make class indexed ways automatically key value would need hashable here three ways could implemented in two separate dicts exposing dictlike methods could perhaps foobykeykey foobyvaluevalue no code given complicated i lazy i think suboptimal anyway in different structure could dkey dinversevalue class bidictdict def initself args kwargs selfinverse superbidict selfinitkey value def setitemself key value superbidict selfsetitemkey value selfinversevalue key def delitemself key del selfinverseselfkey superbidict selfdelitemkey in structure could dkey dvalue class bidictdict def setitemself key value superbidict selfsetitemkey value superbidict selfsetitemvalue key def delitemself key superbidict selfdelitemselfkey superbidict selfdelitemkey notably absent implementations bidict update method slightly complex helpdictupdate indicate need cover without update bidict intended would dupdate also consider whether data structure would appropriate,fairly new python still struggling much information all documentation i seen dictionaries explain various ways getting value via key i looking pythonic way opposite get key via value i know i loop keys inspect values i find value i looking grab key i looking direct route,3 there implicit space printed from python docs a space written object converted written unless output system believes positioned beginning line this case characters yet written standard output last character written standard output whitespace character except last write operation standard output print statement so try print reverse number,i new python i using v filenamereversenumberpy dataintrawinputenter number print reverse number data adata print datadata so output come like enter number reverse number instead second line printing one extra space every number how overcome,1 first handling io python just let sub process stdout stderr go place python second instead actually using time command retrieve resources directly python try something like usrbinpython import os import resource import sys import time cmd joinsysargv stime timetime ossystemcmd fire command etime timetime get resource utilization r resourcegetrusageresourcerusagechildren usertime rruutime systime rrustime resource know clock time figure realtime etime stime print realt strrealtime print usert strusertime print syst strsystime this prints times seconds if really want look like time command format accordingly to answer second part question actually different time commands when running child python getting output usrbintime when run hand getting shell builtin version time try typing type time shell prompt also try running test program like usrbintime testpy see second form,i trying write simple python version time command line program except instead displaying realusrsys times shell record database what i currently wrapperpy usrbinpython import sys subprocess import popen pipe cmd time join v v else v v sysargv p popencmd shelltrue stdinpipe stdoutpipe stderrpipe closefdstrue print pstdoutread print pstderrread for simplicity i excluded database insert code however illustrate problem i using test script usrbinpython import time xrange print timesleep if i run wrapperpy python delaypy i like see seconds print real time followed something like real ms user ms sys ms instead i get output seconds printed user system elapsed cpu avgtextavgdata maxresidentk inputsoutputs majorminorpagefaults swaps how read print output subprocess happens real time also output time differ i run directly shell become jumbled run subprocess inside python script,1 installing latest version python pythonorg fixed problem,when trying install mysql python bindings mysqldb i followed instructions build install macbook running mac os x entering following line terminal usermysqlpythonc jianweigan sudo python setuppy build i get following errors running build running buildpy creating buildlibmacosxi copying mysqlexceptionspy buildlibmacosxi creating buildlibmacosximysqldb copying mysqldbinitpy buildlibmacosximysqldb copying mysqldbconverterspy buildlibmacosximysqldb copying mysqldbconnectionspy buildlibmacosximysqldb copying mysqldbcursorspy buildlibmacosximysqldb copying mysqldbreleasepy buildlibmacosximysqldb copying mysqldbtimespy buildlibmacosximysqldb creating buildlibmacosximysqldbconstants copying mysqldbconstantsinitpy buildlibmacosximysqldbconstants copying mysqldbconstantscrpy buildlibmacosximysqldbconstants copying mysqldbconstantsfieldtypepy buildlibmacosximysqldbconstants copying mysqldbconstantserpy buildlibmacosximysqldbconstants copying mysqldbconstantsflagpy buildlibmacosximysqldbconstants copying mysqldbconstantsrefreshpy buildlibmacosximysqldbconstants copying mysqldbconstantsclientpy buildlibmacosximysqldbconstants running buildext building mysql extension creating buildtempmacosxi compiling sdk seem exist developersdksmacosxusdk please check xcode installation it looks like setuppy build script recognizing os mac os x instead tries locate older version xcode i does anyone know get around problem perhaps manually configuring script recognize os,1 try using enumerate list comprehension index index letter enumerateword letter e,suppose i find index letter e word internet letter e word internet idx wordindexletter but code gives first index how i find rest,3 mark answer better single letter i adding case real substring longer single character if want use strindex take optional start position raise valueerror desired substring found letter e word internet lastindex true try lastindex wordindexletter lastindex print lastindex except valueerror break,suppose i find index letter e word internet letter e word internet idx wordindexletter but code gives first index how i find rest,3 you one test defined report one test one test test method assert statement you several asserts one single test may need assert several results order confirm successful test result so first step desired output would put second assert second test method see two test results,i gone various tutorials stack overflow posts understand selenium output xml test results way hudson readreport html format what i understand syntax use python get results look something like testcaseloginpageverifybuttonpresent fail testcaseloginpageverifybuttonpresent pass currently i drill results hudson formatted useful way i described also report ran one test even though ran multiple assert tests traceback recent call last file dtemptestingappsseleniumscriptssamplescriptssamcodesampletestsoreportspy line teardown selfassertequal selfverificationerrors assertionerror lists differ sign up button issue second list contains additional elements first extra element sign up button issue sign up button issue ran test failed errors generating xml reports code thanks advance help selenium import selenium import unittest xmlrunner os class demounittesttestcase def setupself selfverificationerrors selfselenium seleniumlocalhost chrome httpsworkflowycom selfseleniumstart def testhhself sel selfselenium selopenaccountsregister try selfassertequalsign up fail sign up failsign up button issue except assertionerror e selfverificationerrorsappendstre try selfassertequalsign up fail sign up failsign up button issue except assertionerror e selfverificationerrorsappendstre def teardownself selfseleniumstop selfassertequal selfverificationerrors name main format code way so complaining bad indent unittestmaintestrunnerxmlrunnerxmltestrunneroutput testreports,1 there two issues firstly rpparse method takes list strings add splitn line the second issue rules user agent stored rpdefaultentry rather rpentries if check see contains entry object i sure fault python implementation parser respects first useragent section example given next disallowed the disallow lines ignored i read spec i say malformed robotstxt file python code wrong i would assume former though,i understandong use parse function robotparser module here i tried in rpseturlhttpanilattechwordpresscomrobotstxt in rpparse if regularly crawling wordpresscom sites please use firehose receive realtime push updates instead please see httpenwordpresscomfirehose details sitemap httpanilattechwordpresscomsitemapxml useragent irlbot crawldelay useragent disallow next har har useragent disallow activate useragent disallow signup useragent disallow relatedtagsphp mt refugees useragent disallow cgibin useragent disallow in rpcanfetchhttpanilattechwordpresscomsignup out true as seems rpentries i understanding wrong i tried simpler example problem,1 i probleme trying compile macvim python i finally managed first dynamic option work i seen tip net look configure script help recognized therefore use that equivalent disabling python explain py work you compiled macvim python what i done end reinstall python using official installer python website you config libraryframeworkspythonframeworkversionslibpythonconfig try compile following options configure enablepythoninterp withpythonconfigdirlibraryframeworkspythonframeworkversionslibpythonconfigpythonconfig that gave error end compilation i ignore launch binary anyway works this problem might specific computer seems related icon instalation good luck note way i managed compile macvim python objective necessarily way compile runtime version python,in brief i problem compiling vim preferred python version when i use enablepythoninterp compiles system osx python version when i use enablepythoninterpdynamic i get error vim trying py import sys here i detail git clone httpsgithubcombwincklermacvimgit cd macvim configure enablepythoninterp withpythonconfigdirusrlocallibpythonconfig option affects result checking python usrlocalbinpython checking python version checking python better yep checking python install prefix usrlocal checking python execution prefix usrlocal checking python configuration directory usrlocallibpythonconfig make build succeeded open srcmacvimbuildreleasemacvimapp in opened macvim i type py import sys print sysversion sysexecutable r jun gcc apple inc build usrbinpython why why usrbinpython my default python and lives usrlocalbinpython i searching solution day and i found it dynamic attribute solution explanation after i tried recompile vim dynamic python configure enablepythoninterpdynamic output make open srcmacvimbuildreleasemacvimapp in opened macvim py import sys and comes error e could load library libpythona e sorry command disabled python library could loaded my osx version default python version python usrlocalbinpython can anybody explain python integrating vim compilation and fix error libpythona update i longer environment described question so i test new answers but remaining part mankind appreciate help,3 modify code import pdb def getdata print start pdbsettrace and dropped interpreter prompt press w see call trace this help figure things,i import function package readvideo import getdata i wrote function it following structure def getdata print start print end then i call function videodata getdata on screen i see start end start end i thought may function calls but case i also thought function calls function call function but also case does anybody knows reason strange behavior,1 a pyparsing parser format lines long see annotations following code data pb aatatattcaatatggagagaataaaagaactaagagatctaatgtcacagtctcgcactcgcgagatac tcaccaaaaccactgtggaccacatggccataatcaaaaagtacacatcaggaaggcaagagaagaaccc tgcactcaggatgaagtggatgatg pb aaccatttgaatggatgtcaatccgactttacttttcttgaaagttccagcgcaaaatgccataagcacc acatttccctatactggagaccctcc pyparsing import word nums quotedstring combine oneormore define basic forms integer wordnums key quotedstring endquotechar sequences words made characters a g c t want match one parser combine single string combine default requires elements adjacent within input string want allow intervening end lines add adjacentfalse sequence combineoneormorewordagct adjacentfalse define overall pattern scan attach results names matched element seqentry integerindex keykey sequencesequence seqse seqentryscanstringdata dump matched data print seqdump could also access fields seqindex seqkey seqsequence prints pb aatatattcaatatggagagaataaaagaactaagagatctaatgtcacagtctcgcactcgcgagatactcaccaaaaccactgtggaccacatggccataatcaaaaagtacacatcaggaaggcaagagaagaaccctgcactcaggatgaagtggatgatg index key pb sequence aatatattcaatatggagagaataaaagaactaagagatctaatgtcacagtctcgcactcgcgagatactcaccaaaaccactgtggaccacatggccataatcaaaaagtacacatcaggaaggcaagagaagaaccctgcactcaggatgaagtggatgatg pb aaccatttgaatggatgtcaatccgactttacttttcttgaaagttccagcgcaaaatgccataagcaccacatttccctatactggagaccctcc index key pb sequence aaccatttgaatggatgtcaatccgactttacttttcttgaaagttccagcgcaaaatgccataagcaccacatttccctatactggagaccctcc,i trying parse large fasta file i encountering memory errors some suggestions improve data handling would appreciated currently program correctly prints names however partially file i get memoryerror here generator def readfastaentry fp name seq line fp linestartswith tmp tmpappend name tmpappend seq name line seq yield tmp else seq seqjoin line caller stub added part works fp open sysargv r seq readfastaentry fp print seq for fimilar fasta format example pb aatatattcaatatggagagaataaaagaactaagagatctaatgtcacagtctcgcactcgcgagatac tcaccaaaaccactgtggaccacatggccataatcaaaaagtacacatcaggaaggcaagagaagaaccc tgcactcaggatgaagtggatgatg pb aaccatttgaatggatgtcaatccgactttacttttcttgaaagttccagcgcaaaatgccataagcacc acatttccctatactggagaccctcc entry starts stating name etc next n lines data there defined ending data next line beginning,3 there easier way python join james james this makes use fact python strings iterable,if someone writes james i want program style name james i thought would simple letter name print letter i know get rid last asterix end i friend show c thoughso i understand underlying concept achieve c include stringh include stdioh int mainint argc char argv int argc int len strlenargvi int j j j len j printfcargvij printfcnargvij return,3 it easy name james print joinname edit to understand done verbose code explains concept name james decoratedname name letter name decoratedname decoratedname letter print decoratedname,if someone writes james i want program style name james i thought would simple letter name print letter i know get rid last asterix end i friend show c thoughso i understand underlying concept achieve c include stringh include stdioh int mainint argc char argv int argc int len strlenargvi int j j j len j printfcargvij printfcnargvij return,1 there feature request scheduled numpy httpsgithubcomnumpynumpyissues,how i find index first occurrence number numpy array speed important i interested following answers scan whole array stop find first occurrence itemindex numpywherearrayitem nonzeroarray item note none answers question seem relevant python numpy array help is function return index something array note using ccompiled method preferred python loop,3 the write call defined posix atomicity guarantee so need confirm anything atomic it even guarantee data reached hard drive drive completes successfully successfully reading back data give guarantees either you need use sync family functions get durability guarantees,in cases coder cannot rely system calls atomic eg file nfs filesystem cf nfs overview faq howto documents but atomic system calls ultimately required database work cf atomicity database systems is standard os independent way confirming writes syscalls atomic particular file c python any suggestions subsequent notes atomicity pipes discussed following unix pipe multiple writers what happens write system call called file different processes simultaneously note inparticular man page extract dealing specifically oappend if oappend flag file status flags set file offset shall set end file prior write intervening file modification operation shall occur changing file offset write operation,2 empty set already seen ips seenips set openaccesslogtxt f line lines arr linesplit date arr ip still seen print add seenips set arr seenips print arr date arr seenipsaddarr else ie ip already seen ignore go next line,i need help printing sorted txt logfile problem printing except i dont want print ip number this code textfile openaccesslogtxt entirefile textfilereadlines textfileclose line reversedentirefile try arr linesplit date arr print arr date arr except indexerror e error e as se i want print ip number date page visited but similar ip well maybe see im total beginner thanks,2 class myclassobject def myfuncselfvarname setattrselfvarname myclass amyfunc yes ayes,i class i want something like following class myclass def myfuncself varname selfvarname myclass amyfunc yes printayes i sure set class variable name using function however,3 how scripting client that ensure maximum security also save server resources in words javascript would scripting platform what expose functionality backend javascript functions depending app currently written might require backend work oh way limited javascript actual language google compile javascript first hit list languages use,i developing web based application written php basically ui top database to give users flexible tool i want embed scripting language complex things like fire sql queries loops store data variables in business domain python widely used scripting i also thinking making simple domain specific language the script wrap existing php classes i seeking advise approach development task update i try scripting database using plpgsql postgresql this i use php classes way lua approach appealing seems i want besides python,2 not sure question parts address want random i assuming last bytes using python netaddr library import random netaddrip import ipnetwork ipaddress randomseed ipa ipaddress cafe randomgetrandbits ipn ipnetworkipa ipnprefixlen print ipa print ipn sample output cafec cafec the advantage simple string formatting would easy customize starting address random bit len also netaddr classes many useful attr eg broadcast address network,in test case i need send na random ipv source address fixed prefix for example fixed prefix cafe the remainder address random how achieve python scapy,2 check pip actually running pip also try running pip e pathtoyourenv install,i installed virtualenv created virtual environment called env then i activated environment running source binactivate i sure virtual environment activated command prompt changed reflecting new environment then command prompt i ran pip install lpthwweb i would thought package get installed somewhere env directory instead got installed usrlocallibpythondistpackages is correct behavior could someone please point i something wrong,2 import random m cafe joinx randomrandint m range,in test case i need send na random ipv source address fixed prefix for example fixed prefix cafe the remainder address random how achieve python scapy,2 if bound python could use example lua scripting language lua lightweight language easy learn developed embedding mind there already least two php extensions available nicely embed lua php therefore provide possibility allow access php lua part application have look httppeclphpnetpackagelua this one also nice examples httpphpluauude i already used latter one bit simple experiments works quite good,i developing web based application written php basically ui top database to give users flexible tool i want embed scripting language complex things like fire sql queries loops store data variables in business domain python widely used scripting i also thinking making simple domain specific language the script wrap existing php classes i seeking advise approach development task update i try scripting database using plpgsql postgresql this i use php classes way lua approach appealing seems i want besides python,1 use join threadjoin threadjoin also note setdaemon old api threaddaemon true preferred way,is way pause main python thread application perminantly i code fires two threads class start def initself thread functionsthreadsthread threadsetdaemontrue threadstart thread functionsthreadsthread threadsetdaemontrue threadstart stop thread at moment program gets end function exits there nothing else main thread killing threads run infinately looping how i stop main process exiting i true none loop uses lot cpu probably better way,2 the whole point daemon threads prevent application terminated still running you obviously want threads keep application process alive make daemons,is way pause main python thread application perminantly i code fires two threads class start def initself thread functionsthreadsthread threadsetdaemontrue threadstart thread functionsthreadsthread threadsetdaemontrue threadstart stop thread at moment program gets end function exits there nothing else main thread killing threads run infinately looping how i stop main process exiting i true none loop uses lot cpu probably better way,2 if setdaemontrue threads process keep running long threads run the daemon flag indicates interpreter wait thread it exit daemon threads left,is way pause main python thread application perminantly i code fires two threads class start def initself thread functionsthreadsthread threadsetdaemontrue threadstart thread functionsthreadsthread threadsetdaemontrue threadstart stop thread at moment program gets end function exits there nothing else main thread killing threads run infinately looping how i stop main process exiting i true none loop uses lot cpu probably better way,2 you probably calling connectionclose before psycopg implicit rollback issued connection delete condition guaranteed anymore even considered safe see httpinitdorgpsycopgdocsconnectionhtmlconnectionclose,i got application psycopg pgbouncer gevent asynchronous application ie one process serves multiple requests asynchronous access database appeared latest version psycopg rather but release introduces bug lot disconnections pgbouncer in pgbouncer logs entries log cxbf databaseuser login successful dbdatabase useruser log cxbfa databaseuser login successful dbdatabase useruser log cxb databaseuser closing client close request age log sxbcd databaseuser closing unclean server age log cxbef databaseuser closing client close request age log sxbe databaseuser closing unclean server age log sxbe databaseuser new connection server log cxbf databaseuser closing client close request age log sxbd databaseuser closing unclean server age log sxbd databaseuser new connection server log sxbcd databaseuser new connection server log sxbdbf databaseuser new connection server log sxbcb databaseuser new connection server log cxbff databaseuser login successful dbdatabase useruser log sxbc databaseuser new connection server log cxbf databaseuser login successful dbdatabase useruser log cxbee databaseuser closing client close request age log sxbc databaseuser new connection server log cxbff databaseuser closing client close request age log sxbdaa databaseuser closing unclean server age log cxb databaseuser closing client close request age log sxbdc databaseuser closing unclean server age log sxbdc databaseuser new connection server log cxbfc databaseuser closing client close request age log sxbd databaseuser closing unclean server age log cxb databaseuser closing client close request age log sxbde databaseuser closing unclean server age log cxb databaseuser closing client close request age log sxbe databaseuser closing unclean server age maybe way configure pgbouncer avoid messages unclean server information bug like patch cures something all packages ubuntu repositories apply patches production machine good option my config pgboucner pgbouncer logfile varlogpostgresqlpgbouncerlog pidfile varrunpostgresqlpgbouncerpid listenaddr listenport unixsocketdir varrunpostgresql poolmode session serverresetquery discard all servercheckquery select servercheckdelay maxclientconn defaultpoolsize logconnections logdisconnections,2 you need measure intended purposes results speed if method tend faster i really think going impact overall performance much your main latency rpc call memache might two factor slower slowest serialization,i page handler traffic fetches model db using key uses fields fetched model fill django template i want memcache fetched model avoid db reads not fields model used template want cache required feilds improve cache utilization fit models cache so want convert model dictionary class boject fields required template memcache uses pickle serialize values serialization purpose faster dictionary class object,1 you consider defining getstate setstate methods model class select properties model want cache simplify reification process unpickled data arrives actual instance model instead stand somehow convert another way,i page handler traffic fetches model db using key uses fields fetched model fill django template i want memcache fetched model avoid db reads not fields model used template want cache required feilds improve cache utilization fit models cache so want convert model dictionary class boject fields required template memcache uses pickle serialize values serialization purpose faster dictionary class object,1 you setting linebreak without vim ignores breakat variable see details lots vim goodness also note need set nolist breaks linebreak another blog post dealing word wrapping this one notes filetypes auto include format options flag without auto wrapping occur i think simplest thing would add mapping run pythontidy pythontidy script python take python code stdin output pretty version stdout with mapping allow run current file replace entire contents reformatted version add autocommand run whenever exit insert mode python files set,so problems let say i python file i typing really long line like last one class someclassobject def somemethodself somevariable someotherclasssomeothermethodsomeparametersomevalue when i type vim happens class someclassobject def somemethodself somevariable someotherclasssomeothermethodsomeparametersomevalue that bad style breaks pep what i like happen class someclassobject def somemethodself somevariable someotherclasssomeothermethod someparametersomevalue which keeping pep for purposes discussion i interested line breaking behavior indentation behavior edit breakat works conjunction linebreak govern lines displayed it apparently work conjunction textwidth determine hard line breaks inserted so idea work surprisingly i found nothing indicating others share problem leads think i something wrong nevertheless idea add character breakat setting along i i tried output set breakat breakat i however avail no matter i vim insists breaking i problem long function names well break right def here complete contents vimrc set nobackup set nowritebackup set noswapfile set columns set tabstop set shiftwidth set softtabstop set autoindent set smarttab set smartindent set textwidth set wrap set breakat i filetype indent filetype filetype plugin i plugins etc installed purpose trying figure does anyone idea i get vim obey breakat setting thoughts best way deal behavior,2 i also setup shop almost new language es spanish so i put differences installation in settings i also lcctype esesutf timezone europemadrid allowtranslationchoice false strange worked fine maybe overriden localsettings file i also changed settingspy satchmo unique variables djangoconfurlsdefaults import patterns include satchmosettings shopbase multishop false shopurls patterns satchmostoreshopviews shopurls patterns r include lnurls customshippingmodules flatshippingnormal ssl true if help tried adding languages like de en enable language selector see changes eg german this way find problem dutchtranslation did translated missing messages i looked installation already pofiles nl and least productpo looks fine so probably need run makemessagescompilemessages needed new languages want update pofiles case sourcefiles changed but need updatetranslations i would recommend take look rosetta great have sometimes bugs new generated translationfiles headers i put manually based existing files djangosrc contenttype textplain charsetutfn contenttransferencoding bitn adding headers new files works great and compile pofiles rosetta save,i trying set default shop language satchmo installationto dutch i following instructions translating content from directory homemyusernamewebappsmyshoplibpythonsatchmopyegg i issued following command compile dutch langauge files find name locale exec sh c cd ampamp cd ampamp python homemyusernamewebappsmyshoplibpythondjangobindjangoadminpy makemessages l nl e htmltxtrml i see multiple localenllcmessagesdjangopo files wich contain messagestrings translated dutch my localsettingspy file localepaths variable defined localepaths i compiled po files mo files find name locale exec sh c cd ampamp cd ampamp python homemyusernamewebappsmyshoplibpythondjangobindjangoadminpy compilemessages i want text appear dutch localsettingspy contains languagecode nl languages nl nederlands users ablo choose translations allowtranslationchoice set false settingspy lnsettings currencyformats euro symbol u € positive u€valf negative u€valf decimal defaultcurrency euro showadmintranslations true allowtranslationchoice false file i enabled urls satchmosettings shopbase multishop false shopurls patterns r include lnurls to make sure templates use correct language code i also settingspy templatecontextprocessors satchmostoreshopcontextprocessorssettings djangocorecontextprocessorsauth djangocorecontextprocessorsin after jumping hoops shop language still shows english still change language empty dropdown button lower right corner anyone clue i went wrong thanks advance,1 len tell length list to quote docs lens nbspnbspnbspnbspreturn length number items object the argument may sequence nbspnbspnbspnbspstring tuple list mapping dictionary of course want get final element list tuple string since indexes based length item element count alena last item as aside generally proper way access last element object allows numeric indexing str list tuple etc using obviously involve len though,list say i want see null way without using exception assertion,3 you providing specific usecase generally list would use len see many elements list lena do something,list say i want see null way without using exception assertion,1 use len lena index note your question asks would find null anything get indexerror try check,list say i want see null way without using exception assertion,1 the general way check currently looking element end list language compare current index looking length list minus one since indexes start really anything exist languages may implement null undefined many simply throw exception try access instead,list say i want see null way without using exception assertion,1 import numpy np def splitarr cond return arrcond arrcond nparray print splita nparray print splita this produces following output array array array array,for example i ndarray nparray now i want split two parts one numbers array array certainly i traverse create two new array but i want know numpy provide better ways similarly multidimensional array eg array i want split according first column result array array are better ways instead traverse thanks,3 if server gives indication length requested data sends data closes connection http client must assume successfully transferred only using additional nonhttp information checksum error correction within payload format application determine error occurred use http range header ie range bytesnnnn subsequent client request resume transfer if server support range header may conclude server transmits response header acceptranges none time far i know recourse broken server implementation except periodically retry request hoping eventually serves response passes error detection footnote it surprise contentlength header missing serving blob contents many database apis allow length blob tested without actually retrieving entire thing i suspect reason lack support test sql engines,properly download file python http response contain contentlength header im issue appengine sendblob function reason add contentlength header bigger mb blobs right im using urlliburlretrieve sometimes download whole file im right sending content length downloading file check file right size proceeding im sure better way headers one files http ok cachecontrol nocache contenttype applicationoctetstream expires fri jan gmt date fri sep gmt server google frontend transferencoding identity connection close tried use wget download file wget serverresponse continue headers http ok cachecontrol nocache contenttype applicationoctetstream expires fri jan gmt date wed oct gmt server google frontend transferencoding chunked length unspecified applicationoctetstream,1 in research question i found essentially three options use google authentication mechanisms including federated login via openid pros you easily check logged via users service provided appengine google handles security quite sure well tested cons this integrate third party openid providers cannot integrate facebooktwitter time use social authentication mechanisms provided known framework tipfy django pros these integrate major social authentication services they quite widely used likely quite robust pretty well tested cons while probably well tested may maintained they come part larger framework may get comfortable deploying app roll social authentication pros you mix whatever flavours openid oauth tickles fancy cons you likely introduce security holes unless bit experience working technologies likely time consuming further notes it probable everyone move openid eventually standard google authentication work everywhere the first option allows point finger google problem authentication second option imposes responsibility still allows say use widely used solution problem final option puts responsibility most issues revolve around session management case google session management pretty invisible developer case session management handled framework rd case devise,this question intended means capture findings sanity check i put answer toute suite see answers comments appear i spent little time trying get head around different social authentication options python appengine i particularly confused authentication mechanisms provided google interact social authentication mechanisms the picture complicated fact google nice integration third party openid providers biggest social networks openid providers eg facebook twitter note facebook use openid relaying party provider the question following different options social authentication appengine pros cons,3 this question covered several times see django tips laying application web application django typical project folder structure best practice folder hierarchy django web app,i set project wondering best way i notice open source files apps directory stores thirdparty apps etc i looking following two projects httpsgithubcomjosephmisitinewsblur httpsgithubcomdkukraleveryblock my project consist code run multiple different connected web applications i also found httpsgithubcomlincolnloopdjangostartprojecttreemasterdjangostartprojectprojecttemplatemyproject thanks,1 ah found axyaxissettickspositionright instead trying control tracker swap location yaxes axyaxissettickspositionright axyaxissettickspositionleft axplott g label axplott r label afaik tracker always follows ax using twinx,the tracker lowerright corner highlighted red reports yvalues relative yaxis right how i get tracker report yvalues relative yaxis left instead import matplotlibpyplot plt import numpy np nprandomseed numdata nplinspace numdata npcumsumnprandomrandomnumdata npcumsumnprandomrandomnumdata fig pltfigure ax figaddsubplot ax axtwinx axplott r label axplott g label axlegend pltshow i know swapping make tracker report yvalues also places tickmarks righthand side i want happen axplott g label axplott r label,2 i sure standard way store custom metadata python objects example python implementation dbus adds attributes dbus prefix published methods signals,i working structured data analysis framework based streaming data nodes currently nodes implemented subclasses root node class provided framework for node classfactory i need metadata list node attributes description node output the metadata might endusers frontend application programming use stream management tools in future note i started learn python writing code currently metadata provided class variable class aggregatenodebasenode aggregate nodeinfo label aggregate node description aggregate values grouping key fields output key fields followed aggregations aggregated field last field record count attributes name keys description list fields according records grouped name recordcountfield description name field record count stored default recordcount more examples found i feel done much cleaner way there one restriction nodes custom subclasses classes minimal interference potential future attribute names what i thinking split current nodeinfo it meant private framework i realize much wider use i thinking using node attributes common attribute namespace taking much names potential custom node attributes my question what common way providing metadata python programs single variable dictionary multiple variables one metadata attribute would conflict restriction custom classstructure use kind prefix like node use multiple variables,1 solved i discovered problem uncommon mixing gcc versions mac after reading solution mpich checking mpich source code i found solution add following flag gcc mac systems flatnamespace i happy i wish taken week figure,executive summary python module linked different version libstdcdylib python executable the result calls iostream module crash backstory i creating python module using swig older computer running for various reasons i using gcc installed via macports using python installed via macports compiled using systemdefault gcc observed behavior to make long story short calling str myobject python causes c code turn call stdoperator stdchartraitschar this generates following error python malloc error object xc nonaligned pointer freed set breakpoint mallocerrorbreak debug setting breakpoint calling backtrace fails gives xde mallocerrorbreak xad szoneerror xefdfc stdstringrepmdestroy xe stdbasicstringchar stdchartraitschar stdallocatorchar basicstring xeb stdbasicstringbufchar stdchartraitschar stdallocatorchar overflow xeea stdbasicstreambufchar stdchartraitschar xsputn x stdostreaminsertchar stdchartraitschar xd stdoperator stdchartraitschar x meshliboperator transupportdimensionunsigned short osxbfffc cxac userssethrjcodepytrtmeshlibonedcellcpp xb meshlibcellsltransupportdimensionslusgsgstr selfxac userssethrjcodebuildpytrtgccdebugmeshlibswigmeshonedpythonwrapcxx xd wrapcelltstr argsxeb userssethrjcodebuildpytrtgccdebugmeshlibswigmeshonedpythonwrapcxx xf pyevalevalframeex xfbb pyevalevalcodeex snip suspected issue i believe issue code links new version libstdc optlocallibgcclibstdcdylib compatibility version current version whereas python binary indirect dependence system libstdc loads first output info shared gdb dyld xfe dyld y y usrlibdyld xfe offset x prefix dyld python x exec y y optlocallibraryframeworkspythonframeworkversionsresourcespythonappcontentsmacospython offset x objfile optlocalbinpython python f x dyld y y optlocallibraryframeworkspythonframeworkversionspython x offset x libsystembdylib xd dyld y y usrliblibsystembdylib xd offset xdc commpage objfile usrliblibsystembdyliblcsegmentdatacommpage corefoundation f xb dyld y y systemlibraryframeworkscorefoundationframeworkversionsacorefoundation xb offset xfd libgccsdylib xe dyld y y usrliblibgccsdylib xe offset xdca libmathcommonadylib xaf dyld y y usrlibsystemlibmathcommonadylib xaf offset xbb libicucoreadylib xcf dyld y y usrliblibicucoreadylib xcf offset xc libobjcadylib xf dyld y y usrliblibobjcadylib xf offset xd commpage objfile usrliblibobjcadyliblcsegmentdatacommpage libautodylib xeac dyld y y usrliblibautodylib xeac offset xa libstdcdylib xed dyld y y usrliblibstdcdylib xed offset xc meshonedso x dyld y y userssethrjcodebuildpytrtgccdebugmeshlibswigmeshonedso x offset x libhdfdylib xc dyld y y optlocalliblibhdfdylib xc offset xc libzdylib x dyld y y optlocalliblibzdylib x offset x libstdcdylib x dyld y y optlocallibgcclibstdcdylib x offset x snip note malloc error occurs memory address system libstdc one shared library linked attempted resolutions i tried force macports build python using gcc rather apple compiler install phase fails needs create mac framework vanilla gcc apparently even staticlibstdc compiler flag ostreaminsert calls stdbasicstreambuf systemloaded shared library i tried modifying dyldlibrarypath prepending optlocallibgcc without avail what i get work i wit end more information this problem seems common mac os x notice debug outputs show address jumps calls stdostreaminsert stdbasicstreambufxsputn leaving new gcc code jumping older shared library code usrbin now find workaround,2 i prefer limit number retries problem specific item eventually continue onto next one thus range attempt range try thing except perhaps reconnect etc else break else failed attempts deal consequences,i loop starting range normally runs correctly sometimes fails due network conditions currently i set failure continue except clause continue next number is possible reassign number run failed iteration loop,3 you may realize trying something hard tkinter while text widget tags powerful concept weaknesses comes creating something like wysywig editor you need change approach bit instead inserting spaces i think better solution add bindings apply remove tags time character inserted this set problems enough attention detail overcome we though custom key binding when insert character text widget handled binding key event text widget class so could bind key add tag however add binding key widget fire class binding meaning code execute character inserted rather we trying modify something actually inserted widget yet one way solve bind key release rather key press since character inserted press however think scenario user presses holds key multiple characters entered may get single keyup event so solution particularly good another solution somehow arrange custom binding happen default binding to need two things adjust bind tags widget additional tag class tag add binding new bind tag there downsides approach not bind tags lot events need handle besides key example controlv paste handled key binding add special case pasting that said solution might good enough least good enough help better understand problem understanding problem often biggest obstacle finding solution in following example i text widget additional bindtag named customtext place standard text bind tag i put binding tag key event handler i simply apply appropriate tags justinserted character you add code handle clipboard paste problem dealing conflicting tags two tags font hopefully though example act inspiration import tkinter tk class sampleapptktk def initself args kwargs tktkinitself args kwargs selftagvars underline tkintvar red tkintvar selftext mytextself width height selftexttagconfigurered foregroundred selftexttagconfigureunderline underlinetrue toolbar tkframeself selfunderline tkcheckbuttonself textunderline onvalue true offvaluefalse variable selftagvarsunderline selfred tkcheckbuttonself textred onvalue true offvaluefalse variable selftagvarsred selfunderlinepackintoolbar sideleft selfredpackintoolbar sideleft toolbarpacksidetop fillx selftextpacksidetop fillboth expandtrue class mytexttktext def initself parent args kwargs tktextinitself args kwargs selfparent parent add new bind tag customtext code run class binding done work bindtags listselfbindtags bindtagsindextext bindtagsinserti customtext selfbindtagstuplebindtags set binding fire whenever selfinserting key pressed selfbindclasscustomtext key selfonkey def onkeyself event assuming called whenever character inserted apply remove tag depending state checkbutton tag selfparenttagvarskeys usetag selfparenttagvarstagget usetag selftagaddtag insertc insert else selftagremovetag insertc insert name main app sampleapp appmainloop,i need help tagrelated i writing simple editor supporting basic formatting by using text widget named text i put tag b set text tag applies bold this problem i apply bold selection texttagadd b selfirstsellast i instead two problems i want switch onoff bold typing to switch way i found textinsertinsert b textmarksetinsert insert c notice i insert two spaces if i insert one bold doesnt apply if i insert cursor goes back one char my second problem switch i writing within bolded region i havent slightest idea thanks help,1 case throw indexerror exception comparing value index none you values none list compare values encounter none mean index found list for example anone anone true traceback recent call last file stdin line module indexerror list index range since lists contiguous indexed sequentially correct way check index list compare len list depending application ways around like catching indexerror iteration index value enumeratea print index value none,list say i want see null way without using exception assertion,1 so aii tells index ai ai creates another list possible long aii element empty,list say i want see null way without using exception assertion,1 sessions authentication pyramid general disjoint concepts there lot people learn way store authenticated user session way requirement the point session store arbitrary data visitor site across requests that could fact logged could random strings the point store random stuff session it available pyramid setup sessionfactory configurator directly request object via requestsession requestsession mykey random value this require use authentication rememberforget anything session factory httpsdocspylonsprojectorgprojectspyramidnarrsessionshtml,i pyramid application using beaker encrypted cookie sessions i log user using requestwithuserattribute pyramidsecurityauthenticateduserid remember forget fine however majority users never log specific value i like save cookie encrypted possible user given site location string matter i cannot discover set principal session using remember function i prefer send setcookie headers let alone deal encryption data i found pass keyword arguments remember rememberrequest principal kw but i try send extra values i continuously run error ideally i would expect something like rememberrequest public location requestparamsget location is even correct route,1 i bet generate sql metadata references getting mixed you seem using two different metadata objects table classes really good you need one the metadata tracks staleness objects whether needs issue queries object updates foreign key constraints etc needs know tables relationships change use single metadata object pass echotrue sqlalchemycreateengine call print sql query using standard output try executing query logged role user postgres you may find simple permissions issue regarding copypasting i think django good convention placing table declarative classes module importing however pass metadata object table factory complicates matters you use singletonglobal metadata object convert declarative for i chose implement oneargument functions returned table objects given metadata cached resultin effect implementing singleton model class then i decided silly switched declarative,i trying alter column name first attempt script meta metadata users table users meta column id integer primarykeytrue column name string uniquetrue column email string uniquetrue def upgrademigrateengine metabind migrateengine userscidaltername id def downgrademigrateengine metabind migrateengine userscidaltername userid running migratepy test dev database sqlite works upgrading downgrading but deploying test environment heroku postgresql used i get trace i try upgrade gist message sqlalchemyexcprogrammingerror programmingerror column id exist i tried use userscuserid upgrade method that fails environments attributeerror userid the workaround i using script metaold metadata metanew metadata usersold table users metaold column userid integer primarykeytrue column name string uniquetrue column email string uniquetrue usersnew table users metanew column id integer primarykeytrue column name string uniquetrue column email string uniquetrue def upgrademigrateengine metaoldbind migrateengine usersoldcuseridaltername id def downgrademigrateengine metanewbind migrateengine usersnewcidaltername userid it already recommended practice copypaste model sqlalchemymigrate scripts but extra duplications gets bit much anyone knows done assuming bug i like suggestions dry workaround,1 a lot functionality describing overlaps epydoc class aggregatenodebasenode r aggregate values grouping key fields ivar keys list fields according records grouped ivar recordcountfield name field record count stored recordcountfield recordcount def getoutputself r return key fields followed aggregations aggregated field last field record count import epydocdocbuilder api epydocdocbuilderbuilddocaggregatenode apivariables keys descrtoplaintextnone u list fields according records groupednn apivariables recordcountfield valuepyval recordcount,i working structured data analysis framework based streaming data nodes currently nodes implemented subclasses root node class provided framework for node classfactory i need metadata list node attributes description node output the metadata might endusers frontend application programming use stream management tools in future note i started learn python writing code currently metadata provided class variable class aggregatenodebasenode aggregate nodeinfo label aggregate node description aggregate values grouping key fields output key fields followed aggregations aggregated field last field record count attributes name keys description list fields according records grouped name recordcountfield description name field record count stored default recordcount more examples found i feel done much cleaner way there one restriction nodes custom subclasses classes minimal interference potential future attribute names what i thinking split current nodeinfo it meant private framework i realize much wider use i thinking using node attributes common attribute namespace taking much names potential custom node attributes my question what common way providing metadata python programs single variable dictionary multiple variables one metadata attribute would conflict restriction custom classstructure use kind prefix like node use multiple variables,1 if want load python code dynamically different locations extend search path attributes using pkgutil module by placing lines pydrawinitpy pydrawshapesinitpy pkgutil import extendpath path extendpathpath name you able write import statement unique package import pydrawshapes pydrawshapespath usrlibpythonpydrawshapes homesomeuserpythonpydrawshapes pydrawshapes import circle square you may think autoregistration plugins you still use basic python code setting module variable act kind singleton pattern add last line every pydrawshapesinitpy file pkgutil import extendpath path extendpathpath name shape registry shapes you register shape top related module circlepy squarepy pydrawshapes import shapes shapesappendname last check pydrawshapes import circlesquare pydrawshapes import circlesquareshapes shapes pydrawshapescircle pydrawshapessquare,i looking techniques allow users override modules application extend application new modules imagine application called pydraw it currently provides circle class inherits shape the package tree might look like usrlibpython └── pydraw ├── initpy ├── shapepy └── shapes ├── circlepy └── initpy now suppose i like enable dynamic discovery loading user modules implement new shape perhaps even shape class it seems straightforward user tree structure application tree homesomeuserpython └── pydraw ├── initpy ├── shapepy new superclass └── shapes ├── initpy └── squarepy new user class in words i like overlay mask application tree samenamed files user tree least get apparent structure python point view then configuring syspath pythonpath pydrawshapessquare might discoverable however python module path search find modules squarepy i presume method already contains parent module another path how would accomplish task python,1 difflib algorithm claim yield minimal edit sequences although statement comes docs sequencematcher i suspect applies difflib general htmldiff particular while googling around python alternative difflib minimal edit i found googlediffmatchpatch if try demo diff example strings yields although output exactly requested show found minimal edits the api docs state diffprettyhtmldiffs html takes diff array returns pretty html sequence this function mainly intended example write ones display functions suggests looking source code diffprettyhtml might good starting point build html table looking,i using difflibhtmldiff compare two files i want differences highlighted outputted html this already works maximum two different chars one line b but different characters one line output whole line marked red left side green right side table b is behaviour configurable so i set number different characters line marked deleted added edit example import difflib diffdifflibhtmldiff printdiffmakefile splitlines splitlines gives output line output i want it highlights differences yellow line odd detect one character change instead shows delete add line line whole line marked,1 you could write function behaves kind like dictget dictionaries def listgetlist index defaultnone return item index index range list else default if default given defaults none method never raises indexerror index lenlist index lenlist return default else return listindex example usage names markfrankjames listgetnames james listgetnames mark listgetnames returns none listgetnames so always return value get exceptions,list say i want see null way without using exception assertion,1 the problem keys must immutable lists tuples however simply convert v tuple xtuplev to elaborate writing x latter syntactic variation x,i list v i would like use list key i manually x x but xv work what easiest way i need added i imagine solution something like xopenv,3 dict keys must hashable lists hashable tuples a hash value object never change life object moreover two hashable objects compare equal must hash since lists mutable way satisfy conditions would make lists return hash value rather allowing subverting purpose hashes python make mutable containers unhashable xtuplev x works tuple indicated use commas parentheses in out,i list v i would like use list key i manually x x but xv work what easiest way i need added i imagine solution something like xopenv,1 python two similar data structures storing lists values list mutable version values changed x x list tuple immutable version once created value modified x x x tuple python let use mutable types dictionary keys need create tuple list xtuplev,i list v i would like use list key i manually x x but xv work what easiest way i need added i imagine solution something like xopenv,1 it huge improvement could something like keyphraselist text text even text i looking row reader phrase keyphraselist phrase rowx total total writerwriterowrow break tested,i written crude python program pull phrases index csv file write rows another file import csv total ifile open datacsv rb reader csvreaderifile ofile open newdatawritecsv wb writer csvwriterofile delimiter quotechar quotingcsvquoteall row reader text rowx total total writerwriterowrow elif text rowx total total writerwriterowrow elif even text i looking rowx total total writerwriterowrow many many lines print ntotal total ifileclose my question isn better elegantless verbose pythonic way i feel case knowing i know the csv file i searching large lines kb i think necessary use sql solve although i certainly open i python newbie love language teaching normal channels books tutorials project euler stack overflow any suggestions greatly appreciated,1 you looking generator expression matches text text even text i looking row reader anymatch row match matches total writerwriterowrow alternatively could write rows writerwriterowsrow row reader anymatch row match matches written get total,i written crude python program pull phrases index csv file write rows another file import csv total ifile open datacsv rb reader csvreaderifile ofile open newdatawritecsv wb writer csvwriterofile delimiter quotechar quotingcsvquoteall row reader text rowx total total writerwriterowrow elif text rowx total total writerwriterowrow elif even text i looking rowx total total writerwriterowrow many many lines print ntotal total ifileclose my question isn better elegantless verbose pythonic way i feel case knowing i know the csv file i searching large lines kb i think necessary use sql solve although i certainly open i python newbie love language teaching normal channels books tutorials project euler stack overflow any suggestions greatly appreciated,3 if use sympy matrixrref in sympymatrixnprandomrandomrref out e e e e e e,does python builtin function converts matrix row echelon form also known upper triangular,3 the trademark symbol unicode character u python notation uu just search replace string replaceuu,i trying prep data designer i pulling data sql server python windows machine sure os important how would i make string official trademark™ official trademark also informationreading unicode pertinent subject matter would help become little independent thanks help edited perhaps i included code i getting error run time unicodedecodeerror ascii codec decode byte x position ordinal range here code rownote tm™ datan rownote trstriposlineseplstriposlinesep treplaceuu,3 official trademark™ strip ™ official trademark,i trying prep data designer i pulling data sql server python windows machine sure os important how would i make string official trademark™ official trademark also informationreading unicode pertinent subject matter would help become little independent thanks help edited perhaps i included code i getting error run time unicodedecodeerror ascii codec decode byte x position ordinal range here code rownote tm™ datan rownote trstriposlineseplstriposlinesep treplaceuu,1 urls like items items match regexp means exactly digits you probably specify two another url entries cases urlr items achievementlistviewasview yearstrdatetodayyear weekstrdatetodayisocalendar urlr itemspyeardweekpweekd itemweekarchiveviewasview using isocalendar get week number,i astonished little documentation classbased generic views anything slightly complex trivial sample get done guesswork trial error i want use weekarchiveview display week item list there urlspy entry urlr itemspyeardweekpweekd itemweekarchiveviewasview when year week specified i get error page i want equal today year week default what right place tweak should i introduce another mixing override method,2 adding alias activate script activating virtualenv type want use cd env echo alias python arch python binactivate source binactivate python myscriptpy,short question using virtualenv virtualenvwrapper possible add prefix python call linked specific virtual environment background i would like multiple virtual environment using brew installed python running bit mode others bit mode below i typical setup os x development the specific prefix i would like add python call arch force python run bit mode again important part would added calling workon env shown example i know i setup alias bashprofile would modified everytime i create remove virtual environments edit to elaborate issues i using simple alias could bit virtual environment this said call workon would ideally add prefix python call workflow terminal would meaning calling workon envx i would able use python arch would transparent using terminal python installation brew install python framework universal creating virtual environmentsafter installing pip virtualenv virtualenvwrapper mkvirtualenv env nositepackages mkvirtualenv env nositepackages mkvirtualenv env nositepackages mkvirtualenv env nositepackages bit usage workon env python myscriptpy workon env python myotherprojectscriptpy bit usagecurrent nonideal workon env arch python myscriptpy workon env arch python myotherprojectscriptpy bit usage ideal workon env python mybitprojectpy note arch would transparent solution running sean comments i added alias inside activate deactivate environments i wanted run bit see detail env activate script this file must used source binactivate bash cannot run directly deactivate alias python python added line reset old environment variables n oldvirtualpath patholdvirtualpath export path unset oldvirtualpath fi removed content keep post shorter unset irrelavent variables deactivate nondestructive virtualenvusersadamenvsenv export virtualenv this detect bash zsh hash command must called get forget past commands without forgetting past commands path changes made may respected n bash n zshversion hash r fi removed content keep post shorter alias python arch python added line run bit,3 your problem right podcheck freadlines the first call checklist uses data f subsequent calls checklist skip loop nothing left read so opening f read data without changing much code i would add open file flines freadlines and change loop checklist podcheck flines,the code suppose take string multiple arguments split split it passes first argument checklist so i type pass checklist everything else works import def checkliststart doit intstart end end strend podcheck freadlines rematch pod end podcheckstrip doit rematch pod start podcheckstrip doit doit print podcheck return def splitp pods psplit pod pods checklistpod return f opencusersuserdesktopiplisttxt pod rawinput what pod number would like check splitpodstrip print done,3 on ubuntu simply sudo aptget install pythonoauth package installed automatically for appengine might take look google api python client appengine examples they oauth client specifically designed work appengine,i want use tumblr api v includes oauth i need find oauth module i supposed use like import oauth oauth i found oauth source code httpsgithubcomsimplegeopythonoauth if i want use linux ubuntu whats process i installed git i notice setuppy i run the readme httpsgithubcomsimplegeopythonoauthblobmasterreadmemd doesnt mention install maybe newbie if i want use google app engine i thanks help i pretty new git stuff,1 see httpmailscipyorgpipermailnumpydiscussionnovemberhtml basically the rref algorithm produces much inaccuracy implemented computer so either want solve problem another way use symbolics like aix suggested,does python builtin function converts matrix row echelon form also known upper triangular,1 using issafe together marksafe redundant probably see differences as noted section linked talks marksafe there need worry issafe attribute case although including hurt anything whenever manually handle autoescaping issues return safe string issafe attribute change anything either way issafe simply way automatically mark return value function safe given external inputs already safe django still autoescape anything input try escape parts added afterwards function marksafe hand certifies output safe regardless whether inputs safe much stronger requirement fulfill going use,i reading django documentation custom filter i see reason existence issafe httpsdocsdjangoprojectcomenhowtocustomtemplatetagsfiltersandautoescaping i coded examples tried result always whether issafe true false why use issafe here code extratagspy djangotemplatedefaultfilters import stringfilter django import template import datetime register templatelibrary registerfiltername customlower stringfilter def lowervalue issafe true return sxx value lowerissafe true djangoutilshtml import conditionalescape djangoutilssafestring import marksafe registerfiltername customlf def initialletterfiltertext autoescapenone first text text autoescape esc conditionalescape else esc lambda x x result strongsstrongs escfirst escother return marksaferesult initialletterfilterissafe false initialletterfilterneedsautoescape true point whether i code issafetrue issafefalse result autoescaped characters i see use issafe,3 you could use pltxlim pltylim set region plotted import matplotlibpyplot plt import numpy np datanparangereshape pltimshowdata pltxlim pltylim pltshow,i several images represented d arrays i viewing imshow i need zoom exact spot every image i know i manually zoom tedious precise enough is way programmatically specify specific section image show instead entire thing,3 try cookie cycle domain lowercase domain,i want get domain cookie http response code cookie cookiesimplecookie cookieloadcookiestring print cookie cookie shows cookie cookie setcookie cyclemamama domainabcxyznet expirestue oct gmt path i want extract domain result i trying print cookie domain print cookie domain value print cookie cycle domain value none work thanks,1 yes in scipylinalg lu lu decomposition essentially get rowechelon form there factorizations qr rq svd interested documentation,does python builtin function converts matrix row echelon form also known upper triangular,3 once get coords point show objectlinked info textctrl toolbar for instantiate toolbar navigationtoolbarwx canvas add textcontrol this nice popup job here example customizing toolbar showing x coordinate txtctrl usrbinenv python coding utf jvisorspectrumpanel visor julio import wx matplotlibfigure import figure matplotlibbackendsbackendwxagg import figurecanvaswxagg figurecanvas matplotlibbackendsbackendwx import navigationtoolbarwx class spectrumpanelwxpanel def initself parent xlabel mz ylabel intensity wxpanelinitself parent selfparent parent selfxlabel xlabel selfylabel ylabel selfsetbackgroundcolourwhite selffigure figure selfcanvas figurecanvasself selffigure selfaddtoolbar sizer wxboxsizerwxvertical sizeraddselfcanvas wxleft wxtop wxgrow wxexpand sizeraddselftoolbar wxleft selfcanvasmplconnect motionnotifyevent selfonmotion selfsetsizersizer selffit selfclean def addtoolbarself selftoolbar navigationtoolbarwxselfcanvas masstxt wxstatictextselftoolbar label mz pos size masstxtsetbackgroundcolourlight gray selfmass wxtextctrlselftoolbar pos size stylewxtereadonly selftoolbarsettoolbitmapsizewxsize selftoolbarsetminsize selftoolbarrealize selftoolbarupdate def cleanself selffigureclear selfaxes selffigureaddsubplot def dibujaself dibuja el canvas selfaxessetxlabelselfxlabel selfaxessetylabelselfylabel selfcanvasdraw def onmotionself evt evtinaxes xpos evtxdata selfmasssetvalue f xpos name main class testframewxframe def initself args kargs wxframeinitself args kargs selfpanel spectrumpanelself selffit app wxpysimpleapp fr testframenone frshow appmainloop and see new control toolbar,i scatter plot several thousand points this post tells label matplotlib how put individual tags scatter plot but look like disaster many points what i would like instead tool tip type label pops mouseover point is possible using matplotlib,3 those oauth token token secret come registration process this code assumes user already registered authorized application tumblr you find code walks registrationauthorization process google code,i want use tumblr api httpwwwtumblrcomdocsenapiv i already registered application httpwwwtumblrcomoauthapps but i get oauth consumer key secret key where oauthtoken oauthtokensecret one program httpsgistgithubcom needs parameters class tumblrapiv def initself consumerkey consumersecret oauthtoken oauthtokensecret selfconsumer oauthconsumerconsumerkey consumersecret selftoken oauthtokenoauthtoken oauthtokensecret selfurl httpapitumblrcom,1 try rmstaticsconstspropertyidssssd a couple notes matches beginning line negative lookahead asserting not followed space character s nonspace character,i trying write regex python parse file contents like static const propertyid propertyx static const propertyid propertyy static const propertyid propertyz i want extract property name number non commented properties this expression i wrote tuples refindallrstatic tconst tpropertyid tw tdfilecontents filecontents data file string but regex even matching commentedlines lines how make avoid matching commented lines,1 you could specify start line want spaces first static tuples refindallrsstatic tconst tpropertyid tw tdfilecontents,i trying write regex python parse file contents like static const propertyid propertyx static const propertyid propertyy static const propertyid propertyz i want extract property name number non commented properties this expression i wrote tuples refindallrstatic tconst tpropertyid tw tdfilecontents filecontents data file string but regex even matching commentedlines lines how make avoid matching commented lines,1 there kinds weird stuff going code def generatemodelcfdistwordnum you use word key look dictionary word then change are intentionally chaining result one random lookup key next lookup randomchoice if intentionally chaining right want bunch words dict want randomsample imclass this completely unnecessary just call like randomchoice look examples random docs cfdistword you getting value cfdist key equal value word passed case living first time key equal result choice is intended keys this work value cfdist dict now say want saving words list but since i sure exactly want i give two examples the first i aggregate words change anything else def generatemodelcfdistwordnum words add starting word wordsappendword want rangenum wordrandomchoicecfdistwordkeys wordsappendword return words the second i assume want random words dict repetitions def generatemodelcfdistwordnum return randomsamplecfdistwordkeys num then either way call words generatemodelcfd living get list words,how modify program generation saving words list choosing randomchoice previously import random mistake working correct def generatemodelcfdistwordnum rangenum wordrandomchoiceimclasscfdist wordkeys generatemodelcfd living,1 after time researching i concluded worthwhile way building php library python code the pip project closest thing i could find abandoned my solution declare every new function i add i write python i translate code php python necessary it working great far,i rather large api written php i worked years some functionality needs upgraded extent i really rewrite classes since i need scrap old code anyway i thinking perhaps i could replace old functionality python code i came across pip searching answers seems like exellent solution since i actually create python class instances php call methods etc seems abandoned alpha stages reasons unknown i suppose simplest solution would cli one meaning i could run python instance php collect results i particularly like solution though considering amount python code i write handle input php respond accordingly plus reusable i know normal problem google certainly seem think would best way complementing php code library python code,1 i almost missed answer i reread question finally caught bit last line i type localhostalphaadmin go admin that means url settings wrong currently mediaurl media staticurl static adminmediaprefix staticurl admin whereas mediaurl alphamedia staticurl alphastatic adminmediaprefix staticurl admin additionally need static staticfilesdirs so remove setting,so i installed bitnami django stack enabled admin module followed tutorial creating admin menu polls however i go admin everything white plaintext all css images error all i enable settingspy installedapps djangocontribadmin in urlspy uncommented djangocontrib import admin adminautodiscover urlr admin includeadminsiteurls uncommented in settingspy i tried using default settings also tried mediaroot mediaurl media staticroot staticurl static adminmediaprefix staticurl admin import os siteroot ospathdirnameospathrealpathfile staticfilesdirs ospathjoinsiteroot static nothing seems work refuses find static files adminmediacss etc i made sure windows path bin django i even tried including contrib nothing helps i installed django cdjangostackappsdjango i installed project cusersdexterbitnami djangostack projectsalpha i type localhostalphaadmin go admin,2 note binary form xap exactly b b python binary numbers displayed like first useful method float instances floathex inverse function float class method floatfromhex fh hex print fh print floatfromhexfh result xaeaeaep hexadecimal representation float note floathex instance method floatfromhex class method httpdocspythonorglibrarystdtypeshtmlfloatfromhex secondly i find python function transform hexadecimal representation float binary representation float say dot one transform directly decimal representation float binary one so i created function purpose before hand function transforms hexadecimal representation decimal representation string input float then two problems transform part dot this part integer easy use bin transform part dot the problem transformation asked several times so i understand solutions i wrote then function wish qiang li def hexfbinfx transforms hexadecimal float dot binary float dot ap strfloatfromhexxpartition following part transforms part dot binary dot tinies decimal decimali xrange bits pdec decimal p tin tinies pdectin bitsappend break elif pdectin bitsappend pdec tin else bitsappend pbin joinbits binary dot integer dot easily transformed binary return joinbinintapbin in order perform verification i wrote function transform part binary float dot decimal representation decimal import decimal getcontext getcontextprec precision large tinies decimal decimali xrange com dictitin itin enumeratetinies def afterdotbinaryfloatsbin com com transforms binary lying dot float dot sbinstartswith b sbinstartswith sbin sbinsplit allc c sbin return sumintccomi ic enumeratesbin else return none finally applying functions decimal import decimal getcontextprec precision large tinies decimal decimali xrange com dictitin itin enumeratetinies def afterdotbinaryfloatsbin com com transforms binary lying dot float dot sbinstartswith b sbinstartswith sbin sbinsplit allc c sbin return sumintccomi ic enumeratesbin else return none def hexfbinfx transforms hexadecimal float dot binary float dot ap strfloatfromhexxpartition following part transforms float dot binary dot tinies decimal decimali xrange bits pdec decimal p tin tinies pdectin bitsappend break elif pdectin bitsappend pdec tin else bitsappend pbin joinbits binary dot float dot easily transformed binary return joinbinintapbin n print n n transformed method hex nhexed nhex print nhexed nhex nhexed print nhexfbinfnhexed hexfbinfnhexed print nverificationnbeforeafter hexfbinfnhexedpartition beforeafter hexfbinfnhexedpartition print print intbefore intbefore print afterdotbinaryfloatafter afterdotbinaryfloatafter print nn result n transformed method hex nhexed nhex xdp hexfbinfnhexed b verification beforeafter hexfbinfnhexedpartition b intbefore afterdotbinaryfloatafter n transformed method hex nhexed nhex xdp hexfbinfnhexed b verification beforeafter hexfbinfnhexedpartition b intbefore afterdotbinaryfloatafter n transformed method hex nhexed nhex xffp hexfbinfnhexed b verification beforeafter hexfbinfnhexedpartition b intbefore afterdotbinaryfloatafter for two numbers decimal import decimal tinies decimal decimali xrange com dictitin itin enumeratetinies def hexfbinfx tinies tinies transforms hexadecimal float dot binary float dot ap strfloatfromhexxpartition following part transforms float dot binary dot bits pdec decimal p tin tinies pdectin bitsappend break elif pdectin bitsappend pdec tin else bitsappend pbin joinbits binary dot float dot easily transformed binary return joinbinintapbin print hexfbinf xap print print hexfbinf xbcp result displays b b,i wondering convert result returned floathex binary example xap can anyone please help thanks,2 that definitely interesting sure enough monthmixin includes getnextmonth getprevmonth methods daymixin includes getnextday getprevday methods however yearmixin weekmixin functional equivalent definitions seems like bit oversight django team part i think best bet subclass either weekarchiveview baseweekarchiveview may eventually want change response format want reimplement methods add getnextweek getprevweek methods then view inherit subclass instead a simple modification daymixin methods sufficient def getnextweekself date get next valid week next date datetimetimedeltadays return getnextprevmonthself next ispreviousfalse usefirstdayfalse def getpreviousweekself date get previous valid week prev date datetimetimedeltadays return getnextprevmonthself prev isprevioustrue usefirstdayfalse,in continuation struggle weekarchiveview i paginate week all i want know next previous week available case provide link template i like also skip empty weeks the source shows getnextday getprevday getnextmonth getprevmonth available nothing weeks,2 def floattobinarynum exponent shiftednumnum shiftednum intshiftednum shiftednum exponent exponent return b formatintshiftednum binary b formatintshiftednumexponent integerpartbinaryexponent fractionalpartbinaryexponentrstrip return formatintegerpartfractionalpart def floathextobinaryfloathex num floatfromhexfloathex return floattobinarynum printfloathextobinary xap printfloathextobinary xbcp explanation floatfromhex returns float num we like binary representation bformat returns binary representations integers floats but multiply float enough powers shift binary representation left enough places end integer shiftednum once integer home free use bformat we reinsert decimal point err binary point using bit string slicing based number places shifted left exponent technical point the number digits binary representation shiftednum may smaller exponent in case need pad binary representation left binary slicing binaryexponent empty we manage b format the format string sets width formated string padded left zeros the gets replaced number exponent,i wondering convert result returned floathex binary example xap can anyone please help thanks,3 decorators applied function definition time for functions module loaded functions defined functions decorator applied time enclosing function called so want monkeypatch decorator need import module contains define mock decorator function set eg moduledecorator mymockdecorator import modules use decorator use module if module contains decorator also contains functions use already decorated time see probably sol edit reflect changes python since i originally wrote if decorator uses functoolswraps version python new enough may able dig original function using wrapped attritube redecorate means guaranteed decorator want replace also may decorator applied,i function decorator i trying test help python mock library i like use mockpatch replace real decorator mock bypass decorator calls function what i figure apply patch real decorator wraps function i tried different variations patch target reordering patch import statements without success any ideas,3 think methods class like class attribute reference self def initself b selfgcdab selfgcdab it matter whether instance method class method static method while certainly use staticmethod want keep code associated class usual python use modulelevel function case call gcd def gcdab b ab ba true b return b ba class fractionobject def initself b gcdab gcdab,below i created class i trying use method gcdab initialization fraction object however i trying would work without fraction part fractiongcdab i used staticmethod absolutely nothing ie code works without is anyway i call gcd without putting fraction front in java i would normally create static method call i could easily put gcd code inside init i trying learn i missing lot can anyone explain static methods helper methods class pretty much i use various methods inside class class fractionobject def initself b fractiongcdab fractiongcdab selfnum ad selfdenom bd else selfnum selfdenom b staticmethod def gcdab b ab ba true b return b ba def reprself return strselfnum strselfdenom,2 don forget python everything needs class there nothing gcd makes bettersuited class method standalone function take class now call gcda b,below i created class i trying use method gcdab initialization fraction object however i trying would work without fraction part fractiongcdab i used staticmethod absolutely nothing ie code works without is anyway i call gcd without putting fraction front in java i would normally create static method call i could easily put gcd code inside init i trying learn i missing lot can anyone explain static methods helper methods class pretty much i use various methods inside class class fractionobject def initself b fractiongcdab fractiongcdab selfnum ad selfdenom bd else selfnum selfdenom b staticmethod def gcdab b ab ba true b return b ba def reprself return strselfnum strselfdenom,2 given hexadecimal string h find corresponding float x floatfromhexh so really interesting able produce fixed point binary representation float its possible finite representation probably want restrict length eg binary representation mathpi end so something like following might work def binaryrepresentationx n base remainder handle negatives well base intx fraction absintround x base n format remove redundant zeros return bbformatbase fractionrstrip,i wondering convert result returned floathex binary example xap can anyone please help thanks,1 i think referring java import static feature just clarify java enforces object orientation cannot modules like languages so using import static math example make static methods math available called without class name in python add function outside class call,below i created class i trying use method gcdab initialization fraction object however i trying would work without fraction part fractiongcdab i used staticmethod absolutely nothing ie code works without is anyway i call gcd without putting fraction front in java i would normally create static method call i could easily put gcd code inside init i trying learn i missing lot can anyone explain static methods helper methods class pretty much i use various methods inside class class fractionobject def initself b fractiongcdab fractiongcdab selfnum ad selfdenom bd else selfnum selfdenom b staticmethod def gcdab b ab ba true b return b ba def reprself return strselfnum strselfdenom,1 taking chrisdpratt code basis i created class provides template nextweek previousweek class betterweekarchiveviewweekarchiveview def getnextweekself date get next valid week next date timedeltadays return getnextprevmonthself next ispreviousfalse usefirstdayfalse def getpreviousweekself date get previous valid week prev date timedeltadays return getnextprevmonthself prev isprevioustrue usefirstdayfalse def getdateditemsself return datelist items extracontext request inject nextweek previousweek extracontext result superbetterweekarchiveview selfgetdateditems extracontext result date extracontext week extracontextupdate nextweek selfgetnextweekdate previousweek selfgetpreviousweekdate return result this works perfect,in continuation struggle weekarchiveview i paginate week all i want know next previous week available case provide link template i like also skip empty weeks the source shows getnextday getprevday getnextmonth getprevmonth available nothing weeks,1 okay bit short thing json translate array string eg array first hello array second become u first u hello u second jsonencode run sting throu jsondecode get array back simply run json file thou decoder able reach data array metadata album array metadata artist never used python look httpwwwphpnetmanualenfunctionjsondecodephp might clear upp thing two,this bugging quite hours i searching lot i found lot information the problem i good i actually beginner max i like achieve python possible maybe javascript php also let explain i found website httplisteningroomnet great you createjoin rooms upload tracks listen together friends i like extractscrapeget specific data json file this file contains artist album title track title i like extract artist album track title httplisteningroomnetroomchillasfuckspinsjson the json file contains tracks played past hours i managed scrape whole json file python looking around local json file following probably valid code jsondataopen spinsjson data jsonloadjsondata pprintdata jsondataclose this prints following u endtime u u id u cfeeafad u length u metadata u album u mezzanine u artist u massive attack u bitrate u label u virgin u length u title u group four just part print i like scrape url one provided top just get album artist title make sure prints simple possible like artist track title album artist track title album if much save txt file i hope i could get help i really want create i check music marvin,1 in first case nparrayc dtypenpobject numpy knows nothing shape intended array for example define range nparrayd then expect numpy determine shape based length so similarly case numpy attempt see lenc defined access elements c via ci you see effect defining class class xobject def lenself return def getitemself return x then print numpyarrayx dtypeobject produces x xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx xxxxxxxxx in contrast second case npempty dtypenpobject c then shape already determined thus numpy directly assign object however extent true since vector if defined different shape method accesses still occur the following example still call getitem class numpyempty dtypeobject x print returns x xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx xxxxxxxxx,i recently run issues creating numpy object arrays using eg nparrayc dtypenpobject c instance complicated class cases numpy tries access methods class however npempty dtypenpobject c solves issue i curious difference two internally why first case might numpy try access attributes methods c edit for record example code demonstrates issue import numpy np class thingobject def getitemself item print getitem def lenself return nparraything dtype object this prints getitem twice basically len present class one run unexpected behavior,3 this usually due shifting tabs spaces tabs i set invisible character color preferences colors visible page i see i using tabs spaces the python standard use spaces tab i set default well preferences editor uncheck use tabs set tab width finally clean file switches tabs spaces using tabs instead spaces selecting text going text menu selecting detab,any one else getting lots indentation syntax errors writing python panics coda ide ive getting lot shuffling code around seems gets rid error bug,3 python loaded json elem data print artistntitlenalbumn formatelem metadata to save file open thefilenametxt w f elem data fwrite artistntitlenalbumnn formatelem metadata,this bugging quite hours i searching lot i found lot information the problem i good i actually beginner max i like achieve python possible maybe javascript php also let explain i found website httplisteningroomnet great you createjoin rooms upload tracks listen together friends i like extractscrapeget specific data json file this file contains artist album title track title i like extract artist album track title httplisteningroomnetroomchillasfuckspinsjson the json file contains tracks played past hours i managed scrape whole json file python looking around local json file following probably valid code jsondataopen spinsjson data jsonloadjsondata pprintdata jsondataclose this prints following u endtime u u id u cfeeafad u length u metadata u album u mezzanine u artist u massive attack u bitrate u label u virgin u length u title u group four just part print i like scrape url one provided top just get album artist title make sure prints simple possible like artist track title album artist track title album if much save txt file i hope i could get help i really want create i check music marvin,2 for php need jsondecode php json filegetcontentsurl val jsondecodejson room valmetadata echo album roomalbumn echo artist roomartistn echo title roomtitlen outputs album future sandwich artist them roaringtwenties title fast acting nitenite spray with realistic uncle beard note truck load json data iterate adequately,this bugging quite hours i searching lot i found lot information the problem i good i actually beginner max i like achieve python possible maybe javascript php also let explain i found website httplisteningroomnet great you createjoin rooms upload tracks listen together friends i like extractscrapeget specific data json file this file contains artist album title track title i like extract artist album track title httplisteningroomnetroomchillasfuckspinsjson the json file contains tracks played past hours i managed scrape whole json file python looking around local json file following probably valid code jsondataopen spinsjson data jsonloadjsondata pprintdata jsondataclose this prints following u endtime u u id u cfeeafad u length u metadata u album u mezzanine u artist u massive attack u bitrate u label u virgin u length u title u group four just part print i like scrape url one provided top just get album artist title make sure prints simple possible like artist track title album artist track title album if much save txt file i hope i could get help i really want create i check music marvin,1 the pycurl documentation terrible i think want set writefunction function nothing eg psetoptpycurlwritefunction lambda x none also i wish state record i thought set everything apis went vms gaaah,i beginner using python pycurl webpage stressing testing purposes however pycurl keeps printing returned html terminal makes stress testing take even time one pycurl code i using posted is way run pycurl without print write result anywhere any assistance would appreiciated p pycurlcurl psetoptpycurlpost psetoptpycurlcookie sessioncookie psetoptpycurlurl httpexamplecomlogoffphp pperform pclose,3 could try devnull open devnull w psetoptpycurlwritefunction devnullwrite function nothing,i beginner using python pycurl webpage stressing testing purposes however pycurl keeps printing returned html terminal makes stress testing take even time one pycurl code i using posted is way run pycurl without print write result anywhere any assistance would appreiciated p pycurlcurl psetoptpycurlpost psetoptpycurlcookie sessioncookie psetoptpycurlurl httpexamplecomlogoffphp pperform pclose,1 does help xmletreeelementtree import xml txt xml titleinfotitle fooaldfjfoo datatext i want countdata xml give us contents data tag data xmltxtfinddatatext could whatever want print data,i new python i particularly difficult time working xml python the situation i i trying count number times word appears xml document simple enough xml document response server is possible without writing file it would great trying memory here sample xml code xml titleinfotitle fooaldfjfoo datatext i want countdata xml here i python import urllib import stringio import xmldomminidom xmletreeelementtree import parse usock urlliburlopen httpwwwexamplecomfilexml xmldoc minidomparseusock print xmldoctoxml past this point i tried using stringio elementtree minidom success i gotten point i sure else any help would greatly appreciated,1 there two basic problems running xxx methods looked class typeerror set attributes builtinextension type module means solution would also keep track module examined otherwise every module would instancesubstitution behavior means even possible least directly fortunately sysmodules picky goes wrapper work module access ie import somemodule somemodulesalutation world samemodule access pretty much yank methods substitution class add globals eiher custom method class i like using export generic function already listed answers one thing keep mind wrapper creating new instance time globals solution end subtly different behavior oh get use time one update from guido van rossum there actually hack occasionally used recommended module define class desired functionality end replace sysmodules instance class class insist generally less useful eg module foopy import sys class foo def functself args code def functself args code sysmodulesname foo this works import machinery actively enabling hack final step pulls actual module sysmodules loading this accident the hack proposed long ago decided liked enough support import machinery so established way accomplish want create single class module last act module replace sysmodulesname instance class play getattr setattr getattribute needed,how implement equivalent getattr class module example when calling function exist module statically defined attributes i wish create instance class module invoke method name failed attribute lookup module class aobject def salutationself accusative print hello accusative note function intentionally module class def getattrmod name return getattra name name main hope getattr function invoked since salutation exist current namespace salutationworld which gives mattstanleydesktop python getattrmodpy traceback recent call last file getattrmodpy line module salutationworld nameerror name salutation defined,3 if trying count number times word appears xml document read document string count import urllib data urlliburlopen httpwwwexamplecomfilexml read print datacount foobar otherwise iterate tags looking xmletree import celementtree et xml etfromstringurlliburlopen httpwwwexamplecomfilexml read data xmlgetiterator data something datatext,i new python i particularly difficult time working xml python the situation i i trying count number times word appears xml document simple enough xml document response server is possible without writing file it would great trying memory here sample xml code xml titleinfotitle fooaldfjfoo datatext i want countdata xml here i python import urllib import stringio import xmldomminidom xmletreeelementtree import parse usock urlliburlopen httpwwwexamplecomfilexml xmldoc minidomparseusock print xmldoctoxml past this point i tried using stringio elementtree minidom success i gotten point i sure else any help would greatly appreciated,2 it quite simple far i tell import urllib xmldom import minidom usock urlliburlopen httpwwwexamplecomfilexml xmldoc minidomparseusock element xmldocgetelementsbytagname data print elementfirstchildnodevalue so count occurrences string try bit condensed i like oneliners count sumelementfirstchildnodevaluefind substring element xmldocgetelementsbytagname data,i new python i particularly difficult time working xml python the situation i i trying count number times word appears xml document simple enough xml document response server is possible without writing file it would great trying memory here sample xml code xml titleinfotitle fooaldfjfoo datatext i want countdata xml here i python import urllib import stringio import xmldomminidom xmletreeelementtree import parse usock urlliburlopen httpwwwexamplecomfilexml xmldoc minidomparseusock print xmldoctoxml past this point i tried using stringio elementtree minidom success i gotten point i sure else any help would greatly appreciated,2 in python emulate browser mechanize library also good documentation mechanize cookies,i want write program opens browser open url given cookie i dont know maybe i could modify cookies default place,1 import urllib opener urllibbuildopener openeraddheadersappend cookie cookienamecookievalue f openeropenhttpexamplecom modules look urllib cookielib cookie,i want write program opens browser open url given cookie i dont know maybe i could modify cookies default place,1 based matth answer could use decorator like def singleinstancetasktimeout def taskexcfunc functoolswrapsfunc def wrapperargs kwargs lockid celerysingleinstance funcname acquirelock lambda cacheaddlockid true timeout releaselock lambda cachedeletelockid acquirelock try funcargs kwargs finally releaselock return wrapper return taskexc use like periodictaskruneverytimedeltaminutes singleinstancetask def fetcharticles yada yada,i use celery update rss feeds news aggregation site i use one task feed things seem work nicely there detail i sure handle well though feeds updated every minute periodictask feed still updating last periodic task new one started example feed really slow offline task held retry loop currently i store tasks results check status like import socket datetime import timedelta celerydecorators import task periodictask aggregatormodels import feed results periodictaskruneverytimedeltaminutes def fetcharticles feed feedobjectsall feedpk results resultsfeedpkready the task finished yet continue resultsfeedpk updatefeeddelayfeed task def updatefeedfeed try feedfetcharticles except socketerror exc updatefeedretryargsfeed excexc maybe sophisticatedrobust way achieving result using celery mechanism i missed,3 have added root folder system path import sys syspathappendplace proj dir could import follows srcmodelsomefile import something if know absolute path proj always use combinations ospathdirnameosgetcwdu,so i working python project svn repo when i first pulled structure bit odd due fact similar proj src tags trunk and everything inside src python module files except src turns logical folder overall package inside there initpy project anywhere so i want restructure least i use relative imports project i also want set looks like proj src model controller view test tags trunk however i tried setting matter i seem cannot resolve relative import moment i traverse packages i placed initpy file level package including one inside src folder defined however i try make unit test test package import saying modelfoo import foo attempt import foo class module foopy located inside model package resolve just case problem specifically unit tests i also tried module controller package dependent class model package vice versa none worked how i resolve,1 here blog post i ago using httpwebrequest post site cookies involved httpcrazorsharpblogspotcomchtmlscreenscrapingparthtml the idea get response using httpwebrequest get access cookies sent for every subsequent request new cookiecontainer request object add cookies got container,i wondering log specific site however luck far the way happens browser click button triggers jquery ajax request ajaxauthorizeajaxhtml post variables login pass when returns result true reloads document logged when i go ajaxauthorizeajaxhtml browser gives data resultfalse response using c i went address posted login pass gave data resulttrue response however course i go back main folder website i logged can anyone help solve problem i think cookies set via javascript even possible case i research i could please help get around problem used urllib python web libraries net edit it setting cookie response headers sid path amp domain example sidbfbffdfdbfdad path domainsite i know save cookie go back using cookie i never done anything like someone give example using python edit all done thanks post how use python login webpage retrieve cookies later usage,1 addon ubuntu ubuntunbsp lts lucid lynx the repository moved pip install e githttpgithubcomscipyscipyeggscipy failed with following steps finally worked root virtual environment python link python install ubuntu dependencies see elaichi clone numpy scipy git clone gitgithubcomscipyscipygit scipy git clone gitgithubcomnumpynumpygit numpy build numpy within numpy folder python setuppy build fcompilergnu install scipy within scipy folder python setuppy install,it possible install numpy pip using pip install numpy is similar possibility scipy doing pip install scipy work update the package scipy available installed pip,2 merely partial answer learn size resource forks simply use namedfork psuedodirectory ospathgetsizepath file interestnamedforkrsrc its theoretically possible named forks may exist discover list available forks as extended attributes size interested you use xattr module discover content thus length keyvalue pairs but interested disk size worth noting extended attributes stored sort file they form part file metadata ie like name modified time metadata stored directly within btree node rather file,i written small utility creating xml folder structure comparison folders via generated xml supports win mac platforms however mac recursively calculating folder size adds total size on investigation came due extended attributes resource forks present certain files can anybody know i determine extended attributes resource forks size preferably python currently i using ospathgetsize determine size file adding files size determine folder size eventually,1 as obvious heads error also triggered including protocol host parameter for example code conn httplibhttpconnectionhttpsecureauthorizenet also cause gaierror errno name service known error even networking setup correct,i trying use httplib send credit card information authorizenet when try post request i get following traceback file libcgiapppy line run res method file varwwwhtmlindexpy line processregistration connrequestpost gatewaytransactdll mystring headers file usrlocallibpythonhttplibpy line request selfsendrequestmethod url body headers file usrlocallibpythonhttplibpy line sendrequest selfendheadersbody file usrlocallibpythonhttplibpy line endheaders selfsendoutputmessagebody file usrlocallibpythonhttplibpy line sendoutput selfsendmsg file usrlocallibpythonhttplibpy line send selfconnect file usrlocallibpythonhttplibpy line connect selftimeout selfsourceaddress file usrlocallibpythonsocketpy line createconnection raise error msg gaierror errno name service known i build request like mystring urlliburlencodecardhash headers contenttype textxml contentlength strlenmystring conn httplibhttpsconnectionsecureauthorizenet sourceaddressmyurlcom connrequestpost gatewaytransactdll mystring headers add another layer working development server httplib without sourceaddress parameter httplibhttpsconnection any help greatly appreciated edit i run command line apparently sort permissions issue any ideas permissions i would need grant users make happen possibly apache open port,3 you get keyerror try look something dict dict contain key in case appears key hwieasalbaaxx occur h,part python script i first made dictionary h def histograml x l x dx else dx return hhistogramlist vhfile vhfiles linelistcommandsgetoutput cat vhfilesplitlinestrue list line linelist name linesplit inthname listappendline then i got error line file homexugscratchmrfastnadisrmpy line module inthname keyerror hwieasalbaaxx any idea happened thx,2 i think right track let try import scipy import scipyclusterhierarchy sch x scipyrandn dimensional observations schdistancepdistx vector choose pairwise distances l schlinkaged method complete ind schfclusterl dmax distance ind give cluster indices input observations ind depends method used linkage try methodsingle complete average then note ind differs example in l schlinkaged method complete in schfclusterl dmax distance out array in l schlinkaged method single in schfclusterl dmax distance out array scipyclusterhierarchy sure confusing in link i even recognize code,using code posted i created nice hierarchical clustering let say dendrogram left created something like y schlinkaged method average d distance matrix cutoff maxy z schdendrogramy orientation right colorthresholdcutoff now i get indices members colored clusters to simplify situation ignore clustering top focus dendrogram left matrix this information stored dendrogram z stored variable there function i want called fcluster see documentation however i cannot see i give fcluster cutoff i specified creation dendrogram it seems threshold variable fcluster terms various obscure measurements inconsistent distance maxclust monocrit any ideas,3 you already really close data jsonloadjsondata taking json string converting python object case list dictionaries plus metadata dictionary dictionaries to get format want need loop items song data artist song metadata artist this tells look dictionary it looking dictionary item called metadata then looking inside dictionary artist album song metadata album songtitle song metadata title print snsnsn artist album songtitle or print file open thefilenametxt w f song data artist song metadata artist album song metadata album songtitle song metadata title fwrite snsnsn artist album songtitle,this bugging quite hours i searching lot i found lot information the problem i good i actually beginner max i like achieve python possible maybe javascript php also let explain i found website httplisteningroomnet great you createjoin rooms upload tracks listen together friends i like extractscrapeget specific data json file this file contains artist album title track title i like extract artist album track title httplisteningroomnetroomchillasfuckspinsjson the json file contains tracks played past hours i managed scrape whole json file python looking around local json file following probably valid code jsondataopen spinsjson data jsonloadjsondata pprintdata jsondataclose this prints following u endtime u u id u cfeeafad u length u metadata u album u mezzanine u artist u massive attack u bitrate u label u virgin u length u title u group four just part print i like scrape url one provided top just get album artist title make sure prints simple possible like artist track title album artist track title album if much save txt file i hope i could get help i really want create i check music marvin,1 that hackery removed python the new documentation exec function notes fully explain situtation python seeing exec statement change every access vars functions loadname instead loadfast loadglobal check answer,the code x def f execx printx f runs python python prints different results is change documented anywhere a pointer mailing list discussion would also fine i ask purely curiosity,3 a key error means referenced key dict exist there error retrieving value key specified key exist one way deal using tryexcept block if code try raises keyerror know name h whatever appropriate line linelist name linesplit try inthname listappendline except keyerror code deal condition this methodology favoring exception handling rampant use checking known python community eafp easier ask forgiveness permission you also using less pythonic means check name list trying reference name h inthname get idea this methodology called look before you leap lbyl eafp generally preferable large as aside even need histogram function in python counter object list this sentence get split multiple list elements the list elements get counted using defaultdict need histogram function allsplit list this sentence get split multiple list elements the list elements get counted using defaultdict need histogram function collections import counter c counterlist c counter get list defaultdict elements need sentence split function elements multiple this histogram using the counted pre use defaultdict get result collections import defaultdict dd defaultdictint word list ddword dd defaultdicttype int defaultdict elements need sentence split get function elements multiple this histogram using the list counted,part python script i first made dictionary h def histograml x l x dx else dx return hhistogramlist vhfile vhfiles linelistcommandsgetoutput cat vhfilesplitlinestrue list line linelist name linesplit inthname listappendline then i got error line file homexugscratchmrfastnadisrmpy line module inthname keyerror hwieasalbaaxx any idea happened thx,1 the postgresql interval type really looking specifically intended storing arbitrary length time ranging anywhere microsecond million years an interval starting ending point measure long if specifically storing week event associated probably better either first two options,i using postgresql python i need store data group week year so plenty alternatives week year two separated fields date pointing start week random day week and one i like interval type i never use reading docs seems fit but reading psycopg docs i found interval mapped python timedelta object seems weird timedelta difference so two question really can i handle choice using psycopg is better alternative thanks,2 this looks lot like dupe logging using cookies pycurl you give pycurl path file write cookies csetoptpycurlcookiejar cookietxt path read probably csetoptpycurlcookiefile cookietxt,i found something similar something i want using urllib how use python login webpage retrieve cookies later usage their solution import urllib urllib cookielib username myuser password mypassword cj cookielibcookiejar opener urllibbuildopenerurllibhttpcookieprocessorcj logindata urlliburlencode username username jpassword password openeropen httpwwwexamplecomloginphp logindata resp openeropen httpwwwexamplecomhiddenpagephp print respread i want something like using pycurl possible any assistance would appreciated,1 if simply subclass group object default create new database table admin site pick new fields you need inject new fields existing group hasattrgroup parent field modelsforeignkeygroup blanktrue nulltrue relatedname children fieldcontributetoclassgroup parent to add methods group subclass tag model proxy class mygroupgroup class meta proxy true def myfunctionself return true,is way extend builtin django group object add additional attributes similar way extend user object with user object following class userprofilemodelsmodel user modelsonetoonefielduser add following settingspy file authprofilemodule appuserprofile gets profile userobjectsgetidgetprofile is equivalent approach extending group if alternative approach i take,3 you use environusername get user logon name sample i presume windows sub getdir msgbox cusers amp environusername amp documents end sub you also automatically retrieve certain locations regardless os using specialfolders ie sub getpath set wshshell createobjectwscriptshell documents wshshellspecialfoldersmydocuments msgbox documents end sub,i excel file button calls shell command vb shellthisworkbookpath amp pythonscriptbat vbnormalfocus the shell command calls batch file runs python script python pythonscriptpy all pertinent files excel file batch file data files python file located directory call sampleprogram i building someone else i intend simply unzip run in excel testing i click button get error cusersusernamedocumentspython pythonscriptpy python open file pythonscriptpy errno no file directory for reason although files location cmdexe running user directory cusersusernamedocuments i want cmdexe use path i want use pathtosampleprogram directory how i get use relative paths i transfer folder someone else place anywhere work selfcontained unit,1 you need compile version python debugging symbols you building python configure withpydebug hopefully able find error way that change behavior python internally ways if still get segfault way might try running configure cflagso ggdb even configure cflagsggdb,i test runs python script calls c code segfaults dumps core i tried load core file gdb using usrbinpython gives items stack trace how i debug core file,1 you use datetime strptime function datetime import datetime date result datetimestrptimedate ymd hms you lucky i line written project mine to print back try strftime print resultstrftime mdy hms,i following datetime i need convert i also need able subtract one date another get result hhmmss format i tried use dateutilparserparse function parses date fine sadly seem get time correctly i also tried use another method i found stackoverflow uses time i get error time defined,2 use pythondateutil import dateutilparser dateparser mydate dateparserparse fuzzytrue printmydatestrftime mdy thms,i following datetime i need convert i also need able subtract one date another get result hhmmss format i tried use dateutilparserparse function parses date fine sadly seem get time correctly i also tried use another method i found stackoverflow uses time i get error time defined,1 in django contribgis helpers djangocontribgisgeos import point pointwkt point,i get easily latlong pair google maps api googlemaps import googlemaps gmaps googlemapsgooglemapsapikey gmapsaddresstolatlng jose javier diaz cordoba argentina and i model like django import models class maappointmodelsmodel geom modelspointfieldsriddefaultsrid but i find way get wkt latlng returned gmaps any pointer,2 try calling dbrollback close cursor write operation dbcommit,i writing script access data established database unfortunately i breaking db i able recreate issue command line userbox tmp python python default sep gcc red hat linux type help copyright credits license information import pgdb db pgdbconnect localhostmydbpostgres cur dbcursor curexecuteselect from mytable limit curclose at point activity mytable greatly degraded select pgstatactivity shows connection idle transaction if i call dbclose everything fine script loops infinitely i think i need open close db connection loop i think anything fact i using data real script i calling fetchone loop process data i much db guy i sure info would useful my postgres version python shown,1 for unixes linux mac os x solaris could also use getrusage function standard library module resource the resulting object attribute rumaxrss gives peak memory usage calling process resourcegetrusageresourcerusageselfrumaxrss peak memory usage bytes os x kilobytes linux the python docs clear units exactly mac os x man page getrusage describes units bytes the linux man page clear seems equivalent information procselfstatus kilobytes the getrusage function also given resourcerusagechildren get usage child processes systems resourcerusageboth total self child process usage resource standard library module if care linux check procselfstatus file described similar question,is way python program determine much memory currently using i seen discussions memory usage single object i need total memory usage process i determine necessary start discarding cached data,3 every time index query like performs query fetches relevant result decodes returns in second snippet modify one instance entity immediately discard fetch store unmodified second copy generally avoid indexing queries like call get fetch instead for reason avoid using count possible since also requires running another query if want one result call get need call fetch count number results returned,i issue put appear work i access model class indexed member query directly however i explicitly extract class query seems work fine why this code works class record field dbstringproperty rs recordallfilter name namestr rscount assume get one record return r rs rfield somevalue rput code raise errors class record field dbstringproperty rs recordallfilter name namestr rscount assume get one record return rsfield somevalue rsput,2 neither instead cache entity protocol buffer described you might want consider switching ndb built support memcaching model instances,i page handler traffic fetches model db using key uses fields fetched model fill django template i want memcache fetched model avoid db reads not fields model used template want cache required feilds improve cache utilization fit models cache so want convert model dictionary class boject fields required template memcache uses pickle serialize values serialization purpose faster dictionary class object,1 your question efficiency absolutely unrelated use try except exception handling python relatively fast running python statement talking order microseconds your second performance undoubtedly due behaviour netgroupgetusers ip address unreachable,the code works fine i efficiency question in code i using try except pass error would crash program the error caused ip address reachable as i said code job i want know quickest way see ip reachable pass it stalls seconds ip found piled handful times could rather time consuming import winnet def getusers ip try users winnetnetgroupgetusersip none except print ip was found else print ip users return f opencusersuserdesktopiplisttxt currentip freadlines getuserscurrentipstrip fclose print done,3 you look pyicu provides access rich unicode text library provided icu including breakiterator class provides sentence finder,i trying parse sentence like base lote numero marcelo t de alvear demanda otras palabras i want first split text periods use whatever colon label sentence colon right i following definition pyparsing import unicodeprintables u joinunichrc c xrange unichrcisspace def parsetesttext label wordalphassuppress value oneormorewordunicodeprintablesliteral group grouplabelsetresultsname label valuesetresultsname value exp delimitedlist group delim return expparsestringtext and kind works drops unicode caracters whatever alphanums i thinking i would like value whole sentence value u lote u numero u u marcelo u t u de u alvear u is simple way tackle,1 there nothing app engine specific need make ajax request app set appropriate flag jquery pretty invaluable library making sort work much simpler client end on server end need handler gets value modify post request modifies returns status code your client side code call ajax,i list bookmarks displayed table i added hide link hide bookmark i want see list i still want keep table hide link show logged now i getting item database changing display property false rendering page i think better done javascript without reloading page i found several references hide row table hiding i also need write new display property database i understand i what best way hide row write new display property database thanks this code i main table display selfrequestgetdisplay mainid selfrequestgetmainid selfresponseoutwritetable classmytable tr classhead th widthlinksththedit tagsth tr display false k maingetbyidintmainid kdisplay false kput selfredirectuseradminpage query mainall queryfilterowner user queryfilterdisplay true queryorderdate cursor selfrequestgetcursor cursor querywithcursorcursor e queryfetch cursor querycursor item e mainid itemkeyid selfresponseoutwrite tr tda hrefs targetblanksaspan classsmall spanbr span classsmallsspan hrefeditmainidsspan classsmalleditspana hrefuseradminpagemainidsampdisplayfalsespan classsmallhidespana hrefcommentmainidsspan classsmallcommentsspana tda hreftcurlsampmainidsampusertaglists titleedit tagssatd tr tupleitemurl itemtitle urlparseitemurlnetloc ftruncateatspaceitempitch mainid mainid mainid itemurl mainid joinitemtaglist joinitemtaglist selfresponseoutwritetable update trying styledisplay robg answer following code work item e mainid itemkeyid selfresponseoutwrite div tr tda hrefs targetblanksaspan classsmall spanbr span classsmallsspan hrefeditmainidsspan classsmalleditspana hrefuseradminpagemainidsampdisplayfalse onclickthisparentnodestyledisplay nonespan classsmallhidespana hrefcommentmainidsspan classsmallcommentsspana tda hreftcurlsampmainidsampusertaglists titleedit tagssatd tr div update trying robg edited answer in case i click hide button row hidden moment back i understand i paste code including holding table holding table start selfresponseoutwrite table border cellpadding cellspacing tbody tr td selfresponseoutwritetd styleverticalaligntop tags table start selfresponseoutwritetable classmytable tbody tr classhead thtagsbr hrefuseradminpageorderalphaspan classsmallalphaspanabr hrefuseradminpageorderdatespan classsmallnewestspanabr hrefuseradminpageorderpopularspan classsmallpopularspana th tr orderby popular tag mostused selfresponseoutwrite trtda hreftagtagssatdtr tag tag else tag uniquetags selfresponseoutwrite trtda hreftagtagssatdtr tag tag selfresponseoutwritetable holding table first column end selfresponseoutwritetd holding table second column start selfresponseoutwritetd styleverticalaligntop main table display selfrequestgetdisplay mainid selfrequestgetmainid selfresponseoutwritetable classmytable tr classhead th widthlinksththedit tagsth tr query mainall queryfilterowner user queryfilterdisplay true queryorderdate cursor selfrequestgetcursor cursor querywithcursorcursor e queryfetch cursor querycursor item e mainid itemkeyid selfresponseoutwrite tr tda hrefs targetblanksaspan classsmall spanbr span classsmallsspan hrefeditmainidsspan classsmalleditspana hrefuseradminpagemainidsampdisplayfalse onclickthisparentnodeparentnodestyledisplay none span classsmallhidespana hrefcommentmainidsspan classsmallcommentsspana tda hreftcurlsampmainidsampusertaglists titleedit tagssatd tr tupleitemurl itemtitle urlparseitemurlnetloc ftruncateatspaceitempitch mainid mainid mainid itemurl mainid joinitemtaglist joinitemtaglist selfresponseoutwritetbodytable holding table end selfresponseoutwrite hrefuseradminpagecursorsmore resultsa cursor selfresponseoutwritetdtr selfresponseoutwritetbodytable selfresponseoutwritediv,1 you tagged javascript i see script page i also see table hide link to hide element child nodes set styledisplay property none eg divhere content button onclickthisparentnodestyledisplay none hidebutton div of course want show need reference elementstyledisplay you send http request database update display value using variety methods ajax ie using xmlhttprequest object popular edit based reply want something like page note change dobule single quotes handler since want hide entire row need go link td tr table tr tda href targetblankaspan classsmallspanbr span classsmallsspan hrefeditmainidsspan classsmalleditspana hrefuseradminpagemainidsampdisplayfalse onclickthisparentnodeparentnodestyledisplay none return false span classsmallhidespana hrefcommentmainidsspan classsmallcommentsspana tda hreftcurlsampmainidsampusertaglists titleedit tagssatd tr table incidentally closing tags tr td optional missing closing tag first cell cause issues edit the fullblown fix hide link use real url hides bookmark trip server then use dom ready onload handler add listener hide links hides element shown sends request server update status http request cancels navigation returns false that way page works without script here whole thing helper get text inside element function gettextel if textcontent supported use typeof eltextcontent string return eltextcontent otherwise innertext supported use typeof elinnertext string return elinnertext function attached listener hiding var hiderow function store image closure used http request var img new image this actual function assigned hiderow return function e get reference element called function e e windowevent var el etarget esrcelement var src go dom get link href sending request hide tr elparentnode ampamp elparentnodetagname el elparentnode get link way store href value eltagnametolowercase src elhref when get tr send request hide row eltagnametolowercase tr elstyledisplay none send request using fake image could use xmlhttprequest imgsrc src cancel navigation return false adds listener links text hide case insensitive function addlisteners get links document var link links documentlinks a regular expression match hide var hidei for link var ilenlinkslength iilen use variable current link bit efficient link linksi if link contains text hide add onclick listener retestgettextlink linkonclick hiderow call add listener function content loaded could add script element bottomo page immediately closing body tag windowonload function addlisteners,i list bookmarks displayed table i added hide link hide bookmark i want see list i still want keep table hide link show logged now i getting item database changing display property false rendering page i think better done javascript without reloading page i found several references hide row table hiding i also need write new display property database i understand i what best way hide row write new display property database thanks this code i main table display selfrequestgetdisplay mainid selfrequestgetmainid selfresponseoutwritetable classmytable tr classhead th widthlinksththedit tagsth tr display false k maingetbyidintmainid kdisplay false kput selfredirectuseradminpage query mainall queryfilterowner user queryfilterdisplay true queryorderdate cursor selfrequestgetcursor cursor querywithcursorcursor e queryfetch cursor querycursor item e mainid itemkeyid selfresponseoutwrite tr tda hrefs targetblanksaspan classsmall spanbr span classsmallsspan hrefeditmainidsspan classsmalleditspana hrefuseradminpagemainidsampdisplayfalsespan classsmallhidespana hrefcommentmainidsspan classsmallcommentsspana tda hreftcurlsampmainidsampusertaglists titleedit tagssatd tr tupleitemurl itemtitle urlparseitemurlnetloc ftruncateatspaceitempitch mainid mainid mainid itemurl mainid joinitemtaglist joinitemtaglist selfresponseoutwritetable update trying styledisplay robg answer following code work item e mainid itemkeyid selfresponseoutwrite div tr tda hrefs targetblanksaspan classsmall spanbr span classsmallsspan hrefeditmainidsspan classsmalleditspana hrefuseradminpagemainidsampdisplayfalse onclickthisparentnodestyledisplay nonespan classsmallhidespana hrefcommentmainidsspan classsmallcommentsspana tda hreftcurlsampmainidsampusertaglists titleedit tagssatd tr div update trying robg edited answer in case i click hide button row hidden moment back i understand i paste code including holding table holding table start selfresponseoutwrite table border cellpadding cellspacing tbody tr td selfresponseoutwritetd styleverticalaligntop tags table start selfresponseoutwritetable classmytable tbody tr classhead thtagsbr hrefuseradminpageorderalphaspan classsmallalphaspanabr hrefuseradminpageorderdatespan classsmallnewestspanabr hrefuseradminpageorderpopularspan classsmallpopularspana th tr orderby popular tag mostused selfresponseoutwrite trtda hreftagtagssatdtr tag tag else tag uniquetags selfresponseoutwrite trtda hreftagtagssatdtr tag tag selfresponseoutwritetable holding table first column end selfresponseoutwritetd holding table second column start selfresponseoutwritetd styleverticalaligntop main table display selfrequestgetdisplay mainid selfrequestgetmainid selfresponseoutwritetable classmytable tr classhead th widthlinksththedit tagsth tr query mainall queryfilterowner user queryfilterdisplay true queryorderdate cursor selfrequestgetcursor cursor querywithcursorcursor e queryfetch cursor querycursor item e mainid itemkeyid selfresponseoutwrite tr tda hrefs targetblanksaspan classsmall spanbr span classsmallsspan hrefeditmainidsspan classsmalleditspana hrefuseradminpagemainidsampdisplayfalse onclickthisparentnodeparentnodestyledisplay none span classsmallhidespana hrefcommentmainidsspan classsmallcommentsspana tda hreftcurlsampmainidsampusertaglists titleedit tagssatd tr tupleitemurl itemtitle urlparseitemurlnetloc ftruncateatspaceitempitch mainid mainid mainid itemurl mainid joinitemtaglist joinitemtaglist selfresponseoutwritetbodytable holding table end selfresponseoutwrite hrefuseradminpagecursorsmore resultsa cursor selfresponseoutwritetdtr selfresponseoutwritetbodytable selfresponseoutwritediv,1 you called something stringpy shadowing actual string module rename delete,i selfteaching python elkner how to think gotten chapter strings i tried load string module typing import string seemed work however i get import string dir string builtins doc file name package string confusingly help function seems died related reason help builtins doc file name package string traceback recent call last file stdin line module file systemlibraryframeworkspythonframeworkversionslibpythonsitepy line call import pydoc file systemlibraryframeworkspythonframeworkversionslibpythonpydocpy line module string import expandtabs find join lower split strip rfind rstrip importerror cannot import name expandtabs what i wrong how i fix running mac os x,2 the mcrypto modules expose much openssl functionality python including publicprivate encryption decryption signing most linux distribution provide mcrypto module native package,i would like encrypt secret text publickey decrypt privatekey python i achieve openssl command echo secrettext openssl rsautl encrypt pubin inkey publicpem base datacry base d datacry openssl rsautl decrypt inkey privatepem how would one implement python,1 i similar case worked namefirstchildchildnodesdata xml supposed simple really i know python minidom complicated made,i creating gui frontend eve online api python i successfully pulled xml data server i trying grab value node called name xmldomminidom import parse dom parsecevexml name domgetelementsbytagname name print name this seems find node output dom element name xed how could i get print value node,1 the song data work sounds rather static data set primarily inserts updates in case gae technique called relation index entity rie efficient way implement keywordbased search but preparation work required briefly build special rie entity place searchable keywords song onetoone relationship rie stores stringlistproperty supports searches like keywords searchterm returns true values list keywords matches searchterm and condition works immediately adding multipe filters or condition needs work implementing inmemory merge andonly queries you find details solution workflow code samples blog relation index entities python google datastore,i wondering way search datastore entry i bunch entries songstitle artistrating im sure really search song title artist we take search term looking entries match but lost help much appreciated we using python edit current code useless exact search might help see issue query songgqlselect from song where title searchterm or artist searchterm,1 have look answer question it uses getrusage function standard library resource module works mac os x,are methods cpython inspect process current memory usage in particular i like determine highwater mark memory usage testing script necessary i mind periodically checking memory usage calculating high water mark edit i looking either purepython solution something works os x,2 this get time zone name according tz variable localtime file unset usrbinenv python import time timetzset print timetzname,how i get olson timezone name australiasydney corresponding value given c localtime call this value overridden via tz symlinking etclocaltime setting timezone variable timerelated system configuration files,2 switched using icalendar instead vobject works lot better ics urlliburlopenhttpswwwgooglecomcalendaricalpcolaluggmailcompublicbasicicsread events cal calendarfromstringics event calwalk vevent tozone tzgettz americachicago date eventget dtstart dtastimezonetozone description eventget description eventsappend start datestrftimedateformat description description description else no description return events events,i trying parse feed multiple events returning one item ics urlliburlopenhttpswwwgooglecomcalendaricalpcolaluggmailcompublicbasicicsread events components vobjectreadcomponentsics event components tozone tzgettz americachicago date eventveventdtstartvalueastimezonetozone description eventveventdescriptionvalue eventsappend start datestrftimedateformat description description description else no description return events events what i wrong,2 in order iterate classes members need use inpsectgetmembers so last example would look like import inspect fields membername memberobject inspectgetmembersselfclass inspectisdatadescriptormemberobject fieldsappendmembername in descriptor replace accessing dict directly python getattr setattr builtins also keep mind want make distinction descriptor attribute name class underlying instance attribute in cases like i usually prepend underscore eg class field object def initself name requiredfalse selfname name selfrequired required def setself obj val setattrobj selfname val def getself obj return getattrobj selfname,i seem figure get list classes data descriptors basically i want run validation fields unset fields for instance class field object def init self name requiredfalse selfname name selfrequired required def set self obj val objdictselfname val def get self obj obj none raise attributeerror selfname objdict raise attributeerror return objdictselfname then i wanted implement model like class basemodel object someattr field someattr requiredtrue def save self field fields fieldrequired fieldname selfdict raise exeception validation error how would i go getting list fields i define i thinking i could following import inspect fields attr selfclassdict inspectisdatadescriptorselfclassdictattr fieldsappendattr but i ran problems inheritance ideas,1 i suggest using psycopg instead pgdb pgdb uses following semantics connect open database connection begin transaction commit commit begin transaction rollback rollback begin transaction execute execute statement psycopg hand uses following semantics connect open database connection commit commit rollback rollback execute begin transaction unless already transaction execute statement amber mentioned rollback commit select statement terminate transaction unfortunately pgdb immediately start new transaction rollback commit even performed work for many database systems pgdb behavior fine way postgresql handles transactions cause trouble got lots connections accessing tables trouble specifically vacuum why pgdb start transaction right away the python dbapi spec calls seems kind silly way spec written,i writing script access data established database unfortunately i breaking db i able recreate issue command line userbox tmp python python default sep gcc red hat linux type help copyright credits license information import pgdb db pgdbconnect localhostmydbpostgres cur dbcursor curexecuteselect from mytable limit curclose at point activity mytable greatly degraded select pgstatactivity shows connection idle transaction if i call dbclose everything fine script loops infinitely i think i need open close db connection loop i think anything fact i using data real script i calling fetchone loop process data i much db guy i sure info would useful my postgres version python shown,1 you set one method look another class testclassobject def currentself test just method get value selftest test printtest def nextoneself trying get value current method newval selftest printnewval as note want set selftest try retrieve otherwise cause error i generally init class testclassobject def initself selftest none def currentself test just method get value selftest test printtest def nextoneself trying get value current method newval selftest printnewval,looking make variable set one methodfunction class accessible another methodfunction class without excess problematic code outside here example work may show i trying i coppied one init method class testclassobject def currentself test just method get value printtest pass def nextoneself trying get value current method newval selfcurrentplayertest printnewval pass,3 encrypt usrbinenv python import fileinput mcrypto import rsa rsa rsaloadpubkeypublicpem ctxt rsapublicencryptfileinputinputread rsapkcspadding print ctxtencode base decrypt usrbinenv python import fileinput mcrypto import rsa priv rsaloadkeyprivatepem ctxt fileinputinputreaddecode base print privprivatedecryptctxt rsapkcspadding see also how encrypt string using key what best way encode string publickey python,i would like encrypt secret text publickey decrypt privatekey python i achieve openssl command echo secrettext openssl rsautl encrypt pubin inkey publicpem base datacry base d datacry openssl rsautl decrypt inkey privatepem how would one implement python,3 django newbiemistakes problem you using sqlite databasename set database file full path database file writeable apache still get error solution make sure apache also write parent directory database sqlite needs able write directory make sure folder database file full path start number eg wwwmywebdb observed windows if databasename set something like usersyournamesitesmydjangoprojectdbdb make sure created db directory first make sure tmp directory worldwritable unlikely cause thing system also work ls tmp ald produce drwxrwxrwt make sure path database specified settingspy full path also make sure file present expect,i get error setting server django it sqlite means create db file seem i stipulated sqlite backend absolute file path put luck is bug i something incorrect was thinking absolute file path specified differently ubuntu here beginning settingspy file django settings omnicloud project debug true templatedebug debug admins your name youremailexamplecom managers admins databases default engine djangodbbackendssqlite add postgresqlpsycopg postgresql mysql sqlite oracle name haroldserveromniclouddb or path database file using sqlite user not used sqlite password not used sqlite host set empty string localhost not used sqlite port set empty string default not used sqlite,3 their documentation serve purposes httpwwwcrummycomsoftwarebeautifulsoupdocumentationhtml it looks like going want something like beautifulsoup import beautifulsoup import soup beautifulsoupthexmlasastring results soupfindallrecompile info r results myurl rparenthref that code tested general idea use beautifulsoup,i trying scrape contents following page using beautifulsoup div datareferrerpagelet idpagelet div id classp div classuiheader uiheadertopandbottomborder uiheadersection div classclearfix uiheadertop div h classuiheadertitleinfo h divdivdivdiv classphs table classuicontenttable tbody tr th classlabelotherth td classdatadiv iduaty classuicollapsedlist uicollapsedlisthidden uicollapsedlistnoseparate pageslistdata span classvisible hrefhttpabccomfedererinfoa hrefhttpabccompagesianwrightoutofboundsinfoa hrefhttpabccomjunipernetworksinfoa hrefhttpabccompagesjoindiasporainfoa span div td td classrightcol td tr tbody table div div div div datareferrerpageletent idpageletent div id classsection div classuiheader uiheadertopandbottomborder uiheadersection div classclearfix uiheadertop div h classuiheadertitleinfoh divdivdiv div classphstable classuiinfotable mtm profileinfotable tbody tr th classlabelinfo thtd classdata div classmediarowwrapper ul classuilist uilisthorizontal clearfix pbl mediarow li classuilistitem uilisthorizontalitemborder uilisthorizontalitem hrefurl div classmediaportrait div styleheight px width px classfbprofilescalablethumb photo img width stylemargin px px titlehans zimmer alt srchttpprofileakfbcdnnethprofileaksncsjpg classimgdivdiv classmediapagenameinfo divdivalili classpls uilistitem uilisthorizontalitemborder uilisthorizontalitem hrefurl div classmediaportraitdiv styleheight px width px classfbprofilescalablethumb photoimg width stylemargin px px titletest alt srchttpexternalakfbcdnnetsafeimagephpdaqcvrllyopjazfampampwampamphampampurlhttpaffuploadwikimediaorgfwikipediafcommonsfffjpgampampfallbackhubmusicampampprefixs classimgdivdiv classmediapagenametestdivdiva div div classmediapagenameinfo div div this page contains multiple nested div table need help using beautifulsoup parse info info info url url i read beautifulsoup documentation much helpful also please suggest beautifulsoup reference doc book parsing complex web pages thanks help appreciated sat,1 try pathtosampleprogram drive home drive shell cmdexe k cd amp thisworkbookpath amp ampamppythonscriptbat pathtosampleprogram drive home drive dont know advance shell cmdexe k amp leftthisworkbookpath amp ampampcd amp thisworkbookpath amp ampamppythonscriptbat,i excel file button calls shell command vb shellthisworkbookpath amp pythonscriptbat vbnormalfocus the shell command calls batch file runs python script python pythonscriptpy all pertinent files excel file batch file data files python file located directory call sampleprogram i building someone else i intend simply unzip run in excel testing i click button get error cusersusernamedocumentspython pythonscriptpy python open file pythonscriptpy errno no file directory for reason although files location cmdexe running user directory cusersusernamedocuments i want cmdexe use path i want use pathtosampleprogram directory how i get use relative paths i transfer folder someone else place anywhere work selfcontained unit,1 after running around problem i able figure actual cause come issue the underling problem i another module accidentally carries name so due conflicting exception occurs finally i changed module name model names problem sorted thanks inputs regards gayan,i process trying upgrade module written openerp although works fine local machine local openerp server it gives error i try update files via svn staged server the error states trying insert record db actually update insertion i worried remove record postgres db directly though think might trick i also removed existing files i svn update staged server may might pit fall quite sure let know guys think best solution problem below error messages show openerp server restarted svn update the server stops never ends but soon i revert files remove update server works like charm module abc loading objects oetest infoinitmodule abcregistering objects oetest infoinitmodule abc creating updating database tables oetest debugsqlbad query insert into irmodeldata namedateinitdateupdatemodulemodelresid values e modelabc e abc e irmodel oetest debugsql modelabc u abc irmodel oetest debugsqlduplicate key value violates unique constraint irmodeldatamodulenameuniq regards gayan,1 i never seen real convention i personally put main sentinel within initpy invoked via python somepackage,i coding new python package used others to demonstrate used i writing demo script executes main parts new package what convention find script easily should separate module name should located package root directory out package in initpy,1 i sure python usually expensive operation copies string new memory using string builder array join probably much faster,i trying tests external sorting algorithms i thought i generate huge amount random numbers put file here i import tempfile random nf tempfilenamedtemporaryfiledeletefalse j buf j buf strrandomrandint j nfwritebuf i thought i speed generating process reducing file io operations i use buf store many numbers possible write buf file question i still got sense generating writing process slow am i getting something wrong edit in c simply write int float file without converting string so python i mean write integer file without converting str,1 don use string concatenation loop use strjoin instead cpython implementation detail if strings python implementations cpython usually perform inplace optimization assignments form when applicable optimization makes quadratic runtime much less likely this optimization version implementation dependent for performance sensitive code preferable use strjoin method assures consistent linear concatenation performance across versions implementations your code would look like buf joinstrrandomrandint j range and note since specified separator look like change want numbers example comma separated i also think need buffer writing file already buffered,i trying tests external sorting algorithms i thought i generate huge amount random numbers put file here i import tempfile random nf tempfilenamedtemporaryfiledeletefalse j buf j buf strrandomrandint j nfwritebuf i thought i speed generating process reducing file io operations i use buf store many numbers possible write buf file question i still got sense generating writing process slow am i getting something wrong edit in c simply write int float file without converting string so python i mean write integer file without converting str,2 you force queries fetch fields want save memory,i django model load relatively small fields one kinda huge one let say something like class mymodelmodelsmodel thing modelsforeignkey thing egg modelstextfield spoon modelstextfield race modelsfloatfield bigfield modelstextfield bigfield needed small number functions however model used place how i avoid bigfield stored memory is lazy evaluation say i iterated queryset extracting egg time would cause bigfield stored memory also thanks,2 if need generate random numbers linux try shell command echo random done testin ok test code takes seconds finish import tempfile random nf tempfilenamedtemporaryfiledeletefalse xrange nfwritestrrandomrandint,i trying tests external sorting algorithms i thought i generate huge amount random numbers put file here i import tempfile random nf tempfilenamedtemporaryfiledeletefalse j buf j buf strrandomrandint j nfwritebuf i thought i speed generating process reducing file io operations i use buf store many numbers possible write buf file question i still got sense generating writing process slow am i getting something wrong edit in c simply write int float file without converting string so python i mean write integer file without converting str,1 use im imtransformimageaffine prefix variable module name,i using transform method image class import image im imageopen imagejpg im imtransformaffine the code produces error nameerror name affine defined if i use image import works image import im open imagejpg im imtransformaffine however i want override previously defined methods therefore i want use import image how i make first example work without use image import,3 you specified absolute path used shortcut might work context use homeyourusernameharoldserveromniclouddb instead,i get error setting server django it sqlite means create db file seem i stipulated sqlite backend absolute file path put luck is bug i something incorrect was thinking absolute file path specified differently ubuntu here beginning settingspy file django settings omnicloud project debug true templatedebug debug admins your name youremailexamplecom managers admins databases default engine djangodbbackendssqlite add postgresqlpsycopg postgresql mysql sqlite oracle name haroldserveromniclouddb or path database file using sqlite user not used sqlite password not used sqlite host set empty string localhost not used sqlite port set empty string default not used sqlite,3 operating systems already optimized io operations so directly write numbers file get good speed import tempfile random tempfilenamedtemporaryfiledeletefalse nf xrange xrange efficient range python nfwritestrrandomrandint in practice numbers written disk sizeoptimized file buffer full the code question code take time machine so i would advise use simpler code rely operating system builtin optimizations if result fits memory case million numbers indeed save io operations creating final string writing one go tempfilenamedtemporaryfiledeletefalse nf nfwrite joinstrrandomrandint xrange this second approach faster computer instead probably thanks single write call instead million write calls–and probably many fewer actual disk writes the many big writes approach question falls middle it improved though clearer pythonic write like import tempfile random tempfilenamedtemporaryfiledeletefalse nf xrange nfwrite joinstrrandomrandint xrange this solution equivalent faster code original question machine instead â in summary first simple approach might fast enough if whole file fit memory second approach fast simple otherwise initial idea fewer writes bigger blocks good fast single write approach still quite simple written,i trying tests external sorting algorithms i thought i generate huge amount random numbers put file here i import tempfile random nf tempfilenamedtemporaryfiledeletefalse j buf j buf strrandomrandint j nfwritebuf i thought i speed generating process reducing file io operations i use buf store many numbers possible write buf file question i still got sense generating writing process slow am i getting something wrong edit in c simply write int float file without converting string so python i mean write integer file without converting str,3 you aware dp problems per se optimal independent distributed computations when consider classical forms dp algorithms matrixtablearray successively compute new values certain order each computation value requires values created hence lose data independence maximally compute certain number array fields time depending specific dp algorithms for example many dp algorithms process whole table column parallel field relies fields previous column but already limit due data dependency remaining fields column that said calculating sum possibilities various numbers available list not dp problem you solve subproblems simply collect possible sums happen match one list entries hence i suggest following sightly different approach compute new list possible summations this data independent parallelized need upper bound termination example becomes you explicitly construct list pass combination next step evaluate computation ie create sum check whether matches value original list again data independent perform calculations independently combine positive results final datastructure so sum answer questions rethink whether want regard problem dp you may want read dataparallelism this particularly relevant solving problems gpus corresponding literature cudaopencl may useful,i posted bit related project i trying work i keep hitting design problems design scratch so i wondering i post i trying someone help understand i get result i want background i new programming trying learn so i took project interested involves basically taking list breaking number using numbers list i know i could easily brute force thiswhich i i wanted also learn hbase hadoop parallel processing i wanted way i could break process across various machines i thought way using dynamic programming recursions create table possibilities could broken even example if i submit list i get what basically saying trying see ways make i look listwhich database see break i lookup job working breakdown i problems using brute force let use large numberssay million thousand numbers list way i use hadoop tool scale here examples possible results the logic approach take time comput next possible data list i send list million numbers could quickly even scale hadoop cluster the code i created get work question correct design problem i got advice partition problem looked around found much simpler versions i trying activestate exactly i trying breaks number use specific data set question so hopefully i clearly described i trying what i need readstudylearn create table partition list python using dynamic programming scale its hobby time sensitive i feel i working months time i hit design problems cause start scratch how i build correctlyto see incorrect way see link i googled found solutions knapsack problem partition problems seem school work really built scale large datasets hopefully someone give insight regardless thank reading,2 sudo aptget install libjpegdev rebuild pil install,im working ubuntu i trying work pil django project sadly pil cannot load image here pil setup summary pil setup summary version platform linux r apr gcc tkinter support available jpeg support available zlib pngzip support available freetype support available littlecms support available i tried coding python shell returns error i called load function import pil import image import imaging imageopensomeimagejpg jpegimagepluginjpegimagefile image modergb sizex xcc iload traceback recent call last file console line module file homejosephdesktopthesisenvlibpythonsitepackagespilimagefilepy line load raiseioerrore file homejosephdesktopthesisenvlibpythonsitepackagespilimagefilepy line raiseioerror raise ioerrormessage reading image file ioerror broken data stream reading image file i also working virtual environment i problems uploading jpeg image django project png works fine rejects jpeg,3 i know code seems long overly complex simple problem manual optimization usually code potential bugs that premature optimization almost always mistake in init sets plot setting references axis canvas line starts line drawn screen preanimation background additionally init registers callbacks handle resizing shutdown the onresize callback needed update background used blit window resized the onclose callback uses lock update running status i eliminated race conditions works prevent tkintertclerror caused trying blit terminated tk app i tested tk one machine ymmv i open suggestions in run method i added call canvasflushevents this keep plot window hanging try drag window around resize the loop method calls selfgetnewvalues set data plot it updates plot using configured method if selfblit true uses canvasblit else uses pyplotdraw the variable spf samples per frame controls many samples plotted frame you use implementation getnewvalues determine number bytes read eg selfspf bytes per sample i set default frames per second data rate samples per second you find sweet spot maximizes throughput vs time resolution graph also keeping incoming data reading data numpy array instead using python list likely speed processing also would give easy access tools downsample analyze signal you read numpy array directly byte string make sure get endianess right data b xxff big endian nplittleendian machine little endian true npfromstringdata dtypenpuint wrong array dtypeuint nplittleendian ybyteswap fixed array dtypeuint code future import division matplotlib import pyplot import threading class mainobject def initself samplesperframe blittrue selfblit blit selfspf samplesperframe pyplotion selfax pyplotsubplot selfline selfaxplotrangeselfspf selfspf selfaxaxis selfspf pyplotdraw selfcanvas selfaxfigurecanvas selfbackground selfcanvascopyfrombboxselfaxbbox selfcanvasmplconnect resizeevent selfonresize selfcanvasmplconnect closeevent selfonclose selflock threadinglock selfrun def getnewvaluesself import time import random simulate receiving data bps cntrlcrc timesleep selfspf randomrandrange rangeselfspf selflinesetydatay def onresizeself event selflinesetydata selfspf pyplotdraw selfbackground selfcanvascopyfrombboxselfaxbbox def oncloseself event selflock selfrunning false def runself selflock selfrunning true selfrunning selfcanvasflushevents selflock selfgetnewvalues selfrunning selfblit blit higher frame rate selfcanvasrestoreregionselfbackground selfaxdrawartistselfline selfcanvasblitselfaxbbox else versus regular draw pyplotdraw name main mainsamplesperframe blittrue,so deal i module sends data serial port baud i using matplotlib plot data real time i wrote code python import section import serial import struct import numpy np import matplotlibpyplot plt serial configuration com serialserial print successfully opened comportstr def getnewvalues comread rawdata structunpack bbbbbbbbbbbbbbbbbbbb j normdata range bigbyte rawdatairawdatai normdataappendbigbyte j j return normdata x range getnewvalues pltion line pltplotxy getnewvalues linesetydataa pltdraw comclose print port closed successfully i get bytes make big bytes byte data split two byte values transmitting but i noticed i getting real time values i windows home basic matters any clue happening edit also whenever i click plot hangs,1 i know python function easily code one import math def ceilx return mathceilfloatxs the conversion float necessary python avoid integer division arguments integers you also use future import division this needed python,i know mathceil numpyceil lack significance parameter for example excel ceiling numpyceil mathceil hand numpyceil mathceil so i wonder is similar excel solution already,3 you probably go faster def extractrawstring startmarker endmarker start rawstringindexstartmarker lenstartmarker end rawstringindexendmarker start return rawstringstartend but want try regex try benchmark there good timeit module,i looking build string function extract string contents two markers it returns extraction list def extractrawstring startmarker endmarker function return extractionlist i know done using regex fast this called billions times process what fastest way what happens markers appear odd number times the function return multiple strings start end markers appear,3 it sounds like looking particular parameter blanktime this done following sed oneliner cat myfiletxt sed sblanktimes this search blanktime replace value leaving lines intact edit to replace contents file use following twostep approach cat myfiletxt sed sblanktimes myfiletxttmp mv myfiletxttmp myfiletxt,i beginner python useless regex struggling replace unknown number file new number i looked python tos examples still make progress create expression myfiletxt some text more text option blanktime text i want replace another number line appears file line number unknown value also unknown could number contained quotation marks best way would python done maybe sed,1 turns even dryer solution i hoped introspection like def upgrademigrateengine meta metadatabindmigrateengine users table users meta autoloadtrue userscuseridaltername id def downgrademigrateengine meta metadatabindmigrateengine users table users meta autoloadtrue userscidaltername userid works like charm,i trying alter column name first attempt script meta metadata users table users meta column id integer primarykeytrue column name string uniquetrue column email string uniquetrue def upgrademigrateengine metabind migrateengine userscidaltername id def downgrademigrateengine metabind migrateengine userscidaltername userid running migratepy test dev database sqlite works upgrading downgrading but deploying test environment heroku postgresql used i get trace i try upgrade gist message sqlalchemyexcprogrammingerror programmingerror column id exist i tried use userscuserid upgrade method that fails environments attributeerror userid the workaround i using script metaold metadata metanew metadata usersold table users metaold column userid integer primarykeytrue column name string uniquetrue column email string uniquetrue usersnew table users metanew column id integer primarykeytrue column name string uniquetrue column email string uniquetrue def upgrademigrateengine metaoldbind migrateengine usersoldcuseridaltername id def downgrademigrateengine metanewbind migrateengine usersnewcidaltername userid it already recommended practice copypaste model sqlalchemymigrate scripts but extra duplications gets bit much anyone knows done assuming bug i like suggestions dry workaround,3 import datetime import logging class logger def myloggerself loggerlogginggetlogger provisioningpython lenloggerhandlers loggersetlevelloggingdebug datetimedatetimenow handlerloggingfilehandler rootcredentialslogsprovisioningpython nowstrftimeymd log formatter loggingformatter asctimes levelnames messages handlersetformatterformatter loggeraddhandlerhandler return logger made trick using python,i using python logger the following code import os import time import datetime import logging class logger def myloggerself logger logginggetlogger provisioningpython loggersetlevelloggingdebug datetimedatetimenow handlerloggingfilehandler rootcredentialslogsprovisioningpython nowstrftimeymd log formatter loggingformatter asctimes levelnames messages handlersetformatterformatter loggeraddhandlerhandler return logger the problem i i get multiple entries log file loggerinfo call how i solve,3 import l ab tb item l researchrddd item f floatmgroup intmgroup outappendf,i got list strings following format ab tb how parse strings like take st element list real type integer type real type integer type how loop,1 should separate module name demosomeusefulnamepy a demo directory contains demo scripts similarly test directory contains unit tests should located package root directory no it part package it demo out package yes in init py never a package two lives uninstalled source libsitepackages installed code the source include readme setuppy demo directory test directory package the toplevel source setuppy install package the demo test get installed they get left behind part download,i coding new python package used others to demonstrate used i writing demo script executes main parts new package what convention find script easily should separate module name should located package root directory out package in initpy,2 l ab tb el l endoffloat elrfind f floatelendoffloat intelendoffloat,i got list strings following format ab tb how parse strings like take st element list real type integer type real type integer type how loop,1 use beautifulsoup beautifulsoup import beautifulsoup html doctype html public wcdtd xhtml transitionalen httpwwwworgtrxhtmldtdxhtmltransitionaldtd html xmlnshttpwwwworgxhtml head meta httpequivcontenttype contenttexthtml charsetwindows titleuntitled documenttitle head body this body body html soup beautifulsouphtml print soupfind body string,i wanted capture text html using python example usrbinpython import urllib open urlliburlopen httplocalhostmainphp read openread print read source code target url doctype html public wcdtd xhtml transitionalen httpwwwworgtrxhtmldtdxhtmltransitionaldtd html xmlnshttpwwwworgxhtml head meta httpequivcontenttype contenttexthtml charsetwindows titleuntitled documenttitle head body this body body html i want catch words this body please guys help matter for example html replaced one table width aligncenter tr tdthe information available site freely accessible publictd tr table table classadminlist border width cellpadding cellspacing aligncenter tr td rowspan colspanimg srcimagesforumpngbrtd tr tr tdibphonebtdtd td tr tr tdibnamebtdtd stundettd tr tr tdibclassbtd td summertd tr tr tdibemailbtd td studentlocalhostcomtd tr table want make output phone name student class summer email studentlocalhostcom caught words core html,2 try beautiful soup beautifulsoup import beautifulsoup soup beautifulsouphtml soupfindallbodystring,i wanted capture text html using python example usrbinpython import urllib open urlliburlopen httplocalhostmainphp read openread print read source code target url doctype html public wcdtd xhtml transitionalen httpwwwworgtrxhtmldtdxhtmltransitionaldtd html xmlnshttpwwwworgxhtml head meta httpequivcontenttype contenttexthtml charsetwindows titleuntitled documenttitle head body this body body html i want catch words this body please guys help matter for example html replaced one table width aligncenter tr tdthe information available site freely accessible publictd tr table table classadminlist border width cellpadding cellspacing aligncenter tr td rowspan colspanimg srcimagesforumpngbrtd tr tr tdibphonebtdtd td tr tr tdibnamebtdtd stundettd tr tr tdibclassbtd td summertd tr tr tdibemailbtd td studentlocalhostcomtd tr table want make output phone name student class summer email studentlocalhostcom caught words core html,3 python require function it slicing syntax supports stringsub functionality directly hello hello lo abcdefghijklmnop acegikmo abcdefghijklmnop bdfhjlnp reverse siht esrever,as per title i looking python function similar lua stringsub whether rd party part python standard library i searching internet including stackoverflow nearly hour able find anything whatsoever,3 to directly answer question wrap value definition originaltextfor give back string slice matching tokens came single string you could also add parse action like valuesetparseactionlambda joint but would explicitly put single space item might spaces case word one space originaltextfor give exact input substring but even simpler reading everything would use restofline of course simplest would use split i assume specifically asking pyparsing a couple notes xxxsetresultsname yyy shortened xxx yyy improving readability parser definition your definition value oneormorewordunicodeprintables literal couple problems for one thing included set characters unicodeprintables included parsed words the best way solve use excludechars parameter word sentence words include commas oneormorewordunicodeprintables excludechars now also exclude possible punctuation like etc adding excludechars string i noticed using delimiter delimitedlist work include excluded character pyparsing like regular expression regard lookahead try match next token parser next character continues match current token that extra work avoid reading much in general something openended oneormorewordunicodeprintables likely eat entire rest input string,i trying parse sentence like base lote numero marcelo t de alvear demanda otras palabras i want first split text periods use whatever colon label sentence colon right i following definition pyparsing import unicodeprintables u joinunichrc c xrange unichrcisspace def parsetesttext label wordalphassuppress value oneormorewordunicodeprintablesliteral group grouplabelsetresultsname label valuesetresultsname value exp delimitedlist group delim return expparsestringtext and kind works drops unicode caracters whatever alphanums i thinking i would like value whole sentence value u lote u numero u u marcelo u t u de u alvear u is simple way tackle,1 yes python offers opinion nice substring option string returns ri note slicing supports variety options string ring string stri string strin everything last character string string captures string srn take every second character you find information,as per title i looking python function similar lua stringsub whether rd party part python standard library i searching internet including stackoverflow nearly hour able find anything whatsoever,2 lua stringsubhello lua user character end lua user stringsubhello lua user character including lua stringsubhello lua user end end lua user stringsubhello lua user end start lua stringsubhello lua user end end lua python hello lua user lua user hello lua user lua hello lua user lua user hello lua user lua hello lua user lua python unlike lua zero index hence character counting different arrays start lua python in python slicing first value inclusive second value exclusive upto including empty first value equal zero empty second value equal size string,as per title i looking python function similar lua stringsub whether rd party part python standard library i searching internet including stackoverflow nearly hour able find anything whatsoever,3 there simple way reuse plot windows must use eclipse run when i working interactively matplotlib i use either spyder ipython edit class reload class run code if want get rid open plot windows hit stacked stop icons kill runing python instances,i using matplotlibpyplot eclipse windows every time i run code opens several pyplot figure windows the problem i close windows manually accumulate i would like use pyplot find windows opened another process pythonexe reuse in words i want multiple windows figure even across interpreter processes is simple way,1 there graphviz httpwwwgraphvizorg it uses dot language plot graphs you either generate dot code use pydot httpscodegooglecomppydot you could also use networkx httpnetworkxlanlgovtutorialtutorialhtmldrawinggraphs make easy draw either graphviz matplotlib networkx matplotlib graphviz gives flexibility power need install lot if want quick solution try install graphviz open hellodot w writedigraph g helloworld import subprocess subprocesscallpathtodotexetpnghellodotographpng i think right try form command line debug then install pydot pydot already then use networkx drive pydot,i want plot trees using python decision trees organizational charts etc any library helps,3 big edit big numbers the following code shows problem solution answer note i changed parameter function hexfbinffloathex h floathex make parameter used unutbu function floathextobinaryfloathex decimal import decimalgetcontext getcontextprec tinies decimal decimali xrange com dictitin itin enumeratetinies def hexfbinffloathex tinies tinies fromh floatfromhexfloathex print fromh floatfromhexh done print fromh fromh print strfloatfromhexfloathex strfloatfromhexfloathex ap strfloatfromhexfloathexpartition print dot print dot p following part transforms float dot binary dot bits pdec decimal p tin tinies pdectin bitsappend break elif pdectin bitsappend pdec tin else bitsappend pbin joinbits binary dot float dot easily transformed binary return joinbinintapbin x x print x f formatx h xhex print h xhex h print nentering hexfbinffloathex h argument v hexfbinfh print nhexfbinfx v result x h xhex xabfadp entering hexfbinffloathex h argument fromh floatfromhexh done fromh e strfloatfromhexfloathex e dot dot e hexfbinfx b the problem due instruction strfloatfromhexx instruction ap strfloatfromhexxpartition produces big number representation floatfromhexx exponent then the parts before the dot ante and after the dot p post are false correcting easy replacing inaccurate instruction one ap f formatfloatfromhexxpartition nota bene on typical machine running python bits precision available python float value stored internally enter decimal number binary fraction httpdocspythonorgtutorialfloatingpointhtml that means big value float written code internal representation fact approximation written value that shown following code x print x h xhex print h xhex h floatfromhexh print floatfromhexh f formaty print x print x h xhex print h xhex h floatfromhexh print floatfromhexh f formaty print result x h xhex xabfadp floatfromhexh x h xhex xabfadp floatfromhexh values h h though different values assigned identifiers x x script objects x x represented approximation machine the internal representation exact value internal representation approximation hence deduction h h x x gives value h h this problem exists write number decimal representation script it exist write number directly hexadecimal binary representation what i wanted underline i wrote function afterdotbinaryfloatsbin com com perform verification results yielded hexfbinf this verification works well number passed hexfbinf big internal approximation big numbers lot digits i wonder verification distorted indeed big number arrives function already approximated digits dot transformed series zeros shown decimal import decimal getcontext getcontextprec tinies decimal decimali xrange com dictitin itin enumeratetinies def afterdotbinaryfloatsbin com com transforms binary lying dot float dot sbinstartswith b sbinstartswith sbin sbinsplit allc c sbin return sumintccomi ic enumeratesbin else return none def hexfbinffloathex tinies tinies transforms hexadecimal float dot binary float dot ap f formatfloatfromhexfloathexpartition following part transforms float dot binary dot bits pdec decimal p tin tinies pdectin bitsappend break elif pdectin bitsappend pdec tin else bitsappend pbin joinbits binary dot float dot easily transformed binary return joinbinintapbin n decimal print n f transformed method hex formatn nhexed nhex print nhexed nhex nhexed print nhexfbinfnhexed hexfbinfnhexed print nverificationnbeforeafter hexfbinfnhexedpartition beforeafter hexfbinfnhexedpartition print print intbefore intbefore print afterdotbinaryfloatafter afterdotbinaryfloatafter print nn result n transformed method hex nhexed nhex xabfadp hexfbinfnhexed b verification beforeafter hexfbinfnhexedpartition b intbefore afterdotbinaryfloatafter e n transformed method hex nhexed nhex xabfadp hexfbinfnhexed b verification beforeafter hexfbinfnhexedpartition b intbefore afterdotbinaryfloatafter e n transformed method hex traceback recent call last file iverfitrucpy line module nhexed nhex attributeerror decimal object attribute hex conclusion testing numbers makes difference interest so i wanted test unapproximated numbers i passed decimal float number as see problem instance hex method finally i entirely sure function big numbers works correctly common numbers i corrected inaccurate instruction edit i added instruction ap f formatfromhpartition otherwise value p could truncated thus giving binary representation slightly different number one passed function i put length i defined list tinies contains decimal instances corresponding etc however though rare number digits comma sense adding remains unsatisfactory code absolutely general case unutbu code,i wondering convert result returned floathex binary example xap can anyone please help thanks,1 i really want change things around what best way go i hate break best way refactor code ie shuffle things around you want circular dependencies going make life hard long run a hierarchical tree dagstructured module setup far easiest handle the easiest way achieve merge three modules one perhaps move stuff back separate modules,i files file imports file file imports file file needs refference something file a basic example filepy import file class core def initself selfsomething hello world selfrun filerun c core filepy import file class run def initself selfsomethingelse cows filefunc filepy import file class func print filecsomething so see file needs access variable csomething exists file part class calls file turn calls file this piece code i inhereted rest code quite complicated i really want change things around to give realistic example going basically actual code filepy import file import config class core def initself selfconfig configload configload expensive db opperation run selfrun filerun c core filepy import file class run def initself do things require access config filefunc filepy import file class func do stuff requires access config print filecconfig config we call configload lots functions must able access we also pass selfconfig arguments function call far many functions depend reasonable we like avoid using global variables keep refferenced class possible what best way go,3 the easiest way make working move import file line end filepy see description httpeffbotorgzoneimportconfusionhtmcircularimports,i files file imports file file imports file file needs refference something file a basic example filepy import file class core def initself selfsomething hello world selfrun filerun c core filepy import file class run def initself selfsomethingelse cows filefunc filepy import file class func print filecsomething so see file needs access variable csomething exists file part class calls file turn calls file this piece code i inhereted rest code quite complicated i really want change things around to give realistic example going basically actual code filepy import file import config class core def initself selfconfig configload configload expensive db opperation run selfrun filerun c core filepy import file class run def initself do things require access config filefunc filepy import file class func do stuff requires access config print filecconfig config we call configload lots functions must able access we also pass selfconfig arguments function call far many functions depend reasonable we like avoid using global variables keep refferenced class possible what best way go,1 use custom method admin class class bookadminadminmodeladmin listdisplay name threetags def threetagsself obj return objbooktagsetall,i models admin code the question i show first three tag book listdisplay property i show tags book editing i would like tags book listed admin panel modelspy class bookmodelsmodel name modelscharfieldmaxlength def unicodeself return selfname class booktagmodelsmodel name modelscharfieldmaxlength book modelsforeignkeybooknullfalseblankfalse def unicodeself return selfname adminpy class booktaginlineadmintabularinline model jobtitletag class bookadminadminmodeladmin listdisplay name inlines booktaginline adminsiteregisterbookbookadmin could give suggestion thanks,3 you could import runtime rather module load time file would class func def initself import file do stuff requires access config print filecconfig config although still issue c core line line means extra module initialisation happens core happens assigned c variable to get around probably want file something like import file class core def initself selfconfig def runself selfrun filerun c core make sure global variables initialised nicely crun initialisation finished work,i files file imports file file imports file file needs refference something file a basic example filepy import file class core def initself selfsomething hello world selfrun filerun c core filepy import file class run def initself selfsomethingelse cows filefunc filepy import file class func print filecsomething so see file needs access variable csomething exists file part class calls file turn calls file this piece code i inhereted rest code quite complicated i really want change things around to give realistic example going basically actual code filepy import file import config class core def initself selfconfig configload configload expensive db opperation run selfrun filerun c core filepy import file class run def initself do things require access config filefunc filepy import file class func do stuff requires access config print filecconfig config we call configload lots functions must able access we also pass selfconfig arguments function call far many functions depend reasonable we like avoid using global variables keep refferenced class possible what best way go,1 it expirmental google graphviz api it convenient want quickly visualize graph want install software,i want plot trees using python decision trees organizational charts etc any library helps,1 like import random import struct open binarydat wb output xrange u randomrandint number b structpack u bytes outputwriteb this create million bytes data million byte values you read struct various packing options httpdocspythonorglibrarystructhtml,i trying tests external sorting algorithms i thought i generate huge amount random numbers put file here i import tempfile random nf tempfilenamedtemporaryfiledeletefalse j buf j buf strrandomrandint j nfwritebuf i thought i speed generating process reducing file io operations i use buf store many numbers possible write buf file question i still got sense generating writing process slow am i getting something wrong edit in c simply write int float file without converting string so python i mean write integer file without converting str,1 i suspect following happens ab python looks value finds kind reference b says true ab python looks finds b looks since holds b b now sees b holds kind reference exactly b so python compare elements means compare b now infinite recursion starts note works python actually copy list assigning ab python rather creates reference b stored,it possible create infinite nested list python that clear although popular definitely useful known fact true my question happening b b b b b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true which way deeper i trying understand i feel much like brain going explode i see contains b contains now questions one do really two lists one how thing like gets stored memory what could purpose enable programers implement something strange like please treat question superserious and forget programming fun sometimes,3 these two lists first create b and assign one first element one b b so say b b situation first example obe level deeper additionally compare identity equality this leads try compare deeply inside leads recursion,it possible create infinite nested list python that clear although popular definitely useful known fact true my question happening b b b b b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true which way deeper i trying understand i feel much like brain going explode i see contains b contains now questions one do really two lists one how thing like gets stored memory what could purpose enable programers implement something strange like please treat question superserious and forget programming fun sometimes,2 i see contains b contains they contain a reference list first thing list reference b vice versa b true b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true the number matter many list lookups like matters example odd numbers lookups saying b equal b point python compares memory addresses sees thing says yes with example even lookups saying a equal b python sees different memory addresses tries load whole infinite data structure memory indepth comparison,it possible create infinite nested list python that clear although popular definitely useful known fact true my question happening b b b b b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true which way deeper i trying understand i feel much like brain going explode i see contains b contains now questions one do really two lists one how thing like gets stored memory what could purpose enable programers implement something strange like please treat question superserious and forget programming fun sometimes,3 refers b b refers this circular reference as glglgl mentioned try operator tries comparison values try might make things clear ida idb ida idb,it possible create infinite nested list python that clear although popular definitely useful known fact true my question happening b b b b b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true which way deeper i trying understand i feel much like brain going explode i see contains b contains now questions one do really two lists one how thing like gets stored memory what could purpose enable programers implement something strange like please treat question superserious and forget programming fun sometimes,3 pyinstaller unpacks data temporary folder stores directory path meipass environment variable to get meipass dir packedmode use local directory unpacked development mode i use def resourcepathrelative return ospathjoin osenvironget meipass ospathabspath relative development resourcepathappiconico homeshishsrcmyappappiconico deployment resourcepathappiconico tmpmeiappiconico,i trying build onefile exe pyinstaller include image icon i cannot life get work onefile if i onedir works works well when i use onefile find referenced additional files running compiled exe it finds dlls everything else fine two images i looked tempdir generated running exe tempmei example files indeed when i drop exe tempdirectory finds very perplexing this i added spec file adatas imagesiconico dworkspaceappsrcimagesiconico data imagesloaderanigif dworkspaceappsrcimagesloaderanigif data i add i tried putting subfolders well make difference edit marked newer answer correct due pyinstaller update,3 use httpsbitbucketorgkmikedjangoexcelresponse,on django site i want generate excel file based data database i thinking using xlwt method save data file how get file httpresponse object or maybe know better library i also found snippet i need all i want way get stream xlwt object response object without writing temporary file,1 looks like fabric issue you use openssh key ppk,thank taking time look post i django site running i trying run command remote ubuntu host local windows computer via fab i set envkeyfilename every time i run command i prompted user password does anyone suggestions fab snippet envkeyfilename pathtokeyppk envnokeys true envname testing envuser ubuntu envprojectname project envprojectroot homeusersvenvsnamesprojectnames env envhoststring myip envbranch master envvenv source homeusersvenvsnamesbinactivate ampamp env console fab testing installrequirements myip run source homeubuntuvenvstestingbinactivate ampamp pip install r requirementstxt password ubuntumyip,2 welcome stack overflow future one question provide separate post feel free link together might help provide context table inheritance postgres different thing solves different set problems class inheritance python sqlalchemy makes attempt combine when use table inheritance postgres trickery schema level elaborate constraints enforced might easy express ways once designed schema applications normally aware inheritance if insert row magically appears parent table much like view this useful instance making kinds bulk operations efficient drop table month january this fundamentally different idea inheritance seen oop python otherwise relational persistence otherwise in case application aware two types related subtype permissible substitute supertype a holding address contact address therefore contact holding which mostly orthogonal tools need depends application you might need neither might need sqlalchemy mechanisms working object inheritance flexible robust use favor home built solution compatible particular needs true almost applications the declarative extension convenience it allows describe mapped table python class mapping two one thing instead three it makes code dry it however convenience layered top classic sqlalchemy necessary measure if find need table inheritance visible sqlalchemy mapped classes different using features tables inheritance still normal relations like tables views mapped without knowledge inheritance python code,pretty recent newborn python sqlalchemy postgresql trying understand inheritance hard as i taking another programmer code i need understand necessary inheritance concept work my questions is possible rely sqlalchemy inheritance in words sqlalchemy apply inheritance postgresql database tables created without specifying inherits is declarativebase technology sqlalchemy necessary use inheritance proper way if rewrite everything please discourage assuming use table instance empty entity classes mapper could give simple example go process properly link easily understandable tutorial i find easy enough yet the real world working real estate objects so basically one table immobjectid createtime one table objectattributeid immoobjectid oatype several attribute tables oaattributenameoaid attributevalue thanks help advance vincent,2 customising module path order import libraries eg i nonstandard libraries bundled lib folder source code tree add pathslib pyinstaller command line syspathappendlib middle code work sure managed compile find took track,i trying build python exe windows able create fine however i run application i notice cannot perform functions libraries imported pysnmp getting imported specific when i look output build process i notice pysnmp listed even though several modules program import anyone know could causing issue thanks here code generates installer files main program modules py pyinstaller cpythonpyinstaller cygpyinstaller cygdrivecpythonpyinstaller run python apppy makespec files echo pyinstaller makespec python pyinstallermakespecpy onefile windowed iconiconsiconico nameapplication apppy,1 pyinstaller allow bundle resources exe without trickyness turning data files py files collect object seems correct tricky step accessing files runtime pyinstaller unpack temporary directory tell meipass variable to get file paths development packed mode i use def resourcepathrelative return ospathjoin osenvironget meipass ospathabspath relative development resourcepathguiglade homeshishsrcmyappguiglade deployment resourcepathguiglade tmpmeiguiglade,i wrote gtk application python all graphical user interface glade file images used i wish compile application executable file for i using pyinstaller compiler upx packer i done manual says python configurepy python makespecpy onefile windowed upx pathtoyourscriptpy python buildpy pathtoyourscriptspec pyinstaller works perfectly create one exe file but make application work correctly copy glade image files exe folder is way compile files executable i edited spec file various ways achieve want spec file copies file directory compile executable file mode python analysisospathjoinhomepath supportmountzlibpy ospathjoinhomepath supportuseunicodepy rconnectionmainpy pathex cdocuments settingslixasdesktoppyinstallerrc pyz pyzapure exe exe pyz ascripts abinaries azipfiles adatas nameospathjoin dist networkcheckerexe debugfalse stripfalse upxtrue consolefalse icon rconnectionikonaico coll collect exe guiglade rconnectionguiglade data questionpng rconnectionquestionpng data abinaries stripfalse upxtrue name distfinal i wish one executable file everything included,3 better use sockbindmcastgrp mcastport instead sockbind mcastport want listen multiple mcast groups port get messages listeners,how send receive udp multicast python is standard library,3 yes there xlrd allow read spreadsheet httppypipythonorgpypixlrd csv allow write csv files httpdocspythonorglibrarycsvhtml this happened often i uploaded spreadsheet reader library sourceforge httpsourceforgenetprojectsstingrayreader,is way convert worksheets excel file number csv files,2 i tried thing days ago i finished i found python terminal emulator libs i choose pyte clean api easy use a list libs job available end pyte readme,i trying build ssh client web browser similar ajaxterm i built python backend uses paramiko sshclientinvokeshellterm vt web server communicates frontend html ajax the system works displays output i send commands ssh channel output includes vt escape sequences if i understand correctly anything i get ssh channel interpreted commands x terminal window which means escape sequences may change color clear screen remove lines change way lines behave i found good list which means i clear i checked ajaxterm source figure terminal class used i could use purposes the question would easiest way interpret output stream properly display terminal screen browser in words library parses output keeps screen contents if i misunderstood inner workings terminals please let know i much experience past,1 loggercritical failed create file filename e has left right this appears syntax error since statement complete python continues parsing the error message shows following line read httpdocspythonorglibraryrehtmlregularexpressionsyntax then update question specific aspects regular expression confuse regular expressions potentially deep topic,i fairly new python fully understand items i given base programme i need alter bits i far import sys os filename cmainintxt resultfile cmainouttxt try file open filename w except exception e loggercritical failed create file filename e name value brgiteritems stringfind name ctrl name name type filewrite sn name value fileclose run fortran programme resultcode ossystem scmaindebugmainexe sresult options optionscriptpath filename filename read results try file open resultfile r except exception e loggercritical failed create file resultfile e regexp recompile pnamesspvalue row filexreadlines row rowstrip rn regexpmatch row name mgroup name value mgroup value brg name value i completely lost currently work finding syntax error name value bearingiteritems i sure whether mistakes due indentation i also quite understand last part i output text file final part reading i however understand particular line regexp recompile pnamesspvalue with re i understand exactly means matching p matching also regexp represent thank time,2 there way put constraint mm field models level ie limitchoicesto however form class myformformsmodelform class meta model modelscategory def initself args kwargs supermyform selfinitargs kwargs instance kwargs mycategory kwargs instance selffields winner queryset mycategorycategoryall well notice mycategorycategoryall probably want class foomodelsmodel name modelscharfieldmaxlength more fields category modelsforeignkey category relatedname participants,i foos organized categories for category i want able select winner foo hence i models look like class categorymodelsmodel name modelscharfieldmaxlength more fields winner modelsmanytomanyfield foo relatedname winner class foomodelsmodel name modelscharfieldmaxlength more fields category modelsforeignkey category relatedname category the reason winner manytomanyfield single foo may belong several categories single category may one winner due exaequo i want impose natural constraint foo win category belongs category the reasonable way seems use limitchoicesto parameter seems possible limit choices based current instance model i may able impose constraint given form i would like avoid two reasons constraint naturally lives model level it particular relation always hold two related models choice winner made admin i would like avoid customize admin forms is way impose constraint django,2 i know prefab solutions but pypy python implementation written rpython sandboxing feature enables run untrusted code but obvious dsl designed domain might easier solution,i developing web based application written php basically ui top database to give users flexible tool i want embed scripting language complex things like fire sql queries loops store data variables in business domain python widely used scripting i also thinking making simple domain specific language the script wrap existing php classes i seeking advise approach development task update i try scripting database using plpgsql postgresql this i use php classes way lua approach appealing seems i want besides python,1 the jinja templating language different python language in jinja operation values often done filters something operation you find list filters jinja documentation for example round round this display web page a abs filter exist way please note filters used alter values display used calculations calculations done template anyway,i guess generally i curious operations allowable jinja brackets eg i trying perform operation embedded data like roundmileage chevy mileage ford this throws error traceback undefinederror round undefined similarly i try use abs bracketed jinja block i get undefined erroreven though standard lib functions is way perform operation templaterendering rather passing data,3 i experience adbapi cpreconnect parameter mentioned docs looks promising thus pool initialization look something like selfpool adbapiconnectionpoolmysqldb selfparms host selfparms username selfparms password selfparms database cpreconnecttrue,in twisted i perpetual event loop always lookig new query run it polls sqs queue times time queres long enough time error i get new query arrives mysqldb mysqlexceptionsoperationalerror mysql server gone away connection selfpool adbapiconnectionpoolmysqldb selfparms host selfparms username selfparms password selfparms database here logic i use try solve problem try selfpoolrunqueryquery except selfpool adbapiconnectionpoolmysqldb selfparms host selfparms username selfparms password selfparms database selfpoolrunqueryquery print reconnecting problem seem work well soif get error try reconnection execute query what best practice solve problem thanks,1 check see user php server running if i network drive expect mapped user use unc path instead things try different path know cworkspacesparserssrcmain works try,i python program parses files takes path argument parses files given path sub directories using oswalkpath i want call php web app user specify path passed argument parser passing path ok internal network i call parser fine pass arguments ok using popen path python program receives always invalid i php script output command sending browser if i copy paste command command window parser works fine i know path php script passes invalid result ospathexistspath python script this code call python program path request location echo path given path command python cworkspacesparserssrcmainmainpy intvalmode path echo pcommandp parser popencommand r parser echo pran programp feofparser read fgetsparser read echo preached end filep else echo preadp the command echoed browser like python cworkspacesparserssrcmainmainpy idirdirdir where another argument script request location defined input text box form calling page this windows system i assuming something backslashes path basically i unsure backslashes handled i would like understand strings containing backslashes sent php page sent using popen i think result printed browser raw command string i sure many backslashes really command issued popen if anyone ideas i really appreciate edit so python program path used follows nfiles print parsing files directory tree pathbr start timetime ospathexistspath print ppath not realp else print ppath is realp root dirs files oswalkpath f files file ospathjoinrootf print file nfiles code run parser print nfiles files parsedbr this echoed back browser read variable output parsing files directory tree idirdirdir path not real files parsed this identical output command run command line command copied browser pasted cmd window except run way path is real files parsed command window html markup shows the web server parsers hosted local machine,1 you could use pubsub send data editorwindow display do sending ondroptext method sends actually drop end drag here simple tutorial pubsub get going httpwwwblogpythonlibraryorgwxpythonandpubsubasimpletutorial,i one window editwindow object class inherit wxframe contain grid object selfgrid in class write method def onsubindexgridcellleftclick self event dragsource mydropsource selfgrid dragsourcesetdata data dragsourcedodragdrop eventskip bind init editwindow selfgridbind wxgridevtgridcellleftclick selfonsubindexgridcellleftclick another window variablewindow got another grid variablesgrid determine following class class variabledroptargetwxtextdroptarget def initself parent wxtextdroptargetinitself selfparentwindow parent def ondroptextself x data x selfparentwindowvariablesgridcalcunscrolledpositionx in another window set drop target selfvariablesgridsetdroptargetvariabledroptargetself how hook information object variablesgrid moment drop cursor grid situated editorwindow i want take information data variablesgrid editwindow receive information sorry bad english,1 subthing gets parent definition inheritance if want behavior subthing cannot inherit object a possible solution introduce yet another base class class attributeobject declaredattr actual syntax sqlalchemy mixins def acls return columninteger class basethingbase pass class thingbasething attribute b columninteger class subthingbasething c columninteger then subthing column c thing b,i following setup class attributeobject columninteger class thingbase attribute b columninteger class subthingthing c columninteger however thing subthing attribute mixin meaning columns specified attribute thing b subthing c i want mixin columns present thing subthing thing b subthing c is possible i resort making columns methods manually instead using mixin every thing,2 if need rest image define function crop image coordinates want display cropped image note x visual x horizontal axis vertical axis image respectively meaning inverted compared real x row column numpy array import scipy sp import numpy np import matplotlibpyplot plt def cropimage x x return cropped image x x coordinates x ximageshape yimageshape mask npzerosimageshape maskyy xx mask return imagemreshapeyy xx image splena imagecropped cropimage fig pltfigure ax figaddsubplot ax figaddsubplot aximshowimage aximshowimagecropped pltshow,i several images represented d arrays i viewing imshow i need zoom exact spot every image i know i manually zoom tedious precise enough is way programmatically specify specific section image show instead entire thing,1 they passed old way you access via selfargs selfkwargs positional keyword arguments respectively in case selfkwargs id would trick edit overridden get preserved signature if overriding method always def getself request args kwargs,i following class based view class myclassview def getself lots code return response my urlconf looks like r callmyclassview myclassviewasview i want pass parameters urlconf old functional way r callmyclassviewpidw myclassviewasview how pass parameters urlconf receive parameter class view,3 from pyfinalize docs some extensions may work properly initialization routine called happen application calls pyinitialize pyfinalize apparently numpy one see also message numpydiscussion calling pyinitialize cleaning exit way go and faster,on second call following code app segfault i guess i missing something pyinitialize pname pystringfromstringcompmacbeth pmodule pyimportimportpname pydecrefpname ifpmodule null pyerrprint pyfinalize return pfunc pyobjectgetattrstringpmodule compute pfunc new reference pfunc pycallablecheckpfunc pyerrprint pyfinalize return pyfinalize the compmacbethpy importing numpy if i remove numpy import everything fine is numpy bug i missing something imports,3 the problem form name id loginform you use predicate brselectformpredicatelambda f fattrsget id none loginform se fattrs key id id value equal loginform alternatively pass number form page know first one second one etc for example line selects first form brselectformnr,i want select form mechanize this code br mechanizebrowser selfbropenurl brselectformnameloginform the form code form idloginform onsubmitreturn indexloginsubmit methodpost actionindexphpactionloginampserverlist but i getting error mechanizemechanizeformnotfounderror form matching name loginform,3 wouldn work import json f open pathtofile r arr headers header freadlinesplit headersappendheader line freadlines lineitems iitem enumeratelinesplit lineitemsheadersi item arrappendlineitems fclose jsontext jsondumpsarr print jsontext,i need convert csv file hierarchical json object preferably using python i thought script i correct job converting json javascript library i feeding json data djs work the csv file looks like subjectbranchbookchapterencode idlevel level level level mattrick trigonometry second editionright triangles introduction trigonometrymattriright triangles introduction trigonometry mattrick trigonometry second editionright triangles introduction trigonometrymattrithe pythagorean theorem mattrick trigonometry second editionright triangles introduction trigonometrymattrithe pythagorean theorem mattrick trigonometry second editionright triangles introduction trigonometrymattripythagorean triples mattrick trigonometry second editionright triangles introduction trigonometrymattriconverse pythagorean theorem mattrick trigonometry second editionright triangles introduction trigonometrymattrithe distance formula mattrick trigonometry second editionright triangles introduction trigonometrymattrispecial right triangles right i following code recursively builds hierarchical array import csv import json import random randomseed open csv file f open pathtofile ru c csvdictreaderf lists keeping track subjects branches i already iterated subjectlist branchlist levlist levlist levlist levlist iterate file row c subject row subject branch row branch lenrow level lev row level else lev none lenrow level lev row level else lev none lenrow level lev row level else lev none else row subject subject add branches subject subjectlistappend name subject type subject children branchlist set current subject subject row subject row branch branch add concepts branch branchlistappend name branch type branch children levlist empty levlist levlist set new branch branch row branch lenrow level row level lev print lev add level concepts level levlistappend name lev type concept level children levlist print lev empty levlist levlist levlistappendrow level lev row level lenrow level row level lev print lev print levlist add level concepts level lev none levlistappend name lev type concept level children levlist empty levlist levlist levlistappendrow level lev row level lenrow level row level lev print lev add level concepts level levlistappend name lev type concept level empty level concepts levlist add new level lev none levlistappend name lev type concept level size randomrandint lev row level row level none row level lev levlistappend name lev type concept level lev row level fclose branchlistappend name branch type branch children levlist subjectlistappend name subject type subject children branchlist subjectdict name subject type subject children branchlist jsonlist jsondumpssubjectlist jsonlist jsondumpssubjectdict f open usersthaymoresitesddatatrigmapjson wb fwritejsonlist fclose what gets right something like type subject name mat children type branch name tri children children children size type concept name the pythagorean theorem level size type concept name pythagorean triples level size type concept name converse pythagorean theorem level type concept name the pythagorean theorem level children size type concept name the distance formula level size type concept name special right triangle isosceles right triangle level size type concept name special right triangle triangle level type concept name special right triangles level children size type concept name using special right triangle ratios level size type concept name the sine cosine tangent functions level type concept name basic trigonometric functions level children size type concept name secant cosecant cotangent functions level size type concept name solving right triangles level size type concept name inverse trigonometric functions level size type concept name finding area triangle level size type concept name angles elevation depression level size type concept name right triangles bearings level type concept name solving right triangles level children size type concept name other applications right triangles level size type concept name angles rotation standard position level type concept name measuring rotation level children size type concept name coterminal angles level size type concept name trigonometric functions angles standard position level type concept name applying trig functions angles rotation level children size type concept name the unit circle level size type concept name reference angles angles unit circle level size type concept name trigonometric functions negative angles level size type concept name trigonometric functions angles greater degrees level type concept name trigonometric functions any angle level type concept name right triangles introduction trigonometry level children children size type concept name using calculator find values level size type concept name reciprocal identities level size type concept name domain range signs trig functions level size type concept name quotient identities level size type concept name cofunction identities reflection level type concept name relating trigonometric functions level children size type concept name pythagorean identities level size type concept name understanding radian measure level size type concept name critial angles radians level size type concept name converting any degree radians level size type concept name the six trig functions radians level type concept name radian measure level children size type concept name check mode level size type concept name rotations level size type concept name length arc level size type concept name area sector level size type concept name length chord level type concept name applications radian measure level children size type concept name angular velocity level size type concept name the sine graph level size type concept name the cosine graph level size type concept name the tangent graph level size type concept name the three reciprocal functions level size type concept name cotangent level size type concept name cosecant level type concept name circular functions real numbers level children size type concept name secant level size type concept name vertical translations level type concept name translating sine cosine functions level children size type concept name horizontal translations phase shifts level size type concept name amplitude level size type concept name period frequency level type concept name amplitude period frequency level children size type concept name combining amplitude period level size type concept name the generalized equations level size type concept name drawing sketchesidentifying transformations equation level type concept name general sinusoidal graphs level type concept name graphing trigonometric functions nd edition level children children size type concept name writing equation sketch level size type concept name tangent cotangent level size type concept name secant cosecant level type concept name graphing tangent cotangent secant cosecant level children size type concept name graphing calculator note level size type concept name quotient identity level size type concept name reciprocal identities level size type concept name pythagorean identity level size type concept name even odd identities level type concept name fundamental identities level children size type concept name cofunction identities level size type concept name working trigonometric identities level type concept name proving identities level children size type concept name technology note level size type concept name simplifying trigonometric expressions level size type concept name solving trigonometric equations level size type concept name solving trigonometric equations using factoring level type concept name solving trigonometric equations level children size type concept name solving trigonometric equations using quadratic formula level size type concept name sum difference formulas cosine level size type concept name using sum difference identities cosine level size type concept name sum difference identities sine level size type concept name sum difference identities tangent level size type concept name using sum difference identities verify other identities level type concept name sum difference identities level children size type concept name solving equations sum difference formulas level size type concept name deriving double angle identities level size type concept name applying double angle identities level type concept name double angle identities level children size type concept name solving equations double angle identities level size type concept name deriving half angle formulas level type concept name halfangle identities level type concept name trigonometric identities equations nd edition level children children size type concept name solving trigonometric equations using half angle formulas level size type concept name sum product formulas sine cosine level size type concept name product sum formulas sine cosine level size type concept name solving equations product sum formulas level size type concept name tripleangle formulas beyond level size type concept name linear combinations level type concept name products sums linear combinations applications level children size type concept name applications amp technology level size type concept name defining inverse trigonometric ratios level size type concept name exact values inverse sine cosine tangent level type concept name basic inverse trigonometric functions level children size type concept name finding inverses algebraically level size type concept name finding inverse mapping level type concept name graphing inverse trigonometric functions level children size type concept name finding inverse trigonometric functions level size type concept name composing trig functions inverses level size type concept name composing trigonometric functions level size type concept name inverse reciprocal functions level size type concept name composing inverse reciprocal trig functions level type concept name inverse trigonometric properties level type concept name inverse trigonometric functions nd edition level children children type concept name applications amp models level children size type concept name trigonometry terms algebra level size type concept name derive law cosines level size type concept name case finding side oblique triangle level size type concept name case finding angle triangle level type concept name the law cosines level children size type concept name identify accurate drawings general triangles level size type concept name find area using three sides heronus formula level size type concept name heronus formula level type concept name area triangle level children size type concept name finding part triangle given area level size type concept name deriving law sines level size type concept name aas angleangleside level size type concept name asa anglesideangle level type concept name the law sines level children size type concept name solving triangles level size type concept name possible triangles ssa level size type concept name using law sines level type concept name the ambiguous case level children size type concept name using law cosines level size type concept name summary triangle techniques level size type concept name using law cosines level type concept name general solutions triangles level children size type concept name using law sines level size type concept name directed line segments equal vectors absolute value level size type concept name vector addition level size type concept name vector subtraction level type concept name vectors level type concept name triangles vectors level i think might technically fit json specs library i trying feed json data djs seem anything is order elements outofwhack ie children element coming name element is something basic i the file whose structure i trying match located,3 why create class function def foofactoryindex name food index class fooobject refobj refobjname fooname name return foo,i want dynamically create classes runtime python for example i want replicate code class refobjobject def initself parentclassname print created refobj ties parentclassname class fooobject refobj refobjfoo class fooobject refobj refobjfoo created refobj ties foo created refobj ties foo i want foo foo foo classes created dynamically ie execution instead firstpass compile one way achieve type like class refobjobject def initself parentclassname print created refobj ties parentclassname def makefooclassindex name foos index return typename object dictrefobj refobjname foo makefooclass created refobj ties foo foo makefooclass created refobj ties foo typefoo typefoo class foo class foo i also achieve exec like class refobjobject def initself parentclassname print created refobj ties parentclassname def makefooobjectindex classtemplate class fooindexdobject refobj refobjfooindexd dictindex index global refobj namespace dictrefobj refobj exec classtemplate namespace return namespacefood index foo makefooobject created refobj ties foo foo makefooobject created refobj ties foo typefoo typefoo class foo class foo the use exec sit well i expect lot people read question exec exactly python collectionsnamedtuple class implemented see line also relevant defense use exec creator class raymond hettinger in defense stated it key feature named tuples exactly equivalent handwritten class one might take imply use type good using exec is difference why use exec vs type i expect answer may ways simply namedtuple implementation lot namedtuple variables peppered dynamically generate closures methods made code get unwieldy i want know something regarding discomfort exec i recognize way whatsoever untrusted parties inject nefarious code fine ensuring makes nervous,2 there disadvantage using type exec i think raymond defense bit defensive you choose technique find readable understandable both ways create confusing code you try really hard avoid code creates classes first place would best,i want dynamically create classes runtime python for example i want replicate code class refobjobject def initself parentclassname print created refobj ties parentclassname class fooobject refobj refobjfoo class fooobject refobj refobjfoo created refobj ties foo created refobj ties foo i want foo foo foo classes created dynamically ie execution instead firstpass compile one way achieve type like class refobjobject def initself parentclassname print created refobj ties parentclassname def makefooclassindex name foos index return typename object dictrefobj refobjname foo makefooclass created refobj ties foo foo makefooclass created refobj ties foo typefoo typefoo class foo class foo i also achieve exec like class refobjobject def initself parentclassname print created refobj ties parentclassname def makefooobjectindex classtemplate class fooindexdobject refobj refobjfooindexd dictindex index global refobj namespace dictrefobj refobj exec classtemplate namespace return namespacefood index foo makefooobject created refobj ties foo foo makefooobject created refobj ties foo typefoo typefoo class foo class foo the use exec sit well i expect lot people read question exec exactly python collectionsnamedtuple class implemented see line also relevant defense use exec creator class raymond hettinger in defense stated it key feature named tuples exactly equivalent handwritten class one might take imply use type good using exec is difference why use exec vs type i expect answer may ways simply namedtuple implementation lot namedtuple variables peppered dynamically generate closures methods made code get unwieldy i want know something regarding discomfort exec i recognize way whatsoever untrusted parties inject nefarious code fine ensuring makes nervous,1 list specifies range within list case defines complete range list ie whole list changes listrange hand kind wipes original contents list sets new contents but try following prints you see changed first two elements assignment this means using notation change several elements list,what difference list range list range python edit i mentioned assignment list variable already assigned list list list range list list range,1 list range work uninitialized variable modifying the specifies whole listtouple,what difference list range list range python edit i mentioned assignment list variable already assigned list list list range list list range,1 the first one redefines builtin name list point list the second fails typeerror type object support item assignment,what difference list range list range python edit i mentioned assignment list variable already assigned list list list range list list range,3 list work already object named list allows slice assignment also name variables list builtin named list list type,what difference list range list range python edit i mentioned assignment list variable already assigned list list list range list list range,1 i would recommend type exec in fact class statement syntactic sugar call type the class body executed within namespace passed metaclass defaults type custom metaclass specified this approach less errorprone since need parse code runtime might even bit faster,i want dynamically create classes runtime python for example i want replicate code class refobjobject def initself parentclassname print created refobj ties parentclassname class fooobject refobj refobjfoo class fooobject refobj refobjfoo created refobj ties foo created refobj ties foo i want foo foo foo classes created dynamically ie execution instead firstpass compile one way achieve type like class refobjobject def initself parentclassname print created refobj ties parentclassname def makefooclassindex name foos index return typename object dictrefobj refobjname foo makefooclass created refobj ties foo foo makefooclass created refobj ties foo typefoo typefoo class foo class foo i also achieve exec like class refobjobject def initself parentclassname print created refobj ties parentclassname def makefooobjectindex classtemplate class fooindexdobject refobj refobjfooindexd dictindex index global refobj namespace dictrefobj refobj exec classtemplate namespace return namespacefood index foo makefooobject created refobj ties foo foo makefooobject created refobj ties foo typefoo typefoo class foo class foo the use exec sit well i expect lot people read question exec exactly python collectionsnamedtuple class implemented see line also relevant defense use exec creator class raymond hettinger in defense stated it key feature named tuples exactly equivalent handwritten class one might take imply use type good using exec is difference why use exec vs type i expect answer may ways simply namedtuple implementation lot namedtuple variables peppered dynamically generate closures methods made code get unwieldy i want know something regarding discomfort exec i recognize way whatsoever untrusted parties inject nefarious code fine ensuring makes nervous,3 import code codeinteractlocallocals but using python debugger probably want import pdb pdbsettrace,i often case i writing script i part script i want play around variables interactively getting part requires running large part script i already written in case trivial run program inside shell i would recreate conditions function somehow what i want call function like runshell run python shell point program keeping variables scope allowing poke around how would i go,3 you use python debugger pdb settrace function for example invoke script like def whatever x import pdb pdbsettrace name main whatever you get scope point settrace called python testtestpy return homejterracetesttestpywhatevernone pdbsettrace pdb x pdb,i often case i writing script i part script i want play around variables interactively getting part requires running large part script i already written in case trivial run program inside shell i would recreate conditions function somehow what i want call function like runshell run python shell point program keeping variables scope allowing poke around how would i go,3 when lst anything you pointing name lst object it change old object lst used point way though nothing else pointed object reference count drop zero get deleted when lst whatever you iterating whatever creating intermediate tuple assigning item tuple index already existing lst object that means multiple names point object see change reflected reference names use append extend inplace operations an example difference lst range idlst lst idlst different pointed lst new object lst range idlst iterated list returned range lst xrange lst xrange list xrange object idlst different lst idlst different lst xrange gets read temporarily tuple idlst iterated xrange lst still list when comes speed slice assignment slower see python slice assignment memory usage information memory usage,what difference list range list range python edit i mentioned assignment list variable already assigned list list list range list list range,3 as best way identify unique individual key words tfidf total measure so somehow integrate search engine make simple custom inverted index dynamic holds term frequencies document frequencies calculate tfidf efficiently onthefly as ngrams create custom parser using window approach window length n identifies say frequent keep every ngram key dictionary value either frequency score based tfidf individual terms,i text stored python string what i want to identify key words text identify ngrams text ideally bi tri grams keep mind the text might small eg tweet sized the text might middle eg news article sized the text might large eg book chapter sized what i have i already using nltk break corpus tokens remove stopwords split across nonword character tokenizer nltktokenizeregexptokenizer w gapstrue tokenize tokens tokenizertokenizetext remove stopwords tokens w w tokens w nltkcorpusstopwordswords english i aware bigramcollocationfinder trigramcollectionfinder exaclty i looking two cases the question i need advice ngrams higher order improving kinds results come bcf tcf advice best way identify unique individual key words many thanks,1 also useful make deep copy list def xl fl gl lappend print l l print g g print f f l range print l xl l g f print l modification l get reflected g point list fact g l names python fbecause copy l but case it make difference though i eligible comment memory usage methods edit h range idh hrange idh hrange idh list range updates list list range creates new list agf thanks pointing error,what difference list range list range python edit i mentioned assignment list variable already assigned list list list range list list range,1 it necessary cast csvreader list already iterable you something like following benchmark open testcsv r inp csvincsvreaderinp row csvin benchmarkappendrow floatrow row,i new python apologies seems extremely simple i csv file columns dozen rows i import contests list list lists contents come strings what i want loop list variable number rows convert index string float i run following code print list everything still string import csv def main benchmark listcsvreaderopen testcsv r rangelenbenchmark benchmarki floatbenchmarki any help would much appreciated thanks,1 nslogin username xsitypensstringremovedusername password xsitypensstringremovedpassword ip xsitypensstringip nslogin nsstring correct one nsstring,i attempting use suds connect knowledgetree web service local network i create client retrieve service information calling login method listed produces sudswebfault server raised fault method login defined service note i use importdoctor resolve namespace issue creating client i know current problem could related is problem way i setting client sending command problem serverside i alter code server generates wsdl necessary i know needs corrected point setting client import logging sudsclient import client sudsxsddoctor import importdoctor import import getpass loggingbasicconfiglevellogginginfo logginggetlogger sudsclient setlevelloggingdebug url httpknowledgetreektwebservicewebservicephpwsdl imp import httpschemasxmlsoaporgsoapencoding impfilteradd urnknowledgetree importdoctorimp client clienturl doctord printclient response clientservicelogingetpassgetuser getpassgetpass results printclient suds httpsfedorahostedorgsuds version ga build r service knowledgetreeservice tnsurnknowledgetree prefixes ns httpschemasxmlsoaporgsoapencoding ns urnknowledgetree ports knowledgetreeport methods addbasedocumentxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring base addbasedocumentwithmetadataxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring base ktmetadatafieldsets metadata ktsysdata sysdata adddocumentxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring tempfilename adddocumentwithmetadataxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring tempfilename ktmetadatafieldsets metadata ktsysdata sysdata addfolderxsstring sessionid xsint folderid xsstring foldername addsmalldocumentxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring base anonymousloginxsstring ip changedocumentownerxsstring sessionid xsint documentid xsstring username xsstring reason changedocumenttypexsstring sessionid xsint documentid xsstring documenttype checkinbasedocumentxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring base xsboolean majorupdate checkinbasedocumentwithmetadataxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring base xsboolean majorupdate ktmetadatafieldsets metadata ktsysdata sysdata checkindocumentxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring tempfilename xsboolean majorupdate checkindocumentwithmetadataxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring tempfilename xsboolean majorupdate ktmetadatafieldsets metadata ktsysdata sysdata checkinsmalldocumentxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring base xsboolean majorupdate checkoutbasedocumentxsstring sessionid xsint documentid xsstring reason xsboolean download checkoutdocumentxsstring sessionid xsint documentid xsstring reason xsboolean download checkoutsmalldocumentxsstring sessionid xsint documentid xsstring reason xsboolean download copydocumentxsstring sessionid xsint documentid xsint folderid xsstring reason xsstring options copyfolderxsstring sessionid xsint sourceid xsint targetid xsstring reason createfolderxsstring sessionid xsint folderid xsstring foldername deletedocumentxsstring sessionid xsint documentid xsstring reason deletedocumentworkflowxsstring sessionid xsint documentid deletefolderxsstring sessionid xsint folderid xsstring reason downloadbasedocumentxsstring sessionid xsint documentid downloaddocumentxsstring sessionid xsint documentid downloadsmalldocumentxsstring sessionid xsint documentid getclientpoliciesxsstring sessionid xsstring client getdocumentdetailxsstring sessionid xsint documentid xsstring detail getdocumentdetailbyfilenamexsstring sessionid xsint folderid xsstring filename xsstring detail getdocumentdetailbynamexsstring sessionid xsint folderid xsstring documentname xsstring xsstring detail getdocumentdetailbytitlexsstring sessionid xsint folderid xsstring title xsstring detail getdocumentlinktypesxsstring sessionid getdocumentlinksxsstring sessionid xsint documentid getdocumentmetadataxsstring sessionid xsint documentid getdocumenttransactionhistoryxsstring sessionid xsint documentid getdocumenttypemetadataxsstring sessionid xsstring documenttype getdocumenttypesxsstring sessionid getdocumentversionhistoryxsstring sessionid xsint documentid getdocumentworkflowstatexsstring sessionid xsint documentid getdocumentworkflowtransitionsxsstring sessionid xsint documentid getdocumentsbyoemnoxsstring sessionid xsstring oemno xsstring detail getfoldercontentsxsstring sessionid xsint folderid xsint depth xsstring getfolderdetailxsstring sessionid xsint folderid getfolderdetailbynamexsstring sessionid xsstring foldername getworkflowsxsstring sessionid linkdocumentsxsstring sessionid xsint parentdocumentid xsint childdocumentid xsstring type loginxsstring username xsstring password xsstring ip logoutxsstring sessionid movedocumentxsstring sessionid xsint documentid xsint folderid xsstring reason xsstring options movefolderxsstring sessionid xsint sourceid xsint targetid xsstring reason performdocumentworkflowtransitionxsstring sessionid xsint documentid xsstring transition xsstring reason renamedocumentfilenamexsstring sessionid xsint documentid xsstring newfilename renamedocumenttitlexsstring sessionid xsint documentid xsstring newtitle renamefolderxsstring sessionid xsint folderid xsstring newname searchxsstring sessionid xsstring search xsstring options startdocumentworkflowxsstring sessionid xsint documentid xsstring workflow stopdocumentworkflowxsstring sessionid xsint documentid undodocumentcheckoutxsstring sessionid xsint documentid xsstring reason unlinkdocumentsxsstring sessionid xsint parentdocumentid xsint childdocumentid updatedocumentmetadataxsstring sessionid xsint documentid ktmetadatafieldsets metadata ktsysdata sysdata types nsarray nsentities nsentity nsid nsidref nsidrefs nsncname nsnmtoken nsnmtokens nsnotation nsname nsqname nsstruct nsanyuri nsarraycoordinate nsbase nsbasebinary nsboolean nsbyte nsdate nsdatetime nsdecimal nsdouble nsduration nsfloat nsgday nsgmonth nsgmonthday nsgyear nsgyearmonth nshexbinary nsint nsinteger ktclientpoliciesarray ktclientpoliciesresponse ktclientpolicy ktdocumentcollection ktdocumentcollectionresponse ktdocumentdetail ktdocumenttransactionhistory ktdocumenttransactionhistoryitem ktdocumenttransactionhistoryresponse ktdocumenttypesarray ktdocumenttypesresponse ktdocumentversionhistory ktdocumentversionhistoryitem ktdocumentversionhistoryresponse ktfoldercollection ktfoldercollectionresponse ktfoldercontents ktfolderdetail ktfolderitem ktfolderitems ktlinkeddocument ktlinkeddocumentresponse ktlinkeddocuments ktmetadatafield ktmetadatafields ktmetadatafieldset ktmetadatafieldsets ktmetadataoptions ktmetadataresponse ktmetadataselection ktmetadataselectionitem ktresponse ktsearchresponse ktsearchresultitem ktsearchresults ktsysdata ktsysdataitem ktworkflowtransitions ktworkflowtransitionsresponse ktworkflowsarray ktworkflowsresponse nslanguage nslong nsnegativeinteger nsnonnegativeinteger nsnonpositiveinteger nsnormalizedstring nspositiveinteger nsshort nsstring nstime nstoken nsunsignedbyte nsunsignedint nsunsignedlong nsunsignedshort debug results clientserviceloginusername password address debugsudsclientsending httpknowledgetreektwebservicewebservicephp message xml version encodingutf soapenvenvelope xmlnssoapenchttpschemasxmlsoaporgsoapencoding xmlnsnshttpschemasxmlsoaporgsoapencoding xmlnsnshttpschemasxmlsoaporgsoapenvelope xmlnsnshttpwwwworgxmlschema xmlnsxsihttpwwwworgxmlschemainstance xmlnssoapenvhttpschemasxmlsoaporgsoapenvelope soapenvencodingstylehttpschemasxmlsoaporgsoapencoding soapenvheader nsbody nslogin username xsitypensstringremovedusername password xsitypensstringremovedpassword ip xsitypensstringip nslogin nsbody soapenvenvelope debugsudsclientheaders soapaction u httpschemasxmlsoaporgsoapenvelopektwebservicelogin contenttype textxml charsetutf errorsudsclientxml version encodingutf soapenvenvelope xmlnssoapenchttpschemasxmlsoaporgsoapencoding xmlnsnshttpschemasxmlsoaporgsoapencoding xmlnsnshttpschemasxmlsoaporgsoapenvelope xmlnsnshttpwwwworgxmlschema xmlnsxsihttpwwwworgxmlschemainstance xmlnssoapenvhttpschemasxmlsoaporgsoapenvelope soapenvencodingstylehttpschemasxmlsoaporgsoapencoding soapenvheader nsbody nslogin username xsitypensstringremovedusername password xsitypensstringremovedpassword ip xsitypensstringip nslogin nsbody soapenvenvelope debugsudsclienthttp failed xml version encodingutf soapenvenvelope xmlnssoapenvhttpschemasxmlsoaporgsoapenvelope xmlnsxsdhttpwwwworgxmlschema xmlnsxsihttpwwwworgxmlschemainstance xmlnssoapenchttpschemasxmlsoaporgsoapencoding soapenvencodingstylehttpschemasxmlsoaporgsoapencoding soapenvbody soapenvfault faultcode xsitypexsdqnamesoapenvserverfaultcode faultstring xsitypexsdstringmethod ampquotloginampquot defined servicefaultstring faultactor xsitypexsdanyurifaultactor detail xsitypesoapencarray soapencarraytypexsdanytype soapencoffset item object xsiniltrueitem item object xsiniltrueitem item object fault xsiniltrueobjectitem item object fault xsiniltrueobjectitem item object fault xsiniltrueobjectitem item object xsiniltrueitemdetailsoapenvfault soapenvbody soapenvenvelope traceback recent call last file pyshell line module response clientservicelogingetpassgetuser getpassgetpass file buildbdistwineggsudsclientpy line call return clientinvokeargs kwargs file buildbdistwineggsudsclientpy line invoke result selfsendsoapenv file buildbdistwineggsudsclientpy line send result selffailedbinding e file buildbdistwineggsudsclientpy line failed r p bindinggetfaultreply file buildbdistwineggsudsbindingsbindingpy line getfault raise webfaultp faultroot webfault server raised fault method login defined service,1 i know function code since least far back srepy file code still comment sre extensions experimental rely t template srecompilesreflagtemplate disable backtracking i would stay away,while using module ipython i noticed undocumented template function in retemplate type function base class type function string form function template xbebe namespace interactive file usrtidewaylibpythonrepy definition retemplatepattern flags docstring compile template pattern returning pattern object also flag retemplate alias ret none mentioned docs either what are obsolete hangovers earlier version python experimental feature may officially added future,1 i reasonable solution problem least debugging purposes i currently solution raise exception back main processes my first thought use decorator pickle functions defined top level module right instead simple wrapping class pool subclass uses applyasync hence apply i leave mapasync exercise reader import traceback multiprocessingpool import pool import multiprocessing shortcut multiprocessing logger def errormsg args return multiprocessinggetloggererrormsg args class logexceptionsobject def initself callable selfcallable callable def callself args kwargs try result selfcallableargs kwargs except exception e here add debugging help if multiprocessing debugging arrange log traceback errortracebackformatexc reraise original exception pool worker clean raise it fine give normal answer return result class loggingpoolpool def applyasyncself func args kwds callbacknone return poolapplyasyncself logexceptionsfunc args kwds callback def go print raise exception print multiprocessinglogtostderr p loggingpoolprocesses papplyasyncgo pclose pjoin this gives errorpoolworker traceback recent call last file mpdebugpy line call result selfcallableargs kwargs file mpdebugpy line go raise exception exception,it seems exception raised multiprocessingpool process stack trace indication failed example multiprocessing import pool def go print raise exception print p pool papplyasyncgo pclose pjoin prints stops silently interestingly raising baseexception instead works is way make behavior exceptions baseexception,3 in cpython retemplate defined def templatepattern flags compile template pattern returning pattern object return compilepattern flagst compile calls compiletyped calls srecompilecompile the place code t aka sreflagtemplate flag checked function elif op repeatingcodes flags amp sreflagtemplate raise error internal unsupported template operator emitopcodesrepeat skip lencode emit emitav emitav compilecode av flags emitopcodessuccess codeskip lencode skip this would effect disabling repetition operators etc in retemplate error internal unsupported template operator the way code structured unconditional raise preceding bunch dead code makes think feature either never fully implemented turned due problems i guess intended semantics may the end result function nothing useful,while using module ipython i noticed undocumented template function in retemplate type function base class type function string form function template xbebe namespace interactive file usrtidewaylibpythonrepy definition retemplatepattern flags docstring compile template pattern returning pattern object also flag retemplate alias ret none mentioned docs either what are obsolete hangovers earlier version python experimental feature may officially added future,3 work like english x returns x x trueish value otherwise returns strings trueish empty worse higher precedence expression x whatever so x empty returns x true execute if x empty evaluate whatever btw don use compare value equality use you want parens optional x whatever whatever concise stranger whatever x,i new member also new python my question follows valid line like x whatever i tested interpreter getting inconsistent results it would seem line yields consistent expected results x whatever or always best explicitly everything laid x whatever whatever this last one always works i trying make code bit concise still following best practices i tried search ask redundant question searching rather difficult thanks advance assistance edit thanks quick replies this works perfectly i need whatever xy but would i condense i need x whatever whatever,3 i think would work whatever x it kind weird though,i new member also new python my question follows valid line like x whatever i tested interpreter getting inconsistent results it would seem line yields consistent expected results x whatever or always best explicitly everything laid x whatever whatever this last one always works i trying make code bit concise still following best practices i tried search ask redundant question searching rather difficult thanks advance assistance edit thanks quick replies this works perfectly i need whatever xy but would i condense i need x whatever whatever,1 python english x whatever means x whatever which x true or whatever x whatever x becomes either x if x true returns x otherwise becomes y then result compared whatever you never never compare strings anyways string compared using means something different sometimes works accident you actual request written whatever xy this checks whether string whatever list xy,i new member also new python my question follows valid line like x whatever i tested interpreter getting inconsistent results it would seem line yields consistent expected results x whatever or always best explicitly everything laid x whatever whatever this last one always works i trying make code bit concise still following best practices i tried search ask redundant question searching rather difficult thanks advance assistance edit thanks quick replies this works perfectly i need whatever xy but would i condense i need x whatever whatever,2 x whatever akin x whatever x whatever x returns first nonfalse value x whatever whatever valid correct aside fact using see you may whatever x case longer list conditions nice use function anyconditionk k list but overkill case exposed since want know whatever contained x update consider actually comparing memory addresses pointed good practice use strings,i new member also new python my question follows valid line like x whatever i tested interpreter getting inconsistent results it would seem line yields consistent expected results x whatever or always best explicitly everything laid x whatever whatever this last one always works i trying make code bit concise still following best practices i tried search ask redundant question searching rather difficult thanks advance assistance edit thanks quick replies this works perfectly i need whatever xy but would i condense i need x whatever whatever,1 it usually odd import name module import whole module in case importing submodule seem bad though people use ospath function calls just pychecker like mean turn warning,my script contains following two lines importstatements import os os import path this seems logical approach script i use ospath often i want access path on side i need additional methods os rarely ok write osaccess example why discouraged pychecker example complains,3 asyncresult msgids attribute the outstanding jobs intersection rcoutstanding completed jobs difference msgset setarmsgids completed msgsetdifferencercoutstanding pending msgsetintersectionrcoutstanding,i use ipython parallelprocessing facility big map operation while waiting map operation finish i like display user many jobs finished many running many remaining how i find information here i i create profile uses local engine start two workers in shell ipython profile create parallel profilelocal ipcluster start n profilelocal here client python script usrbinenv python def meati import numpy np import time import sys seconds nprandomrandint timesleepseconds return seconds import time ipythonparallel import client c clientprofile local dview c ar dviewmapasyncmeat range elapsed true print after running elapsed lencoutstanding arready break timesleep elapsed print arget example output script after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running after running as see i get number currently running jobs number jobs completed remaining how i tell many mapasync jobs finished,2 i lots issues trying use suds connect kt below module i ended using sudsclient import client sudsxsddoctor import importdoctor import sudsplugin import plugin import urllib class sessionproxy all methods except login wants sessionid first argument this proxy adds def initself service session baseurl selfservice service selfsession session selfbaseurl baseurl def openself docid u selfdownloaddocumentdocid return urlliburlopenselfbaseurl umessage def getattrself attr getattrselfservice attr callablea def args return aselfsession args return return class adjustprefixesplugin def sendingself ctx ctxenveloperefitprefixes class attrfixerplugin def initself attrs selfattrs attrs def receivedself ctx ideally parse xml rewrite dom fr selfattrs ctxreply ctxreplyreplaces fr ctxreply ctxreplyreplaces fr def connectbaseurl user password url sktwebservicewebservicephpwsdl baseurl imp import httpschemasxmlsoaporgsoapencoding doctor importdoctorimp client clienturl pluginsdoctor adjustprefixes attrfixerareplace checkedoutby modifiedby srv clientservice r srvloginuserpassword rstatuscode raise runtimeerror failed login sessionproxysrv rmessage baseurl return,i attempting use suds connect knowledgetree web service local network i create client retrieve service information calling login method listed produces sudswebfault server raised fault method login defined service note i use importdoctor resolve namespace issue creating client i know current problem could related is problem way i setting client sending command problem serverside i alter code server generates wsdl necessary i know needs corrected point setting client import logging sudsclient import client sudsxsddoctor import importdoctor import import getpass loggingbasicconfiglevellogginginfo logginggetlogger sudsclient setlevelloggingdebug url httpknowledgetreektwebservicewebservicephpwsdl imp import httpschemasxmlsoaporgsoapencoding impfilteradd urnknowledgetree importdoctorimp client clienturl doctord printclient response clientservicelogingetpassgetuser getpassgetpass results printclient suds httpsfedorahostedorgsuds version ga build r service knowledgetreeservice tnsurnknowledgetree prefixes ns httpschemasxmlsoaporgsoapencoding ns urnknowledgetree ports knowledgetreeport methods addbasedocumentxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring base addbasedocumentwithmetadataxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring base ktmetadatafieldsets metadata ktsysdata sysdata adddocumentxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring tempfilename adddocumentwithmetadataxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring tempfilename ktmetadatafieldsets metadata ktsysdata sysdata addfolderxsstring sessionid xsint folderid xsstring foldername addsmalldocumentxsstring sessionid xsint folderid xsstring title xsstring filename xsstring documentype xsstring base anonymousloginxsstring ip changedocumentownerxsstring sessionid xsint documentid xsstring username xsstring reason changedocumenttypexsstring sessionid xsint documentid xsstring documenttype checkinbasedocumentxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring base xsboolean majorupdate checkinbasedocumentwithmetadataxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring base xsboolean majorupdate ktmetadatafieldsets metadata ktsysdata sysdata checkindocumentxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring tempfilename xsboolean majorupdate checkindocumentwithmetadataxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring tempfilename xsboolean majorupdate ktmetadatafieldsets metadata ktsysdata sysdata checkinsmalldocumentxsstring sessionid xsint documentid xsstring filename xsstring reason xsstring base xsboolean majorupdate checkoutbasedocumentxsstring sessionid xsint documentid xsstring reason xsboolean download checkoutdocumentxsstring sessionid xsint documentid xsstring reason xsboolean download checkoutsmalldocumentxsstring sessionid xsint documentid xsstring reason xsboolean download copydocumentxsstring sessionid xsint documentid xsint folderid xsstring reason xsstring options copyfolderxsstring sessionid xsint sourceid xsint targetid xsstring reason createfolderxsstring sessionid xsint folderid xsstring foldername deletedocumentxsstring sessionid xsint documentid xsstring reason deletedocumentworkflowxsstring sessionid xsint documentid deletefolderxsstring sessionid xsint folderid xsstring reason downloadbasedocumentxsstring sessionid xsint documentid downloaddocumentxsstring sessionid xsint documentid downloadsmalldocumentxsstring sessionid xsint documentid getclientpoliciesxsstring sessionid xsstring client getdocumentdetailxsstring sessionid xsint documentid xsstring detail getdocumentdetailbyfilenamexsstring sessionid xsint folderid xsstring filename xsstring detail getdocumentdetailbynamexsstring sessionid xsint folderid xsstring documentname xsstring xsstring detail getdocumentdetailbytitlexsstring sessionid xsint folderid xsstring title xsstring detail getdocumentlinktypesxsstring sessionid getdocumentlinksxsstring sessionid xsint documentid getdocumentmetadataxsstring sessionid xsint documentid getdocumenttransactionhistoryxsstring sessionid xsint documentid getdocumenttypemetadataxsstring sessionid xsstring documenttype getdocumenttypesxsstring sessionid getdocumentversionhistoryxsstring sessionid xsint documentid getdocumentworkflowstatexsstring sessionid xsint documentid getdocumentworkflowtransitionsxsstring sessionid xsint documentid getdocumentsbyoemnoxsstring sessionid xsstring oemno xsstring detail getfoldercontentsxsstring sessionid xsint folderid xsint depth xsstring getfolderdetailxsstring sessionid xsint folderid getfolderdetailbynamexsstring sessionid xsstring foldername getworkflowsxsstring sessionid linkdocumentsxsstring sessionid xsint parentdocumentid xsint childdocumentid xsstring type loginxsstring username xsstring password xsstring ip logoutxsstring sessionid movedocumentxsstring sessionid xsint documentid xsint folderid xsstring reason xsstring options movefolderxsstring sessionid xsint sourceid xsint targetid xsstring reason performdocumentworkflowtransitionxsstring sessionid xsint documentid xsstring transition xsstring reason renamedocumentfilenamexsstring sessionid xsint documentid xsstring newfilename renamedocumenttitlexsstring sessionid xsint documentid xsstring newtitle renamefolderxsstring sessionid xsint folderid xsstring newname searchxsstring sessionid xsstring search xsstring options startdocumentworkflowxsstring sessionid xsint documentid xsstring workflow stopdocumentworkflowxsstring sessionid xsint documentid undodocumentcheckoutxsstring sessionid xsint documentid xsstring reason unlinkdocumentsxsstring sessionid xsint parentdocumentid xsint childdocumentid updatedocumentmetadataxsstring sessionid xsint documentid ktmetadatafieldsets metadata ktsysdata sysdata types nsarray nsentities nsentity nsid nsidref nsidrefs nsncname nsnmtoken nsnmtokens nsnotation nsname nsqname nsstruct nsanyuri nsarraycoordinate nsbase nsbasebinary nsboolean nsbyte nsdate nsdatetime nsdecimal nsdouble nsduration nsfloat nsgday nsgmonth nsgmonthday nsgyear nsgyearmonth nshexbinary nsint nsinteger ktclientpoliciesarray ktclientpoliciesresponse ktclientpolicy ktdocumentcollection ktdocumentcollectionresponse ktdocumentdetail ktdocumenttransactionhistory ktdocumenttransactionhistoryitem ktdocumenttransactionhistoryresponse ktdocumenttypesarray ktdocumenttypesresponse ktdocumentversionhistory ktdocumentversionhistoryitem ktdocumentversionhistoryresponse ktfoldercollection ktfoldercollectionresponse ktfoldercontents ktfolderdetail ktfolderitem ktfolderitems ktlinkeddocument ktlinkeddocumentresponse ktlinkeddocuments ktmetadatafield ktmetadatafields ktmetadatafieldset ktmetadatafieldsets ktmetadataoptions ktmetadataresponse ktmetadataselection ktmetadataselectionitem ktresponse ktsearchresponse ktsearchresultitem ktsearchresults ktsysdata ktsysdataitem ktworkflowtransitions ktworkflowtransitionsresponse ktworkflowsarray ktworkflowsresponse nslanguage nslong nsnegativeinteger nsnonnegativeinteger nsnonpositiveinteger nsnormalizedstring nspositiveinteger nsshort nsstring nstime nstoken nsunsignedbyte nsunsignedint nsunsignedlong nsunsignedshort debug results clientserviceloginusername password address debugsudsclientsending httpknowledgetreektwebservicewebservicephp message xml version encodingutf soapenvenvelope xmlnssoapenchttpschemasxmlsoaporgsoapencoding xmlnsnshttpschemasxmlsoaporgsoapencoding xmlnsnshttpschemasxmlsoaporgsoapenvelope xmlnsnshttpwwwworgxmlschema xmlnsxsihttpwwwworgxmlschemainstance xmlnssoapenvhttpschemasxmlsoaporgsoapenvelope soapenvencodingstylehttpschemasxmlsoaporgsoapencoding soapenvheader nsbody nslogin username xsitypensstringremovedusername password xsitypensstringremovedpassword ip xsitypensstringip nslogin nsbody soapenvenvelope debugsudsclientheaders soapaction u httpschemasxmlsoaporgsoapenvelopektwebservicelogin contenttype textxml charsetutf errorsudsclientxml version encodingutf soapenvenvelope xmlnssoapenchttpschemasxmlsoaporgsoapencoding xmlnsnshttpschemasxmlsoaporgsoapencoding xmlnsnshttpschemasxmlsoaporgsoapenvelope xmlnsnshttpwwwworgxmlschema xmlnsxsihttpwwwworgxmlschemainstance xmlnssoapenvhttpschemasxmlsoaporgsoapenvelope soapenvencodingstylehttpschemasxmlsoaporgsoapencoding soapenvheader nsbody nslogin username xsitypensstringremovedusername password xsitypensstringremovedpassword ip xsitypensstringip nslogin nsbody soapenvenvelope debugsudsclienthttp failed xml version encodingutf soapenvenvelope xmlnssoapenvhttpschemasxmlsoaporgsoapenvelope xmlnsxsdhttpwwwworgxmlschema xmlnsxsihttpwwwworgxmlschemainstance xmlnssoapenchttpschemasxmlsoaporgsoapencoding soapenvencodingstylehttpschemasxmlsoaporgsoapencoding soapenvbody soapenvfault faultcode xsitypexsdqnamesoapenvserverfaultcode faultstring xsitypexsdstringmethod ampquotloginampquot defined servicefaultstring faultactor xsitypexsdanyurifaultactor detail xsitypesoapencarray soapencarraytypexsdanytype soapencoffset item object xsiniltrueitem item object xsiniltrueitem item object fault xsiniltrueobjectitem item object fault xsiniltrueobjectitem item object fault xsiniltrueobjectitem item object xsiniltrueitemdetailsoapenvfault soapenvbody soapenvenvelope traceback recent call last file pyshell line module response clientservicelogingetpassgetuser getpassgetpass file buildbdistwineggsudsclientpy line call return clientinvokeargs kwargs file buildbdistwineggsudsclientpy line invoke result selfsendsoapenv file buildbdistwineggsudsclientpy line send result selffailedbinding e file buildbdistwineggsudsclientpy line failed r p bindinggetfaultreply file buildbdistwineggsudsbindingsbindingpy line getfault raise webfaultp faultroot webfault server raised fault method login defined service,2 i exactly torsen saids works sudo find grep fab i found fab file optlocallibraryframeworkspythonframeworkversionsbinfab mac os x,i installed fabric python using pip created two directories librarypythonsitepackagesfabfile librarypythonsitepackagesfabric when i initially ran fab command said command found then i made sure system path included folders still i got command found furthermore i looked folder could find fab file directory note i python prompt fabricapi import what i need able execute fab command thank,1 why use struct unsigned long long type twice import struct somefilewritestructpackqq var var that documented scroll get table q httpdocspythonorglibrarystructhtml,in python long integers unlimited precision i would like write byte bit integer file struct standard library supports byte integers array limitation is way without masking shifting integer some clarification i writing file going read nonpython programs pickle all bits used,1 this would probably encoding issue input quite match file system expects output first need tell python encoding input uses encoding popen call expects filename ctestã¼ã¼ã¼directorydecodeutf res ospopendir filenameencodecp you may experiment various encoding combinations get right pair utf utf cp likely candidates windows system might set use another encoding if really lucky ospopen might even accept unicode string case encode step could skipped if really unlucky character canonicalization could issue there two possible representations ã¼ unicode ufc u u second u combining diaresis first precombined if windows expects one encode produces may work bit get right string,under winxp pro x version sp running following cmd prompt works fine dir ctestã¼ã¼ã¼directory please note ã¼ character but python following always returns error code res ospopendir ctestã¼ã¼ã¼directory resclose how get popen accept ã¼ character,2 a hint note loop string way list iterable object python def countlettersword letter word print letter countlettersabc the output a b c so instead printing use loop look letter got letter variable count somehow,i beginner python trying solve questions lists i got stuck one problem i able solve write function countlettersword takes word argument returns list counts number times letter appears the letters must sorted alphabetical order ex countletters google e g l i able count occurrences every character for sorting i using sortedlist i also using dictionaryitems functions format outputtuples list but i able link things,1 i needed use paramiko run gui another x window found post i think may need add lines make work it handler parameter here assign function incoming x connections chanrequestx handlertestfunc and write simple one import commands def testfunc cmd xterm result commandsgetoutputcmd it pop new window at least works,i manage use paramiko python module passing ssh x management functionality i would like use i used ssh x option i tried several solution nothing work system here code i tried client paramikosshclient clientsetmissinghostkeypolicyautoaddpolicy clientconnectmachinename usernamexxx passwordxxx clientgettransport chan topensession chanrequestx chansetcombinestderr true chanexeccommand xxxxx command display x window bufsize stdin chanmakefile wb bufsize stdout chanmakefile rb bufsize stderr chanmakefilestderr rb bufsize line stdout print linestrip n clientclose i also tried instead execcommand changetptyvt chaninvokeshell chansendxxxxx command display x window unfortunately application freezes moment x window normally appear remark if i launch command without x window displaying works perfectly thank help regards,1 use test command option setuppy documented extended setuptools distribute,i know setuptools option run tests i find information regarding make run tests by default tests included module i use discovery detect run themall any ideas,1 use sets google u setm sortedl mcountl l u e g l,i beginner python trying solve questions lists i got stuck one problem i able solve write function countlettersword takes word argument returns list counts number times letter appears the letters must sorted alphabetical order ex countletters google e g l i able count occurrences every character for sorting i using sortedlist i also using dictionaryitems functions format outputtuples list but i able link things,1 judging examples looks like extremely tricky regardless technique how program know part title middle movie maybe best bet list acronyms truncate string first matching acronym forwards it would give the birds deal i really see way around,i writing program pyqt needs take messy strings clean the possible input values extremely variable for example i would like take strings sevenpoundsbdrippengitagermultisubxbluraymkv thebirdshdtvxvidhdpnpwavi xvidachdminavi turn seven pounds the birds i considered using escape expressions method seems likely fail last example the program media gerbil uses google diffmatchpatch algorithm deal string cleaning this seems like better alternative i sure implement is another effective method cleaning strings pythonpyqt regex diffmatchpatch best route follow,1 datetime import datetime print datetimestrptimetimestring ymdthmsz docs,i want datetime object i strings format tz how i turn datetime object,3 import datetime datetimedatetimestrptimetz ymdthmsz,i want datetime object i strings format tz how i turn datetime object,1 from looks diffmatchpatch match closest talking seems maybe best solution match apparently wants find specific patterns regex rules i think might want define series regex rules underscore treated like space words non azaz possibly signaling end title you would least make assumption title starts beginning string pattern match nonword character reached maybe something like rx recompiler azazdazazd but unfortunately mentioned another answers way really deal the birds i think solution combination assuming title start possibly stop list common tags strip maybe edit thought info maybe narrowed potential title far get could then google diffmatchpatch maybe api search imdbcom find closest match real title,i writing program pyqt needs take messy strings clean the possible input values extremely variable for example i would like take strings sevenpoundsbdrippengitagermultisubxbluraymkv thebirdshdtvxvidhdpnpwavi xvidachdminavi turn seven pounds the birds i considered using escape expressions method seems likely fail last example the program media gerbil uses google diffmatchpatch algorithm deal string cleaning this seems like better alternative i sure implement is another effective method cleaning strings pythonpyqt regex diffmatchpatch best route follow,1 most browsers permit crossorigin xhr the general workaround jsonp basically means using script tag invoke remote javascript passes response data local callback there nothing app enginespecific problem solution,i php web application i want make comments section so i decided way make python web application store comments retrieve comments bigtable i make ajax request store comment along comment parameters make ajax request get comments bigtable json format is possible return formatted html directly i replace div parent page makes request the problem php web application running different domain i sure whether i make ajax calls violate crossdomain security policy if yes rest based apis work i make ajax requests get json response ideally i like return formatted html directly gae but possible i fine returning json can done if yes pointers make api like would useful if workarounds,1 based example import athebirdshdtvxvidhdpnpwavi bsevenpoundsbdrippengitagermultisubxbluraymkv cxvidachdminavi def cleanitstr result l resplit str flag rematch azaz l flag elif rematch l flag flag x l rematch azaz x break resultappendx return joinresult flag x l rematch x break resultappendx return joinresult name main print cleanita print cleanitb print cleanitc print kent python cleanitpy the birds seven pounds,i writing program pyqt needs take messy strings clean the possible input values extremely variable for example i would like take strings sevenpoundsbdrippengitagermultisubxbluraymkv thebirdshdtvxvidhdpnpwavi xvidachdminavi turn seven pounds the birds i considered using escape expressions method seems likely fail last example the program media gerbil uses google diffmatchpatch algorithm deal string cleaning this seems like better alternative i sure implement is another effective method cleaning strings pythonpyqt regex diffmatchpatch best route follow,1 using threading going problem you also going achieve parallelism the global interpreter lock gil python allows single thread process time if want true parallel processing need look multiprocessing module it ability actually leverage multiple processors machine,i function myfunc eg takes start end date amp iterates accesses dictionaries process data time period i looking use threads parallelize code my main function reads data bunch files amp stores dictionaries every time i call myfunc i pass dictionaries start amp end date when i call myfunc using multiple threads pass along dictionaries would conflict these dictionaries used readonly purposes myfunc creates lot dictionaries writes another file this output file would differ every thread since across threads dictionaries named would conflict theoretically i understand concept threading means conflict long dictionaries global but since first attempt threading would like confirmation thanks,3 i actually one point basically follow series steps eliminate anything remove file extension now split in case get seven pounds multisub x bluray the birds hdtv xvidhd p npw xvid ac hd min now basically keep list words purge list look obvious ones example x multisub bluray hdtv xvidhd xvid hd p p ac note want caseinsensitive compares note list expand manually go collection leaves seven pounds the birds min this probably good get semiautomated system one methods would tell purge numbers appear front i point mess things like toy story in case i processing tried figure directory patterns matched archival then i cursesbased interface allowed scroll manually correct script conclusions including renaming edit on second thought script actually made assumption second set numbers well everything afterwards could safely removed these heuristics though run exceptions adding step would corrected last example title,i writing program pyqt needs take messy strings clean the possible input values extremely variable for example i would like take strings sevenpoundsbdrippengitagermultisubxbluraymkv thebirdshdtvxvidhdpnpwavi xvidachdminavi turn seven pounds the birds i considered using escape expressions method seems likely fail last example the program media gerbil uses google diffmatchpatch algorithm deal string cleaning this seems like better alternative i sure implement is another effective method cleaning strings pythonpyqt regex diffmatchpatch best route follow,1 you use slicing operator make shallow copies list mylist mylist mylist mylist if values complex list scalars look copy library,the picture best way explain problem i trying populate dictionary object python key dictionary value list currently keys point list this i want instead i want key associated independent copy list i want change list dict change also occur dict if better object kind task dict i would love hear advise well i tried using list lists gave error surprised thanks a bit noob sorry httpdldropboxcomuimagjpg,2 ok think misinterpreted little you need usermysiteorg served webpy app one way site hosted mysiteorg pass requests regardless subdomain webpy application need a record like mysiteorg dns provider httpkbmediatemplenetquestionsdnsexplainedarecord then use routes something like routesin httppusermysiteorgpany apppagesblogganynameguser the save args may need this map request usermysiteorg mysiteorgapppagesblogargsnameuser you might play little get working the key make sure request subdomain mysiteorg given directly app meaning go wwwmysiteorg mysiteorg somerandomfakesubdomainmysiteorg always get place mysiteorg you probably want put logic blog function ensure subdomain string eg user represents valid user,i page httpmysiteorgmyapppagesblognameuser i need usermysiteorg what write routespy,2 you issue happening basically passing references list wrap lists list use mylist notation mentioned another answer pass that way new instance list different memory location list used python python r jun gcc release cygwin type help copyright credits license information l l l lappend the shows adding element original list modifies lists dict this list memory listl listl lappend l the shows modifying original list adding change lists dict they separate lists,the picture best way explain problem i trying populate dictionary object python key dictionary value list currently keys point list this i want instead i want key associated independent copy list i want change list dict change also occur dict if better object kind task dict i would love hear advise well i tried using list lists gave error surprised thanks a bit noob sorry httpdldropboxcomuimagjpg,1 on linuxmac os use python instead python,currently i use python command points python i installed python i want python command point python how possible mahmoodmpc python usrbinpython mahmoodmpc ls l usrbinpython lrwxrwxrwx root root usrbinpython python mahmoodmpc uname linux orca server ubuntu smp wed jul utc x gnulinux,1 try updatealternatives linux,currently i use python command points python i installed python i want python command point python how possible mahmoodmpc python usrbinpython mahmoodmpc ls l usrbinpython lrwxrwxrwx root root usrbinpython python mahmoodmpc uname linux orca server ubuntu smp wed jul utc x gnulinux,1 you really want change python points programs might expect python break the solution use virtualenv create isolated python environment p python option activate good go,currently i use python command points python i installed python i want python command point python how possible mahmoodmpc python usrbinpython mahmoodmpc ls l usrbinpython lrwxrwxrwx root root usrbinpython python mahmoodmpc uname linux orca server ubuntu smp wed jul utc x gnulinux,3 it advisable you could write top script shebang usrbinenv python if windows install pylauncher it understands on linux make script executable run chmod x yourscript after run script yourscript for interactive use could create virtualenv petr viktorin points to installupgrade versions ubuntu repositries old pip install u virtualenvwrapper follow instructions pathtovirtualenvwrappersh create virtualenv uses python mkvirtualenv python python py to activate virtualenv workon py in active virtualenv python refers pathvirtualenvbinpython so could run python yourmodulepy,currently i use python command points python i installed python i want python command point python how possible mahmoodmpc python usrbinpython mahmoodmpc ls l usrbinpython lrwxrwxrwx root root usrbinpython python mahmoodmpc uname linux orca server ubuntu smp wed jul utc x gnulinux,2 write output disk virus scanner see,i need trigger antivirus mcafee accessing testvirus url httpeicarorgdownloadeicarcom via python if i use ie firefox even wget windows antivirus detects virus url accessed expected behavior however using urllib urllib virus url successfully accessed antivirus detect bad url reached has anyone tried something similar,1 you could follow procedure sudo rm usrbinpython sudo ln usrbinpython usrbinpython but already stated petr viktorin programs would expect python v would stop work so use caution you undo change running sudo rm usrbinpython sudo ln usrbinpython usrbinpython,currently i use python command points python i installed python i want python command point python how possible mahmoodmpc python usrbinpython mahmoodmpc ls l usrbinpython lrwxrwxrwx root root usrbinpython python mahmoodmpc uname linux orca server ubuntu smp wed jul utc x gnulinux,1 since linux want simply type python instead python order run python programs solution simply define alias shell configuration file bashrc etc for bourne shells something like alias pythonpython whatever python name this way change anything system solution quite innocuous break system,currently i use python command points python i installed python i want python command point python how possible mahmoodmpc python usrbinpython mahmoodmpc ls l usrbinpython lrwxrwxrwx root root usrbinpython python mahmoodmpc uname linux orca server ubuntu smp wed jul utc x gnulinux,3 you could use dict dispatcher for example code linked might look like def processnumberresulttokval tokval resultextend name decimal op string reprtokval op def processdefaultresulttokval resultappendtoknum tokval dispatchernumber processnumber toknum tokval g dispatchergettoknumprocessdefaultresulttokval instead adding blocks add keyvalue pairs dispatcher this may efficient evaluating long list ifelse conditionals since dict lookup o require function call you benchmark see compares many ifelse blocks i think main advantage keeps code organized smaller comprehensible units,i library translation uses awesome tokenizegeneratetokens function and pretty fast i things working correctly but translating i found function keeps growing new tokens i want translate elif conditions start pop i also keep variables outside generator keeps track last keyword seen similar a good example actual python documentation one seen bottom httpdocspythonorglibrarytokenizehtmltokenizeuntokenize every time i add new thing i need translate function grows couple conditionals i think function many conditionals way proper way pave ground grow furthermore i feel tokenizer consumes lot irrelevant lines contain keywords i translating so questions how i avoid adding conditional statements make translation function easyclean keep growing without performance hit how i make efficient irrelevant lines i interested,2 this exactly need xmldom import minidom doc minidomparsestringtext question docgetelementsbytagname question answer questiongetelementsbytagname answer answerchildnodesnodevaluestrip questionparentnoderemovechildquestion print doctoxml result html body questionaire question questiontext do i love htmlxml parsing questiontext questalter choice oh god yeah choice choice makes feel good choice choice oh hmm noo choice choice totally choice questalter answer answer question questionaire body html,i problem getting right solution i want delete question children answer as result i need string filtered questions i following html structure html body questionaire question questiontext do i question questiontext answer answer question question questiontext do i love htmlxml parsing questiontext questalter choice oh god yeah choice choice makes feel good choice choice oh hmm noo choice choice totally choice questalter answer answer question question questionaire body html so far tried realize xpathbut lxmlhtml iterparsehas thanx,1 lxml import etree html etreefromstringhtmlstring questions htmlxpath htmlbodyquestionairequestion question questions elements questiongetchildren elementtag answer elementtext htmlxpath htmlbodyquestionaire removequestion print etreetostringhtml,i problem getting right solution i want delete question children answer as result i need string filtered questions i following html structure html body questionaire question questiontext do i question questiontext answer answer question question questiontext do i love htmlxml parsing questiontext questalter choice oh god yeah choice choice makes feel good choice choice oh hmm noo choice choice totally choice questalter answer answer question question questionaire body html so far tried realize xpathbut lxmlhtml iterparsehas thanx,1 presuming structure like class myclassobject def doauthself callauthprocedure callauthprocedure returns token simply adjust class myclassobject def doauthself selftoken callauthprocedure later methods instance class use selftoken necessary,i class class i function performs authentication returns token i would like store token memory use functions class how would i,3 i know answer questions maybe could try using screen if session drops always reattach tail still running it also supports multiuser users view tail command httpenwikipediaorgwikignuscreen create name log screen s log disconnect ctrla d reattach screen r log list remember name screen list to get rid session type exit,we several application servers central monitoring server we currently running ssh tail f monitoring server stream several text logfiles realtime app servers the issue apart brittleness whole approach killing ssh process sometimes leave zombie tail processes behind we mucked around using create pseudoterminals still sometimes leaves zombie processes around apparently also causing issues elsewhere job scheduling product using as cheapanddirty solution get proper centralised logging logstash rabbitmq hopefully i hoping write simple python wrapper start ssh tail f still capture output store pid textfile disk kill appropriate tail process later need i first tried using subprocesspopen i hit issues actually getting tail f output back realtime needs redirected file apparently going host blockingbuffer issues a sources seemed recommend using pexpect pxssh something like ideally i like use python included libraries possible however library really way i open is nice easy way getting python start ssh tail f get output realtime printed local stdout i redirect local file also saving pid file kill later or even i use ssh tail f way still streaming remote file near realtime includes saving pid file cheers victor edit just clarify want tail process die kill ssh process we want start ssh tail f monitoring server ctlrc tail process remote box die well want stay behind normally ssh fix fully reliable reasons i understand play nicely job scheduling hence using screen keep process alive end want,3 print mydictfirstred print item fourth item since item first element in case give six also list contained within dict contained within list contained within another dict the numeric index accesses part inner list something generally useful dict,if i dictionary looks like first red six three seven six green eight three four second blue one five three how i get specific points dictionary for example i print second six first header subheading red,1 you could define table way mymetadata metadata base declarativebasemetadatamymetadata class accntbase tablename accnt code columnstring def columnstring,hello i trying port legacy application python sqlalchemy the application existing database tables every table colum named def create table accnt code varchar def varchar accnt definition so declarative syntax reflection i easily create class class accntbase table table accnt metadata autoload true autoloadwithengine but i try reach def column i eventually get error for example q sessionqueryaccnt row q print qdef because def reserved word python to overcome issue i create class class accntbase table table accnt metadata autoload true autoloadwithengine mapperargs columnprefix but putting front every column name boring fancy what i like access def column another name key any ideas edit editing original post requested tokenmacguy while i accepted tokenmacguy answer i tried engine createengine firebirdsysdbamasterkeydprjdbmakkifdbcharse‌​twin echofalse metadata metadata dbsession sessionmakerbindengine base declarativebase class accntbase table table accnt metadata autoload true autoloadwithengine def columndef string and i got sqlalchemyexcargumenterror can add additional column def specifying table error the main difference tokenmacguy mine table tokenmcguy tablename accnt tableargs autoload true metadata binding so previous attemp generated error,2 assuming dictionary called could printd first red the expression first gives value associated key first the value list the gives first element list way list containing one element note indexing based python then another dictionary whose values lists the red fetches value dictionary the accesses fourth element list,if i dictionary looks like first red six three seven six green eight three four second blue one five three how i get specific points dictionary for example i print second six first header subheading red,1 for one asked first red six three seven six green eight three four second blue one five three first red six,if i dictionary looks like first red six three seven six green eight three four second blue one five three how i get specific points dictionary for example i print second six first header subheading red,1 disclaimer i use python things i say may wrong python experts feel free correct great question i think central misconception i even call perfectly reasonable arrived thought process used prompts ask question when i write b mean b it means b includes reference points thing points the variables b even things also merely pointers otherwise anonymous things memory the concept references major leap nonprogramming world let step program mind you create list happens something ignore what matters list that list gets stored memory let say stored memory location then assignment creates variable programming language allows use later at point list object memory reference access name b this thing b there new list gets stored memory location the programming language creates reference b use refer memory location turn list object b b this two things identical let focus one b what pretty fancy it first evaluates right side equality sees variable b fetches corresponding object memory memory object since b reference what happens left side equally fancy variable points list memory object memory object number references instead references names like b use references numerical indices like so pulls memory object pile indexed references goes reference index previously reference pointed actual number something line repoints reference ie first reference memory object thing right side equation evaluates so object th reference points object b this fanciness done programming language when ask evaluate pulls memory object list location detects using magic infinite renders b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp the failure statement python comparisons when compare object immediately evaluates true when compare object another object uses magic determine whether equality true false in case lists python looks every item list checks equal turn using items equalitychecking methods so try b what first dig b object object realizes different things memory goes recursive list checker it iterating two lists object one element index points object object one element index points object therefore program concludes object equal references point thing ergo reference points reference points thing this equality check never stop the thing would happen list stop you could c c c c would raise error b true as i hinted previous paragraph immediately resolves true python takes shortcut it need compare list contents points object b points object python detects identical literal sense thing even bother checking contents b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp this goes back error ends pointing object the identity check fails falls back recursive content check never ends b true once points object b the recursive check skipped comparison immediately returns true higher level jibber jabber directly related specific code snippet since references referring objects even though appears infinite nesting object referred i called object object referred b size memory and size actually incredibly small since lists point respective memory locations it also worth note less generous languages comparing two references returns true memory objects point sense references point spot memory java example the stylistic convention emerged languages define methodfunction objects java conventionally called equals custom equality testing python box lists i know python particular least ruby overloaded sense someobject otherobject actually calls method called someobject overwrite in theory nothing stopping making someobject otherobject return something boolean,it possible create infinite nested list python that clear although popular definitely useful known fact true my question happening b b b b b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true b traceback recent call last file stdin line module runtimeerror maximum recursion depth exceeded cmp b true which way deeper i trying understand i feel much like brain going explode i see contains b contains now questions one do really two lists one how thing like gets stored memory what could purpose enable programers implement something strange like please treat question superserious and forget programming fun sometimes,3 i think want look twistedwebserversite twistedwebresourceresource also since using twisted probably want use twistedprotocolstelnettelnet telnet connection otherwise application asynchronous this blog post answer may also useful hope helps,this i want webbrowser connect remote server telnetserver squidproxywhich requires authentication telnet port server i written small python script uses twisted usrbinpython twistedinternet import reactor protocol twistedweb import http telnetlib import telnet import getpass sys import stdout class datareceiverprotocolprotocol def datareceivedselfdata selftelnetconwritedata stdoutwrite selftelnetconreadall def connectionmadedata stdoutwritena connection made servern def main server user rawinputenter remote account password getpassgetpass tn telnetserver password tnreaduntilpassword tnwritepassword n this server tnwritetelnet n serverfac protocolfactory serverfac httphttpfactory datareceivertelnetcon tn serverfacprotocol datareceiver reactorlistentcpserverfac reactorrun tnwriteexitn print tnreadall name main main but i realized i wrong way shell getting replies squid instead browser can someone outline correct way should i use something else instead twisted,1 unlink usrbinpython ln usrbinpython usrbinpython,currently i use python command points python i installed python i want python command point python how possible mahmoodmpc python usrbinpython mahmoodmpc ls l usrbinpython lrwxrwxrwx root root usrbinpython python mahmoodmpc uname linux orca server ubuntu smp wed jul utc x gnulinux,1 if want act like python best write python you cannot change numbers compiled program what can however make program accept parameters change runtime you c commandline parameters configuration files asking input all easier involving python if reason parts code c really want python expose c routines library python one popular approach swig what could make functions call python would accept changeable parameters your python script would simply call,i wanted know could i change values arguments cc program python in program i use newtonraphson method compute roots function what i want change value variable xn initial guess certain value given python interface this code simple i trying bigger code i need change values variables i dont want compile code time i change values variables i write input file order avoid compiling code i want controlling code even instance stop program certain time step change values variables continue execution could tell straightforward way regards include iostream using namespace std double firstderivativedouble x double dummy parabolic function dummy x return dummy double secondderivativedouble x double dummy parabolic function dummy returndummy int main double xnfdsd int xn cout xn n fori fd firstderivativexn sd secondderivativexn xn xn fdsd cout fd sd xn n return,1 you need version pyexe matches architecture python install if bit python install need win pyexe installer if x python install need win pyexe installer in case i bit machine bit python install the source forge latest link gave win version pyexe detected machine type but work i kept getting following error importerror dll load failed error code i needed go back source forge browse files find win version,i different forums spent week googling arse try find solution i cannot seem get pyexe work properly i run python setuppy pyexe cmd well python setuppy install when i try run executable setup i get error after week i starting get quite frustrated i hoping able resolve issue today i using python pyexe v bit windows thanks advance,1 you cake eat define columns want rename sqlalchemy automatically infer columns mention sqlalchemy import sqlalchemyextdeclarative import declarativebase engine createenginesqlitememory engineexecute create table accnt id integer primary key code varchar def varchar sqlalchemyenginebaseresultproxy object x base declarativebase basemetadatabind engine class accntbase tablename accnt tableargs autoload true def column def string accntdef sqlalchemyormattributesinstrumentedattribute object xe accntcode sqlalchemyormattributesinstrumentedattribute object x edit by supplying table argument telling declarative extension already properly configured table like use but true want def column referred another name class by using tablename tableargs defer construction table told declarative want use table there elegant workaround dead set using table you provide property aliases column may able specify column def getattrtablec def really use tablename it convenient flexible great example aside conventional give alternate identifiers trailing underscore instead leading underscore use def instead def leading underscores usually signify name private implementation detail name meant public looks like private name may cause confusion necessary,hello i trying port legacy application python sqlalchemy the application existing database tables every table colum named def create table accnt code varchar def varchar accnt definition so declarative syntax reflection i easily create class class accntbase table table accnt metadata autoload true autoloadwithengine but i try reach def column i eventually get error for example q sessionqueryaccnt row q print qdef because def reserved word python to overcome issue i create class class accntbase table table accnt metadata autoload true autoloadwithengine mapperargs columnprefix but putting front every column name boring fancy what i like access def column another name key any ideas edit editing original post requested tokenmacguy while i accepted tokenmacguy answer i tried engine createengine firebirdsysdbamasterkeydprjdbmakkifdbcharse‌​twin echofalse metadata metadata dbsession sessionmakerbindengine base declarativebase class accntbase table table accnt metadata autoload true autoloadwithengine def columndef string and i got sqlalchemyexcargumenterror can add additional column def specifying table error the main difference tokenmacguy mine table tokenmcguy tablename accnt tableargs autoload true metadata binding so previous attemp generated error,3 i suggest looking shootout pretty complete pyramid demo app,i learning pyramid i like see open source projects get quick start,1 one approach use boost python boostpython c library enables seamless interoperability c python programming language sounds like fits requirements alternatively c program accept arguments you could change main function accept arguments int mainint argc char argv argc contains number arguments argv pointer argument strings you parse use something like boostprogramoptions this program invoked python using python subprocess,i wanted know could i change values arguments cc program python in program i use newtonraphson method compute roots function what i want change value variable xn initial guess certain value given python interface this code simple i trying bigger code i need change values variables i dont want compile code time i change values variables i write input file order avoid compiling code i want controlling code even instance stop program certain time step change values variables continue execution could tell straightforward way regards include iostream using namespace std double firstderivativedouble x double dummy parabolic function dummy x return dummy double secondderivativedouble x double dummy parabolic function dummy returndummy int main double xnfdsd int xn cout xn n fori fd firstderivativexn sd secondderivativexn xn xn fdsd cout fd sd xn n return,1 in tokenizer regularexpressions used specify tokens want extract text look like i bit confused many regular expressions used simple tokenization nonwhitespace tokens could use corpus sentence another sentence homepage httptestcom nltkregexptokenizecorpus rs sentence another sentence homepage httptestcom equivalent corpussplit sentence another sentence homepage httptestcom another approach could using nltk functions senttokenize nltkwordtokenize sentences nltksenttokenizecorpus sentences sentence another sentence homepage httptestcom sentence sentences print nltkwordtokenizesentence sentence another sentence homepage http testcom though text contains lots websiteurls might best choice information different tokenizers nltk found want extract urls corpus could use regular expression like nltkregexptokenizecorpus r httphttpswww hope helps if answer looking please try explain bit precisely want exactely want tokens look like eg example inputoutput would like help finding right regular expression,hi i never deal regex i trying preprocess raw text python nltk i tried tokenize document using tokens nltkregexptokenizecorpus sentencere sentencere r x set flag allow verbose regexps azaz abbreviations eg usa ww words optional internal hyphens dd currency percentages eg ww hashtags signs ellipsis separate tokens httpwww websites able take website one single token print toks seamonkey sm i short chirp exchange angiep thdec btw sm faster also agile user community http bit ly xnf icr http help greatly appreicated thanks much florie,2 to elaborate comment sole purpose threads consume values queue perform function decidedly better something like imho q queue results def worker true x qget resultsappendx qtaskdone rangeworkercount threadtarget worker tdaemon true tstart tup listofxys qputtup qjoin some code results list qjoin block empty the worker threads continue attempt retrieve values find wait indefinitely queue empty when script finishes execution later worker threads die marked daemon threads,i function accepts large array xy pairs input elaborate curve fitting using numpy scipy returns single value to try speed things i trying two threads i feed data using queuequeue once data done i trying threads terminate end calling process return control shell i trying understand i resort private method threadingthread stop threads return control commandline the selfjoin end program the way get back control use private stop method def stopself print stop called selffinishedset print set done selfjointimeoutnone work selfthreadstop here approximation code class calcthreadthreadingthread def initselfinqueueoutqueuefunction threadingthreadinitself selfinqueue inqueue selfoutqueue outqueue selffunction function selffinished threadingevent def stopself print stop called selffinishedset print set done selfthreadstop def runself selffinishedisset paramsforfunction selfinqueueget try tm selffunctionparamsforfunction selfinqueuetaskdone selfoutqueueputtm except valueerror v modify params reinsert queue window paramsforfunctionwindow paramsforfunctionwindow window selfinqueueputparamsforfunction def bigcalculationwellidwindowdataarrays analysis calculate tm return tm name main numthreads workers inqueue queue outqueue queue rangenumthreads w calcthreadinqueueoutqueuebigcalculation wstart workersappendw optionsanalyzeall wellids inqueueputdictwellidiwindowdataarraysmydatadict inqueuejoin print all threads seem to be done gather data report outqueue wellids p outqueueget print p outqueuetaskdone i get outqueue proceed outqueueqsize outqueuejoin break calling stop method seem return control command line unless i use threadingthread private method aworker workers aworkerstop,2 list comprehension terse way accomplish intx x sssplit ss ssplit,would split string list values like mydata,3 i believe if hope probably need look python net might give ironpython try but code using subprocess simply giving result ran string command line which launches explorer application arguments but started running its looking command line input i looked list command line arguments explorer i see nothing would indicate manipulate running sorry hope helps,i program opens lot folders right i hoping i use already open explorer instances open new ones i code import subprocess subprocesspopenr explorer selectcpathoffolderfile i seen threads c does anyone know way done python thanks ben,1 in general bad idea kill thread modifies shared resource cpu intensive tasks multiple threads worse useless python unless release gil performing computations many numpy functions release gil threadpoolexecutor example docs import concurrentfutures python x pip install futures calcargs optionsanalyzeall calcargsextenddictwellidi wellids concurrentfuturesthreadpoolexecutormaxworkersnumthreads executor futuretoargs dictexecutorsubmitbigcalculation args args args calcargs futuretoargs future concurrentfuturesascompleteddictfuturetoargs args futuretoargspopfuture futureexception none print r generated exception args futureexception isinstancefutureexception valueerror modify params resubmit argswindow futuretoargsexecutorsubmitbigcalculation args args else print fr returned r args futureresult printall work seems to be done you could replace threadpoolexecutor processpoolexecutor shared state put code main function,i function accepts large array xy pairs input elaborate curve fitting using numpy scipy returns single value to try speed things i trying two threads i feed data using queuequeue once data done i trying threads terminate end calling process return control shell i trying understand i resort private method threadingthread stop threads return control commandline the selfjoin end program the way get back control use private stop method def stopself print stop called selffinishedset print set done selfjointimeoutnone work selfthreadstop here approximation code class calcthreadthreadingthread def initselfinqueueoutqueuefunction threadingthreadinitself selfinqueue inqueue selfoutqueue outqueue selffunction function selffinished threadingevent def stopself print stop called selffinishedset print set done selfthreadstop def runself selffinishedisset paramsforfunction selfinqueueget try tm selffunctionparamsforfunction selfinqueuetaskdone selfoutqueueputtm except valueerror v modify params reinsert queue window paramsforfunctionwindow paramsforfunctionwindow window selfinqueueputparamsforfunction def bigcalculationwellidwindowdataarrays analysis calculate tm return tm name main numthreads workers inqueue queue outqueue queue rangenumthreads w calcthreadinqueueoutqueuebigcalculation wstart workersappendw optionsanalyzeall wellids inqueueputdictwellidiwindowdataarraysmydatadict inqueuejoin print all threads seem to be done gather data report outqueue wellids p outqueueget print p outqueuetaskdone i get outqueue proceed outqueueqsize outqueuejoin break calling stop method seem return control command line unless i use threadingthread private method aworker workers aworkerstop,3 you close idnum the loop good you break wrong place id idnumber aiteritems idnum idnumberkeys skip keys default calculate somefunctionofidnumberidnum break find done looking leave loop otherwise continue next dictionary else loop else clause find end never broke loop calculate yourdefaultvalue whatever want find if need know many keys inner dict idnum print sumidnum idnumber idnumber aitervalues this works key dict test key exits returns true false equal sum number occurences idnum,i python dictionaries like a id idnumber condition eg a i need search dictionary idnumber calculate something condition but entire dictionary idnumber i need continue next dictionary this try id idnumber aiteritems idnumberkeys calculate else break,2 i suggest looking eclipse pydev debugging i imagine many alternatives though,given python source code possible run code line line debugging and comes function call i would like step function also thanks,1 python pdb scriptpy run script python debugger,given python source code possible run code line line debugging and comes function call i would like step function also thanks,3 okay proofofconcept shows note goes one level deep properties nested functions adjusted to implement well make robust function globals compared globals replaced make substitution def migrateclasscls globals recreates class substituting passedin globals globals already existing class this proofofconcept version goes onelevel deep ie properties nested functions changed name clsname bases clsbases newdict dict hasattrcls slots newdict slots clsslots name clsslots hasattrcls name attr getattrcls name callableattr closure attrclosure defaults attrdefaults funccode attrcode attr functiontypefunccode globals newdictname attr hasattrcls dict od getattrcls dict name attr oditems callableattr closure attrclosure defaults attrdefaults kwdefaults attrkwdefaults funccode attrcode attr functiontypefunccode globals name defaults closure kwdefaults attrkwdefaults kwdefaults newdictname attr return typename bases newdict after gone excercise i really curious need,i want modify classes standard library use different set globals ones classes module use example this example example moduleapy myglobal class a def initself myglobalappendself class b def initself myglobalappendself in example if i create instance a via a call append object named myglobal but i wish create new module import b b use myglobal module imported instead myglobal module b original defined modulebpy modulea import b myglobal related i struggling explain problem previous attempt fact ask something completely different clone module make changes copy update the example illustration i trying achieve since variable scope classes unlike say c i think reference globals mapping stored class instead attached every function defined update an example requested standard library many maybe classes threading module make use globals allocatelock getident active defined one cannot change globals without changing classes module,1 if tagid part movies object would simple case checking tagid movies null sessionquerymoviesfiltermoviestagid noneall but manytomany comment suggests moviestags link entity trickier involves linking moviestags using left outer join there good guide writing debugging similar sql queries and basically want end select moviesname movies left outer join moviestags moviesmovieid moviestagsmovieid moviestagstagid null,say i two types objects movies tags related orm many many relationship association table indicated secondary argument relationship i want able find say movies without tags what kind query would i run achieve effect,1 you might like thomas rachel alllist decorator class alllistlist list called order used alladding decorator def callself obj decorators selfappendobjname return obj import whereever top module whereeveralllist module looks like def somefunc def anotherfunc need worry globals update if really want worry globals take look use class context different module pretty however,i simple decorator function i use expose functions defined module via module’s property because i use multiple modules within package i defined package’s initpy because i cannot use within definition would refer initpy module rather package i currently like def expose fn fnglobals append fnname this seems work totally fine however i’m sure using global property ideal way especially property seems undocumented least i couldn’t find anything documentation is using globals fine maybe easier robust way make work edit for clarification i don’t necessarily need access property module i easily use different name end question i’m using purpose holding exposed objects module matches intention but time i could also name exposedfunctions whatever so question access global properties module,1 root subdirs files oswalkthispath myfile files shutilmoveospathjoinroot myfile ospathjointhispath filename,so i let user set path directory may contain subdirectories levels files i use oswalk code scan whole directory root subdirs files oswalkthispath myfile files shutilmoveospathrealpathmyfile ospathjointhispathfilename ospathrealpathmyfile instead giving absolute path myfile i also tried ospathabspathmyfile thing basically gives path script running like oschdir attached myfile filename basically ospathrealpathmyfile ospathjoinoschdirmyfile whereas myfile obviously random directory when i try move file says exist true path goes look how i get absolute path file i walking myfile,1 you close one approaches actually want lisortkey itemgetter reverse true,i trying sort nested list structure based last values nested lists my list looks like li b c the output i would like b c i tried solutions worked using itemgetter like ranklist isortkeyitemgetter li what i wrong is better way sort nested lists i get attributeerror str object attribute sort thanks help,2 here solution improvements welcome in ipython config add following lines mine configipythonprofiledefaultipythonconfigpy c getconfig port bash aliases ipython import os string ospopenbash l c alias read atranslatestringmaketrans split alias tuplexstripsplit x caliasmanageruseraliases x x lenx,how port bash aliases ipython version this question already answered ipython link httpipythonscipyorgwikitips,1 unless i missing something use python query db like djangocontribauthmodels import user x userobjectsfilterfirstname john lastname smith edit to answer question if need return john paul smith user searches john smith use contains translates sql like if need capacity store name john paul put names firstname column userobjectsfilterfirstnamecontains john lastnamecontains smith this translates select from users where firstname like john and lastname like smith,how i query full name django to clarify i essentially want create temporary column combining firstname lastname give fullname like like select fields users concatfirstname lastname like john smith the query would return users named john smith if possible i like avoid using raw sql call the model i talking specifically stock djangocontribauthmodels user model making changes model directly problem for example user search john paul smith match users first name john paul last name smith well users first name john last name paul smith,3 there two ways redirect both apply either subprocesspopen subprocesscall set keyword argument shell true executable pathtotheshell specify command since redirecting output file set keyword argument stdout anopenwriteablefileobject object points output file subprocesspopen general subprocesscall popen block allowing interact process running continue things python program the call popen returns popen object call block while supports arguments popen constructor still set process output environmental variables etc script waits program complete call returns code representing process exit status returncode callargs kwargs basically calling returncode popenargs kwargswait call convenience function it implementation cpython subprocesspy def callpopenargs timeoutnone kwargs run command arguments wait command complete timeout return returncode attribute the arguments popen constructor example retcode callls l popenpopenargs kwargs p try return pwaittimeouttimeout except pkill pwait raise as see thin wrapper around popen,i want call external program python i used popen call what difference two my specific goal run following command python i sure redirects work myscriptsh output i read documentation says call convenience function shortcut function do lose power using call instead popen,3 the insert statement invalid syntax there something wrong inside loop mention you include loop question insert into dummykm data values a valid statement could look like assuming column type integer also include question insert into dummykmdata values int insert into dummykmdata values array note array dimensional array looks bit like error msg insert into dummykmdata values int insert into dummykmdata values array more array value input manual ergo matdatai needs contain array one listed variants valid syntax instead valid integer array psychopg automatically converts postgresql array python list when building insert need convert list back array i quote python lists converted postgresql arrays curmogrifyselect select array disclaimer i expert postgresql much python for somebody knows python better easy format string accordingly i found quote quick research web,i reading data mat file using pytables module after reading data i want insert data database using psycopg here sample code piece file tablesopenfilematfile x populate matdata list var dest data filegetnode var matdataappenddata x x insert db rangex curexecuteinsert into values tablenamedestimatdatai i getting following error traceback recent call last file loaddbfrommatpy line module readinputfileandloadargsmatfilenameargstablename file loaddbfrommatpy line readinputfileandload curexecuteinsert into values tablenamedestimatdatai psycopgprogrammingerror syntax error near line insert into dummykm data values it would great anyone suggest workaround thanks,1 it based address none memory type definition says,on machine hashnone returns value hashnone just curiosity hash value calculated it seem though value based none id i restart python interpreter,3 i think screen idea best idea wanting ssh want python script here simple pythonic xmlrpc way getting info it update something appended file question this client file you tell file want read computer usrbinpython this run computer want output files you must pass filename location filename must full path root directory relative path directory server running location must form httplocationport ie httplocalhost import xmlrpclib time sys os def tailfilename location connect server xmlrpclibserverproxylocation get starting length file curseek sgetsizefilename constantly check timesleep make sure sleep get new length file check changes prevseek curseek times fails file writter wait another second finish try curseek sgetsizefilename except pass file length changed print prevseek curseek print stailfilename prevseek def main check got file passed us lensysargv ospathisfilesysargv print must give valid filename return run tail function tailsysargv sysargv main this server run computer file want look its nothing fancy you daemonize want you run client connect tell client right ports open usrbinpython this runs computers want read file make sure change host port variables host localhost port simplexmlrpcserver import simplexmlrpcserver simplexmlrpcserver import simplexmlrpcrequesthandler import time os def getsizefilename get file size return osstatfilename def tailfilename seek set filename open file f openfilename r find size file move end fseekseek return fread def createserver create server server simplexmlrpcserverhost port requesthandlersimplexmlrpcrequesthandler register functions serverregisterfunctiontail tail serverregisterfunctiongetsize getsize run server main loop serverserveforever start server createserver ideally run server client run python clientpy samplelog httpsomehost start going hope helps,we several application servers central monitoring server we currently running ssh tail f monitoring server stream several text logfiles realtime app servers the issue apart brittleness whole approach killing ssh process sometimes leave zombie tail processes behind we mucked around using create pseudoterminals still sometimes leaves zombie processes around apparently also causing issues elsewhere job scheduling product using as cheapanddirty solution get proper centralised logging logstash rabbitmq hopefully i hoping write simple python wrapper start ssh tail f still capture output store pid textfile disk kill appropriate tail process later need i first tried using subprocesspopen i hit issues actually getting tail f output back realtime needs redirected file apparently going host blockingbuffer issues a sources seemed recommend using pexpect pxssh something like ideally i like use python included libraries possible however library really way i open is nice easy way getting python start ssh tail f get output realtime printed local stdout i redirect local file also saving pid file kill later or even i use ssh tail f way still streaming remote file near realtime includes saving pid file cheers victor edit just clarify want tail process die kill ssh process we want start ssh tail f monitoring server ctlrc tail process remote box die well want stay behind normally ssh fix fully reliable reasons i understand play nicely job scheduling hence using screen keep process alive end want,1 it based none id none one python objects defined c global variables address typically change python runs other objects true false hashed ints builtin classes like object tuple the address hash different different cpython builds however on system hashnone gives,on machine hashnone returns value hashnone just curiosity hash value calculated it seem though value based none id i restart python interpreter,3 a lot people strongly believe supposed scripts ipython syntax curious enough i looking fun ways mix python shell scripts checkout wrapper program github example use case cat exampleipy rehashx ls l tail n print afields b foo echo bar b ipyscriptpy exampleipy rwrr drwxrxrx drwxrwxrx bar foo as turns ipython core also supports barely functional version script in ipythoncoreinteractiveshellinteractiveshellsafeexecfileipy type instancemethod base class type instancemethod string formunbound method interactiveshellsafeexecfileipy namespace interactive file optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagesipythoncoreinteractiveshellpy definition ipythoncoreinteractiveshellinteractiveshellsafeexecfileipyself fname docstring like safeexecfile ipy files ipython syntax parameters fname str the name file execute the filename must ipy extension,i ipython scripts redundant functionality i would like refactor common functionality one module include modules existing script the problem cannot made python module code uses ipython language extensions etc is possible make module ipython code include another ipython scripts,2 using python string methods line textsplitlines line linesplit line print join joinline joinline this splits line wherever whitespace joins three data columns text together adds final text data,i trouble placing delimiters following text i want place text subsequent numbers the problem sometimes numbers actually dashes signify ie instead text a line text another line another one one so far i get delimiters using following code text resubr sd text text resubr sd text text resubr sd text this outputs a line text another line another one one however i want another delimiter second row without placing delimiter one is way python i would like final output a line text another line another one one,1 it looks like ospathjoin uses build add method verified putting print statement add method class pathstr def addself print add return pathospathjoinstrself p pathr thepath p thefiletxt add class pathstr def addself print add return pathospathjoinself p pathr thepath p filetxt add add add printed twice simplest solution change return pathospathjoinself return pathospathjoinstrself it works,does anybody knows ospathjoin function work subclasses str i using python x python x windows result that code i class pathstr def addself return pathospathjoinself p pathr cthepath p somefiletxt result i want cthepathsomefiletxt output somefiletxt matter value self i know i either strself store selfpath use later osjoinpath accept str subclass raise error like use number non string type,1 httpsupervisordorg better choice,sorry wrong site maybe superuser i trying make pythonpy file executable i click automatically thing without specifying open terminal default prompt i already chmod x permissions clarification i want run clicking terminal i meant i said click automatically thing already shebang line when i click right prompts want open text file terminal i make always default opening terminal oddball request,1 you need use something sophisticated cmp try fnmatchfnmatch instead passing find entries you may want look fnmatchfilter well,here program called telephone import shelve import string unknown home work fax cell class phoneentry def initself name unknown number unknown type unknown selfname name selfnumber number selftype type create string representation def reprself return sd selfname selftype fuzzy compare two items def cmpself stringlowerstrself stringlowerthat stringfindthis return returncmpthis def showtypeself selftype unknown return unknown selftype home return home selftype work return work selftype fax return fax selftype cell return cellular class phonedb def initself dbname phonedata selfdbname dbname selfshelve shelveopenselfdbname def delself selfshelveclose selfshelve none def addself name number type home e phoneentryname number type selfshelvestre e def lookupself string list key selfshelvekeys e selfshelvekey cmpe string listappende returnlist loaded module run small test name main foo phonedb fooadd sean reifschneider home fooadd sean reifschneider cell fooadd evelyn mitchell home print first lookup entry foolookup reifsch print entryname entrynumber entryshowtype print print second lookup entry foolookup e print entryname entrynumber entryshowtype i take program modify make better i able accomplish everything print list database contains everyone added respective information can someone assist stir right directionsee code telephone import pb phonedb print welcome telephone database print print please make selection print print add new number print print find number print print list directory print print e exit print myinput rawinput myinput print pushed myinput print pushed myinput print pushed print myinput print what name person want add p rawinput print what number want specified person n rawinput print what type communication device unknown home work fax cell rawinput pbaddp n unknown pbaddp n home pbaddp n work pbaddp n fax pbaddp n cell myinput print type name person whos number looking search rawinput entry pblookupsearch print entryname entrynumber entryshowtype myinput this is where i need assistance entry pblookup print entername entrynumber entryshowtype myinput e myinput e break print thanks playing el gooey,1 one cannot change globals without changing classes module that root problem good explanation problem global variables general the use globals threading tethers classes global objects by time jerryrig something find monkey patch use global variable within individual class module ahead reimplementing code use the work around might use situation something like mock mock patch decoratorscontext managers something similar could used swap global variable lifetime given object it works well within controlled context unit testing circumstances i recommend would think reimplementing code suit needs,i want modify classes standard library use different set globals ones classes module use example this example example moduleapy myglobal class a def initself myglobalappendself class b def initself myglobalappendself in example if i create instance a via a call append object named myglobal but i wish create new module import b b use myglobal module imported instead myglobal module b original defined modulebpy modulea import b myglobal related i struggling explain problem previous attempt fact ask something completely different clone module make changes copy update the example illustration i trying achieve since variable scope classes unlike say c i think reference globals mapping stored class instead attached every function defined update an example requested standard library many maybe classes threading module make use globals allocatelock getident active defined one cannot change globals without changing classes module,1 you need configparser module httpdocspythonorglibraryconfigparserhtml it parses files look like not knowing exact situation i sure,let say sample text file linux sampletexttxt abcd efgh homeusertargetfiletxt ijkl homeusertargetfiletxt how i get specific path homeusertargetfiletxt amp homeusertargetfiletxt sampletexttxt place variable,1 my suggested approach parse file general configuration file store things look like assignments if weird stuff going file may work i think work myvars iterate lines line open sampletexttxt readlines skip line look like assignment line continue split left right pieces left right linesplit keep around dictionary myvarsleftstrip rightstrip query get stuff myvars efgh returns homeusertargetfiletxt,let say sample text file linux sampletexttxt abcd efgh homeusertargetfiletxt ijkl homeusertargetfiletxt how i get specific path homeusertargetfiletxt amp homeusertargetfiletxt sampletexttxt place variable,1 row refers second column current row phone that well good however newrowsappendrow add entire row list when check row newrows checking individual phone number list complete rows but want you need check list set phone numbers for probably want keep track rows set observed phone numbers something like f csvreaderopen filecsv rb writer csvwriteropenfilecsv wb phonenumbers set row f row phonenumbers writerwriterowrow phonenumbersadd row,i csv file multiple entries example csv user phone email joe joexcom mary maryxcom ed edxcom i trying remove duplicates specific column csv however code i getting list index range i thought comparing row newrows i would find duplicates rewrite unique entries filecsv this work though i understand f csvreaderopen filecsv rb newrows row f row newrows newrowsappendrow writer csvwriteropenfilecsv wb writerwriterowsnewrows my end result list maintains sequence file set workright look like user phone email joe joexcom mary maryxcom,3 do mean want setdefaultkey default foo keyerror asetdefault foo bar key exist set foo bar asetdefault foo x key exist return bar,it seems silly write following l x l lx something else lx somethingelse doesn perform lookup x twice i tried using index gives error value found ideally i would like say like x l save index i appreciate might beginner python idiom seems rather unsearchable thanks,1 if list use index catching valueerror thrown yourlist try yourlistindexx except valueerror none then test value none do things item found,it seems silly write following l x l lx something else lx somethingelse doesn perform lookup x twice i tried using index gives error value found ideally i would like say like x l save index i appreciate might beginner python idiom seems rather unsearchable thanks,1 another option tryexcept try dx somethingelse except keyerror dx something same result code edit okay fast moving target same idiom list different exception indexerror,it seems silly write following l x l lx something else lx somethingelse doesn perform lookup x twice i tried using index gives error value found ideally i would like say like x l save index i appreciate might beginner python idiom seems rather unsearchable thanks,1 as cgi need blank line headers body print contenttype textplain print print hello world,i apache server i using cgi i writing cgis python as long responses form contenttype texthtmln works but i send anything else i get error logs say malformed header script bad header can i change configurations make work is anything else i,2 you need send contenttype header tell browser type data sending without get error experiencing,i apache server i using cgi i writing cgis python as long responses form contenttype texthtmln works but i send anything else i get error logs say malformed header script bad header can i change configurations make work is anything else i,1 i would suggest referring django admin app works situations like typically would two stage operation first create several labels create document pick labels want associated multiselect list save django would automatically associate labels selected list via manytomany table documents labels if hoping one step possibility using inline formsets the admin app uses mainly foreign keys poll questions example used limited degree manytomany relationships well be warned inline formsets tricky if split operation two separate views would much easier simply create one view creating labels another creating documents automatically list picking labels associate document,i set document objects label objects i want two objects linked it typical manytomany relationship i following code modelspy class documentmodelsmodel title modelscharfieldmaxlength uniquetrue titleslug modelsslugfieldmaxlength uniquetrue editablefalse labels modelsmanytomanyfield label def saveself args kwargs selftitleslug slugifyselftitle superdocument selfsaveargs kwargs class labelmodelsmodel name modelscharfieldmaxlength uniquetrue slug modelsslugfieldmaxlength uniquetrue editablefalse def saveself args kwargs selfslug slugifyselfname superdocument selfsaveargs kwargs viewspy class documentformmodelform class meta model document fields titlelabels def uploaddocumentrequest requestmethod post form documentformrequestpost requestfiles formisvalid newdocument formsave return httpresponseredirectthanks else form documentform return rendertoresponse uploadpagehtml form form contextinstancerequestcontextrequest when i upload document gets added database however labels created associated document do i need explicitly add something document save function make happen or somewhere viewspy file i imagine go something like check see label added already exists if create new label grab current documentid newexisting labelid add record documentlabels table automatically created manytomany relationship i feel like pretty standard functionality i assumed would built manytomany relationship django seem working far i trying avoid reinventing wheel somewhat new django thanks advance,1 here sample code access yahoo boss api v using pythonoauth oauth liberary oauthconsumerkey oauth consumer key oauthconsumersecret oauth consumer secret url httpybossyahooapiscomysearchweb import urllib import oauthoauth oauth data q yahoo boss search start count formatjson consumer oauthoauthconsumeroauthconsumerkey oauthconsumersecret signaturemethodplaintext oauthoauthsignaturemethodplaintext signaturemethodhmacsha oauthoauthsignaturemethodhmacsha oauthrequest oauthoauthrequestfromconsumerandtokenconsumer tokennone httpmethod get httpurlurl parametersdata oauthrequestsignrequestsignaturemethodhmacsha consumer completeurl oauthrequesttourl response urlliburlopencompleteurl print request url completeurl print print response print responseread,i awfully hard time yahoo authenticationauthorization i enabled boss account set payment method i trying run search using python code import urllib import oauth oauth import time oauthconsumerkey blahblahblah oauthconsumersecret blah def oauthrequesturl params methodget params oauthversion params oauthnonce oauthgeneratenonce params oauthtimestamp inttimetime consumer oauthconsumerkeyoauthconsumerkey secretoauthconsumersecret params oauthconsumerkey consumerkey req oauthrequestmethodmethod urlurl parametersparams reqsignrequestoauthsignaturemethodhmacsha consumer none return req name main url httpybossyahooapiscomysearchweb req oauthrequesturl paramsq cats dogs requrl reqtourl print requrl result urlliburlopenrequrl i keep getting urllibhttperror http error unauthorized exception i figure whether something wrong key method signing i somehow tampering data signing deal anyone suggestions,1 you want hidden member stat result called stblocks osstat somefile posixstatresultstmode stino stdev stnlink stuid stgid stsize statime stmtime stctime sstsize e size data fork mb xstblocks e total size disk mb the file question mb resource fork shows result stat hidden attribute bonus points anyone knows exactly file note documented man stat stblocks attribute always measures increments bytes note stsize measures number bytes data stblocks measures size disk including overhead partially used blocks so open filetxt w write hello world osstat filetxt sstsize sstblocks now get info finder see file size kb disk bytes,i written small utility creating xml folder structure comparison folders via generated xml supports win mac platforms however mac recursively calculating folder size adds total size on investigation came due extended attributes resource forks present certain files can anybody know i determine extended attributes resource forks size preferably python currently i using ospathgetsize determine size file adding files size determine folder size eventually,1 so i revisited question found two solutions i switched python sometime ago i sure python replace find findstr remove doublequotes output subprocesspopen netstat ano findstr stdoutsubprocesspipe shelltrue communicate but explain find cannot used use string parameter instead list output subprocesspopen netstat ano find stdoutsubprocesspipe shelltrue communicate pipeout subprocesspopen netstat ano stdout subprocesspipe output subprocesspopen find stdin pipeoutstdout stdout subprocesspipe communicate the problem arise fact find actually translated find thus following command executed windows command shell find access denied proof running output subprocesspopen echo find stdoutsubprocesspipe shelltrue communicate print output returns find running output subprocesspopen echo find stdoutsubprocesspipe shelltrue communicate print output returns find,i using windows i tried python python so i trying call command line python netstat ano find windows cmd line works perfectly fine so st attempt output subprocesspopen r netstat ano find stdoutsubprocesspipe shelltrue communicate an error raised find actually receive correct parameter eg find access denied nd attempt calling netstat cmdnetstat subprocesspopen netstat ano stdout subprocesspipe pipelining netstat result find cmdfind subprocesspopen find stdin cmdnetstatstdout stdout subprocesspipe again error raised access denied what i wrong edit rd attempt as pavel repin suggested cmdnetstat subprocesspopen cmdexe c netstat ano find stdoutsubprocesspipe communicate unfortunately subprocess cmdexe c results something resembling deadlock blank cmd window i assume c ignored cmd resulting communicate waiting indefinitely cmd termination since windows bet bet cmd accepts parameter starting slash so i substituted c c cmdnetstat subprocesspopen cmdexe c netstat ano find stdoutsubprocesspipe communicate andback error access denied edit i gave i process string returned netstat ano python might bug,2 maybe take look selenium it firefox plugin enables automation also webdriver system write automation scripts various languages including python server execute code various browsers i never tried webdriver part want,i trying automate web application validation performed teami choosen python language although exp python limitedi done similar things past using perl now problem posting url website directs logon page made javascript from whatever little python i know i believe scrappingparsing website made javascript possible i faced issue perl well able proceed any pointers help resolving issue would highly appreciated thanks,1 i think code automatically reflect foreignkey use relationship without changes just ideas explore issue though make sure multiple foreignkey parent table else must specify join condition using primaryjoin parameter sa cannot automatically decide one use make sure actually foreignkey defined slorder table shown code example check maybe nondefault schema defined tables maybe need define one tables tableargs schema myschema just guessing i know firebird idea schema support really checkdebug reflection step sqlalchemydialectsfirebirdbasepy getforeignkeys check sql statement fkqry execute directly database see reflects foreignkey if try find,i trying set onetomany relationship existing database simplified ddl create table accnt code varchar null def varchar constraint pkaccnt primary key code commit create table slorder code varchar null def varchar dt date caccnt varchar null constraint pkslorder primary key code constraint fkslorderaccnt foreign key caccnt references accnt code update cascade delete cascade commit sqlalchemy code sqlalchemy import sqlalchemyextdeclarative import declarativebase sqlalchemyorm import engine createengine firebirdsysdbamasterkeydprjdbmakkifdbcharsetwin echofalse base declarativebase basemetadatabind engine class accntbase tablename accnt tableargs autoload true defi column def string class slorderbase tablename slorder tableargs autoload true defi columndef string accnt relationship accnt backref slorders gives sqlalchemyexcargumenterror could determine join condition parentchild tables relationship slorderaccnt specify primaryjoin expression if secondary present secondaryjoin needed well error my possible solutions problem class slorderbase tablename slorder tableargs autoload true defi columndef string caccnt columncaccnt string foreignkey accntcode accnt relationship accnt backref slorders but approach needs i add every foreign key constraint column manually leads making reflection useles because i got many columns references tables class slorderbase table table accnt metadata autoload true autoloadwithengine accnt relationship accnt backref slorders primaryjointablecaccntaccntcode this approach another consequence please see previous question so i missing what best way define relationship using reflection declarative syntax edit i figured sqlalchemy finds builds relationships child table one reference parent table but child table one reference create table slorder code varchar null def varchar dt date caccnt varchar null caccntref varchar constraint pkslorder primary key code constraint fkslorderaccnt foreign key caccnt references accnt code update cascade delete cascade constraint fkslorderaccntref foreign key caccntref references accnt code update cascade delete action error occurs so expected behavior sqlalchemy give error one relation two tables,1 use specifically useful kind queries query sessionquerymoviesfiltermoviestagsany here tags manytomany relationship name tags,say i two types objects movies tags related orm many many relationship association table indicated secondary argument relationship i want able find say movies without tags what kind query would i run achieve effect,1 spynner may help httpcodegooglecompspynner,i trying automate web application validation performed teami choosen python language although exp python limitedi done similar things past using perl now problem posting url website directs logon page made javascript from whatever little python i know i believe scrappingparsing website made javascript possible i faced issue perl well able proceed any pointers help resolving issue would highly appreciated thanks,1 there circular import code item imported action you solve problem removing import class one files replacing string containing name class explained documentation for example effects modelsmanytomanyfield effectseffect itemeffect blanktrue,i got error i understand cannot import name item in model i items these items required actions but items effect actions items djangodb import models effectsmodels import effect class typemodelsmodel name modelscharfieldmaxlength def unicodeself return selfname class itemmodelsmodel name modelscharfieldmaxlength description modelscharfieldmaxlength type modelsforeignkeytype quality modelsintegerfield effects modelsmanytomanyfieldeffectthrough itemeffect blanktrue itemrequirement modelsmanytomanyfield self itemcraft symmetricalfalseblanktrue points modelsintegerfield def unicodeself return selfname class fooditem ap modelsintegerfield class toolitem durability modelsintegerfield class itemeffectmodelsmodel item modelsforeignkeyitem effect modelsforeignkeyeffect def unicodeself return selfitemname strlowerselfeffectname class meta verbosenameplural items effects class itemcraftmodelsmodel item modelsforeignkeyitemrelatedname classsitemcrafted itemrequirement modelsforeignkeyitemrelatedname classsitemrequired number modelsintegerfield def unicodeself return selfitemname requires strlowerselfitemname selfnumber class meta verbosenameplural items crafts actions djangodb import models itemsmodels import item class actionmodelsmodel name modelscharfieldmaxlength description modelscharfieldmaxlength pa modelsintegerfield def unicodeself return selfname class craftactionaction item modelsforeignkeyitem def unicodeself return selfitemname craft class meta verbosenameplural crafts actions effects djangodb import models actionsmodels import action class effectmodelsmodel action modelsforeignkey class apeffecteffect ap modelsintegerfield,3 in xx matrix x i would expect result false true true true true true true true true true first ten x arrays zero five you get result using xanyaxisanyaxis xanyaxisanyaxis means first eliminate second axis third asix dimension remaining second axis get one dimension originally first one axis,i slight problem getting numpyany work fine problem consider i d matrix n x m x m matrix i need get rid matrix mxm elements zeros say here example illustrate issue x nparangereshape x what i need get rid first x matrix since contain zeros so i tried npanyxaxis expected results falsetruetruetruetruetruetruetruetruetrue get array true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true dtypebool applying follwing results i want i hope better way without loops rangexshape yappendnpanyxi did i make mistake somewhere thanks,2 def etreetodictt ttag mapetreetodict titerchildren dupdate k v k v tattribiteritems text ttext return call tree etreeparsesomefilexml etreetodicttreegetroot this works long actually attribute text change third line function body use different key also handle mixed content tested lxml,i looking xml dictionary parser using elementtree i already found excluding attributes case i lot attributes,3 i think add foreignkey child table by way define foreignkey assign value caccnt also assign object parent accnt internally sqlalchemy fire query wrote primaryjoin if foreign key model understand field run query you use way but i personally prefer foreignkey relation foreignkey this way write code give flexibility assign value plus object directly,i trying set onetomany relationship existing database simplified ddl create table accnt code varchar null def varchar constraint pkaccnt primary key code commit create table slorder code varchar null def varchar dt date caccnt varchar null constraint pkslorder primary key code constraint fkslorderaccnt foreign key caccnt references accnt code update cascade delete cascade commit sqlalchemy code sqlalchemy import sqlalchemyextdeclarative import declarativebase sqlalchemyorm import engine createengine firebirdsysdbamasterkeydprjdbmakkifdbcharsetwin echofalse base declarativebase basemetadatabind engine class accntbase tablename accnt tableargs autoload true defi column def string class slorderbase tablename slorder tableargs autoload true defi columndef string accnt relationship accnt backref slorders gives sqlalchemyexcargumenterror could determine join condition parentchild tables relationship slorderaccnt specify primaryjoin expression if secondary present secondaryjoin needed well error my possible solutions problem class slorderbase tablename slorder tableargs autoload true defi columndef string caccnt columncaccnt string foreignkey accntcode accnt relationship accnt backref slorders but approach needs i add every foreign key constraint column manually leads making reflection useles because i got many columns references tables class slorderbase table table accnt metadata autoload true autoloadwithengine accnt relationship accnt backref slorders primaryjointablecaccntaccntcode this approach another consequence please see previous question so i missing what best way define relationship using reflection declarative syntax edit i figured sqlalchemy finds builds relationships child table one reference parent table but child table one reference create table slorder code varchar null def varchar dt date caccnt varchar null caccntref varchar constraint pkslorder primary key code constraint fkslorderaccnt foreign key caccnt references accnt code update cascade delete cascade constraint fkslorderaccntref foreign key caccntref references accnt code update cascade delete action error occurs so expected behavior sqlalchemy give error one relation two tables,1 your parser fine something stupid main method def main data data rawinput print yaccparsedata you feeding parser reversed string data no wonder gives error seen parser just pass real data fine,i trying use python ply simple expression parser i get work the code available bitbucket offending parts first definitions def pexprminusp expr expr minus term p pp def ptermdividep term term divide factor p pp seem inverted get results second parenthesis expression factor expr work in particular part def pfactorbracketsp factor obracket expr cbracket p p function correctly parsing expression raises typeerror unknown text what source errors,1 listbox text canvas entry scrollable default canvas could work bit overkill imo something seems like want using text usrbinpython tkinter import root tk descriptionframe frameroot definitionframe labelframedescriptionframe textdefinition definitionscroll scrollbardefinitionframe definitiontext textdefinitionframe width height yscrollcommanddefinitionscrollset definitionscrollconfigcommanddefinitiontextyview definitiontextdelete end example delete current text definitiontextinsert na example add new text text area descriptionframepackfillboth expandtrue definitionframepackfillboth expandtrue definitionscrollpacksideright filly definitiontextpacksideleft fillboth expandtrue rootmainloop,root tk descriptionframe frameroot definitionframe labelframedescriptionframe textdefinition definitionscroll scrollbardefinitionframe definitioncanvas canvasdefinitionframe width height yscrollcommanddefinitionscrollset definitionscrollconfigcommanddefinitioncanvasyview definitionlabel labeldefinitioncanvas textna descriptionframepack definitionframepack definitionscrollpacksideright filly definitioncanvaspacksideleft fillboth expandtrue definitionlabelpackfillboth expandtrue rootmainloop i code the canvas set width height i run ignores width height canvas resulting window sized around label instead i tried using packpropagatefalse every single frame code affect anything definitionframe i use descriptionframe results empty window how would i create gui frames window sized canvas size width height thanks,1 a simple sqlonly solution create inmemory table using sqlite attach command special memory pseudofilename attach database memory as memdb create table memdbmytable since whole database memdb kept ram data lost close database connection take care persistence one way could open main sqlite database file attach inmemory secondary database duplicate performancecritical table inmemory database run queries duplicate table once done write inmemory table back original table begin delete from realtable insert into realtable select from memorytable but best advice i give make sure really performance problem simple solution could well fast enough,we currently working python project basically reads writes mm data intofrom sqlite database this database consists multiple tables one storing current values coming cloud this last table worrying bit since written often application runs flash drive i read virtual tables could solution i thought converting critical table virtual one link contents real file xml json stored ram tmp example debian i reading article httpdrdobbscomdatabasepgno explains less i want it quite complex i think doable using python maybe need develop sqlite extension i know any idea place conflicting table ram whilst rest database stays flash any bettersimpler approach take virtual table way python,1 what i would get user current scores front create dictionary mapping exercise score add score attribute exercise something like userscores requestuserscoresetall scoredict dictscexoid scscore sc userscores exos exerciseobjectsall ex exos excurrentuserscore scoredictgetexid now exercise exos currentuserscore attribute current user score exercise none,consider model class exercisemodelsmodel name modelscharfieldmaxlength def unicodeself return selfname class scoremodelsmodel scores users exercise exo modelsforeignkeyexercise user modelsforeignkeyuser score modelsintegerfield class meta uniquetogether exo user i template displays exercise ul exo exos li exo li endfor ul here view def viewexosrequest lists exercises objs exos exerciseobjectsall return rendertoresponse contentcontentshtml objs contextinstancerequestcontextrequest now i like display score current user front exercise one order access template manner li exo exouserscore li,1 class user modelsmodel firstname modelscharfield maxlength lastname modelscharfield maxlength fullname modelscharfield maxlength def save self args kw selffullname format firstname lastname super user self save args kw,how i query full name django to clarify i essentially want create temporary column combining firstname lastname give fullname like like select fields users concatfirstname lastname like john smith the query would return users named john smith if possible i like avoid using raw sql call the model i talking specifically stock djangocontribauthmodels user model making changes model directly problem for example user search john paul smith match users first name john paul last name smith well users first name john last name paul smith,2 you simply derive class tuple implement getitem class pointtuple def newcls x return tuplenewcls x def addself return pointself self def reprself return point formatself self p point print p point point print p point,one exercises says write add method points works either point object tuple if second operand point method return new point whose x coordinate sum x coordinates operands likewise coordinates if second operand tuple method add first element tuple x coordinate second element coordinate return new point result this far i got i sure tuple portion code accurate can someone shed light i would call program tuple portion i think i nailed first part here code class point defaddselfother isinstanceotherpoint return selfaddpointother else return selfprintpointother def addpointselfother totalx selfx otherx totaly selfy othery total totalx totaly return total def printpointself print selfx selfy blank point blankx blanky blank point blankx blanky that i built far i sure actually run tuple part i know blank blank portion would run call addpoint function i initiate tuple i sure i wrote correctly please assist,1 alternatively want able use pointx pointy syntax could implement following class point def initself x selfx x selfy def addself isinstanceother point return pointselfx otherx selfy othery elif isinstanceother tuple return pointselfx selfy else raise typeerrorunsupported operand types point formattypeother def reprself return u point formatselfx selfy remove u using python,one exercises says write add method points works either point object tuple if second operand point method return new point whose x coordinate sum x coordinates operands likewise coordinates if second operand tuple method add first element tuple x coordinate second element coordinate return new point result this far i got i sure tuple portion code accurate can someone shed light i would call program tuple portion i think i nailed first part here code class point defaddselfother isinstanceotherpoint return selfaddpointother else return selfprintpointother def addpointselfother totalx selfx otherx totaly selfy othery total totalx totaly return total def printpointself print selfx selfy blank point blankx blanky blank point blankx blanky that i built far i sure actually run tuple part i know blank blank portion would run call addpoint function i initiate tuple i sure i wrote correctly please assist,1 using python line open filename print ststs evalline course need pass oneline python script python interpreter python c eval function safe considered evil going process unverified user input function real threat use version much restrictive input import ast line open filename print ststs astliteralevalline documentation astliteraleval,i file looking like chr chr chr chr n number rows i want print like chr tab tab any one liner shell python perl,2 djangocontribauth context processor adds user variable template context referencing current user this enable get scores current user create template filter returns score particular exercise in file named exercisespy within templatetags package put package folder one apps installedapps remember templatetags must valid python package ie initpy djangotemplate import library register library registerfilter def scoreforexercisescores exercise scoresfilterexoexercise return sscore return none in template load exercises userscoresetall userscores ul exo exos userscoresscoreforexerciseexo score li exo score score endif li endwith endfor ul endwith,consider model class exercisemodelsmodel name modelscharfieldmaxlength def unicodeself return selfname class scoremodelsmodel scores users exercise exo modelsforeignkeyexercise user modelsforeignkeyuser score modelsintegerfield class meta uniquetogether exo user i template displays exercise ul exo exos li exo li endfor ul here view def viewexosrequest lists exercises objs exos exerciseobjectsall return rendertoresponse contentcontentshtml objs contextinstancerequestcontextrequest now i like display score current user front exercise one order access template manner li exo exouserscore li,1 would sedawk work awk print tt yourfilewithstuffinit sed g,i file looking like chr chr chr chr n number rows i want print like chr tab tab any one liner shell python perl,1 i tried could try using sysstdoutflush sending script sleep,i simple python script i would like run background output redirected file eg testpy outputlog amp amp this works fine long sleep statement python script usrbinenv python import sys import time time import gmtime strftime urls httpa httpb httpc httpd httpe def main true url urls try print url except exception e print error checking url url print e timesleep name main main if sleep statement uncommented output generated script run background if run foreground works fine sleep output sent console file i choose eg always works testpy outputlog my question sleep statement prevent output directed file script run background i get round,1 the output get lost simply takes long time reach file this buffering sleep takes long time output buffer accumulate enough data get flushed if call sysstdoutflush calling sleep make output appear right away sysstdoutflush timesleep,i simple python script i would like run background output redirected file eg testpy outputlog amp amp this works fine long sleep statement python script usrbinenv python import sys import time time import gmtime strftime urls httpa httpb httpc httpd httpe def main true url urls try print url except exception e print error checking url url print e timesleep name main main if sleep statement uncommented output generated script run background if run foreground works fine sleep output sent console file i choose eg always works testpy outputlog my question sleep statement prevent output directed file script run background i get round,2 perl oneliner cat filetxt perl ni e printf qqststsn g,i file looking like chr chr chr chr n number rows i want print like chr tab tab any one liner shell python perl,2 perl pe ttg yourfile trick,i file looking like chr chr chr chr n number rows i want print like chr tab tab any one liner shell python perl,2 you use elementtree api implemented python standard library lxml library it meant xml processing also use handling treestructured data general get xml serialization free,i noticed python quite lot specialities working data structures various iterators generators list comprehensions etc could advise data structures useful working trees pythonic style the nodes tree would contain data would classical operations like children siblings etc you present python special features dealing trees smart examples eg functional approach programming,1 there two parts first must enable reading formatting info opening source workbook the copy operation copy formatting import xlrd import xlutilscopy inbook xlrdopenworkbook inputxls formattinginfotrue outbook xlutilscopycopyinbook secondly must deal fact changing cell value resets formatting cell this less pretty i use following hack i manually copy formatting index xfidx def getoutcelloutsheet colindex rowindex hack extract internal xlwt cell representation row outsheetworksheetrowsgetrowindex row return none cell rowrowcellsgetcolindex return cell def setoutcelloutsheet col row value change cell value without changing formatting hack retain cell style previouscell getoutcelloutsheet col row end hack part i outsheetwriterow col value hack part ii previouscell newcell getoutcelloutsheet col row newcell newcellxfidx previouscellxfidx end hack outsheet outbookgetsheet setoutcelloutsheet test outbooksave outputxls this preserves almost formatting cell comments copied though,i using xlrd xlutilscopy xlwt open template file copy fill new values save however seem easy way preserve formatting cells always gets blown away set blank is simple way i thanks yga a sample script xlrd import openworkbook xlutilscopy import copy rb openworkbook outputtemplatexls formattinginfotrue rs rbsheetbyindex wb copyrb ws wbgetsheet icell enumeraterscol continue wswriteiplain wbsave outputxls versions xlrd xlwt,3 you use compile exec eval depending exact needs,in code i generate new python classes runtime for i want generate python code i wrote classes py file let say i created dynamically class a type a bar true equivalent code class aobject bartrue what i want generate equivalent code dynamic class i trying implement function generateacode klsa type a bar true klsagenerateacode hope helps bit thanks,1 to answer specific question stop frame container widget resizing fit contents call either packpropagatefalse gridpropagatefalse depending geometry manager using if tried working wrong since post code diagnose went wrong when call packpropagatefalse make sure widget appropriate size labels buttons default size fit text frame default size x making contents nearly invisible if using frame make sure give explicit width height,root tk descriptionframe frameroot definitionframe labelframedescriptionframe textdefinition definitionscroll scrollbardefinitionframe definitioncanvas canvasdefinitionframe width height yscrollcommanddefinitionscrollset definitionscrollconfigcommanddefinitioncanvasyview definitionlabel labeldefinitioncanvas textna descriptionframepack definitionframepack definitionscrollpacksideright filly definitioncanvaspacksideleft fillboth expandtrue definitionlabelpackfillboth expandtrue rootmainloop i code the canvas set width height i run ignores width height canvas resulting window sized around label instead i tried using packpropagatefalse every single frame code affect anything definitionframe i use descriptionframe results empty window how would i create gui frames window sized canvas size width height thanks,1 benchname string identifier need use getattr processappendgetattrmybench benchname,previously i asked question that problem solved error developing script currently option obtained command line like b b code processing import mybench optparse parseraddoptionb benchmark default helpthe benchmark loaded optionsbenchmark b process mybenchb elif optionsbenchmark b process mybenchb else print benchmark now i changed one option passed b b bb the code process benchmarks optionsbenchmarksplit benchname benchmarks print benchname processappendmybenchbenchname if notice first code process gets value like process mybenchb now i write processappendmybenchbenchname i expect command line b bb results process mybenchb process mybenchb however i get error processappendmybenchbenchname attributeerror module object attribute benchname is solution,2 for difference processb processbenchname processb getattr may key wills,previously i asked question that problem solved error developing script currently option obtained command line like b b code processing import mybench optparse parseraddoptionb benchmark default helpthe benchmark loaded optionsbenchmark b process mybenchb elif optionsbenchmark b process mybenchb else print benchmark now i changed one option passed b b bb the code process benchmarks optionsbenchmarksplit benchname benchmarks print benchname processappendmybenchbenchname if notice first code process gets value like process mybenchb now i write processappendmybenchbenchname i expect command line b bb results process mybenchb process mybenchb however i get error processappendmybenchbenchname attributeerror module object attribute benchname is solution,1 you could convert xml instance python class import lxmletree et import io class settingsobject def initselftext rootetparseiobytesiotextgetroot selfsettingsdictelttagelttext elt rootxpath settings def updateselfother selfsettingsupdateothersettings text xml version encodingutf settings pathasomepathtodirectorypatha pathbanotherpathpathb settings text xml version encodingutf settings pathbchangethispathpathb settings ssettingstext ssettingstext supdates printssettings yields pathb changethispath patha somepathtodirectory,i writing application configuration module uses xml files consider following example xml version encodingutf settings pathasomepathtodirectorypatha pathbanotherpathpathb settings now i like override certain elements different file gets loaded afterwards example override file xml version encodingutf settings pathbchangethispathpathb settings when querying document overrides xpath i like get element tree xml version encodingutf settings pathasomepathtodirectorypatha pathbchangethispathpathb settings this similar python configparser read method done xml how i implement,1 look docs networkx python toolkit handling graphbased data structures including trees,i noticed python quite lot specialities working data structures various iterators generators list comprehensions etc could advise data structures useful working trees pythonic style the nodes tree would contain data would classical operations like children siblings etc you present python special features dealing trees smart examples eg functional approach programming,1 the problem mylist mylistmaxlen creates new list instead modifying mylist place results never propagate back et al if replace mylist mylistmaxlen mylist mylistmaxlen fix as aside could use itertools transformation in v v itertoolsisliceitertoolscyclea maxlen out,i want build lists b c extending periodically given input the structure periodicity first element list must repeated elements must maximum length set input reached possible period get repeated integer number times to give example i input maxlen i want obtain output i wrote piece code mylist b c period mylist elements first repeated lenmylist maxlen mylistextendperiod mylist mylistmaxlen cut maxlen print mylist print b c if i run i see two print commands lists i want program still loop get back nonsliced length loop gets back length greater maxlen period repeated exactly times why it looks like program forgotten slicing extension i understand pretty simple problem i could get around way i would like understand idea work thank help,3 yahoo decent documentation access apis python the information tell access yahoo apis yql http requests this means directly performing http gets posts parsing results however also python library wraps calls updated since mileage may vary,is official way import contacts user address book yahoo for google really simple import gdata contactsservice gdatacontactsservicecontactsservice contactsserviceemail email contactsservicepassword password contactsserviceprogrammaticlogin query gdatacontactsservicecontactsquery querymaxresults googlecontactsmaxresults entries contactsservicegetcontactsfeedquerytouri is simple way yahoo i found solutions use api looks strange serious game example contactgrabber i found solutions require bbauth token djangofriends app but i want official clear way grab user contacts yahoo does exists upd finally i avoiding use yahoo api using djangoopeninviter purposes but i still looking examples importing user contacts using api,1 mylist loop starts referring one input lists assign rebinding name mylist new list modifying original list this would work mylist b c period mylist elements first repeated lenmylist maxlen mylistextendperiod mylist mylistmaxlen cut maxlen print mylist print b c the slice assignment updates original list or could try updating original list mylist b c mylist mylist maxlenlenmylistmaxlen printmylist print b c,i want build lists b c extending periodically given input the structure periodicity first element list must repeated elements must maximum length set input reached possible period get repeated integer number times to give example i input maxlen i want obtain output i wrote piece code mylist b c period mylist elements first repeated lenmylist maxlen mylistextendperiod mylist mylistmaxlen cut maxlen print mylist print b c if i run i see two print commands lists i want program still loop get back nonsliced length loop gets back length greater maxlen period repeated exactly times why it looks like program forgotten slicing extension i understand pretty simple problem i could get around way i would like understand idea work thank help,1 perl ne say eval filetxt making use perl output record separator provide tabs eval safe use single quoted strings probably best option,i file looking like chr chr chr chr n number rows i want print like chr tab tab any one liner shell python perl,3 errors pass silently if ask printing message instead raising exception situation counts “silently” calling exit worse – time function called matter deep imported library malformed request kill program the pythonic alternative printing message ignoring erorr calling exit let caller code catch exception deal you need exception handling function if need distinguish parse errors object creation errors raise custom parseerror objectcreationerror let caller deal as answers suggest block ends raise exit return need indented else block,i code like try requestparserequest except print cannot parse malformed request exit else try fhafactoryfunction except print cannot create object else request operation search pass elif request operation morelikethis pass elif request operation listfiles pass elif request operation update pass else print unsupported operation in present form two levels indentation parse request factory function generate object process request i easily imagine getting levels becoming complex puny reasoning is pythonic way flatten indentation make linear,1 another option simply store exception want lose python x version try filepath whateverjpg stuff file except baseexception e try osunlinkfilepath except exception tracebackprintexc raise e the python x version slightly complex since need store complete exception information manually otherwise lose traceback try filepath whateverjpg stuff file except e sysexcinfo try osunlinkfilepath except exception tracebackprintexc raise e e e edit only catch subclasses exception inner try block since want catch systemexit keyboardinterrupt also report excpetion occurred unlinking instead dropping,i need file deleted operations must done successful exception raised it could simple using except deleting file reraising exception case original exception would lost file cannot deleted except clause whatever arcane reason the best i able come try filepath whateverjpg stuff file except exceptionraised true raise finally try exceptionraised osunlinkfilepath except pass return filepath everything ok does anybody know better pythonic approach,3 remove line says selfgrabset a grab means grab events direct toward window want if read bit deeper web page got code see mentions exact line next constructor creates dialog body calls grabset make dialog modal,i using class called customdialog based based httpeffbotorgtkinterbooktkinterdialogwindowshtm the standard code creates class subclasses toplevel creates modal dialogs i trying adapt code also create modeless dialogs the standard code calls toplevel constructor creates dialog selfwaitwindowself end waits dialog window dismissed but i succeeding my naive attempt simply skip waitwindow attempt code snipped i tried things dialog remains modal i interact application main window what forcing modal the dialogs contain widgets buttons typically class dialogtoplevel def initself parent title nonemodaltrue toplevelinitself parent selftransientparent title selftitletitle selfparent parent selfresult none body frameself register validators selfvalidateposint bodyregisterselfonvalidateposint p s v v w selfinitialfocus selfbodybody calls body function overridden draws dialog bodygrid selfbuttonbox selfgrabset selfinitialfocus selfinitialfocus self selfprotocolwmdeletewindow selfcancel selfgeometrydd parentwinforootx parentwinforooty selfinitialfocusfocusset modal selfwaitwindowself,2 lo i quote pep wise words considered law upon topic pep saith write docstrings public modules functions classes methods docstrings necessary nonpublic methods comment describes method this comment appear def line,in python designate internal function private methonds underscore beginning should functions documented docstringsis required formal documentation mean one helping codereader understand code what common practice,3 unless i misinterpreting code using else clause try statement normal processing in effect simulating return code error handling exceptions why try requestparserequest fhafactoryfunction except malformedrequesterror print cannot parse malformed request exit except createobjecterror print cannot create object exit request operation search pass elif request operation morelikethis pass elif request operation listfiles pass elif request operation update pass else print unsupported operation there good answer blair conrad stackoverflow explains might want use else clause,i code like try requestparserequest except print cannot parse malformed request exit else try fhafactoryfunction except print cannot create object else request operation search pass elif request operation morelikethis pass elif request operation listfiles pass elif request operation update pass else print unsupported operation in present form two levels indentation parse request factory function generate object process request i easily imagine getting levels becoming complex puny reasoning is pythonic way flatten indentation make linear,1 the thing pythonic code using spaces indentation “pythonic” always mean “concise” example following shorter less readable loop setattre someattr somevalue e somelist somecondition so stick code,how i following concise pythonic way element somelist somecondition elementsomeattr somevalue,1 the second line pixels s you probably tuple named pixel tuples immutable construct new pixels instead image imageopen balloonjpg pixels pix pix pix imagegetdata imageputdatepixels,i using pil library i trying make image look reder got pil import image image imageopen balloonjpg pixels listimagegetdata pixel pixels pixel pixel imageputdatapixels imagesave newbmp however i get error typeerror tuple object support item assignment,3 tuples python values changed if like change contained values though i suggest using list,i using pil library i trying make image look reder got pil import image image imageopen balloonjpg pixels listimagegetdata pixel pixels pixel pixel imageputdatapixels imagesave newbmp however i get error typeerror tuple object support item assignment,1 pil pixels tuples tuples immutable you need construct new tuple so instead loop pixels pixel pixel pixel pixel pixels imageputdatapixels also pixel already red adding overflow value you probably want something like minpixel int pixel instead pixel and able handle images lots different formats image imageconvertrgb opening image the convert method ensure pixels always r g b tuples,i using pil library i trying make image look reder got pil import image image imageopen balloonjpg pixels listimagegetdata pixel pixels pixel pixel imageputdatapixels imagesave newbmp however i get error typeerror tuple object support item assignment,3 you probably want next transformation pixels pixels maplist imagegetdata,i using pil library i trying make image look reder got pil import image image imageopen balloonjpg pixels listimagegetdata pixel pixels pixel pixel imageputdatapixels imagesave newbmp however i get error typeerror tuple object support item assignment,1 if use numpy numpyrandommultivariatenormalmean cov size for example get d samples nprandommultivariatenormalmean cov meanshape covshape,i generate gaussian data randomgaussmu sigma function i generate d gaussian is function like,3 there also skiptest plugin nosetest cause test show test output skipped here decorator def skippedfunc nosepluginsskip import skiptest def raise skiptesttest skipped funcname name funcname return example output nosetests tests s ran tests ok skip,when using nosetests python possible disable unit test setting test function test attribute false i implemented using following decorator def unittestdisabled def wrapperfunc functest false return func return wrapper unittestdisabled def testmysampletest code however side effect calling wrapper unit test wrapper always pass included nosetests output is another way structuring decorator test run appear nosetests output,3 since standard d gaussian distribution product two d gaussian distribution correlation two axes ie covariant matrix diagonal call randomgauss twice,i generate gaussian data randomgaussmu sigma function i generate d gaussian is function like,3 for example dllmain call dllthreadattach flag see msdn update i found link similar problem dll load poisons fpu control word new threads but yes threads created dll load,i bit windows application written primarily delphi performs floating point numerical simulations using fpu i recently added ability link external python code using python api pythonxdll this recent change led strange behaviour the application batch mode operation performs multiple simulations parallel take advantage multicore architectures as soon python code executed process i start see changes control word different threads i checked carefully i observed control word changed even thread never called python dll i know sounds fantastical i discovered mechanisms behaviour manifest i learnt signals i first hypothesised python dll setting process wide signal handlers calling signal signal handlers responsible changing control word for example thread unrelated python code could perhaps cause sigfpe may turn modify control word i rather come conclusion signal mechanism i arranged execute python code startup then i set signal handlers back sigdfl then i started simulations but still control word changes occurred my question finally whether anyone knows another mechanism control word could changed manner i looking interrupts apcs etc i think update the control word changed xf intel default value this differs msvcwindows default xf i hypothesise something calling fpinit i also discovered pyinitializeex allows caller stop python setting signal handlers the control word changes occur even i use approach initialisation i even convinced mechanism,3 if i remember correctly delphi problem there discussions issue i remember bumping trying write vst plugins delphi,i bit windows application written primarily delphi performs floating point numerical simulations using fpu i recently added ability link external python code using python api pythonxdll this recent change led strange behaviour the application batch mode operation performs multiple simulations parallel take advantage multicore architectures as soon python code executed process i start see changes control word different threads i checked carefully i observed control word changed even thread never called python dll i know sounds fantastical i discovered mechanisms behaviour manifest i learnt signals i first hypothesised python dll setting process wide signal handlers calling signal signal handlers responsible changing control word for example thread unrelated python code could perhaps cause sigfpe may turn modify control word i rather come conclusion signal mechanism i arranged execute python code startup then i set signal handlers back sigdfl then i started simulations but still control word changes occurred my question finally whether anyone knows another mechanism control word could changed manner i looking interrupts apcs etc i think update the control word changed xf intel default value this differs msvcwindows default xf i hypothesise something calling fpinit i also discovered pyinitializeex allows caller stop python setting signal handlers the control word changes occur even i use approach initialisation i even convinced mechanism,1 either matt said comment binzfill use format strings python b format you omit first zero python implicitly number groups,i looking convert dec number bit binary number bin works fine omits leading zeros important example etc largest dec number allowed,3 the problem case due dynamic models creation order more specifically models dynamically created others defined meta caches filled therefore lead errors clearing caches changing creation order resolves problem see also httpsgroupsgooglecomdmsgdjangousersrjlvribzkptvqljnej,just updating django come across odd error i getting following error code works version fielderror cannot resolve keyword emailconfigset field choices id name site type the odd thing emailconfigset related name manytomany field i sure django trying resolve field the error occurs deep inside django traceback recent call last file coredriverpy line run selfinitnorm file driveremaileventbackgroundpy line initnorm selfloadconfig file driveremaileventbackgroundpy line loadconfig events listconfigeventsselectrelated file usrlocallibpythonsitepackagesdjangopyeggdjangodbmodelsmanagerpy line selectrelated return selfgetquerysetselectrelatedargs kwargs file usrlocallibpythonsitepackagesdjangopyeggdjangodbmodelsfieldsrelatedpy line getqueryset return superclassgetquerysetselfusingdbnextisstickyfilterselfcorefilters file usrlocallibpythonsitepackagesdjangopyeggdjangodbmodelsquerypy line filter return selffilterorexcludefalse args kwargs file usrlocallibpythonsitepackagesdjangopyeggdjangodbmodelsquerypy line filterorexclude clonequeryaddqqargs kwargs file usrlocallibpythonsitepackagesdjangopyeggdjangodbmodelssqlquerypy line addq canreuseusedaliases forcehavingforcehaving file usrlocallibpythonsitepackagesdjangopyeggdjangodbmodelssqlquerypy line addfilter negatenegate processextrasprocessextras file usrlocallibpythonsitepackagesdjangopyeggdjangodbmodelssqlquerypy line setupjoins choices name joinnames fielderror cannot resolve keyword emailconfigset field choices id name site type any pointers tips would welcome,1 your approach using two antiparallel edges works if edge ab capacity send introduce new residual edge b residual capacity residual edge b remaining capacity the original backedge b left new residual edge original backedge melt one edge i could imagine adding residual capacity original backedge bit simpler sure,i trying solve maxium flow problem graph using ford–fulkerson algorithm the algorithm described directed graph what graph undirected what i done mimic undirected graph use two directed edges pair vertices what confuses should edges residual edge opposite directed edge residual edge i assumed last algorithm seems go infinite loop i hope give help below implementation i using dfs find import sys import fileinput class vertexobject def initself name selfname name selfedges def findself sink path ifself sink return path edge selfedges residual edgecapacity edgeflow ifresidual edgeinf ifedge path edgeoppositeedge path tovertex edgetovertex pathappendedge result tovertexfindsink path result none return result class edgeobject def initself fromvertex tovertex capacity selffromvertex fromvertex selftovertex tovertex selfcapacity capacity selfflow selfinf false ifcapacity selfinf true def reprself return selffromvertexnamestrip selftovertexnamestrip def buildgraphvertices edges edge edges sourcevertex verticesintedge sinkvertex verticesintedge capacity intedge edge edgesourcevertex sinkvertex capacity edge edgesinkvertex sourcevertex capacity sourcevertexedgesappendedge sinkvertexedgesappendedge edgeoppositeedge edge edgeoppositeedge edge def maxflowsource sink path sourcefindsink path none mincap sysmaxint e path ifecapacity mincap einf mincap ecapacity edge path edgeflow mincap edgeoppositeedgeflow mincap path sourcefindsink return sumeflow e sourceedges vertices edges parse buildgraphvertices edges source vertices sink verticeslenvertices maxflow maxflowsource sink,3 the cycle replace content pixel creates new instance tosses away you create new array example newdata pixel pixel pixel pixel pixels,i trying import image manipulate rgb colors this got pil import image image imageopen grapesjpg pixels listimagegetdata pixel pixels pixel pixel pixel pixel imageputdatapixel imagesave grapesmodifiedjpg see trying reduce red channel this work it produces exact duplicate imported image even something like pixel it would produce duplicate image modify image thanks,2 it different one after one special some class attributes instance attributes inherited doc initialized class created also pass dict argument type constructor the special syntax works string literals need variable docstring set explicitly class someclassobject doc this class format name also set class created class set instance created ie new setattr friends inherited object,when builtin attributes initialized doc name i guess i know one class setattr etc in question regarding docstrings one answers mentioned docstrings simple strings i tried worked but i used variable assigned string value put variable place docstring work that i started wondering doc attribute get initialized edit this i tried interpreter yes crazy i wierd d docstr says hello world class helloworld def say docstr printhello world hw helloworld hwsaydoc class anotherhelloworld def initself docstrsays hello world selfdocstr docstr def sayself selfdocstr printhello world ahw anotherhelloworldscream hello world ahwsaydoc class yetanotherhelloworld def initself docstrstill say hello world selfdocstr docstr def sayself sselfdocstr printhello world again,1 you might find discussion reddit informative,what good easy way distribute web application server bundled together python way so i say user here take tarwhatever unpack run blahblahpy blahblahpy run httpwsgi server serve application im looking stable productionready multithreaded wsgiserver i bundle app without need nginx frontends deal configuration,1 use dictupdate method copy defaults defaults dicta b c result dictdefaults copy defaults resultupdaterequest update values this allows keep defaults class attribute module global variable probably want you also combine last two lines result dictdefaults request for another solution see kevin answer,i parsing json requests using json library parses python dictionary as requests usergenerated i need fix default values parameters supplied other languages stuff like ternary operators make sense repetitive applications but code needs lines per parameter searchterm requestkeys searchtermrequest searchterm else searchterm start requestkeys startrequest start else start rows requestkeys rowsrequest rows else rows is pythonic way reduce lines code make readable edit both top answers equally useful i used different circumstances,3 you use dictionary method get whose second argument default value return value exists dictionary start requestget start,i parsing json requests using json library parses python dictionary as requests usergenerated i need fix default values parameters supplied other languages stuff like ternary operators make sense repetitive applications but code needs lines per parameter searchterm requestkeys searchtermrequest searchterm else searchterm start requestkeys startrequest start else start rows requestkeys rowsrequest rows else rows is pythonic way reduce lines code make readable edit both top answers equally useful i used different circumstances,3 cherrypy act wsgi container,what good easy way distribute web application server bundled together python way so i say user here take tarwhatever unpack run blahblahpy blahblahpy run httpwsgi server serve application im looking stable productionready multithreaded wsgiserver i bundle app without need nginx frontends deal configuration,1 a fatal error induced calling pyfatalerror bids farewell explanatory message calls abort,i embedding python c dll ultimately i put xll when setup wrong pyinitialize documented terminally failing see httpdocspythonorgcapiinithtml fatal error initialization fails is possible catch error thinking maybe global windows hook,1 python dictionaries get function takes default parameter check so something like paramsget searchterm paramsget someotherfield edit you probably want go update solution petr,i parsing json requests using json library parses python dictionary as requests usergenerated i need fix default values parameters supplied other languages stuff like ternary operators make sense repetitive applications but code needs lines per parameter searchterm requestkeys searchtermrequest searchterm else searchterm start requestkeys startrequest start else start rows requestkeys rowsrequest rows else rows is pythonic way reduce lines code make readable edit both top answers equally useful i used different circumstances,1 you reduce although order calls lefttoright def fa return def fa return def fa return def callaf return fa reducecall f f f f f f reducecall lambda x x abs,some time ago i looked haskell docs found functional composition operator really nice so i implemented tiny decorator functools import partial class compfuncpartial def lshiftself f lambda args kwargs selffuncyargs kwargs return compfuncf def rshiftself f lambda args kwargs yselffuncargs kwargs return compfuncf def composablef return compfuncf composable def fx return x composable def fx return x composable def fx return x composable def fa return print f f f print f f print f f the problem without language support use syntax builtin functions lambdas like lambda x x abs the question useful does worth discussed python mail list,3 awk f begin ofst print file,i file looking like chr chr chr chr n number rows i want print like chr tab tab any one liner shell python perl,1 take look stackoverflow thread how i get thread safe print python apparently printing sout threadsafe if turn verbose threading see better threadingthreadtargetecho argsc verbosetruestart i get output like mainthread threadthread initialstart starting thread thread threadthread started bootstrap thread started mainthread threadthread initialstart starting thread thread threadthread started bootstrap thread started mainthread threadthread initialstart starting thread thread threadthread started bootstrap thread started mainthread threadthread started join waiting thread stops b thread threadthread started bootstrap normal return thread threadthread started bootstrap normal return mainthread threadthread stopped join thread stopped mainthread threadthread started join waiting thread stops thread threadthread started bootstrap normal return mainthread threadthread stopped join thread stopped c you see thread shown finishing printing c character this clearly cannot case leads assume printing console threadsafe this however explain printing sysstderr appears work correctly,if print replaced print sysstderr effect vanishes import random sys time import threading lock threadinglock def echos timesleeperandomrandom instead threadingtimer lock print c abc threadingthreadtargetecho argscstart example run empty line found python examplepy amptee outgrep echo n donecat output b c the output contain empty lines i understand print threadsafe i would thought lock help the question happens my machine python mplatform linuxgenericxwithubuntunatty extra lines printed py py pypy py py py py behave expected empty lines variations sysstdoutflush print solve problem lock prints sysstdoutflush even strange ordinary sysstdoutwrite produce empty lines lock lock sysstdoutwrites sysstdoutwrite n note flush print function works expected empty lines to reproduce download files run tox,2 the documentation states safe bug relative security literaleval bug tracker probably assume safe also according source literaleval parses string python ast source tree returns literal the code never executed parsed reason security risk,are known ways astliteralevalnodeorstring evaluation actually safe if yes patches available i already know pypysandbox presumably secure unless answers yes needs minor enough i going far,3 you pass keyword arguments filter kwargs filterfield filtervalue alertobjectsfilterkwargs,i function accepts two parameters filterfield filtervalue i want filter model like alertobjectsfilterfilterfieldfiltervalue however i get following error cannot resolve keyword filterfield field choices is way pass string stored filterfield literal string filterfield,2 the output need either tmpmycronlog mailed root type mail root check also trying different variations the syntax crontab files strictly defined man crontab s etccrontab min hour day month weekday user cmdline personal crontabs min hour day month weekday cmdline you omit user name etccrontab neither use usrbinpython place user name you also need word command works builtin bash function name apparently runs command arguments the correct line must either root pathtomyscriptmanagepy mycommand amp tmpmycronlog root usrbinpython pathtomyscriptmanagepy mycommand amp tmpmycronlog in first case managepy must executable chmod x managepy first line must usrbinpython whatever python interpreter path,i trying run django management command via crontab installed etccrondmycron ubuntu i first tested basic setup writing following etccrondmycron root command echo test date amp tmpmycronlog and i confirmed tmpmycronlog updated minute contains expected text i tried following variations using actual management command root command python pathtomyscriptmanagepy mycommand amp tmpmycronlog root command usrbinpython pathtomyscriptmanagepy mycommand amp tmpmycronlog root command pathtomyscriptmanagepy mycommand amp tmpmycronlog python pathtomyscriptmanagepy mycommand amp tmpmycronlog pathtomyscriptmanagepy mycommand amp tmpmycronlog usrbinpython pathtomyscriptmanagepy mycommand amp tmpmycronlog and even though log file generated contains none expected logging text management command outputs after variation i run sudo touch etccrond reload cron even error python code i expect sort error message get logged i checked tail f varlogsyslog errors shows crontabs start root gives error error bad username reading etccrondmycron for others i see something like oct localhost cron root cmd pathtomyscriptmanagepy mycommand amp tmpmycronlog but nothing written log database changes i expect happen occuring what i wrong,2 finally made import collections def countchstrng dcollectionsdefaultdictint letter strng dletter print sortedditems this solutionnow ask solutions problemi would love see code,i beginner python trying solve questions lists i got stuck one problem i able solve write function countlettersword takes word argument returns list counts number times letter appears the letters must sorted alphabetical order ex countletters google e g l i able count occurrences every character for sorting i using sortedlist i also using dictionaryitems functions format outputtuples list but i able link things,1 your intuition use itertoolsgroupby correct key group groupbycolumn count sum item group thanks jbernardo key column count number items alternatively need counts simple collections import counter python groupcounts countercolumn you implement counter collections import defaultdict groupcounts defaultdictint item column groupcountsitem older versions python,i trying loop column access table using python the column i sorted ascending i trying loop though rows value column changes i want get count values in example column first group values i want count m when next row changes m i want count m changes mb i want use else statement hundred different possible values i played around groupby function itertools module i able solve syntax work example i also tried silly loop something like row rownext dosomething blew face if anyone suggest workaround show sample script i appreciate example column m m m m m mb mb s sb sb o o o o,2 the best answer i found far bug python httpbugspythonorgissue the intepreter seems call exit certain errors rather passing code back caller not friendly embedding python app but go,from vba vb i calling dll creates python interpreter if i set path environment variable point cpython pythonpath cpythonlib fine if i set path calling pyinitialise crashes xl vb app even i call pysetprogramname cpythonpythonexe first i like specify installation vbvba rather set environment i xl works ok vb,2 here working code the trick module operator used draw scale number axis axis number close hundred there minor problems code variable names def histogramlenghts xmax maxlenghtskeys ymax maxlenghtsvalues symbol indexing step j rangeymax step j step symbol formatj else symbol format fill histogram range xmax lenghtskeys lenghtsi j symbol else symbol printsymbol xaxis symbol format range xmax symbol printsymbol indexing xaxis indexing range xmax indexing formati printindexing lenghts histogramlenghts,want put values yaxis histogram made i want every values example put etc my code def histogramlenghts xmaxmaxlengthskeys ymaxmaxlenghtvalues symbol indexing j rangeymax symbolformat v rangeymaxhere try put values printformatv fill histogram rangexmax lengthskeys lengthsij symbol else symbol printsymbol xaxis symbolformat rangexmax symbol printsymbol indexing xaxis rangexmax indexingformati printindexing return i getting values values example i figure right,1 use len finds length object x computer xlenx p apy x computer print x print lenx python apy computer,i started learning python first language i know next nothing come across problem find midpoint word point using caret example computer thanks tips anyone could give,3 the python profiler provide quite bit information python cprofile fooprof myscriptpy you load results using simple script usrbinenv python import pstats p pstatsstats fooprof pstripdirssortstatsprintstats alternatively specify fooprof results printed stdout see documentation httpdocspythonorglibraryprofilehtml i sure aspects wanting count determine many times function called if interested frequency calls find average frequency function total execution time number times function called for example suppose foo called times seconds the average frequency calls second,is tool able measure frequency function calls project counts aspects statistics purposes python code thank,1 text computer printtext print format lentext tells format replace replace first argument gets replaced second argument lentext tells format center text make total width equal lentext so docs full specs format,i started learning python first language i know next nothing come across problem find midpoint word point using caret example computer thanks tips anyone could give,1 replace keyfirstchildwholetext new text either keyfirstchildreplacewholetextnew text keyfirstchilddata new text the key xmldomminidomtextwholetext data descriptor meant used like function like attribute in fact collects data nearby text cdata nodes addition data unfortunately setter seem getting called writing wholetext overriding function the writexml implementation however looks data attribute wholetext this could seen bug in fact someone could probably link replacewholetext setter wholetext property may bypass magic module uses work older versions python,i xml file i read python i want make changes xml file write back here code xmldomminidom import filename filexml dom xmldomminidomparsefilename dicts domgetelementsbytagnamedict dict dictlist keys dictgetelementsbytagnamekey key keys keycdata keyfirstchildwholetext keycdata kind print keycdata prints kind keyfirstchildwholetext new text print keyfirstchildwholetext prints new text f opentempxml w domwritexmlf fclose when i open tempxml look though elements key tag still cdata kind instead new text so i get new data written file,1 the code i perfectly fine except i calling elementtreeiterparse file object i already read elementtreeparse d oh so happen make mistake solution either open new file object use fileseek reset file cursor,import xmletreeelementtree et xmldata file myxmlfilexml tree etparsexmldata root treegetroot rootiter rootiter now i call rootiternext get element objects the problem real file i working huge i fit memory so i trying use parseiter etiterparsexmldata if i call parseiternext raises following traceback recent call last file pyshell line module parseiternext file cpythonlibxmletreeelementtreepy line next selfroot selfparserclose file cpythonlibxmletreeelementtreepy line close selfraiseerrorv file cpythonlibxmletreeelementtreepy line raiseerror raise err parseerror element found line column what i wrong,2 if want add printing loop work following may helpful collections import counter defaultdict colcounts counter defaultdictint lastvalue object show table row accesstable colcountsrowfield rowfield lastvalue printcolcountslastvalue lastvalue rowfield otherprocessing,i trying loop column access table using python the column i sorted ascending i trying loop though rows value column changes i want get count values in example column first group values i want count m when next row changes m i want count m changes mb i want use else statement hundred different possible values i played around groupby function itertools module i able solve syntax work example i also tried silly loop something like row rownext dosomething blew face if anyone suggest workaround show sample script i appreciate example column m m m m m mb mb s sb sb o o o o,1 simple way use parse file regular expression could work azsaz list list string aka a b c f g r convert list format must like a b c abc remove spaces one convertedstringlist liststrlist print convertedstringlist result list like one string like adf a d f merge list find duplicates straigh forward solution i sure better solution exists,i need find number times entry list repeats consecutively for example consider following file hello hello a b c world d c f l tick tock a l in file number times c repeats a repeat counted repeating consecutively i sure using wouldnt tell repeats consecutively any help would apprecited,1 try pythonpython fileuploaderpy backupsql,i script i using time easily upload files server it working great long time i get work new desktop computer the code simple import ospath import sys import os ftplib import ftp host acc pw filepath sysargv ospathisfilefilepath x inputerror invalid filepath exit filename ospathbasenamefilepath fileobject openfilepath rb ftp ftphost ftploginacc pw ftpstorbinary stor filename fileobject ftpquit fileobjectclose i run fileuploaderpy backupsql i get following error traceback recent call last file cusersadmindesktopfileuploaderpy line filepath sysargv indexerror list index range i sure giving error find first commandline argument even though i passed one script i running windows bit python thanks,1 you need map select desired columns mapping join causes sqlalchemy turn corresponding select join skip block creates test fixture sqlalchemyorm import mapper sessionmaker sqlalchemysql import join select sqlalchemy import engine createenginepostgresqlusernamelocalhostdbname engine createenginesqlitememory engineexecuter create table userprofile id integer primary key fieldid integer keep integer discard integer sqlalchemyenginebaseresultproxy object xd engineexecuter create table profilefield id integer primary key fieldid integer keep integer discard integer sqlalchemyenginebaseresultproxy object xe metadata metadataengine session sessionmakerengine profiles table userprofile metadataautoloadtrue profilefields table profilefield metadataautoloadtrue engineexecuteprofilesinsert fieldid keep discard sqlalchemyenginebaseresultproxy object xe engineexecuteprofilefieldsinsert fieldid keep discard sqlalchemyenginebaseresultproxy object xed class dbobjobject def reprself return dbobj strselfdict j joinprofiles profilefields profilescfieldidprofilefieldscfieldid here new part js selectprofilescid profilesckeep profilefieldsckeep profilescfieldid profilefieldscfieldid uselabelstrue fromobjj mapperdbobjaliasjsproperties fieldid profilescfieldidprofilefieldscfieldid mapper xead dbobj q sessionquerydbobjall q dbobju userprofilekeep u userprofileid sainstancestate sqlalchemyormstateinstancestate object xfd fieldid u profilefieldkeep,i started using sqlalchemy work existing postgres db what i like autoload two tables perform inner join map subset columns object to accomplish last part i written following code sqlalchemyorm import mapper sessionmaker sqlalchemysql import join select engine createenginepostgresqlusernamelocalhostdbname metadata metadataengine session sessionmakerengine profiles table userprofile metadataautoloadtrue profilefields table profilefield metadataautoloadtrue class dbobjobject pass j joinprofilesprofilefieldsprofilescfieldidprofilefieldscfieldid mapperdbobjjproperties fieldid profilescfieldidprofilefieldscfieldid q sessionquerydbobjall how i modify code assert i want specified columns mapped dbobj i searched far wide seem find example accomplish,1 your py association registry incorrect it missing end,i script i using time easily upload files server it working great long time i get work new desktop computer the code simple import ospath import sys import os ftplib import ftp host acc pw filepath sysargv ospathisfilefilepath x inputerror invalid filepath exit filename ospathbasenamefilepath fileobject openfilepath rb ftp ftphost ftploginacc pw ftpstorbinary stor filename fileobject ftpquit fileobjectclose i run fileuploaderpy backupsql i get following error traceback recent call last file cusersadmindesktopfileuploaderpy line filepath sysargv indexerror list index range i sure giving error find first commandline argument even though i passed one script i running windows bit python thanks,2 you don’t put anything datafiles the arguments distutilscoresetup pymodules packages datafiles etc control built installed distribute additional file use manifestin file httpdocspythonorgdevdistutilssourcedistspecifyingthefilestodistribute there copying file python files tests anything installed,i simple pure python project i want make available distutils i successfully created compressed tar files python modules license text files these relevant parts setuppy setup argument list packages pkga pkgasubpkga pkgasubpkga requires matplotlib pytest datafiles copying copyinglesser the problem also puts license files distribution directly sysprefix i would like ship license files source distribution install python setuppy install run i currently manifestin file post build actions,1 doxygen great c working mostly python code give sphinx try if choose sphinx need follow pep,i know parameters object documentation quite important specify would expect first specify parameter types like str use string string int list dict function tuple object instance class myclass second specify params multiple types like function handle single parameter int str please use example demonstrate syntax needed documenting proposed solution mind desired able hyperlink reference image class inside documentation def mymethodself name image does something name string name image image image instance image class string indicating filename return true operation succeeded false return true note welcome suggest usage documentation tool sphinx oxygen long able deal requirements update it seams kind support documenting parameter types doxygen general the code works adds annoying param name initially made php param str arg description param strint arg description,1 django uses wsgi natively running fastcgi adds another layer http messages travel having said choice quick fastcgi container slow wsgi container may better living extra layer,two configurations i need know difference better faster first conf homeuserbinpython import sys os syspathinserthomeuserprojects osenviron djangosettingsmodule djangoprojectsettings flupserverfcgi import wsgiserver djangocorehandlerswsgi import wsgihandler wsgiserverwsgihandlerrun second conf homeuserbinpython import sys os syspathinserthomeuserprojects osenviron djangosettingsmodule djangoprojectsettings djangocoreserversfastcgi import runfastcgi runfastcgimethodthreaded daemonizefalse thanks d update i quick test python cprofile lib in doc wsgi corresponds first conf fcgi corresponds second conf,1 the example given question uses neither superclass instance variable from title question presumably wanted use here example would work class aobject def initself selfvar class ba def initself superbselfinit selfvar print avar print bvar note example simply assigns attributes unrelated classes using classes sortof like namespaces which perfectly reasonable quite asked class a var class b var avar print avar print bvar,is way python something like class a var class b var instance b instancevar,2 append replace replace expression includes original class aobject var class ba var avar instance b instancevar that simple uses interesting solution might use descriptor the easy way use property class aobject var class ba subvar property def varself return superb selfvar selfsubvar instance b instancevar which works instances b b first example to get back must implement descriptor class appenderobject def initself cls attr selfcls cls selfattr attr def getself instance owner var superselfcls ownervar return var getattrselfcls selfattr class ba realvar bvar appenderb realvar which works equally well class instances class,is way python something like class a var class b var instance b instancevar,1 edit answer question somewhat changed significantly general it would still useful asker would tell us kinds objects values backup the scipyiosavemat apparently take dictionary dictionaries arrays structure numpy import array import scipyio data bigdata array b array c array scipyiosavemat testmat data loads matlab load testmat bigdata bigdata x int c x int b x int i imagine dictionaries nested python recursion limit since implementation recursive i tested levels nesting dictionaries edit now asking structure like data key apple b banana key c crabapple dragonfruit specified apple banana etc it depends data python objects want matlab objects i tested classes like str converted char array set failed convert array list array homogeneous character array strings numbers the code looks pretty ducktypeish objects common dataholding interface get i present excerpt relevant bit matlab version def towriteablesource isinstancesource npndarray return source source none return none objects dicts hasattrsource dict source dictkey value key value sourcedictitems keystartswith mappings object dicts hasattrsource keys dtype values field value sourceitems isinstancefield basestring field dtypeappendfieldobject valuesappendvalue dtype return nparray tuplevalues dtype else return none next try convert array narr npasanyarraysource narrdtypetype npobject npobject narrshape narr source no interesting conversion possible return none return narr code recursive write function calls function,i complex data structure data temp data bigdata temp after i copy key data values data structure temp like key backupkeys tempkey key backupkeys val backupkey tempkeyappendval after if i siosavematoutputmatfiledataonedas column giving error saying ttypeerror data type understood is possible store complex dictionary like matlab file using python,3 the python ssl library seems like parses cert valid signature returns formatted version data certificate provided end ssl channel return none certificate provided certificate provided validated you still get server certificate sslgetservercertificate function returns pem format alternatively could call cgetpeercerttrue returns cert binary der format whether validated print sslgetservercertificate servertestcom begin certificate miidzccasugawiba from i would use mcrypto openssl read cert get values mcrypto cert sslgetservercertificate wwwgooglecom x mcryptoxloadcertstringcert xgetsubjectastext cus stcalifornia lmountain view ogoogle inc cnwwwgooglecom openssl x opensslcryptoloadcertificateopensslcryptofiletypepem cert xgetsubjectgetcomponents c us st california l mountain view o google inc cn wwwgooglecom,i need scan list ips retrieve common name certificate ip every ip allows port connections i able successfully using sockets ssl modules it works ips valid signed certificates working selfsigned certificates if i use method requires valid cert verified cabundle socket import socket import ssl socket c sslwrapsocketscertreqssslcertrequired cacerts cabundlecrt cconnect print cgetpeercert if i remove certreqssslcertrequired connects get certificate how i retrieve common name certificate ip whether validates cabundle,3 the repo include built html documentation run make tornadowebsite directory also make sure mysqldb installed why documentation web server requires run another significantly worse web server read beyond though,i using facebook tornado framework week i sometimes areas internet spotty since website repo i get run locally is appengine the first time i ran i look inside i python websitepy and well gave following traceback recent call last file systemlibraryframeworkspythonframeworkversionslibpythonwsgirefhandlerspy line run selfresult applicationselfenviron selfstartresponse file usersphwdtornadowebsitetornadowsgipy line call handler webapplicationcallself httprequestenviron file usersphwdtornadowebsitetornadowsgipy line init selfmethod environrequestmethod keyerror requestmethod status dude whack contenttype textplain contentlength oh okay using wsgipy i tried calling google app engine instead devappserverpy it started first page soon i peeked main documentation error devappserverpy error encountered reading file usersphwdtornadowebsitesphinxbuildhtmlindexhtml errno no file directory usersphwdtornadowebsitesphinxbuildhtmlindexhtml info devappserverpy get documentationindexhtml http is something i need sphinx get documentation working locally tornado web server there confpy file already setup how run website app necessary dependencies i need use,1 youâ´ll need use prefix test test method,i created testpy module filled djangotest import testcase djangotestclient import client djangocontribauthmodels import user djangocontribsitesmodels import site forummodels import class simpletesttestcase def setupself u userobjectscreateuserak akabcorg pwd forumobjectscreatetitleforum siteobjectscreatedomaintestorg nametestorg def contenttestself url values get content url test items values list present r selfcgeturl selfassertequalsrstatuscode v values selfasserttruev rcontent def testself selfc client selfcloginusernameak passwordpwd selfcontenttestforum hrefforumforumforuma placed folder application when run tests python managepy test forum creating test database get answer ran tests what wrong ps here project hierarchy myproj forum app managepy modelspy viewspy testspy i renamed testpy testspy eclipse got module tests answer still ran tests,3 want switch forms use qstackedwidget below find working sample code import sys functools import partial pyqtqtgui import pyqtqtcore import class formqwidget showformsignal pyqtsignal def initself parentnone superform selfinitparent selfnewgamebutton qpushbuttonnew game self selfquitbutton qpushbuttonquit self layout qvboxlayoutself layoutaddwidgetqlabelhtmlmy gamebrstart pagehtml layoutaddwidgetselfnewgamebutton layoutaddwidgetselfquitbutton selfnewgamebuttonclickedconnectselfshowformsignalemit selfquitbuttonclickedconnectqappquit class formqwidget showformsignal pyqtsignal def initself parentnone superform selfinitparent selfbackbutton qpushbuttonback self layout qvboxlayoutself layoutaddwidgetqlabelnew game started layoutaddwidgetselfbackbutton selfbackbuttonclickedconnectselfshowformsignalemit class mainwidgetqwidget def initself parentnone supermainwidget selfinitparent selfstack qstackedwidget layout qvboxlayoutself layoutaddwidgetselfstack selfform formself selfform formself selfstackaddwidgetselfform selfstackaddwidgetselfform selfformshowformsignalconnectpartialselfstacksetcurrentwidget selfform selfformshowformsignalconnectpartialselfstacksetcurrentwidget selfform selfstacksetcurrentwidgetselfform name main app qapplicationsysargv w mainwidget wshow appexec sysexit if want ask name user use qdialog widget,like learn pyqt writing simple game first widget would buttons like new game quit etc trouble understanding transition menu widget new one instance click new game new widget appear replaces old one asks user name way approaching something like form qtguiqwidget ui uimainmenu uisetupuiform formshow newgamebutton pressed would go subroutine form qtguiqwidget ui uinewgame uisetupuiform formshow asking code explanation approaching problem code squat thanks,2 quick dirty way linux user python convertimagepy convertfile filename convertimagepy name main import sys function getattrsysmodulesname sysargv filename sysargv functionfilename a sophisticated approach would use argparse optparse,i python file called convertimagepy inside file i script converts image liking entire converting script set inside function called convertfilefilename now problem i need execute python script linux command line passing convertfilefilename function along example linux user python convertimagepy convertfilefilename this execute python script passing appropriate function example def convertfilefilename import os sys import image import string splitname stringsplitfilename endname splitname splittwo stringsplitendname userfolder splittwo imagefile varwwwuploadstmpfilename rest script return what right way execute python script properly pass file name function liunx command line thank advanced,1 this name main command join sysargv eval command this work but insanely dangerous you really need think commandline syntax and need think breaking longestablished linux standards specifying arguments program for example consider removing useless example make instead python convertimagepy convertfile filename then little work use argparse get command convertfile arguments filename work within standard linux command line syntax functionmap convertfile convertfile conv convertfile parser argparseargumentparser parseraddargument command nargs parseraddargument filename nargs args parserparseargs function functionmapargscommand function argsfilename,i python file called convertimagepy inside file i script converts image liking entire converting script set inside function called convertfilefilename now problem i need execute python script linux command line passing convertfilefilename function along example linux user python convertimagepy convertfilefilename this execute python script passing appropriate function example def convertfilefilename import os sys import image import string splitname stringsplitfilename endname splitname splittwo stringsplitendname userfolder splittwo imagefile varwwwuploadstmpfilename rest script return what right way execute python script properly pass file name function liunx command line thank advanced,3 there number problems eval evaluating expression executing statements exec would need entire function one exec split onto separate lines there much easier ways create functions depending want body tell us really want your loop much simpler title blah blah,i try define function variable name names retrieved database for every name i want define button separate handling title bnl ce rangelentitle panelvpuaddbuttontitlei rangelentitle eval def onbuttonclick titlei self event eval windowalertyes the button definition ok handling event defined function gives error im syntaxerror index def onmenuitemself windowalertitem selected expected got onmenuitem after feedback i changed title bnl ce title panelvpuaddbuttont title defcode print execdefcode just get feeling python works fine but i use pyjamas last code rais error stating im typeerror iter undefined it appears pyjamas supporting eval exec yet richard,3 this gets complicated you need actually mix audio knowledge possible ffmpeg the problem going loss quality take mp convert wav work reencode back mp i think use sox httpsoxsourceforgenet use ffmpeg first decode audio wav adjusting sample rate bit depth necessary then call soxmix httplinuxdienetmansoxmix,i working project i need postprocess bunch audio files various formats firstly files need converted wav format secondly depending length i need insert short audible watermark certain intervals new wav files the first part easy using lame encoder cli the second part get difficult i tried method lame ffmpeg seem get working the script running cron job background full cli access available if possible would great someone could point example scriptgem class related way,1 if running script arcgis toolbox calendar popup possible even worse look like date data type provides validation toolbox this means need either validate actual date entered code modify validation code script properties i would,i gis specialist using python within arcgis i creating script importing arcgis default graphical interface form in default forms i set certain parameters made different data types one parameters i would like set field user opens calendar selects date passed script because i working within arcgis i sure i add field if anyone needs clarification i want let know thanks,1 if ready take python route i would suggest scipy read wav files numpy arrays scipyio import wavfile fs data wavfilereadfilename official documentation contains details sounds conveniently manipulated array manipulation routines numpy scipyiowavfile write file back wav format scipy numpy general scientific data tools more musiccentric python modules found official web site,i working project i need postprocess bunch audio files various formats firstly files need converted wav format secondly depending length i need insert short audible watermark certain intervals new wav files the first part easy using lame encoder cli the second part get difficult i tried method lame ffmpeg seem get working the script running cron job background full cli access available if possible would great someone could point example scriptgem class related way,1 a snippet better explanation might django ship simplified filter mechanism,i simple django model like class personmodelsmodel referrer modelsforeignkey self nulltrue in model modeladmin would i allow filtered whether referrer null by default adding referrer listfilter causes dropdown shown lists every person record may hundreds thousands effectively preventing page loading even loads i still filter criteria i want ie how would i modify dropdown lists all null not null choices i seen posts claim accomplish something similar using custom filterspec subclasses none explain use the i seen appear apply fields models i want moreover zero documentation filterspec makes nervous i want invest lot custom code tied transient internal class might disappear next release,1 there ticket bouncing around years httpscodedjangoprojectcomticket it missed milestone reached new feature status presumably found way trunk if mind running trunk use the patch supposedly compatible though probably get patching currently installation,i simple django model like class personmodelsmodel referrer modelsforeignkey self nulltrue in model modeladmin would i allow filtered whether referrer null by default adding referrer listfilter causes dropdown shown lists every person record may hundreds thousands effectively preventing page loading even loads i still filter criteria i want ie how would i modify dropdown lists all null not null choices i seen posts claim accomplish something similar using custom filterspec subclasses none explain use the i seen appear apply fields models i want moreover zero documentation filterspec makes nervous i want invest lot custom code tied transient internal class might disappear next release,1 yes write trait selftrait selftrait selfspousetrait else defaulttrait this called conditional expression python,i saw question uses operator null check i want use bool truefalse test i code python selftrait selfspousetrait trait selftrait else trait defualttrait in c i could write trait thistrait thisspousetrait thistrait defualttrait is similar way python,3 an alternative approach trait selfstrait defaulttraitselftrait selfspousetrait,i saw question uses operator null check i want use bool truefalse test i code python selftrait selfspousetrait trait selftrait else trait defualttrait in c i could write trait thistrait thisspousetrait thistrait defualttrait is similar way python,1 on nullcoalescing operator c question correct usage that would fail compile time in c correct way write attempting would trait thistrait thisspousetrait selftrait defaulttrait null coalesce c returns first value null chain values null nonnull values for example write c return first nonnull trait default trait others null actually trait thisspousetrait selftrait defaulttrait,i saw question uses operator null check i want use bool truefalse test i code python selftrait selfspousetrait trait selftrait else trait defualttrait in c i could write trait thistrait thisspousetrait thistrait defualttrait is similar way python,1 python sets implementation operator you use set union amp set intersection sets implement set difference you also use symmetric set difference ie return new set objects appear one set appear sets,i would like know valid setrange setrange valid setrange setrange is could mean intersection union,3 because means union amp means intersection there clearly reason add multiple operators function the reasons using amp probably goes back bitwise operations if represent set bits number operators use union intersect simple tied union set difference,i would like know valid setrange setrange valid setrange setrange is could mean intersection union,3 sure could used union would still need symbol intersection union symmetrical amp intersection thus makes better choice,i would like know valid setrange setrange valid setrange setrange is could mean intersection union,3 because set difference useful commonly known concept universally used concept „set addition“,i would like know valid setrange setrange valid setrange setrange is could mean intersection union,1 give inner self another name def fooself def closuerb print closure selfval return closuer also rather using typesmethodtype might want use functoolspartial,i trying something bit strange least python closure say i classes like usrbinpython import types def methodaself print selfval class aobject def initself selfval pass def fooself def closureself print closure selfval return closure class bobject def initself selfval pass def fooself print bfoo selfval a b b bundo typesmethodtypeafoo b bundo so object method returns closure used object b closure function bound object b code result closure my question anyway allow closure method access attribute method object thanks,3 python chose use instead set union concept closely related boolean disjunction bit vectors python int long define operation across sequence boolean values call bitwise in fact operation similar set union binary integers sometimes also called bit sets elements set taken natural numbers because int already defines setlike operators amp natural newer set type use interface,i would like know valid setrange setrange valid setrange setrange is could mean intersection union,3 as per pep style guide imports imports usually separate lines eg yes import os import sys no import sys os okay say though subprocess import popen pipe so i think split i aware utility also projectbar contains say defgxyz i would say import projectbar code much less easy eyes,we lot files ugly import statements like projectfoo import b projectfoo import c projectbar import e f g does exist something change one import per line projectfoo import projectfoo import b projectfoo import c projectbar import projectbar import e projectbar import f projectbar import g clarification the reason maintain consistent style like google style guide python,3 i found use scatter scatter format scatterxysizesmarkertype produces,i like nonuniform point sizes matplotlib set size point is way i guess i could hack separate plot command markersize set point would really annoying is principled way,3 if tool onetime use really care efficiency just let run minute several rather spending even time optimizing that said queries expensive python loops loading tags list first looping list times speed things tags todelete tags tnameinsensitive tname mergett todeleteappendtag also remove commit call loop not expensive process changes db list tags looping could get sync of course proper way make things efficient profiling first concentrating specific problems you serious performance,let say i database full tag objects each tag id name in beginning making database i allowed case sensitive tags however i later realized i needwant capability i started forcing name lowercase storing tag now i remnants different names would stored tag previously for example trendy trendy nothalfbad nothalfbad nothalfbad sql sql sql i using python sqlalchemy i created function clean mess looks something like todelete sessionquerytag todelete if already encountered tag sessionquerytagfilterbynameinsensitivetname tid tid mergett calls function i made merges two tags todeleteappendtag sessioncommit mark everything deletion tag todelete sessiondeletetag now commit deletes sessioncommit this horribly inefficient is better way,1 the way i ever found i looking many years use python bindings microsoft active accessibility layer pyaa this project longer actively maintained build version windows way i know get work,i find way add callback window closed also reliable way react newly created windows my application creates processes using subprocesspopen each process visible window the processes share events pyhook using pumpmessages i use method get handle window tim golden find window subprocess this method first sleeps bit wait windows creation uses enumwindows compares pid ok method sometimes works given enough time sometimes stays idle way long obviously waiting notification new window created would better same goes closing window i guess i check handle iswindow pyhook events seem right i found python examples msdn examples say wmclose send i get listen messages nothing ever happens i see pyhook events i even sure i using hookmessage correctly def closewindowhwnd msg print closed strhwnd window winuicreatewindowfromhandlehwnd wmclose x windowhookmessageclosewindowx is way add callback gets executed process creates window how i get callback executed window closed,1 find string method python find gives,i using piece code trying debug but something weird happening in one part i line vals finda but gives error global name find defined i thought find like inbuilt function python clearly i mistaken but want check case i forgetting include anything,2 since release use container directive name option container test name myid paragraph results div classtest container idmyid paragraph div,using rsstructuredtext generate html i trying wrap paragraph extra div element the must contain id attribute value i assign also must class attribute editable value this i far raw html div idanidentifier class editable paragraph content raw html div this output div idanidentifier p classeditableparagraph contentp div i already got results i looking although i like raw html embedded my question whether directive method restructuredtext achieve results unobtrusively thanks hector,3 your current example runs issue recursion limits way calls recursively the stack size continues grow grow hits default likely see modified example import time import inspect import thread tx timetime def loopevent print stack size leninspectstack tx timetime txtx print running code return loop threadstartnewthreadloop timesleep output stack size running code stack size running code stack size running code exception runtimeerror maximum recursion depth exceeded its probably easiest use custom thread class run tell stop this way stack size keep growing it loops calls handler function here working complete example import time threading import thread class intervaltimerthread def initself secs func args kwargs superintervaltimer selfinittargetfunc argsargs kwargskwargs selfinterval secs selffunc func selfargs args selfkwargs kwargs selfexiting false def runself selfexiting timesleepselfinterval selffuncselfargs selfkwargs def cancelself selfexiting true def testval print val name main intervaltimer test argshi tstart timesleep tcancel,timer inside game i programmed def functionevent timesleep tx timetime txtx repetitive stuff return function tx timetime threadstartnewthreadfunction better way write seems bit dirty calling recursive function new thread moreover crashes,2 as others said andor pointed hardcode specific agencies urlspy keep generic dry allowing variables urls urls r airagencypnameazaz airagencyviewsindex passes value name view index views def indexrequest name needs know name passed somequery agencyobjectsfilter agencyname name also add catching unknown objects go return somesortofhttpresponse examples docs,i model named agencyagency field named urlfor example i add agencies first one give value a url second one give value b url fieldnow i wanna override savemodel method index viewspy add agencie url urlspy adding agencylike r airagencya airagencyviewsindex r airagencyb airagencyviewsindex sowhen enter httpairagencya index view detect agency i wanna access pass data pagenow i question i addremove url urlspy overriding save method viewspy user enter url browser i parse find agency wanna access send agency information first question i searched lot i find anythingfor second question i googled i found parse requested urlbut u think string search agency table based url field good way,1 what describe could work notice value attribute constrained object callabledefault class this probably useful i strongly suggest try for one thing spending lot time trying trick python something want for another users api confused acts differently every python code ever seen they confused write python api works naturally python,this kindof experiment i interested api supports syntaxes objthing returns default value objthing returns value derived args kwargs thing object cases i like calling thing optional implicit i tried overriding repr visual representation object actually returned instance containing object obj so good i thinking would attribute set object callable care instance def call object enough default values class callabledefaultobject callself num letterz return letter num class dumbobjectobject foo callabledefault obj dumbobject ideally obj alone would return zzz one could also obj get aaaaaaa i thinking decorators might way i great decorators one could override getattr call containing class would mean containing class supports feature,2 what happens either objthing objthing python goes looking thing obj thing either returns first case calls parameters second case critical point call happen attribute retrieved containing class way knowing thing returns called you could add call method every type might use way way lies madness update well long comfortable insanity could try something like class callablestrstr def callself num letter return numletter class callableintint def callself num pow return num pow class testerobject wierd callablestr zzz big callableint tester print reprtwierd print reprtwierd print reprtbig print reprtbig one nice thing magic object becomes normal soon use calculation call print typetbig typetbig tbig print typetbig typetbig tbig results class maincallableint type int class maincallableint type int,this kindof experiment i interested api supports syntaxes objthing returns default value objthing returns value derived args kwargs thing object cases i like calling thing optional implicit i tried overriding repr visual representation object actually returned instance containing object obj so good i thinking would attribute set object callable care instance def call object enough default values class callabledefaultobject callself num letterz return letter num class dumbobjectobject foo callabledefault obj dumbobject ideally obj alone would return zzz one could also obj get aaaaaaa i thinking decorators might way i great decorators one could override getattr call containing class would mean containing class supports feature,2 apache processes run special user if temp directory truly owned app apache user likely able write what user apache run are using daemon mode overridden user run,i running python virtualenv django modwsgi apache application ubuntu everything including psycopg etc working great wsgi app running the issue selenium i getting error only i execute wsgi creating firefox driver follows selenium import webdriver wd webdriverfirefox webdriverexception exception value message can load profile profile dir tmptmphmw selenium version apache launched root child process launched user called app execute code virtualenv without wsgi works fine so makes think permission issue level i tried ls l tmptmphmw drwxrxrx app app extensions rwrr app app userjs i would appreciated could point right direction i might misconfiguring wsgi,1 thanks nice answer i problem it works nicely forces supply external model unnecessary i extended code also work internal standard model already supplied combobox also cleanup documentation done usrbinenv python coding utf pyqtqtcore import qt pyqtqtgui import qcompleter qcombobox qsortfilterproxymodel class extendedcomboboxqcombobox def initself parentnone superextendedcombobox selfinitparent selfsetfocuspolicyqtstrongfocus selfseteditabletrue add filter model filter matching items selfpfiltermodel qsortfilterproxymodelself selfpfiltermodelsetfiltercasesensitivityqtcaseinsensitive selfpfiltermodelsetsourcemodelselfmodel add completer uses filter model selfcompleter qcompleterselfpfiltermodel self always show filtered completions selfcompletersetcompletionmodeqcompleterunfilteredpopupcompletion selfsetcompleterselfcompleter connect signals selflineedittexteditedunicodeconnectselfpfiltermodelsetfilterfixedstring selfcompleteractivatedconnectselfoncompleteractivated selection item completer select corresponding item combobox def oncompleteractivatedself text text index selffindtexttext selfsetcurrentindexindex model change update models filter completer well def setmodelself model superextendedcombobox selfsetmodelmodel selfpfiltermodelsetsourcemodelmodel selfcompletersetmodelselfpfiltermodel model column change update model column filter completer well def setmodelcolumnself column selfcompletersetcompletioncolumncolumn selfpfiltermodelsetfilterkeycolumncolumn superextendedcombobox selfsetmodelcolumncolumn name main import sys pyqtqtgui import qstringlistmodel qapplication app qapplicationsysargv stringlist hola muchachos adios amigos hello world good bye combo extendedcombobox either fill standard model combobox comboadditemsstringlist use another model combosetmodelqstringlistmodelstringlist comboresize comboshow sysexitappexec,i need qcombox items filtered based text input if i set qcombobox editable user insert text qcompleter automatically created but items filtered i don’t want user add new items is possibility add functionality qcombobox,3 l x adds x existing l initialized l presumably want l somewhere top file,it populations genetics program handed professors modified students basically supposed simulate expected number mutations twenty times given sample population mutation rate u however critical piece total branch length l sum various smaller branch lengths branchlength however i define l keeps coming back error l branchlength nameerror name l defined i sure wrong since treedepth defined way works flawlessly here full code random import expovariate pgen import poidev k sample size number gene copies twon population size u treedepth age last common ancestor generations each pass loop deals one coalescent interval a range k h kktwon hazard coalescent event expovariateh time next coalescent event treedepth branchlength tk k l branchlength s poidevul print simulation a total mutations s print total tree depth l l generations am i missing something really really obvious thanks advance,2 have run python managepy syncdb have changed model added username since first ran syncdb are using south if probably learn syncdb works new models you got sort migrations south comes alternatively modify database use another app closer method called nashvegas this approximation sql need alter table omnicloudappuser add column username varchar not null,so i got trying add user database and i thought i wonder columns so i asked sql databaseerror table omnicloudappuser column named username rootharoldomnicloudomnicloud python managepy sql omnicloudapp begin create table omnicloudappuser id integer not null primary key email varchar not null username varchar not null password varchar not null hey there why would get mad two following lines seems fact said column u useremailgmailgmailcom usernamegmail passwordgmail usave also i defining user class says user column called username why go lowercase,1 you using exact example the example req urllibrequesturl data headers request urllibrequesturl headers because positional arguments important keep straight the second argument string data need supply request urllibrequesturl headers,def downloadurl print url useragent mozilla windows u windows nt rv gecko firefox headers useragent useragent request urllibrequesturl headers response urlliburlopenrequest return response what i wrong i using exact example docs httpdocspythonorghowtourllibhtmlheaders,3 adding custom queries managers django convention from django docs custom managers adding extra manager methods preferred way add tablelevel functionality models if private app convention word matter much indeed company internal codebase classmethods perhaps belong custom manager however writing app going share django users expect see findby custom manager i think inheritance issues mention bad if read custom managers model inheritance docs i think get caught the verbosity writing objects bearable queries using xyzobjectsget xyzobjectsall here advantages using manager methods opinion consistency api your method findby belongs get filter aggregate rest want know lookups xyzobjects manager it simple introspect dirxyzobjects static methods clutter instance namespace xyzfindby fine define static method also xyzfindby running findby lookup particular instance really make sense dryness sometimes use manager one model having said i aware killer reason use static method you adult code want write findby manager method sky going fall for reading i recommend blog post managers versus class methods james bennett django release manager,after reading django managers i still unsure much benefit i get using it seems best use add custom queries readonly methods like xyzobjectsfindby but i easily static methods model classes i prefer latter always code locality terms readability easier maintenance slightly less verbose i need objects property calls manager classes weird rules regarding model inheritance might well stay clear is good reason use static methods instead use manager classes,3 you need define l l x in general modifying need define variable for assignment problem python infer type some examples invalid traceback recent call last file input line module nameerror name defined valid now valid defined mylistappend invalid traceback recent call last file input line module nameerror name mylist defined mylist mylistappend now valid mylist mylist valid assignment,it populations genetics program handed professors modified students basically supposed simulate expected number mutations twenty times given sample population mutation rate u however critical piece total branch length l sum various smaller branch lengths branchlength however i define l keeps coming back error l branchlength nameerror name l defined i sure wrong since treedepth defined way works flawlessly here full code random import expovariate pgen import poidev k sample size number gene copies twon population size u treedepth age last common ancestor generations each pass loop deals one coalescent interval a range k h kktwon hazard coalescent event expovariateh time next coalescent event treedepth branchlength tk k l branchlength s poidevul print simulation a total mutations s print total tree depth l l generations am i missing something really really obvious thanks advance,1 create variable stores converting swap function change variable update labels to change text label label text new text labelconfiguretext new text here working modification code import tkinter inputmode feet this variable stores converting win tkintertk wintitle converter row tkinterframewin blank tkinterlabelrow text font courier new blankpack rowpack label tkinterlabelwin text convert between feet meters font courier new bold labelpack def convert st entryget v evalst typev type hello inputmode feet check way convert answerconfigtextstrv else answerconfigtextstrv def swap global inputmode inputmode meters inputmode feet flabel text feet changes text label mlabel text metres else inputmode meters flabel text metres mlabel text feet row tkinterframewin flabel tkinterlabelrow text feet justify right font courier new entry tkinterentryrow width font courier new flabelpackside left entrypackside right rowpack row tkinterframewin mlabel tkinterlabelrow text meters justify right font courier new answer tkinterlabelrow text width relief sunken font courier new mlabelpackside left answerpackside left rowpack row tkinterframewin quit tkinterbuttonrow text quit command windestroy font courier new convert tkinterbuttonrow text convert command convert font courier new swap tkinterbuttonrow text swap commandswap font courier new quitpackside left convertpackside left swappackside right rowpack row tkinterframewin blank tkinterlabelrow text font courier new blankpack rowpack winmainloop,i simple tkinter program python converts feet meters it label feet entry box meters box sunken border buttons quit covert swap i trying figure make swap button exactly swap position feet meters window enter x meters convert feet hitting convert really i need switch positions math part easy enough i think logic would work here i far import tkinter win tkintertk wintitle converter row tkinterframewin blank tkinterlabelrow text font courier new blankpack rowpack label tkinterlabelwin text convert between feet meters font courier new bold labelpack def convert st entryget v evalst typev type hello answerconfigtextstrv def swap i need figure swap row tkinterframewin flabel tkinterlabelrow text feet justify right font courier new entry tkinterentryrow width font courier new flabelpackside left entrypackside right rowpack row tkinterframewin mlabel tkinterlabelrow text meters justify right font courier new answer tkinterlabelrow text width relief sunken font courier new mlabelpackside left answerpackside left rowpack row tkinterframewin quit tkinterbuttonrow text quit command windestroy font courier new convert tkinterbuttonrow text convert command convert font courier new swap tkinterbuttonrow text swap commandswap font courier new quitpackside left convertpackside left swappackside right rowpack row tkinterframewin blank tkinterlabelrow text font courier new blankpack rowpack winmainloop first last frames space padding thanks advance help,2 are looking xmlsax it right standard library,are xml parsers python parse file streams my xml files big fit memory i need parse stream ideally i root access install things lxml good option i using xmletreeelementtree i convinced broken,2 best explanation ever seen web moment httpnicholasbenchmarkofpythonwebservers quote nicholas when interested quickly hosting threaded application really can’t go wrong apache modwsgi even though apache modwsgi might put little strain memory requirements lot go terms functionality for example protecting part website using ldap server easy enabling module standalone cherrypy also shows great performance functionality really viable fully python alternative lower memory requirements when little adventurous look uwsgi fapws relatively new compared cherrypy modwsgi show significant performance increase lower memory requirements,difference using fapws modwsgi dealing django fapws seems alot faster serving requests toward python scripts i would like know i missing anything any ideas,1 here ideas explain file occasionally really mean works sometimes fails sometimes file do following failing file find file point complaining text openthefilexml rbread errcol print reprtexterrcolerrcol include error text print reprtext show xml declaration throw file webbased xml validation service eg httpwwwvalidomeorgxml httpvalidatoraborlanet edit question display findings update here minimal xml file illustrates problem badcharrefxml aampa python output import xmletreeelementtree et etiterparsefilebadcharrefxml ev el print eltag traceback recent call last file stdin line module file cpythonlibxmletreeelementtreepy line next selfparserfeeddata file cpythonlibxmletreeelementtreepy line feed selfraiseerrorv file cpythonlibxmletreeelementtreepy line raiseerror raise err xmletreeelementtreeparseerror reference invalid character number line column not valid unicode characters valid xml see xml specification you may wish examine files using regexes like r amp r ampxafaf convert matched text int ordinal check valid list spec ie x xa xd xxdff xexfffd xxffff maybe numeric character reference syntactically invalid eg terminated ampnotadigit etc etc update i wrong number elementtree error message counting unicode code points bytes see code snippets output running two bad files coding ascii find numeric character references refer unicode code points valid xml get byte offsets seeking etc undecoded file bytestreams get unicode offsets checking elementtree error message if input file small enough byteoffsets true import sys codecs fname sysargv print fname byteoffsets text openfname rbread else assumes file encoded utf text codecsopenfname rb utfread rx recompileampampxafaf endpos lentext pos pos endpos rxsearchtext pos break mstart mend mspan target mgroup target num inttarget else num intmgroup x xa xd xxdff xexfffd xxffff notnum x xa xd x num xdff xe num xfffd x num xffff print mstart mgroup pos mend output commentsxml ampx ampx ampx ampx ampx ampx ampxb ampxb ampx ampx postsxml ampxf ampxb ampxb ampxb ampxb ampxb ampxc ampxc ampx ampxffff whoops ampx ampx ampx ampxb,i trying parse file xmletreeelementtree import xmletreeelementtree et xmletreeelementtree import parseerror def analyzexml etiterparsefilexml count last none try ev el count last el except parseerror printcatastrophic failure printlast successful formatlast print count formatcount this course simplified version code enough break program i get error files i remove trycatch block traceback recent call last file pyshell line module yparse import analyze analyze filexml file cpythonyparsepy line analyze ev el file cpythonlibxmletreeelementtreepy line next selfparserfeeddata file cpythonlibxmletreeelementtreepy line feed selfraiseerrorv file cpythonlibxmletreeelementtreepy line raiseerror raise err parseerror reference invalid character number line column the results deterministic though file works always work if file fails always fails always fails point the strangest thing i using trace find i malformed xml breaking parser i isolate node caused failure but i create xml file containing node neighbors parsing works this seem size problem either i managed parse much larger files problems any ideas,3 the python wiki great page profiling resources httpwikipythonorgmoinpythonspeedperformancetipsprofilingcode python docs httpdocspythonorglibraryprofilehtml shown chris lawlor cprofile great tool easily used print screen python cprofile time minepy args file python cprofile outputfile minepy args ps if using ubuntu make sure install pythonprofile sudo aptget install pythonprofiler if output file get nice visualizations using following tools pycallgraph tool create call graph images install sudo pip install pycallgraph run pycallgraph minepy args view gimp pycallgraphpng you use whatever like view png file i used gimp unfortunately i often get dot graph large cairorenderer bitmaps scaling fit makes images unusably small so i generally create svg files pycallgraph f svg pycallgraphsvg minepy args ps make sure install graphviz provides dot program sudo pip install graphviz alternative graphing using gprofdot via maxy quodlibetor sudo pip install gprofdot python cprofile profilepstats minepy gprofdot f pstats profilepstats dot tsvg minesvg,project euler coding contests often maximum time run people boast fast particular solution runs with python sometimes approaches somewhat kludgey ie adding timing code main what good way profile long python program takes run,3 getnames return copy def getnamesself return selfnames,i following code class helloobject def initself names selfnames names def getnamesself return selfnames name main names first middle last ob hellonames obgetnames print aremove first print print obgetnames the following output first middle last middle last middle last is method getnames mutable or may something else going can anyone explain how i make method return original list,2 in python assignment never makes copy data structure it makes name refer value also function invocation essentially assigns actual arguments argument names so nothing copied code the names obnames refer list if want two copies list original one modify need make copy point you decide makes sense you copy list different ways listl l common ways,i following code class helloobject def initself names selfnames names def getnamesself return selfnames name main names first middle last ob hellonames obgetnames print aremove first print print obgetnames the following output first middle last middle last middle last is method getnames mutable or may something else going can anyone explain how i make method return original list,2 you add flags individual tree widget items control drag drop behaviour amongst things for instance prevent item drop target try something like item qtreewidgetitemparent itemsetflagsitemsflags amp qtitemisdropenabled see qt docs details httpdocqtnokiacomqthtmlitemflagenum,i qtreewidget i thought proper settings setup order able reorder items dragging around it work times often i drag item another one either disappears becomes child is anyway prevent happening lose items trying reorder i figured could achieve within qt designer i dragdrop mode set internalmove defaultdropaction set moveaction i even certain i need adjusting thanks advance,1 what new also standard library documents certain features added for example string formatting added third party library support could dodgy though,i starting new python project work targeted primarily rhel machines may upgraded rhel couple years given python standard rhel system admins support getting python local repo take convincing while seems i could get fine python i feel leery creating project ground aimed compatible old version should i fight project done aim smoothest compliance rhel what pitfalls i aware i stick fyi i definitely using sqlite pygtk,1 what which python,i starting new python project work targeted primarily rhel machines may upgraded rhel couple years given python standard rhel system admins support getting python local repo take convincing while seems i could get fine python i feel leery creating project ground aimed compatible old version should i fight project done aim smoothest compliance rhel what pitfalls i aware i stick fyi i definitely using sqlite pygtk,1 use xmletreecelementtree it much faster xmletreeelementtree neither broken your files broken see answer question,are xml parsers python parse file streams my xml files big fit memory i need parse stream ideally i root access install things lxml good option i using xmletreeelementtree i convinced broken,3 you customise fields displayed django admin using listdisplay option modeladmin class the model unicode method metaordering option affect fields displayed if set listdisplay default behaviour display single column unicode string object if unicode string displayed model sounds like set listdisplay for example display name field instead unicode string would class mymodeladminmodelsmodeladmin listdisplay name if want display unicode string fields simply include unicode listdisplay class mymodeladminmodelsmodeladmin listdisplay unicode name,for models djangoadmin index model objects instead displaying output unicode method like normally displays one model fields this happens usually something like class meta ordering name model value field name displayed even though also unicode method always sometimes displays unicode says even class meta ordering all unicode methods quite normal something like def unicodeself return u selffield selfname i puzzled field used sometimes instead unicode i make use unicode method always this django is bug django,1 it sounds though interactive mode enabled somehow although i sure try like def main import matplotlibpyplot plt data range fig pltplotdata pltioff turns interactive mode off make show blocking pltshow name main main,how easily i make blocking gui app os x i simple python plotting program when i run inside existing python interactive session within ipython gui window displayed i see interact when i run py file cli gui flashes closes immediately i would like run command line gui remain name main import matplotlib matplotlib import pyplot data range fig pyplotplotdata pyplotshow,2 trying change objectname really bad idea it set modelmeta say one documented available meta options trying change risks breaking stuff i understand important change it displayed publicly really matter whether underscore in comment point objectname used cbv i would use documented ways change contextobjectname cbv instead trying change model if must change model probably need hack around djangodbmodelsoptions you could try monkey patching defaultparams allow set objectname model meta class,i object leatherchair django pisses django gives objectname leatherchair i want leatherchair underscore the objectname seems stored options instance i change,1 remove sysexit if basing wording httpcodegooglecomappenginedocspythonruntimehtmlresponses since reworded pretend moment use exit first two sentences means completes finishes,i running code sysexit call end without sysexit line selfresponse works fine renders template but i call sysexit page returns blank it almost like sysexit interrupting template midrender why page indexhtml templatevalues path ospathjoinospathdirnamefile page selfresponseoutwritetemplaterenderpath templatevalues sysexit edit i solved problem using return instead sysexit,3 part your code work getattr accesses selfsoup initialized this happens due four innocuouslooking lines try selfpage urlliburlopenselffile except urlliburlerror print please enter valid url starting httphttpsftpfile why catch exception actually handle the next line accesses selfpage set yet urlopen threw exception selfsoup beautifulsoupselfpage since set accessing calls getattr accesses selfsoup set yet accesses getattr the easiest fix specialcase soup prevent infinite recursion additionally seems make sense getattr simply normal attribute lookup soup def getattrselfattr attr soup raise attributeerror return getattrselfsoupattr part copying methods unlikely work well seems miss point class composition entirely,following advice subclassing beautifulsoup html parser getting type error i trying use class composition instead subclassing beautifulsoup basic scraper class works fine least limited testing scraper class beautifulsoup import beautifulsoup import urllib class scrape base class subclassed basically wrapper providers basic url fetching urllib basic html parsing beautifulsoup×¥ useful methods provided class composition beautifulsoup direct access soup class use soup property def initselffile selffile file basic input validation import import urllib beautifulsoup import beautifulsoup try selfpage urlliburlopenselffile fetching page except urlliburlerror print please enter valid url starting httphttpsftpfile selfsoup beautifulsoupselfpage calling html parser beautifulsoupinitselfselfpage next part class compostion part transform attribute method calls beautifulsoup class search functions selffind selfsoupfind selffindall selfsoupfindall selfiter selfsoupiter enables iteratinglooping object selflen selfsouplen selfcontains selfsoupcontains attribute fetching setting getattr implented scraper class selfsetattr selfsoupsetattr selfgetattribute selfsoupgetattribute called implement evaluation selfkey selfgetitem selfsoupgetitem selfsetitem selfsoupsetitem selfdelitem selfsoupdelitem selfcall selfsoupcallcalled instance “called” function selfgetattrmap selfsoupgetattrmap selfhaskey selfsouphaskey walking html document methods selfcontents selfsoupcontents selftext selfsouptext selfextract selfsoupextract selfnext selfsoupnext selfparent selfsoupparent selffetch selfsoupfetch selffetchtext selfsoupfetchtext selffindallnext selfsoupfindallnext selffindchild selfsoupfindchild selffindchildren selfsoupfindchildren selffindnext selfsoupfindnext selffindnextsibling selfsoupfindnextsibling selffirst selfsoupfirst selfname selfsoupname selfget selfsoupget selfgetstring selfsoupgetstring comparison operators similiar boolean checks selfeq selfsoupeq selfne selfsoupne selfhash selfsouphash selfnonezero selfsoupnonzero sure class represntation magic methods selfstr selfsoupstr selfrepr selfsouprepr selfdict selfsoupdict def getattrselfmethod basically magic method transforms calls unknown attributes enables traverse html document notation example using instancenamediv return first div explantion python calls getattr it find method attribute correspanding call i sure good right use method return selfsoupfindmethod def cleanselfworkfalseelementfalse clean method providesbasic cleaning headscripts etc input work soup object clean unneccesary partsscriptsheadstyle optional variable element get tuple element enables override element clean selfwork work selfsoup selfcleanelementselement headstylescript elem selfworkfindallselfcleanelements elem selffindallselfcleanelements elemextract i subclass i get sort recursion loop i figure subclassthe relevant parts class maintrafficscrape class traffic subclasses scrape class inputs page url category def initself file cat caller false caller selffile file import urllib selfrequest urllibrequestselffile request post show questions scrapeinitselfselffile selfpagecat cat selfcleanself selfcleansoup selfcleantotableself selffetchlinksselfcleansoup selfpopulatequestiondic del selfcleansoup def cleantotableself pass def fetchlinksselffetch pass def lengthself sqlalchemy import func selflen sessionqueryfunccountquestionidscalar return intselflen def lenself return selflength def reprself selfrepr traffic theory question current number questionsformatselflength return selfrepr def getitemselfkey try selfitem sessionqueryquestionfilterbyquestionnumkeyfirst return selfitem except indexerror keyerror print keyformatkey error message file cpythonlearntrafficpy line init scrapeinitselfselffile file cpythonlearntrafficpy line init selfsoup beautifulsoupselfpage calling html parser file cpythonlearntrafficpy line getattr return selfsoupfindmethod file cpythonlearntrafficpy line getattr return selfsoupfindmethod file cpythonlearntrafficpy line getattr return selfsoupfindmethod runtimeerror maximum recursion depth exceeded i suspect problem misusing getattr i figure i change,2 my main worry would third party libraries library authors running thinking x bugs show older versions likely get lower priority ignored completely bug python author could easily say library fault,i starting new python project work targeted primarily rhel machines may upgraded rhel couple years given python standard rhel system admins support getting python local repo take convincing while seems i could get fine python i feel leery creating project ground aimed compatible old version should i fight project done aim smoothest compliance rhel what pitfalls i aware i stick fyi i definitely using sqlite pygtk,1 avoid working regular strings whenever possible unicode generally useful text many wellknown solutions manipulating dealing,i extracting field webpage ad tag html text content looks like ampnbspnew in python extracted data looks like xanew how i deal unicode python convert regular string new library i use thanks,2 essentially f special syntax use array list comprehension pass result functions provided standard library let intset set x list x yield x let intmap dict x list x yield xy,i looking something akin dictlistset comprehensions python in python x x list x f x list x yield x python also x x list x generate sets k v k v listitems k generate dicts is equivalent terms function terms overall tidyness syntax sort thing f,1 there set function accepting seq set x list x yield x same dict here relevant docs set httpmsdnmicrosoftcomenuslibraryeeaspx dict httpmsdnmicrosoftcomenuslibraryeeaspx,i looking something akin dictlistset comprehensions python in python x x list x f x list x yield x python also x x list x generate sets k v k v listitems k generate dicts is equivalent terms function terms overall tidyness syntax sort thing f,2 as john machin suggested files question dubious numeric entities though error messages seem pointing wrong place text perhaps streaming nature buffering making difficult report accurate positions in fact entities appear text set ampx ampxe ampxe ampxc ampx ampx ampxa ampxc ampx ampx ampx ampx ampx ampx ampxd ampxd ampxf ampx ampxb ampx ampx ampx ampx most allowed looks like parser quite strict need find another strict preprocess xml,i trying parse file xmletreeelementtree import xmletreeelementtree et xmletreeelementtree import parseerror def analyzexml etiterparsefilexml count last none try ev el count last el except parseerror printcatastrophic failure printlast successful formatlast print count formatcount this course simplified version code enough break program i get error files i remove trycatch block traceback recent call last file pyshell line module yparse import analyze analyze filexml file cpythonyparsepy line analyze ev el file cpythonlibxmletreeelementtreepy line next selfparserfeeddata file cpythonlibxmletreeelementtreepy line feed selfraiseerrorv file cpythonlibxmletreeelementtreepy line raiseerror raise err parseerror reference invalid character number line column the results deterministic though file works always work if file fails always fails always fails point the strangest thing i using trace find i malformed xml breaking parser i isolate node caused failure but i create xml file containing node neighbors parsing works this seem size problem either i managed parse much larger files problems any ideas,3 since wayneed deepcopy string slicing particular list effect but normally performs shallow copy sequence,i using python i list lst b c if i need copy list i used lstcpy lst i came across function deepcopy package copy enables achieve import copy lstcpy copydeepcopylst can i use two methods interchangeably difference two thanks,1 in case simple list if list structures within example elements lists dictionaries would different l makes new list element new list new reference values old list if one values mutable changes seen new list copydeepcopy makes new list element deep copy values old list so nested data structures copied every level,i using python i list lst b c if i need copy list i used lstcpy lst i came across function deepcopy package copy enables achieve import copy lstcpy copydeepcopylst can i use two methods interchangeably difference two thanks,3 parse html using beautifulsoup retrieve text,i wanted remove tags html file for i used module python for example consider line hhello worldh i want retain hello world in order remove tags i used resub string for obvious reasons result i get empty string the regexp identifies first last angle brackets removes everything how could i get issue,1 you make match nongreedy you also need careful html crafty beast thwart regexes,i wanted remove tags html file for i used module python for example consider line hhello worldh i want retain hello world in order remove tags i used resub string for obvious reasons result i get empty string the regexp identifies first last angle brackets removes everything how could i get issue,1 i believe difference one items list list dict mutable object with normal copy object shared copies l b l l lappend c l b c deepcopy object copied well l copydeepcopyl lappend l b c l b c,i using python i list lst b c if i need copy list i used lstcpy lst i came across function deepcopy package copy enables achieve import copy lstcpy copydeepcopylst can i use two methods interchangeably difference two thanks,1 make nongreedy httpdocspythonorgreleasehowtoregexhtmlgreedyversusnongreedy offtopic approach uses regular expressions error prone cannot handle cases angle brackets represent tags i recommend httplxmlde,i wanted remove tags html file for i used module python for example consider line hhello worldh i want retain hello world in order remove tags i used resub string for obvious reasons result i get empty string the regexp identifies first last angle brackets removes everything how could i get issue,1 you import lxmletree et lxmletree import xmlparser parser xmlparsernscleantrue recovertrue html htmlbodydiv idcontentdivreviewhistopopbhygu styledisplaynonebodyhtml tree etfromstringhtml parser tmp list elem treeiter elemtag div ii elemitems iilower id contentdivreviewhistopop ii tmpappendelem tmp contain list matching div elements matching text if use lxmlhtml import lxmlhtml html htmlbodydiv idcontentdivreviewhistopopbhygu styledisplaynonebodyhtml doc lxmlhtmldocumentfromstringhtml tmp list elem dociter elemtag div ii elemitems iilower id contentdivreviewhistopop ii tmpappendelem again tmp contain matching tags,i tab looks like div idcontentdivreviewhistopopbhygu styledisplaynone i use doc lxmlhtmldocumentfromstringhtml el docgetelementbyid contentdivreviewhistopopbhygu find tag i use eg wild card find contentdivreviewhistopop would find tags contains portion string thanks,1 use parser either lxml beautifulsoup import lxmlhtml print lxmlhtmlfromstringmystringtextcontent related questions using regular expressions parse html why possible use regex parse htmlxml formal explanation laymans terms,i wanted remove tags html file for i used module python for example consider line hhello worldh i want retain hello world in order remove tags i used resub string for obvious reasons result i get empty string the regexp identifies first last angle brackets removes everything how could i get issue,1 patch httpbugspythonorgissue solves issue thanks narendra sisodiya,while python tp cursestextpadtextboxstdscr insertmodetrue text tpedit i get runtimeerror maximum recursion depth exceeded calling python object could please tell enable insert mode cursestextpad thanks advance,1 it work set python use fiddler proxy it may easier use wireshark let monitor http traffic without need proxies,i tried use fiddle debug one python program makes http request gets response however i see traffic fiddler matter i ran python command prompt python gui fiddle filter set ie set show processes i see browsers traffic is settings i need set thanks,2 python use proxy default fiddler cannot intercept network traffic you may need change python program little here another thread see proxy python programs proxy urllib,i tried use fiddle debug one python program makes http request gets response however i see traffic fiddler matter i ran python command prompt python gui fiddle filter set ie set show processes i see browsers traffic is settings i need set thanks,3 your array binary values array bytes if using pillow resizing pil import image im imagefromarrayarr and imshow see if array bit depth bw may multiply im imagefromarrayarr here example arr numpyrandomrandint example d array arrresize im imagefromarrayarr imshow,i numpy array binary values i would like convert matrix grayscale image python however i try reshape array x matrix i get memory error how i reduce size matrix turn image fit screen without losing uniquenessdata furthermore would i turn grayscale image any help advice would appreciated thank,3 gnu pspp apparently read spss data files i also found link description format pspp source although comes warning try readwrite format directly,i finding mixed results googling i need parse spss sav file discover data layout extract survey results step one read schema data for example i need know question type allowed responses i plan model data sql table i slice dice per apps requirements step two populate data model respondents answers looking spss sav file i believe types data i looking i need want expensive spss software i strictly require we statistics data selecting subsets respondents based answer filters the spss file provided partner company licenses spss i need data back spss use case readonly i use python java without groovy cc parser program this program run end data collection performance particularly important ideally i like code cross platform i develop mac deploy linux i use windows i must a lot finding either java classes modern python code requires dll ibm windows specific based quick explanation requirements i would appreciate recommendations so community i think needs simple found exactly i hoped an open source lib would ideal i even pay simple commercial solution reasonable price,1 well solution anyone interested edit line optlibpythonsitepackagessetuptoolscommandeasyinstallpy tmpdir tempfilemkdtempprefixeasyinstall tmpdir tempfilemkdtempprefixeasyinstalldiropttmp this works opt mounted hdd plenty free space i python expert never programmed seems like b option bearing file downloaded,i trying install python script packaged egg format using easyinstall the problem easyinstall downloads dependencies tmp however tmp dir mb free space i working nas drive set way is way specifying download directory help seem throw anything useful edit some details i running python setuputils c installed optware the nas arm based specifically dns funplug installed please let know like specific info when i use b option file still downloaded tmp it fact extraction process uses remaining space tmp easyinstall b mnthdhdaffphomeroot sqlalchemy searching sqlalchemy reading httppypipythonorgsimplesqlalchemy reading httpwwwsqlalchemyorg best match sqlalchemy downloading httppypipythonorgpackagessourcessqlalchemysqlalchemytargzmdbaaeedefdbbff processing sqlalchemytargz error no space left device i know file downloaded tmp running ls l tmp download happening ls l tmpeasyinstall total rwrr root root oct sqlalchemytargz df h output filesystem size used avail use mounted rootfs m m m devroot m m m devloop m m usrlocalmodules devmtdblock m k m usrlocalconfig devsda m m m mnthda devsdb m m m mnthdb devsda t g t mnthdhda devsdb t g t mnthdhdb devsda t g t opt thanks jack,3 your best bet probably stick timemachine module goodies later pythons want for example properties first came something like def getpropself return selfprop def setpropself value selfprop value prop propertygetprop setprop enhanced properties also decorators could write property def propself return selfprop propsetter def propself value selfprop value means less redundant functions hanging around class namespace i happen like feature lot timemachinepy code similar property sysversioninfo define property type class property properties def initself fgetnone fsetnone fdelnone docnone def callself func def getself obj objtypenone def setself obj value def deleteself obj def setterself func def deleterself func the really nice part python equivalents often used demonstrate new functionality even write code,i starting new python project work targeted primarily rhel machines may upgraded rhel couple years given python standard rhel system admins support getting python local repo take convincing while seems i could get fine python i feel leery creating project ground aimed compatible old version should i fight project done aim smoothest compliance rhel what pitfalls i aware i stick fyi i definitely using sqlite pygtk,1 in set theory symbol normally indicates disjoint union two sets if a b sets disjoint union defined set a b a u b b b ie construct disjoint union mark elements a elements b different tags example i used numbers two different things would job take union two resulting sets in example i used u set union make similar usual mathematical notation i use python notation ie union amp intersection if a b disjoint a b correspondence a b if common elements x a amp b appear twice a b x x so since symbol quite wellestablished meaning set operation i find consistent python use symbol set union intersection probably python designers mind chose set operators,i would like know valid setrange setrange valid setrange setrange is could mean intersection union,3 httpclientfactory used internally getpage constructor signature looks like def initself url method get postdatanone headersnone agenttwisted pagegetter timeout cookiesnone followredirect thus try passing headers keyword param clientgetpageiurlmethod get cookiescj headersheaders headers look quite normal,below us callback fetching page using twisted clientgetpageiurlheadersmethod get cookiescjaddcallbackselfprocesspageiurladderrbackselfprinterroriurl here format headers headers headers contenttype texthtml charsetutf useragent mozilla macintosh u intel mac os x enus rv gecko firefox i know user agent works i use urllib i extract fields require header using header twisted work i suspect i using headers twisted so proper way specify header code thanks,2 if lines array use key parameter sort function lambda split line spacestabs take second column convert float use comparison reverse causes order descending sorry tested works modulo typing errors datafileyourfilereadlines datasortkeylambda l floatlsplitreversetrue,i txt file containing lines follows first field keywords second field frequency keywords third field related texts anorexia nervosa ampampampampampampamp glaucoma want suck eyeballs replaced cancer drug helps fight cancer called avastin gene therapy writing review paper gene therapy hormone glad hormone injections end month depression depression made depression cake recipe i want parse file like keywords sorted keywords frequency cancer depression hormone glaucoma anorexia nervosa gene therapy i check questions sort order problem i find good example sort seem worked please let know good start point,1 what looking called voxel visualization voxel grid i would seriously consider mayavi never used i keep eye seems something close paraview built atop vtk like mayavi might good option i think going straight vtk visualization difficult lowlevel probably make frustrated that said want save data vtk datasets opening mayaviparaview difficult pick right structure vtkgrid vtkunstructedgrid,in day job phd student i geological modeling in spare time mainly fun i learning python trying write simple program view d geocellular models the geocellular model d grid every grid cell value shown right figure so i would want viewer able display d grid model like picture right side as well i would like able display cross sections model x z directions shown left figure i would also want models able rotate around three axes zoom i done preliminary investigation mainly seems like visvis vtk two potential options i trying use wxpython main gui looks like options work wxpython far i tell questions am i right i say i think visvis vtk would work i want is one preferable which two options would easiest implement is another option i also consider keep mind i newish python new wxpython,3 you manually close file descriptors after calling communicate call procstderrclose procstdoutclose,code used sync uploaded picture another place works period timeabout days service unusable showing error filedescriptor range select restart service solves problem syncpy def syncfilesourcepic hashval retrynum picpath ospathjoingendirhashval ospathsplitsourcepic filename tempfilemkstemp openfilename w f fwritepicpath syncpath optionssyncpaths trynum rsynccmd rsync au filesfrom filename optionspicpath syncpath trynum retrynum proc subprocesspopenrsynccmdstdoutsubprocesspipe stderrsubprocesspipe stdoutvalue stderrvalue proccommunicate lenstderrvalue loggererror sync failed stderrvalue trynum trynum raise uploadexception sync failed else break osremovefilename log info file pathtosyncpy line syncfile stdoutvalue stderrvalue proccommunicate file usrlibpythonsubprocesspy line communicate return selfcommunicateinput file usrlibpythonsubprocesspy line communicate rlist wlist xlist selectselectreadset writeset valueerror filedescriptor range select unclosed file descriptors cause error seems subprocess close file descriptor runs times file descriptor range using python subprocess forced use selectselect limit file descriptors even epoll available,1 using pil really needed plot array directly pyplot see to save file could use pltimsave fnamepng im,i numpy array binary values i would like convert matrix grayscale image python however i try reshape array x matrix i get memory error how i reduce size matrix turn image fit screen without losing uniquenessdata furthermore would i turn grayscale image any help advice would appreciated thank,2 we combine graphtheory probability on st day build set feasible solutions lets denote solutions set aa aan on second day build solutions set a now element a need check reached element a given x tolerance if connect an am if reached node am delete node basically building connected directed acyclic graph all paths graph equally likely you find exact solution single edge am am node am node am sure nodes appear paths nodes the probability node directly deduced based number paths contains node by assigning weight node equals number paths leads node need keep history previous day also look nonnegativevalues linear diphantine equations a question i asked ago the accepted answer great way enumarte combos step,i learning programming python algo’s trying work project i find interesting i created basic python scripts i’m sure approach solution game i trying build here’s game work users given items value for example apple pears oranges they get chance choose combo like ie apples pears oranges the output computer gets total valuein example currently the computer try guess which obviously won’t able get correctly first turn value quantityday valueday apple pears orange total the next turn user modify numbers total quantity percent may chose i’ll use example the prices fruit changeat random total value may change based alsofor simplicity i changing fruit prices example using example day game user returns value day here example quantityday changeday valueday quantityday changeday valueday i hope tables show right i manually space hopefully screen work let know i try upload screenshot i trying see i figure quantities timeassuming user patience keep entering numbers i know right restriction total value cannot i cannot within accuracy right user entering forever what i done far here’s solution farnot much basically i take values figure possible combos themi done part then i take possible combos put database dictionaryso example could dictionary entry apple pears oranges way apple pears oranges i time i get new number i list possibilities here’s i’m stuck is using rules i figure best possible solution i think i’ll need fitness function automatically compares two days data removes possibilities variance previous days data questions so question user changing total list probabilities i approach what i need learn is algorithms theories i use applicable or help understand mistake suggest rules i add make goal feasibleif current state i thinking adding fruits saying must pick least etc also i vague understanding genetic algorithms i thought i could use something i use i eager learn advice tips would greatly appreciatedjust please tell game impossible thanks advance update getting feedback hard solve so i thought i add another condition game interfere player doinggame stays everyday value fruits change pricerandomly would make easier solve because within movement certain fruit value changes combo probable time day anything possible getting close enough range almost impossible prices fruits change user choose change tover time range narrow narrow in example prices volatile enough i think i could brute force solution gave range guess i trying figure elegant solution solutions keep narrowing range time update after reading asking around i believe hidden markovviterbi problem tracks changes fruit prices well total sumweighting last data point heaviest i sure apply relationship though i think case could wrong least i starting suspect type machine learning problem update i created test casewith smaller numbers generator help automate user generated data i trying create graph see likely here code along total values comments users actually fruit quantities usrbinenv python import itertools fruit price data fruitpriceday apple pears oranges fruitpriceday apple pears oranges fruitpriceday apple pears oranges generate possibilities testingwarningwill scale large numbers def possibilitygeneratortargetsum apple pears oranges alldaypossible counter applerange range targetsum apple pearsrange range targetsum pears orangesrange range targetsum oranges j k itertoolsproductapplerange pearsrange orangesrange j k targetsum currentpossible print counter print apple iapple pears jpears oranges koranges currentpossible apple iapple currentpossible pears jpears currentpossible oranges koranges print currentpossible alldaypossiblecounter currentpossible counter counter return alldaypossible total sum returned user value fruits totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day graph graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges sample dict oranges apple pears oranges apple pears print graph,3 as others already given good solutions i try explain happens the systemexit exception raised sysexit differs exceptions one particullar way if caught sysexcepthook called instead printing message contained within extracting exit reason python shuts pyfinalize calls ansic function exit terminates process a solution either let process end normally see answers flush streams,i running code sysexit call end without sysexit line selfresponse works fine renders template but i call sysexit page returns blank it almost like sysexit interrupting template midrender why page indexhtml templatevalues path ospathjoinospathdirnamefile page selfresponseoutwritetemplaterenderpath templatevalues sysexit edit i solved problem using return instead sysexit,1 i made small changes make example work see code comments import urllib import oauth oauth import time oauthconsumerkey blahblahblah oauthconsumersecret blah def oauthrequesturl params methodget removed trailing commas make difference params oauthversion params oauthnonce oauthgeneratenonce params oauthtimestamp inttimetime consumer oauthconsumerkeyoauthconsumerkey secretoauthconsumersecret params oauthconsumerkey consumerkey req oauthrequestmethodmethod urlurl parametersparams reqsignrequestoauthsignaturemethodhmacsha consumer none return req name main url httpybossyahooapiscomysearchweb req oauthrequesturl paramsq cats dogs this one bit nasty apparently boss api like urls replace manually not sure api expected accept either not sure tourl return instead also oauthrequest seems store parameters unicode forget encode utf prior percentage encoding tourl method however handled correctly generating signatures tourl fails query parameters contain nonascii characters to work around manually utf encode request parameters req q req q encode utf requrl reqtourlreplace print requrl result urlliburlopenrequrl,i awfully hard time yahoo authenticationauthorization i enabled boss account set payment method i trying run search using python code import urllib import oauth oauth import time oauthconsumerkey blahblahblah oauthconsumersecret blah def oauthrequesturl params methodget params oauthversion params oauthnonce oauthgeneratenonce params oauthtimestamp inttimetime consumer oauthconsumerkeyoauthconsumerkey secretoauthconsumersecret params oauthconsumerkey consumerkey req oauthrequestmethodmethod urlurl parametersparams reqsignrequestoauthsignaturemethodhmacsha consumer none return req name main url httpybossyahooapiscomysearchweb req oauthrequesturl paramsq cats dogs requrl reqtourl print requrl result urlliburlopenrequrl i keep getting urllibhttperror http error unauthorized exception i figure whether something wrong key method signing i somehow tampering data signing deal anyone suggestions,3 solution eudoxos work split tabs ie datafileyourfilereadlines datasortkeylambda l floatlsplit reversetrue here looks input text i assumes different fields delimited tabs however delimits comma better solution possibility mixing tabs spaces,i txt file containing lines follows first field keywords second field frequency keywords third field related texts anorexia nervosa ampampampampampampamp glaucoma want suck eyeballs replaced cancer drug helps fight cancer called avastin gene therapy writing review paper gene therapy hormone glad hormone injections end month depression depression made depression cake recipe i want parse file like keywords sorted keywords frequency cancer depression hormone glaucoma anorexia nervosa gene therapy i check questions sort order problem i find good example sort seem worked please let know good start point,1 just ignore exception start script true try dowork except exception e print exception occurred restarting e pass,i wrote twitter scraper i want run indefinitely server pythondjango how i make sure always runs i understand i make cronjob start however sometimes script errors twitter connection fails how i make something checks script still running every minute i could make cronjob start every minute i want still running properly need restarted,1 no way decide whether myfunca b means args args ab args args b args ab args instead simply let function take two lists arguments,i would like create function uses two variable length arguments for example def myfuncargs args args stuff j args stuff is way python use one args thanks advance help,3 you use lists that way obvious item goes argument def myfuncargs args args print b args print b myfunc,i would like create function uses two variable length arguments for example def myfuncargs args args stuff j args stuff is way python use one args thanks advance help,1 the headers parameter twistedwebclientgetpage accepts dict twistedwebhttpheadersheaders instance,below us callback fetching page using twisted clientgetpageiurlheadersmethod get cookiescjaddcallbackselfprocesspageiurladderrbackselfprinterroriurl here format headers headers headers contenttype texthtml charsetutf useragent mozilla macintosh u intel mac os x enus rv gecko firefox i know user agent works i use urllib i extract fields require header using header twisted work i suspect i using headers twisted so proper way specify header code thanks,3 text ldapalberthwangeeidldapmengeeidbuildingcl sample dictitemsplit item partsplit part textsplit printsample eeid ldap alberthwang building cl eeid ldap meng printsample building cl list comprehensions convenient way construct lists a dict constructed iterable keyvalue pairs the iterable used generator expression str builtin type assigning string str overwrites builtin it better choose variable name avoid future surprising bugs i read write list comprehensions backwards expression variable iterable first understand iterable in solution textsplit variable causes variable assigned values iterable one time finally expression python expression usually using variable the syntax generator expressions almost the difference list comprehension generator expression list comprehension returns list generator expression returns iterator object yields contents ondemand looped next called instead generating items case list a list consume lot memory list long a generator expression consume less memory even infinite elements exist memory time,would turn string str ldapalberthwangeeidldapmengeeidbuildingcl list give print x building cl would x ldap alberthwang eeid ldap meng eeid building cl tried split string first append list sample strsplit sampleappends but stuck turn list items dictionary use populate another list,2 the following using numpy might get started it fast enough though could get much faster even python look see httpwwwscipyorgperformancepython by way several drawbacks method described cannot control speed ripples would modify equations used ripple function figure relates wave equation httpenwikipediaorgwikiwaveequation done depth pool fixed probably shallow i added depth parameter magnify effect article reads integer pixel offsets would get much nicer result interpolated values guess opengl knowledge area nil code import numpy def ripplew w damp n xrangen w w w w w w w w w w damp w w w w def refractx w rindex depth sx x x sy dwdx w w sx dwdy w w sy xang numpyarctandwdx xrefract numpyarcsinsinxang rindex dx numpytanxrefract dwdx depth yang numpyarctandwdy yrefract numpyarcsinsinyang rindex dy numpytanyrefract dwdy depth dx numpysigndwdx dy numpysigndwdy xmin x xmax x x dx x numpywherex xmin xmin x x numpywherex xmax xmax x ymin ymax dy numpywherey ymin ymin numpywherey ymax ymax x grids numpymeshgrid call sample usage xy meshgridxy w exp xx yy w wcopy xy meshgridrlenx rleny ripplew w w modified refractx w rindex depth x modified numpyaroundx outx get better results interpolate numpyaroundy outy,i googled ready scripts opposed effect flash i checked algorithm the water effect explained also tested implementation perlin noise provides good simulation end waves flat surface i looking implementation found several flash effects based mouseoverhover actions this targetting interactive floor library i would enjoy moving away flash matter particularly avoid easy reverseengineering code yes i know could use readymade flash code i would use last resort has anyone seen suitable implementation effect pygame using opengl edit can anyone provide suitable implementation effect using opencvopengl pygame the culprit code interface pass list values sent external interpreter tracker tuio though via python i tried straight days pygame able generate anything fast sheer cc code used shaders opengl knowledge cc null so target least coming python code a good example different flash effect still good water simulation using java applet bounty showing answers enough detail since closest op incapable creating code wants lacks fundamental skills answer probably use several people,3 vpython simpler use mayavi fewer features httpvpythonorgcontentsbounceexamplehtml,in day job phd student i geological modeling in spare time mainly fun i learning python trying write simple program view d geocellular models the geocellular model d grid every grid cell value shown right figure so i would want viewer able display d grid model like picture right side as well i would like able display cross sections model x z directions shown left figure i would also want models able rotate around three axes zoom i done preliminary investigation mainly seems like visvis vtk two potential options i trying use wxpython main gui looks like options work wxpython far i tell questions am i right i say i think visvis vtk would work i want is one preferable which two options would easiest implement is another option i also consider keep mind i newish python new wxpython,1 what i understood huge number ids file want know specific userid file you use python set fd openfilepath mode ids setintid id fd userid ids numberofususer,i number set contains unique numbers txt file the data structure looks like i want match number line another data number set extracting data i need so i coded like def getususersidsfilepath mode ids openfilepath mode f line f sp linestrip id sp idsappendidlower return ids ids joingetususersids nasusauserlisttxt r matcher recompileids matchermatchuserid numberofususer text tweetsplit but takes lot time running is idea reduce run time,1 i think except multiline string processed however python ides shortkey commenting multiple lines code,i recently started studying python i find implement multiline comments most languages block comment symbols like i tried python throws error probably correct way does python actually multiline comment feature,2 python multiline stringcomment syntax sense unless used docstrings multiline strings generate bytecode like prepended comments in effect acts exactly like comment on hand say behavior must documented official docs true comment syntax yes would right say guaranteed part language specification in case editor also able easily commentout selected region placing front line individually if switch editor programming python without certain text editing features painful experience finding right editor knowing use make big difference python programming experience perceived not editor able commentout selected regions also able shift blocks code left right easily automatically place cursor current indentation level press enter code folding also useful to protect link decay content guido van rossum tweet bsucsclub python tip you use multiline strings multiline comments unless used docstrings generate code,i recently started studying python i find implement multiline comments most languages block comment symbols like i tried python throws error probably correct way does python actually multiline comment feature,3 afaik python block comments for commenting individual lines use character if using notepad shortcut block commenting i sure others like gvim emacs similar features,i recently started studying python i find implement multiline comments most languages block comment symbols like i tried python throws error probably correct way does python actually multiline comment feature,3 elementtext seems none iterations the error saying cant look none check elementtext none first like html etreefromstringplanhtmlclearutf questions htmlxpath questionairequestion question questions â â element questiongetchildren â â â â elementtag answer elementtext elementtext â â â â â â htmlxpath questionaire removequestion print etreetostringhtml the line failing xml answeranswer text tag edit second part issue combining tags you use beautifulsoup like lxml import etree import beautifulsoup planhtmlclearutfu questionaire question questiontextwhat upquestiontext answeranswer question question questiontextcoolquestiontext answeranswer question questionaire html etreefromstringplanhtmlclearutf questions htmlxpath questionairequestion question questions â â element questiongetchildren â â â â elementtag answer elementtext elementtext â â â â â â htmlxpath questionaire removequestion soup beautifulsoupbeautifulstonesoupetreetostringhtml print soupprettify prints questionaire question questiontext what questiontext answer answer question questionaire here link download beautifulsoup module or compact way lxml import etree import beautifulsoup abbreviating reduce answer length planhtmlclearutfuquestionairequestionaire html etreefromstringplanhtmlclearutf questiongetparentremovequestion question htmlxpath questionairequestionanswertext print beautifulsoupbeautifulstonesoupetreetostringhtmlprettify,i trying delete everything number i get following error typeerror argument type nonetype iterableif elementtag answer elementtext what wrong any help usrlocalbinpython coding utf lxml import etree planhtmlclearutfu questionaire question questiontextwhat upquestiontext answeranswer question question questiontextcoolquestiontext answeranswer question questionaire html etreefromstringplanhtmlclearutf questions htmlxpath questionairequestion question questions element questiongetchildren elementtag answer elementtext htmlxpath questionaire removequestion print etreetostringhtml,1 blender app i know gui written fully opengl problem c i python developer well i getting using ogl i honestly think toolkits develop gui ogl blender developers giving runaround documentation instead direct help i let know i figure edit bit documentation pyopengl functions httppyopenglsourceforgenetdocumentationmanualreferencegluthtml,i developing graphical application present data game real workhorse app it needs cross platform i chosen python opengl i need d blending textures etc pyopengl wxpywx windowing dialogs etc the last component wx raises question i put together nice looking app prototypes look slick i need interact user ask questions get input i use wx it makes app look inconsistent traditional ui traditional dialogs combos text entry top full screen d app blending smooth motion textures etc has anyone developed gui using opengl python can share toolkits andor tricks used i need combos text entry buttons radios option buttons tree view there toolkits either incomplete old unmaintained a great example pyui httppyuisourceforgenet looks slick untouched years,1 an alternative checking elementtext none refine xpath questions htmlxpath questionairequestionanswertext question questions questiongetparentremovequestion the brackets mean so question find question elements answer answer subelement text whose text equals,i trying delete everything number i get following error typeerror argument type nonetype iterableif elementtag answer elementtext what wrong any help usrlocalbinpython coding utf lxml import etree planhtmlclearutfu questionaire question questiontextwhat upquestiontext answeranswer question question questiontextcoolquestiontext answeranswer question questionaire html etreefromstringplanhtmlclearutf questions htmlxpath questionairequestion question questions element questiongetchildren elementtag answer elementtext htmlxpath questionaire removequestion print etreetostringhtml,1 if want easier way getting vtkmayavi world see eudoxos fine answer look mlab api this brings matplotliblike convenience basic volume visualizations i yet find need dig deeper underlying platform,in day job phd student i geological modeling in spare time mainly fun i learning python trying write simple program view d geocellular models the geocellular model d grid every grid cell value shown right figure so i would want viewer able display d grid model like picture right side as well i would like able display cross sections model x z directions shown left figure i would also want models able rotate around three axes zoom i done preliminary investigation mainly seems like visvis vtk two potential options i trying use wxpython main gui looks like options work wxpython far i tell questions am i right i say i think visvis vtk would work i want is one preferable which two options would easiest implement is another option i also consider keep mind i newish python new wxpython,2 take look streaming contents,php flush function used push content client meanwhile keep current connection look flask found function like python web framework support flush ps reason use flush implement comet iframe stream though ajax long poll thing,1 you need python byteplay httpcodegooglecompbyteplay installed dizpy usrbinenv python import byteplay marshal sys name main sysstdinread c byteplaycodefromcodemarshalloadsysstdincode labels set x l c x l isinstancex byteplaylabel labels dictli il enumeratelabels byteplaylabelrepr lambda self labelsd labelsself print reprc azpy usrbinenv python import byteplay sys imp struct marshal time name main byteplaylabels dicti byteplaylabel xrange sysplatform win import os msvcrt msvcrtsetmodesysstdoutfileno osobinary asm sysstdinread c evalasm byteplaydict c byteplaycodec tocode sysstdoutwriteimpgetmagic sysstdoutwritestructpack l timetime marshaldumpc sysstdout usage python dizpy foopyc fooaz python azpy fooaz foopyc,how i recompile pyc files made python python i source files i cannot obtain i looking free solution,2 this problem impossible solve lets say know exactly ratio number items increased maximum ratio user n fruits d days guessing in day get n new variables total dn variables for day generate equations one equation sum nitemprice based know ratio in total d equations independent d nd n,i learning programming python algo’s trying work project i find interesting i created basic python scripts i’m sure approach solution game i trying build here’s game work users given items value for example apple pears oranges they get chance choose combo like ie apples pears oranges the output computer gets total valuein example currently the computer try guess which obviously won’t able get correctly first turn value quantityday valueday apple pears orange total the next turn user modify numbers total quantity percent may chose i’ll use example the prices fruit changeat random total value may change based alsofor simplicity i changing fruit prices example using example day game user returns value day here example quantityday changeday valueday quantityday changeday valueday i hope tables show right i manually space hopefully screen work let know i try upload screenshot i trying see i figure quantities timeassuming user patience keep entering numbers i know right restriction total value cannot i cannot within accuracy right user entering forever what i done far here’s solution farnot much basically i take values figure possible combos themi done part then i take possible combos put database dictionaryso example could dictionary entry apple pears oranges way apple pears oranges i time i get new number i list possibilities here’s i’m stuck is using rules i figure best possible solution i think i’ll need fitness function automatically compares two days data removes possibilities variance previous days data questions so question user changing total list probabilities i approach what i need learn is algorithms theories i use applicable or help understand mistake suggest rules i add make goal feasibleif current state i thinking adding fruits saying must pick least etc also i vague understanding genetic algorithms i thought i could use something i use i eager learn advice tips would greatly appreciatedjust please tell game impossible thanks advance update getting feedback hard solve so i thought i add another condition game interfere player doinggame stays everyday value fruits change pricerandomly would make easier solve because within movement certain fruit value changes combo probable time day anything possible getting close enough range almost impossible prices fruits change user choose change tover time range narrow narrow in example prices volatile enough i think i could brute force solution gave range guess i trying figure elegant solution solutions keep narrowing range time update after reading asking around i believe hidden markovviterbi problem tracks changes fruit prices well total sumweighting last data point heaviest i sure apply relationship though i think case could wrong least i starting suspect type machine learning problem update i created test casewith smaller numbers generator help automate user generated data i trying create graph see likely here code along total values comments users actually fruit quantities usrbinenv python import itertools fruit price data fruitpriceday apple pears oranges fruitpriceday apple pears oranges fruitpriceday apple pears oranges generate possibilities testingwarningwill scale large numbers def possibilitygeneratortargetsum apple pears oranges alldaypossible counter applerange range targetsum apple pearsrange range targetsum pears orangesrange range targetsum oranges j k itertoolsproductapplerange pearsrange orangesrange j k targetsum currentpossible print counter print apple iapple pears jpears oranges koranges currentpossible apple iapple currentpossible pears jpears currentpossible oranges koranges print currentpossible alldaypossiblecounter currentpossible counter counter return alldaypossible total sum returned user value fruits totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day graph graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges sample dict oranges apple pears oranges apple pears print graph,3 an important thing keep mind python different bits code executed along fact class def statements executed seen stored away later with def little easier understand thing executed whatever code def init self name myclassdefaultname python sees myclassdefaultname tries find first local namespace module aka global namespace finally builtins what local namespace executing class statement that fun part become class namespace moment anonymous reference name aka myclass code directly reference anything already defined defined in class example one thing defaultname so init look like def init self namedefaultname keep mind change myclassmyclassdefaultname later changes show new instances why because init def executed whatever value defaultname moment stored away always used unless directly specify new value create new instance myinstance myclassname new name,i would like use class attribute default value one arguments class init method this construct raises nameerror exception though i understand class myclass defaultname defaultname def initself name myclassdefaultname selfname name why fail way works,3 if sequence characters long use buffers overlapping characters that way sure sequence even slip buffers here example help visualize ampx ampx ampx x as implementation prepend last characters last buffer new buffer buffer buffer freadbuffersize the problem concatenation may require copy whole buffer another solution random access file rewind little bit fseek osseekcur in case modify script slightly handle first iteration,i xml files contain invalid characters sequences cause parsing fail they look like ampx to solve problem i escaping replacing whole thing escape sequence ampx then i done parsing i restore buffersize kb buffer def escapefilename filefilename esc w openfilename r f buffer x prettier way handle first one buffer buffer freadbuffersize outwriteresubr ampxafaf r buffer outclose the files large i use buffering mmap gave memoryerror because buffer fixed size i running problems buffer happens small enough split sequence imagine buffer size file like helloampx the buffer read helloampx allowing ampx slip cracks how i solve i thought getting characters last look like could belong character sequence logic i thought ugly,1 first bother read write file create filelike object wraps open file processes data handled parser second buffering take care ends read bytes here working code class wrappedobject def initself f selff f selfbuffer def readself size buf selfbuffer selffreadsize buf bufreplace buf resubrampxafaf r buf if ampersand near end hold onto piece sure miss one lastamp bufrfindamp lastamp selfbuffer buflastamp buf buflastamp else selfbuffer return buf then code replace etiterparsefilexml rb etiterparsewrappedfilexml rb third i used substitution replacing amp fix parsing counting obscure sequences this stack overflow data lots strange random punctuation could occur naturally,i xml files contain invalid characters sequences cause parsing fail they look like ampx to solve problem i escaping replacing whole thing escape sequence ampx then i done parsing i restore buffersize kb buffer def escapefilename filefilename esc w openfilename r f buffer x prettier way handle first one buffer buffer freadbuffersize outwriteresubr ampxafaf r buffer outclose the files large i use buffering mmap gave memoryerror because buffer fixed size i running problems buffer happens small enough split sequence imagine buffer size file like helloampx the buffer read helloampx allowing ampx slip cracks how i solve i thought getting characters last look like could belong character sequence logic i thought ugly,1 it seems startdate tuple single date value that date filter work you check cstartdate date looks like tuple,i adding variable dictionary like rrcontextstartdate cstartdate and i pass dictionary rendertoresponse return rendertoresponse rrtemplate rrcontext contextinstancerequestcontextrequest then template i try format way startdatedatef but returns nothing i found problem reason django passes variable looking like datetimedate i know happens way i read docs i think i right way what issue,1 i followed procedure i got winpdb working however closer look i realized working rpdb entity spepluginswinpdb another installation sitepackages maybe problem related in procedure forgot include initpy file winpdb module it come winpdb zip distribution file needed convert folder package modules imported you info packages module search so copy paste initpy file old new folder empty file anyway,the default version winpdb spe v problems work python here i done upgrade version winpdb v step rename cprogram filesspecwxnosetupspepluginswinpdb cprogram filesspecwxnosetupspepluginswinpdbv step download winpdb v copy folder cprogram filesspecwxnosetupspepluginswinpdb step load winpdb v directly without problems cpythonpythonexe cprogram filesspecwxnosetupspepluginswinpdbwinpdbpy step launch winpdb spe c following errors python default jun msc v bit intel win type help copyright credits license information traceback recent call last file cprogram filesspecwxnosetupspesmwxpnotebookctrlpy line onmousemotion insidetab selfgetinsidetabpt file cprogram filesspecwxnosetupspesmwxpnotebookctrlpy line getinsidetab tabs selftabrect attributeerror tabctrl object attribute tabrect traceback recent call last file cprogram filesspecwxnosetupspedialogswinpdbdialogpy line ondebug pluginswinpdb import file filename file cprogram filesspecwxnosetupspepluginswinpdbrpdbpy line rpdbimportwrapper gimportargs kwargs importerror no module named winpdb i done following things without solving problem add path cdocuments settingsdaliuset pythonpath pythonpathcprogram filesspecwxnosetupspepluginswinpdb add code import sys syspathappendr cprogram filesspecwxnosetupspepluginswinpdb rpdbpy winpdbdialogpy question why spe find winpdb module old winpdb version question how fix problem thank,1 there pad module scheduled inclusion numpy – see ticket for download use withconstant function unpadding simple field,program numpy array convolution filtering looking way make array padding unpad output easily using numpy avoid boundary checking know scipy convolution reasons make gnuplotpy used output def touchfield coords value fieldcoords coords value coords fieldcoords coords value coords fieldcoords coords value coords fieldshape fieldcoords coords value coords fieldshape fieldcoords coords value,3 use max function it operation correctly maxintgrossfilm film year yearfilm c your problem set maxgross zero iteration so values last ignored please also look creating film class using one dict film objects rather multiple parallel dicts,i problem i need use data csv file find film high gross total year i already dict year film year came gross despite code still returning max gross what i missing def maxgrossfinderc film year maxgross f intgrossfilm yearfilm c f maxgross maxgross f return maxgross,2 take maxgross forloop def maxgrossfinderc maxgross film year f intgrossfilm yearfilm c f maxgross maxgross f return maxgross with maxgross inside forloop prior iterations mean nothing only last would affect maxgross that probably intention another problem might occur c yearfilm floats don compare floats equality unless know since floats inexact representations instead define concept nearness def nearabrtoleatole return absabatolrtolabsb compare nearyearfilmc,i problem i need use data csv file find film high gross total year i already dict year film year came gross despite code still returning max gross what i missing def maxgrossfinderc film year maxgross f intgrossfilm yearfilm c f maxgross maxgross f return maxgross,1 you could use psutil psutil provides information running processes system utilization,i task whenever specific applications launched is way list processes running operating system detect whenever new process created operating system,2 this official way edit copied verbatim example link import wincomclient wincomclientgencacheisreadonly true allow gencache create cached wrapper objects wincomclientgencacheisreadonly false pexe call gencache init happen use rebuild force creation genpy folder wincomclientgencacherebuild nb you must ensure pythonwincomclientgenpy dir exist allow creation cache temp use sapi speech idispatch wincomclientgencache import ensuredispatch wincomclient import constants voice ensuredispatchsapispvoice bfordemand voicespeak hello world constantssvsflagsasync,i program uses wincom library control itunes issues getting compile executable the problem seems revolve around using dispatchwithevents instead dispatch i created simple program illustrate problem import wincomclient wincomclientgencacheisreadonly false from pyexe wiki class ituneseventsobject def initself selfcomenabled true def oncomcallsdisabledeventself reason selfcomenabled false def oncomcallsenabledeventself selfcomenabled true the first line works exe second itunes wincomclientdispatchitunesapplication itunes wincomclientdispatchwitheventsitunesapplication itunesevents lib getattritunes libraryplaylist src getattrlib source playlists getattrsrc playlists print found playlists getattrplaylists count using dispatch program compiles runs correctly using dispatchwithevents program runs fine called command line produces following error running exe traceback recent call last file sandboxpy line module itunes wincomclientdispatchwitheventsitunesapplication itunesevents file wincomclientinitpyc line dispatchwithevents file wincomclientgencachepyc line ensuremodule file wincomclientgencachepyc line makemodulefortypelib file wincomclientmakepypyc line generatefromtypelibspec file wincomclientgencachepyc line getgeneratepath ioerror errno no file directory distdirlibraryzipwincomgenpyinitpy i also tried using pyinstaller gives similar error file string line module file outdirwincomclient line dispatchwithevents file outdirwincomclientgencache line ensuremodule file outdirwincomclientgencache line makemodulefortypelib file outdirwincomclientmakepy line generatefromtypelibspec file outdirwincomclientgencache line addmoduletocache file outdirwincomclientgencache line getmodule file pyinstallerdiriupy line importhook raise importerror no module named fqname importerror no module named wincomgenpyecfcfdfbabaxxx i know i manually add typelib setuppy file i like run code computers different versions itunes without recompiling i prefer dynamically create if way setupspec maybe another way load events thanks addition thanks ryan i found i could take generated py file little digging able come following take generated py file makepypy rename somewhere like cominterfacepy then need following actually create com object event handler import cominterface types import classtype wincomclient import eventsproxy eventsetattr class itunesevents itunes events class see cominterface details def onplayerplayeventself tprint playing def onplayerstopeventself print stopping itunes cominterfaceitunesapp rclass classtypecomeventclass itunesclass itunesdefaultsource itunesevents setattr eventsetattr instance rclassitunesoleobj itunesdefaultsourceinitinstance instance ituneseventsinitinstance uncomment line events class init itunes eventsproxyinstance then go business,1 use regular expression module for example third delimited field sample record variable match rematchrptitle pnum pspecial title matchgroups title issue matchgroups num special matchgroups special you get indexerror last three lines missing field adapt re parses everything want,i new pythondjango i trying suss effective information scraper currently scraper takes list comic book titles correctly divides csv list three parts published date original date title i pass current date title different parts databse i loader script convert mmddyy yyyymmdd save pubdate column title goes title column a common string look like stan lee traveler copy incentive cover i successfully grabbing date title trickier in instance i ideally like fill three different columns information second the title go title charfield number go decimalfield issuenum everything go special charfield i sure kind rigorous parsing sometimes multiple one comic particular described bundle containing issues several multiple groups betrayal of the planet of the apes of copy incentive cover what would good road start onto crack problem my knowledge ifelse statements quickly fell apart complicated lines how i efficiently possible pythonicly parse lines subdivide i later slot correct place database,1 parsing title hard part sounds like handle dates etc the problem one rule parse every title many rules guess one works particular title i usually handle creating list rules specific general try one one one matches to write rules use module even pyparsing the general idea goes like class cantparseexception pass one rule parse one kind title import def titlewithspecial title accepts title form text issue special rematchrd title return mgroup mgroup else raise cantparsetitle def parseextratitle rules tries parse extra information title using rules rule rules try return ruletitle except cantparse pass nothing matched raise cantparsetitle lets try rules titlewithspecial list rules apply add functions titles stan lee traveler copy incentive cover betrayal of the planet of the apes of copy incentive cover title titles try issue special parseextratitle rules print parsed title issues special issue special except cantparse print no matching rule title as see first title parsed correctly nd you write bunch rules account every possible title format data,i new pythondjango i trying suss effective information scraper currently scraper takes list comic book titles correctly divides csv list three parts published date original date title i pass current date title different parts databse i loader script convert mmddyy yyyymmdd save pubdate column title goes title column a common string look like stan lee traveler copy incentive cover i successfully grabbing date title trickier in instance i ideally like fill three different columns information second the title go title charfield number go decimalfield issuenum everything go special charfield i sure kind rigorous parsing sometimes multiple one comic particular described bundle containing issues several multiple groups betrayal of the planet of the apes of copy incentive cover what would good road start onto crack problem my knowledge ifelse statements quickly fell apart complicated lines how i efficiently possible pythonicly parse lines subdivide i later slot correct place database,1 you could use textwrapwrap break text list strings width characters long import textwrap lines textwrapwraptext width ytext h line lines width height fontgetsizeline drawtextw width ytext line fontfont fillforeground ytext height,i try add text bottom image actually i done case text longer image width cut sides simplify i would like text multiple lines longer image width here code foreground width height text chyba najwyå¼szy czas zadaä‡ pytanie na å›niadanie n chyba najwyå¼szy czas zadaä‡ pytanie na å›niadanie fontpath libraryfontsarialttf font imagefonttruetypefontpath encoding unic text textdecode utf width height fontgetsizetext x imageopen mediaconvertyimagepng imageopsexpandxborderfill white imageopsexpandyborderfill black w h ysize bg imagenew rgba w w h bgsize xo yo ww hh bgpastey xo xow h draw imagedrawdrawbg drawtextw width w text fontfont fillforeground bgshow bgsave mediaconvertytestpng,3 why try valid set string substrings dictionarywordshaskeystring validaddstring fwritelinessortedvalid there need extra forloop inside main forloop this haskey solves issue moving next substring string dictionaryword hope helps,i got code looks like valid set string substrings line dictionarywords string line validaddstring fwritelinessortedvalid both dictionarywords substrings currently lists after substring found inside dictionarywords go ahead move onto next substring what best way writing,1 if meant predict number return values function j hillupillu raise valueerror function return exactly two values you catch usual try construct try j hillupillu except valueerror printhey i expecting two values this follows common python idiom asking forgiveness permission if hillupillu might raise valueerror want explicit check r hillupillu lenr maybe check whether tuple well isinstancer tuple printhey i expecting two values j r if meant want check none returned values check none j clause,basic stuff i knowp but best way check function returns values def hillupillu none blillestalle return ab j hillupillu check j empty coursep print ij,3 valid set string substrings line dictionarywords string line validaddstring break fwritelinessortedvalid fc if use continue instead break run next iteration inner forloop,i got code looks like valid set string substrings line dictionarywords string line validaddstring fwritelinessortedvalid both dictionarywords substrings currently lists after substring found inside dictionarywords go ahead move onto next substring what best way writing,1 functions python always return single value in particular return tuple if know many values tuple could check length tuple hillupillu tuple tuple else none j tuple lentuple else none,basic stuff i knowp but best way check function returns values def hillupillu none blillestalle return ab j hillupillu check j empty coursep print ij,3 you use example uri class ascorelib usage import comadobeneturi create uri want updated var newuriurinew uri resjerpng update newuri full path newurimakeabsoluteurinew uri httpwwwcwinldocpythonhtml traceuritostring output httpwwwcwinlresjerpng make utility function base function urljoinurlstring urlstringstring var uriurinew uriurl urimakeabsoluteuriurl return uritostring,python function urljoin takes two urls concatenates intelligently is library provides similar function as urljoin documentation httpdocspythonorglibraryurlparsehtml and python example urljoin httpwwwcwinldocpythonhtml resjerpng httpwwwcwinlresjerpng i want know implementation urljoin function whole urlparse package,2 managepy probably executable bit set purpose use python managepy instead per django docs,i trying migrate django app using south getting permission denied warning i logged root though i know risk risk trying get things setup why get rejected rootharoldomnicloudomnicloud managepy converttosouth omnicloudapp bash managepy permission denied,3 the execute method return value you would need use fetchone fetchall order get results first query,i trying insert results query table add variable result set i looked similar questions i think i representing query variables correctly i getting global variable defined error can point right direction i guessing fact i trying represent select statement variable i sure syntax look def main datadump datetimedatetoday querycursexecute select from data order by ac sqlresults querycursfetchall xyz sqlresults querycursexecute insert into history values x z createdbcommit thanks,1 have tried setting debug level http handler change code something like import urllib handlerurllibhttphandlerdebuglevel opener urllibbuildopenerhandler urllibinstallopeneropener respurlliburlopen httpwwwgooglecom read send get http acceptencoding identity host wwwgooglecom connection close useragent pythonurllib reply http ok header date sat oct gmt header expires header cachecontrol private maxage header contenttype texthtml charsetiso remainder send reply data so three lines prepend handlerurllibhttphandlerdebuglevel opener urllibbuildopenerhandler urllibinstallopeneropener rest urllib code that show raw http send reply cycle stderr edit comment does work code line openerurllibbuildopenerauthhandler urllibhttphandlerdebuglevel rest code,i making request using urllib httpbasicauthhandler like import urllib theurl httpsomeurlcom username username password password passman urllibhttppasswordmgrwithdefaultrealm passmanaddpasswordnone theurl username password authhandler urllibhttpbasicauthhandlerpassman opener urllibbuildopenerauthhandler urllibinstallopeneropener params foobar response urlliburlopen httpsomeurlcomsomescriptcgi params print responseinfo i currently getting httplibbadstatusline exception running code how could i go debugging is way see raw response regardless unrecognized http status code,3 you need make sure managepy executable bit set chmod ax managepy,i trying migrate django app using south getting permission denied warning i logged root though i know risk risk trying get things setup why get rejected rootharoldomnicloudomnicloud managepy converttosouth omnicloudapp bash managepy permission denied,1 if reason need execute managepy run chmod x managepy how ever larsmans already said python managepy way run,i trying migrate django app using south getting permission denied warning i logged root though i know risk risk trying get things setup why get rejected rootharoldomnicloudomnicloud managepy converttosouth omnicloudapp bash managepy permission denied,1 the following untested code equivalent loops valid sets substrings ln dictionarywords ln in python could use set comprehension valid substrings ln dictionarywords ln slightly efficient valid sets substrings anys ln ln dictionarywords,i got code looks like valid set string substrings line dictionarywords string line validaddstring fwritelinessortedvalid both dictionarywords substrings currently lists after substring found inside dictionarywords go ahead move onto next substring what best way writing,1 take look bellow datetime import datetime datetimenowstrftime dby oct datetimenowstrftime dby oct today datetimedatetoday todaystrftime dby printtoday,when using python strftime way remove first date th ie can find thingy thanks,2 yeah bit stuff standard python library jython implement probably platform dependent much work small jython community implement try looking java solution trivial invoke java code jython,i task whenever specific applications launched is way list processes running operating system detect whenever new process created operating system,2 some raw code want skip bloated libraries var urljoinfunction functionbasestring relativestringstring see already protocol relativeindexof return relative see protocolrelative relativeindexof var protocolindexint baseindexof return basesubstr protocolindex relative we need split domain path remaining options var protocolindexendint baseindexof baseindexof protocolindexend append slash passed httpblacom base var enddomainindexint baseindexof protocolindexend var domainstring basesubstr enddomainindex var pathstring basesubstrenddomainindex pathlastindexof pathlength trim ending file name path pathsubstr pathlastindexof see siteabsolute relativeindexof return domain relative see documentrelative relativeindexof relative relativesubstr pathlength var secondtolastslashindexint pathsubstr pathlengthlastindexof path pathsubstr secondtolastslashindex finally slap whatever ending left return domain path relative,python function urljoin takes two urls concatenates intelligently is library provides similar function as urljoin documentation httpdocspythonorglibraryurlparsehtml and python example urljoin httpwwwcwinldocpythonhtml resjerpng httpwwwcwinlresjerpng i want know implementation urljoin function whole urlparse package,1 the title string attribute tag p tag also notice space title questionssoupfindall classtitle the found looking html snippet p classtitlea classtitle hrefhttpwwwredditcomraskredditcommentslwhatsthebestfaceyoucanpullbeforeandafterwhat best face pull before pleasea span classdomaina hrefhttpwwwredditcomraskredditselfaskredditaspanp,i trying get thread titles raskreddit the code returns none instead thread title beautifulsoup import beautifulsoup import urllib json site httpwwwredditcomraskreddit soupbeautifulsoupurlliburlopensite questionssoupfindall p classtitle questions print istring break,1 given x list percents completion download x then use finite differencing get change deltax xi xi xrange lenx i written list comprehension could also loop,so problem downloader percent file downloaded far and sometimes percent doesent go one times goes etc say files percent download went like done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done done would want number percent went done done done done done done done done done done done done result would thing like know simple far ive tried thing like import random z c brandomrandint za b za print ca finalca print final im almost positive im making complicated,1 i hate reopen old post i hardest time installing pygame version python ubuntu default build so i created tutorial install python pygame ubuntu i hopes helps next unfortunate soul try,i reading book introduction computer science using python pygame paul craven note legally available free online in book uses combination python pygame in linux ubuntu machine i python even i sudo aptget installed pythonpygame version python import pygame python r sep gcc linux type help copyright credits license information import pygame traceback recent call last file stdin line module importerror no module named pygame python imports without fuss however python r apr gcc linux type help copyright credits license information import pygame are aware issues linuxubuntu python prof craven used windows book how come pygame worked python thanks pointers,2 the following simplest code i could come allowed position image position usrbinenv python import pyglet pygletgl import window pygletwindowwindow glenablegldepthtest image pygletimageload imgsappfoliopng texture imagegettexture glenabletexturetarget glbindtexturetexturetarget textureid glteximagedgltextured glrgb imagewidth imageheight glrgba glunsignedbyte imagegetimagedatagetdata rgba imagewidth rectw floatimagewidth imageheight recth windowevent def ondraw glclearglcolorbufferbit gldepthbufferbit glloadidentity gltranslatef glbindtexturetexturetarget textureid glbeginglquads gltexcoordf glvertexfrectw recth gltexcoordf glvertexf rectw recth gltexcoordf glvertexf rectw recth gltexcoordf glvertexfrectw recth glend def onresizewidth height glviewport width height glmatrixmodeglprojection glloadidentity gluperspective widthfloatheight glmatrixmodeglmodelview windowonresize onresize need replace use windowevent pygletapprun the difficult part i found onresize function replaced order work i expected default orthographic projection work i found jess hill pyglet conversion nehe tutorial texture mapping helpful the complete logo visualization code found blog entry i wrote titled moving images d space pyglet,i trying create logo visualization python i would like animate number images d space images always facing center screen images move fixed path i done python using vizard however i like free cross platform manor what quickest read shortest amount code using pyglet get handle imaged mapped quad i manipulate position orientation said quad,3 the documentation tell parses xml section element tree emphasis incrementally cover avoid retaining uninteresting elements may that covered article effbot i strongly recommend anybody using iterparse read article liza daly it covers lxml celementtree previous coverage so using python iterparse for large xml files can python xml elementtree parse large xml file what fastest way parse large xml docs python,a simplified version xml parsing function import xmletreecelementtree et def analyzexml etiterparsefilexml count ev el count print count formatcount this causes python run memory make whole lot sense the thing i actually storing count integer why see sudden drop memory cpu usage end that python crashing spectacularly at least gives memoryerror depending else i loop gives random errors like indexerror stack trace instead segfault but crashing,3 your implementation look before you leap style it pythonic execute code catch errors instead def getl dnone try return li except indexerror return,calling getkey dictionary return none default key present dictionary what idiomatic equivalent list list least size passed index element returned otherwise none returned to rephrase idiomaticcompact version function def getl lenl return li else return none,3 if expect li often exist use def getli return li ilenl else none if expect li almost always exist use tryexcept def getli try return li except indexerror return none rationale tryexcept expensive exception raised fairly quick otherwise,calling getkey dictionary return none default key present dictionary what idiomatic equivalent list list least size passed index element returned otherwise none returned to rephrase idiomaticcompact version function def getl lenl return li else return none,2 in clike type systems functions first order citizens there certain restrictions handling that decision simplicity speed implementationexecution stuck to functions behave like objects one generally requires support closures those however naturally supported mosts processors instruction sets as c designed close metal support when declaring recursive structures c type must fully expandable a consequence pointers selfreferences struct declarations struct rec struct rec struct rec next also every identifier use declared one restrictions functiontypes one forward declare a state machine c usually works making mapping integers functions either switch statement jump table typedef int funct void run funct table b c int state whiletrue state tablestate alternatively could profile python code try find code slow you port critical parts cc keep using python state machine,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,3 the problem haskell code type introduces synonym quite similar typedef c one important restriction expansion type must finite give finite expansion state machine a solution using newtype a newtype wrapper exist type checker absolutely zero overhead excluded stuff occurs generalization removed here signature typechecks newtype fn fn unfm io fn please note whenever want use fn unpack first using unfn whenever return new function use fn pack,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,3 your problem recursive declaration function pointer c c operator overloading used hide mechanics essentially c haskell solutions herb sutter describes gotw recursive declarations struct funcptr typedef funcptr funcptr struct funcptr funcptr funcptr pp p pp operator funcptr return p funcptr p funcptr f return f natural return syntax int main funcptr p f natural usage syntax p but business functions likelihood perform worse equivalent numeric states you use switch statement state table really want situation structured semantic equivalent goto,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,1 here function finding columns bunch lines the second argument pat defines column regex import itertools import def findcolumnslines pat r usage widths findcolumnslines line lines line continue vals linewidthsiwidthsistrip rangelenwidths widths maxlen maxlenline line lines line lines line joinline maxlenlenline candidates match refinditerpat line candidatesextendrangematchstart matchend widthsappendsetcandidates widths sortedsetintersectionwidths diffs widthsiwidthsi rangelenwidths diffs nonediffs widths w w zipdiffs widths widths widths widths return widths def reporttext key group itgroupbytextsplitlines lambda linelinestartswith id lines listgroup key print n joinlines else r azaz defines column whitespace followed alphabetic characters widths findcolumnslines pat r sazaz line lines line continue vals linewidthsiwidthsi rangelenwidths vals v vstrip else v v vals print joinvals text id hello world another line text more text even text id another table another line text more text even text reporttext yields id hello world another line text more text even text id another table another line text more text even text,i tables looks like text id hello world another line text more text even text id another table another line text more text even text is way replace blank entries table i trying set delimiters entries using following code deal blank spots tables line textsplitlines id line line linesplit line join joinline joinline print line else print line the output id hello world another line oftext more text even moretext id another table another line withtext more texthere even text as see first problem shows second line first table the word text considered first column any way fix python replace blank entries,1 in haskell idiom go ahead execute next state type statemachine io b c statemachine print b b print b c c print c you need worry overflow stack anything like if insist states make data type explicit data possiblestates a b c type statemachine possiblestates io possiblestates machine a print return b machine b print b return c machine c print c return a you get compiler warnings statemachine forgot states,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,3 if use newtype instead data incur overhead also wrap state function point definition expressions use import controlmonad newtype state state runstate io state state state print return b b state b state print b return c c state c state print c return runmachine state io runmachine runmachine runstate main runmachine edit struck runmachine general form monadic version iterate iteratem monad iteratem f b f iteratem f b return aas main iteratem runstate edit hmm iteratem causes spaceleak maybe iteratem would better iteratem monad iteratem f f iteratem f main iteratem runstate edit if want thread state state machine use definition state change state functions int state state print show return b b int state b state print b show return c c int state c state print c show return main iteratem runstate,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,3 receiver imported dispatch module djangodispatch import receiver note receiver decorator added django you check django version import django djangoversion edit the wrong import statement part init module dispatch package gotten version rewrite delete whole django package directory cpythonlibsitepackagesdjango reinstall it crude probably best solution,very basic django app gives following i try anything runserver syncdb thoughts if problem one files could help guide issue may file librarypythonsitepackagesdjangodispatchinitpy line module djangodispatchdispatcher import signal receiver importerror cannot import name receiver,2 regular expression way go but fill uncomfortably writing try small parser i wrote httpsgithubcomhgreccostringparser it translates string format pep regular expression in case following stringparser import parser p parserrdatesdatestitlesissued specials x pstan lee traveler copy incentive cover ordereddict date date title stan lee traveler issue special copy incentive cover xissue the output case ordered dictionary this work simple cases might tweak catch multiple issues multiple one thing notice current version need manually escape regex characters ie want find need type i planning change soon,i new pythondjango i trying suss effective information scraper currently scraper takes list comic book titles correctly divides csv list three parts published date original date title i pass current date title different parts databse i loader script convert mmddyy yyyymmdd save pubdate column title goes title column a common string look like stan lee traveler copy incentive cover i successfully grabbing date title trickier in instance i ideally like fill three different columns information second the title go title charfield number go decimalfield issuenum everything go special charfield i sure kind rigorous parsing sometimes multiple one comic particular described bundle containing issues several multiple groups betrayal of the planet of the apes of copy incentive cover what would good road start onto crack problem my knowledge ifelse statements quickly fell apart complicated lines how i efficiently possible pythonicly parse lines subdivide i later slot correct place database,1 you get effect c python code declare functions return void include stdioh typedef void myfuncvoid void avoid void bvoid void cvoid void avoid printfan return b void bvoid printfbn return c void cvoid printfcn return void main void state state myfuncstate sleep,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,2 from practical stand point whole lot difference partial curry number arguments case instancemethod pass self instance whatever happens wrapped function they thing the difference somewhat document in linked question closure callable method anything regular function returned method a it happens body sees instance b first argument enough make method b so matter style you something looks like functoolspartial use even though achieve effect typesmethodtype,this continuation question python closure oop in answer question winston ewert suggested use functoolspartial instead typesmethodtype so question difference two why functool way considered better ps i managed use functoolspartial closure feel cool,1 the reliable way i found include extra files distribution using distutils provide manifestin file place file directory setuppy include list resource files require for example manifestin file might like include resourcessomefiletxt resourcespng recursiveinclude resourcesstatic png jpg css js see distutils documentation details though i prefer manifestin method using setuptools distribute look answer alternative method thing,i working website project when i use setuppy run setuppy build build script excludes resources web site basically non python files what i wrong,1 you need make two sql queries instead use insert query form insert into select connsqliteconnect cursorconncursor today datetimedatetoday sql insert into history select foo bar baz from data order by ac cursorexecutesqltoday conncommit,i trying insert results query table add variable result set i looked similar questions i think i representing query variables correctly i getting global variable defined error can point right direction i guessing fact i trying represent select statement variable i sure syntax look def main datadump datetimedatetoday querycursexecute select from data order by ac sqlresults querycursfetchall xyz sqlresults querycursexecute insert into history values x z createdbcommit thanks,1 if error exactly no module named random written import random really meant import random there module python standard library called random module names case sensitive python if solve problem please show us code whatever module imports random,python i run python via command line import random works fine when i run django based website python managepy runserver server starts fine soon i load page tosses error i really clue fix i done searching random core python import i tried python interpreter seems indicated working however working running website any help would greatly appreciated thanks p,2 i think perhaps rfft performed wrong axes by default uses last two axes axes the third axis represents rgb channels instead seems plausible one would want perform fft spatial axes axes import image import numpy np imageopen imagepng convert rgb npasarrayi npuint printashape b absnpfftrfftaaxes b npuintb j imagefromarrayb jsave tmpimgpng,i attempting use fft module numpy import image numpy imageopen imgpng numpyasarrayi numpyuint b absnumpyfftrffta b numpyuintb j imagefromarrayb jsave imgpng however i try convert numpy array back pil image i get error typeerror cannot handle data type however b arrays appear data type uint imagefromarraya runs fine i notice shapes slightly different ashape vs bshape i fix find data types pil accepts,3 you use qtimer reference object callback something like work def callthis selfwpcpuusagedisplaycpupercentinterval selfmytimer qtcoreqtimer selfmytimertimeoutconnectcallthis selfmytimerstart second interval,i learning program pyqt python i trying code simple app display current cpu usage qlcd widget for cpu usage i using psutils module the problem cpu usage updated time records cpu usage moment app launched i guessing stops so i looking sort loop equivalent hopefully take much cpu power process this i far selfwpcpuusagedisplaycpupercentinterval within init qmainwindow class i tried putting loop iterates basically waits iterate executes program help,2 it sounds like trying render every html file directory why write renderer python language plenty others here example using wm could equally use lynx links find name html exec wm dump,i directory html files for files i want find visible texts text data would actually visible person viewing file browser i seen fine solutions using libraries beautifulsoup i want something faster a regex based solution i wrote much faster would i speed things using kind file stream reader python what faster alternatives i happy lose accuracy using trusted parsers like beautifulsoup solution faster edit fast enough minutes faster hours that beautifulsoup takes average th second parse file seems optimistic based previous work i using,1 probably easiest way get exactly behaviour would using pyopenssl thin python wrapper openssl,i would like encrypt secret text publickey decrypt privatekey python i achieve openssl command echo secrettext openssl rsautl encrypt pubin inkey publicpem base datacry base d datacry openssl rsautl decrypt inkey privatepem how would one implement python,2 that means script executed successfully if code anything zero would indicate error yes command window likely python thread,i new python started learning today i installed python tools visual studio using vs editor my test python programs run correctly last line output window i see following the thread python thread xf exited code x please advice error means i resolve thanks bunch advance edit also whenever i try run program pressing f start debugging opens command window titled cprogram filespythonpythonexe seems calling main python file location is supposed open command window second i suspect command window python thread question edit for future new explorers python if using python tools visual studios might want build program shiftaltf instead f this output python interactive window inside vs display annoying command window popup,2 no matter app engine send response user handler code completes there currently way unfortunately tell app engine send response i output you options just put log entry synchronously datastore writes hugely expensive respect wallclock latency especially minimize number index updates needed enqueue task queue task write log data if use pull queues fetch log entries write batches datastore another task backend start datastore write log entry soon relevant data use asynchronous operation allowing overlap write processing,this probably noobish question i want make sure code i think here i get request make decision respond request decision log the sequence important writes slow i want make sure response published writes take place here sample code class conferencegreetinghandlerwebapprequesthandler def getself selfpost def postself xmltemplateself templatesconfgreetingxml newlog log newloglog test newlogput i think i serving response logging fact true also better way again sorry supernoobishness edit here template def xmltemplatehandler page valuesnone path ospathjoinospathdirnamefile page handlerresponseheaderscontenttype textxml handlerresponseoutwritetemplaterenderpath values,2 as usual despite great answers already present i resist trying one thing bothered presented ignores input state machinesthe ones i familiar withchoose various possible transitions based input data state vocab state stateid string possibleinputs vocab runtrans vocab state vocab goalstate stateid string instance show state show stateid runtransition eq vocab state vocab vocab maybe state vocab runtransition goalstate id nothing runtransition x x notelem possibleinputs nothing otherwise just runtrans x here i define type state parameterized vocabulary type vocab now let define way trace execution state machine feeding inputs tracemachine show vocab eq vocab state vocab vocab io tracemachine putstrln end input tracemachine xxs putstrln current state print putstrln current input print x putstrln case runtransition x nothing putstrln invalid transition just case goalgoalstate putstrln goal state reached print putstrln input remaining print xs tracemachine xs now let try simple machine ignores inputs be warned format i chosen rather verbose however function follows viewed node state machine diagram i think find verbosity completely relevant describing node i used stateid encode string format visual information state behaves data simplevocab a b c deriving eq ord show enum simplemachine state simplevocab simplemachine statea statea state simplevocab statea state stateid a state b possibleinputs abc runtrans stateb stateb state simplevocab stateb state stateid b state c possibleinputs abc runtrans statec statec state simplevocab statec state stateid c state a possibleinputs abc runtrans statea since inputs matter state machine feed anything ghci tracemachine simplemachine aaaa i include output also verbose see clearly moves statea stateb statec back statea now let make slightly complicated machine lesssimplemachine state simplevocab lesssimplemachine startnode startnode state simplevocab startnode state stateid start node a c possibleinputs ac runtrans startnodetrans startnodetrans c node startnodetrans a node node state simplevocab node state stateid node b start a goal possibleinputs b a runtrans nodetrans nodetrans b startnode nodetrans a goalnode node state simplevocab node state stateid node c goal a b possibleinputs abc runtrans nodetrans nodetrans a node nodetrans b node nodetrans c goalnode goalnode state simplevocab goalnode goalstate goal the possible inputs transitions node require explanation verbosely described code i let play tracemachine lesssipmlemachine inputs see happens inputs invalid adhere possible inputs restrictions hit goal node end input i suppose verbosity solution sort fails basically asking cut cruft but i think also illustrates descriptive haskell code even though verbose also straightforward represents nodes state machine diagram,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,3 you could vectorize function apply directly numpy array time need import numpy np def fx return x x x x else x f npvectorizef use different name want keep original f resultarray fa a numpy array it probably better specify explicit output type directly vectorizing f npvectorizef otypesnpfloat,given numpy array a fastestmost efficient way apply function f every cell suppose assign aij faij the function f binary output thus masking operations help is obvious double loop iteration every cell optimal solution,3 i faced similar problems discovered i used zero width joiner ud explicitly tell rendering engine join two characters that used work looks like changes rendering engine i aware i find joiner creates problem it broke working code i remove explicit zero width joiners code work hope helps,python tkinter processing unicode characters correctly but able display unicode encoded characters correctly i using python tkinter ubuntu i trying use tamil unicode characters all processing done correctly but display wrong here wrong display tkinter httpsdocsgooglecomleafidbyakkyneomumzingutntkncmzyzltknytmtjjytayjcmmeamphlengbampauthkeyckorhugk here correct display gedit httpsdocsgooglecomleafidbyakkyneondbmmzyzowetmjynynwmlwemwytmtgzdvhogqmmezamphlengbampauthkeycpwhij can someone please help,1 er actual exception object got caught except clause,try osexecvp sqlite args except oserror er ererrno file found raise oserror sqlite executable found is installed else raise except raise in code except statement catches oserror er variable stand edit one excepts oserror way except error get exception object,1 er exception object,try osexecvp sqlite args except oserror er ererrno file found raise oserror sqlite executable found is installed else raise except raise in code except statement catches oserror er variable stand edit one excepts oserror way except error get exception object,1 as others said er instantiated form exception oserror if helpful alternative somewhat explicit syntax using keyword try osexecvp sqlite args except oserror er ererrno file found raise oserrorsqlite executable found is installed else raise except raise which says er oserror as er syntax added python way,try osexecvp sqlite args except oserror er ererrno file found raise oserror sqlite executable found is installed else raise except raise in code except statement catches oserror er variable stand edit one excepts oserror way except error get exception object,3 try condition actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore when write ab c true equal b c true true true equal b c,i trying set function calculate score similarity two films there preexisting dictionaries films keys either directors genres main actors values there three actor dictionaries lead actors film listed the code mostly works fine sometimes i get resulting score greater i get create twovariable function deterime favactor similarity score def favactorfunctionfilmfilm set result favactor formula two films default favactorscore add similarity score films director directfilm directfilm favactorscore add similarity score films genre genrefilm genrefilm favactorscore add similarity score actor common actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore print resulting score return favactorscore assumption counting actors common counting things twice way revise part code comes accurate result actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore,1 looks like er exception object type oserror also looks like holds errors er probably stands error,try osexecvp sqlite args except oserror er ererrno file found raise oserror sqlite executable found is installed else raise except raise in code except statement catches oserror er variable stand edit one excepts oserror way except error get exception object,1 the python used repl python script run print sysexecutable verify,when i write import wx python interpreter problem i run script line windows console error importerror no module named wx appears result commands help modules contains wx wxpython wxversion syspath contains sitepackages pathwxmswunicode how solve problem,1 add html end already optionally removing moving existing,my pattern already matches eg vi vi i also want match eg vihtm vihtml can help thank,1 you could use recursion def flattencountiterable element count item iterable item element count isinstanceitem list count flattencountitem element return count or concisely def flattencountiterable element return sum flattencountitem element isinstanceitem list else item element item iterable use like x printflattencountx,i array x i want count every occurrence number store number variable onecounter xcount returns occurrences insufficient my code serves purpose stores onecounter however looks messy feels unpythonic any suggestions i improve pythonicity expand moredimensional lists thanks x onecounter x typei list j typej list k j k onecounter else j onecounter else onecounter,3 if htm html part optional suit needs vidhtml otherwise use vidhtml,my pattern already matches eg vi vi i also want match eg vihtm vihtml can help thank,2 a hacky solution working conversion datatype string httpcodepadorgvnevbm import x nums inti refindallr strx printnumscount,i array x i want count every occurrence number store number variable onecounter xcount returns occurrences insufficient my code serves purpose stores onecounter however looks messy feels unpythonic any suggestions i improve pythonicity expand moredimensional lists thanks x onecounter x typei list j typej list k j k onecounter else j onecounter else onecounter,2 let number n number digits n given mathfloormathlogn note give correct answers integers,in python find number digits integer,3 one best python package plotting data matplotlib parse input file import time data line open inputtxt datetimesamples linesplit dataappendtimestrptimestrjoin date time dmy hms samples use matplotlib plot data parsing code may rewritten using list comprehension may memory efficient since implicitly use iterators lazy evaluation instead storing whole data list,hi want plot txt file graph date x axis columns axisin separate lines thanks pol,1 this pycon talk creator twisted give answers it changed opinion twisted before i viewed massive piece software interfaces weird names two things many developers dislike actually superficial things i’ve seen history behind amazing number use cases i respect lot life short need twisted,i playing around twisted framework week nowmore curiosity rather use lot fun event driven asynchronous network programming however something i fail understand the twisted documentation starts twisted framework designed flexible let write powerful servers my doubt why need eventdriven library write powerful servers already efficient implementations various servers surely must couple concrete implementations twisted developers mind writing eventdriven io library what why exactly twisted made,2 there simpler ways get build dir name distutilsutil import getplatform getplatform linuxx i’ll let finish string concatenation another way solve problem create setupcfg file alongside setuppy content buildext inplace this build extension modules parent package directory sphinx see,i written python module including submodule written c module called foo c part foobar the structure looks like src fooinitpy contains public stuff foobarbarc c extension doc sphinx configuration confpy fooinitpy imports bar augment useful stuff exposed foo module this works fine built obviously work uncompiled form since bar exist built i like use sphinx document project use autodoc extension foo module this means i need build project i build documentation since i build distutils built module ends variably named dir buildliblinuxarchpyversion — means i hardcode directory sphinx confpy so i configure distutils setuppy script run sphinx builder built module for completeness call setup fake things custom builders subclass build buildext setupcmdclass fake fake buildextfake buildextfake packagedir src packages foo name foo version description desc extmodules modulereal,1 distutils support man pages people written extensions support generally form custom distutils command see example pythondistutilsextra ubuntu distutils support installing man pages,i python project basically set command line scripts helper package as scripts number command line options i decided create manual page script used ronn httprtomaykogithubcomronn write manuals markdown generate mdoc the question generate install man pages distutils based project i came following solution create simple installsh script generates installs manual pages i call script overloaded install command pass specified prefix check actual code httpgithubcomnovellctools i quite like solution simple task i add hacks setuppy implement shell script well moreover i use prefixshareman man page path correct systems eg freebsd seem install rd party man pages usrlocalman ie share are elegant ways,1 as twisted trunk could compiled ok pypy i used dev however order install twisted need apply patch zipfilepy i submitted stdlib zipfilepy leaks file descriptors cpythonoriented programming style used zipfilepy therefore installation fails pypy uses gc model cpython,i install twisted ubuntu box after download twisted source i issue command pypy setuppy install after i receive error building twistedrunnerportmap extension creating buildtemplinuxx creating buildtemplinuxxtwisted creating buildtemplinuxxtwistedrunner cc ibuildspypylinuxinclude c twistedrunnerportmapc buildtemplinuxxtwistedrunnerportmapo cc shared buildtemplinuxxtwistedrunnerportmapo buildliblinuxxtwistedrunnerportmappypyso usrbinldbfdreal buildtemplinuxxtwistedrunnerportmapo relocation rx rodata used making shared object recompile fpic buildtemplinuxxtwistedrunnerportmapo could read symbols bad value collect ld returned exit status error command cc failed exit status so i fix thanks,1 as producing pdf files i would suggest look cairo library vector graphics libaray support drawing pdf surfaces it python bindings as drawing polygons rounded corners i aware graphics library supports box but complicated compute arc coordinates polygon corners given corner radius basically find point angle bisector two adjacent edges distance r ie desired radius edges this center arc finding starting ending point project point two edges there might nontrivial cases eg polygon edges short fit two arcs i guess select smaller radius case maybe others i currently aware hth,what right tool job i want write python script produces vector graphics pdf format in particular i need draw filled polygons rounded corners ie plane figures composed straight lines circular arcs it seems matplotlib makes fairly easy draw rectangles rounded corners general polygons sharp corners however draw polygons rounded corners seems i first compute bã©zier curve approximates shape is anything straightforward available or another library i use compute bã©zier curve approximates shape i want produce ideally i would simply specify location corner radius pair vertex here example i would like specify red polygon radius corner library would output grey figure for convex polygons i could cheat use thick pen draw outline polygon however work nonconvex case,2 i think better separate task parts part part create generator flatten input list def flattenlistl l isinstanceilist j flattenlisti yield j else yield testing output x flattenlistx print output part part use flattened list count number occurrences printsumi flattenlistx output note returns true false equal but true equal false equal sum calculates number true occurrences equal case,i array x i want count every occurrence number store number variable onecounter xcount returns occurrences insufficient my code serves purpose stores onecounter however looks messy feels unpythonic any suggestions i improve pythonicity expand moredimensional lists thanks x onecounter x typei list j typej list k j k onecounter else j onecounter else onecounter,1 unlike elementtree serializers would allow lxml needs set namespaces beforehand nsmap dc httppurlorgdcelements xlink httpwwwworgxlink root elementgraph nsmap nsmap forth rest declarations and use namespaces using proper declarations n subelementroot httppurlorgdcelementsfoo of course gets annoying type generally beneficial assign paths short constant names dcns httppurlorgdcelements and use variable nsmap subelement declarations n subelementroot sfoo dcns,i using lxml create write xml specifically xgmml the app reading apparently fairly fussy wants see top level element graph labeltest xmlnsdchttppurlorgdcelements xmlnsxlinkh ttpwwwworgxlink xmlnsrdfhttpwwwworgrdfsyntax ns xmlnscyhttpwwwcytoscapeorg xmlnshttpwwwcsrpieduxgmml di rected how i setup xmlns attributes lxml if i try obvious rootattrib xmlnsdc httppurlorgdcelements rootattrib xmlnsxlink httpwwwworgxlink rootattrib xmlnsrdf httpwwwworgrdfsyntaxns rootattrib xmlnscy httpwwwcytoscapeorg rootattrib xmlns httpwwwcsrpieduxgmml lxml throws valueerror invalid attribute name u xmlnsdc i used xml lxml fair amount past simple stuff managed avoid needing know anything namespaces far,3 whenever run command bash caches command location that may running use hash r clean cache note three pythons system system usrbin optpythonbin virtualenv envbin only last one flask installed make extra sure caling one also mess bashprofile especially root bashprofile – need root privileges flask stick virtualenv much cleaner much lower chance mess system that said path scanned first match instead pathpathoptpythonbin want export pathoptpythonbinpath but next time need change path,i followed tutorial order install python centos httpvillaroadcomrollingpythononcentos after installation python i got optpython ls la total drwxrxrx root root drwxrxrx root root drwxrxrx root root bin drwxrxrx root root include drwxrxrx root root lib drwxrxrx root root share optpython ls la bin total drwxrxrx root root drwxrxrx root root rwxrxrx root root rwxrxrx root root easyinstall rwxrxrx root root easyinstall rwxrxrx root root idle rwxrxrx root root pip rwxrxrx root root pip rwxrxrx root root pydoc rwxrxrx root root python rwxrxrx root root python rwxrxrx root root pythonconfig lrwxrwxrwx root root pythonconfig pythonconfig rwxrxrx root root smtpdpy rwxrxrx root root virtualenv i use optpythonbinvirtualenv binary create environment varwwwmyprojenv cd varwwwmyproj virtualenv nositepackages p optpythonbinpython clear promptmyprojcom env activate pip install flask pip installes flask envlibpythonsitepackages syspath python python default oct gcc linux type help copyright credits license information import flask traceback recent call last file stdin line module importerror no module named flask import sys syspath optpythonlibpythonsitepackagessetuptoolscpyegg optpythonlibpythonsitepackagespippyegg optpythonlibpythonzip optpythonlibpython optpythonlibpythonplatlinux optpythonlibpythonlibtk optpythonlibpythonlibold optpythonlibpythonlibdynload optpythonlibpythonsitepackages i tried using easyinstall instead pip result flask installed envlibpythonsitepackages main question virtualenv add envlibpythonsitepackages python sys path if i better add appropriate sitepackages directory python path runtime eg syspathinsert path sitepackages flask application modify system pythonpath trigger virtualenv afterinstall method add path sitepackages python path info i added user root bashprofile profile ubuntu alias python optpythonbinpython alias python optpythonbinpython pathpathoptpythonbin source profile python produces usrbinpython hmmmm python r dec gcc linux type help copyright credits license information exit odd enough i run python i getting right version python python default oct gcc linux type help copyright credits license information what even odd following python installation tutorial i getting optpythonbinpython python command anyway question help appreciated please consider i python newbie probably silly question i asking,2 using elementmaker import lxmletree et import lxmlbuilder builder e builderelementmakernamespace httpwwwcsrpieduxgmml nsmapnone httpwwwcsrpieduxgmml dc httppurlorgdcelements xlink httpwwwworgxlink rdf httpwwwworgrdfsyntaxns cy httpwwwcytoscapeorg graph egraphlabeltest directed printettostringgraph prettyprinttrue yields graph xmlnscyhttpwwwcytoscapeorg xmlnsrdfhttpwwwworgrdfsyntaxns xmlnsdchttppurlorgdcelements xmlnsxlinkhttpwwwworgxlink xmlnshttpwwwcsrpieduxgmml directed labeltest,i using lxml create write xml specifically xgmml the app reading apparently fairly fussy wants see top level element graph labeltest xmlnsdchttppurlorgdcelements xmlnsxlinkh ttpwwwworgxlink xmlnsrdfhttpwwwworgrdfsyntax ns xmlnscyhttpwwwcytoscapeorg xmlnshttpwwwcsrpieduxgmml di rected how i setup xmlns attributes lxml if i try obvious rootattrib xmlnsdc httppurlorgdcelements rootattrib xmlnsxlink httpwwwworgxlink rootattrib xmlnsrdf httpwwwworgrdfsyntaxns rootattrib xmlnscy httpwwwcytoscapeorg rootattrib xmlns httpwwwcsrpieduxgmml lxml throws valueerror invalid attribute name u xmlnsdc i used xml lxml fair amount past simple stuff managed avoid needing know anything namespaces far,1 it highly likely iso solution first problem you need aware anyrandomgibberishdecode iso simply cannot fail secondly i sure encoding would needed uploading file surely object exercise reproduce file exactly server decoding zip file unicode objects seems strange it would good idea publish error got encoding error showed reading file full traceback somebody help also needed url api mentioned update you say got ascii error line body rn joinl a reasonable guess based limited information problem joinufoo xff traceback recent call last file stdin line module unicodedecodeerror ascii codec decode byte xff position ordinal range ufoo xff produces result what happening mixture unicode str objects concatenating requires converting str object unicode attempted using default encoding normally ascii fail str object ascii in case problem str objects unicode objects send unencoded unicode objects wire i suggest replace code key filename files f filefilename r filedata freaddecodeiso key filename files f filefilename rb specify binary mode case gets run windows filedata fread decode immediately entering function print args see exactly unicode print fields reprfields print files reprfiles it quite likely unicode objects safely coerced ascii explicitly unicodeobjectencodeascii update it worth investigating values unicode str it appears unicode safely encoded ascii new k vencode ascii isinstancev unicode else v k v original,i trying use python script upload zip file site the site provided api exactly purpose but i tried use encoding error showed joining strings send httplib connect request i traced string question filedata zip file traceback recent call last file libraryapplication junkprojectmanagermainpy line onupload curseuploaderuploadfile babdebdbede wow slug version versionid r logtext creole plain zippath file libraryapplication junkprojectmanagercurseuploaderpy line uploadfile contenttype body encodemultipartformdataparams file filepath file libraryapplication junkprojectmanagercurseuploaderpy line encodemultipartformdata body rn joinl unicodedecodeerror ascii codec decode byte xcb position ordinal range edit as requested full code edit tried suggested encode notascii strings ascii it throws bug li valueencodeascii httplib import httpconnection ospath import basename exists mimetools import chooseboundary try import simplejson json except importerror import json def getgameversionsgame return json response given gameversionsjson curseforgecom given game game the shortened version game eg wow war rom conn httpconnection gamescurseforgecom game game connrequestget gameversionsjson response conngetresponse assert responsestatus statusd reasons gameversionsjson status responsestatus reason responsereason assert responsecontenttype applicationjson data jsonloadsresponseread return data def uploadfileapikey game projectslug name gameversionids filetype changelog changemarkuptype knowncaveats caveatsmarkuptype filepath upload file curseforgecom project apikey the apikey httpwwwcurseforgecomhomeapikey game the shortened version game eg wow war rom projectslug the slug project eg myproject name the name file uploading version name include project name gameversionids a set game version ids filetype specify alpha b beta r release changelog the change log file up k characters acceptable changemarkuptype markup type change log creole plain recommended knowncaveats the known caveats file up k characters acceptable caveatsmarkuptype markup type known caveats creole plain recommended filepath the path file upload assert lenapikey assert lengameversionids assert filetype r b assert existsfilepath params paramsappend name name gameversionid gameversionids paramsappend gameversion gameversionid paramsappend filetype filetype paramsappend changelog changelog paramsappend changemarkuptype changemarkuptype paramsappend knowncaveats knowncaveats paramsappend caveatsmarkuptype caveatsmarkuptype contenttype body encodemultipartformdataparams file filepath print got headers useragent curseforge uploader script contenttype contenttype xapikey apikey conn httpconnection gamescurseforgecom game game connrequestpost projectsslugsuploadfilejson slug projectslug body headers response conngetresponse responsestatus print successfully uploaded names name name elif responsestatus assert responsecontenttype applicationjson errors jsonloadsresponseread print form error uploading names name name k items errorsiteritems item items print ks items k k name name else print error uploading names statusd reasons name name status responsestatus reason responsereason def isasciis return allordc c def encodemultipartformdatafields files encode data multipartformdata format fields a sequence name value elements regular form fields files a sequence name filename elements data uploaded files return contenttype body ready httplibhttp instance boundary chooseboundary l key value fields value none value elif value false continue lappend boundarys boundary boundary lappend contentdisposition formdata namenames name key lappend lappendvalue key filename files f filefilename rb filedata fread fclose lappend boundarys boundary boundary lappend contentdisposition formdata namenames filenamefilenames name key filename basenamefilename lappend contenttype applicationzip lappend lappendfiledata lappend boundarys boundary boundary lappend rangelenl value li isasciivalue li valueencodeascii body rn joinl contenttype multipartformdata boundaryboundarys boundary boundary return contenttype body how i workaround edit as requested full result printing vars fields name u gameversion u gameversion u gameversion u filetype r changelog u n jaliborc fixed bug causing wrong items shown leather mail plate slotsn jaliborc items organized level wellnn n jaliborc completly rewritten categories dropdown fix bugnn n jaliborc updated patch n jaliborc included firelands itemsnn n jaliborc now works n jaliborc completely redesigned improvedn jaliborc includes items ingame right startn jaliborc searches trough thousands items blazen jaliborc mostly load demandn jaliborc only works english clients versions clients released close futurenn n added linkerator support multiple chat framesnn n fixed bug linking item chat frame nn n added compatibility wow nn n bumped toc nn n bumped toc nn n toc bump potential wim bugfixnn n added heirloom option quality selectorn fixed bug causing db reloaded item scrolln cleaned code bit still need work guilocalizationn altered slash commands see addon description detailsnn n bumped max item id check k k glyphs etc appearnn n fixed crash issue linking tradeskillsnn n made wrath compatiblen seems causing lot cpu usage investigate later changemarkuptype creole knowncaveats caveatsmarkuptype plain files file u usersjaliborcdesktopludwig zip it appears contain unicode strings should i encode,1 join items print resulting string print joinstrcomplementsi seqa,seqa poola print seqa seqa print complementsi print complements dict poola list when i print complementsi spaces i remove spaces,3 well print use either future import printfunction printcomplementsi end sysstdoutwritecomplementsi,seqa poola print seqa seqa print complementsi print complements dict poola list when i print complementsi spaces i remove spaces,1 some advices why use actor actor actor rather mainactors you store dictionnaries inside you also use seq place c … finally could use printf like formatting strings end print trthstdstdtdstdtdstdtdstdtdstdtdtdtrth c maxfilmsc maxlist maxlist maxlist maxlist but i think actual problem html case must use th eatch row the syntax following table trthcolnameththcolnameththcolnamethtr trtdvalue tdtdvalue tdtdvalue tdtr trtdvalue tdtdvalue tdtdvalue tdtr trtdvalue tdtdvalue tdtdvalue tdtr table but i may missed something script,i trying make table sorts highgrossing films similar films all code completed i trouble finishing table code import data csv file use dictread interpret information import csv csvfile openmoviestatsmedcsv csvdata csvdictreadercsvfile create dictionary films directors direct create dictionary films genres genre create dictionary films main actor actor actor actor create dictionary films worldwide gross gross create dictionary films year came year name iterate csv file fill dictionaries c csvdata directc name c director genrec name c genre actorc name c actor actorc name c actor actorc name c actor grossc name c worldwide gross yearc name c date namec name c name create twovariable function deterime favactor similarity score def favactorfunctionfilmfilm set result favactor formula two films default favactorscore add similarity score films director directfilm directfilm favactorscore add similarity score films genre genrefilm genrefilm favactorscore add similarity score actor common actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore print resulting score return favactorscore create function find film greatest worldwide gross per year def maxgrossfinderc set intial maximum gross zero maxgross replace maxgross film year greater gross film year f intgrossfilm yearfilm c f maxgross maxgross f max film print year max value year return max create dictionary max grossing films year maxfilms create list years c maxfilmsc maxgrossfinderc maxlist maxsimilarity year f favactorfunctionmaxfilmsc maxgrossfinderc yeard c f maxsimilarity maxsimilarity f max maxlistappendmax maxsimilarity year g favactorfunctionmaxfilmsc maxgrossfinderc max yeard c g maxsimilarity maxsimilarity g max maxlistappendmax maxsimilarity year h favactorfunctionmaxfilmsc maxgrossfinderc max max yeard c h maxsimilarity maxsimilarity h max maxlistappendmax maxsimilarity year favactorfunctionmaxfilmsc maxgrossfinderc max max max yeard c maxsimilarity maxsimilarity max maxlistappendmax print contenttype texthtml print print html print body print table border print tr print thfont colorgreenyearfontth print thfont colorbluehighest grossing filmfontth print thfont colorredmost similarfontth print thfont colorrednd most similarfontth print thfont colorredrd most similarfontth print thfont colorredth most similarfontth print tr c sortedmaxfilms print trth print c print td print maxfilmsc print tdtd print maxlist print tdtd print maxlist print tdtd print maxlist print tdtd print maxlist print tdtrth table i come mostly correct most similar films every row correspond first year how i alter code most similar films correspond right data,2 c sortedmaxfilms print trth print c print td print maxfilmsc print tdtd print maxlist print tdtd print maxlist print tdtd print maxlist print tdtd print maxlist print tdtrth you print variables maxlist every time go loop since change variables course get output time you need either move logic decide similiar loop create new loop stores similar list fetch inside loop,i trying make table sorts highgrossing films similar films all code completed i trouble finishing table code import data csv file use dictread interpret information import csv csvfile openmoviestatsmedcsv csvdata csvdictreadercsvfile create dictionary films directors direct create dictionary films genres genre create dictionary films main actor actor actor actor create dictionary films worldwide gross gross create dictionary films year came year name iterate csv file fill dictionaries c csvdata directc name c director genrec name c genre actorc name c actor actorc name c actor actorc name c actor grossc name c worldwide gross yearc name c date namec name c name create twovariable function deterime favactor similarity score def favactorfunctionfilmfilm set result favactor formula two films default favactorscore add similarity score films director directfilm directfilm favactorscore add similarity score films genre genrefilm genrefilm favactorscore add similarity score actor common actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore actorfilm actorfilm actorfilm actorfilm favactorscore print resulting score return favactorscore create function find film greatest worldwide gross per year def maxgrossfinderc set intial maximum gross zero maxgross replace maxgross film year greater gross film year f intgrossfilm yearfilm c f maxgross maxgross f max film print year max value year return max create dictionary max grossing films year maxfilms create list years c maxfilmsc maxgrossfinderc maxlist maxsimilarity year f favactorfunctionmaxfilmsc maxgrossfinderc yeard c f maxsimilarity maxsimilarity f max maxlistappendmax maxsimilarity year g favactorfunctionmaxfilmsc maxgrossfinderc max yeard c g maxsimilarity maxsimilarity g max maxlistappendmax maxsimilarity year h favactorfunctionmaxfilmsc maxgrossfinderc max max yeard c h maxsimilarity maxsimilarity h max maxlistappendmax maxsimilarity year favactorfunctionmaxfilmsc maxgrossfinderc max max max yeard c maxsimilarity maxsimilarity max maxlistappendmax print contenttype texthtml print print html print body print table border print tr print thfont colorgreenyearfontth print thfont colorbluehighest grossing filmfontth print thfont colorredmost similarfontth print thfont colorrednd most similarfontth print thfont colorredrd most similarfontth print thfont colorredth most similarfontth print tr c sortedmaxfilms print trth print c print td print maxfilmsc print tdtd print maxlist print tdtd print maxlist print tdtd print maxlist print tdtd print maxlist print tdtrth table i come mostly correct most similar films every row correspond first year how i alter code most similar films correspond right data,1 what want recursive type different languages different ways for example ocaml staticallytyped language optional compilerinterpreter flag rectypes enables support recursive types allowing define stuff like let rec printendline b b printendline b c c printendline c although ugly complained c example happens underneath still the compiler simply worries instead forcing write as others pointed haskell use newtype overhead but complain explicitly wrap unwrap recursive type ugly similarly c example overhead since machine level member struct identical member ugly another example i want mention go another staticallytyped language in go type construct defines new type it simple alias like typedef c type haskell creates fullfledged new type like newtype haskell type independent method set methods define because type definition recursive type fn func fn,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,2 it sounds like two steps given list extensions get list files folder matching extension if files directory extension matching list remove note include information traverse directory structure directories test sample code single directory hardcoded import os dir mydirectory extlist ext ext ext allfiles oslistdirdir files directory myfiles appended contain files extensiosn matching extlist file allfiles parts filesplit split filename based parts extensionlist myfilesappendfile lenmyfiles lenallfiles file myfiles path ss dir file osremovepath osremovefile,i want delete certain files type cuejpgpngmuetc folder files cuejpgpngmuetc type i already function get files type cuejpgpngmuetc given folder return list i need delete according conditions to give example file qjpg folder after myfunc finishes deleted edit sorry unclearness let give better example we two folders alpha beta folder gamma in alpha three files mp mp folderjpg in beta one file coverjpg after myfunc finishes mp mp folderjpg untouched coverjpg deleted,1 you need provide detail get meaningful answers there several ways make variable available methods class instance variable defined scope current class instance commonly created init ie instance initiated class someclassobject def initself selfgreeting hello def greetself name return selfgreeting name class variable defined class definition shared instances class someclassobject greeting hello def greetself name return selfgreeting name note selfgreeting references class variable greeting via instance assigning selfgreeting change class variable rather overwrites greeting instance attribute new value a explicit perhaps clearer way accessing class variable selfclassgreeting module global variable defined toplevel usually module define variable outside class definition reference within class functions greeting hello class someclassobject def greetself name return greeting name there sorts reasons often good idea search stackoverflow python globals find many explanations well cases might appropriate,how i create variables methods class share fields global vars another question meaning python,1 convert date using datetimestrptime timestrptime however two functions cannot parse timezone offset see bug solution see split date remove timezone offset feed rest strptime process offset manually look question find hints parse offset,i receiving twitter messages sent certain date following format twitter tue mar i want store dates timestamp time zone field postgresql djangos datetimefield field when i store string however i get error validationerror u enter valid datetime yyyymmdd hhmmssuuuuuu format i automatically transform twitter datetype python datetime time work elsewhere app saving dates,1 the main difference hadoop good processing big data dozen terabytes data it provides simple logical framework called mapreduce well appropriate data aggregation distributed storage system called hdfs if inputs smaller gigabyte probably want use hadoop,i new using multiple cpu process jobs wondering people could let know procons parallelpythonor type python module versus hadoop streaming i large cpu intensive process i would like spread across several servers,1 the sphinxbuild command installed cpythonscripts either use full path cpythonscriptssphinxbuild call command add directory path,on python i installed sphinx using easyinstall available following location windows cpythonlibsitepackagessphinxpyeggsphinx i wanted convert couple rst files html but whenever i sphinxbuild i encounter following error sphinxbuild recognized internal external command operable program batch file am i missing something,3 mizardx answer gives good collection multiple approaches this i came thinking aloud mylist x ix enumeratemylist x mylisti,is builtin removes duplicates list python whilst preserving order i know i use set remove duplicates destroys original order i also know i roll like def uniqinput output x input x output outputappendx return output thanks unwind code sample but i like avail builtin pythonic idiom possible related question in python fastest algorithm removing duplicates list elements unique preserving order,1 give go it assumes date format twitter rfc compliant see question linked adrien a naive datetime object constructed ie timezone info it adjusted according timezone offset utc unless need keep original timezone i store date time utc format local time display datetime import datetime timedelta emailutils import parsedatetz tue mar def todatetimedatestring timetuple parsedatetzdatestringstrip dt datetimetimetuple return dt timedeltasecondstimetuple,i receiving twitter messages sent certain date following format twitter tue mar i want store dates timestamp time zone field postgresql djangos datetimefield field when i store string however i get error validationerror u enter valid datetime yyyymmdd hhmmssuuuuuu format i automatically transform twitter datetype python datetime time work elsewhere app saving dates,3 it appears function favactorfunction returning list characters rather list words if iterate string rather iterating list strings happen for example notice happens i convert string list print listhello world print listhello world h e l l w r l and since learning consider advice use descriptive variable names names like c h g make code almost impossible understand use variables like actor director etc you win bonus points concise unless bad instructor,i trying make list top maximum values data dictionaries result get keeps separating term individual characters the full code maxlist maxsimilarity year f favactorfunctionmaxfilmsc maxgrossfinderc yeard c f maxsimilarity maxsimilarity f max maxlistappendmax maxsimilarity year g favactorfunctionmaxfilmsc maxgrossfinderc max yeard c g maxsimilarity maxsimilarity g max maxlistappendmax maxsimilarity year h favactorfunctionmaxfilmsc maxgrossfinderc max max yeard c h maxsimilarity maxsimilarity h max maxlistappendmax maxsimilarity year favactorfunctionmaxfilmsc maxgrossfinderc max max max yeard c maxsimilarity maxsimilarity max maxlistappendmax print maxlist result i get t r n f r e r s p e r m n i alter code get transformers etc,1 from error log file arpahhuksyprojectsmysitepollsmodelspy unicode return selfquestion make sure self actually property called question,i trying follow django tutorial i get error i continue httpdpastecom can someone help i new python django thank much,2 since moving data becomes harder harder size comes parallel computing data localization becomes important hadoop mapreduce framework maximizes localization data processed it also gives way spread data efficiently across cluster hdfs so basically even use parallel modules long data localized computers process long move data across cluster time get maximum benefit parallel computing that one key ideas hadoop,i new using multiple cpu process jobs wondering people could let know procons parallelpythonor type python module versus hadoop streaming i large cpu intensive process i would like spread across several servers,1 you need return false onclick handler call dajax,i working random machine example i trouble i installed dajax dajaxice according two pages dajax dajaxice my ajaxpy file looks like import random dajaxcore import dajax dajaxicedecorators import dajaxiceregister dajaxiceregister def randomizerequest dajax dajax dajaxassign result value randomrandint return dajaxjson here viewspy djangoshortcuts import rendertoresponse djangotemplate import requestcontext def dajaxrequest return rendertoresponse dajaxhtml contextinstancerequestcontextrequest here urlspy djangoconfurlsdefaults import patterns include url dajaxicecore import dajaxiceautodiscover dajaxice import urls djangoconf import settings dajaxmyappviews import dajax dajaxiceautodiscover urlpatterns patterns r settingsdajaxicemediaprefix include dajaxiceurls r dajax dajax my html form tag looks like form input typetext nameresult value idresult input typebutton namerand valuelet rand idrand onclickdajaxicemyapprandomizedajaxprocess return false form here head tag looks like head titlemy base templatetitle dajaxicejsimport script srchttpajaxgoogleapiscomajaxlibsjqueryjqueryminjs typetextjavascript charsetutfscript script src staticurl jsjquerydajaxcorejs typetextjavascript charsetutfscript head i added following init py file project dir myappajax import randomize also note django app name myapp on page i click let rand page goes httplocalhostdajaxresult value shows text input box i checked console chromium errors did i incorrectly install either dajax dajaxice something wrong code my guess i using jquery instead prototype something different i need thanks help,1 is way create tree iteratively instead recursively have look httpenwikipediaorgwikitreetraversaliterativetraversal,i segment tree holds data range numbers data structure chosen here code class segmenttree def initself n def initb e b e data foo no dependency return nodeb e data none none else mid b e l initb mid r initmid e data foo data depends l r return nodeb e data l r selfroot init n this fails n around max recursion depth exceeded error is way create tree iteratively instead recursively,1 in general way convert recursion iterative maintain stack queue manually something like stack empty item pop stack processing adding onto node push l r onto stack the stack grow memory since item popping pushing two,i segment tree holds data range numbers data structure chosen here code class segmenttree def initself n def initb e b e data foo no dependency return nodeb e data none none else mid b e l initb mid r initmid e data foo data depends l r return nodeb e data l r selfroot init n this fails n around max recursion depth exceeded error is way create tree iteratively instead recursively,1 you need add join query class x use filter instead filterby qry dbsessionqueryy qry qryjoinx qry qryfilterxpublish true qryall one go dbsessionqueryyjoinxfilterxpublish trueall see question regarding difference using filter filterby,i model x model y y contains foreign key reference xid instance related x entry available property x xid columninteger foreignkey xtableid x relationship x x also boolean property publish executing query y filter results xpublish true ive tried something like dbsessionqueryyfilterbyxpublish trueall but doesnt work get error saying keyword cant expression ive looked sql alchemy docs solution cant seem find im looking any suggestions,2 since would appear first entry sublist key sort remaining entries somehow derived key dictionary might suitable data structure vals a b c d f g h i j z vals print found z else vals z aa bb,i tlist list lists i would like add new items list present for instance item i present add tlist otherwise skipis pythonic way note at first tlist may empty elements added code after adding z example tlist abcdfghijzaabb the elements based calculations z item c example item given user tlist abcdfghij tlist something check files previously present tlist add tlist elif item ziptlist something,1 the real problem recursion depth algorithm value like comparing numbers the keyword checks object identity checks equality true false because condition terminate recursion never true function keep recursing even b e equal if change problem go away b e for small numbers problem might occur python caches reuses objects ints certain size,i segment tree holds data range numbers data structure chosen here code class segmenttree def initself n def initb e b e data foo no dependency return nodeb e data none none else mid b e l initb mid r initmid e data foo data depends l r return nodeb e data l r selfroot init n this fails n around max recursion depth exceeded error is way create tree iteratively instead recursively,3 need keep data structure something like work create set already seen items seen setziptlist start adding new items item seen seenadditem add new sublist tlist,i tlist list lists i would like add new items list present for instance item i present add tlist otherwise skipis pythonic way note at first tlist may empty elements added code after adding z example tlist abcdfghijzaabb the elements based calculations z item c example item given user tlist abcdfghij tlist something check files previously present tlist add tlist elif item ziptlist something,1 you might able set pixmap opacity implementing custom gtkcellrenderer draws pixmap according selection state replacing gtkiconview default cell renderer,i want change opacity color gtkiconview select box i want actually make selection visible i noticed gtkiconview widget style properties selectionboxalpha amp selectionboxcolor accessible reading the setselectfunction method gtktreeselection class would useful i want used gtktreeview i found equivalent gtkiconview so i control selection perform action user select unselect stuff edit in fact change values selectionboxalpha selectionboxcolor style properties solution i really want change selection box opacity opacity pixbuf compositing color so i need equivalent method setselectfunction gtkiconview widget,1 first change current directory executable want run find dependencies target cankexe oschdirospathdirnametarget ossystemtarget otherwise ossystem executes directory running script,i calling exe dependent batch files python giving error i able call exe independent i import os ossystemnotepadexe working ossystemcankexe giving error ankexe dependent batch files,3 take resultsa make sure exact match somewhere resultsb el resultsa el resultsb get partial matches pmatch dict def partialmatchab instance return sumea eb eaeb zipab ela resultsa pmatchela elb elb resultsb partialmacthelaelb return records match nomatch el el resultsa el resultsb edit another possible partialmatch def partialmatchxy nbmatches sumea eb eaeb zipxy return floatnbmatches lenx,i trying figure best way write query compare rows two tables my goal see two tuples result set a larger result set b i want see tuples different query results select tablefieldb tablefieldc tablefieldd from table order by fieldb resultsa select tablefielda tablefieldb tablefield from table order by fielda resultsb so i want take resultsa make sure exact match somewhere resultsb so since second record second tuple different resultsa i would like return second tuple resultsa ultimately i would like return set also second tuple match set i could reference program ideally since second tuples primary key fieldb table match corresponding primary key fielda table i would want display resultsc this complicated facts results tables order i write code says compare tuple resultsa tuple resultsb it like compare tuple resultsa see matches record resultsb if primary keys match none tuples results b completely match partial match found return records match i apologize wordy i think better way explain any help would much appreciated thanks updated effort on partial matches b pmatch dict def partialmatchxy return sumea eb eaeb zipxy ela pmatchela elb elb b partialmatchelaelb printpmatch output i would expected sets different any ideas,1 you change globals without affecting users module sort create private copy whole module i trust familiar sysmodules remove module python forgets imported old objects referencing continue when imported new copy module made a hacky solution problem could would something like import sys import threading remove original module keep around mainthreading sysmodulespop threading get private copy module import threading privatethreading cover evidence restoring original sysmodules threading mainthreading modify private copy privatethreadingallocatelock myallocatelock and privatethreadinglock globals entirely separate threadinglock needless say module written mind especially system module threading might run problems for example threadingactive supposed contain running threads solution neither active the code may also eat socks set house fire etc test rigorously,i want modify classes standard library use different set globals ones classes module use example this example example moduleapy myglobal class a def initself myglobalappendself class b def initself myglobalappendself in example if i create instance a via a call append object named myglobal but i wish create new module import b b use myglobal module imported instead myglobal module b original defined modulebpy modulea import b myglobal related i struggling explain problem previous attempt fact ask something completely different clone module make changes copy update the example illustration i trying achieve since variable scope classes unlike say c i think reference globals mapping stored class instead attached every function defined update an example requested standard library many maybe classes threading module make use globals allocatelock getident active defined one cannot change globals without changing classes module,3 no ldap server send passwords plain encrypted you write provide correct credentials,as title said i want use pythonldap get user password here pythonldap reference httpwwwpythonldaporgdochtmlindexhtml i find function get user password is anybody thing like and possible get user password,1 here somewhat hacky matplotlib solution the main complications related using matplotlib path objects build composite path usrbinenv python import numpy np matplotlibpath import path matplotlibpatches import pathpatch polygon matplotlibtransforms import bbox bboxtransformto def sidea b c on side line ab point c returns return npsignnplinalgdetnpcabc def centerprev curr next radius find center arc approximating corner curr p p prev c c curr n n next dp radius nphypotc p c p dn radius nphypotc n c n p p c p c n n c n c results nplinalgsolvep c c p n c c n p dp p dp p dp p dp n dn n dn n dn n dn siden sideprev curr next sidep sidenext curr prev r resultst sideprev curr r sidenext curr r siden sidep return r raise valueerror cannot find solution def projprev curr next center project center onto lines prevcurr nextcurr p p prev npasarrayprev c c curr npasarraycurr n n next npasarraynext pc curr prev nc curr next pc npdotpc pc nc npdotnc nc return prev npdotcenter prev pcpc pc next npdotcenter next ncnc nc def raddegangle return angle nppi def anglecenter point x npasarraypoint npasarraycenter return nparctany x def arcpathcenter start end return path arc start end around center matplotlib arcs always go ccw may need mirror mirror sidecenter start end mirror start center end return patharcraddeganglecenter start raddeganglecenter end mirror def pathvertices radii return path closed rounded polygon npisscalarradii radii nprepeatradii lenvertices else radii npasarrayradii pv pc first true rangelenvertices seg vertices vertices vertices elif lenvertices seg vertices vertices vertices else seg verticesii r radiii c centerseg r b projseg c arc mirror arcpathc b mirror else bb bboxc c r r iter arcitersegmentsbboxtransformtobb v c iter c pathcurve pvextendm v v v pcextendc c c elif c pathmoveto pvappendm v first pcappendpathmoveto first false else pcappendpathlineto pvappend pcappendpathclosepoly return pathpv pc name main matplotlib import pyplot fig pyplotfigure ax figaddsubplot vertices patch polygonvertices edgecolor red facecolor none linewidth axaddpatchpatch patch pathpatchpathvertices edgecolor black facecolor blue alpha linewidth axaddpatchpatch axsetxlim axsetylim figsavefig foopdf,what right tool job i want write python script produces vector graphics pdf format in particular i need draw filled polygons rounded corners ie plane figures composed straight lines circular arcs it seems matplotlib makes fairly easy draw rectangles rounded corners general polygons sharp corners however draw polygons rounded corners seems i first compute bã©zier curve approximates shape is anything straightforward available or another library i use compute bã©zier curve approximates shape i want produce ideally i would simply specify location corner radius pair vertex here example i would like specify red polygon radius corner library would output grey figure for convex polygons i could cheat use thick pen draw outline polygon however work nonconvex case,3 bear mind short circuit evaluation always want fixing reduce short circuit would mistake reason for example i recently change use reduce processing list forms django i want report isvalid problems first one,if i result reduceoperatorand false will stop first result since false amp anything false similarly result reduceoperatoror true,1 kiva part enable library abstracts vector renderer it supports cairo agg several renderers though agg default it works linux os x windows,not i anything cairo i love fact it terribly difficult install python bindings especially mac see so questions installing pycairo os x are better alternatives edit for little context i creating web service i would like simple deploy ideally using standard installation channels able simply use pip easyinstall introduces complexity deployment process many deployment platforms additionally i like easy anyone set virtual environment development application local machine again ease installation important point,2 the open function returns open file string open files len you need actually read string file example read method contents openpathread mystrlen lencontents if need contents also get file size osstat mystrlen osstat tmpxpy stsize fakefile gae sandboxed implementation file,i using latest gae default python environment both give expected results istrue ospathexistspath numbergreaterthanzero ospathgetsizepath but mystrlen lenopenpath gives error typeerror object type fakefile len there results error google not able open files real bummer what i wrong why pythongae think file fake,2 one option would use signal system firstly reusable class lets define signal class signalobject def initself selfhandlers def connectself handler selfhandlersappendhandler def fireself args handler selfhandlers handlerargs your item class uses signal create destroyed signal classes listen class itemobject def initself selfdestroyed signal def destroyself selfdestroyedfireself and inventory listens signals items updates internal state accordingly class inventoryobject def initself selfitems def addself item itemdestroyedconnectselfondestroyed selfitemsadditem def ondestroyedself item selfitemsremoveitem,every i like take break projects try make classic adventure textbasedgame python time fun project i always design issues implementing item system i like items game descend one base item class containing attributes every item damage weight my problems begin i try add functionality items when item damage gets past threshold destroyed and lies problem i really know accomplish since del self work million different reasons edit i intentionally providing use del something i know wrong i know garbage collection i want i and similar tasks should item contain kind reference container the player i guess ask deleted the first thing comes mind big dictionary containing every item game object would reference list know unique id i like solution i think right way go does anybody suggestions edit i seeing lot people thinking i worried garbage collection what i talking garbage collection actually removing object gameplay i sure objects initiate removal etc,1 fix import seex seex import user seexcachetest pickled class needs namespace the reason shelf uses pickle uses user class when working classes must ensure class pickled appears namespace process reading pickle only data instance pickled class definition the class name used find constructor create new object unpickling take example writes instances class file quoted httpwwwdoughellmanncompymotwpickleindexhtmlproblemsreconstructingobjects,i trying shelve module i running trouble my intention one module call function second one modify file inside shelve i made prototype simply tries set variable something stored shelve print object when i attempt i get following attribute error attributeerror module object attribute user my guess realize user class exists i unsure reason file calls function file main function correctly works instance i appreciate help problem i confused issue import seex seexcachetest import shelve cacheusers shelveopenuserstestcache class userobject def initself name num selfname name selfnum num def strself return name numformatselfname selfnum def cachetest obj cacheusers userred print obj name main cachetest used creating cache first time red userred green usergreen blue userblue cacheusers userred red cacheusers usergreen green cacheusers userblue blue print done full traceback traceback recent call last file cusersakagrimmy documentsaptana studio workspaceshelvetestseexpy line module seexcachetest file cusersakagrimmy documentsaptana studio workspaceshelvetestseexpy line cachetest obj cacheusers userred file cpythonlibshelvepy line getitem value unpicklerfload attributeerror module object attribute user,1 in python generally use quite approaches oop statically typed languages specifically actually need object implement specific interface derive abstract base class rather object needs able required operations this colloquially known duck typing if walks like duck talks like duck intents purposes duck so decide methods required objects make sure always should wish share implementation different actors system consider class inheritance but may well implement disjoint class hierarchies,i getting started python trying figure right way use classes my program currently two classes call planner model the planner modelagnostic given model uses presents consistent interface so seems like i want several different available models inherit something order enforce consistent interface additionally model classes share functionality for example singleagent model might simulate one agent doubleagent model would simulate two agents behaving like singleagent so i implement language features i need edit thanks fast responses straightening duck classes so sounds like i would use inheritance i wanted override subset another model functionality and doubleagent i probably use singleagents class members i taken look questions similar tags seem concerned syntax rather design choices i also looked official python documentation classes found i looking possibly i know enough recognize,2 one python strengths many would argue weaknesses rely compiletime type checking enforce interfaces this means required set objects inherit common base class order interface still used interchangeably function this behavior commonly known duck typing in fact python dynamically typed would hard pressed enforce consistent interface said for reason things like zopeinterface created the main benefit get classes case code reuse model types implement common behavior to take even one step unrelated object type third party library control wish use model even called monkey patching duck punching order add code necessary provide model interface,i getting started python trying figure right way use classes my program currently two classes call planner model the planner modelagnostic given model uses presents consistent interface so seems like i want several different available models inherit something order enforce consistent interface additionally model classes share functionality for example singleagent model might simulate one agent doubleagent model would simulate two agents behaving like singleagent so i implement language features i need edit thanks fast responses straightening duck classes so sounds like i would use inheritance i wanted override subset another model functionality and doubleagent i probably use singleagents class members i taken look questions similar tags seem concerned syntax rather design choices i also looked official python documentation classes found i looking possibly i know enough recognize,1 zipfilezipfile context manager added,based statement the context manager’s exit loaded later use the context manager’s enter method invoked i seen one usage zipfile question i checked source code zipfile located usrlibpythonzipfilepy i know enter exit functions defined thank,3 you describe you could dct dct word dct word dct word dct word but end end word word keys dictionary cannot repeated if code actually set like first example may want collections import defaultdict dct defaultdictlist dct word append dct word append dct word append dct word append after defaultdicttype list word word,i dct word word word word i need get list keys dont duplicate contain values dictionary fe lst word word is possibility make like python,2 if use linux use lsof find process using given port might install first though usage pretty simple lsof,i trying learn python using flask microframework i confused somewhere code keeping server open i believe i spin server python apppy close however still lives i sure possible must done something wrong connection there two questions really first how i find active connectionsocket close second is way i diagnose open connection hunch sqllite closing last thing i implemented this one file application minus config file static content i post code required error generated folder locations changed developmentflaskprojectstestemailenvbinpython developmentflaskprojectstestemailapppy running http traceback recent call last file developmentflaskprojectstestemailapppy line module apprun file developmentflaskprojectswtchnemailenvlibpythonsitepackagesflaskpyeggflaskapppy line run runsimplehost port self options file librarypythonsitepackageswerkzeugpyeggwerkzeugservingpy line runsimple testsocketbindhostname port file systemlibraryframeworkspythonframeworkversionslibpythonsocketpy line meth return getattrselfsocknameargs socketerror errno address already use,3 read tutorial carefully the pyuic tool make full dialog provide method sets already existing dialog dialog qtguiqdialog ui uiaboutdialoguiaboutdlg uisetupuidialog dialogexec,i writing small app learning python pyqt about box i designed qmainwindow qtdesigner managed make work i also designed about box qtdesigner dialog i used pyuic convert ui files py files mainpy aboutdialogpy however i call dialog main app what function look like i tried putting dialog uiaboutdialoguiaboutdlg dialogexec however gives dialog exec attribute show here beginning aboutdialog class class uiaboutdlgobject def setupuiself aboutdlg aboutdlgsetobjectnamefromutfaboutdlg aboutdlgresize i think something wrong setupui rather init trying yielded results either help,2 you get spss io modules detailed documentation free order build app read write sav files the modules available platforms supported spss statistics go spss community site httpwwwibmcomdeveloperworksspssdevcentral follow links spss downloads you register free the sav file binary format number complex structures better use io modules and new features added sav file often happened io modules updated time code go date hth jon peck,i finding mixed results googling i need parse spss sav file discover data layout extract survey results step one read schema data for example i need know question type allowed responses i plan model data sql table i slice dice per apps requirements step two populate data model respondents answers looking spss sav file i believe types data i looking i need want expensive spss software i strictly require we statistics data selecting subsets respondents based answer filters the spss file provided partner company licenses spss i need data back spss use case readonly i use python java without groovy cc parser program this program run end data collection performance particularly important ideally i like code cross platform i develop mac deploy linux i use windows i must a lot finding either java classes modern python code requires dll ibm windows specific based quick explanation requirements i would appreciate recommendations so community i think needs simple found exactly i hoped an open source lib would ideal i even pay simple commercial solution reasonable price,2 you need instruction setuppy include resource files distribution there couple ways see distutils setuptools distribute depending using build distribution pyexe wiki example you may need use pyexe tip find resources installing directory exe see answer additional info including resource files distribution,i python programmer i trying build executable binary distribute software clients even fully executable i want able distribute software way convenient end user i already tried pyinstaller well pyexe i facing problem particular software i used splinter module program course new high level framework interact frameworks like selenium every time i try compile seems file called webdriverxpi always left final package therefore program attempts execute webdriver fails io error saying file webdriverxpi foundbut gui everything works perfectly fine so way include even manually i tried including manually browsing specific folder libraryzip file work i really expert matter i rely guiexe building everythingand i would really appreciate advice possible fix thanks,1 you seeing overflow assuming long bit range values store th fibonacci number to accurately need larger integers python supports natively i dont think numpy supports as pure python example def fibn x xrangen xappendxx return x this forces python use larger integer values calculation,i try write fast fibonacci algorithm python used extremely large values i keep getting negative values i assuming properly using longs fibonaccimatrix numpymatrix def fibn return fibonaccimatrixn fibonaccimatrix numpymatrixllll def fibn return fibonaccimatrixn def fibn n return l else return longlongfibnlongfibn print fib print fib print fib which gives output instead positive values like fibonacci numbers can someone help troubleshoot or better yet help write improved efficient infinetly accurate fibonnaci sequence code most googling yields terrible basic slow recursive fibonnacci algorithms,2 you make numpy use python arbitraryprecision integers setting dtype object fibonaccimatrix numpymatrix dtypeobject def fibn return fibonaccimatrixn fib l i know much help usually want really fast implementation recursive function like use various identities reductions for example using identity fn fnfn allows nice logarithmic evaluation actually wikipedia lists generalization even better is reason really need speed,i try write fast fibonacci algorithm python used extremely large values i keep getting negative values i assuming properly using longs fibonaccimatrix numpymatrix def fibn return fibonaccimatrixn fibonaccimatrix numpymatrixllll def fibn return fibonaccimatrixn def fibn n return l else return longlongfibnlongfibn print fib print fib print fib which gives output instead positive values like fibonacci numbers can someone help troubleshoot or better yet help write improved efficient infinetly accurate fibonnaci sequence code most googling yields terrible basic slow recursive fibonnacci algorithms,2 the qch files pyqt documentation folder demos work correctly if accepted default paths installed python pyqt probably cpythonlibsitepackagespyqtdoc before move qch files open qt assistant remove documentation added previously then close qt assistant move qch files qch folder pyqt doc folder eg cpythonlibsitepackagespyqtdocqch the required qch files qtqch designerqch linguistqch when reopen qt assistant automatically find documentation start reindexing after finishes close qt assistant open pyqt demos there couple important things note firstly warning message box always appear windows even documentation installed correctly really bug startup script could easily make necessary checks secondly demos descriptions still see warning could load description ensure documentation qt built many places eg demonstrationsminehunt however installed things correctly demos dialogs section descriptions screenshots instance,i installed pyqt windows python trying execute demo i got following warning after research i could obtain copy qt documentation qch format works qt assistant how documentation installed order get pyqt demo eliminate warning is qtqch documentation i using qt assistant valid specific document demo if yes downloaded i searching net time found people asking similar questions also so useful answer,3 a similar question mapping numpy array place if find ufunc f use parameter,given numpy array a fastestmost efficient way apply function f every cell suppose assign aij faij the function f binary output thus masking operations help is obvious double loop iteration every cell optimal solution,2 usrbinpython def cls subprocess import call platform import system os system os linux call clear shell true elif os windows call cls shell true,what i need look see i windows unix etc,2 here method using sets setunion set b set c set master abc setunionmaster found something else not set something else if reason testing membership simply avoid adding entry twice set structure uses aadd add something set add thus eliminating need test thus following aset aadd set aadd set if need set elsewhere list simply say lista get list tuplea get tuple,i tlist list lists i would like add new items list present for instance item i present add tlist otherwise skipis pythonic way note at first tlist may empty elements added code after adding z example tlist abcdfghijzaabb the elements based calculations z item c example item given user tlist abcdfghij tlist something check files previously present tlist add tlist elif item ziptlist something,1 the use character class range specification this result character class containing actually excluding since using much intend to specify literal character class mention first like,i trying match cc function definition using fairly complex regular expression i found case working i trying understand here input string match void dumpconst char itemname ofstream amp os clearly valid c method declaration here re wsifforswitchwhilecatchreturnws this basically tries distinguish c syntax looks like method declaration ie words followed paraentheses using useful python regular expression debugger httpwwwpythonregexcom i narrowed trailing i remove trailing regular expression matches method signature i leave there must idiosyncracy python re eluding thanks,2 the output pythonregex somewhat misleading the results rgroups rfindall u void dump content first capturing group if showed whole match see remove matching void dump whole function definition intended the reason greg explained syntax error last character class you need escape hyphen listing first last adding backslash the way i see get pythonregex show whole match removing capturing groups converting noncapturing,i trying match cc function definition using fairly complex regular expression i found case working i trying understand here input string match void dumpconst char itemname ofstream amp os clearly valid c method declaration here re wsifforswitchwhilecatchreturnws this basically tries distinguish c syntax looks like method declaration ie words followed paraentheses using useful python regular expression debugger httpwwwpythonregexcom i narrowed trailing i remove trailing regular expression matches method signature i leave there must idiosyncracy python re eluding thanks,1 you check value freq if value loop never run percentagefreq return value looking loop x az freq compressedtxtcountx print x freqt freq last value countz likely zero,when i run program function percentagefreq returns none what i wrong def main file rawinputplease enter name file readfilefile print print the file contains print lc tolowercases print the file lowercase print lc print compressedtxt nospaceslc print the alphabetic characters alone print compressedtxt print count alphalc nonchr lens count print the number alphabetic characters count print the number nonalphabetic charcters nonchr print print lettertfrequencytpercentage countfreqcompressedtxt percent percentagefreqcount print percent def readfilefile text openfiler textread textclose return def tolowercases lc x a x z lc lc chrordx else lc lc x return lc def nospaceslc compressedtxt x lc x z compressedtxt compressedtxt x return compressedtxt def alphalc count x lc x z count count return count def countfreqcompressedtxt global freq freq az abcdefghijklmnopqrstuvwxyz x az freq compressedtxtcountx print x freqt def percentagefreqcount rangefreq percent icount return percent i trying calculate percentage letter appearing file text main,1 you pretty much everything wrong sorry say my comments answer explain several problems here improvements well def main there really reason pull separate function something simple opening reading file it done one line following simpler way handling fileclosing logic filename rawinputplease enter name file openfilename f fread print print the file contains print again lowercasing built right reason write lc slower print the file lowercase print lc print nospaces bad name function actually removing everything letter again trivial oneliner compressed filterstrisalpha lc print the alphabetic characters alone print compressed print there much simpler way count alphabetic nonalphabetic characters already string alphabetic characters strings know long count lencompressed nonchr lens count print the number alphabetic characters count print the number nonalphabetic charcters nonchr print print lettertfrequencytpercentage your logic entirely messed print letters frequencies magically go back insert percentages you need calculate frequencies first calculate percentages frequencies print everything again counting frequencies actually building list need oneliner alphabet abcdefghijklmnopqrstuvwxyz by way notice i abbreviating names frequencies compressedtxtcountletter letter alphabet stop trying tell python put together list data ask data want similarly percentages f floatcount f frequencies notice conversion divide two integers throw away remainder case means get every value now output data using builtin zip function take pairs data two lists l f p zipalphabet frequencies percentages print l f p main without comments diagnostics get something simple def main filename rawinputplease enter name file openfilename f data filterstrisalpha freadlower alphabet abcdefghijklmnopqrstuvwxyz frequencies datacountletter letter alphabet percentages f floatlendata f frequencies print lettertfrequencytpercentage l f p zipalphabet frequencies percentages print l f p or even simply could calculate values within loop mostly show techniques necessary actually pass around data way seem want def main filename rawinputplease enter name file openfilename f data filterstrisalpha freadlower print lettertfrequencytpercentage letter abcdefghijklmnopqrstuvwxyz frequency datacountletter print letter frequency frequency floatlendata,when i run program function percentagefreq returns none what i wrong def main file rawinputplease enter name file readfilefile print print the file contains print lc tolowercases print the file lowercase print lc print compressedtxt nospaceslc print the alphabetic characters alone print compressedtxt print count alphalc nonchr lens count print the number alphabetic characters count print the number nonalphabetic charcters nonchr print print lettertfrequencytpercentage countfreqcompressedtxt percent percentagefreqcount print percent def readfilefile text openfiler textread textclose return def tolowercases lc x a x z lc lc chrordx else lc lc x return lc def nospaceslc compressedtxt x lc x z compressedtxt compressedtxt x return compressedtxt def alphalc count x lc x z count count return count def countfreqcompressedtxt global freq freq az abcdefghijklmnopqrstuvwxyz x az freq compressedtxtcountx print x freqt def percentagefreqcount rangefreq percent icount return percent i trying calculate percentage letter appearing file text main,1 as df eg et as string you need fix code list strings imm suggests now use zip two lists make dictionary let as df eg et as num dictziplet num df et as eg note one values as dictionary since duplicate keys,i trying create lookup table two arrays i created text file one letters let as df eg et as the numbers num i want able retrieve number corresponding pair letters how i i think problem something fact let array string indicated is way i change tuple two lists,1 pretty much viable way far i know run python subprocess within ide this avoids pollution current python interpreter makes fairly likely program run way started independently if issues check subprocess environment in manner run script debug mode using p subprocesspopenargssysexecutable pdb scriptnamepy arg stdinsubprocesspipe stdoutsubprocesspipe stderrsubprocesspipe this start python debugger prompt you need run debugger commands set breakpoints like oe pcommunicate break scriptnamepylineno if works normal output python interpreter sets breakpoint e empty i suggest play around add checks code ensure whether breakpoints properly set after start program running pcommunicate continue at point probably want hook input output error streams console embedding ide you would probably need event loop roughly like preturncode none oe pcommunicateconsoleread consolewriteo consolewritee you consider snippet effectively pseudocode since depending exactly console works probably take tinkering get right if seems excessively messy probably simplify process bit using features python pdb bdb modules i guessing python debugger basic debugger respectively the best reference source code pdb module basically way responsibilities modules split bdb handles hood debugger functionality like setting breakpoints stopping restarting execution pdb wrapper around handles user interaction ie reading commands displaying output for ideintegrated debugger would make sense adjust behavior pdb module two ways i think automatically set breakpoints initialization without explicity send textual commands make take input send output ide console just two changes easy implement subclassing pdbpdb you create subclass whose initializer takes list breakpoints additional argument class mypdbpdbpdb def initself breakpoints completekey tab stdinnone stdoutnone skipnone pdbpdbinitself completekey stdin stdout skip selfbreakpoints breakpoints the logical place actually set breakpoints debugger reads pdbrc file occurs pdbpdbsetup method to perform actual setup use setbreak method inherited bdbbdb def setinitialbreakpointsself breakpoints selfbreakpoints selfbreakpoints none avoid setting breaks twice bp breakpoints selfsetbreakfilenamebpfilename linebpline temporarybptemporary conditionalbpconditional funcnamebpfuncname def setupself f pdbpdbsetupself f selfsetinitialbreakpoints this piece code would work breakpoint passed eg named tuple you could also experiment constructing bdbbreakpoint instances directly i sure would work properly since bdbbdb maintains information breakpoints next need create new main method module runs way pdb runs to extent copy main method pdb name main statement course need augment way pass information additional breakpoints what i suggest writing breakpoints temporary file ide passing name file second argument tmpfilename write breakpoint info p subprocesspopenargssysexecutable mypdb tmpfilename delete temporary file then mypdbmain would add something like def main code excerpted pdbmain del sysargv add bpfilename sysargv openbpfilename f read breakpoint info breakpoints del sysargv back excerpt pdbmain syspath ospathdirnamemainpyfile pdb pdbbreakpoints modified now use new debugger module like would use pdb except explicitly send break commands process starts this advantage directly hook standard input output python subprocess console allows,i writing little python ide i want add simple debugging i need features winpdb how i launch python program file name breakpoint set line number runs line number halts note i want commandline i want edit source inserting settrace example and i want stop first line i run debugger i tried obvious ways pdb bdb i must missing something,3 so i traced firefxbinarypy figure actual error connection refused socketconnect selfprofileport called the port value changes every time ie the error occurs depends group setting apache config apache run user group graham suspected i playing users groups app app app groups nreeves nreeves nreeves adm dialout fax cdrom floppy tape dip video plugdev fuse i tried patters works still confuses hope someone could tell work usernreeves groupadm work either userapp groupapp works usernreeves groupnreeves,i running python virtualenv django modwsgi apache application ubuntu everything including psycopg etc working great wsgi app running the issue selenium i getting error only i execute wsgi creating firefox driver follows selenium import webdriver wd webdriverfirefox webdriverexception exception value message can load profile profile dir tmptmphmw selenium version apache launched root child process launched user called app execute code virtualenv without wsgi works fine so makes think permission issue level i tried ls l tmptmphmw drwxrxrx app app extensions rwrr app app userjs i would appreciated could point right direction i might misconfiguring wsgi,1 i usually ask index value i care g foo,if i function like following def foo return i would normally call function like g f foo but i never plan using second value returned way calling function makes clear future i get distracted placefiller variable for example something like g notused foo seems like probably standard way,1 you could get first item directly g foo i think pylint recommends dummy g foo,if i function like following def foo return i would normally call function like g f foo but i never plan using second value returned way calling function makes clear future i get distracted placefiller variable for example something like g notused foo seems like probably standard way,3 not discourage experience using com python find many examples i would shocked happy see anybody posted big tutorial reference using powerpoint python probably best find probably already found article however follow along article pythoncom code around start see patterns vb c code converts python code using interfaces once understand best source information probably powerpoint api reference msdn,i gat samples open presentation access slides shapes but i want operationseg generate thumbnail specified slide what methods i use is document illustrating functionalities,3 the no fixtures found nothing south south merely tries reload fixture data performed schemadata migrations based output looks like already latest revision migrations the fixture looking case initialdataxmlyamljson this also fixture get loaded run syncdb for example i try migrate application python managepy migrate running migrations home migrating forwards initial homeinitial loading initial data home no fixtures found however i provide initialdatajson load fixture performing migration using south based question sounds like might migrations generated django app you start running following command python managepy schemamigration omnicloudapp initial this command generate file called initialpy when run python managepy migrate run migration database,trying update app admin page i run syncdb tyre python managepy syncdb syncing creating tables installing custom sql installing indexes no fixtures found synced djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles south djangocontribadmin not synced use migrations omnicloudapp use managepy migrate migrate so alright south installed little migrationing tyre python managepy migrate running migrations omnicloudapp nothing migrate loading initial data omnicloudapp no fixtures found wait you told migrate i fixtures found fixing app synced,1 the kademlia paper actually calls optimization dynamically splitting buckets routing table grows there logic difference two approaches optimization save space when implementing fixed full sized routing table find k nodes send requests if bucket target falls empty fewer k nodes pick neighboring buckets given closest bucket split first place makes search simpler faster point i think may misunderstood kademlia the routing table bucket boundaries always relative node id and id space buckets span double bucket away without property say bucket covered equal range id space would able searches properly would certainly logn the mainline dht implements kademlia,i middle implementing dht internal cluster since used filesharing program like bittorrent mainline dht first thing i look after i found entangled python dht using twisted matrix congress python dht using pyev libev course original kademlia they different approaches organizing kbuckets congress kademlia use fixed buckets range difference id us mainline dht entangled use dynamic buckets on start bucket covering whole space after filled alive nodes bucket splitted new but only id inside bucket if bucket never splitted so soon closest us buckets both variants good enough but i found huge difference logic detects belongs id bucket and question congress kademlia treat bucket bundaries minimum distance us maximum distance us so id always bucket maximum ids bucket covers x distances always closest us so brain breaks coz everything ok but look mainline dht entangled see bucket bundaries treated absolute node id bundaries xor distance so theoretically full table ids bucket so why implementations treat bucket boundaries maxmin distance us others maxmin bit integer value,3 try including wincomgenpy package you always look created zip see directory exists done zip everything works well change following executables executableconsolepy packages wincomgenpy,so i trying package python script exe run windows machine without needing python install i running win amp application uses pywin amp launcher file called consolepy takes couple command line arguments executes another script i created setuppy file upon i ran python setuppy build following setup file cxfreeze import setup executable setup name onenote email notifications version description an email notifier onenote executables executableconsolepy that returned following error traceback recent call last file cpythonlibsitepackagescxfreezeinitscriptsconsolepy line module execcode mdict file consolepy line module file cusersvarundesktopmy dropboxonepyomnotifications vnotificati onspy line module import application file cusersvarundesktopmy dropboxonepyomnotifications vapplicatio npy line module import applicationserver file cusersvarundesktopmy dropboxonepyomnotifications vapplicatio nserverpy line module wincomclientgencacherebuild file cpythonlibsitepackageswincomclientgencachepy line rebuild savedicts file cpythonlibsitepackageswincomclientgencachepy line savedicts f openospathjoingetgeneratepath dictsdat wb file cpythonlibsitepackageswincomclientgencachepy line getgeneratepath f openfnamew ioerror errno no file directory cusersvarundesktopmy dro pboxonepyomnotifications vbuildexewinamdlibraryzipwin comgenpyinitpy i figured perhaps issue reading zipfile decided run build without creating libraryzip so i changed setuppy cxfreeze import setup executable setup name onenote email notifications version description an email notifier onenote options buildexe createsharedzip false appendscripttoexe true includeinsharedzip false executables executableconsolepy i get following error message traceback recent call last file cpythonlibsitepackagescxfreezeinitscriptsconsolepy line module execcode mdict file consolepy line module file cusersvarundesktopmy dropboxonepyomnotifications vnotificati onspy line module import application file cusersvarundesktopmy dropboxonepyomnotifications vapplicatio npy line module import applicationserver file cusersvarundesktopmy dropboxonepyomnotifications vapplicatio nserverpy line module wincomclientgencacherebuild file cpythonlibsitepackageswincomclientgencachepy line rebuild savedicts file cpythonlibsitepackageswincomclientgencachepy line savedicts f openospathjoingetgeneratepath dictsdat wb file cpythonlibsitepackageswincomclientgencachepy line getgeneratepath f openfnamew ioerror errno no file directory cusersvarundesktopmy dro pboxonepyomnotifications vbuildexewinamdconsoleexewin comgenpyinitpy,1 input pretty much useful building block interactive python shell you certainly right surprising works way rather purposespecific builtin i presume got removed python,i currently teach first year university students python i surprised learn seemingly innocuous input function students decided use confused odd behaviour hiding call eval behind so question input function call eval would ever useful safer rawinput i understand changed python seems like unusual design decision first place python x input function documentation,2 python input function returns object result evaluating expression rawinput function returns string name arthur age first rawinputplease enter age second inputplease enter age first always contain string second could contain object even type calculation use name age enter run time print you said arefirst print then said aresecond examples running example prompt python yraw please enter age please enter age you said then said example prompt python yraw please enter age please enter age you said then said prompt q input function call eval a consider scenario user inputs expression input input give correct result compared rawinput python x,i currently teach first year university students python i surprised learn seemingly innocuous input function students decided use confused odd behaviour hiding call eval behind so question input function call eval would ever useful safer rawinput i understand changed python seems like unusual design decision first place python x input function documentation,3 you change genexp better fit needs may real data work v dvalues key v istartswith list vkey listvkeyvalues dictionary content want,i set data looks similar nameitemkey valuevalue nameitemkey valuevalue nameitemlist valuelistvalue nameitemlist valuelistvalue nameitemlist valuelistvalueâ· nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalueâ· nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameotherkey valueotherkeyvalue the names flattened nested data containing lists dicts i want unflatten back dicts lists appropriate so far i obj def addobjo path value lenpath osetdefaultpathpop addobjo path value else opathpop value item data parts item name split addobjobj parts item value which generate item key value key value list listvalue listvalue listvalue list key listkeyvalue key listkeyvalue key listkeyvalue list key listkeyvalue key listkeyvalue key listkeyvalue key otherkeyvalue but i want dict keys cast ints converted lists final output would look like item key value key value list listvalue listvalue listvalue list key listkeyvalue key listkeyvalue key listkeyvalue list key listkeyvalue key listkeyvalue key listkeyvalue key otherkeyvalue any suggestions i accomplish,1 you could recursively walk dictionaries check keys converted integers using mapint yourdictkeys this generate valueerror one keys cannot converted int note check whether keys consecutive integers whether start might waste lot space convert dictionary list,i set data looks similar nameitemkey valuevalue nameitemkey valuevalue nameitemlist valuelistvalue nameitemlist valuelistvalue nameitemlist valuelistvalueâ· nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalueâ· nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameotherkey valueotherkeyvalue the names flattened nested data containing lists dicts i want unflatten back dicts lists appropriate so far i obj def addobjo path value lenpath osetdefaultpathpop addobjo path value else opathpop value item data parts item name split addobjobj parts item value which generate item key value key value list listvalue listvalue listvalue list key listkeyvalue key listkeyvalue key listkeyvalue list key listkeyvalue key listkeyvalue key listkeyvalue key otherkeyvalue but i want dict keys cast ints converted lists final output would look like item key value key value list listvalue listvalue listvalue list key listkeyvalue key listkeyvalue key listkeyvalue list key listkeyvalue key listkeyvalue key listkeyvalue key otherkeyvalue any suggestions i accomplish,1 i problem using pythondateutil there discussion problem author real solution the version listed pypi pip easyinstall scrape home page pypi listing downloads pickup version python listed there might something distutils could work around would mean pythondateutil rd party library would update distribution metadata includeuse requirespython info i think best option already make sure project depends directly,i python project depends another project depended pythondateutil when i tried python setuppy install project resolved dateutil dependency pythondateutil work python x the way i found fix problem make project installable make project directly depend pythondateutil even though directly use dateutil dependency it looks like distutils pep requirespython field specify versions python project compatible is distutils way specify information project will pypi something similar able make use information i installing project python x dependency resolution ignore pythondateutil,1 all sysexit raise exception type systemexit from documentation exit python this implemented raising systemexit exception cleanup actions specified finally clauses try statements honored possible intercept exit attempt outer level if run following see import sys try sysexit except systemexit ex print caught systemexit ex as alternative osexit stop process bypassing much cleanup including finally blocks etc,i new python i want know finally block executing calling sysexit except block code import sys def sumbyzero try print it never print except exception sysexit print printing exit finally print finally always print sumbyzero btw i trying thing java finally block executed systemexit catch block,3 about example a finally clause always executed leaving try statement whether exception occurred this error exceptions part python docs so finally block always executed example show unless use osexit but use wisely,i new python i want know finally block executing calling sysexit except block code import sys def sumbyzero try print it never print except exception sysexit print printing exit finally print finally always print sumbyzero btw i trying thing java finally block executed systemexit catch block,2 in eclipse set following ‘environment variables’ ‘pydev’ interpreter – python ever using oraclehomeyour installation pathinstantclient ldlibrarypathoraclehome dyldlibrarypathoraclehome it worked,i successfully installed latest version pydev eclipse os x python i troubles making libraries i installed work for example i trying use cxoracle library perfectly working called python interpeter simple scripts made text editor but i cant make work inside eclipse i small piece code import cxoracle conn cxoracleconnectconnstring sql select field mytable cursor conncursor cursorexecutesql row cursor field row print field if i execute eclipse i get following error import cxoracle file buildbdistmacosxuniversaleggcxoraclepy line module file buildbdistmacosxuniversaleggcxoraclepy line bootstrap importerror dlopenusersdavepythoneggscxoraclepymacosxuniversaleggtmpcxoracleso library loaded brdbmsliblibclntshdylib referenced usersdavepythoneggscxoraclepymacosxuniversaleggtmpcxoracleso reason suitable image found did find usersdaveliblibclntshdylib macho wrong architecture same snippet works perfectly python shell i configured interpeter eclipse preferences pydev interpreter python using auto config option selecting libs found what i wrong edit launching file usersdavepythoneggscxoraclepymacosxuniversaleggtmpcxoracleso command line tells usersdavepythoneggscxoraclepymacosxuniversaleggtmpcxoracleso macho universal binary architectures usersdavepythoneggscxoraclepymacosxuniversaleggtmpcxoracleso architecture macho bundle usersdavepythoneggscxoraclepymacosxuniversaleggtmpcxoracleso architecture ppc macho bundle ppc usersdavepythoneggscxoraclepymacosxuniversaleggtmpcxoracleso architecture x macho bit bundle x,3 it possible easygui what reuse code easygui see line modify slightly use askopenfilenames instead askopenfilename,i using fileopenbox i want select text files i windows box open i tried press shift ctrl a work openfile fileopenboxwelcome copr filetypes txt,1 demonizing python script actually demonizing python if root consider using gnu screen job screen handle terminal control usually complicated task regarding build daemon process start screen run program detach logout wish leave daemonlike process behind this approach effective especially program construction stable dumping many quicklywritten messages debugging still things noted daemonizing program like change working directory close descriptors use case unmount filesystem reprogram signal handles etc however conditions satisfied daemonize process init clean login session remember change directory usually enough but using screen help survive crash crashes always programmers deal,i finished app would like deploy but run app servicedeamon a google search showed different approches using python libraries twisted can i run python script service but figure any one done is bestpractice approach fredrik,1 since using python x i believe simply need use unicode rather str wincom rest however i would expected wincom automatically convert str unicode you write like itunescurrenttrackaddartworkfromfileu filelocalhostcusersarchangeldesktopapng if work i think problem lies elsewhere,i using itunes com interface windows the method itunescurrenttrackaddartworkfromfilepath requires path type bstr i understand research bstr cvisual basic data type means basic string is way converting python ascii strings bstr code import urllib beautifulsoup import beautifulsoup import import wincomclient import sys itunes wincomclientgencacheensuredispatchitunesapplication ctrackname itunescurrenttrackname cartist itunescurrenttrackartist calbum itunescurrenttrackalbum print calbum cartist ctrackname url httpwwwlastfmmusic cartist calbum albumpage urlliburlopenurlread soup beautifulsoupalbumpage soupprettify z recompile img width src classart idalbumcover itempropimage classalbumcover covermega p refindallzs print p urlliburlretrievep apng urllibquote filelocalhostcusersarchangeldesktopapng itunescurrenttrackaddartworkfromfile filelocalhostcusersarchangeldesktopapng print binasciiabuu sadsaffas itunescurrenttrackaddartworkfromfileb cusersarchangeldesktopapng error pywintypescomerror exception occurred none none none none,2 i added another answer generally answer initial question however help fix problem class myzipfilezipfilezipfile create class based zipfilezipfile def initfile mode r initial part module zipfilezipfileinitfile mode create zipfile object def enterself on entering returnself return object created init part def exitself exctype excval exctb on exiting selfclose use close method zipfilezipfile usage myzipfile newzip w tempzip use content manager myzipfile tempzipwrite sbdtoolspy write file archive if type helpmyzipfile see methods original zipfilezipfile methods init enter exit you add another functions want good luck,based statement the context manager’s exit loaded later use the context manager’s enter method invoked i seen one usage zipfile question i checked source code zipfile located usrlibpythonzipfilepy i know enter exit functions defined thank,2 basically like transcript i added blank lines aid readability pax python python r apr gcc linux type help copyright credits license information xyz open minimalmainc print xyzread int main void return xyzclose ctrld pax all showing need script order run python commands command line interface used much way,i trying solve exercise extra credit questions zed shaw learn python hard way i ran problem the code follows sys import argv script filename argv txt openfilename print here file r filename print txtread print i also ask type fileagain rawinput txtagain openfileagain print txtagainread print txtagainread i understand code used extra credit question asks startup python use open prompt notice open files run read right i tried inputting everything i could think terminal mac first starting python python command i get code run what i get piece code run prompt,1 zed say run particular piece code within python obviously code getting filename value parameters used invoke script starting python shell used parameters if filename myfilenametxt txt openfilename would work,i trying solve exercise extra credit questions zed shaw learn python hard way i ran problem the code follows sys import argv script filename argv txt openfilename print here file r filename print txtread print i also ask type fileagain rawinput txtagain openfileagain print txtagainread print txtagainread i understand code used extra credit question asks startup python use open prompt notice open files run read right i tried inputting everything i could think terminal mac first starting python python command i get code run what i get piece code run prompt,2 is ever useful use python input rawinput no input evaluates code user gives it puts full power python hands user with generator expressionslist comprehensions import ifelse operators literally anything python achieved single expression malicious users use input remove files import os remove preciousfile monkeypatch rest program setattrimport main function lambda anything a normal user need use advanced functionality if need expressions use astliteralevalrawinput – literaleval function safe if writing advanced users give better way input code plugins user modules etc – something full python syntax functionality if absolutely sure know say evalrawinput the eval screams i dangerous trained eye but odds ever need input one old design mistakes python solving,i currently teach first year university students python i surprised learn seemingly innocuous input function students decided use confused odd behaviour hiding call eval behind so question input function call eval would ever useful safer rawinput i understand changed python seems like unusual design decision first place python x input function documentation,3 i think may regex wrong urlspy the pattern specifier groups need inside parenthesis example instead urlr pusernamewppasswordwpapikeydprogramadorespemitterformat proghandler try urlr pusernamewppasswordwpapikeydprogramadores pemitterformat proghandler,i problems django api i website works well i want make api djangopiston make android app when i try get data i sent key url handlers api project empty urlspy handlerspy inside api app urlspy djangoconfurlsdefaults import pistonresource import resource myprojectapihandlers import programadorhandler myprojectapihandlers import userhandler myprojectapihandlers import getproghandler myprojectapihandlers import getuserhandler proghandler resourceprogramadorhandler userhandler resourceuserhandler getproghandler resourcegetproghandler getuserhandler resourcegetuserhandler urlpatterns patterns urlr pusernamewppasswordwpapikeydprogramadorespemitterformat proghandler urlr pusernamewppasswordwpapikeydprogramadorespprogiddprogpemitterformat getproghandler urlr pusernamewppasswordwpapikeydusuarios pemitterformat userhandler urlr pusernamewppasswordwpapikeyduser pemitterformat getuserhandler and handlerspy pistonhandler import basehandler pistonutils import rc httpstatuscode myprojectwebmodels import djangocontribauth import authenticate class programadorhandlerbasehandler allowedmethods get model programador def readself request username password apikey user authenticateusernameusername passwordpassword apikey return rcforbidden user none return programadorobjectsfilternombreprogramador completo return programadorobjectsall class getproghandlerbasehandler allowedmethods get model programador def readself request username password apikey progid user authenticateusernameusername passwordpassword user none apikey return rcforbidden return programadorobjectsall class userhandlerbasehandler allowedmethods get model usuario def readself request username password apikey user authenticateusernameusername passwordpassword ifapikey return rcforbidden return usuarioobjectsall class getuserhandlerbasehandler allowedmethods get model usuario def readself request username password apikey user authenticateusernameusername passwordpassword apikey user hola return rcforbidden return usuarioobjectsgetusernameersame how i fix,1 i checked code get output i using suds parse values in suds import client in cl clientclient httplocalhostwsdl in clservicetest out but check type value in typeclservicetest out class sudssaxtexttext so soaplib return string type data convert i check response writing soapreturnsinteger def testself return so get soa client plugin firefox response xml version encoding utf senvenvelope xmlnswsahttpschemasxmlsoaporgwsaddressing xmlnsplinkhttpschemasxmlsoaporgwspartnerlink xmlnsxophttpwwwworgxopinclude xmlnssenchttpschemasxmlsoaporgsoapencoding xmlnssenvhttpwwwworgsoapenvelope xmlnssenchttpwwwworgsoapencoding xmlnsxshttpwwwworgxmlschema xmlnswsdlhttpschemasxmlsoaporgwsdl xmlnsxsihttpwwwworgxmlschemainstance xmlnssenvhttpschemasxmlsoaporgsoapenvelope xmlnssoaphttpschemasxmlsoaporgwsdlsoap senvbody tnstestresponse tnstestresult tnstestresult tnstestresponse senvbody senvenvelope from xml cant get raw integer data,i problem soaplib i following function provided web service soapinteger integer returnsinteger def testself n n return n n the corresponding declaration datatypes generated wsdl file xscomplextype nametest xssequence xselement namen typexsinteger minoccurs nillabletrue xselement namen typexsinteger minoccurs nillabletrue xssequence xscomplextype xscomplextype nametestresponse xssequence xselement nametestresult typexsinteger minoccurs nillabletrue xssequence xscomplextype when i use ide visual studio powerbuilder generate code wsdl file whatever ide generates two classes test testresponse whose attributes strings does anyone know i tweak python declaration i avoid complextype obtain real integer datatype client side,1 python casesensitive the two lines referring two different variables note capital n first one def readwritefilename list print arg file filename what happening second line picks global variable called filename instead function argument called filename,i learning python i function readwritefilename list filename type string list list containing strings wtitten file i simple function call like fname hellotxt readwrite xx fname datalist i facing problem print filename argument value inside function definition get hellotxt rather xxhellotxt strange thing didnt expect commadline sample function works fine i wonder i missing here code def readwritefilename list print arg file filename curdir osgetcwd fullpath ospathjoincurdir filename print full path calculated fullpath fileexist ospathexistsfullpath iffileexist print file exists opening arw mode fiel openfilename arw valid exists else print file doesnt exist opening w mode fiel openfilename w doesnt exist cant open reading nothing read line list fielwrite n line print position new pointer fieltell main code calling function filename puttxt strlist hello readwrite xx filename strlist second line fn def print arg file filename prints hellotxt rather xxhellotxt this confusion behaving starngely smthing wrong,3 other option you create direct new relationship like x relationshipx primaryjoin andxidyxid xpublishtrue this join automatically,i model x model y y contains foreign key reference xid instance related x entry available property x xid columninteger foreignkey xtableid x relationship x x also boolean property publish executing query y filter results xpublish true ive tried something like dbsessionqueryyfilterbyxpublish trueall but doesnt work get error saying keyword cant expression ive looked sql alchemy docs solution cant seem find im looking any suggestions,2 i started openxyztxt well yes course going work variable xyz even attribute txt since file name want string xyztxt create putting quotes xyztxt notice python treats single double quotes less unlike languages like c java separate data type individual characters length strings,i trying solve exercise extra credit questions zed shaw learn python hard way i ran problem the code follows sys import argv script filename argv txt openfilename print here file r filename print txtread print i also ask type fileagain rawinput txtagain openfileagain print txtagainread print txtagainread i understand code used extra credit question asks startup python use open prompt notice open files run read right i tried inputting everything i could think terminal mac first starting python python command i get code run what i get piece code run prompt,1 as already said actual idea behind hashing i think really looking encryption when data encrypted nobody read only know decrypt read there many different ways encryption symmetric asymmetric read supply information really trying tell encryption use,i trying read lines file contains hashed data the data hash following code encoder hashlibsha encoderupdatestring filewriteencoderhexdigest i rehash data,1 writing something like convert twitter date timestamp ts timestrftime ymd hms timestrptimetweet createdat b hms y,i receiving twitter messages sent certain date following format twitter tue mar i want store dates timestamp time zone field postgresql djangos datetimefield field when i store string however i get error validationerror u enter valid datetime yyyymmdd hhmmssuuuuuu format i automatically transform twitter datetype python datetime time work elsewhere app saving dates,3 ipython different api fix exists last django versions for older django versions use ipython work pip install ipython,one great features django open python interpreter setup use project this used analyse objects database allows python commands executed project i find essential django development it invoked project directory using command python managepy shell i started developing new project reason shell work i look online error found anything i would greatly appreciate help error traceback recent call last file managepy line executemanagersettings file librarypythonsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file librarypythonsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file librarypythonsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file librarypythonsitepackagesdjangocoremanagementbasepy line execute output selfhandleargs options file librarypythonsitepackagesdjangocoremanagementbasepy line handle return selfhandlenoargsoptions file librarypythonsitepackagesdjangocoremanagementcommandsshellpy line handlenoargs shell ipythonshellipshellargv attributeerror module object attribute shell thanks advance help,3 yes sqlite memory cache check pragma cachesize instance also looking speedups check pragma tempstore there also api implementing cache the sqlite database file os nothing automatically done to ensure caching happen sqliteh defines runtime pragma settings it depends lot cases get slowdown instead,i pylons application using sqlalchemy sqlite backend i would like know every read operation going sqlite always lead hard disk read slow compared ram caching mechanisms already involved sqlite maintain subset database ram faster access can os linux automatically how much speedup could i expect using production database mysql postgresql instead sqlite,2 if using python use function annotations described pep def compile source something compilable filename compilable thing comes mode single statement suite see also function definitions,i know parameters object documentation quite important specify would expect first specify parameter types like str use string string int list dict function tuple object instance class myclass second specify params multiple types like function handle single parameter int str please use example demonstrate syntax needed documenting proposed solution mind desired able hyperlink reference image class inside documentation def mymethodself name image does something name string name image image image instance image class string indicating filename return true operation succeeded false return true note welcome suggest usage documentation tool sphinx oxygen long able deal requirements update it seams kind support documenting parameter types doxygen general the code works adds annoying param name initially made php param str arg description param strint arg description,2 if handled exceptions errors code code working fine still getting message correct output msg no handlers could found logger sudsclient then simple solution add line logginggetlogger sudsclient setlevelloggingcritical yourclientpy file import statement,i trying control camera wsdl file using suds i got code working i want place error handling script i tried different exceptions unable get script working when i enter invalid coordinate i get error the code i using followed error i recieving homebuildpythonpython import suds sudsclient import client python suds script controls movement camera absolute move function def absolutemove connects wsdl file stores location variable client client client httpfilewsdl create token object pass argument using factory namespace token clientfactorycreate nsreferencetoken print token create dest object pass argument values passed object dest clientfactorycreate nsptzvector destpantiltx destpantilty destzoomx print dest create speed object pass argument values passed object speed clientfactorycreate nsptzspeed speedpantiltx speedpantilty speedzoomx print speed absolutemove method invoked passing new values entered objects try result clientserviceabsolutemovetoken dest speed except runtimeerror detail print handling runtime error detail print absolutemove result result result absolutemove the error no handlers could found logger sudsclient traceback recent call last file ptztestpy line module name main result absolutemove file ptztestpy line absolutemove result clientserviceabsolutemovetoken dest speed file buildbdistlinuxieggsudsclientpy line call file buildbdistlinuxieggsudsclientpy line invoke file buildbdistlinuxieggsudsclientpy line send file buildbdistlinuxieggsudsclientpy line failed file buildbdistlinuxieggsudsbindingsbindingpy line getfault sudswebfault server raised fault error setting requested pan i sure exception i using does anyone know catch error the x coordinate value degree error happens thanks okay i found solution in suds enter faultsfalse client definition catches faults gives reason fault happened the line read client client httpfilewsdl faultsfalse the post i marked correct answer also able catch problem happened thanks,3 indentation probably lost broken have look ipython enhanced python interpreter many convenient features one magic function paste allows paste multiple lines code it also tabcompletion autoindentation many have look site using paste ipython and copyandpaste stuff one things fixed qt console using plain old copyandpaste code block works new ipython qtconsole,this piece code testpy print foo print bar succesfully executed execfiletestpy python testpy one tries copypaste python interpreter file stdin line print bar syntaxerror invalid syntax why can interpreter configured way would read copypasted text succesfully i guess may affect typing interpreter ok,3 i know trick standard command prompt i suggest advanced interpreter like ipython special syntax multiline paste in cpaste pasting code enter alone line stop c range print c another option bpython interpreter automatic paste mode typing fast human c range print c cr rewind cs save f pastebin f pager f show source,this piece code testpy print foo print bar succesfully executed execfiletestpy python testpy one tries copypaste python interpreter file stdin line print bar syntaxerror invalid syntax why can interpreter configured way would read copypasted text succesfully i guess may affect typing interpreter ok,3 as i understand build custom python default python installation you either use newly installed python specify path numpy default installation there ways second choice asume numpy module located usersmepythonmodules directory set environment variable external modules commandline setenv pythonpath usersmepythonmodules to make permanent user could add line bashrc file in code could add directory path import sys syspathappend usersmepythonmodules import numpy i hope help,while trying build python adding numpy i managed created problems somewhere now even though i numpy packages like beautifulsoup installed i unable import within mac default python previously i able import where i initially look potential problems my bash profile profile somewhere python any help would appreciated i new installing packages well path variables guidance error might would helpful edit after following john keyes advice printing python path result librarypythonsitepackagespippyegg libraryframeworkspythonframeworkversionslibpythonzip libraryframeworkspythonframeworkversionslibpython libraryframeworkspythonframeworkversionslibpythonplatdarwin libraryframeworkspythonframeworkversionslibpythonplatmac libraryframeworkspythonframeworkversionslibpythonplatmaclibscriptpackages libraryframeworkspythonframeworkversionslibpythonlibtk libraryframeworkspythonframeworkversionslibpythonlibold libraryframeworkspythonframeworkversionslibpythonlibdynload libraryframeworkspythonframeworkversionslibpythonsitepackages librarypythonsitepackages librarypythonsitepackagessetuptoolscpyegginfo should paths include installed packages numpy beautiful soup listed edit this bash profile from comments question seems like may issue i thought i include how i change python build go back installing things right place export pathusrlocalbinusrlocalsharepythonusrlocalsbinpath setting path python the orginal version saved bashprofilepysave pathlibraryframeworkspythonframeworkversionsbinpath export path,1 continuation lines needed entering multiline construct interactive mode the python tutorial v v so need enter print foo print bar i yet find suitable explanation different noninteractive session alas,this piece code testpy print foo print bar succesfully executed execfiletestpy python testpy one tries copypaste python interpreter file stdin line print bar syntaxerror invalid syntax why can interpreter configured way would read copypasted text succesfully i guess may affect typing interpreter ok,2 i think third example best solution it shortest version it avoids duplication it clear read easy follow much unlike second version you might want use newer except fooerror err syntax though python higher also example first version quite correct since urlerror handler already catches httperror except httperror part never reached you switch two except around another reason use,what good pattern avoid code duplication dealing different exception types python eg i want treat urlerror httperror simlar quite try page urlopenrequest except urlerror err loggererroran error ocurred err except httperror err loggererroran error occured err loggererrorerror message errread in example i would like avoid duplication first loggererror call given urlerror parent httperror one could something like except urlerror err loggererroran error occurred err try raise err except httperror err specialization http errors loggererrorerror message errread except pass another approach would use isinstance eg urlerror httperror would chain inheritance except urlerror httperror err loggererroran error occured err isinstanceerr httperror loggererrorerror message errread which one i prefer another better approach,3 most builtin types directly weak referenceable eg str int float list dict none cannot even made subclassing eg tuples cpython some details underlying implementation weakrefs several builtin types found march pythonlist post raymond hettinger,in python weakref document httpdocspythonorglibraryweakrefhtml says several builtin types list dict directly support weak references add support subclassing i think creating weakref big dict could useful real cases i wondering reason behind implementation,2 the user supplies goods countries postage free i wanted filter countries all countries yes postage free no charged postage the main answer question work django i think fieldpath parameter provided init method also subclassed datefieldfilterspec the postage field floatfield djangocontribadminfilterspecs import filterspec class isfreepostagefilterspec def initself f request params model modeladmin fieldpathnone superisfreepostage selfinitf request params model modeladmin fieldpath selfremoves yes postagegt no postageexact all postageexact postagegt selflinks all yes postageexact no postagegt requestgethaskey postageexact selfttl yes elif requestgethaskey postagegt selfttl no else selfttl all def choicesself cl title paramdict selflinks yield selected title selfttl querystring clgetquerystringparamdict selfremovestitle display title def titleself return free postage filterspecfilterspecsinsert lambda f getattrf freepostage false isfreepostage in selflinks supply dicts used construct http query strings like postageexact possible filters filters i think cumulative previous request no request yes remove no query selfremoves specifies needs removed query the choices method constructs query strings says filter selected sets displayed name filter,how i add custom filter django admin filters appear right side model dashboard i know easy include filter based field model calculated field like class newsitemmodelsmodel headline modelscharfieldmaxlength blankfalse byline modelscharfieldmaxlength blanktrue dateline modelsdatetimefieldhelptextdatetime appears article bodycopy modelstextfieldblankfalse whentopublish modelsdatetimefieldverbosenamewhen publish blanktrue nulltrue how can i have islive part admin filter it calculated state def isliveself selfwhentopublish none selfwhentopublish datetimenow return img alttrue srcmediaimgadminiconyesgif else return img altfalse srcmediaimgadminiconnogif isliveallowtags true class newsitemadminadminmodeladmin form newsitemadminform listdisplay headline id islive listfilter islive make work,1 you terminating shell process spawned that guess if right look question subprocess deleting child processes windows,when start windows executable using subprocesspopen shell mode kill instead letting exe finish running executable remains locked long python program running this happen shellfalse anyone know solution import time import subprocess proc subprocesspopenrpathtoexecutable shelltrue timesleep procterminate kill proc none executable locked next secs timesleep,1 yes anotherfunction lambda x x to clear taking place anotherfunction called defined,is way achieve something like python anotherfunction functionx return x,3 make sure open file b attribute example filemyfilebin rb then use seek method file object look httpdocspythonorgreleaselibbltinfileobjectshtml,i huge binary file i want read bytes exact positions file how i access specific bytes binary file loop bytes beginning file thanx,3 the fn key usually proprietary devicespecific modifier handled device driver hardware it normal button catch code to honest i imagine ever possibly want,i like find easiest way read fn key keyboard python windowsi tried use pygame library work fn key,3 sitepy indeed answers i wanted remove dependencies old python installed default mac this works pretty good sitepy called time python interpreter started for mac i manually added following line end main systemlibraryframeworkspythonframeworkversionsextraslibpythonsitepy syspath filter lambda astartswith system syspath,when i run import sys print syspath mac mac os x python i get following results librarypythonsitepackagesplypyegg librarypythonsitepackagesipythonpyegg systemlibraryframeworkspythonframeworkversionslibpythonzip systemlibraryframeworkspythonframeworkversionslibpython systemlibraryframeworkspythonframeworkversionslibpythonplatdarwin systemlibraryframeworkspythonframeworkversionslibpythonplatmac systemlibraryframeworkspythonframeworkversionslibpythonplatmaclibscriptpackages systemlibraryframeworkspythonframeworkversionsextraslibpython systemlibraryframeworkspythonframeworkversionslibpythonlibtk systemlibraryframeworkspythonframeworkversionslibpythonlibold systemlibraryframeworkspythonframeworkversionslibpythonlibdynload librarypythonsitepackages systemlibraryframeworkspythonframeworkversionsextraslibpythonpyobjc systemlibraryframeworkspythonframeworkversionsextraslibpythonwxmacunicode they grouped categories librarypythonsitepackagesegg librarypythonsitepackages frameworkspythonframeworkversionslibpython frameworkspythonframeworkversionsextraslibpython path pythonpath environment variable and i add paths using code syspathinsert morepath what routines sets paths are paths built python source code is possible paths inserted syspathinsert ignored i curious modwsgi i found paths found syspathinsert i asked another post question added based michael answer i looked sitepy i got following code def addsitepackagesknownpaths add sitepackages possibly sitepython syspath sitedirs seen prefix prefixes prefix prefix seen continue seenappendprefix sysplatform osemx riscos sitedirsappendospathjoinprefix lib sitepackages elif sysplatform darwin prefix sysprefix sitedirsappendospathjoinlibrarypython sysversion sitepackages i also think directory name sitepy systemlibraryframeworkspythonframeworkversionslibpython mac built python source code,3 you shuold take look pybrain great machine learning module python can tell much i never really used read looked several projects solved seems good you may also want take look list python machine learning modules httpwebmediamitedustefietechnicalpythonmlhtml or so question is recommended package machine learning python,i need test various famous classification methods like knn id huge dataset project choose one future use i limitation language performance readable code learning classification phase important therefore i looking good library following features includes various classification methods high performance easily usable suggestions,1 this probably efficient way import pprint data nameitemkey valuevalue nameitemkey valuevalue nameitemlist valuelistvalue nameitemlist valuelistvalue nameitemlist valuelistvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameotherkey valueotherkeyvalue obj def addobjo path value lenpath osetdefaultpathpop addobjo path value else opathpop value item data parts item name split addobjobj parts item value function assumes keys strings def convertobj isinstanceobj dict allkeyisdigit key objkeys return convertobjkey key sortedobjkeys keyint return dictkey convertvalue key value objitems return obj pprintpprintconvertobj which generates following ouput item key value key value list listvalue listvalue listvalue list key listkeyvalue key listkeyvalue key listkeyvalue list key listkeyvalue key listkeyvalue key listkeyvalue key otherkeyvalue,i set data looks similar nameitemkey valuevalue nameitemkey valuevalue nameitemlist valuelistvalue nameitemlist valuelistvalue nameitemlist valuelistvalueâ· nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalueâ· nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameitemlistkey valuelistkeyvalue nameotherkey valueotherkeyvalue the names flattened nested data containing lists dicts i want unflatten back dicts lists appropriate so far i obj def addobjo path value lenpath osetdefaultpathpop addobjo path value else opathpop value item data parts item name split addobjobj parts item value which generate item key value key value list listvalue listvalue listvalue list key listkeyvalue key listkeyvalue key listkeyvalue list key listkeyvalue key listkeyvalue key listkeyvalue key otherkeyvalue but i want dict keys cast ints converted lists final output would look like item key value key value list listvalue listvalue listvalue list key listkeyvalue key listkeyvalue key listkeyvalue list key listkeyvalue key listkeyvalue key listkeyvalue key otherkeyvalue any suggestions i accomplish,1 thanks steven russell owen tkinter folklore explains get stringvar value directly name argument pyvar using globalgetvar map name widget your lambda method changing callback args like magic us python newbies least when one entry often necessary know value entry changed expanding steven example slightly following python passes index used keep track multiple entries tkinter import tk frame label entry stringvar class fruitlist def entryupdateself sv printsv selffruiti svget def initself root cf frameroot cfpack selfsva selffruit apple banana cherry date f selffruit lenselfsva selfsvaappendstringvar selfsvaitracew lambda name index mode varselfsvai ii selfentryupdatevar labelcf textfgridcolumn rowi entrycf width textvariableselfsvaigridcolumn rowi root tk roottitleentryupdate app fruitlistroot rootmainloop,exactly question says text widgets modified event entry widgets appear,3 it name main you forgot underscores around main,i installed python machine i attempting run code class helloobject def mainself print hello world name main h hello hmain when i call python foopy return either print statement log statement appears newline when i call python shell works expected additionally i could write file print hello world and print either powershell cmd what i missing,3 in l foo bar in joinl x lenl out foo bar x x the x lenl produces list comprising correct number x entries needed padding edit there question happens lenl in case x lenl results empty list expected,how i pad list printed python for example i following list mylist foo bar i want print padded four indices commas i know i following get comma space separated list joinmylist but i pad four indices x output like foo bar x x,3 two approaches ex commands formatting my first thought textwidth se tw gnorm gqq ampg this sets text width chars reformats nonempty line inserts space start lines start use macro alternatively make macro gg qqfacrescjq q rationale go begin buffer record macro q qq starts recording q ends recording f forward second comma acresc append newline j next line move caret first character rinse repeat number times repeat processing stop macro fails eg end file,so i several large datasets i need make readable currently i go move rd value insert newline i tried several things vim get work none seem return value i looking here data what i need make look like instead i used selection try get move rd value duplicated entire thing moved entire line ssrampg i also tried removing make work work either so way i capture rd value insert carriage return newline make work thanks edit i apologize miscommunicating part problem the data top one line several lines it looks like e,3 another possibility using itertools import itertools l foo bar joinitisliceitchainl itrepeat x,how i pad list printed python for example i following list mylist foo bar i want print padded four indices commas i know i following get comma space separated list joinmylist but i pad four indices x output like foo bar x x,1 the way i would would something like szsr translated over visual range sxy substitute x y start line anything comma one many possible a comma end first field anything comma one a comma send second field zs mark point start match bother including result r we replacing nothing end match newline r another alternative sampr translated sxy as start line a group containing everything including first comma match preceding group twice including second comma ampr replace already followed newline and another given equal data widths navigate space third column first row hit ctrlv go selected whole column spaces j example press either shifti depending whether want keep space enter esc,so i several large datasets i need make readable currently i go move rd value insert newline i tried several things vim get work none seem return value i looking here data what i need make look like instead i used selection try get move rd value duplicated entire thing moved entire line ssrampg i also tried removing make work work either so way i capture rd value insert carriage return newline make work thanks edit i apologize miscommunicating part problem the data top one line several lines it looks like e,1 use macros format line go begining next line then apply macro may times need so starting record macro q register edit line press q save macro and finally apply using prefix number times want repeat,so i several large datasets i need make readable currently i go move rd value insert newline i tried several things vim get work none seem return value i looking here data what i need make look like instead i used selection try get move rd value duplicated entire thing moved entire line ssrampg i also tried removing make work work either so way i capture rd value insert carriage return newline make work thanks edit i apologize miscommunicating part problem the data top one line several lines it looks like e,1 make recursive macro alternative sehe macrofortimes answer ggqafacrescjaq then run command second line need move cursor visualization gg qa f acresc jaq,so i several large datasets i need make readable currently i go move rd value insert newline i tried several things vim get work none seem return value i looking here data what i need make look like instead i used selection try get move rd value duplicated entire thing moved entire line ssrampg i also tried removing make work work either so way i capture rd value insert carriage return newline make work thanks edit i apologize miscommunicating part problem the data top one line several lines it looks like e,1 in general use dir builtin python inspect object it would seem tweepy documentation lacking i would imagine status objects mirror structure twitter rest status format see example httpsdevtwittercomdocsapigetstatuseshometimeline so try print dirstatus see lives status object say print statustext print statususerscreenname,i writing twitter program using tweepy when i run code prints python values like tweepymodelsstatus object xffcc which good how i get actual tweet import tweepy tweepyapi key xxxxx sec xxxxx tok â xxxxx tsec xxxxx auth tweepyoauthhandlerkey sec authsetaccesstokentok tsec api tweepyapiauth pub apihometimeline pub â â â â print stri,3 there seems python port arc readability script might point right direction least direction,i would like scrape several different discussions forums different html formats rather dissecting html page would efficient fun implement sort learning algorithm could identify different messages ie structures page individually parse simultaneously ignoring extraneous crap ie ads nonsense could someone please point references sample code work already carried area moreover anyone know pseudocode arc readability code httpwwwminvolaicomblogdecruftarcsreadabilityinpython,1 it appears tkintertkinter changed tkintertkinter python compare docs python python also dooneevent longer tkintertkinter still member tk aka root object so change code def keyspresseddoelambda arg rootwindowdooneeventarg dwtkintertkinterdontwait this takes advantage fact linked code rootwindow global rootwindow available class defined available lambda run,updated see below i porting code assignment httpwwwstanfordeduclasscsprogassignmentspasearchhtml entire source code available zip python x x note porting assignment trying keep code date avoiding installing another version python after usual x x syntax fixes printing exception raising etc realizing module tkinter known tkinter x lowercase i run stranger problems snippet several others like def keyspresseddoetkintertkinterdooneeventdwtkintertkinterdontwait the errors type attributeerror module object attribute tkinter code completion ide variable trace indeed seems indicate tkinter module attribute subclass tkinter one might refer dooneevent dontwait however references internet people using constructs like tkinterdooneeventtkinterdontwait move main loop ahead even referencing like still yields error any ideas greatly appreciated update referring rootwindow via lambda notation seems work longer complains preexecution time majority cases to untrained eye however basically magic i little idea subsequent error saying work around the method looks like changes first line def movetoobject x ynone doelambda arg rootwindowarg dwtkintertkinterdontwait none try x x except raise incomprehensible coordinates horiz true newcoords currentx currenty canvascoordsobject first point coord canvascoordsobject horiz inc x currentx else inc currenty horiz horiz newcoordsappendcoord inc canvascoordsobject newcoords doedw error i get typeerror tk object callable referencing line method defined first line,1 gnorm wim explanation gcmd run cmd every line norm execute following string normal mode commands wim move words insert return m accomplished pressing cvcr cqcr it tempting norm wim fail messes lines worked,so i several large datasets i need make readable currently i go move rd value insert newline i tried several things vim get work none seem return value i looking here data what i need make look like instead i used selection try get move rd value duplicated entire thing moved entire line ssrampg i also tried removing make work work either so way i capture rd value insert carriage return newline make work thanks edit i apologize miscommunicating part problem the data top one line several lines it looks like e,3 i came across problem recently i’m becoming partial “always use virtualenv” mindset problem install virtualenv pip without installing distribute global user sitepackages directory to i manually downloaded distribute pip virtualenv one i ran “python setuppy install prefix localpythonprivate” temporary setting pythonpathlocalpythonprivate setup scripts able find distribute i’ve moved virtualenv script another directory i path edited distribute virtualenv modules found syspath tada i install anything usr usrlocal user sitepackages dir i run virtualenv anywhere virtualenv i get pip,short question what proper way install pip virtualenv distribute background in answer so question i recommended using ezsetup could install pip virtualenv follows curl o httppeaktelecommunitycomdistezsetuppy sudo python ezsetuppy sudo easyinstall pip sudo pip install virtualenv i originally pulled instructions jesse noller blog post so want use python mac i like idea keeping clean global sitepackages directory packages i install virtualenvwrapper distribute i recently added distribute toolbox python public service announcement to install two packages i used sudo pip install virtualenvwrapper curl o httppythondistributeorgdistributesetuppy sudo python distributesetuppy no setuptools easyinstall to really follow python public service announcement fresh python install i would following curl o httppythondistributeorgdistributesetuppy sudo python distributesetuppy sudo easyinstall pip sudo pip install virtualenv sudo pip install virtualenvwrapper glyph rebuke in comment answer so question so user glyph stated no never ever sudo python setuppy install whatever write pydistutilscfg puts pip installation local something especially files named ezsetuppy tend suck newer versions things like setuptools easyinstall potentially break things operating system back short question so glyph response leads original question what proper way install pip virtualenv distribute,1 this hard answer can give us command lines used does setuppy use distutils setuptools have changed pydistutilscfg pypirc file two times,i betaversion package pypi the metainformation eg home page categories etc setuppy appeared project pypi page later i updated project the thing i changed setuppy version number update as always never trust someone says i changed setuptools distutils cargo cult programming i copied another project done sorry but next version project pypi page metainformation i trying work i broke i find pypi rather taxing get right i sure this time i used python fairly fresh install windows previously i used python x i almost certainly used different commandline upload this time seemed need signing pgp installed i recall needing last time where i look see metainformation setuppy file longer uploaded,1 scipy griddata seems able deal data sets size without problems import numpy np import scipyinterpolate old grid x npmgridj j z npsinx j npcosy data new grid x npmgridj j interpolate onto new grid z scipyinterpolategriddataxravel yravel zravel x method cubic the griddata step takes old amd athlon if data grid ie coordinates corresponding value zij xi yj get speed using scipyinterpolaterectbivariatespline z scipyinterpolaterectbivariatesplinex zrealx jscipyinterpolaterectbivariatesplinex zimagx takes it much faster even grid spacings irregular efficient algorithm used long grid rectangular,i trying interpolate complex values one irregular grid another irregular grid using python the grids d data points i using python scipy numpy matplotlib in matlab using griddata achieved roughly seconds bngrid griddatargridzgridbngridrgridzgrid matlab note arrays x however i try using matplotlibmlabgriddata i get memoryerror even i try work real part mlabgriddatargridflattenzgridflattennumrealbngridflattenrgridflattenzgridflatten if i try using interpd i get segmentation fault python exits interpinterpdrgridzgridnumrealbngrid i tried using kdtree seems work ok however takes minutes compared seconds matlab i explored option much yet was wondering anyone ideas i get done quickly matlab seems i noticed newer version scipy also griddata anyone know handle large irregular grids,3 add line jquery code ajaxsetup data csrfmiddlewaretoken csrftoken done,i could use help complying django csrf protection mechanism via ajax post i followed directions httpdocsdjangoprojectcomendevrefcontribcsrf i copied ajax sample code page exactly httpdocsdjangoprojectcomendevrefcontribcsrfajax i put alert printing contents getcookie csrftoken xhrsetrequestheader call indeed populated data i sure verify token correct i encouraged finding sending something but django still rejecting ajax post here javascript postmemorize data function result result failure getrandomcard else alertfailed save card data here error i seeing django feb post memorize http i sure i missing something maybe simple i know i searched around so saw information turning csrf check view via csrfexempt decorator i find unappealing i tried works i rather get post work way django designed expect possible just case helpful gist view def myviewrequest profile requestuserprofile requestmethod post process post return httpresponseredirect memorize else requestmethod get ajax requestgethaskey ajax some irrelevent code ajax response httpresponse profilegetstackjsonresponse return response else get data send along content page return rendertoresponse memorizememorizehtml my data contextinstancerequestcontextrequest thanks replies,3 loop create scope this reason in particular code idx local variable printme function from docs the following blocks module function body class definition update generator expressions scopes as python list comprehensions also scopes,i searched so i post question hopefully duplicated one def printme alist range idx aa enumeratealist pass printidx name main printme output follows i came c world could figure idx still scope code side loop thank,3 import numpy np nparray dtypenpint aviewnpuint print array dtypeuint this creates copies operations inplace edit safer cast first uint unsigned wraparound defined edit snumpynpg,i large numpy array signed bytes dtype int it contains values full range i like convert efficiently array unsigned bytes dtype uint adding element → → → etc course results still fit unsigned byte simple elementwise addition given correct numerical result creates result array using twice memory dtype int addition source array even though low bytes result elements needed import numpy numpyarray dtypenumpyint b b array dtypeint is way control dtype result array uint the alternative approach modifying values inplace casting data new type like xrange ai ai elif ai ai array dtypeint aviewdtypenumpyuint array dtypeuint much space efficient costly time large arrays transformation python how i transformation inplace quickly,3 that work remember first number example total width column including digits decimal place decimal place leading n print f n,i looking display numeric data right justified forced sign spaces mantissa decimals align column the new format specifier uses align i unable get something working c style format for example i using f n data how i get alignment is possible old style formatting i looking get decimal places aligned upseems silly question seem get anything using format command,1 have tried setting custom cc environment variable ccgcc python setuppy build,i trying compile package mac osx the package install script relies distutils the problem computer default gcc version i determined running gcc version terminal window i run python setuppy build i see output distutils choosing gcc instead this big problem code i using require gcc i admin rights machine workaroud i created symlinks send gcc gcc the result code compiles generated files work i try import python i get errors complaining missing init function shared object i tried compiling code different mac works like charm distutils chooses without forced i import generated shared object without problem so i would like compile code computer without symlink trickeryi want distutils choose automatically i tried taking files compile properly transferring computer fails number reasons linked libraries present machineare different version installed does anyone advice thanks josh,2 import sys time xrange print r you finished sysstdoutflush timesleep print the r carriage return you need comma end print statement avoid automatic newline finally sysstdoutflush needed flush buffer stdout,most questions related topics so follows how print information line without introducing new line q q instead question follows i expect see following effect you finished keep increasing time i know c cannot find good solution python,3 python print puts newline command unless suppress trailing comma so print command print you finished r formatpercentage note comma end in python print string end r unfortunately python sends output terminal complete line the complete line need flush manually import sys sysstdoutflush,most questions related topics so follows how print information line without introducing new line q q instead question follows i expect see following effect you finished keep increasing time i know c cannot find good solution python,1 example creating class using object class class zipextractorobject create class extract zip files def initself path initial part import zipfile import old zipfile selfpath path to make path available class try openselfpath rb to check whether file exists except ioerror print file exist catch error print else if file opened openselfpath rb temp selfheader tempread read first bytes selfheader xxbxx print your file zip archive else selfzipobject zipfilezipfileselfpath r def enterself on entering returnself return object created init part def exitself exctype excval exctb on exiting selfclose use close method class def superextractmembernone pathnone used extract files zip archive if arg member set extract files if path set extract files selected folder print extracting zip archive selfpath print path zip print archive header selfheader print header zip filenamenone selfzipobjectextractallpath extract member set else selfzipobjectextractmamber path else extract selected file def closeself to close file selfzipobjectclose usage zipextractor pathtozip zfile zfilesuperextract file extract file current dir zfilesuperextractnone path yourfolder extract selected dir another way zfile zipextractor pathtozip zfilesuperextract file zfileclose don forget line clear memory if run helpzipextractor see five methods init enter exit close superextract i hope i helped i test might improve,based statement the context manager’s exit loaded later use the context manager’s enter method invoked i seen one usage zipfile question i checked source code zipfile located usrlibpythonzipfilepy i know enter exit functions defined thank,1 on linux probably windows use curses module like import time import curses win cursesinitscr range winclear winaddstryou finished di winrefresh timesleep cursesendwin benfit curses apposed simpler technique draw terminal like graphics program curses provides moving xy position eg simple script updates four views import time import curses cursesinitscr rows cols winlist r range c range win cursesnewwinrows cols rrows ccols winclear winborder winlistappendwin range win winlist winaddstryou finished di winrefresh timesleep cursesendwin see power curses game snakes lines python,most questions related topics so follows how print information line without introducing new line q q instead question follows i expect see following effect you finished keep increasing time i know c cannot find good solution python,2 ok found solution import webbrowser webbrowseropen imagepng it opens default viewer browser machine also osstartfile,i would like show image using python windows platforms when i pil import image im imageopen imagepng imshow default viewer opens tells windows photo viewer open picture either file deleted etc the file probably deleted pil calls os following command start wait ampamp del f file file i found workaround they recommend changing pil code start wait ampamp ping n nul ampamp del f file file however i want others able use code is simple solution should i look alternative pil would work crossplatform,3 print resubr strteststrip uses positive lookahead print resubr r strteststrip uses backreference,i trying grab string surrounded replace first for example strteststrip strteststrip here code i far print resubr strteststrip with code i grab much result strstrip any thoughts zero first or alternatively way grab string add arround string,1 exclude characters use instead then capture part re want keep replacement string use insert print resubr r strteststrip,i trying grab string surrounded replace first for example strteststrip strteststrip here code i far print resubr strteststrip with code i grab much result strstrip any thoughts zero first or alternatively way grab string add arround string,1 surely want count loop although nice data structure collectionscounter,want count files command directory based extension so created list files cwd list extensions made dict listi made dict count parameter know handle thismy dict looks like txt doc import osglob def myfuncself mypathosgetcwd filelistglobglob list files cwd extensionlistospathsplitextx x filelist make list extensions printextensionlist count mydictdictxcount x extensionlist make dict extensions keys count value printmydict mydictvalues must sth else count printcount printmydict,1 this perfect use collectionscounter class collections import counter c counter foo foo bar foo bar baz c counter foo bar baz,want count files command directory based extension so created list files cwd list extensions made dict listi made dict count parameter know handle thismy dict looks like txt doc import osglob def myfuncself mypathosgetcwd filelistglobglob list files cwd extensionlistospathsplitextx x filelist make list extensions printextensionlist count mydictdictxcount x extensionlist make dict extensions keys count value printmydict mydictvalues must sth else count printcount printmydict,1 from matplotlibpyplothist docstring looks like log argument set true want log scale axis histx bins rangenone normedfalse cumulativefalse bottomnone histtype bar align mid orientation vertical rwidthnone logfalse kwargs log if true histogram axis set log scale if log true x d array empty bins filtered nonempty n bins patches returned there also pyplotloglog function make plot log scaling x axis,i trying make d density plot simulation data matplotlib my x data defined log quantities how i get logarithmic axes log minor ticks here exemple code import numpy np import matplotlibpyplot plt data npgenfromtxtdata a column data file x nplogdata nplogdata xmin xmin xmax xmax ymin ymin ymax ymax fig pltfigure ax figaddsubplot hist axhexbinxybins log gridsize cmapcmreds axaxisxmin xmax ymin ymax pltsavefig plotpdf,2 i aware anything standard library however could use something like def meannumbers return floatsumnumbers maxlennumbers mean mean in numpy numpymean,is builtin standard library method python calculate arithmetic mean average list numbers,3 you script start usrbinenv whateverelse first one important,i using cygwin windows run bash script activates python script i getting following error myscriptscript cydrivecusersmydrivefoldermyscriptpy usrbinenv bad interpreter permission denied i total newbie programming i looked around bit i think means python mounted different directory i access however based i found i tried following things change something user exec fstab however fstab file commented mentions defaults i know i change defaults the fstabd folder empty change usrbinenv python line script actual location python work error add pythonpath environment variables windows error i would really appreciate someone could help suggestion,3 in case i chose use directly vtk bindings python to honest i found simpler get going vtk mayavi partly documentation better many many examples it felt like mayavi adding another layer complexity way get job done but tom right after started using mayavi may easier apart mayavi offers library called tvtk pythonic version vtk bindings end i chose plain vtk order minimize number dependencies but check perhaps searching at beginning i found helpful tutorial it python tcl translating examples trivial helps understand way vtk works also order get started check examples vtk wiki if enough always check c examples translate python the translation difficult names methods properties if encouraged add examples wiki there even examples source while learning vtk rediscover ipython awesome having whole vtk namespace fingertips helps enormously in case need specific help vtkusers mailing list quite active lastly books vtk freethey python though i tried wxpython vtk together i prefer pyqt wxpython afaik problems integration vtk either library in case spending time writing gui check thoroughly paraview it probably already want python scriptable i never checked though,in day job phd student i geological modeling in spare time mainly fun i learning python trying write simple program view d geocellular models the geocellular model d grid every grid cell value shown right figure so i would want viewer able display d grid model like picture right side as well i would like able display cross sections model x z directions shown left figure i would also want models able rotate around three axes zoom i done preliminary investigation mainly seems like visvis vtk two potential options i trying use wxpython main gui looks like options work wxpython far i tell questions am i right i say i think visvis vtk would work i want is one preferable which two options would easiest implement is another option i also consider keep mind i newish python new wxpython,3 the outputwriter stuff still experimental there provision specifying output filenames yet you follow example demo app use indirection attach blobkey output blog entity choice holds desired name look yield storeoutputwordcount filekey output mainpy,how i specify outputwriter filename content type gae mapreduce job this configuration working fine creates new blobstore entry new filename every time i run job i would like able specify filename content type overwrittenreplaced time i run mapreduce job my handler writing lines text csv file mapreduce name export model mapper inputreader mapreduceinputreadersdatastoreinputreader outputwriter mapreduceoutputwritersblobstoreoutputwriter handler exportmodel params name entitykind default modelsmymodel,1 this work pillowpil solution slow bit image see pil import image import numpy np data nprandomrandint im imagefromarraydata imsave testtif im imageopen testtif data nparrayimgetdatareshapeimsize another solution using tifffile c gohlke fast import tifffile fp r pathtoimageimagetif tifffiletifffilefp tif data tifasarray,i want use tiff images effectively save large arrays measurement data with setting modei corresponding bit data range yield mb files x pixel which good however i troubles reconverting arrays comes analysing for bit data i numpyarray command works fine in case i result d numpy array tiff entry is way get work i would really like avoid using bit images i need range doubles hdd space required lots lots measurements planned,3 osunlinkfilename work also use finally try block close file descriptor like import os u httphapmapncbinlmnihgovdownloadsfrequenciesphaseiii filename allelefreqschr chromosomesi populations phasenrbfwdtxtgz url u filename try site urlliburlretrieveurlfilename except ioerror print sysstderr error opening urln try f gzipopenfilename rb except ioerror print sysstderr error opening filen sysexit else line freadline finally try fclose except pass osunlinkfilename,my python script opens gzip file ftp reads every time i run script gz files downloaded harddisk siteshtdocs folder python cgi i dont want download files harddisk else delete files execution script here snapshot script u httphapmapncbinlmnihgovdownloadsfrequenciesphaseiii filename allelefreqschr chromosomesi populations phasenrbfwdtxtgz url u filename try site urlliburlretrieveurlfilename except ioerror print sysstderr error opening urln try f gzipopenfilename rb except ioerror print sysstderr error opening filen sysexit linefreadline i appreciate suggestions,2 i know top head elevate privileges could use bit applescript ask password for example see httpsgithubcomapenwarrsshuttleblobmasteruimacosaskpasspy,in python gui application i run command root perform certain action specific installs python module systemwide on linux i simply use gksudo kdesu prefixed command passed subprocesspopen there seem mac equivalent unfortunately i seen question pointing complicated objectivec code called betterauthorizationsample i really understand would prefer write objectivec code simple task if simpler way i like know i thinking i could make password dialog box pass regular commandline sudo stdin,1 like daenyth anwer precisely answer question asked i think probably find helpful given answer seems well nt netstatexe may quite capable least cdocuments settingssammy documentsnetstat b n active connections proto local address foreign address state pid tcp established xmingexe tcp established xmingexe tcp established xmingexe tcp established can obtain ownership information tcp established boincmgrexe tcp established puttyexe the can obtain ownership information lines i running administrator like linux i really see info processes i probably actually allowed process whose acl grants necessary access practice means basically thing processes nonadmin users the exact version netstatexe copied explorer properties dialog xpsp i happen running xp sp i sure file last updated yes i using nonadmin account xp it easy also hard might think,in linux i use lsof following function def findprocessusingportportnum import os fp ospopenlsof portnum lines fpreadlines fpclose pid none lenlines pid intlinessplit return pid is crossplatform way figure as relevant reference i know process id psutil library nice lets determine sorts useful process information crossplatform way i get first part work finding pid crossplatform moment if familiar lsof switch output looks like launching python process opens tcp socket listening port lsof command pid user fd type device sizeoff node name python russ u ipv tcp listen,1 you could use gdal numpyscipy read raster images bit channel data import gdal tif gdalopen pathtif arr tifreadasarray,i want use tiff images effectively save large arrays measurement data with setting modei corresponding bit data range yield mb files x pixel which good however i troubles reconverting arrays comes analysing for bit data i numpyarray command works fine in case i result d numpy array tiff entry is way get work i would really like avoid using bit images i need range doubles hdd space required lots lots measurements planned,2 you may look boostpython library really great interfacing python c,i code c creates file writes data is possible use python functions use python functionality c code for example i like content functionpy pil import image imgobject imageopen myfilejpg create image object pixarray imgobjectload create array pixels pixcolor pixarray get color pixel i want write pixcolor text file using c possibilities include fstream include iostream int main ofstream fout colortxt iosbaseout iosbasebinary fout pixcolor that example my application really detect color pixel output colortxr file i need something faster python is possibility thanks lot,1 membership testing set vastly faster especially large sets that set uses hash function map bucket since python implementations automatically resize hash table speed constant o matter size set assuming hash function sufficiently good in contrast evaluate whether object member list python compare every single member equality ie test on,lets say i graph want see b na which faster implementation b range n setb setab or n bab this obviously oversimplified imagine graph becomes really dense,3 set i mean hash based set like hashset much faster list lookup value list go sequentially find value exists hashset directly jump locate bucket look value almost constant time,lets say i graph want see b na which faster implementation b range n setb setab or n bab this obviously oversimplified imagine graph becomes really dense,1 class interngenericformmodelform class meta model intern exclude lastachievement program widgets name textinputattrs placeholder ð˜ð¼ñ ð¸ ñ„ð°ð¼ð¸ð»ð¸ñ class internapplicationforminterngenericform class metainterngenericformmeta exclude isactive interngenericformmetaexclude,i need “override” base class nested class members keeping rest intact this i class interngenericformmodelform class meta model intern exclude lastachievement program widgets name textinputattrs placeholder ð˜ð¼ñ ð¸ ñ„ð°ð¼ð¸ð»ð¸ñ class internapplicationforminterngenericform class meta boilerplate code violates dry model interngenericformmetamodel exclude isactive interngenericformmetaexclude widgets interngenericformmetawidgets in fact i want internapplicationformmeta exactly like interngenericformmeta except exclude tuple contain one item what beautiful way python i wish i write boilerplate code like model interngenericformmetamodel also prone errors,3 i one simplecv developers it appears trying use standard python opencv wrapper what i recommend run example httpsgithubcomsightmachinesimplecvblobdevelopsimplecvexamplesdisplaysimplecampy or code well import time webbrowser simplecv import create jpeg streamers js jpegstreamer cam camera camgetimagesavejs webbrowseropenhttplocalhost camgetimage isavejs timesleep yield webserver,i trying use simplecv wwwsimplecvorg module run image recognition manipulation unfortunately incoming video feed quite finicky i sure i wrong just using basic sample code import cvwindow cvnamedwindowcamera capture cvcreatecameracapture width intcvgetcapturepropertycapture cvcvcappropframewidth height intcvgetcapturepropertycapture cvcvcappropframeheight img cvqueryframecapture cvshowimagecamera img k cvwaitkey ifk cvdestroywindowcamera break which works perfectly i plug logitech webcam however i attempt use vimicro altair camera i get grey screen saving file file empty i also attempted use simplecv code based cookbook along lines mycam camera img mycamgetimage equally unsuccessful however instead returning data simply returned image completely black i quite loss causing i tried exact system laptop failed even get image logitech cam i running windows bit python simplecv thanks,3 just pass list nparray nparraya you also take opportunity set dtype default desire nparraya dtype,i d list something like i want convert numpy array can without allocating memory like numpyzeros storing values,3 anthony one simplecv developers can try changing last line sleep just see type issue going process fast enough i recently upgraded ubuntu i think couple python bugs i need squash popped since also could post issue queue i would appreciate httpgithubcomingenuitassimplecvissues,i using simplecv find blobs used selfdriving robot the problem i call findblobs command simplecv when i completely block lens kinect camera pygame crashes giving error fatal python error pygame parachute segmentation fault sometimes works times crashes even lens unblocked it almost always crash run longer thirty seconds i reinstalled fixed many problems simplecv tried reinstalling pygame seem help also i using xbox kinect camera source i using ubuntu here exact code simplecv import simplecvdisplay import time import sleep k kinect dis display depth kgetdepth depth depthinvert depth deptherode blobs depthfindblobsthreshval minsize maxsize blobs blobsdraw depthsavedis sleep,1 the simple brute force way use numpywhere for example wanting bounding box import numpy np x nparray val npuniquex rows cols npwherex val rowstart rowstop npminrows npmaxrows colstart colstop npmincols npmaxcols print val rowstart colstart rowstop colstop this work example zeros well if array large already scipy around might consider using scipyndimagefindobjects instead unutbu suggested in particular case example unique values sequential integers use findobjects directly it expects array sequential integer represents object needs return bounding box ignored exactly want however general need touch preprocessing convert arbitrary unique values sequential integers findobjects retuns list tuples slice objects honestly probably exactly want wanting bouding box however look bit messy print starting stopping indicies import numpy np import scipyndimage ndimage x nparray item enumeratendimagefindobjectsx start print item this look slightly different might expect these slice objects max value always one higher max previous example this simply slice given tuple get data question eg item enumeratendimagefindobjectsx start print print xitem n if really want starts stops something like rowslice colslice enumeratendimagefindobjectsx start print print rowslicestart rowslicestop print colslicestart colslicestop if unique values sequential integers need bit preprocessing i mentioned you might something like import numpy np import scipyndimage ndimage x nparray ignoredval labels npzerosdatashape dtypenpint val npuniquex val ignoredval labelsx val now use labels array input findobjects item enumeratendimagefindobjectslabels start print print xitem n,i d numpy array i want find every location unique elements we find unique elements using numpyuniquenumpyarray here comes tricky part now i know locations every unique element lets consider following example array the result how could suitable way store iterate values it noted unique values adjacent the gaps could zeros lets consider another variant array the result the zeoros boundaries neglected thanks lot,2 you need remove sql alchemy object session aka expunge then request already loaded attribute wo attempting reuse last known sessionunbound session selfexpungerecord be aware though unloaded attribute return last known value none if would like later work object call add merge selfaddrecord,i want pass instance mapped class nonsqlalchemy aware method another process need values attributes the problem unboundexecutionerror occurs every time method wants read attribute value i understand happens i would like solution problem i need values defined attributes id name dirty example need sqlalchemy overhead destination method example class base declarativebase class recordbase tablename records id column id integer primarykeytrue name column name string dirty column dirty boolean indextrue synonymfor id property def idself return selfid property def nameself return selfname namesetter def nameself value selfname value selfdirty true name synonym name descriptorname synonymfor dirty property def dirtyself return selfdirty example call def doitself records selfqueryfilterrecorddirty true record records passtootherprocessrecord i tried using sessionexpunge copycopy without success,3 kat i wrote simplecv blob library there couple issues blob library found shipped release the two big ones blob library would hit python max recursion depth bail the second one stems actual underlying opencv wrapper causes pygame error blobs detected blob maker the solution right use version master branch github repo the patched version also available new simplecv release slated later month if want manually fix code i pasted fixed snippet in blobmakerpy around line def extractfrombinaryselfbinaryimgcolorimg minsize maxsize fix recursion limit bug syssetrecursionlimit maxsize maxsize colorimgwidth colorimgheight retval fix black image bug test binaryimgmeancolor test test test return featuresetretval seq cvfindcontours binaryimggetgrayscalebitmap selfmmemstorage cvcvretrtree cvcvchainapproxsimple retval selfextractfrombinaryseqfalsecolorimgminsizemaxsize del seq return featuresetretval,i using simplecv find blobs used selfdriving robot the problem i call findblobs command simplecv when i completely block lens kinect camera pygame crashes giving error fatal python error pygame parachute segmentation fault sometimes works times crashes even lens unblocked it almost always crash run longer thirty seconds i reinstalled fixed many problems simplecv tried reinstalling pygame seem help also i using xbox kinect camera source i using ubuntu here exact code simplecv import simplecvdisplay import time import sleep k kinect dis display depth kgetdepth depth depthinvert depth deptherode blobs depthfindblobsthreshval minsize maxsize blobs blobsdraw depthsavedis sleep,3 disclaimer i changed answer dramatically temporarily deleting answer rereading question carefully i misread critical parts question while still referencing similar topics algorithms answer greatly improved i attempted solve problem c hollywood version the problem dynamic constraint satisfaction problem dcsp variation constraint satisfaction problems csp use monte carlo find potential solutions given day values quantity ranges tiny otherwise use brute force find every potential solutions use constraint recording related dcsp applied cascade previous days restrict potential solution set cross fingers aim shoot guess based probability optional bruce willis wins original version first i would like state i see two main problems the sheer number possible solutions knowing number items total value lets say example yield lot possible solutions plus easy algorithm picking valid solution without inevitably trying invalid solutions total equal when possible solutions found given day d one must find way eliminate potential solutions added information given d d let lay bases upcoming examples lets keep item values whole game it either random chosen user the possible item values bound limited range two items value no item quantity greater that means in order solve easily i took liberty change one constraint makes algorithm converge faster the total quantity rule overridden rule you add remove number items within range total one day however cannot add remove number items total twice this also gives game maximum lifecycle days this rule enables us rule solutions easily and nontiny ranges renders backtracking algorithms still useless like original problem rules in humble opinion rule essence game facilitator enabling computer solve problem problem finding potential solutions for starters problem solved using monte carlo algorithm find set potential solutions the technique simple generate random numbers item values quantities within respective accepted range repeat process required number items verify whether solution acceptable that means verifying items distinct values total equal target total say while technique advantage easy implement drawbacks the user solution guaranteed appear results there lot misses for instance takes less tries find potential solutions given constraints it takes lot time around seconds lazy laptop how get around drawback well limit range smaller values find adequate number potential solutions good chance user solution appears solution set use heuristics find solutions easily later note restrict ranges less useful monte carlo algorithm since enough valid solutions iterate reasonable time for constraints around valid solutions constrained target total value monte carlo usable for around no need use monte carlo brute force loops fine i believe problem would call constraint satisfaction problem csp problem restrict set potential solutions given fact problem csp i would go ahead call problem problem general dynamic csp dcsp dcsps useful original formulation problem altered way typically set constraints consider evolves environment dcsps viewed sequence static csps one transformation previous one variables constraints added restriction removed relaxation one technique used csps might useful problem called constraint recording with change environment user entered values d find information new constraint what possibly used quantities addremove constraint apply constraint every preceding day cascade rippling effects might significantly reduce possible solutions for work need get new set possible solutions every day use either brute force monte carlo then compare solutions d d keep solutions succeed previous days solutions without violating constraints you probably keep history solutions lead solutions probably directed graph constraint recording enables remember possible addremove quantities rejects solutions based there lot steps could taken improve solution here ideas record constraints itemvalue combinations found previous days solutions reject solutions immediately item values must change you could even find smaller solution sets existing solution using solutionspecific constraints reject invalid solutions earlier generate mutant fullhistory solutions day order repair case d solution set contain user solution you could use genetic algorithm find mutant population based existing solution set use heuristics order find solutions easily eg valid solution found try find variations solution substituting quantities around use behavioral heuristics order predict user actions eg quantity every item extreme patterns etc keep making computations user entering new quantities given try figure ranking system based occurrence solutions heuristics determine candidate solution,i learning programming python algo’s trying work project i find interesting i created basic python scripts i’m sure approach solution game i trying build here’s game work users given items value for example apple pears oranges they get chance choose combo like ie apples pears oranges the output computer gets total valuein example currently the computer try guess which obviously won’t able get correctly first turn value quantityday valueday apple pears orange total the next turn user modify numbers total quantity percent may chose i’ll use example the prices fruit changeat random total value may change based alsofor simplicity i changing fruit prices example using example day game user returns value day here example quantityday changeday valueday quantityday changeday valueday i hope tables show right i manually space hopefully screen work let know i try upload screenshot i trying see i figure quantities timeassuming user patience keep entering numbers i know right restriction total value cannot i cannot within accuracy right user entering forever what i done far here’s solution farnot much basically i take values figure possible combos themi done part then i take possible combos put database dictionaryso example could dictionary entry apple pears oranges way apple pears oranges i time i get new number i list possibilities here’s i’m stuck is using rules i figure best possible solution i think i’ll need fitness function automatically compares two days data removes possibilities variance previous days data questions so question user changing total list probabilities i approach what i need learn is algorithms theories i use applicable or help understand mistake suggest rules i add make goal feasibleif current state i thinking adding fruits saying must pick least etc also i vague understanding genetic algorithms i thought i could use something i use i eager learn advice tips would greatly appreciatedjust please tell game impossible thanks advance update getting feedback hard solve so i thought i add another condition game interfere player doinggame stays everyday value fruits change pricerandomly would make easier solve because within movement certain fruit value changes combo probable time day anything possible getting close enough range almost impossible prices fruits change user choose change tover time range narrow narrow in example prices volatile enough i think i could brute force solution gave range guess i trying figure elegant solution solutions keep narrowing range time update after reading asking around i believe hidden markovviterbi problem tracks changes fruit prices well total sumweighting last data point heaviest i sure apply relationship though i think case could wrong least i starting suspect type machine learning problem update i created test casewith smaller numbers generator help automate user generated data i trying create graph see likely here code along total values comments users actually fruit quantities usrbinenv python import itertools fruit price data fruitpriceday apple pears oranges fruitpriceday apple pears oranges fruitpriceday apple pears oranges generate possibilities testingwarningwill scale large numbers def possibilitygeneratortargetsum apple pears oranges alldaypossible counter applerange range targetsum apple pearsrange range targetsum pears orangesrange range targetsum oranges j k itertoolsproductapplerange pearsrange orangesrange j k targetsum currentpossible print counter print apple iapple pears jpears oranges koranges currentpossible apple iapple currentpossible pears jpears currentpossible oranges koranges print currentpossible alldaypossiblecounter currentpossible counter counter return alldaypossible total sum returned user value fruits totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day graph graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges sample dict oranges apple pears oranges apple pears print graph,3 it depends trying accomplish using example verbatim faster use lists go overhead creating sets import timeit def usesetsa b return setb seta b def uselistsa b return b b ttimeittimerusesetsa b main import usesets b range print usesets ttimeitnumber ttimeittimeruselistsa b main import uselists b range print uselists ttimeitnumber produces usesets uselists however reasons already mentioned benefit using sets searching large sets it impossible tell example inflection point whether see benefit i suggest test ways go whatever faster specific usecase,lets say i graph want see b na which faster implementation b range n setb setab or n bab this obviously oversimplified imagine graph becomes really dense,2 your question tagged mysql yet traceback shows using postgresqlpsycopg backend could problem fix tags question set right databaseengine settingspy,i trying map data onto staging server run issue when running migrations i get following error djangodbutilsdatabaseerror column itemnameid cannot cast type pgcatalogint any ideas i resolve traceback recent call last file geckomanagepy line module executemanagersettings file applibpythonsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file applibpythonsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file applibpythonsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file applibpythonsitepackagesdjangocoremanagementbasepy line execute output selfhandleargs options file applibpythonsitepackagessouthmanagementcommandsmigratepy line handle ignoreghosts ignoreghosts file applibpythonsitepackagessouthmigrationinitpy line migrateapp success migratormigratemanytarget workplan database file applibpythonsitepackagessouthmigrationmigratorspy line migratemany result migratorclassmigratemanymigrator target migrations database file applibpythonsitepackagessouthmigrationmigratorspy line migratemany result selfmigratemigration database file applibpythonsitepackagessouthmigrationmigratorspy line migrate result selfrunmigration file applibpythonsitepackagessouthmigrationmigratorspy line run return selfrunmigrationmigration file applibpythonsitepackagessouthmigrationmigratorspy line runmigration migrationfunction file applibpythonsitepackagessouthmigrationmigratorspy line lambda return lambda directionorm file appgeckoquotemigrationsautochgfieldorderitemnamepy line forwards dbaltercolumn quoteorder itemnameid selfgf djangodbmodelsfieldsrelatedforeignkey toorm fleetgroup file applibpythonsitepackagessouthdbgenericpy line altercolumn flattenvalues file applibpythonsitepackagessouthdbgenericpy line execute cursorexecutesql params file applibpythonsitepackagesdjangodbbackendspostgresqlpsycopgbasepy line execute return selfcursorexecutequery args djangodbutilsdatabaseerror column itemnameid cannot cast type pgcatalogint,1 so i ran issue the problem i database properly synced simple problems always seem cause angst to sync django db within app directory within terminal type python managepy syncdb edit note using djangosouth running python managepy migrate command may also resolve issue happy coding,i got lot errors message databaseerror current transaction aborted commands ignored end transaction block changed pythonpsycopg pythonpsycopg django project database engine the code remains dont know errors,3 seem something like usernotices notificationnoticeobjectsfilterrecipientrequestuser unseennotices usernoticesfilterunseentrueorderbyadded notices usernoticesexcludeunseentrueorderbyadded,i writing inbox view i want exclude unseen messages seen messages my code def rendernotificationsrequest unseennotices notificationnoticeobjectsfilterrecipientrequestuserunseentrueorderbyadded notices notificationnoticeobjectsfilterrecipientrequestuserexcludeidin iid unseennoticesorderbyadded msg unseennotices msgunseen false msgsave context requestcontextrequest notices notices unseennotices unseennotices return rendertoresponse mynotificationshtml contextinstancecontext as see i exclude unseen messages using loop seem convenient i sure line cause performance issues and lastly way i replace line something similar notices notificationnoticeobjectsfilterrecipientrequestuserexcludeidin unseenmessages edit i get seen messages correctly using unseen false i mark unseen messages seen page visited with strange reason i use unseen false notices query marked unseen messages retrieved notices query,1 contlist dictkv kv diteritems k filtkeylist readinconts want slightly factored version filteroutkeys lambda x dictkv kv diteritems k x contlist filteroutkeysd filtkeylist readinconts ps i suggest making filtkeylist set instead make checks faster,import pprint fullkeylist setf f f f f expected field filtkeylist setf f fields included contlist stores filtered documents readincont f f true f abc f f xz document readincont f f false f efg f f xz document readincont f f true f acd f f xz document assume readinconts contains list documents readinconts readincont readincont readincont oneitem readinconts document list contdict key value oneitemiteritems key filtkeylist field included contdictkey value add field temporary document contlistappendcontdict pprintpprintcontlist output f f abc f f f efg f f f acd f here i want achieve given original raw collection documents ie readinconts simulation i need filter fields included process above implementation python however i think heavy expect see clean solution task thank,2 def filterdictd keys return dictkey value key value diteritems key filtkeylist contlist filterdictd filtkeylist readinconts,import pprint fullkeylist setf f f f f expected field filtkeylist setf f fields included contlist stores filtered documents readincont f f true f abc f f xz document readincont f f false f efg f f xz document readincont f f true f acd f f xz document assume readinconts contains list documents readinconts readincont readincont readincont oneitem readinconts document list contdict key value oneitemiteritems key filtkeylist field included contdictkey value add field temporary document contlistappendcontdict pprintpprintcontlist output f f abc f f f efg f f f acd f here i want achieve given original raw collection documents ie readinconts simulation i need filter fields included process above implementation python however i think heavy expect see clean solution task thank,1 seems flaw python standard library fixed python see httpwwwenricoziniorgcazzeggiopythongzip urllib urllib file objects provide method tell requested gzip,i found snippet seems job i understand uses stringio isn f already filelike object what need read make look like file read i tested well slightly modified version work without stringio,1 it possible gunzip code needs filelike object seek method http library unlikely provide what work mean error message if efficiency real concern slightly modify code uses cstringio stringio,i found snippet seems job i understand uses stringio isn f already filelike object what need read make look like file read i tested well slightly modified version work without stringio,1 you code fine you make slightly shorter sets faster ignoredkeys actually much longer ignoredkeys setf f inline version loop dict comprehension inside list comprehension filtered k v kv rowiteritems k ignoredkeys row readinconts,import pprint fullkeylist setf f f f f expected field filtkeylist setf f fields included contlist stores filtered documents readincont f f true f abc f f xz document readincont f f false f efg f f xz document readincont f f true f acd f f xz document assume readinconts contains list documents readinconts readincont readincont readincont oneitem readinconts document list contdict key value oneitemiteritems key filtkeylist field included contdictkey value add field temporary document contlistappendcontdict pprintpprintcontlist output f f abc f f f efg f f f acd f here i want achieve given original raw collection documents ie readinconts simulation i need filter fields included process above implementation python however i think heavy expect see clean solution task thank,1 not really your best bet would probably use resplit instead regex uses lookbehind make sure forward slash escaped eg unescapedslashre recompiler ptn repl unescapedslashresplitline,i file containing perlstyle regexs form patternreplace i attempting read python list compiled patterns associated replacement strings below i done far def getregexfilename regex fi openfilename r text l l fireadlines lstartswith ficlose line text ptn repl linesplit regexappendrecompileptn repl return regex this works perfectly well i get lines escaped forward slashes like when i try split string python returns list three elements rather hoped is way make replace interpret escapes,2 use split in pairs in dictpsplit p pairs out,ok i need create program accepts ordered pairs divided space adds dictionary ie pointsdict how make python recognize first number key second number value,2 values print dictxsplit x values prints,ok i need create program accepts ordered pairs divided space adds dictionary ie pointsdict how make python recognize first number key second number value,1 savefilesavepath error if dprojectaxcsv dprojectbxcsv exist write savepath if second path empty xcsv would overwrite result empty file try instead import os import csv def ensuredirf ospathdirnamef ospathexistsd osmakedirsd readpath ospathjoind project savepath ospathjoind save ensuredirsavepath dname oslistdirreadpath readpath ospathjoindname fname ospathisdirreadpath continue fname oslistdirreadpath fullfname ospathjoinreadpath fname ospathisfilefullfname continue savefile opensavepath dname fname wb writer csvwritersavefile delimiter readfileopenfullfname rb reader csvreaderreadfile delimiter try row reader writerwriterowrow row except printi finally savefileclose readfileclose this code could greatly improved oswalk,my python program loops bunch csvfiles read write specific columns file another csv file while program runs see files written correct manner program finished files written become empty the solution similar threads seems closing file write properly cant seem figure im wrong anyone import os import csv def ensuredirf ospathdirnamef ospathexistsd osmakedirsd readpath ospathjoind project savepathospathjoind save ensuredirsavepath contentsoslistdirreadpath contentslencontents readpathospathjoinreadpath ospathisdirreadpath true contentsoslistdirreadpath contents readpathospathjoinreadpath ospathisfilereadpath true savefilesavepath savefile opensavefile wb writer csvwritersavefile delimiter readfileopenreadpath rb reader csvreaderreadfile delimiter try row reader writerwriterowrow row except printi finally savefileclose readfileclose,1 in code adding nodes et cetera since reading file going give strings unless explicitly convert however trying refer nodes i guessing networkx think try changing gaddedgesrc dest gaddedgeintsrc intdest,i would like find node connectivity node rest nodes graph the input text file format follows lines first column represents source node second column represents destination node last column represents weight edge i trying read source destination nodes input file forming edge i need find connected network one component graph subcomponents here code numpy import import networkx nx gnxemptygraph row file outtxt row rowsplit src row dest row print src gaddedgesrc dest print src dest range nxbidirectionaldijkstrag print path exists manually adding edges using gaddedge works tedious suitable large input files mine the loop condition works i add edges manually throws following error code neighborsiter raise networkxerrorthe node graphn networkxexceptionnetworkxerror the node graph any help much appreciated,1 if maximum likelihood calculations first step need take following assume distribution depends parameters since generate data even know parameters tell program assume gaussian distribution however tell program parameters leave unknown priori compute afterwards now sample vector let call x elements x x process to compute following f denotes probability density function gaussian distribution fx fx as see given link f employs two parameters greek letters âµ ïƒ you calculate values âµ ïƒ way fx fx takes maximum possible value when done âµ maximum likelihood value mean ïƒ maximum likelihood value standard deviation note i explicitly tell compute values âµ ïƒ since quite mathematical procedure i hand probably i would understand i tell technique get values applied distributions well since want maximize original term simply maximize logarithm original term saves dealing products transforms original term sum summands if really want calculate simplifications lead following term hope i mess anything n lnïƒsqrtpi xiâµ ïƒ now find values âµ ïƒ beast maximal doing nontrivial task called nonlinear optimization one simplification could try following fix one parameter try calculate this saves dealing two variables time,i need code maximum likelihood estimator estimate mean variance toy data i vector samples created numpyrandomrandn the data zero mean unit variance gaussian distribution i checked wikipedia extra sources i little bit confused since i statistics background is pseudo code maximum likelihood estimator i get intuition mle i cannot figure start coding wiki says taking argmax loglikelihood what i understand i need calculate loglikelihood using different parameters i take parameters gave maximum probability what i get i find parameters first place if i randomly try different mean amp variance get high probability i stop trying,3 not sure option aware buildin support networkx multiple graph text formats the edge list format seems apply pretty well case specifically following method read input files without need custom code g nxreadweightededgelistfilename if want remove weights need could subsequently following e gedgesiterdatatrue eclear rd element tuple contains dictionary edge attributes,i would like find node connectivity node rest nodes graph the input text file format follows lines first column represents source node second column represents destination node last column represents weight edge i trying read source destination nodes input file forming edge i need find connected network one component graph subcomponents here code numpy import import networkx nx gnxemptygraph row file outtxt row rowsplit src row dest row print src gaddedgesrc dest print src dest range nxbidirectionaldijkstrag print path exists manually adding edges using gaddedge works tedious suitable large input files mine the loop condition works i add edges manually throws following error code neighborsiter raise networkxerrorthe node graphn networkxexceptionnetworkxerror the node graph any help much appreciated,1 in fact need replace gtkiconview default cell renderer gtkcellrendererpixbuf followstate property we replace default cell renderer using gtkcelllayout class gtkiconview inherits model gtkliststoregobjecttypestring gtkgdkpixbuf gobjecttypestring iconview gtkiconviewmodel renderer gtkcellrendererpixbuf renderersetproperty followstate true iconviewpackstartrenderer iconviewsetattributesrendererpixbuf pixbuf column number corresponding pixbuf render model,i want change opacity color gtkiconview select box i want actually make selection visible i noticed gtkiconview widget style properties selectionboxalpha amp selectionboxcolor accessible reading the setselectfunction method gtktreeselection class would useful i want used gtktreeview i found equivalent gtkiconview so i control selection perform action user select unselect stuff edit in fact change values selectionboxalpha selectionboxcolor style properties solution i really want change selection box opacity opacity pixbuf compositing color so i need equivalent method setselectfunction gtkiconview widget,1 if i wanna simulate cc blocks usually trick def anon a pi anon these blocks able nested if small piece initial boilerplate acceptable also use decorator call function def blockfunction function now repeat name block def anon a pi note function decorators usually return function one the result name anon points none executing code code block really anonymous,preface so far i used python full scale programming language now i like use write notes comments calculation python code i actually using emacs send current buffer running ipython instance the problem i like reuse common variable names like a multiple times within document without running problem i accidentally forget reassign value one variable names i far abuse class statement topic one bla bla class anon a pi topic two bla bla class anon a pi error raised since missing this works since class statement creates execution frame works variable scope i wonder dedicated syntax use case,1 no cannot but use python super python,can i use clean python super syntax python maybe kind future import,3 it looks like post answer still sure grab majorminor devsda entry match osstat returns device number stat command output import os print hexosstat x minor device number major device number meserver ls l devsda brwrw root disk jun devsda meserver jgaines minor device number major device number,how use python determine linux devicepartition contains given filesystem eg getfilesystemdevice devsda getfilesystempartition devsda,1 you cannot use bare super call contains typeclass nor implement replacement work python x contains special support enable bare super calls places class cell variable functions defined within class see pep,can i use clean python super syntax python maybe kind future import,3 django querysets lazy this explains unseen notices appear seen notices list follow derek suggestion comments the notices query executed template rendered call rendertoresponse by timetime already saved msg seen if call list querysets evaluated immediately unseen notifications longer appear seen notices def rendernotificationsrequest usernotices notificationnoticeobjectsfilterrecipientrequestuserorderby added unseennotices listusernoticesfilterunseentrue notices listusernoticesfilterunseenfalse snip an alternative render response update unseen flag notifications finally return response def rendernotificationsrequest usernotices notificationnoticeobjectsfilterrecipientrequestuserorderby added unseennotices usernoticesfilterunseentrue notices usernoticesfilterunseenfalse context requestcontextrequest notices notices unseennotices unseennotices response rendertoresponse mynotificationshtml contextinstancecontext update seen flag unseennoticesupdateunseenfalse return response note i used update method queryset instead looping notice you model custom save method using written prepost save hooks,i writing inbox view i want exclude unseen messages seen messages my code def rendernotificationsrequest unseennotices notificationnoticeobjectsfilterrecipientrequestuserunseentrueorderbyadded notices notificationnoticeobjectsfilterrecipientrequestuserexcludeidin iid unseennoticesorderbyadded msg unseennotices msgunseen false msgsave context requestcontextrequest notices notices unseennotices unseennotices return rendertoresponse mynotificationshtml contextinstancecontext as see i exclude unseen messages using loop seem convenient i sure line cause performance issues and lastly way i replace line something similar notices notificationnoticeobjectsfilterrecipientrequestuserexcludeidin unseenmessages edit i get seen messages correctly using unseen false i mark unseen messages seen page visited with strange reason i use unseen false notices query marked unseen messages retrieved notices query,1 instead creating new type keep flag instance says whether call result negated and offload actual overrideable call behaviour separate nonspecial method part protocol class baseobject def initself selfnegatecall false def callimplself args kwargs raise notimplementederror def callself args kwargs result selfcallimplargs kwargs return result selfnegatecall else result def negself copycopyself othernegatecall othernegatecall return,i apologize advance rather long question i implementing callable objects would like behave somewhat like mathematical functions i base class whose call method raises notimplementederror users must subclass define call my question i define special method neg base class subclasses immediately expected behavior without implement neg subclass my sense expected behavior f instance subclass base class properly defined call f instance class f possessing attributes f except call return negative f call here example i mean class baseobject def callself args kwargs raise notimplementederror please subclass def negself def callargs kwargs return selfargs kwargs mbase type mbase base call call return mbase class onebase def initself data selfdata data def callself args kwargs return this expected behavior one one print one prints minusone one print minusone prints though exactly i like since minusone instance class one i could live now i like new instance minusone inherit attributes methods one call method change so i could change neg def negself def callargs kwargs return selfargs kwargs mbase type mbase base call call new mbase n v inspectgetmembersself n call setattrnew n v return new this seems work my question cons strategy implementing generic neg must standard exercise i find anything web are recommended alternatives thanks advance comments,1 it looks like need add djangocontribauthcontextprocessorsauth djangocorecontextprocessorsrequest context processors templatecontextprocessors setting before defined templatecontextprocessors django would used default it looks code requires auth processor hence first error message the keyerror looks require request processor try following settings file templatecontextprocessors djangocontribauthcontextprocessorsauth djangocorecontextprocessorsdebug djangocorecontextprocessorsin djangocorecontextprocessorsmedia djangocorecontextprocessorsstatic djangocontribmessagescontextprocessorsmessages djangocorecontextprocessorsrequest i used default list given django request context docs added request processor commented ones seem need the order template context processors usually matter long define overlapping variable names,i making template django site quote database i wanna digglike pagination altough author application made pagination unfortunately without page numering previous next links so i installed djangopagination i use site i completly new django even programming i simple webdesigner ok go there original script httpsbitbucketorgflegfqdb the first thing problem template context processors my settingspy section i added exactly like djangopagination documentation when i run site i get error put djangocontribauthcontextprocessorsauth templatecontextprocessors setting order use admin application so i order a second problem template i use exactly like screencast extends fqdbbasehtml load paginationtags block title title endblock block content h title h quotes autopaginate quotes quote quotes include fqdbquotebodyhtml endfor paginate else pbrak cytatã³wp endif endblock but i get template error caught keyerror rendering request but seriously i know wrong code there paginated view quote list it work without pagination i think problem maybe def listpagedrequest page orderbywhat title reversename hash getiphashrequest lista quoteobjectsfilteraccepted trueorderbyorderbywhat returndict quotes lista title title hash hash sidebar getsidebar return rendertoresponse fqdbquotelisthtml quotes getquotesquotes contextinstancerequestcontextrequest i modified paginating djangopagination task you find original view bitbucket maybe know better pagination solutions,3 the answer use lambda for good explanation see tkinter callbacks effbotorg,just wondering how i bind entry field return key function requires arguments counting event one without lambda classes one function arguments def functionevententryentry widget focused also entry place holder not a widget entry must specified cannot removed entryfocus entrybindreturnfunctionnoneentry when entry binded function bound executes right binded ignores input it lets put characters field i hit return go focus second entry if i remove none one arguments gives error one two required arguments defined matter i put place none still work how i make work without classes anonymous function,1 your approach several downsides one example copy members original instance new instance work class overrides special methods call since special methods looked dictionary object type called implicitly moreover copies lot stuff actually inherited object need go instance dict an easier approach satisfies exact requirements make new type subclass instance original type this done defining local class inside neg method def negself class negselfclass def callself args kwargs return selfargs kwargs neg basenewneg negdict selfdictcopy return neg this defines new class neg derived original function type overwrites call method it creates instance class using base constructor cover case self class would take constructor arguments finally copy everything directly stored instance self new instance if i design system i take completely different approach i fix interface function would rely fixed interface every function i bother copy attributes instance negated function rather class functionobject def negself return negatedfunctionself def addself return sumfunctionself class negatedfunctionfunction def initself f selff f def callself args kwargs return selffargs kwargs class sumfunctionfunction def initself funcs selffuncs funcs def callself args kwargs return sumfargs kwargs f selffuncs this approach fulfil requirement function returned neg attributes methods original function i think requirement rather questionable far design concerned i think dropping requirement give much cleaner general approach demonstrated including add operator example,i apologize advance rather long question i implementing callable objects would like behave somewhat like mathematical functions i base class whose call method raises notimplementederror users must subclass define call my question i define special method neg base class subclasses immediately expected behavior without implement neg subclass my sense expected behavior f instance subclass base class properly defined call f instance class f possessing attributes f except call return negative f call here example i mean class baseobject def callself args kwargs raise notimplementederror please subclass def negself def callargs kwargs return selfargs kwargs mbase type mbase base call call return mbase class onebase def initself data selfdata data def callself args kwargs return this expected behavior one one print one prints minusone one print minusone prints though exactly i like since minusone instance class one i could live now i like new instance minusone inherit attributes methods one call method change so i could change neg def negself def callargs kwargs return selfargs kwargs mbase type mbase base call call new mbase n v inspectgetmembersself n call setattrnew n v return new this seems work my question cons strategy implementing generic neg must standard exercise i find anything web are recommended alternatives thanks advance comments,2 i hoped understood got index range error that one problems let examine code conceptual error sense fully understanding code made this code actually think whenever get errors like sample temp rangelensample samplei samplei tempsamplei sampleisamplei sampleitemp first line your get values case second line it check whether members list next it check first left right bigger second check false execute rest code no checking true code execute successfully swap two this good moment learn slick way swap variables python without using temporary variables samplei samplei samplei samplei read google python variable swap want so back original problem you successfully swapped list stands but continue swap swap not swap but list code stop executing did catch problem you would need rerun several times actually order since check whether list organized rather swaps members next so would specific list run j range rangelensample samplei samplei samplei samplei samplei samplei the list would ordered sorting ordered collections like lists much studied field i would recommend reading sorting algorithms starting simple ones like bubblesort since going algorithm like onatm suggested there fun ways learn algorithm example check read interested this site illustrates quite well algorithms work way sorted list good luck please comment doubt,as part python assignment i trying implement list sorting ascending without using sort method i think logic correct i keep getting error sample temp rangelensample samplei samplei sampleitemp sampleisamplei sampleitemp this keeps giving list index range error i know caused fact code still need help i changed code rangelensample samplei samplei tempsamplei sampleisamplei sampleitemp eliminates error sort list,1 since taking user input safest way define exactly valid input dispatcher add add w add try functiondispatcherw except keyerror raise valueerror invalid input if want evaluate strings like add could use safe eval eval add builtins nonedispatcher eval general could dangerous applied user input the safer since builtins disabled locals restricted dispatcher someone cleverer i might able still cause trouble i tell warning even eval builtins none dispatcher unsafe applied user input a malicious user could run arbitrary functions machine given opportunity string evaluated eval,for example i function called add like def addxy return xy i want ability convert string input direct function like wrawinput please input function want use w add is way use w refer function add,3 the builtin function eval want all usual warnings executing arbitrary usersupplied code apply if finite number predefined functions avoid eval use lookup table instead ie dict never trust users,for example i function called add like def addxy return xy i want ability convert string input direct function like wrawinput please input function want use w add is way use w refer function add,3 one safe way map names functions it safer using eval functionmappings add add def selectfunction true try return functionmappingsrawinput please input function want use except keyerror print invalid function try,for example i function called add like def addxy return xy i want ability convert string input direct function like wrawinput please input function want use w add is way use w refer function add,3 unutbu solution i would normally use completeness sake if specifying exact name function use eval although highly discouraged people malicious things evaladdxy,for example i function called add like def addxy return xy i want ability convert string input direct function like wrawinput please input function want use w add is way use w refer function add,3 any solutions work linux i found newline end extension string prevent matches succeeding add strip method end for example import ospath extension ospathsplitextfilenamestrip,is function extract extension filename,3 the sort method lists written c cpython need use getitem setitem methods if use methods would slow normal listsort immensely you may able store file indices list use list builtin sort key function work,i trying sort contents several files sometimes moving line one file another i would like use builtin adaptive merge sort attribute list i tried inheriting method list i know needs len getitem setitem yes i want sort inplace fyi here code far helps explain i order changed i call sort if add bubblesort method written python works terribly slow class memwraplist def initself prefix folder chunksizenone fns fn fn oslistdirfolder fnstartswithprefix fnssort selffiles openospathjoinfolderfn r fn fns selfmmaps mmapmmapffileno f selffiles selfsizes mmsize mm selfmmaps chunksize none selfchunksize lenselfmmapsreadline else selfchunksize chunksize def mmfromidxself idx bidx selfchunksizeidx lo ms zipselfmmaps selfsizes hi lo lo bidx hi return bidxlo lo hi def getitemself idx bidx mmap selfmmfromidxidx return mmapbidxbidxselfchunksize def setitemself idx val assert lenval selfchunksize bidx mmap selfmmfromidxidx mmapbidxbidxselfchunksize val def lenself assert sumselfsizesselfchunksize return sumselfsizesselfchunksize def bubblesortself xrange lenself swaptest false j range lenself selfj selfj selfj selfj selfj selfj swap swaptest true swaptest false break selfflush def flushself mm selfmmaps mmflush def closeself selfflush mm selfmmaps mmclose f selffiles fclose,1 it unclear question step failing might hard linking right error you try strace see system call failing that give better picture problem least this python bug report looks like going fix distutils someone supply patch might useful you might also able mount directory nfs build i believe nfs allows hard linking,i trying create python source package fails creating hard links files python setuppy sdist running sdist running check reading manifest template manifestin writing manifest file manifest making hard links foo hard linking readmetxt foo error operation permitted i tried running command sudo produces error this also produces error ln foo bar i using vbox run virtual instance ubuntu probably problem comes is way round using hard links creating source distributions system information ubuntu server virtualbox osx python,3 check inside hpy installation directory,i spent day trying get hpy module python working without success i installed hdf shared libraries followed instructions i could find web get right but work error message i get trying import module python i tried installing macports wouldnt work i using python bits another module thus installed hdf library right any help welcome thank import hpy traceback recent call last file stdin line module file libraryframeworkspythonframeworkversionslibpythonsitepackageshpyinitpy line module hpy import errors importerror dlopenlibraryframeworkspythonframeworkversionslibpythonsitepackageshpyerrorsso symbol found healreadyexistsg referenced libraryframeworkspythonframeworkversionslibpythonsitepackageshpyerrorsso expected flat namespace libraryframeworkspythonframeworkversionslibpythonsitepackageshpyerrorsso,3 the clean way using inotify system there pyinotify project want use python interface you use inotify directly though tools like icrond hook in fact person link looks trying something similar want check brute force could use watch though runs command periodically something changes,i python script converts images videos withing directory the problem python script executes manually i need script execute automatically file dropped directory linux platform what would best way set python script watchmonitor directory i looked many options sure one simply sets script execute files dropped directory thank advanced,1 the actual list sorting code available around line httpsgithubcompythongitpythonblobmasterobjectslistobjectc as far i tell would possible use code different storage mechanism you make sorting algorithm faster using quicksort etc use ctypes module interface cbased sorting algorithm eg httptomoyosourceforgejpcgibinlxrsourcelibsortc finally could use linux sort application sort data using subprocess module wish control python sort filea fileb filec likely faster anything python mmap,i trying sort contents several files sometimes moving line one file another i would like use builtin adaptive merge sort attribute list i tried inheriting method list i know needs len getitem setitem yes i want sort inplace fyi here code far helps explain i order changed i call sort if add bubblesort method written python works terribly slow class memwraplist def initself prefix folder chunksizenone fns fn fn oslistdirfolder fnstartswithprefix fnssort selffiles openospathjoinfolderfn r fn fns selfmmaps mmapmmapffileno f selffiles selfsizes mmsize mm selfmmaps chunksize none selfchunksize lenselfmmapsreadline else selfchunksize chunksize def mmfromidxself idx bidx selfchunksizeidx lo ms zipselfmmaps selfsizes hi lo lo bidx hi return bidxlo lo hi def getitemself idx bidx mmap selfmmfromidxidx return mmapbidxbidxselfchunksize def setitemself idx val assert lenval selfchunksize bidx mmap selfmmfromidxidx mmapbidxbidxselfchunksize val def lenself assert sumselfsizesselfchunksize return sumselfsizesselfchunksize def bubblesortself xrange lenself swaptest false j range lenself selfj selfj selfj selfj selfj selfj swap swaptest true swaptest false break selfflush def flushself mm selfmmaps mmflush def closeself selfflush mm selfmmaps mmclose f selffiles fclose,1 use pyinotify httpsgithubcomsebmpyinotify a tutorial httpsgithubcomsebmpyinotifywikitutorial,i python script converts images videos withing directory the problem python script executes manually i need script execute automatically file dropped directory linux platform what would best way set python script watchmonitor directory i looked many options sure one simply sets script execute files dropped directory thank advanced,1 check pyinotify or easier example pyinotify tutorial,i python script converts images videos withing directory the problem python script executes manually i need script execute automatically file dropped directory linux platform what would best way set python script watchmonitor directory i looked many options sure one simply sets script execute files dropped directory thank advanced,1 i solve problem taking short break yeah sudo aptget install pythonboto pythonboto package must install connection work,with access key amp secret key located home directory i run following command line botoecconnection import ecconnection conn ecconnection the console show error i place exact command python script it displays error no module named botoecconnection does anyone know error occur,3 fvgroups x abc p f mymap v px v you said terse right,given list items map predicate function value function code applies value functions items satisfying corresponding predicates myre recompiler az myre recompiler mymap myresearch lambda x x myresearch lambda x x x abc p f mymap v px v print fvgroups break is way express single statement if i pass value returned predicate value function i could x abc print nextfx p f mymap px none can something similar done code i know maybe better leave nested loops i curious whether possible,1 from sqlalchemy docs best way define python property you also need use builtin sqlalchemy float type sqlalchemytypes import float class voteinfobase tablename voteinfo id columninteger primarykeytrue upvotes columninteger downvotes columninteger property def controversialself return floatselfupvotes selfdownvotesfloatabsselfupvotes selfdownvotes def initself upvotes downvotes selfupvotes upvotes selfdownvotes downvotes,i trying convert column float assigning column using columnproperty class voteinfobase tablename voteinfo id columninteger primarykeytrue upvotes columninteger downvotes columninteger controversial columnpropertyfloatupvotes downvotesabsupvotes downvotes def initself upvotes downvotes selfupvotes upvotes selfdownvotes downvotes however i run i get following error typeerror float argument must string number is better way i using columnproperty i want able sort controversial,2 gnu stroke implements changesystemtime trick change ctime file if want gnu stroke httpstrokesourceforgenet,i trying following code osstatpathnamestatstctime ctime however gives following error exceptionstypeerror posixstatresult object support item assignment is anyway modify ctime thanks,1 you misunderstand inheriting list your memwrap getting list interface list inmemory structure like array python objects directly expressed python you add bunch additional instance members override list methods talk members instead normal list instance data never actually call base class implementations note memwrap still instance data inherited list far data concerned remains empty list bunch attributes tacked it happens lot operations builtin types implemented c use clevel data directly rather going python level hooks like getitem so sort inheritancetogettheinterface work python level classes although hack really usually builtin types it certainly supposed subclassing builting types expected make list works slightly differently add defaults extra methods metadata etc make completely different thing shares interface for see abcs collections module i see use list builtin sort without actually list memory mapped files supposed faster tons little oslevel calls sort essentially reading rewriting entirety files anyway i see get go faster read files memory sort write results files your trick using mmaps inplace sort files containing fixedsize chunks data quite clever really using c way actually get work fast python operation inplace file sort pretty obscure operation since impossible unless assume data chunks fixedsize get list sort implementing sort python bound slower good c implementation that said io bound operation compute bound sure actually possible job much faster bubble sort,i trying sort contents several files sometimes moving line one file another i would like use builtin adaptive merge sort attribute list i tried inheriting method list i know needs len getitem setitem yes i want sort inplace fyi here code far helps explain i order changed i call sort if add bubblesort method written python works terribly slow class memwraplist def initself prefix folder chunksizenone fns fn fn oslistdirfolder fnstartswithprefix fnssort selffiles openospathjoinfolderfn r fn fns selfmmaps mmapmmapffileno f selffiles selfsizes mmsize mm selfmmaps chunksize none selfchunksize lenselfmmapsreadline else selfchunksize chunksize def mmfromidxself idx bidx selfchunksizeidx lo ms zipselfmmaps selfsizes hi lo lo bidx hi return bidxlo lo hi def getitemself idx bidx mmap selfmmfromidxidx return mmapbidxbidxselfchunksize def setitemself idx val assert lenval selfchunksize bidx mmap selfmmfromidxidx mmapbidxbidxselfchunksize val def lenself assert sumselfsizesselfchunksize return sumselfsizesselfchunksize def bubblesortself xrange lenself swaptest false j range lenself selfj selfj selfj selfj selfj selfj swap swaptest true swaptest false break selfflush def flushself mm selfmmaps mmflush def closeself selfflush mm selfmmaps mmclose f selffiles fclose,1 if data short simple could preformat entire list simple subprocess like import subprocess data list stuff proc subprocesspopensql c copy table from stdin stdinsubprocesspipe proccommunicatenjoindata if data big preformat like attempt use stdin pipe directly though subprocess module flaky using pipes need read stdoutstderr line data print procstdin line,i using python scripts load data database bulk loader the input loader stdin i unable get correct syntax call unix based bulk loader passing contents python list loaded i reading popen pipe behaving expect the python list contains database records bulkloaded in linux would look similar echo string written db sql c copy table from stdin what would correct way replace echo statement python list used command i sample code process experimenting features popen pipe simple syntax obtaining desired result any help would much appreciated thanks,2 a bit less terse nate itertools import product comb productmymap abc mapped pxf pfx comb groups fvgroups vf mapped v print nextgroups listgroups first match rest,given list items map predicate function value function code applies value functions items satisfying corresponding predicates myre recompiler az myre recompiler mymap myresearch lambda x x myresearch lambda x x x abc p f mymap v px v print fvgroups break is way express single statement if i pass value returned predicate value function i could x abc print nextfx p f mymap px none can something similar done code i know maybe better leave nested loops i curious whether possible,1 when write functionnoneentry calling right away function probably returns none essentially functionnone entry entrybindreturn none what probably looking entrybindreturn lambda e functionentry this generates function note generates function call takes one parameter event e ignores when hit return key generated function called turn call functionentry,just wondering how i bind entry field return key function requires arguments counting event one without lambda classes one function arguments def functionevententryentry widget focused also entry place holder not a widget entry must specified cannot removed entryfocus entrybindreturnfunctionnoneentry when entry binded function bound executes right binded ignores input it lets put characters field i hit return go focus second entry if i remove none one arguments gives error one two required arguments defined matter i put place none still work how i make work without classes anonymous function,2 guard timing code attribute that way outermost decorated method object actually get timed staticmethod def timemethodmethod def wrapperself args kwargs hasattrself beingtimed we timed already run method return methodself args kwargs else not timed yet run timing code selfbeingtimed true remember timed try start timetime result methodself args kwargs finish timetime sysstdoutwrite instancemethod took f sn methodname finish start return result finally done timing reset original state del selfbeingtimed return wrapper timing outermost method slightly different “not timing inherited methods unless overridden” i believe solves problem,my issue i using metaclass wrap certain class methods timer logging purposes for example class mymetatype staticmethod def timemethodmethod def wrapperself args kwargs start timetime result methodself args kwargs finish timetime sysstdoutwrite instancemethod took f sn methodname finish start return result return wrapper def newcls name bases attrs attr init run attr attrs continue attrsattr clstimemethodattrsattr return supermetabuildermodule clsnewcls name bases attrs the problem i wrapper runs every init even though i really want current module i instantiating the goes method want time i dont want timing run inherited methods unless overridden class myclassobject metaclass mymeta def initself pass def runself sysstdoutwrite running return true class myclassmyclass def initself i want timed myclassinitself but pass i need inherited run timed i tried things far i success,2 i sure anything multiple inheritance the trouble subclass myclass instance metaclass means myclass gets created mymetanew methods get processed wrapped timing code effectively need myclassinit somehow returns something different two following circumstances when called directly instantiating myclass directly myclass override needs return timed method when called within subclass definition needs return original untimed method this impossible since myclassinit know called i see three options make metaclass complex it check base classes see already instances metaclass make new copy removes timed wrapper methods present class constructed you want mutate base classes directly affect uses including instantiated directly subclassed classes override different methods a downside really screws instanceof relationships unless construct slight variations base classes creating new subclasses ugh caching variations never construct duplicates ugh completely void natural assumptions two classes share base class may share template two completely independent base classes generated make timing code complex have starttiming stoptiming method starttiming called method already timed increment counter stoptiming decrements counter stops timing counter hits zero be careful timed methods call timed methods need separate counters per method name give metaclasses use decorator methods want timed explicitly way getting undecorated method overriding definitions call this involve couple lines boiler plate per use quite possibly add less lines code either two options,my issue i using metaclass wrap certain class methods timer logging purposes for example class mymetatype staticmethod def timemethodmethod def wrapperself args kwargs start timetime result methodself args kwargs finish timetime sysstdoutwrite instancemethod took f sn methodname finish start return result return wrapper def newcls name bases attrs attr init run attr attrs continue attrsattr clstimemethodattrsattr return supermetabuildermodule clsnewcls name bases attrs the problem i wrapper runs every init even though i really want current module i instantiating the goes method want time i dont want timing run inherited methods unless overridden class myclassobject metaclass mymeta def initself pass def runself sysstdoutwrite running return true class myclassmyclass def initself i want timed myclassinitself but pass i need inherited run timed i tried things far i success,1 look networkx graph object see if homework implement scratch i give hint probably want class nodes class edges edit you really need structure class node class edge class something traversing graph matter search algorithms implemented class node namestr class edge node b node string together init functions one two classes depending loading data,what best way implement tree structure generic binary python my intuition would following skeleton class tnodeself data enter things individual node class tstructureself enter code implementing nodes reference,1 why class nodes list children nodes edit add skeleton class treenodeobject def initself data children selfdata data selfchildren listchildren def addself child selfchildrenappendchild there really much every treenode contains set children leaf nodes children close pure code implementation definition tree leaf node get you could add methods manipulate order children need possibly better considering children list exposed using list methods directly you could add methods like search generic tree without known ordering constraints like binary search tree contents one subtree less contents subtree whole lot you could add generator methods traversal several possible traversal strategies if want leaf nodes data separate class internal nodes leaf nodes internal nodes children leaf nodes data,what best way implement tree structure generic binary python my intuition would following skeleton class tnodeself data enter things individual node class tstructureself enter code implementing nodes reference,1 you split str twocharacter chunks using zip slicing step like pair zipinput input number joinpair i write whole thing like def intstrtochrstrintstr res pair zipintstr intstr number intjoinpair number number resappendchrnumber return joinres print intstrtochrstr it useful logic separated input output use function parts program it also good idea avoid repeating use names like number input builtin,i need convert string numbers string letters form words example input program return stay hungry stay foolish i far def number output input rawinput please enter string numbers number input number character chrintnumber outputappendcharacter else character chrintnumber outputappendcharacter print output i need somehow determine every two numbers equals one letter i program reverse outputs numbers given letter looks like def word output input rawinputplease enter string lowercase characters character input number ordcharacter number number outputappend strnumber else outputappendstrnumber else outputappendstrnumber print joinoutput thanks help,1 if i recall correctly pip knows uninstall packages installed via setuptoolsdistribute raw distutils there setuptools features pip based like record option stores package metadata allows pip uninstal package related files try pip install pathtoprojecta pip uninstall projecta,according another question pip offers facility uninstalling eggs help also indicates i project installed structure local sitepackages folder looks like projecta projectapyegginfo using date version pip uninstall projecta asks following question pathtopythonsitepackagesprojectapyegginfo proceed yn answering remove egginfo directory main projecta directory without saying sort error why pip manage know remove directory the project installed via setuppy file using distutils are special settings i couldshould use file help pip removal process,2 good news google apps free accounts also upload files type three key points use resumable upload append convertfalse resumablecreatemedia link upload chunk size multiple kilobyte to see example python please go download gdata find resumableuploadsamplepy directory samplesdocs,i trying upload backup file server google storage python script the backup file encrypted zip file gpg file it connects successfully fails transferring file following error traceback recent call last file backuppy line module entry gdclientuploadms backupgpg folderoruriuri file usrlocallibpythondistpackagesgdatadocsservicepy line upload folderoruri file usrlocallibpythondistpackagesgdatadocsservicepy line uploadfile convertergdatadocsdocumentlistentryfromstring file usrlocallibpythondistpackagesgdataservicepy line post mediasourcemediasource converterconverter file usrlocallibpythondistpackagesgdataservicepy line postorput reason serverresponsereason body resultbody gdataservicerequesterror status body invalid request uri reason bad request here code import os import sys import gdatadocs import gdatadocsservice import gdatadocsclient gdclient gdatadocsservicedocsservice gdclientclientlogin memyemailcom mypassword uri sconvertfalse gdatadocsclientdoclistfeeduri f open backupzipgpg ms gdatamediasourcefilehandlef contenttype applicationoctetstream contentlengthospathgetsizefname entry gdclientuploadms backupgpg folderoruriuri it possible file big mb i use google docs storage way i hope explicit error message case though i wondering problem saying convertfalse it google apps account i using,1 dddg the part identify regex languages like ruby g flag also applicable python try removing use ddd also i think wanted use output response findall web seeing expected string buffer you also remove line webreadlines so may want something like numbers refindallddd webread,i quite new python i researched much i could i decided i ask question so problem i sure i wrong regex i wanted try refindall i thought i would write small script would find phone numbers webpages here code i right import urllib inurl rawinputinput url web urlliburlopeninurl webreadlines numbers refindalldddg web itm numbers print itm not sure happening i keep getting error expected string buffer line numbers refindall web thanks advance,2 make single iterator input string call zip like iterdata pairs zipit gives next pass map join function make integer strings map join zipitit now pass map convert ints mapint map join zipitit now pass map lambda perform decoding logic maplambda n chrn n else chrn mapint map join zipitit h u n g r f l h and lastly pass join joinmaplambda n chrn n else chrn mapint map join zipitit stay hungry stay foolish what could simpler,i need convert string numbers string letters form words example input program return stay hungry stay foolish i far def number output input rawinput please enter string numbers number input number character chrintnumber outputappendcharacter else character chrintnumber outputappendcharacter print output i need somehow determine every two numbers equals one letter i program reverse outputs numbers given letter looks like def word output input rawinputplease enter string lowercase characters character input number ordcharacter number number outputappend strnumber else outputappendstrnumber else outputappendstrnumber print joinoutput thanks help,2 since entire text break one line initially one use single short substitution command amprg,so i several large datasets i need make readable currently i go move rd value insert newline i tried several things vim get work none seem return value i looking here data what i need make look like instead i used selection try get move rd value duplicated entire thing moved entire line ssrampg i also tried removing make work work either so way i capture rd value insert carriage return newline make work thanks edit i apologize miscommunicating part problem the data top one line several lines it looks like e,1 the python profiler lives communitysupported ubuntu “multiverse” install python profiler simply need uncomment multiverse lines apt sources file if trying automate server install — like i — commands work sudo sed natty multiverses etcaptsourceslist sudo aptget update sudo aptget install pythonprofiler good luck,i aws ec instances stuff running python profiler broken traceback recent call last file testpy line module cprofileruntest file usrlibpythoncprofilepy line run result profprintstatssort file usrlibpythoncprofilepy line printstats import pstats importerror no module named pstats i rather reinstall python stuff running systems i want addfix profiler i found advice work example httpwwwcherrypyorgwikiprofilingondebian no matter i try i get sudo aptget install pythonprofiler reading package lists done building dependency tree reading state information done package pythonprofiler available referred another package this may mean package missing obsoleted available another source e package pythonprofiler installation candidate any help to reiterate i tried adding various lines sourceslist file nothing worked please search post link unless solved problem successfully thanks,1 the expression b shorthand b b numbers strings tuples lists must type the comma x means tuple single element x if comma absent x parenthesis,what mean like selfsomething somethin what comma means,3 in python everything object containing attributes that includes classes the whole objectoriented thing classes define methods instances execute methods varying data perinstance protocol looking attributes series objects class aobject def fooself selffoo foo def barself selfbar bar this creates class object bound name a that object contains two attributes foo bar bound method objects a this creates object bound name instance a it contains attributes yet but fact instance a means lookup protocol ask afoo first look attribute fails look attribute a this instances a access set methods in python also create attributes almost object time all requires someobjectsomeattribute somevalue until attribute exist so actually calling afoo abar foo bar attributes exist neither attributes program may may one day add object adict empty point called if expect default values foo bar exist every object need say setting values init method,code goes first class aobject def fooself selffoo foo def barself selfbar bar clsdict dictadict empty a adict dictadict empty,3 addition assignment one sometimes referred iadd inplace add it x add assign result b b b thing print prints print b prints you also operations style amp bitwise bitwise bitwise xor mod exponent something tuple something without comma using parenthesis grouping kind like thing b in order differentiate onemember tuple grouping syntactically python uses comma,what mean like selfsomething somethin what comma means,1 i added modules import subprocesssignalsys class i added def init self parent title selfclickerloop false selfpid def openclickerselfevent selfpidsubprocesspopensysexecutable py i import sys add sysexecutable popen otherwise got error everytime tried open another python program def handlehotkeyself evt selfclickerloop selfclickerloop false printselfclickerloop selfpidterminate else selfclickerloop true printselfclickerloop selfopenclickerself i kill called loop process selfpidterminate otherwise opens seperate py loop file the seperate py file contains code import mouse time import sleep true mouseclick sleep what basically call upon separate python file subprocess module hotkey pressed kills process hotkey pressed thanks help,i trying create hotkey togglef turn loop pressed turn loop pressed the loop mouse click every seconds toggled i found recipe hot keys wxpython site i get loop turn figure way get turn i tried created separate key turn without success the mouse module simulates left mouse click here current code import wx wincon mouse time import sleep class frameclasswxframe def initself parent title superframeclass selfinitparent titletitle size selfcentre selfshow selfreghotkey selfbindwxevthotkey selfhandlehotkey idselfhotkeyid selfreghotkey selfbindwxevthotkey selfhandlehotkey idselfhotkeyid def reghotkeyself this function registers hotkey altf id selfhotkeyid selfregisterhotkeyselfhotkeyidwinconmodalt winconvkfthe key watch def handlehotkeyself evt looptrue print clicks looptrue simulated left mouse click mouseclick sleep xselfreghotkey printx xfalse print did work break else pass second keypress hotkey def reghotkeyself selfhotkeyid selfregisterhotkeyselfhotkeyidwinconmodalt winconvkf def handlehotkeyself evt return false loopfalse printloop name main showytitleappwxapp gotta one every wxpython program apparently frameclassnone title rapid clicks showytitleappmainloop infinite manloop catching program stuff,1 the alias home directory shellism something shell something use python open command pax cd pax ls qqs qqs pax python python r apr gcc linux type help copyright credits license information openqqs traceback recent call last file stdin line module ioerror errno no file directory qqs openqqs open file qqs mode r xbe,i trying open file exist line x opentweetlyauth w that open exists wipe content begin write if exist create itright it i get error ioerror errno no file directory tweetlyauth ideas,2 python operator assign value name the language also support many operators like operations defined special methods objects although math sign add things customized whatever want sometimes want make operation store using name for situations inplace operators normal operators use plus sign for immutable objects numbers strings tuples inplace changes immutable so inplace methods exactly thing normal method followed assignment for mutable objects difference much clear inplace add b b add assign b b b see the object transformed inplace add lists case new object created for question comma tuple separator just number inside parenthesis a tuple one element,what mean like selfsomething somethin what comma means,1 while true python open support expansion directly use conjunction python standard library function ospathexpanduser import os ospathexpanduserqqs usersnadqqs openospathexpanduserqqs w open file usersnadqqs mode w xef,i trying open file exist line x opentweetlyauth w that open exists wipe content begin write if exist create itright it i get error ioerror errno no file directory tweetlyauth ideas,2 ans when giving syntax exactly return check type syntax like when write in thingamountdesc out sqlalchemysqlexpressionunaryexpression object xad it create one object type expressionunaryexpression so expression give sqlalchemy want unary operation now print in thingamountdesc in print thingamount desc so query run converted thingamount desc so create expression call thing create structure query ans when creating query create object needed for filter order need expression pass directly orderby filter create object internally so use way ans in thingamount out sqlalchemysqlexpressionbinaryexpression object xadbd this also expression give expression filterby you get idea expression sqlalchemy site,so i table i want users able view table whichever order like here example class thingbase tablename thing id columninteger primarykeytrue amount columninteger date columndatetime defaultdatetimenow def initself amount selfamount amount so i like make following query sort amount orderby thingamountdesc elif sort date orderby thingdatedesc things dbsessionquerythingorderbyorderbyall main questions when i set orderby statement i actually calling anything statement set am i correctly efficiently can i similarly filters filterby thingamount things dbsessionquerythingfilterbyfilterbyall thanks,2 what seeing manual relational operators including precedence boolean still one level lower precedence relational comparison happens first,i trying understand python better lack parentheses bit confusing reason b c evaluated is b c b c according reference manual lower higher precedence i assuming operators higher precedence evaluate lower right i feel like i need someone break sock puppets right according python reference manual comparisons different precedence then python reference manual comparisons precedence if mistaken b c varying results depending version python would someone please share statement evaluated i sticking b c,3 here good tutorial httpwwwsmashingmagazinecomdesignandbuildanemailnewsletterwithoutlosingyourmind hope helps,i attempting send html email python i find email browsersnot sure thats correct term change htmlcss especially concerning images such i following css myclass backgroundimage urlhttpmywebsitecomimagesimgpng in microsoft outlook removes line css myclass in gmail browser layout html shownits columns gmail shows divs i need send email invitation event and need done programmatically python do know easiest way send html email contains imagespreferably references images website amp attached email whats way least headaches any open source programs i use,1 i dont see you integrate django amp serve requests modeling categories graph database neoj shop categories example neoj django models django amp neoj domain modeling kicks ass seamless django amp neoj integration hope helps i able integrate almost entire imdb neoj amp serve django,i planning implement recommendation engine details given python preferred choice along neoj database can anyone please point integration neoj web framework like django done is possible integrate like php integrates mysql thanks advance,3 you may still need sql database like sqlite plan use django features like authentication but want build recommendation engine use django nodatabase and build backend python using neoj without worrying first django could integrates priori seamlessly links neoj python installation httpdocsneojorgchunkedsnapshotpythonembeddedhtml usage httpdocsneojorgchunkedsnapshottutorialspythonembeddedhtml,i planning implement recommendation engine details given python preferred choice along neoj database can anyone please point integration neoj web framework like django done is possible integrate like php integrates mysql thanks advance,2 check neoj python library httpsgithubcomversaeneojrestclient it uses rest api neoj if planning use rest api may consider jython implementation directly connect database i heard hackers implementing neoj backend django but i think mature enough develop web site,i planning implement recommendation engine details given python preferred choice along neoj database can anyone please point integration neoj web framework like django done is possible integrate like php integrates mysql thanks advance,3 for instance variable methods mandatory use self anytime,are supposed use self referencing member function python within module more generally i wondering required use self methods variables well,1 use self refer instance variables methods instance methods also put self first parameter definition instance methods an example class myclassobject myvar none def mymethodself myvar selfmyvar myvar selfmyothermethod def myothermethodself something,are supposed use self referencing member function python within module more generally i wondering required use self methods variables well,3 the reversed builtin function handy item reversedsequence the documentation reversed explains limitations for cases i walk sequence reverse along index eg inplace modifications changing sequence length i function defined codeutil module import itertools def reversedenumeratesequence return itertoolsizip reversedxrangelensequence reversedsequence this one avoids creating copy sequence obviously reversed limitations still apply,so i start lencollection end collection edit sorry i forgot mention i also want able access loop index,3 use forward slashes r strings begin default snip name ddatabasedb name r ddatabasedb snip additionally need ensure entire directory sqlite file writable case d sqlite needs write journal file next database file,i want use sqlite development django settings default engine djangodbbackendssqlite add postgresqlpsycopg postgresql mysql sqlite oracle name ddatabasedb or path database file using sqlite user not used sqlite password not used sqlite host set empty string localhost not used sqlite port set empty string default not used sqlite try syncdb get following traceback recent call last file managepy line module executemanagersettings file cpythonlibsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file cpythonlibsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file cpythonlibsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file cpythonlibsitepackagesdjangocoremanagementbasepy line execute output selfhandleargs options file cpythonlibsitepackagesdjangocoremanagementbasepy line handle return selfhandlenoargsoptions file cpythonlibsitepackagesdjangocoremanagementcommandssyncdbpy line handlenoargs cursor connectioncursor file cpythonlibsitepackagesdjangodbbackendsinitpy line cursor cursor selfmakedebugcursorselfcursor file cpythonlibsitepackagesdjangodbbackendssqlitebasepy line cursor selfconnection databaseconnectkwargs sqliteoperationalerror unable open database file any idea going notice i tried change db name location many times work,1 just redis stores things inmemory mean meant cache i seen people using persistent store data that used cache hint useful highperformance storage if redis system goes though might loose data written back onto disk there ways mitigate dangers eg hotstandby replica if data missioncritical like run bank shop redis might best pick but write hightraffic game persistent live data socialinteraction stuff manage probability dataloss quite acceptable redis might worth look anyway point remains yes redis used database,i heard rediscache exactly work is used layer django rdbms caching rdbms queries somehow or supposed used directly database which i doubt since github page cover login details setup tells set config property,3 i think looking something like following perl script beginexample endexample print next sg sg sg sg print run cat testfile perl scriptnamepl for nonsilly version python note perl right tool job tchrist python version bad joke fixed future import printfunction import fileinput import import sys systracebacklimit for desperate hide tracebacks oneoff scripts example line fileinputinput example rematchr beginexample line example elif example rematchr endexample line example else line sub r r line reverbose line sub r r line reverbose line sub r r line reverbose line sub r r line reverbose line sub r r line reverbose printline end,i looking text processing bunch org files i would like change following file descriptionlink linkmy description text text heading heading italics italics bold bold yes is markdown syntax orgmode syntax i am aware pandoc the caveat i want changes except occur following block beginexample want changes take place block endexample hence i use pandoc i like process files according requirements using kind unix script awk sed python perl bash etc once i working script i modify learn thanks help,2 adding answer oskarbi explicit you use self defining instance method it passed automatically first parameter call method instance instance method called referencing class instance attribute inside instance method use want call method access name variable instance method called inside method you use self you call instance method normally using oskarbi example instance myclass call myclassmymethod instancemymethodsomevar instancemymethodself somevar you reference class attribute outside instance method inside class definition you inside staticmethod these ts examples use self the dos use,are supposed use self referencing member function python within module more generally i wondering required use self methods variables well,3 this i inspired solution httpblogmediaonfirecomp djangotest import testcase djangoconf import settings djangoutilsimportlib import importmodule class sessiontestcasetestcase def setupself httpcodedjangoprojectcomticket settingssessionengine djangocontribsessionsbackendsfile engine importmodulesettingssessionengine store enginesessionstore storesave selfsession store selfclientcookiessettingssessioncookiename storesessionkey after may create tests class blahtestcasesessiontestcase def testblahwithsessionself session selfsession session operator jimmy sessionsave etc,my site allows individuals contribute content absence logged creating user based current sessionkey i would like setup test view seems possible modify requestsession i like djangocontribsessionsmodels import session session sexpiredate ssessionkey mysessionkey ssave selfclientsession response selfclientget myview but i get error attributeerror set attribute thoughts modify client session making get requests i seen seem work,3 this really late well i using script get mailing list subscribers like says script uses web interface get members quite handy since i access mailman command line tools shared hosting as right give members probably extend suit needs,i trying migrate legacy mailing list new web forum software wondering mailman export option api get lists owners members membership types,2 an example f type cont cont unit cont let rec printfn cont fun b b n printfn bd n cont c c printfn c cont let rec run cont f let f f run f run cont regarding question hard implement state machines using functions statically typed languages that type friends little bit weird function returns function returns function returns function if i remove cont example f compiler complains says expecting given unit the resulting type would infinite unifying unit another answer shows solution ocaml whose type inference strong enough remove need declaring cont shows static typing blame rather lack powerful type inference many statically typed languages i know f i would guess maybe would make type inference algorithm complicated slower powerful could manage infer type incorrectly typed expressions failing later point giving error messages hard understand note python example gave really safe in example b represents family states parameterized integer in untyped language easy make mistake return b b instead correct lambda miss mistake code executed,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,1 ok datatypes xsd defined soaplib integer defined soaplib seen wsdl file integer net framework used powerbuilder failed understand int ok netpowerbuilder soaplib defined soaplib thus i moved soaplib rpclib those libs close one fork,i problem soaplib i following function provided web service soapinteger integer returnsinteger def testself n n return n n the corresponding declaration datatypes generated wsdl file xscomplextype nametest xssequence xselement namen typexsinteger minoccurs nillabletrue xselement namen typexsinteger minoccurs nillabletrue xssequence xscomplextype xscomplextype nametestresponse xssequence xselement nametestresult typexsinteger minoccurs nillabletrue xssequence xscomplextype when i use ide visual studio powerbuilder generate code wsdl file whatever ide generates two classes test testresponse whose attributes strings does anyone know i tweak python declaration i avoid complextype obtain real integer datatype client side,1 fcntl builtin module it written python c unfortunately ported java according bug report unlikely ever to answer question cpython source the problem fcntl unixspecific program portable start java pretty strictly platformindependent jython developers imply bug report lowlevel things possible you search particular functions need — might better chance getting work whole module – i recommend looking way around problem rather trying get fcntl work java i hope find alternative solution,i unix i find location fcntl module i using jython web development existing program i modifying needs module can give way import code able use module thanks advance,1 if i understand problem correctly maximizing function fi integers set you use combination iteration vectorized indexing import numpy np import itertools def cartesianchunkedn nitems chunkdim n chunkdim p n chunkdim q chunkdim outer itertoolsproductrangenitems n chunkdim else p q n def outeriter yield outer outeriter chunk npzerosnitemsq n dtypeint chunkp npindicesnprepeatnitems qreshapeq t seq outer chunkp seq yield chunk def computeenergyindices baseenergies nparray return baseenergiesindicessumaxis maxenergy maxconfig none try e combinations chunks chunk cartesianchunkedn nitems chunkdim energies computeenergychunk j npargmaxenergies energiesj maxenergy maxenergy energiesj maxconfig chunkjcopy copy chunk modified print maxenergy print maxconfig,i function calcdg array corresponding short dna sequence bases gives binding energy sequence actually array lookup nndg array binding energies adjacent pairs bases thus binding energies calculated nndgss using agct way denoting sequences numerically means arrays many sequences calculated quickly numpy i need find length l every sequence fits template results binding energy value certain range this easy iterators iterate every possible array input calculate binding energy record arrays range this however far slow implemented python length possible values element possible arrays etc etc i could use weave method implementing c i prefer find arraybased solution simple fast for example every element possible values eg generating array every possible length l d array values done lambda x indicesrepeatlreshapeltranspose i calcdg result use resultresults desired range get arrays i want final result this much faster using python iterators likely almost fast faster using c iterators unfortunately work arbitrary templates longer sequences run memory store every possible array memory calculating values is way without resorting c,1 there nothing special name self it name preferred convention pythonistas indicate parameter expected contain the python runtime pass self value call instance method instance whether deliberately provide this usually result easily diagnosedunderstood error since function get called wrong number parameters use args lead rather strange type errors the parameter passed implicitly call instance method instance it contains instance upon call method so mention self function call noted make sense self scope general self keyword special name anything b already indicated instance use writing myinstance you course explicitly call instance method accessing class in case need pass instance explicitly first parameter you generally speaking want and especially want write code considers possibility first parameter something else explicitly passed way this akin checking null c could possibly mean anything calling code wrong morally legally at least python problems undefined behaviour still morally wrong within instance method since self parameter assigned instance value write selfwhatever access attributes instance unlike implicit style languages attribute names implicitly scope there use cases self since special name one specific purpose naming convention addresses if needed access variable really attribute another module would use module name if wanted access one current module prefix needed really possible matter well could explicitly look dict returned globals please,are supposed use self referencing member function python within module more generally i wondering required use self methods variables well,1 this problem likely well suited json pickle serialization technique however want preserve input file consisting keyvalue pairs could following file contents delimiter choosing case could etc twentydollar tendollar fivedollar dollar quarter dime nickel penny then python split line delimiter build dict keyvalue pairs ensuring value int open inputtxt r inp usddictkey intvalue key value linesplit line inp,basically i want create text file well keyvalue pairs i input python create dictionary then i going call key use resulting value equations here i want dictionary look like inputted python usd twentydollar tendollar fivedollar dollar quarter dime nickel penny what i issue figuring a format text file b properly take readout file turn dictionary twentydollars change usd twentydollar change change usd twentydollar tendollars change usd tendollar change change usd tendollar sample calculations show type formatting i need key,1 this looks like bug ndb can file one issue tracker,suppose ndbversion amp model key none class testmodelmodel k modelkeyproperty value modelintegerproperty count testquerytestk nonecount error count testquerytestk nonecount error also only filtering key none throws error file applicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebappwebapppy line call handlergetgroups file usersreiotdocumentsworksndbtestmainpy line get count testquerytestk nonecount error file usersreiotdocumentsworksndbtestndbmodelpy line eq return selfcomparison value file usersreiotdocumentsworksndbtestndbmodelpy line comparison return filternodeselfname op selfdatastoretypevalue file usersreiotdocumentsworksndbtestndbmodelpy line datastoretype return datastoretypeskeyvalueurlsafe attributeerror nonetype object attribute urlsafe how i query keyproperty none,1 you need define hash method class return hashcode based value in words need make class hashable class thingobject def initself value selfvalue value def eqself return selfvalue othervalue def reprself return strselfvalue def hashself return hashselfvalue thing b thing set sadda saddb print,i want use sets classes i made i want sets restrict multiplicity objects class however i problem consider toy example class thingobject def initself value selfvalue value def eqself return selfvalue othervalue def reprself return strselfvalue thing b thing set sadda saddb print the output code set i assumed set would use eq determine whether object included perhaps uses is easy workaround output would set,3 to convert plain numpy array structured array use view import numpy np filename unstructuredfiletxt nfields names r g b openfilename r f arr nparrayfreadsplitdtypenpfloat arr arrreshapenfields arrviewdtypezipnames float lennamescopy,i read sequence numbers nparrayfreadsplitdtypenpfloat then i convert d array using npreshape after convert arr record array i tried something like following filename unstructuredfiletxt nfields names r g b openfilename r f arr nparrayfreadsplitdtypenpfloat arr arrreshapenfields nparrayarrdtypezipnames float lengthnames says typeerror expected readable buffer object any suggestions edit the main thing i want name columns instead nparrayarrdtypezipnames float lengthnames if i use npcorerecordsfromrecordsarrreshapenfieldsnames joinnames i use r outdtypenames none what going edit the unstructured file looks like some text more text e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e e,3 if python ≥ update different values dictb i would assume dicta updated question specifies otherwise k dictaviewkeys amp dictbviewkeys dictak dictbk dictbk dictak add missing keys dicta dictaupdate kdictbk k dictbviewkeys dictaviewkeys,suppose i two python dictionaries dicta dictb i need find keys present dictb dicta what fastest way go should i convert dictionary keys set go interested knowing thoughts thanks responses apologies stating question properly my scenario like i dicta dictb may keys missing compared dictb else value keys might different set dicta key value problem dictionary standard values dict dict say dicta key key b key key cc key dd key key dictb key key newb key key cc key newdd key ee so key value reset new value key added inside dict the key value fixed format it simple value dict dict dict,1 using regexes purpose wrong approach since using python really awesome library available extract parts html documents beautifulsoup,i need find content forms html source file i searching found good method problem prints first found i loop output form contents first one line bla bla blaformform form textformform form text matchobj research formform line res print matchobjgroup output form i need output every form content found first one,1 do use regular expressions parse html but ever need find regexp matches string use findall function line bla bla blaformform form textformform form text matches refindall formform line redotall printmatches,i need find content forms html source file i searching found good method problem prints first found i loop output form contents first one line bla bla blaformform form textformform form text matchobj research formform line res print matchobjgroup output form i need output every form content found first one,3 you need numerical optimisation procedure not sure anything implemented python numpy scipy friends look things like neldermead algorithm bfgs if else fails use rpy call r function optim these functions work searching function space trying work maximum imagine trying find top hill fog you might try always heading steepest way or could send friends radios gps units bit surveying either method could lead false summit often need times starting different points otherwise may think south summit highest massive north summit overshadowing,i need code maximum likelihood estimator estimate mean variance toy data i vector samples created numpyrandomrandn the data zero mean unit variance gaussian distribution i checked wikipedia extra sources i little bit confused since i statistics background is pseudo code maximum likelihood estimator i get intuition mle i cannot figure start coding wiki says taking argmax loglikelihood what i understand i need calculate loglikelihood using different parameters i take parameters gave maximum probability what i get i find parameters first place if i randomly try different mean amp variance get high probability i stop trying,2 the displayed idle part python interpreter output i think try listening key events restoring prompt needed see httpdocspythonorglibrarytkinterhtmlbindingsandevents httpeffbotorgtkinterbooktkintereventsandbindingshtm,code tkinter import class mainobject def initself selfconsole textroot relief groove cursor arrow spacing selfconsoleinsertinsert selfconsolefocusset selfscroll scrollbarroot cursor arrow commandselfconsoleyview selfconsoleconfigureyscrollcommandselfscrollset selfscrollpackfill side right selfconsolepackexpandtrue fill root tk rootgeometry sxsss rootoptionadd font courier bold rootresizable app main rootmainloop way make become unremovablelike idle example thanks advance,1 httplib pure python module look code precise information badstatusline raised status line can’t parsed valid http status line no solution,i using suds when creating suds client i randomly get error httplibpy readstatus line class httplibbadstatusline here code used create client imp import httpwwwworgxmlschema impfilteradd httptempuriorgencodedtypes impfilteradd httptempuriorg selfdoctor importdoctorimp selfclient clientselfurldoctorselfdoctor what error mean i fix thanks,1 instead using research use refindall return matches list or could also use refinditer like use return iterator object use iterate found matches line bla bla blaformform form textformform form text match refinditer formform line res print matchgroup,i need find content forms html source file i searching found good method problem prints first found i loop output form contents first one line bla bla blaformform form textformform form text matchobj research formform line res print matchobjgroup output form i need output every form content found first one,3 the unicodedecodeerror thing probably happens code posted anyway try selffilename pyqtqtguiqfiledialoggetopenfilenamedecode utf by way getopenfilename static method qfiledialog means create instance call,the code like dlg pyqtqtguiqfiledialogself selffilename dlggetopenfilename when dialog pops i click file chinese characters path then i get unicodedecodeerror i tried toutf function still get nowhere unicode thing always difficult understand anybody helps,1 perl solution this result simplifying changes i suggested jkerian’s script use flipflop operator p i’ve also fixed regexes use correct rhs altered delimiters avoid lts “leaning toothpick syndrome” added x improve readability there logic error dealing bold italics i’ve fixed i added comments showing transform case corresponding original problem description aligned rhs transforms make easier read usrbinperl p p option makes passthrough filter omit protected region next beginexample endexample text ⇒ text gx desclink ⇒ linkdesc gx heading ⇒ heading nb use x would use ugly italics ⇒ italics gx bold ⇒ bold gx see easy just simple lines eminently readable code perl it’s easy perl perl specifically designed make writing sort filter supereasy python python separate design goals although could certainly rewrite python wouldn’t worth bother python simply isn’t designed sort thing python’s missing p “makemeafilter” flag implicit loop implicit print python missing implicit accumulator variable python missing builtin regexes python missing operator and python missing stateful flipflop operator all contribute making perl solution much much much easier read write maintain python solution however get idea always holds it doesn’t in areas come problems python comes ahead areas but it’s filter thing focused specialty area perl isn’t python the python solution would consequently much longer noisier harder read — therefore harder maintain — easy perl version perl designed make easy things easy one target application areas try rewriting python notice nasty sure it’s possible worth hassle maintenance nightmare python version usrbinenv python future import printfunction import sys import sysversioninfo sysstderrwrites legacy python detected please upgrade vn sysargv sysexit lensysargv sysargvappenddevstdin fliprx recompiler beginexample floprx recompiler endexample eg text text lhsbackticks recompiler reverbose rhsbackticks r eg desclink linkdesc lhsdesclink recompiler reverbose rhsdesclink r eg heading heading lhsheader recompiler rhsheader r eg italics italics lhsitalics recompiler reverbose rhsitalics r bold bold lhsbold recompiler reverbose rhsbold r errcnt flipflop flip filename sysargv try filehandle openfilename r except ioerror oops errcnt errcnt sysstderrwrites open reading sn sysargv filename oops else try line filehandle newflipflop none flipflop flip fliprxsearchline newflipflop flop elif flipflop flop floprxsearchline newflipflop flip else raise flipflopsnafu flipflop flop line lhsbackticks sub rhsbackticks line line lhsdesclink sub rhsdesclink line line lhsheader sub rhsheader line line lhsitalics sub rhsitalics line line lhsbold sub rhsbold line printline end newflipflop none flipflop newflipflop except ioerror oops errcnt errcnt sysstderrwrites read sn sysargv filename oops finally try filehandleclose except ioerror oops errcnt errcnt sysstderrwrites close sn sysargv filename oops errcnt sysexit else sysexit summary it’s important use right tool right job for task tool perl took lines there things don’t try telling python it’s like back assembly language many interrupt stacks python lines clearly cut kind work painful complexity noisey unreadable code shows exactly bug rate per line code matter language choice writing n lines code n lines code choice,i looking text processing bunch org files i would like change following file descriptionlink linkmy description text text heading heading italics italics bold bold yes is markdown syntax orgmode syntax i am aware pandoc the caveat i want changes except occur following block beginexample want changes take place block endexample hence i use pandoc i like process files according requirements using kind unix script awk sed python perl bash etc once i working script i modify learn thanks help,3 you need use pipes subprocess module see httpdocspythonorglibrarysubprocesshtmlreplacingshellpipeline,i got program written python starts several processes now i want information errors warnings prints etc started processes displayed main process console how i,1 given following variables use dictlist variable names offset a abc your example code written dictziprangeoffset offsetlena a using import itertools dictitizipitcountoffset a python newer dictenumeratea offset in cases b c comparing speeds first slowest significant difference latter two,assuming list a strings offset x aabc x int lena int i need serialize return json j nlena jxnan i currently use dict assigning it feels like something efficient instead going entire list answer needs o contradiction thanks dict ix enumeratelist dictioffsetx,1 mysqldb uses string interpolation join parameterized sql arguments passing query server string clearly way go converting array tuples also tuples strings in contrast oursql sends sql queries mysql server separate data since arrays using zip columnstack would require python numpy allocate memory combined object list tuples d numpy array to avoid use itertoolsizip import itertools xnprandomrandome ynprandomrandome connection oursqlconnect hostconfighost userconfiguser passwdconfigpass db test connectioncursor cursor sql insert into foo xy values cursorexecutemanysqlitizipxy printcursorlastrowid ps previously i suggested using oursqlbinaryiterwrapper i able get solution work however perhaps bug pps i tried timing oursql code versus similar code using mysqldb however timing possible mysqldb since raised mysqlexceptionsoperationalerror got packet bigger maxallowedpacket bytes cursorecutemany,it seems like time takes convert array tuple scales linearly length array is way efficient i need insert arrays e elements mysql database mysqldb seems accept tuples lists input insertmany,2 have tried nltk see so question information there also web service xerox claims want,is tool provides language recognition functionality like i input sentence english suggest string may english i think i need one following stuff python language recognition library web service provides functionality anyone help,1 it seems using strptime windows platform uses python implementation strptimepy lib directory c one it might quicker process string datetime import datetime import timeit def f datetimestrptime ymd n print f timeittimeitf numbernn returns system whereas datetime import date import timeit def f parts int x x split return date parts parts parts n print f timeittimeitf numbernn returns,i log parsing code needs turn timestamp datetime object i using datetimestrptime function using lot cputime according cprofile cumtime column the timestamps format nov the current function newentry time datetimestrptime parsedline day parsedline month parsedline year parsedline hour parsedline minute parsedline second dbyhms anyone know i might optimize,2 check natural language toolkit how check word english word python,is tool provides language recognition functionality like i input sentence english suggest string may english i think i need one following stuff python language recognition library web service provides functionality anyone help,1 if really want construct dict list use hack depends implementation details json module class offsetdictdict def initself lst offset selflst lst selfoffset offset def nonzeroself return boolselflst def iteritemsself return enumerateselflst selfoffset a b c offsetdicta print jsondumpsd the code prints b c because constructing offsetdict instance iterate list part would o creating json output inevitably remains on course the code relies fact json treats every subclass dict dict calls nonzero iteritems methods don expect code robust a robust version would need reimplement dict methods in python x overwrite items instead iteritems,assuming list a strings offset x aabc x int lena int i need serialize return json j nlena jxnan i currently use dict assigning it feels like something efficient instead going entire list answer needs o contradiction thanks dict ix enumeratelist dictioffsetx,1 i used guesslanguage module pretty extensively it detects languages works really well long pieces text english good other languages i sure if want process short sentences time tweets pretty bad designed detection full articles my company social media analytics currently looking replacement package well exploring nltk option,is tool provides language recognition functionality like i input sentence english suggest string may english i think i need one following stuff python language recognition library web service provides functionality anyone help,1 try find python windows registry changes path python after try reinstall ipython,if i rename python interpreter cpythonpythonexe cpythonpythonexe run complain but i try run cpythonscriptsipythonexe fail start python interpreter different filename my question i configure ipython ms windows start python interpreter different filename pythonexe,1 packages if committed neural networks i good luck svm kmeans clustering might also helpful both provided milk it also stepwise discriminant analysis feature selection definitely useful trying find similar documents topic god help choose route root framework powerful machine learning package called tmva provides large number classification methods including svm nn boosted decision trees also possibly good option i used pyroot provides python bindings root functionality to fair i first used root i c knowledge head conceptually might actually amazing root huge number data processing tools nb i also written fairly accurate document language identifier using chisquared feature selection cosine matching obviously problem harder consider might need hefty tools storage vs processing you mention question articles would fetched based tags passed neural network ranking just another nb one thing know machine learning processes like training evaluating tend take you probably consider ranking documents tag assuming know tags storing results for machine learning generally much better use storage processing now specific case you say many tags let assume roundness if store results ranking doc tag gives million floats store that lot data calculating take retrieving fast if instead recalculate ranking document demand passes one tag depending kind operations size docs could take seconds minutes if process simple enough wait code several evaluations demand without getting bored go time process making design decisions writing code want use good luck,i planning implementing document ranker uses neural networks how one rate document taking consideration ratings similar articles any good python libraries can anyone recommend good book ai python code edit i planning make recommendation engine would make recommendations similar users well using data clustered using tags user would given chance vote articles there hundred thousand articles documents would clustered based tags given keyword articles would fetched based tags passed neural network ranking,3 if i remember correctly nose loads test based names functions whose name begins test in snippet posted copy name attribute function wrapper function name function returned wraptest nose decides test an easy way copy attributes function new one used functoolswraps,i relatively complex integration tests python code i simplified greatly custom decorator i really happy result here simple example decorator looks like def specialtestfn def wraptestself important stuff pass return wraptest here test may look like class testspecialstuffunittesttestcase specialtest def testsomethingspecialself pass this works great executed pycharm test runner without problem however i run test commandline using nose skips test specialtest decorator i tried name decorator testspecial matches default rules fn parameter get passed how i get nose execute test methods treat decorator intended solution thanks madjar i got working restructuring code look like using functoolswraps changing name wrapper def specialtestfn wrapsfn def testwrapperselfargskwargs important stuff pass return testwrapper class testspecialstuffunittesttestcase specialtest def testsomethingspecialself pass,3 in case i would use python since often concise java plus csv files really easy handle python without installing something i know java task it would roughly based example official documentation import csv open somecsv r f reader csvreaderf rownumber row reader gopenanyfilestrrownumbertxtw gwriterow rownumber rownumber gclose task f opencsvfilecsvw dirlistoslistdirpath fname dirlist fname txt g openfname line g fwriteline gclose fclose,task read row one csv file one seprate txt file task reverse one folder read text txt file put row single csv so read txt files one csv file how would would java python good get task done quickly update for java already quite useful libraries use example opencsv javacsv but better look wikipedia csv knowledge csv and post tells possibilities java note due simplicity question one preassume homework i hereby declare more background i working experiments machine learning setting large scale test set i need crawl scrape file type transfer basic utility experiment building lot things suddenly want learn python due recent discoveries get feeling python concise java many parsing file handling situations hence got question i want save time getting gist without stating notsorelated background and questions second question java vs python because i run lines code python using csv library sure i asked know use python that reasons i got question thanks,1 currently possible although xmpp ability query time zone google app engine allow send raw stanzas there issue acknowledged mode bet seeing anytime soon,context i jabber bot implemented python google appengine xmpp library the bot forwards posts social network i like post timestamps client timezone question is possible query client local timezone bot respective adjustments again bot based appengine xmpp python library alternatives of course ask clients specify timezone explicitly setup store value somewhere use later but i prefer bot extracts information automatically without human involvement respective documentation httpcodegooglecomappenginedocspythonxmpp,2 one approach class springsemestereventmanagermodelsmanager def getquerysetself return superspringsemestereventmanager selfgetqueryset filterisspringsemestertrue class fallsemestereventmanagermodelsmanager def getquerysetself return superfallsemestereventmanager selfgetqueryset filterisfallsemestertrue class eventmodelsmodel eventdate modelsdatefield property def isspringsemesterself month selfeventdatemonth return true month month else false property def isfallsemesterself month selfeventdatemonth return true month month else false objects modelsmanager springsemester springsemestereventmanager fallsemester fallsemestereventmanager then view fallevents eventfallsemesterall hope helps,i django model called event date field date event class eventmodelsmodel eventdate modelsdatefield i like able set method model tell whether event spring semester event fall semester event the spring semester would defined january may fall august december my goal able filter either semester generic list events year how would i go writing method defining semester,1 from write little need using something specific csv files in particular task pure data io operation text files in python instance il enumerateopenthefile f open newfileicsv w fwritel fclose for task guarantee file structure number fields per row pure data io operation glob files files glob filecsv target open combinedcsv w f files targetwriteopenfread targetwritenewlinespeparatorforyourplatform targetclose whether java python depends availability target system personal preference,task read row one csv file one seprate txt file task reverse one folder read text txt file put row single csv so read txt files one csv file how would would java python good get task done quickly update for java already quite useful libraries use example opencsv javacsv but better look wikipedia csv knowledge csv and post tells possibilities java note due simplicity question one preassume homework i hereby declare more background i working experiments machine learning setting large scale test set i need crawl scrape file type transfer basic utility experiment building lot things suddenly want learn python due recent discoveries get feeling python concise java many parsing file handling situations hence got question i want save time getting gist without stating notsorelated background and questions second question java vs python because i run lines code python using csv library sure i asked know use python that reasons i got question thanks,2 did look django models methods you find class eventmodelsmodel eventdate modelsdatefield def getseasonself import datetime returns event specific season datetimedatetodaymonth return winter event obviously code incorrect know,i django model called event date field date event class eventmodelsmodel eventdate modelsdatefield i like able set method model tell whether event spring semester event fall semester event the spring semester would defined january may fall august december my goal able filter either semester generic list events year how would i go writing method defining semester,1 you simply use filter date range using gt greater lt less operators eventobjectsfiltereventdategtdatetimedate eventdateltdatetimedate or write semester db instance override default save method done automatically whenever save new existing event so model would class eventmodelsmodel eventdate modelsdatefield semester modelscharfieldmaxlength def saveself args kwargs determine even spring fall selfeventdatemonth selfsemester spring elif selfeventdatemonth selfsemester fall superevent selfsaveargs kwargs call real save method then simple query eventobjectsfiltersemester spring,i django model called event date field date event class eventmodelsmodel eventdate modelsdatefield i like able set method model tell whether event spring semester event fall semester event the spring semester would defined january may fall august december my goal able filter either semester generic list events year how would i go writing method defining semester,1 i really understand trying said calling exit quit constructor qapplication exit quit tells qapplication leave event loop constructor eventloop yet started exec called,i trying write pyqt application renders html waits finishes i got rendering mostly stripped simplicity sake the code runs hangs seems selfexit call selfquit honored having prior experience qt i feel i missing something obvious can someone shed light i also tried putting exit calls end render function pyqtqt import qapplication pyqtqtwebkit import qwebview import sys class screenshotterapplicationqapplication def initself args html qapplicationinitself args selfbrowser qwebview selfrenderhtml selfexit def renderself html print html name main app screenshotterapplicationsysargv hhello worldh sysexitappexec,2 you need rename methods begin word test as seen httpdocspythonorglibraryunittesthtml a testcase created subclassing unittesttestcase the three individual tests defined methods whose names start letters test this naming convention informs test runner methods represent tests,what exactly i need make python unittest work i checked official documentation so questions even tried using nose nothing worked far what i wrong bashpathtoprojectsrctests ls l total rwrr myuser myuser out echotestpy rwrr myuser myuser out initpy bashpathtoprojectsrctests python unittest v echotest ran tests ok bashpathtoprojectsrctests python unittest discover ran tests ok bashpathtoprojectsrctests cat echotestpy import unittest class echotestunittesttestcase def footestself selfasserttrue def bartestself selfasserttrue suite unittesttestloaderloadtestsfromtestcasetestecho unittesttexttestrunnerverbosityrunsuite name main unittestmain as see tests simply run i idea whysince i python programmer just information i using python initpy empty file any thoughts,3 test functions must start name test so footest testfoo see docs also need initpy file assuming two files tests directory,what exactly i need make python unittest work i checked official documentation so questions even tried using nose nothing worked far what i wrong bashpathtoprojectsrctests ls l total rwrr myuser myuser out echotestpy rwrr myuser myuser out initpy bashpathtoprojectsrctests python unittest v echotest ran tests ok bashpathtoprojectsrctests python unittest discover ran tests ok bashpathtoprojectsrctests cat echotestpy import unittest class echotestunittesttestcase def footestself selfasserttrue def bartestself selfasserttrue suite unittesttestloaderloadtestsfromtestcasetestecho unittesttexttestrunnerverbosityrunsuite name main unittestmain as see tests simply run i idea whysince i python programmer just information i using python initpy empty file any thoughts,1 unittestmain run function begin test so rename functions class echotestunittesttestcase def testfooself selfasserttrue def testbarself selfasserttrue,what exactly i need make python unittest work i checked official documentation so questions even tried using nose nothing worked far what i wrong bashpathtoprojectsrctests ls l total rwrr myuser myuser out echotestpy rwrr myuser myuser out initpy bashpathtoprojectsrctests python unittest v echotest ran tests ok bashpathtoprojectsrctests python unittest discover ran tests ok bashpathtoprojectsrctests cat echotestpy import unittest class echotestunittesttestcase def footestself selfasserttrue def bartestself selfasserttrue suite unittesttestloaderloadtestsfromtestcasetestecho unittesttexttestrunnerverbosityrunsuite name main unittestmain as see tests simply run i idea whysince i python programmer just information i using python initpy empty file any thoughts,2 see example httpmatplotlibsourceforgenetexamplesapifontfilehtml in general something like wanting use specific ttf file keep mind pointing specific font file usually bad idea import matplotlibfontmanager fm import matplotlibpyplot plt fig ax pltsubplots axplotrange prop fmfontpropertiesfname usrsharefontstruetypegroovyghttf axsettitle this random font fontpropertiesprop size pltshow usually point name font let matplotlib worry finding specific file eg import matplotlibpyplot plt pltplotrange plttitle this random font family groovyghosties size pltshow if want matplotlib always use particular font customize matplotlibrc file fontfamily want set note specify name font path specific ttf file as example dynamically ie without setting specific matplotlibrc file import matplotlib mpl mplrcparams fontfamily groovyghosties import matplotlibpyplot plt pltplotrange plttitle everything crazy size pltshow,how i use type font font library computer eg otf ttf matplotlib figures,3 here thing settingsinstalledapps tuple strings the import statement cannot anything to need use import function,say i want print installed apps version info server startup i setup project appone initpy otherstuff apptwo initpy otherstuff initpy adminpy urlspy settingspy main init file import settings settingsdebug â â â app settingsinstalledapps â â â â â try â â â â â â â import app â â â â â â â print getattrapp version none â â â â â except exception â â â â â â â pass app init files versioninfo version joinversioninfo i get pass statement i suppose way instances work python would i fix works though import app getattrapp version none this fixed import settings settingsdebug app settingsinstalledapps app importapp print getattrapp version none,1 edit i misunderstood question initially i corrected answer this functionality built pygraphlib library easily implement consider something like basically gets shortest path decides predefined range removes edge smallest weight computes new shortest path repeats pygraphlib import pygraph algo edges graph pygraphfromlistedges pathlist shortestpath algoshortestpathgraph startnode endnode cost shortestpathlenshortestpath cost maxcost cost mincost pathlistappendshortestpath minedgewt float inf rangelenshortestpath shortestpathi shortestpathi minedgewt minedgewt shortestpathi shortestpathi edgenodes shortestpathi shortestpathi not sure syntax edgenodes tuple hideedge requires edge graphhideedgeedgenodes shortestpath alogshortestpathgraph startnode endnode cost shortestpathlenshortestpath return pathlist note i find copy pygraphlib seeing longer development i test code it work mod syntax uncertainty also possible i would recommend using networkx link kind graph manipulation python complete active development completely documented pygraphlib just suggestion,i want find path graph connects two nodes use node twice the sum weights edges must within certain range i need implement pygraph i sure already algorithm i use purpose what best way achieve,1 app loop module string to load module name use djangoutilsimportlibimportmodule function djangoconf import settings djangoutilsimportlib import importmodule app settingsinstalledapps appmodule importmoduleapp print getattrappmodule version none,say i want print installed apps version info server startup i setup project appone initpy otherstuff apptwo initpy otherstuff initpy adminpy urlspy settingspy main init file import settings settingsdebug â â â app settingsinstalledapps â â â â â try â â â â â â â import app â â â â â â â print getattrapp version none â â â â â except exception â â â â â â â pass app init files versioninfo version joinversioninfo i get pass statement i suppose way instances work python would i fix works though import app getattrapp version none this fixed import settings settingsdebug app settingsinstalledapps app importapp print getattrapp version none,1 happy suggest possibly obvious implementation could made pure python ccython got time space new dependencies need faster a sparse matrix n dimensions assume elements empty use dictionary keyed tuples class ndsparsematrix def initself selfelements def addvalueself tuple value selfelementstuple value def readvalueself tuple try value selfelementstuple except keyerror could also using floats value return value would use like sparse ndsparsematrix sparseaddvalue shouldbezero sparsereadvalue you could make implementation robust verifying input fact tuple contains integers slow things i worry unless releasing code world later edit cython implementation matrix multiplication problem assuming tensor n dimensional numpy array numpyndarray might look like cython boundscheckfalse cython wraparoundfalse cimport numpy np def sparsemultobject sparse npndarraydouble ndim u cdef unsigned int j k npndarrayshapeushapeushapeushape dtypedouble xrangeushape j xrange ushape k xrange ushape note must define rank multiplication rule general nontrivial especially lxmxn tensor loop dummy variable two perform summation outijk uijk sparseijk return although always need hand roll problem hand mentioned code comment need define indices summing careful array lengths things work edit matrix also sparse need three way looping def sparsemultsparse othersparse ndsparsematrix key value sparseelementsitems j k key note must define rank multiplication rule general nontrivial especially lxmxn tensor loop dummy variable two perform summation example indices shown outaddvaluekey outreadvaluekey othersparsereadvalueijk sparseijk return my suggestion c implementation would use simple struct hold indices values typedef struct int index float value entryt need functions allocate maintain dynamic array structs search fast need test python implementation place performance worrying stuff,in scipy construct sparse matrix using scipysparselilmatrix etc but matrix i wondering existing data structure sparse matrix array tensor python ps i lots sparse data need tensor store perform multiplication any suggestions implement tensor existing data structure,3 you want use capture group research bddd dererzip print mgroup should print you could get away terse regex ensuring preceded followed provides minimal protection doublematches funky filenames malformed filenames match edit i replaced initial b matches border alphanumeric nonalphanumeric that way match whether hyphen beginning string preceding date,i need use python extract date filenames the date following format monthdayyearsomefileextension examples zip somedatabasesqltargz the best way extract would using regular expressions i code import research w dererzip print mgroup the code print some clue print date best regards,2 it seems matrixvector library using expression templates in case remarked operator returning vector private type represents operation the returned value left trapped c side things passed python private type registered now i familiar boostpython i think fix problem return value policy passing returnvaluepolicytopythonvaluedimvector policy would force converting returned type dimvector registered this would look like defself self returnvaluepolicytopythonvaluedimvector,i newbie boostpython getting error i would like get help as part larger project i writing wrapper vector class i as notice code bellow class d d big difference current problem i i trying wrap operators defined vector class i works fine long function overloaded operator return value type vector i guess python know objects i returning value code struct d typedef eigenmatrix long double vector struct d typedef eigenmatrix long double vector now following macro defined job possible dimensions boostpythonmoduletypes using namespace boostpython define gpspyexposevectordim name classdimvectorname definitdimvector defnorm ampdimvectornorm defsetitem amppyvectorhelperdimsetvectorelem defgetitem amppyvectorhelperdimgetvectorelem defself self defself self defself self not working defself self not working deftostr amppyvectorhelperdimtopystring defstr amppyvectorhelperdimtostdstring gpspyexposevectord vectord gpspyexposevectord vectord code works right except i try use operator python follows import types v typesvectord v typesvectord v v v error the error following traceback recent call last file stdin line module typeerror no topython byvalue converter found c type eigencwisebinaryopeigeninternalscalarsumoplong double eigenmatrixlong double const eigenmatrixlong double const i followed tutorial i found info related error internet help welcome thanks advance edit luc danton answer to luc danton thanks answer i tried said work error i got error matching function call ‘boostpythonclasseigenmatrixlong double boostpythondetailnotspecified boostpythondetailnotspecified boostpythondetailnotspecifieddefboostpythondetailoperatorboostpythondetailoperatoridu boostpythonselfnsselft boostpythonselfnsselft boostpythonreturnvaluepolicyboostpythontopythonvalueeigenmatrixlong double boostpythondefaultcallpolicies’ however thanks comment got idea write helper function performs addition convert eigen expression object private type representing operator this template typename tdim struct pyvectorhelper static typename tdimvector sumtypename tdimvector const ampv typename tdimvector const ampv return v v defadd amppyvectorhelperdimsum works fine i want since pyvectorhelperdimsum returns dimvector the problem almost every operator overloaded eigen returns expression object meaning i would implement similar functions almost nice practical p maybe still possible use returnvaluepolicy topythonvalue i avoid tedious operators rewriting,2 assuming date always format mmddyyyy research filename,i need use python extract date filenames the date following format monthdayyearsomefileextension examples zip somedatabasesqltargz the best way extract would using regular expressions i code import research w dererzip print mgroup the code print some clue print date best regards,3 so sayeth documentation standard output defined file object named stdout builtin module sys so change stdout like import sys sysstdout openoutputdat w,very simple question i using idle python shell run python scripts i use following type structure import sys sysargv fileinp execfile mypythonscriptpy is simple way outputting results file something like execfile mypythonscriptpy outputdat thanks,1 please file bug report pycharm issue tracker,i seen following errors i start set environment pycharm should i address issues ok leave thank userubuntudownloadspycharmbin pycharmsh error pythonsdkpyskeletonrefresher exit code javalangthrowable comintellijopenapidiagnosticloggererrorloggerjava comintellijexecutionprocessprocessoutputchecksuccessprocessoutputjava comjetbrainspythonsdkpyskeletonrefreshergeneratebuiltinskeletonspyskeletonrefresherjava comjetbrainspythonsdkpyskeletonrefresherregenerateskeletonspyskeletonrefresherjava comjetbrainspythonsdkpyskeletonrefresherregenerateskeletonspyskeletonrefresherjava comjetbrainspythonsdkpythonsdktyperunpythonsdktypejava comintellijopenapiprogressimplprogressmanagerimpltaskrunnablerunprogressmanagerimpljava comintellijopenapiprogressimplprogressmanagerimplrunprogressmanagerimpljava comintellijopenapiprogressimplprogressmanagerimplrunprogressmanagerimpljava comintellijopenapiprogressimplprogressmanagerimplexecuteprocessunderprogressprogressmanagerimpljava comintellijopenapiprogressimplprogressmanagerimplrunprocessprogressmanagerimpljava comintellijopenapiapplicationimplapplicationimplrunapplicationimpljava comintellijopenapiapplicationimplapplicationimplrunapplicationimpljava javautilconcurrentexecutorsrunnableadaptercallunknown source javautilconcurrentfuturetasksyncinnerrununknown source javautilconcurrentfuturetaskrununknown source javautilconcurrentthreadpoolexecutorworkerruntaskunknown source javautilconcurrentthreadpoolexecutorworkerrununknown source javalangthreadrununknown source comintellijopenapiapplicationimplapplicationimplrunapplicationimpljava error pythonsdkpyskeletonrefresher pycharm build py error pythonsdkpyskeletonrefresher jdk error pythonsdkpyskeletonrefresher vm java hotspottm client vm error pythonsdkpyskeletonrefresher vendor sun microsystems inc error pythonsdkpyskeletonrefresher os linux error pythonsdkpyskeletonrefresher last action showsettings,1 in particular case i trying get autodoc read doc string doc string i ended using n everywhere i needed add line break this first linen second linen,i using sphinx generating docs python project the output html preserving line breaks present docstring example code def testmethodargarg this test method arguments arg arg description arg arg description returns none print i test method sphinx op testmoduletestmethodarg arg this test method arguments arg arg description arg arg description returns none any idea fix,2 the second argument shutilmove specifies directory glob mask import ospath shutilmoveospathjoinfiledir pageshtml osgetcwd work,i know may sound really stupid i move file directory user browsed i named mine filedir current directory i example i file called pageshtml cwebs how i move file current working directory this code shutilmovefiledir i got errors using code is another way say current directory,1 it would helpful posted error message complete traceback however get current working directory use osgetcwd as long filedir points file directory work filedir rcwebspageshtml shutilmovefiledir osgetcwd,i know may sound really stupid i move file directory user browsed i named mine filedir current directory i example i file called pageshtml cwebs how i move file current working directory this code shutilmovefiledir i got errors using code is another way say current directory,1 python python r apr gcc linux import sys sysdisplayhookstdout open file stdout mode w xfda xopen myfile w sysdisplayhookx open file myfile mode w xfbc sysstdoutx print changed stdout xclose cat myfile changed stdout note changing objects doesn’t affect standard io streams processes executed ospopen ossystem exec family functions os module so import os ossystemx output x x return code quit,very simple question i using idle python shell run python scripts i use following type structure import sys sysargv fileinp execfile mypythonscriptpy is simple way outputting results file something like execfile mypythonscriptpy outputdat thanks,1 there ways getting information depends trying access if inside dostepif procedure parameter addstep work def insidedostepifstep stepbuildgetstatusnumber if trying prioritize builders next build number work def buildprioritybuildmaster builders builderssortkeylambda b bbuilderstatusnextbuildnumber return builders c prioritizebuilders buildpriority if interested getting information messageformatter function buildbotstatusmailmailnotifier try def formatemailmode name build results masterstatus builder masterstatusgetbuildernames masterstatusgetbuilderbuildernextbuildnumber i test i guarantee api stable i pretty confident work i similar things though build number mastercfg,is variable i access mastercfg the docs clear thanks,3 i concluded strange manifestation perplexing assignment behavior hpy object instance variable i rewrote code file handled within function call variable reused using approach i see strange behavior seems work much better for clarity solution looks like files globr pathh outcsv csvwriteropen outputfilecsv rb def extractdatafromfilenamefilename return extractdatafromhandlehdffilefilename r filename files data extractdatafromfilenamefilename row data outcsvwriterowfilename row,i usint bit version enthought python process data across multiple hdf files i using hpy version hdf bit windows i object provides convenient interface specific data heirarchy testing hpyfilefname r independently yields results i iterating long list files time attempting pull specific pieces information files the problem i i getting information several files my loop looks something like files globr pathh outcsv csvwriteropen outputfilecsv rb filename files handle hdffilefilename r data extractdatafromhandlehandle row data outcsvwriterowfilename row when i inspect files using something like hdfview i know internals different however csv i get seems indicate files contain data has anyone seen behavior any suggestions i could go start debugging issue,2 make pipes nonblocking using fcntlfcntl use selectselect wait data become available either pipe for example helper function add ononblock flag file descriptor def makeasyncfd fcntlfcntlfd fcntlfsetfl fcntlfcntlfd fcntlfgetfl osononblock helper function read data file descriptor ignoring eagain errors def readasyncfd try return fdread except ioerror e eerrno errnoeagain raise e else return process subprocesspopenargs stdoutsubprocesspipe stderrsubprocesspipe makeasyncprocessstdout makeasyncprocessstderr stdout str stderr str returncode none true wait data become available selectselectprocessstdout processstderr try reading data stdoutpiece readasyncprocessstdout stderrpiece readasyncprocessstderr stdoutpiece print stdoutpiece stderrpiece print stderrpiece stdout stdoutpiece stderr stderrpiece returncode processpoll returncode none return returncode stdout stderr note fcntl available unixlike platforms including cygwin if need work windows without cygwin doable much much tougher you use pywin library call native win api use setnamedpipehandlestate pipenowait make stdout stderr pipes nonblocking use waitformultipleobjects instead select wait data become available use readfile read data,maybe someone ether help one i seen number similar questions so none deal standard standard error deal situation quite like mine hence new question i python function opens subprocess waits complete outputs return code well contents standard standard error pipes while process running i like also display output pipes populated my first attempt resulted something like process subprocesspopenargs stdoutsubprocesspipe stderrsubprocesspipe stdout str stderr str returncode none true collect return code pipe info stdoutpiece processstdoutread stdout stdout stdoutpiece stderrpiece processstderrread stderr stderr stderrpiece returncode processpoll check end pipes return code stdoutpiece stderrpiece returncode none return returncode stdout stderr stdoutpiece printstdoutpiece stderrpiece printstderrpiece there couple problems though because read reads eof first line loop return subprocess closes pipe i could replace read favor readint printed output distorted cut end read characters i could readline replacement printed output distorted alternating lines output errors many occur time perhaps readuntilendofbuffer variant i aware or maybe implemented maybe best implement sysstdout wrapper suggested answer another post i would want use wrapper function however any ideas community i appreciate help edit the solution really crossplatform ideas please share away keep brainstorming going for another one python subprocess head scratchers take look another questions accounting subprocess overhead timing,3 qapplicationexit tells application leave main event loop ie return exec soon possible your problem small piece static html easy retrieve render qtwebkit right sethtml called no delays background processing everything done sethtml returns so save called main loop starts ie exec called it like writing return function – except qt ignore exit quietly loop running solution use queuedconnection connect call force signal queued delivered event loop starts this also work loop already running course selfbrowserloadfinishedconnectselfsave qtqueuedconnection,writing script render arbitrary html image using pyqt i confused qapplicationexit call making qapplicationexec return any ideas class screenshotterapplicationqapplication def initself args html qapplicationinitself args selfhtml html selfbrowser qwebview selfbrowserresize selfbrowserloadfinishedconnectselfsave selfbrowserloadprogressconnectselfprogress def renderself selfbrowsersethtmlselfhtml def progressself progress print progress def saveself finished success false finished print saving snip success pixmapsave screenshotpng success print saved screenshotpng qapplicationexit success else def execself args kwargs selfrender superqapplication selfexecargs kwargs def takescreenshothtml app screenshotterapplicationsysargv html return appexec name main print takescreenshot h stylewidth pxhello worldh,2 what looking css javascript pipeline its becoming standard frameworks provide kind tools for instance rails asset pipeline builtin not merge css javascripts single pack also compress even performance boost fortunately django also plugin httpsgithubcomcyberdeliadjangopipeline,according o reilly high performance web sites pages highly recommended make http requests possible highperformance thus library combining multiple js files one file library css well for javascript i least different libraries loaded right jquery x jquery plugins one application javascript file application logic i also css files bootstrap application css file are tools facilitate it nice tool i could use python bash i linux compile minify multiple css stylesheets if possible django addon even better ie managepy packify staticbootstrapmincss staticapplicationcss,3 there various methods a great plugin already mentioned javierieh but easily build one using php server language but gain even load jquery plugins google libraries api it offers minified version many libraries the advantage use server browsers make limited number simultaneous connections server allows users load jquery javascript time and many sites use libraries google files may already exist browser cache visitor speeding loading even,according o reilly high performance web sites pages highly recommended make http requests possible highperformance thus library combining multiple js files one file library css well for javascript i least different libraries loaded right jquery x jquery plugins one application javascript file application logic i also css files bootstrap application css file are tools facilitate it nice tool i could use python bash i linux compile minify multiple css stylesheets if possible django addon even better ie managepy packify staticbootstrapmincss staticapplicationcss,1 of course tool it called webassets and integrates fine django webassets features minification compression css js less css sass css compass etc,according o reilly high performance web sites pages highly recommended make http requests possible highperformance thus library combining multiple js files one file library css well for javascript i least different libraries loaded right jquery x jquery plugins one application javascript file application logic i also css files bootstrap application css file are tools facilitate it nice tool i could use python bash i linux compile minify multiple css stylesheets if possible django addon even better ie managepy packify staticbootstrapmincss staticapplicationcss,2 your question linux less linux specific below code example three variants mapping majorminor device name parse procpartitions ask hal hal also keeps track parent device meaning easily get disk aswell partition check sysfs this hal gets information i say procpartitions simplest one file open check hal gives information abstracts away lots details sysfs may viewed correct procpartitions require hal running for desktop program i would go hal on embedded system i go sysfs import os def main dev osstathomestdev major minor osmajordev osminordev print procpartitions says askprocpartitionsmajor minor print hal says askhalmajor minor print sys says asksysfsmajor minor def parseprocpartitions res line fileprocpartitions fields linesplit try tmaj intfields tmin intfields name fields restmaj tmin name except ignore parse errors headerseparator lines pass return res def askprocpartitionsmajor minor parseprocpartitions return dmajor minor def askhalmajor minor import dbus bus dbussystembus halobj busgetobject orgfreedesktophal orgfreedesktophalmanager hal dbusinterfacehalobj orgfreedesktophalmanager def getdevpropsp bdevi dbusinterfacebusgetobject orgfreedesktophal p orgfreedesktophaldevice return bdevigetallproperties bdevs halfinddevicebycapabilityblock bdev bdevs props getdevpropsbdev props blockmajor props blockminor major minor parentprops getdevpropsprops infoparent return strprops blockdevice strparentprops blockdevice def asksysfsmajor minor glob import glob needle dd major minor files globsysclassblockdev f files filefreadstrip needle return ospathdirnamef return none name main main,how use python determine linux devicepartition contains given filesystem eg getfilesystemdevice devsda getfilesystempartition devsda,1 i bitnami team i saw issue i sure using older version least newer version bitnami djangostack need make sure adminmediaprefix point staticadmin following instructions httpsdocsdjangoprojectcomenintrotutorial you need copy static files project directory django automatically use files djangocontrib directory however currently setting adminmediaprefix staticadminmedia behavior different application served apache instead django server we realize may bit confusing users starting django looking side keep default configuration new projects also allow demo project served apache,so i installed bitnami django stack enabled admin module followed tutorial creating admin menu polls however i go admin everything white plaintext all css images error all i enable settingspy installedapps djangocontribadmin in urlspy uncommented djangocontrib import admin adminautodiscover urlr admin includeadminsiteurls uncommented in settingspy i tried using default settings also tried mediaroot mediaurl media staticroot staticurl static adminmediaprefix staticurl admin import os siteroot ospathdirnameospathrealpathfile staticfilesdirs ospathjoinsiteroot static nothing seems work refuses find static files adminmediacss etc i made sure windows path bin django i even tried including contrib nothing helps i installed django cdjangostackappsdjango i installed project cusersdexterbitnami djangostack projectsalpha i type localhostalphaadmin go admin,1 you use cleaneddata httpsdocsdjangoprojectcomendevtopicsformsprocessingthedatafromaform here example modelspy class bookmodelsmodel author modelscharfieldmaxlength formspy class bookformformsmodelform class meta model book viewspy def bookupdaterequest form bookformrequestpost none formisvalid print formcleaneddata author,would able tell i get datavalue modelform fields i know get initial data i understood correctly form fields also datavalue value associated thanks,1 in short python pty module look solution this question simple may look like it simple change running state process delivering corresponding signals simple manipulate foregroundbackground properties when talk manipulating foregroundbackground processes really talk job control in unix environment job control achieved coordination several parts including kernel controlling terminal current shell almost every process invoked shell session telling process get back foreground tell others shut go background simultaneously see let come back question there could answers one way could done why answers generally cannot job control unless program you also cannot use simple pipe achieve coordination model leads job control mechanism reason essential since cannot deliver signals pipe that answer way least way simple pipe implementation however enough patience program terminal io still done lot labor work concept simple cheat slave program emacs example attached real terminal true keyboard solid monitor standby prepare master program python script handle relay necessary events controlling terminal slave pseudoterminal this schema actually adopted many terminal emulators you need write another terminal emulator case wait does done much effort always luckily your shell manages stuff interactive scenario you tell shell fgbg task quite easy real life the designated command combination found shell manpage it could look like jobs l grep emacs along fg nonetheless combined commands cannot invoked program it different story since program start new shell interpret commands new shell cannot control old running emacs privilege type keyboard read monitor interactive scenario in automation scenario think twice employ job control design automation scenarios require job control schema you need editor player right make stay background pop foreground they better exit complete task but unlucky program job control automation procedures try program pseudoterminal master slave io well they look like sophisticated ipc mechanism details osdependent however standard answer question though annoying i know,i want search process show itemacs examplei use p subprocesspopen ps a grep emacs shelltruestdoutsubprocesspipe get process i wake show wordsthe question shoud python change state process,1 the best solution depends releasing license releasing if concerned revealing code apps distributing service like github bitbucket way go the best way contribute code community releasing open source version control allows people contribute learn but depending audience might need something userfriendly in case cxfreeze pyinstaller perfectly acceptable solutions if distributing package may want look setuptools,quick question once i build py app wx gui etc i compile pyinstaller cxfreeze send binaries servers correct is good way distribute script i fairly new app development cycle i python script i would like make public make life easier if share code rest community provide people py code wanted distribute binaries well would compile py pyinstaller cxfreeze would use method dev environment currently mac osx debian domu thanks,2 similarly stdvector cpython list already preallocates elements required grows allocated space manner gives o amortized appends i would therefore leave i could prove profiling indeed bottleneck edit you mention comments already done profiling in case preallocating nonen might sensible thing try see really repeated reallocations bottleneck if array numeric i would encourage take look numpy,i looking python equivalent c vectorreserve i know big list going ahead time i know going fairly large i want avoid many resizings possible list grown inside deep inner loop the solution i come far cumbersome compared vectorreserve idiom that solution precreate list using nonek tracking size list separate counter appending setting items list need copying slice list fully constructed is alternative,3 to put plainly create presized list following lst none n n size list of course set index manually opposed append keep track last index used if however another question comrades done good job answering,i looking python equivalent c vectorreserve i know big list going ahead time i know going fairly large i want avoid many resizings possible list grown inside deep inner loop the solution i come far cumbersome compared vectorreserve idiom that solution precreate list using nonek tracking size list separate counter appending setting items list need copying slice list fully constructed is alternative,1 regarding immutable querydict error problem almost certainly created form instance like form myformrequestpost this means formdata actual querydict created post vars since request immutable get error try change anything in case saying formdata field none exactly thing requestpost field none to get form modify want construct like form myformrequestpostcopy,i django form allows user change password i find confusing form error fields ed data still i tried several methods removing formdata i keep getting this querydict instance immutable exception message is proper way clear individual form fields entire form data set clean,3 the fann library also looks promising,i planning implementing document ranker uses neural networks how one rate document taking consideration ratings similar articles any good python libraries can anyone recommend good book ai python code edit i planning make recommendation engine would make recommendations similar users well using data clustered using tags user would given chance vote articles there hundred thousand articles documents would clustered based tags given keyword articles would fetched based tags passed neural network ranking,1 after hours searching i found solution problem i still sure code works apposed version here code i using import urllib import urllib import cookielib cj cookieliblwpcookiejar opener urllibbuildopenerurllibhttpcookieprocessorcj urllibinstallopeneropener request urllibrequesthttpwhatcdindexphp none f urlliburlopenrequest fclose data urlliburlencodeusername yourlogin password yourpassword request urllibrequesthttpwhatcdloginphp data f urlliburlopenrequest html fread fclose credit goes carlwaldbieser linuxquestionsorg thanks everyone gave input,i working screen scraper using beautifulsoup whatcd using python i came across script working decided look since seems similar i working however every time i run script i get message credentials wrong even though as far i tell i getting message script tries log whatcd whatcd supposed return cookie containing information lets request pages later script so script failing cj cookielibcookiejar opener urllibbuildopenerurllibhttpcookieprocessorcj logindata urlliburlencode username username password password check openeropen httpwhatcdloginphp logindata soup beautifulsoupcheckread warning soupfind span warning warning exitstrwarning nnprobably means username pw wrong i tried multiple methods authenticating site including using cookiefilejar script located requests module i gotten html message one it says short javascript disabled cookies disabled also provides login box html i really want mess around mechanize i see way moment if anyone provide help would greatly appreciated,1 the basic problem running xxx methods looked class means instances class use xxx methods this suggests using method similar cat plus plus suggested however also want users worry even special names callimpl negate if mind possibly mindmelting power metaclasses route take a metaclass add negate attribute automatically name mangle avoid clashes well take call user wrote rename call create new call calls old call called call negates result necessary returning here code import copy import inspect class metafunctiontype def newmetacls clsname clsbases clsdict resultclass typenewmetacls clsname clsbases clsdict call clsdict originalcall clsdict call args varargs kwargs defaults inspectgetargspecoriginalcall args args defaults none defaults lenargs else defaults lenargs lendefaults listdefaults signature arg default zipargs defaults default signatureappend ss arg default else signatureappendarg varargs none signatureappendvarargs kwargs none signatureappendkwargs signature joinsignature passedargs joinargs newcall def callself signatures result selfcallpassedargss selfclsnamesnegate result result return result clsname clsname signature signature passedargs passedargs evaldict exec newcall evaldict newcall evaldict call newcalldoc originalcalldoc newcallmodule originalcallmodule newcalldict originalcalldict setattrresultclass call newcall setattrresultclass call originalcall setattrresultclass snegate clsname false negate def negself returns instance class returns negation call negated copycopyself negatedclsnamesnegate selfclsnamesnegate return negated clsname clsname evaldict copy copy exec negate evaldict negate evaldict neg negatemodule newcallmodule setattrresultclass neg evaldict neg return resultclass class baseobject metaclass metafunction class powerbase def initself power power power raise selfpower power def callself number raises number power return number selfpower example square power negsquare square square negsquare while metaclass code complex resulting objects easy use to fair code complexity metafunction due rewriting call order preserve call signature make introspection useful instead seeing callargs kwargs help see help power module test object class powerbase method resolution order power base builtinobject methods defined callself number raises number power initself power power power raise negself returns instance class returns negation call,i apologize advance rather long question i implementing callable objects would like behave somewhat like mathematical functions i base class whose call method raises notimplementederror users must subclass define call my question i define special method neg base class subclasses immediately expected behavior without implement neg subclass my sense expected behavior f instance subclass base class properly defined call f instance class f possessing attributes f except call return negative f call here example i mean class baseobject def callself args kwargs raise notimplementederror please subclass def negself def callargs kwargs return selfargs kwargs mbase type mbase base call call return mbase class onebase def initself data selfdata data def callself args kwargs return this expected behavior one one print one prints minusone one print minusone prints though exactly i like since minusone instance class one i could live now i like new instance minusone inherit attributes methods one call method change so i could change neg def negself def callargs kwargs return selfargs kwargs mbase type mbase base call call new mbase n v inspectgetmembersself n call setattrnew n v return new this seems work my question cons strategy implementing generic neg must standard exercise i find anything web are recommended alternatives thanks advance comments,2 since want catch sysstdout sysstderr global interpreter according documentation able catch regardless thread output done on hand code far working it missing call event loop freezed i added call cmain i also added button prints hello i replaced default sysstdout instance consoleoutput hello appear textview import sys import gtk import pygtk pygtkrequire import gobject import threading class mythreadthreadingthread def initself name threadingthreadinitself selfname name def runself range print hello thread selfname class console def initself tv gtktextview tvseteditablefalse tvsetwrapmodegtkwrapword selfbuffer tvgetbuffer button gtkbuttonupdate buttonconnectclicked selfupdate none table gtktable gtkfalse tableattachtv tableattachbutton main window selfwindow gtkwindowgtkwindowtoplevel selfwindowconnect destroyevent lambda w e gtkmainquit selfwindowconnect deleteevent lambda w e gtkmainquit selfwindowsetborderwidth selfwindowaddtable selfwindowsettitle search selfwindowsetdefaultsize selfwindowshowall def updateself widget datanone print hello mythreadastart mythreadbstart def mainself gtkmain c console class consoleoutput def initself source selfsourcesource selfbuf def updatebufferself cbufferinsertcbuffergetenditer joinselfbuf selfbuf def writeself data selfbufappenddata dataendswith n gobjectidleaddselfupdatebuffer def delself selfbuf gobjectidleaddselfupdatebuffer sysstdout consoleoutputnone cmain edit i updated answer include example threads two threads created pressing button i used python threading module i think pygtk threading facilities python module came first searching google the important point made consoleoutput class note i wrapped code updates console buffer method called selfupdatebuffer called indirectly gobjectidleadd what function call selfupdatebuffer within gtk event loop it must done way calls update gui must done within event loop otherwise gtk synchronize access data structures may get strange behaviours crashes there may buffering issues prevent output appearing textview,i problem i creating editor i need console outputsysstderr sysstdout outputted textview the problem i start console waits quit i want catch anything output textview i thought might need different threads make impossible catch anything thread i want case editor started terminal it used module wondering this code far import sys import gtk import pygtk pygtkrequire class console def initself tv gtktextview tvseteditablefalse tvsetwrapmodegtkwrapword selfbuffer tvgetbuffer table gtktable gtkfalse tableattachtv main window selfwindow gtkwindowgtkwindowtoplevel selfwindowconnect destroyevent lambda w e gtkmainquit selfwindowconnect deleteevent lambda w e gtkmainquit selfwindowsetborderwidth selfwindowaddtable selfwindowsettitle search selfwindowsetdefaultsize selfwindowshowall def mainself gtkmain c console class consoleoutput def initself source selfsourcesource selfbuf def writeself data selfbufappenddata dataendswith n cbufferinsertcbuffergetenditer joinselfbuf selfbuf def delself selfbuf cbufferinsertcbuffergetenditer joinselfbuf thank,1 you got couple problems first activatethispy working fine the problem setup you trying activate virtualenv using system default python virtualenv python that seeing system sitepackages nositepackages applies python binary created virtualenv that also adding usrlocalvirtualenvsdevemailslibpythonsitepackages the activatethispy script uses version python executing script determine sitepackages directory use sitepackages ospathjoinbase lib pythons sysversion sitepackages when activate virtualenv uses correct binary second version modwsgi built system python encountering problem see virtualenv activated the activatethispy script actually nothing enforce nositepackages option relies python binary created virtualenv modwsgi never enforce nositepackages which see fall back version django installed system find sitepackages directory virtualenv third apache runs bit installed python binary bit even rebuilt modwsgi version apache would crash trying load and course sites would problem ones your best bet run sites behind something like gunicorn,problem discription the issues i i try load django website using modwsgi python virtualenv i get error i go site browser when i look error created apache log i get following tue oct error client modwsgi pid exception occurred processing wsgi script volumesontariositesemailsconfigapachedevemailswenatcheeworldcomwsgi tue oct error client traceback recent call last tue oct error client file librarypythonsitepackagesdjangopyeggdjangocorehandlerswsgipy line call tue oct error client selfloadmiddleware tue oct error client file librarypythonsitepackagesdjangopyeggdjangocorehandlersbasepy line loadmiddleware tue oct error client middlewarepath settingsmiddlewareclasses tue oct error client file librarypythonsitepackagesdjangopyeggdjangoutilsfunctionalpy line getattr tue oct error client selfsetup tue oct error client file librarypythonsitepackagesdjangopyeggdjangoconfinitpy line setup tue oct error client selfwrapped settingssettingsmodule tue oct error client file librarypythonsitepackagesdjangopyeggdjangoconfinitpy line init tue oct error client raise importerrorcould import settings is syspath does syntax errors selfsettingsmodule e tue oct error client importerror could import settings configsettings is syspath does syntax errors no module named configsettings the traceback make sense files getting loaded global python library virtualenv setup information i installed python os x server running os x i installed python using python mac os x bit ippc installer the server currently virtualenv installed i setup virtualenv using new website using following cd usrlocalvirtualenvs virtualenv nositepackages p usrlocalbinpython devemails i install nessary python packages when i run pip freeze output pip freeze django pil south amqplib anyjson boto celery djangocelery djangocompressor djangograppelli djangopicklefield feedparser htmltext kombu lxml psycopg pyparsing pythondateutil pythonsendgriddev redis requests wsgiref trouble shooting steps i created script called pathtestpy order test virtualenv path import os import sys activate python virtual enviroment activatethis usrlocalvirtualenvsdevemailsbinactivatethispy execfileactivatethis dictfileactivatethis start django import djangocorehandlerswsgi osenviron djangosettingsmodule configsettings p syspath print p application djangocorehandlerswsgiwsgihandler when i run script using python pathtestpy i get following output usrlocalvirtualenvsdevemailslibpythonsitepackages volumesontariositesemailsbin librarypythonsitepackagesmysqlpythonpymacosxiegg librarypythonsitepackagesparamikopyegg librarypythonsitepackagessimplejsonpymacosxiegg librarypythonsitepackagespythonldappymacosxiegg librarypythonsitepackageslxmlpymacosxiegg librarypythonsitepackagespytzhpyegg librarypythonsitepackagespythonopenidpyegg librarypythonsitepackagesmarkdownpyegg librarypythonsitepackagesdjangoauthopenidpyegg librarypythonsitepackagesdjangopyegg librarypythonsitepackagesdjangoprofilespyegg librarypythonsitepackagesdjangoopenidconsumerpyegg librarypythonsitepackagessetuptoolscpyegg librarypythonsitepackagesipythonpyegg librarypythonsitepackageshttplibpyegg librarypythonsitepackagesguesslanguagepyegg librarypythonsitepackagesdjangoratingspyegg librarypythonsitepackagespippyegg systemlibraryframeworkspythonframeworkversionslibpythonzip systemlibraryframeworkspythonframeworkversionslibpython systemlibraryframeworkspythonframeworkversionslibpythonplatdarwin systemlibraryframeworkspythonframeworkversionslibpythonplatmac systemlibraryframeworkspythonframeworkversionslibpythonplatmaclibscriptpackages systemlibraryframeworkspythonframeworkversionsextraslibpython systemlibraryframeworkspythonframeworkversionslibpythonlibtk systemlibraryframeworkspythonframeworkversionslibpythonlibdynload librarypythonsitepackages librarypythonsitepackagespil systemlibraryframeworkspythonframeworkversionsextraslibpythonpyobjc if i activate virtualenv first using source pathtovirtualenvbinactivate run python pathtestpy i get following output usrlocalvirtualenvsdevemailslibpythonsitepackagessetuptoolscpyegg usrlocalvirtualenvsdevemailslibpythonsitepackagespippyegg usrlocalvirtualenvsdevemailslibpythonsitepackageslxmlpymacosxintelegg usrlocalvirtualenvsdevemailslibpythonsitepackages usrlocalvirtualenvsdevemailslibpythonsitepackagespil volumesontariositesemailsbin volumesontariolocalvirtualenvsdevemailslibpythonsitepackagessetuptoolscpyegg volumesontariolocalvirtualenvsdevemailslibpythonsitepackagespippyegg volumesontariolocalvirtualenvsdevemailslibpythonsitepackageslxmlpymacosxintelegg volumesontariolocalvirtualenvsdevemailslibpythonzip volumesontariolocalvirtualenvsdevemailslibpython volumesontariolocalvirtualenvsdevemailslibpythonplatdarwin volumesontariolocalvirtualenvsdevemailslibpythonplatmac volumesontariolocalvirtualenvsdevemailslibpythonplatmaclibscriptpackages volumesontariolocalvirtualenvsdevemailslibpythonlibtk volumesontariolocalvirtualenvsdevemailslibpythonlibold volumesontariolocalvirtualenvsdevemailslibpythonlibdynload libraryframeworkspythonframeworkversionslibpython libraryframeworkspythonframeworkversionslibpythonplatdarwin libraryframeworkspythonframeworkversionslibpythonlibtk libraryframeworkspythonframeworkversionslibpythonplatmac libraryframeworkspythonframeworkversionslibpythonplatmaclibscriptpackages volumesontariolocalvirtualenvsdevemailslibpythonsitepackages volumesontariolocalvirtualenvsdevemailslibpythonsitepackagespil volumesontariositesemails at point i pretty sure problem activatethispy virtualenv setting correct syspath,1 this complete answer manhole i also suggest manually running gccollect prior looking ps top guppy show allocated heap anything proactively free objects longer allocated,i profiling twisted server it uses much memory i expected its memory usage grows time ps pidrssvszszsizecommand pid rss vsz sz sz command twistd broadcasttac as see costs kbs namely mbs and i use guppy twisted manhole watch memory usage profile hpheap partition set objects total size bytes index count size cumulative kind class dict class str tuple dict owner typescodetype dict module function dict class type dict type dict zopeinterfaceinterfacemethod rows type eg view hum it seems something wrong guppy shows total usage memory bytes namely kbs mbs that huge difference what wrong strange result what i wrong update i wrote monitor script last night it records memory usage number online users it radio server see radios total listeners here figure i generated matplotlib something strange sometimes memory usage printed ps low like info info info info info what reason super low value memory usage and even online radios listeners memory usage still high,1 newsobjectsfiltercreatedbyin agencypositionlistusers it documented,i models class agencypositionmodelsmodel agencymodelsforeignkeyagency usersmodelsmanytomanyfielduser positiontypecodemodelsforeignkeypositiontype phonenumbermodelscharfieldmaxlength emailmodelscharfieldmaxlength statustypecodemodelsforeignkeystatustype class newsmodelsmodel categorymodelsforeignkeycategory titlemodelscharfieldmaxlength descriptionmodelstextfield createdbymodelsforeignkeyusereditablefalse actiondatemodelsdatetimefieldautonowtrueeditablefalse i wanna user enter name agency i select top news belong specific agencynews model createdby fieldcreatedby field user insert newsin agencyposition i determine user belong agency i viewspy agnagencyobjectsfilternamekey agencypositionlistagencypositionobjectsfilteragencyagn i users specific agencythen i wanna select news createdby field specific agencysome thing like pseudo code select top news createdby inagencypositionlistusers how i,1 i found making simple tweak directions fixed whole issue open command prompt type set pathpathcpython i using edit accordingly type python cusersresearchdesktopexamplepy first second third for process worked full file name examplepy expy whatever typed good luck,disclaimer i read thread located valueerror need value unpack none answers explained actually get code run i reading learn python hard way i exercise here code i attempting run idle thing know really called python sys import argv script first second third argv print the script called script print your first variable first print your second variable second print your third variable third when run i get error traceback recent call last file cpythonlpthwexampleslpthwexpy line script first second third argv valueerror need value unpack i tried running program windows command prompt avail i also run program typing python expy first nd rd idle command prompt also got error how i get code run heck i wrong edit john machin i made program exactly like one posted saved py went correct directory file saved ran program using python yourcodepy b c d i received following message python recognized internal external command when i run program typing name works programs besides one i get error saying syntaxerror invalid syntax line print lenargv reprargv edit with new code john machin i copied program word word gedit made py file usual i opened terminal command prompt typed python excpy b c d and received python recognized internal external command operable program batch file then i typed excpy and received r nov msc v bit intel cpythonlpthwexampleslpthwexcpy traceback recent call last file cpythonlpthwexampleslpthwexcpy line module b c argv valueerror need value unpack keep mind i running w bit zed teaching x i using entire book far every example worked right i started example i installed different book i start reading every time i use idle included perhaps possible i somehow inadvertently using trying code thanks bearing,1 try pythonpath instead path bash configuration file for info look official documentation topic,i root access i installed psycopg module opt i permission directory python setuppy install prefixopt i tried several methods bashrc pathpathhomebinoptlibpythonsitepackagespsycopg export path bashprofile pathpathhomebinoptlibpythonsitepackages export path i also tried syspathappend optlibpythonsitepackagespsycopg nothing works python import psycopg psycopg module neither optlibpythonsitepackagespsycopg optlibpythonsitepackages path works please help thank,3 chances bitonly python installed system possibly downloaded pythonorg built gcc includes ppc universal variant building c extension modules pythons problematic xcode installed default optional gcc ppc support removed the easiest best longterm solution install bitbit python build see pythonorg download page current releases simply use applesupplied python usrbinpython,i trying install pycurl local environment python gcc os x lion i tried based answer error installing pycurl sudo env archflagsarch x pip install pycurl which fails i gcc installed via xcode error command gcc failed exit status i also tried downloading source building setuppy i modified based problem trying install pycurl mac snow leopard gcc fnostrictaliasing fnocommon dynamic dndebug g fwrapv os wall wstrictprototypes denabledtrace arch x pipe dhavecurlssl isystemlibraryframeworkspythonframeworkversionsincludepython c srcpycurlc this results error i verified i indeed gcc linked usrbin i thinking work i compile correctly knows use gcc installing instead gcc however i know found something explain passing argument use particular gcc i want avoid overriding system defaults possible,1 equivalent code httpdocspythonorglibraryitertoolshtmlitertoolsproduct def productargs kwds product abcd xy ax ay bx by cx cy dx dy productrange repeat pools maptuple args kwdsget repeat result pool pools result xy x result pool prod result yield tupleprod,i python script uses itertoolsproduct i need able run machine python installed since itertoolsproduct new python i longer access function how i emulate itertoolsproduct python pythonic way,3 i familiar python per docs this function equivalent following code except actual implementation build intermediate results memory def productargs kwds product abcd xy ax ay bx by cx cy dx dy productrange repeat pools maptuple args kwdsget repeat result pool pools result xy x result pool prod result yield tupleprod,i python script uses itertoolsproduct i need able run machine python installed since itertoolsproduct new python i longer access function how i emulate itertoolsproduct python pythonic way,3 your init function module needs call importarray void pyinitmoduletrace tracemethods it mentions tutorial near top easy miss without segfaults pyarraycontiguousfromobject,i trying understand python c api works i want exchange numpy arrays python c extension so i started tutorial httpdsnrajplnasagovsoftwarepythonnumpydocnumpyhtml tried first example c module calculates trace numpy array neat since i want elementary operations arrays also include pythonh include numericarrayobjecth includestdioh int main pyinitialize importarray static char doc this c extension xormasking routine static pyobject tracepyobject self pyobject args pyobject input pyarrayobject array double sum int n pyargparsetupleargs o ampinput return null array pyarrayobject pyarraycontiguousfromobjectinput pyarraydouble array null return null n arraydimensions n arraydimensions n arraydimensions sum n sum double arraydata iarraystrides iarraystrides pydecrefarray return pyfloatfromdoublesum static pymethoddef tracemethods trace trace methvarargs doc null null null pymodinitfunc inittracevoid void pyinitmoduletrace tracemethods the module name trace compiled setuppy file distutilscore import setup extension module extension trace sources xormaskingcpp setupname trace test version extmodules module the file compiled traceso imported ipython i try use method trace i get segmentation fault i know i run fedora python gcc numpy,3 you could create kind flash uploader uploads chunk time file request short instead make several when last chunk uploaded call script merges chunks one file a simple googling gave httpwwwpluploadcom,i set php settings phpini file allow file sizes mb max times minutes the problem i hosting account i use killing scripts within seconds script restrictions all scripts following memory run time limitations memory some php cms applications may need larger memorylimit default set phpini you may change limit phpini however exceed maximum m run time all phpcgiperl scripts limited seconds run time if script complete time killed bluedomino cannot allow custom scripts impact performance customer sites shared hosting platform i currently flash uploader i created sends data php processing i works perfectly files take less minute fails takes longer minute is another ways around problem maybe using different programming language like python,2 you avoid serialization shared memory there bytes wire you could use library hides eg execnet module usrbinenv python import execnet gw execnetmakegatewaysshuserhost channel gwremoteexec import dbus sys bus dbussystembus remoteobject busgetobject daemonlocation daemon controller dbusinterfaceremoteobject daemonpath channelsendcontrollergetvalue tuple channelreceive print tuple print tuple but easy parse simple tuple values using astliteraleval stdlib fabfilepy import ast fabricapi import run def getcontroller return controller value cmd import dbus sys bus dbussystembus remoteobject busgetobject daemonlocation daemon controller dbusinterfaceremoteobject daemonpath print reprcontrollergetvalue note must escape quotation marks output run python c cmd tuple astliteralevaloutput print tuple example fab getcontroller h userhost here i used fabric run command remote host you could use json serialization format end produce python literals import json jsondumpst jsonloads u,i writing script needs take advantage java daemon via local dbus linux machines run this daemon particular return array tuples i want i parse throughuse information later code i want code take value multiple machines problem way i see really take returnexit values terminal i ssh ed parsing stdout output i want i much prefer get actual variable right i import os message import dbus sysnbusdbussystembusnremoteobjectbusgetobject daemonlocation daemon ncontrollerdbusinterfaceremoteobject daemonpath nsysexitcontrollergetvalue x ossystem echo e ssh python message ip in example i run controllergetvalue returns array tuples i trying figure way get array when using something like popen pipes output stdout file returns way get string equivalent array what i trying figure get actual array as pass variable returned exiting ssh tty code any ideas,1 it actually really difficult terminate single python request thread multithread application the best make decision shutdown whole process restart because action disrupt concurrent requests would result really need restrict single threaded configuration even support modwsgi x ideal there inactivitytimeout daemon mode actually causes process restarted two situations the first requests process idle the second request threads blocked timeout expires in modwsgi x repository trunk time two concepts separated inactivitytimeout applies completely idle process concurrent requests a new blockedtimeout added separately specific timeout whole process blocked it latter one use if want learn new option need go modwsgi mailing list discusss,i got setup apache modwsgi running django code i like add layer protection case nonterminating view slips something killsoff requests exceeding say seconds would ideal for testing i put timesleep view i tried timeout setting apache i still get curl returning seconds i see modwsgi offers three different timeout values none seem apply longrunning request is standard piece django middleware knob i missing apache modwsgi,3 first set test document open parser beautifulsoup beautifulsoup import beautifulsoup doc htmlbodydiva hrefsomethingyepadivdiva hrefhttpwwwnhlcomiceboxscorehtmidsomelinkadiva hrefhttpwwwnhlcomiceboxscorehtmidanotherabodyhtml soup beautifulsoupdoc print soupprettify html body div hrefsomething yep div div hrefhttpwwwnhlcomiceboxscorehtmid somelink div hrefhttpwwwnhlcomiceboxscorehtmid another body html next search tags href attribute starting httpwwwnhlcomiceboxscorehtmid you use regular expression import soupfindall hrefrecompile httpwwwnhlcomiceboxscorehtmid hrefhttpwwwnhlcomiceboxscorehtmidsomelinka hrefhttpwwwnhlcomiceboxscorehtmidanothera,hi i cannot figure find links begin certain text life findall works fine way much i want make list links begin httpwwwnhlcomiceboxscorehtmid can anyone help thank much,3 here something i used load g mysql dump file loads via subprocess stay away shelltrue not secure start process wasting resources import subprocess fhandle none cmd mysqlpath u mysqluser p mysqlpass h host database fhandle opendumpfile r p subprocesspopencmd stdinfhandle stdoutsubprocesspipe stderrsubprocesspipe stdoutstderr pcommunicate fhandleclose,i kind struggling understand python way solving simple problem my problem quite simple if use follwing code hang this well documented subprocess module doc import subprocess proc subprocesspopen cat stdinsubprocesspipe stdoutsubprocesspipe range procstdinwrite dn output proccommunicate print output searching solution insightful thread i lost i found solution among others uses explicit fork import os import sys subprocess import popen pipe def producetosed range tosedwritedn tosedflush would happen implicitly anyway example tosedclose def consumefromsed res fromsedreadline res sysexit sysexitprocpoll print received res def main proc popen cat stdinpipestdoutpipe tosed procstdin fromsed procstdout pid osfork pid fromsedclose producetosed return else tosedclose consumefromsed name main main while solution conceptually easy understand uses one process stuck low level compared subprocess module hide kind things i wondering simple clean solution using subprocess module hung implement patter i step back implement oldstyle select loop explicit fork thanks,1 you could use pyparsing your example looks much like sexpression sexpression parser examples section httppyparsingwikispacescomfileviewsexpparserpy,i glyph information font looks like character c t charwd r charht r comment krn c r krn c e r krn c r krn c r r krn c r krn c a r krn c u r is straightforward way parse python i used beautifulsoup requires nested tag tag like information it hard convert xml back seems like would reinventing wheel how would i get information data object i manipulate spit back,3 this convert data python data structure not sure looking character c t charwd r charht r comment krn c r krn c e r krn c r krn c r r krn c r krn c a r krn c u r resub resub sw evaltreplace,i glyph information font looks like character c t charwd r charht r comment krn c r krn c e r krn c r krn c r r krn c r krn c a r krn c u r is straightforward way parse python i used beautifulsoup requires nested tag tag like information it hard convert xml back seems like would reinventing wheel how would i get information data object i manipulate spit back,1 probably side effect underlying dbapi handler returns long everything import mysqldb dbmysqldbconnectdbtest c dbcursor cexecuteselect l the difference uses cosmetic there subtle differences one driver another instance sqlite return long query import sqlite db sqliteconnectmemory c dbcursor cexecuteselect sqlitecursor object xfcaed cexecuteselect fetchone,i wondering i get field db defined modelsintegerfield modelspy i getting long instead int eg i model eventschedule class eventschedulemodelsmodel monthlyday modelsintegerfielddefault db mysql describe teventschedule field type null key default extra monthlyday int no i create object retrieve back value db long e eventschedule emonthlyday esave e eventscheduleobjectsgetideid emonthlyday l i using djangoversion final platformpythonversion,2 for heck i performance testing def foon x xrangen xappendy def barn x none n xrangen xy def bazn this obviously silly could rangen way makes fairer test x xrangen timeittimeitlambdafoo number timeittimeitlambdabar number timeittimeitlambdabaz number timeittimeitlambdafoo number timeittimeitlambdabar number timeittimeitlambdabaz number,i looking python equivalent c vectorreserve i know big list going ahead time i know going fairly large i want avoid many resizings possible list grown inside deep inner loop the solution i come far cumbersome compared vectorreserve idiom that solution precreate list using nonek tracking size list separate counter appending setting items list need copying slice list fully constructed is alternative,1 as i pointed reply question others replied possible use different version python modwsgi my solution install setup gunicorn specific site needed different version python first i installed gunicorn usrlocalvirtualenvsmyexamplesitebinactivate pip install gunicorn then i setup launchdplist run gunicorn librarylaunchdaemonsmyexamplesitecomplist xml version encodingutf doctype plist public appledtd plist en httpwwwapplecomdtdspropertylistdtd plist version dict keylabelkeystringmyexamplesitecomstring keyenvironmentvariableskey dict keydjangosettingsmodulekeystringconfigsettingsstring dict keyusernamekeystringwwwstring keyprogramargumentskey array stringusrlocalvirtualenvsmyexamplesitebingunicorndjangostring stringbindstring array keyrunatloadkeytrue keystandarderrorpathkeystringvarloggunicornmyexamplesitecomerrorlogstring keystandardoutpathkeystringvarloggunicornmyexamplesitecomaccesslogstring dict plist next i setup nginx server media proxy gunicorn server server listen servername myexamplesitecom accesslog varlognginxmyexamplesitecomaccesslog errorlog varlognginxmyexamplesitecomerrorlog location faviconico return location static root pathtositeroot location media root pathtositeroot location proxypass http proxyredirect proxysetheader host host proxysetheader xrealip remoteaddr proxysetheader xforwardedfor proxyaddxforwardedfor clientmaxbodysize,problem discription the issues i i try load django website using modwsgi python virtualenv i get error i go site browser when i look error created apache log i get following tue oct error client modwsgi pid exception occurred processing wsgi script volumesontariositesemailsconfigapachedevemailswenatcheeworldcomwsgi tue oct error client traceback recent call last tue oct error client file librarypythonsitepackagesdjangopyeggdjangocorehandlerswsgipy line call tue oct error client selfloadmiddleware tue oct error client file librarypythonsitepackagesdjangopyeggdjangocorehandlersbasepy line loadmiddleware tue oct error client middlewarepath settingsmiddlewareclasses tue oct error client file librarypythonsitepackagesdjangopyeggdjangoutilsfunctionalpy line getattr tue oct error client selfsetup tue oct error client file librarypythonsitepackagesdjangopyeggdjangoconfinitpy line setup tue oct error client selfwrapped settingssettingsmodule tue oct error client file librarypythonsitepackagesdjangopyeggdjangoconfinitpy line init tue oct error client raise importerrorcould import settings is syspath does syntax errors selfsettingsmodule e tue oct error client importerror could import settings configsettings is syspath does syntax errors no module named configsettings the traceback make sense files getting loaded global python library virtualenv setup information i installed python os x server running os x i installed python using python mac os x bit ippc installer the server currently virtualenv installed i setup virtualenv using new website using following cd usrlocalvirtualenvs virtualenv nositepackages p usrlocalbinpython devemails i install nessary python packages when i run pip freeze output pip freeze django pil south amqplib anyjson boto celery djangocelery djangocompressor djangograppelli djangopicklefield feedparser htmltext kombu lxml psycopg pyparsing pythondateutil pythonsendgriddev redis requests wsgiref trouble shooting steps i created script called pathtestpy order test virtualenv path import os import sys activate python virtual enviroment activatethis usrlocalvirtualenvsdevemailsbinactivatethispy execfileactivatethis dictfileactivatethis start django import djangocorehandlerswsgi osenviron djangosettingsmodule configsettings p syspath print p application djangocorehandlerswsgiwsgihandler when i run script using python pathtestpy i get following output usrlocalvirtualenvsdevemailslibpythonsitepackages volumesontariositesemailsbin librarypythonsitepackagesmysqlpythonpymacosxiegg librarypythonsitepackagesparamikopyegg librarypythonsitepackagessimplejsonpymacosxiegg librarypythonsitepackagespythonldappymacosxiegg librarypythonsitepackageslxmlpymacosxiegg librarypythonsitepackagespytzhpyegg librarypythonsitepackagespythonopenidpyegg librarypythonsitepackagesmarkdownpyegg librarypythonsitepackagesdjangoauthopenidpyegg librarypythonsitepackagesdjangopyegg librarypythonsitepackagesdjangoprofilespyegg librarypythonsitepackagesdjangoopenidconsumerpyegg librarypythonsitepackagessetuptoolscpyegg librarypythonsitepackagesipythonpyegg librarypythonsitepackageshttplibpyegg librarypythonsitepackagesguesslanguagepyegg librarypythonsitepackagesdjangoratingspyegg librarypythonsitepackagespippyegg systemlibraryframeworkspythonframeworkversionslibpythonzip systemlibraryframeworkspythonframeworkversionslibpython systemlibraryframeworkspythonframeworkversionslibpythonplatdarwin systemlibraryframeworkspythonframeworkversionslibpythonplatmac systemlibraryframeworkspythonframeworkversionslibpythonplatmaclibscriptpackages systemlibraryframeworkspythonframeworkversionsextraslibpython systemlibraryframeworkspythonframeworkversionslibpythonlibtk systemlibraryframeworkspythonframeworkversionslibpythonlibdynload librarypythonsitepackages librarypythonsitepackagespil systemlibraryframeworkspythonframeworkversionsextraslibpythonpyobjc if i activate virtualenv first using source pathtovirtualenvbinactivate run python pathtestpy i get following output usrlocalvirtualenvsdevemailslibpythonsitepackagessetuptoolscpyegg usrlocalvirtualenvsdevemailslibpythonsitepackagespippyegg usrlocalvirtualenvsdevemailslibpythonsitepackageslxmlpymacosxintelegg usrlocalvirtualenvsdevemailslibpythonsitepackages usrlocalvirtualenvsdevemailslibpythonsitepackagespil volumesontariositesemailsbin volumesontariolocalvirtualenvsdevemailslibpythonsitepackagessetuptoolscpyegg volumesontariolocalvirtualenvsdevemailslibpythonsitepackagespippyegg volumesontariolocalvirtualenvsdevemailslibpythonsitepackageslxmlpymacosxintelegg volumesontariolocalvirtualenvsdevemailslibpythonzip volumesontariolocalvirtualenvsdevemailslibpython volumesontariolocalvirtualenvsdevemailslibpythonplatdarwin volumesontariolocalvirtualenvsdevemailslibpythonplatmac volumesontariolocalvirtualenvsdevemailslibpythonplatmaclibscriptpackages volumesontariolocalvirtualenvsdevemailslibpythonlibtk volumesontariolocalvirtualenvsdevemailslibpythonlibold volumesontariolocalvirtualenvsdevemailslibpythonlibdynload libraryframeworkspythonframeworkversionslibpython libraryframeworkspythonframeworkversionslibpythonplatdarwin libraryframeworkspythonframeworkversionslibpythonlibtk libraryframeworkspythonframeworkversionslibpythonplatmac libraryframeworkspythonframeworkversionslibpythonplatmaclibscriptpackages volumesontariolocalvirtualenvsdevemailslibpythonsitepackages volumesontariolocalvirtualenvsdevemailslibpythonsitepackagespil volumesontariositesemails at point i pretty sure problem activatethispy virtualenv setting correct syspath,1 use getattr function prints getattrfst,i want check imported names code import fst empty file fstpy dirfst prints got string symbolic names output builtins cached doc file name package now i want check values defined name code printbuiltins printcached printdoc printfile printname printpackage question how i extract symbolic name string supposed code import fst empty file fstpy dirfst prints strtosyms call equal strname name,1 use getattr dirfst print getattrfst,i want check imported names code import fst empty file fstpy dirfst prints got string symbolic names output builtins cached doc file name package now i want check values defined name code printbuiltins printcached printdoc printfile printname printpackage question how i extract symbolic name string supposed code import fst empty file fstpy dirfst prints strtosyms call equal strname name,1 i think need change javascript make start file download see question amp answer starting file download javascript,problem overview i creating djangobased client intent returning data web service the goal project return data user web service based values selected user form upon form submit query string generated sent web service page data returned string currently data displayed user browser i want provide functionality would allow user click button download data question how could i return data user click button browser download how i make different options data available ie applicationjson textcsv current notworking implementation i attempting failing following viewspy returning rendertoresponse object template to template i pass form data various forms def viewrequest do stuff get data string get data needed formats see utilspy jsondata jsontojsonfiledatastring filename return rendertoresponse templatehtml someform aform regulardata stringdata jsondata jsondata utilspy contains functions take data string return response objects this part i unsure i correctly i call functions view get jsondata csvdata proper formats original data string def jsontojsonfiledatastring filename get data json thedata jsondumpsdatastring prepare return json file response httpresponsethedata mimetype applicationjson response contentdisposition attachment filename strfilename json return response return response templatehtml i currently passing responses template this i really lost yet begun find good solution i expect i need use javascript return variables jsondata csvdata user button clicked i attempted use onclick action anchor class using javascript return django variable response really working li class button href databuttons onclick javascriptalert test test li li class button href databuttons onclick javascript var jsondata return json li i put test part well test whether alert would work it however i click button json data nothing happens am i approaching completely wrong or something small i missing,1 you manipulate lists produced analysis class using python note pyinstaller toc format analysis exclude anything windows system dir abinaries x x abinaries ospathdirnamexstartswithcwindowssystem,i begun using pyinstaller pyexe however i rather quickly run problem how i exclude modules i want i view ones getting included single executable file i remove pyd dll files dll folder python installation pyinstaller find therefore include i really want modules get quite arduous i try edit spec file pyinstaller makes abinaries ssl pydoc but size file remained i conclude work so i see modules pyinstaller including i exclude i want,2 each qtguiqlistwidgetitem call creates new item what code first creating item adding list and odd position creating whole new item selecting without ever adding list you need make sure dealing one item time save result single qtguiqlistwidgetitem call variable operate range item qtguiqlistwidgetitemstri selfbuiltinpatternslistadditemitem selfbuiltinpatternslistsetitemselecteditem true,i barebones code i trying make items even example preselected inside qlistwidget where i going wrong pyqt import qtgui qtcore qt import sys class mainqtguiqwidget def initself parentnone qtguiqwidgetinitselfparent grid qtguiqgridlayout selfbuiltinpatternslist qtguiqlistwidget selfbuiltinpatternslistsetselectionmodeqtguiqabstractitemviewmultiselection range selfbuiltinpatternslistadditemqtguiqlistwidgetitemstri selfbuiltinpatternslistsetitemselectedqtguiqlistwidgetitemstritrue gridaddwidgetselfbuiltinpatternslist selfsetlayoutgrid name main app qtguiqapplicationsysargv gui main guishow guiraise sysexitappexec,1 i writing full application jython moment would highly recommend having java libraries disposal handy python syntax language features actually make using easier java i mostly talking swing check chapter gui applications jython book it lot comparisons like look java code look reduced python code half length the caveats i found jython development tends run slightly behind python annoying find cool way something python discover supported current jython version occasionally might hiccups interface python java i couple unsolved problems although always workarounds kind thing distribution simple could although figure fairly painless i recommend following method it essentially consists exploding jythonjar adding modules writing compiling small java class creates python interpreter loads python modules creating executable jar file consisting jythonjar modules python modules java class,i recently started learning python not yet ventured coding during one learning sessions came accross term jython i googled amp got information i would like know anyone implemented realworld program using jython,3 in general possible however possible types implemented c instead python unfortunately applies oftenused standard python interpreter builtin types if define class python see works fine class myobjectobject pass b myobject bfoo bar,is possible add attributes object outside scope ie the following code doesnt works i i intended code b object bfoo bar,3 instances object featureless design magic methods dict getterssetters iteration etc dictate default behaviors might expect types in order work must subclass object first class fooobject pass f foo fbar omgwtf,is possible add attributes object outside scope ie the following code doesnt works i i intended code b object bfoo bar,3 you import random module call randomrandom get random sample you double subtract get sample draw values way tuple uniform draw cube,how i generate uniformly distributed data python eg dimension like i know generate uniformly distributed data like nprandomrandnn dimension thing confused lot,1 assuming independence individual coordinates following generate random point nprandomrandomd the following generate n observations row observation nprandomrandomn,how i generate uniformly distributed data python eg dimension like i know generate uniformly distributed data like nprandomrandnn dimension thing confused lot,2 sage integer class uses gmp mpir automatically if trying use gmp independently sage look gmpy disclaimer i maintainer gmpy,i already installed gmp library now want import library sage project tried put import libgmpxxso libgmpxxsopathappend usrlocallib nt work unfortunately regards,1 are using serialprint serialprintln arduino code if former going issue carriage return serreadline code waiting one,i using arduino uno basic digitalreadserial setup outlined httparduinoccentutorialdigitalreadserial if use serial monitor included arduino ide immediately displays changes pressing button this want pyserial either depending whether button pressed eventually trigger timer test threw together prettiest seems read pushbutton state second delay import serial ser serialserial sersetportcom serbaudrate seropen serreadline does anyone ideas,1 import code codeinteractiveinterpreterlocallocals spawn interpreter appropriate local variables you probably want spawn interactive console also able kinds processing gui application though maybe get away use threads instead allow user type commands textbox send interpreter object alternatively perhaps way make codeinteractiveconsole interactiveinterpreter threadhappy,i developed pyqt application analysing delimited log files containing numeric data is way easily add something like console application users access objects data created application perform type arbitrary commands using scipy numpy,1 try newsobjectsfiltercreatedbyagencypositionidyouragencyid,i models class agencypositionmodelsmodel agencymodelsforeignkeyagency usersmodelsmanytomanyfielduser positiontypecodemodelsforeignkeypositiontype phonenumbermodelscharfieldmaxlength emailmodelscharfieldmaxlength statustypecodemodelsforeignkeystatustype class newsmodelsmodel categorymodelsforeignkeycategory titlemodelscharfieldmaxlength descriptionmodelstextfield createdbymodelsforeignkeyusereditablefalse actiondatemodelsdatetimefieldautonowtrueeditablefalse i wanna user enter name agency i select top news belong specific agencynews model createdby fieldcreatedby field user insert newsin agencyposition i determine user belong agency i viewspy agnagencyobjectsfilternamekey agencypositionlistagencypositionobjectsfilteragencyagn i users specific agencythen i wanna select news createdby field specific agencysome thing like pseudo code select top news createdby inagencypositionlistusers how i,1 the expression pazb probably think match character number word boundary absolutely everything which swallows everything terminating png png,i regular expression pattern follows bpcoreazbpextrabxxpng to match strings follows ui screen f round tab reflection xpxpng in python i get following result u core u f round tab reflection xpx u extra none instead u core u f round tab reflection u extra u xpx as far i kown regex quantifier greedy default python so i think work what i wrong,1 add first greedy import x ui screen f round tab reflection xpxpng researchr bpcoreazbpextrabxxpng xgroups output f round tab reflection xpx,i regular expression pattern follows bpcoreazbpextrabxxpng to match strings follows ui screen f round tab reflection xpxpng in python i get following result u core u f round tab reflection xpx u extra none instead u core u f round tab reflection u extra u xpx as far i kown regex quantifier greedy default python so i think work what i wrong,1 how embedding ipython application httpipythonorgipythondocstableinteractivereferencehtmlembedding,i developed pyqt application analysing delimited log files containing numeric data is way easily add something like console application users access objects data created application perform type arbitrary commands using scipy numpy,1 the two main problems amber approach slow basically runs query value behind scenes maxes values query i wrote blog post question it explains best scalable way basically or query app engine you use separate entity make happen see post details httptornbluecompostappenginehowtodoanefficientorquery,can anyone share approach query appengine let say i class adbmodeldbmodel valuea dblistpropertybasestring valuea i aaa aaa bbb bbb ccc i would like return result valuea match aaa bbb return duplicated result,1 you use optionparseraddoption addoptiongroup think complete example spirit note relies commaseparating values makes easier instead using space separation would require quoting option values also note check optionssearchand optionsfilename explicitly instead checking length args optparse import optionparser def main usage useage prog options parser optionparserusage parseraddoptiona typestring destsearchand helpfind all lines file word and word parseraddoptionf file typestring destfilename helpname file options args parserparseargs optionssearchand none optionsfilename none parsererrornot enough number arguments words optionssearchandsplit lines openoptionsfilenamereadlines idx line enumeratelines word words wordlower linelower print the word found line word idx name main main using example invoke script python scriptpy f filenametxt hellosimple,trying learn use outparse so situation i think i got setup correct set options kinda confusing basically i want check filename see specific strings for example python scriptpy f filenametxt hello simple i want return something like reading filenametxt the word hello found line the word simple found line here i far i know set correctly sorry asking silly questions p thanks advance here code thus far optparse import optionparser def main usage useage prog options arg arg parser optionparserusage parseraddoptiongroupa actionstore typestring destsearchand helpfind all lines file word and word options args parserparseargs lenargs parsererrornot enough number arguments not sure set options name main main,1 usrbinenv python urllib import urlencode urlparse import urlparse urlunparse parseqs url httpexamplecomatextampqtextampqtextampqtext u urlparseurl query parseqsuquery querypop q none u ureplacequeryurlencodequery true printurlunparseu,example httpexamplecomatextampqtextampqtextampqtext after removing q return httpexamplecomqtextampqtext in case multiple q removed thank,3 import cgi import urlparse url httpexamplecomatextampqtextampqtextampqtext qs cgiparseqsurlparseurlparseurl delqs q print qs explicitly import cgi import urlparse url httpexamplecomatextampqtextampqtextampqtext qs cgiparseqsurlparseurlparseurl delqs q print qs text q text,example httpexamplecomatextampqtextampqtextampqtext after removing q return httpexamplecomqtextampqtext in case multiple q removed thank,1 you use ssh keepalives problem remote shell way knowing default ssh session killed keepalives enable remote shell detect killed session client paramikosshclient clientloadsystemhostkeys clientconnect someserver username victorhooi password blahblah transport clientgettransport transportsetkeepalive carry usual set keepalive value low like even second several seconds remote shell see ssh login died terminate processes spawned,i using paramiko tail f file remote server previously running via ssh proved flaky caused issues remote scheduling system my question kill tail script catches sigint my script based longrunning ssh commands python paramiko module end usrbinenv python import paramiko import select client paramikosshclient clientloadsystemhostkeys clientconnect someserver username victorhooi password blahblah transport clientgettransport channel transportopensession channelexeccommandtail f homevictorhooimacbethtxt true try rl wl xl selectselectchannel lenrl must stdout print channelrecv except keyboardinterrupt printcaught controlc clientclose channelclose exit the script catches ctrlc successfully ends however leaves tail f process running remote system neither clientclose channelclose seem terminate what command i issue except block kill the remote server running solaris,2 i able run code problems i fixed indentation error def encryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring here demo httpcodepadorgeaaihujz i would also rewrite code follows encryption misnomer def rotatecharch key ch z neword ordch ord key return chrneword ord elif a ch z neword ordch ord a key return chrneword ord a else return ch def rotatestringst key return joinrotatecharc key c st def derotatestringst key return joinrotatecharc key c st demo python python finally i strongly advise using kind encryption anything requires real security,i searched found similar question syntax error trying define multiple functions python question really answered i getting syntax error second def my indentation may messed i cannot figure formatting placebut correct program indentation issue def encryptcharch key neword ordch key ordch neword ordch elif ordch neword neword neword elif neword neword neword newch chrneword return newch def encryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring def decryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring i guessing something functions top level but i fix this python i could include top function inside i still left top level thanks help,2 i get syntax error start function end def encryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring your return statement indented one space rest function causing indentationerror if sure error beginning code another possibility stack overflow automatically converts tabs spaces code post if mixing tabs spaces may created indentation error invisible if want try fix manually text editors feature replaces tabs spaces copy code post back program,i searched found similar question syntax error trying define multiple functions python question really answered i getting syntax error second def my indentation may messed i cannot figure formatting placebut correct program indentation issue def encryptcharch key neword ordch key ordch neword ordch elif ordch neword neword neword elif neword neword neword newch chrneword return newch def encryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring def decryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring i guessing something functions top level but i fix this python i could include top function inside i still left top level thanks help,1 the error message says exactly wrong file testpy line return newstring indentationerror unindent match outer indentation level on line return newstring indentation level match previous indentation level rangelenstring line you need fix indentation whole—use constant indentation level eg spaces throughout code be consistent right indentation place—every time indent different level secondly use name string variable string also name standard python module unable use module code confuse people reading code also use str since name builtin function,i searched found similar question syntax error trying define multiple functions python question really answered i getting syntax error second def my indentation may messed i cannot figure formatting placebut correct program indentation issue def encryptcharch key neword ordch key ordch neword ordch elif ordch neword neword neword elif neword neword neword newch chrneword return newch def encryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring def decryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring i guessing something functions top level but i fix this python i could include top function inside i still left top level thanks help,1 the problem return newstring indentation level characters match earlier line level characters try using editor makes easy always type space tabs writing python painful line everything hand keep running errors like,i searched found similar question syntax error trying define multiple functions python question really answered i getting syntax error second def my indentation may messed i cannot figure formatting placebut correct program indentation issue def encryptcharch key neword ordch key ordch neword ordch elif ordch neword neword neword elif neword neword neword newch chrneword return newch def encryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring def decryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring i guessing something functions top level but i fix this python i could include top function inside i still left top level thanks help,1 i know copy paster error indentation kind messed try using mine see problem def encryptcharch key neword ordch key ordch neword ordch elif ordch neword neword neword elif neword neword neword newch chrneword return newch def encryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring def decryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring,i searched found similar question syntax error trying define multiple functions python question really answered i getting syntax error second def my indentation may messed i cannot figure formatting placebut correct program indentation issue def encryptcharch key neword ordch key ordch neword ordch elif ordch neword neword neword elif neword neword neword newch chrneword return newch def encryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring def decryptstringstring key newstring rangelenstring newstring encryptcharstringi key return newstring i guessing something functions top level but i fix this python i could include top function inside i still left top level thanks help,1 if trying find questions answers questionobjectsfilteranswerisnullfalsedistinct,i relationship follow class questionmodelsmodel qid modelspositiveintegerfieldprimarykeytrue content modelscharfieldmaxlength class answermodelsmodel answerid modelspositiveintegerfieldprimarykeytrue content modelscharfieldmaxlength question modelsforeignkeyquestion i want find questions answer how i please help solve problem thank much,1 see helps picked form httpnetbeansorgbugzillashowbugcgiid simple fix module fixed from httpblogsoraclecomgridbagentrydisablinganetbeanspluginbefore modify cusersyourusernetbeansconfigmodulesorgnetbeansmodulesphpsmartyxml line false param nameenabledtrueparam,i went tools plugins then chose install three python items show after installation i choose restart netbeans option but instead restarting netbeans closed and opening any ideas fix i normally develop java netbeans install i using mac osx i see takers let ask is way revert new plugin install,1 httpcherrypyreadthedocsorgenlatestconfightml excellent place start,i trying use httptoolscherrypyorgwikimako it says i need twoconfig options toolsmakocollectionsize toolsmakodirectories pathtotemplates i specify options i specify options,1 table field b xxxobjectsfiltera updateb info xxxobjectsfiltera item info itemb itemsave,mysql db table xxx id i got query result mysql database info xxxobjectsfiltera item info itemupdateb it makes error xxx attribute update i want append keyvalue set item how i go,2 item mapping if want set attributes object itemb note django retain change unless already field model make sure save item,mysql db table xxx id i got query result mysql database info xxxobjectsfiltera item info itemupdateb it makes error xxx attribute update i want append keyvalue set item how i go,1 you certainly want pil import image im imageopen sthjpg outfile sthjpg regionimcrop do operations want region im regionsaveoutfile jpeg,i following line code image cropping im imageopen pathtoimagejpg outfile pathtodestimgjpg imcopy imcrop imthumbnailsize imageantialias imsaveoutfile jpeg but seems cropping image i bigger image size eg x px edited here solution i could answer question adding answer actually crop return image new handler i realized i make mistake i assign crop new handler bellow cropimg imcrop complete code im imageopen pathtoimagejpg outfile pathtodestimgjpg imcopy cropimg imcrop cropimgthumbnailsize imageantialias cropimgsaveoutfile jpeg notice crop line cropimg handler used,1 when want try catch without handling exception python this help print exception ie try catch without handling exception print exception import sys try dosomething except print unexpected error sysexcinfo reg tilokchan,when want tryexcept without handling exception python is following right way try shutilrmtree path except pass,3 you forgotten assign return values statements im imageopen pathtoimagejpg outfile pathtodestimgjpg im imcrop im imthumbnailsize imageantialias imsaveoutfile jpeg,i following line code image cropping im imageopen pathtoimagejpg outfile pathtodestimgjpg imcopy imcrop imthumbnailsize imageantialias imsaveoutfile jpeg but seems cropping image i bigger image size eg x px edited here solution i could answer question adding answer actually crop return image new handler i realized i make mistake i assign crop new handler bellow cropimg imcrop complete code im imageopen pathtoimagejpg outfile pathtodestimgjpg imcopy cropimg imcrop cropimgthumbnailsize imageantialias cropimgsaveoutfile jpeg notice crop line cropimg handler used,2 this happens time extra variable becomes tuple change lines datau currentuser selfcurrentuser datau username selfcurrentusername,for reason variable currentusername display anything variable username displays instead niklas r displays u niklas r page i render django here method basehandler i hope tell wrong def renderself name data render template data data datau jsconf jsondumps u appid facebookconffacebookappid u canvasname facebookconffacebookcanvasname u useridonserver selfuseruserid selfuser else none datau loggedinuser selfuser datau message selfgetmessage datau csrftoken selfcsrftoken datau canvasname facebookconffacebookcanvasname loggingdebug user object strselfcurrentuser datau currentuser selfcurrentuser datau username selfcurrentusername datau facebookappid facebookappid selfresponseoutwritetemplaterender ospathjoin ospathdirnamefile templates name html data,1 imap rfc in search keys use strings message matches key string substring field the matching caseinsensitive so need search without almost similar result get securitywebsite,is possible use wildcards searching specific sender imap folder typ data msearchnone securitywebsite,2 evaluating results tuple as discovered tuples immutable convert list processing,i writing simple sort program python encounter error i want swap list elements returns error i attaching error program question listi listi typeerror tuple object support item assignment def mysortlist index rangelenlist valuelistindex iindex valuelisti listi listi listivalue ii else break return inputlistevalinputenter list items mysortinputlist printinputlist,3 the problem using empty regex match anything including empty url handle include directive if always append first slash request path considering pnasserurls contain regex match request mysitecom if want mysitecom mysitecom take pnasser index view need something like djangocontrib import admin pnasserviews import index adminautodiscover urlpatterns patterns r index r pnasser include pnasserurls r admin includeadminsiteurls so mysitecom pnasserviewsindex mysitecom pnasserviewsindex mysitecomadmin admin page mysitecompnasser pnasserviewsindex mysitecompnasserhome pnasserviewshome if work make sure django commonmiddleware installed make appendslash true default need mess find settingspy file,i trying include additional urlspy inside main urls however seem working i done bunch searching i seem figure main urlspy file admin works fine djangoconfurlsdefaults import patterns include url djangocontrib import admin adminautodiscover urlpatterns patterns r pnasser include pnasserurls r admin includeadminsiteurls r include pnasserurls i folder pnasser file urlspy following djangoconfurlsdefaults import patterns include url urlpatterns patterns pnasserviews r index r login login r signup signup r insertaccount insertaccount r home home r updatepaccidd update r historypaccidd accounthistory r logoutpaccidd logout i sure i maybe missing something else configuration i visit mysitecomadmin loads admin correctly i goto mysite url views i get page found using urlconf defined mysiteurls django tried url patterns order pnasser admin the current url match edit settingspy installed apps installedapps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles uncomment next line enable admin djangocontribadmin uncomment next line enable admin documentation djangocontribadmindocs pnasser update so i also tried running site via dev server python managepy runserver works i assuming somewhere integration apache using modwsgi problem however i sure problem would,1 there several methods wxpython get colored text wxtextctrl wxterich wxterich styles wxstcstyledtextctrl wxrichtextrichtextctrl wxhtmlwindow inserting color tags text wxlistcrtl you get examples wxpython demo for example change fore background colors part wxtextcrtl rt wxtextctrlself my textsize stylewxtemultilinewxterich rtsetinsertionpoint rtsetstyle wxtextattrred blue wxrichtext also easy use write lines different colors rtc wxrichtextrichtextctrlself stylewxvscrollwxhscrollwxnoborder rtcbegintextcolour rtcwritetextthis color red rtcendtextcolour rtcnewline as indicated answer use wxlistcrtl straighforward method work lines text instead multiline text,i multiline wxtextctrl object i set forground background colors writing stringsi need write different lines different colors wxtextctrlsetforgroundcolor changes previous lines colors wellis way around,3 you use reportlab tutorial and could installed easyinstall,so i university student part time job i python experience anyway i thought i try impress boss making form generator my job go kart place need people fill bunch safety information aim gui webpage computer write name details produce form information sign i look around noticed quite tools i sure explicitly i want looking quite complicated i made simple gui ideally i html page can anyone offer advice go thanks ps i know place mostly code i apologise i broken etiquette making style post,1 mode vowels printlenfilterlambda x x vowels word else printlenfilterlambda x x consonants word so i timed eumiro solution his better vclambda sumwordcountc c vowels vclambda lenfilterlambda x x vowels word timeittimeitvc number timeittimeitvc number,i freshman college taking python coding class currently i working making program count amount vowels consonants based user input determine mode currently i made two lists i trying find program python count vowelsconsonants this i far please keep mind i worked ends center counting goes zane blalock vowelconsonants counter printwelcome vc counter make list vowels listaeiouy consonants listbcdfghjklmnpqrstvexz complete false complete false mode inputwhat mode would like vowels consonants lowerstrip print printyou chose mode strmode print mode vowels word inputplease input word printyour word strword print choice inputare done yn lowerstrip choice complete true else printok back top elif mode consonants word inputplease input word printyour word strword print choice inputare done yn lowerstrip choice complete true else printok back top else printimproper mode please input correct one printthank using program,2 numberofconsonants sumwordcountc c consonants numberofvowels sumwordcountc c vowels,i freshman college taking python coding class currently i working making program count amount vowels consonants based user input determine mode currently i made two lists i trying find program python count vowelsconsonants this i far please keep mind i worked ends center counting goes zane blalock vowelconsonants counter printwelcome vc counter make list vowels listaeiouy consonants listbcdfghjklmnpqrstvexz complete false complete false mode inputwhat mode would like vowels consonants lowerstrip print printyou chose mode strmode print mode vowels word inputplease input word printyour word strword print choice inputare done yn lowerstrip choice complete true else printok back top elif mode consonants word inputplease input word printyour word strword print choice inputare done yn lowerstrip choice complete true else printok back top else printimproper mode please input correct one printthank using program,3 using regex would alternative import refindall bcdfghjklmnpqrstvwxyz wont wovels result h r n b n v l n h r l if take length problem solved text text wovels aeiou consonants bcdfghjklmnpqrstvwxyz import findall wovelcount lenfindall wovels text consonatcount lenfindall consonants text,i freshman college taking python coding class currently i working making program count amount vowels consonants based user input determine mode currently i made two lists i trying find program python count vowelsconsonants this i far please keep mind i worked ends center counting goes zane blalock vowelconsonants counter printwelcome vc counter make list vowels listaeiouy consonants listbcdfghjklmnpqrstvexz complete false complete false mode inputwhat mode would like vowels consonants lowerstrip print printyou chose mode strmode print mode vowels word inputplease input word printyour word strword print choice inputare done yn lowerstrip choice complete true else printok back top elif mode consonants word inputplease input word printyour word strword print choice inputare done yn lowerstrip choice complete true else printok back top else printimproper mode please input correct one printthank using program,1 so i managed using palette image type resulting file small i expected here code case useful someone else someone improve pil import image im imageopenimagepng imp imconvert rgb convert p paletteimageadaptive colors impputpalette index black background index blue index red im imageopenimagepng impl imconvert l need greyscale image create mask mask imageevalimpl lambda else imppaste mask paste color index using image mask impsave outpng transparency optimize save set index transparent,i wonder i could create image transparent background indexed colours red blue minimise file size more specifically i two black white images i want convert one transparent blue transparent red then i want merge images i could regular rgba image i really want colour indexed minimise file size ideally pil python library could also work,2 you use heapq noninteger elements tuples heapq import heap data ten three five seven nine two item data heappushheap item sorted heap sortedappendheappopheap print sorted datasort print data sorted,i need use priority queue python code looking around something efficient i came upon heapq it looks good seems specified integers i suppose works objects comparison operators specify comparison operators needs besides heapq seems implemented python fast are aware fast implementations priority queues python optimally i like queue generic ie work well object specified comparison operator thanks advance update re comparison heapq i either use priority object charlie martin suggests implement cmp object i still looking something faster heapq,3 magic don forget dll,in linux utility called “file” helps us determine identification file is python module job i prefer use subprocesspopen file blahblah platform dependent for instance windows “file” although downloaded,3 ignacio mentioned magic library could also standard library confident filename enough know file type extension import mimetypes mimetypesguesstype initpy textxpython none see mimetypes module standard library this however replacement actually inspecting content file figuring type,in linux utility called “file” helps us determine identification file is python module job i prefer use subprocesspopen file blahblah platform dependent for instance windows “file” although downloaded,1 it sounds like terrible idea def funcprefix g globals gprefix tomato gprefix broccoli whatever probably done dictionaries arrays objects way fragile like method,i using python trying create function look name object given argument among things create globals contain name example objectsomeclassargskwds object instance class given certain name egobject def somefuncsomeargument global tausomeargument global ronsomeargument etc variables i also would like assign variables etc tausomeargumentsomevalue ronsomeargumentsomevalue print ronsomeargument print tausomeargument i want happen i call function follows i call somefuncobject i would like create globals named tauobject ronobject assign values print statements irrelevant similarly called somefuncobject object another instance class i would like create globals tauobject ronobject moment function simply creates globals named tausomeargument obvious code now i read somewhere names python objects immutable unless class function i know reading i get feeling i may need use metaclasses feels like overly complicated way something relatively easy thanks advance,2 nothing joinstrx x slice slice,is opportunity join types using strjoin i class class sliceobject def initself start end selfstart start selfend end def strself return formatselfstart selfend def reprself return formatstrself what override perform kind code joinslice slice and get result like,3 edited hope answers comments i brief direct want impolite model validation form validation i guess rule thumb could long rule really associated model yes better validation model level for multiplemodel forms please checkout so question django multiple models one template using forms forgetting attached link slightly old still relevant dryest way achieve it long rediscuss no you derive form modelform perform model validation need call model validation b no if want validate model try save use fullclean modelform valid know model valid save and yes answers still apply even multimodel forms so still use modelform worry validating model modelform in general find plumbing django another simpler way the nd pointer get started actually simplify code lot,please help understand following choices i made idiomaticgood improve model validation form validation i prefer use new model validation form validation whenever possible seems dry fundamental way create rules data two examples simple calendarentry model start must end period must less endstart is idiomaticgood put model level put forms if modelform best answer case using multiple models form edit i realize multiple modelforms actually used together transferring model validation form modelform edit it turns reinventing plumbing model validation form validation necessary situation solutions show let assume moment model validation errors i directly transferred displayed directly user ie ignore translating model validation errors userfriendly form validation errors this one working way i came one place helper functions viewwithaform formisvalid instance save overridden fullclean optional exclusions try instancesave except validationerror e nfe emessagedictnonfielderrors one big question mark instanceerrors errorlistnfe big question mark seems unnatural formisvalid return response code standard format send user form new form errors model errors return form as commented code is idiomaticgood way transfer model errors form b is idiomaticgood way test new form errors note this example uses nonfield errors i think could equally apply field errors,2 the response function returning display pdf treated file attachment ie saved disk this line response contentdisposition attachment filenamerdbaxfdf tells browser file rdbaxfdf saved check whether printrdba function called if button name submitrdbaform requestposthaskey submitrdbaform false you may also try putting markup template file render template response instead this line django mtv philosophy modeltemplateview similar mvc application logic separated presentation better especially since plan add forms document xfdfhtml templates folder xml version encodingutf xfdf xmlnshttpnsadobecomxfdf xmlspacepreserve fields fields f hreffile targetblank xfdf new printrdba djangohttp import httpresponse djangotemplateloader import gettemplate djangotemplate import context def printrdbaclientnone datanone investmentformnone file mediafilesinvestmentformswhateverpdf response httpresponsemimetype applicationpdf response contentdisposition attachment filenamerdbaxfdf template gettemplatexfdfhtml xfdf templaterendercontextfilefile responsewritexfdf return response,i early process building pdf builder one fillable pdfs at point i trying display pdf i click print form button moment i get errors opens blank tab firefox here printrdba libtoolspy def printrdbaclientnone datanone investmentformnone djangohttp import httpresponse clientsmodels import transit productsmodels import productcategory import cstringio stringio dateutilparser import parse datetime import date settings import url import dateutilrelativedelta import relativedelta ratesmodels import interestoption productsmodels import product url mediafilesinvestmentformswhateverpdf file investmentform file url fdf xml version encodingutfnxfdf xmlnshttpnsadobecomxfdf xmlspacepreserventfields fdf fields f hrefs targetblank xfdf file fdf fdfreplace m response httpresponsefdfencodeiso mimetype applicationpdf response contentdisposition attachment filenamerdbaxfdf return response on views check make sure button pressed requestposthaskey submitrdbaform return printrdbaclientprimarymember data formdata now something else i missing i going using xfdf populate forms like i said i trouble pdf show thanks,2 i would probably use numpysavetxt yourfilemat yourarray python yourarray load yourfilemat matlab,i working python matlab right i d array python i need write file able read matlab matrix any ideas thanks,1 you could always peek sysargv list thus ordered simply iterate checking argument comes first use listindex see respective positions keywords list sysargv contains list words entered command line delimiter word space unless string surrounded quotation marks this means user entered something like myproggie resize sysargv would contain list like myproggie resize,i would like know get order optional argument passed commandline argparse i image processing class able apply different actions image like rotate crop resize and order actions applied often essential example want crop image resize i code parser argparseargumentparserdescription image processing arguments parseraddargument sourcefile help source file parseraddargument targetfile help target file parseraddargument resize nargs help resize image metavar width height parseraddargument rotate nargs help rotate image metavar angle parseraddargument crop nargs help crop image metavar startx starty width height ar parserparseargs print ar but matter order i pass parameters script cmdpy testjpg testjpg crop resize cmdpy testjpg testjpg resize crop namespace items always order alphabetical i suppose namespacecrop resize rotatenone sourcefile testjpg targetfile test jpg is way order position command line string get index,2 i assume row last inserted row globally cannot assume but related connection use select lastinsertid cursorconnectioninsertid maybe even cursorlastrowid i sure would work well,i inserting row using raw sql need get primary key newly inserted row i cannot assume nonpk inserted data unique i assume row last inserted row if possible using raw sql regular inserts i thinking i create new customid field altogether i would create random number variable insert unique id since i inserted i know but seems defeat purpose pk unique identifier is way pull next id sequence oracle insertsql insert mytabletitle text values title text cursor connectioncursor cursorexecuteinsertsql transactioncommitunlessmanaged,2 short answer code well defined order lefttoright long answer first let get terminology right unlike languages assignment python statement operator this means use assignment part another expression example j valid python code the assignment statement defined explicitly permit multiple assignment targets example ai each target list let leave aside where multiple assignment targets value assigned left right to quote documentation an assignment statement evaluates expression list remember single expression commaseparated list latter yielding tuple assigns single resulting object target lists left right,consider following python program ai printa ai printa i expected output but instead i got my question anything python language specification associativity assignment operator behavior example undefined all i able find expressions evaluated form left right except rvalue evaluated first case assignment help,3 iit hard make state machines haskell realize monads a state machine like one want arrow automaton arrow exact newtype state b state b state b this function takes input value produces output value along new version this monad cannot write join equivalently turned arrow realize impossible write arrowapply instance here instances import controlarrow import controlcategory import prelude hiding id instance category state id state x x id state f state g state x let g x z f z instance arrow state arr f let state x f x first state f state x x let f x x first have fun,i implemented simple state machine python import time def print return b def b print b return c def c print c return name main state true state state timesleep i wanted port c fast enough but c let make function returns function type i tried making function type typedef fnfn work i use structure instead now code ugly include stdioh include stdlibh include unistdh typedef struct fn struct fn fvoid fnt fnt avoid fnt bvoid fnt cvoid fnt avoid fnt f b voidprintfan return f fnt bvoid fnt f c voidprintfbn return f fnt cvoid fnt f voidprintfcn return f int mainvoid fnt state voidsleep state statef return exitsuccess so i figured problem c broken type system so i used language real type system haskell problem happens i something like type fn io fn fn print return b b fn b print b return c c fn c print c return i get error cycle type synonym declarations so i make wrapper way i c code like import controlmonad import systemposix data fn fn io fn io fn print return fn b b io fn b print b return fn c c io fn c print c return fn run foldm fn f sleep f fn repeat why hard make state machine statically typed language i make unnecessary overhead statically typed languages well dynamically typed languages problem is easier way statically typed language,2 the easiest solution import resubr lambda repdictmgroup yourtemplate not fast enough someone said use regex obey parsing template using code python would even complex slow forget written c,i long string template containing replacement points form mark occurences string single given marker i want replace markers controlled python dictionary contain signs markers like repdict title this title content here content the problem simple call replace method one one good solution previous replacement may contain one marks must replaced the solution fast enough since i large templates i need replace many within big loop i ugly long implementation many find counting offsets original string replacament process etc i hope much nicer compact quicker solution,2 q install required module pypcap using scapy windows possible exactly work box an install guide found httpwwwsecdevorgprojectsscapydocinstallationhtmlwindows i strongly recommend switch python make live much easier when insist compile require modules also key modules like pypcap patched compiled python see pycap patch here find guidance build modules q possible make python scripts depending scapy standalone windows applications yes while use pyexe build exe python code scapy uses winpcap install addition application,i like use scapy python v windows how i install required module pypcap python will possible make python scripts depending scapy standalone windows applications using distribution tool pyexe the particular python distribution i using enthought python distribution,3 ok well i done p popenopenssl verify capath capath crlcheckall stdin pipe stdout pipe stderr pipe message error pcommunicatecertificate verified ok message error message it i would chosen it passed tests i certain always work i know c well enough read openssl source code verify if anyone find situation would fail please comment,i trying verify x certificate using python in particular i need check crls i now use mcrypto i find option corresponding openssl crlcheck crlcheckall alternatively i could use pipe call openssl directly p popenopenssl verify capath capath crlcheckall stdin pipe stdout pipe stderr pipe message error pcommunicatecertificate exitcode preturncode however seems openssl verify always returns exit code i would compare strings somehow tell verification successful i prefer am i missing something simple thanks,1 fileinputinput uses global shared instance fileinputfileinput use class directly creating two instances work,for line filex i need scan lines filey i tried line fileinputinput filex dofunstuffline element fileinputinput filey processelementline but i get runtimeerror input already active i guess i specify second instance fileinput different first one,1 this work since fileinputinput creates global instance call twice manner trying why simply line open filex dofunstuffline element open filey processelementline,for line filex i need scan lines filey i tried line fileinputinput filex dofunstuffline element fileinputinput filey processelementline but i get runtimeerror input already active i guess i specify second instance fileinput different first one,2 using fileinput iterate multiple files easily unit seem gain anything iterate contents files separately one nice approach using itertoolsproduct import itertools open filex r f open filey r f line element itertoolsproductf f processelement line,for line filex i need scan lines filey i tried line fileinputinput filex dofunstuffline element fileinputinput filey processelementline but i get runtimeerror input already active i guess i specify second instance fileinput different first one,1 pyqtqtgui import qpainter yourqwebviewsetrenderhintsqpaintertextantialiasing qpaintersmoothpixmaptransform qpainterhighqualityantialiasing httpdocqtnokiacomsnapshotqwebviewhtmlrenderhintsprop,img width height src imagepng imagepng larger x i display webkit automatically resizes the problem quality poor my guess uses nearestneighbor algorithm something similar result leaves much desired is possible make use bicubic instead image quality significantly important speed case in contrast chrome much better resizing images i guess also uses webkit note i using qwebview widget pyqt example code python prefered i c programmer hard translate c python,1 you need make sure python installation directory path environment variable i thought activestate installer case seems problem you set path enviroment variable view advanced system settings enviroment variables just add python folder end list separated semicolon,i lots trouble getting python install system correctly i tried download activestate version httpwwwactivestatecomactivepythondownloads seems installed correctly i try run python terminal i keep getting message python recognized internalexternal command operable program batch file anyone know fix i google get answer windows xp thanks,1 razi i think constructing wrong relation ship your relation ship must book mm subject subject mm group so create one model group must assign mm subject your models like subjectbooks table subjectbooks basemetadata column subjectid integer foreignkey subjectsid column bookid integer foreignkey booksid subjectgroup table subjectgroups basemetadata column groupid integer foreignkey groupsid column subjectid integer foreignkey subjectsid class subjectbase tablename subjects id columninteger primarykeytrue value columnunicode uniquetrue groups relationship groups secondarysubjectgroups backref subjects class groupsbase tablename groups id columninteger primarykeytrue name columnunicode uniquetrue class bookbase tablename books id columninteger primarykeytrue title columnunicode isbn columnunicode subjects relationship subject secondarysubjectbooks backref books i also check docs attributemappedcollection but time i found key associated one object one if read anywhere please provide link i check fit code i think help,i created many many relationship sqlalchemy like subjectbooks table subjectbooks basemetadata column subjectid integer foreignkey subjectsid column bookid integer foreignkey booksid column group integer class subjectbase tablename subjects id columninteger primarykeytrue value columnunicode uniquetrue class bookbase tablename books id columninteger primarykeytrue title columnunicode isbn columnunicode subjects relationship subject secondarysubjectbooks collectionclassattributemappedcollection group backref books i created test like following book booktitle first book isbn test booksubjects subjectvalue first subject booksubjects subjectvalue second subject sessionaddbook transactioncommit works fine but i really want store one subject group value i tried following test book booktitle first book isbn test booksubjects subjectvalue first subject subjectvalue second subject booksubjects subjectvalue third subject subjectvalue forth subject sessionaddbook transactioncommit work can done using sqlalchemy thanks advance,2 using regular expressions way bad idea i navigate dom tree using real parser remove i wanted way,i parsing rss content using universal feed parser in description tag times i getting velues like this xml comment pthis test paragraphpbr bsample boldb mtablesampe textmtable inorder remove html elementstags i using following regex pattern recompileu ws redotall remultiline reignorecase reunicode desc patternsubu desc this helps remove html tags xml comments how i remove elemnts xml coments,2 using lxml import lxmlhtml lh content this xml comment pthis test paragraphpbr bsample boldb tablesampe texttable doclhfromstringcontent printdoctextcontent yields this test paragraph sample bold sampe text,i parsing rss content using universal feed parser in description tag times i getting velues like this xml comment pthis test paragraphpbr bsample boldb mtablesampe textmtable inorder remove html elementstags i using following regex pattern recompileu ws redotall remultiline reignorecase reunicode desc patternsubu desc this helps remove html tags xml comments how i remove elemnts xml coments,3 make row tuple list import numpy np x nparray o dtypenpdtype step int symbol s index int numpy developer robert kern explains as rule tuples considered scalar records lists recursed upon this rule helps numpyarray figure sequences records sequences recursed upon ie sequences create another dimension atomic elements,this gives error import numpy np x nparray o dtypenpdtype step int symbol s index int typeerror expected readable buffer object i know fail alternatlively i force something like statement work x nparray o xdtype npdtype step int symbol s index int xviewdtypenpdtype step int symbol s index int give valueerror new type compatible array edit if i try enter record tuple think triple single value rather three separate fields for instance import numpy np x nparray o dtypenpdtype step int symbol s index int seems fine i import numpylibrecfunctions rec recappendfieldsx x x index gives typeerror object type numpyint len presumably xshape rather,3 i found something stackoverflow solved problem this works provided executable option like help version outputs something returns exit status zero see suppress output python calls executables result end code snippet answer zero executable path else likely,in python portable simple way test executable program exists by simple i mean something like command would perfect i want search path manually something involving trying execute popen amp al see fails i imagine launchmissiles,1 as pointed randn produces normally distributed number aka gaussian to get uniformly distributed use uniform if want single sample time uniformly distributed numbers use import numpy np x nprandomuniformlowhighsize or like generate lots eg import numpy np x nprandomuniformlowhighsize now x x length,how i generate uniformly distributed data python eg dimension like i know generate uniformly distributed data like nprandomrandnn dimension thing confused lot,2 just make clear since i struggled understand the statement b c e equivalent e b e c e,consider following python program ai printa ai printa i expected output but instead i got my question anything python language specification associativity assignment operator behavior example undefined all i able find expressions evaluated form left right except rvalue evaluated first case assignment help,3 you use node rank force vertical level node this would insure things correct order north south you would preprocess mud map figure ranking you label group nodes rank you would process mud map determine group room nodes lie level northsouth direction example r r r rr for map could something like digraph m rr rr rr rr rr rr ranksamerr ranksamerrr i able find way force horizontal ordering this would mean eastwest would still possibly line correctly it may work time rank setup rooms help give context,i trying draw map mud i used python graphviz get something like httpimgimageshackusimgarraszpng as see locations going nsweupdown going location is possible graphviz draw map north locations south east locations right west locations i mean like e location w location n s location or maybe better tool draw automatically graphviz,1 there built way you set collection bindings override default behavior particularly easy thing it possible though since complete control bindings ie behavior hardcoded widget changed another solution bullet proof intercept lowlevel tkinter insert delete commands check condition for example see answer question httpstackoverflowcoma that answer provides general solution used prompt asked question tagging sections text readonly,code tkinter import class mainobject def initself selfconsole textroot relief groove cursor arrow spacing selfconsoleinsertinsert selfconsolefocusset selfscroll scrollbarroot cursor arrow commandselfconsoleyview selfconsoleconfigureyscrollcommandselfscrollset selfscrollpackfill side right selfconsolepackexpandtrue fill root tk rootgeometry sxsss rootoptionadd font courier bold rootresizable app main rootmainloop way make become unremovablelike idle example thanks advance,1 using sphinx sphinx documentation site httpsphinxpocooorgextautodochtml specialmembers privatemembers,i using sphinx documenting python project i autodoc extension enabled following docs autoclass classname members the problem documents nonprivate methods class how i include private methods,3 i think subgraphs see dotguide page rank property see dotguide page might methods better organize graph the following might alternative graphviz httpgephiorg provides python bindings newer versions even supports python scripting language inside app httpubietylabnetubigraphindexhtml produces nice d graphs controlled via python,i trying draw map mud i used python graphviz get something like httpimgimageshackusimgarraszpng as see locations going nsweupdown going location is possible graphviz draw map north locations south east locations right west locations i mean like e location w location n s location or maybe better tool draw automatically graphviz,1 try assertitemsequal docs class mytestcaseunittesttestcase def testmytestself selfassertitemsequala range,one unittests checks see range set correctly reading log file i like test var range however range range evaluates false python is straightforward way test equivalence ranges python,1 in python range returns iterable type range two range equal identical ie share id to test equality contents convert range list listrange listrange this works fine short ranges for long ranges charles g waldman solution better,one unittests checks see range set correctly reading log file i like test var range however range range evaluates false python is straightforward way test equivalence ranges python,3 people asked improving graphviz layout i think graphviz overkill if standard mud layout like got fairly strong constraints rooms graphviz know constraints good job simple algorithm like pick starting location grid traverse room using eg depthfirst traversal move one unit n s e w new room if want write visualization code could perhaps approach preprocessing step graphviz using way assigning ranks room then hopefully graphviz would produce correct output edit example pseudocode visitinitialroom def visitcurroom curx cury curroom null return print room curroom location curx cury visitcurroomnorthneighbor curx cury visitcurroomsouthneighbor curx cury visitcurroomwestneighbor curx cury visitcurroomeastneighbor curx cury,i trying draw map mud i used python graphviz get something like httpimgimageshackusimgarraszpng as see locations going nsweupdown going location is possible graphviz draw map north locations south east locations right west locations i mean like e location w location n s location or maybe better tool draw automatically graphviz,3 def upgrademigrateengine basemetadatabind migrateengine col column col string default foobar colcreatetable populatedefaulttrue worked,i try add table new column described documentation sqlalchemymigrate like col column col string default foobar colcreatetable populatedefaulttrue but i get error think use declarative models use migrations,1 i really sure neural networks best way solve i think euclidean distance score pearson correlation score combined item user based filtering would good start an excellent book topic programming collective intelligence toby segaran,i planning implementing document ranker uses neural networks how one rate document taking consideration ratings similar articles any good python libraries can anyone recommend good book ai python code edit i planning make recommendation engine would make recommendations similar users well using data clustered using tags user would given chance vote articles there hundred thousand articles documents would clustered based tags given keyword articles would fetched based tags passed neural network ranking,1 i posted instructions patch cross compiling python android get blog httpmdqinccomblogcrosscompilingpythonforandroid edit i open sourced ignifuga d game engine pythonsdl based cross compiles android even use games might get useful ideas code builder utility named schafer timyou know,we working s version platform nice python api however nothing official python android since jython exists way let snake robot work together,3 not sure still looking answer for trying subclass normalize unsuccessful so i focused manually creating new data set ticks ticklabels get effect i think aiming i found scale module matplotlib class used transform line plots syslog rules i use transform data then i scale data goes normalize usually i scale positive numbers differently negative numbers this vmax vmin might might cover larger positive range negative range it easier create routine calculate tick label values below code example figure import numpy np import matplotlibpyplot plt import matplotlibmpl mpl import matplotlibscale scale ndata vmax vmin linthreshe def maketicklablesvminvmaxlinthresh make two lists one tick positions one labels positions the number placement positive labels different negative labels nvpos intnplogvmaxintnploglinthresh nvneg intnplognpabsvminintnploglinthresh ticks labels lavmin nplognpabsvmin lvmax nplognpabsvmax llinthres intnploglinthresh fx mxb fllinthres flavmin floatllinthreslavmin b llinthresmlavminm itick rangenvneg labelsappendfloatpowitickllinthres ticksappendbitickllinthresm add vmin tick labelsappendvmin ticksappendblavminm fx mxb fllinthres flvmax floatlvmaxllinthres b mlvmaxllinthres itick rangenvpos labelsappendfloatpowitickllinthres ticksappendbitickllinthresm add vmax tick labelsappendvmax ticksappendblvmaxm return tickslabels data vmaxvminnprandomrandomndatandatavmin define scaler object transform symlog scaler scalesymmetricallogscalesymmetricallogtransformlinthresh datas scalertransformdata scale datas two seperate scales one positive one negative data npwherenpgreaterdata datasnplogvmax datasnplognpabsvmin tickslabelsmaketicklablesvminvmaxlinthresh cmap mplcmjet fig pltfigure ax figaddsubplot im aximshowdatacmapcmapvminvmax cbar pltcolorbarimticksticks cbaraxsetyticklabelslabels figsavefig twoscalespng feel free adjust constants eg vmax top script confirm behaves well,i want set middle point colormap ie data goes want zero middle i think way subclassing normalize using norm find example clear exactly implement,3 usual python clients django beware may need block request running amqp commands take look rabbitmq tutorials httpwwwrabbitmqcomgetstartedhtml httpsgithubcomrabbitmqrabbitmqtutorials there least three python clients pythonamqplib pika puka also may find wwwceleryprojectorg useful,i working project need control sending queue code so i curious anybody use create queue rabbitmq pythondjango code,2 use seek tell buff f opensomefile r x move end file fseek get current position eof ftell go back start file fseek arbitrary loop x data freadbuff x lendata print many unread bytes left unread eof x print unread file objects python library reference seekoffset whence set file current position like stdio fseek the whence argument optional defaults absolute file positioning values seek relative current position seek relative file end there return value note file opened appending mode seek operations undone next write if file opened writing append mode mode method essentially noop remains useful files opened append mode reading enabled mode if file opened text mode without b offsets returned tell legal use offsets causes undefined behavior note file objects seekable tell return file current position like stdio ftell,i read periodically bit frames file last frame i need know enough data file valid format fread returns empty string data data least byte how i check many unread bytes left file,1 for know size file using file object could following fseek filesize ftell the variable filesize contain size file bytes while reading simply ftell filesize get number bytes remaining so,i read periodically bit frames file last frame i need know enough data file valid format fread returns empty string data data least byte how i check many unread bytes left file,3 there trivial way object become another object python assigning self self local variable method definition and assigning change existing instance way make inaccessible rest method there ways approach problem the preferred way method returns correct instance class foo def getorsaveself existing loadfromdatabaseselfbar existing none return existing else savetodatabaseself return self newinst text newinstbar baz inst newinstgetorsave stop using newinst there also hackish way get similar effect original example ordinary python classes store attributes special dict attribute you copy though one instance replaced of course works perfectly plain python classes may may work classes defined orm retain state clever ways class foo def saveself existing loadfromdatabaseselfbar existing none selfdict existingdict else savetodatabaseself,i following problem i model class mvc special purpose in certain cases able override is kind behavior possible class textdocument stringfield b stringfield def saveself textobjectaselfacount similar object exists db self textobjectaselfafirst get instance db override origian class else use super class savefunction return supertext selfsave,1 while appear strictly possible using pip workaround accomplishes thing the workaround automatically generate second requirements file original requirements file sdists directory used directory a simple implementation might look something like save file called makereqspy usrbinenv python import import sys import ospath pat egg allowedexts zip targz tarbz def findversionsdistsdir name files f f oslistdirsdistsdir fstartswithname lenfiles return version filesreplacename ext allowedexts version versionreplaceext return version def getrequirementsfilename sdistsdir outreqs findlinks files ospathabspathsdistsdir openfilename reqfile reqs lstrip l reqfilereadlines req reqs match rematchpat req match reqstartswith name matchgroup version findversionsdistsdir name version outreqsappend ss name version else outreqsappendreq else outreqsappendreq return outreqs name main print n joingetrequirementssysargv to use script would something like python makereqspy requirementstxt pathtosdists sdistreqstxt pip install noindex r sdistreqstxt,using following command pip install r requirementstxt sdists you easily create archive requirements distributing project this works great requirements look like django djangotagging djangorobots you install requirements without touching pypi like pip install r requirementstxt findlinks sdists noindex is possible use method editable requirements eg e hghttpsbitbucketorgubernostrumdjangocontactformdfadfbeggdjangocontactform as far i tell pip install happily downloads editable requirements creates sdist pip install findlinks way match downloaded sdist associated line requirements file ignores downloaded sdist continues checking code vcs usual,2 the problem seemed djangowsgi file differences standard djangowsgi file loads python site vs development server loads site i guess well known issue i unaware thanks everyone suggestions alternative djangowsgi file found httpblogdscplcomauimprovedwsgiscriptforusewithhtml,i trying include additional urlspy inside main urls however seem working i done bunch searching i seem figure main urlspy file admin works fine djangoconfurlsdefaults import patterns include url djangocontrib import admin adminautodiscover urlpatterns patterns r pnasser include pnasserurls r admin includeadminsiteurls r include pnasserurls i folder pnasser file urlspy following djangoconfurlsdefaults import patterns include url urlpatterns patterns pnasserviews r index r login login r signup signup r insertaccount insertaccount r home home r updatepaccidd update r historypaccidd accounthistory r logoutpaccidd logout i sure i maybe missing something else configuration i visit mysitecomadmin loads admin correctly i goto mysite url views i get page found using urlconf defined mysiteurls django tried url patterns order pnasser admin the current url match edit settingspy installed apps installedapps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles uncomment next line enable admin djangocontribadmin uncomment next line enable admin documentation djangocontribadmindocs pnasser update so i also tried running site via dev server python managepy runserver works i assuming somewhere integration apache using modwsgi problem however i sure problem would,2 the amount time takes channel api frontend servers realize channel disconnected contingent browser implementation on wellbehaved browsers catch beforeunload event post message frontend says client going away on browsers may get event may able listen various implementation reasons like browser sends often fffuuuu ie get event xhr send may get swallowed in cases frontend server realizes client gone fails receive heartbeat happening phone curiousity phone your case interesting explicitly calling onclose the thing dispose iframe channel fe code words onclose behaves whole browser window closed take advantage fact browser still good state could wait close message sent so i recommend two things add custom handler code thing ahdisconnect handler make xhr know manually closing channel this kludgy functional the bummer need explicitly know client id javascript code second add issue issue tracker httpcodegooglecompgoogleappengineissueslist request better disconnect notification onclose called explicitly hope helps sorry easy answer right,im using gae application phone i face problem getting disconnect notification ahchanneldisconnected channels api even manually close socket socketclose function post occurs delay say one minute does anyone know way speed things in case socketclose doesnt produce channel disconnect notificationonly phone though works perfectly laptop,2 the first proposed solution use list turn ranges lists ineffecient since first turn range objects lists potentially consuming lot memory ranges large compare element consider eg range range object tiny coerce list becomes huge then compare one million elements answer even less efficient since assertitemsequal going instantiate lists going sort well elementwise comparison instead since know objects ranges equal strides start end values equal eg rangesequal lenalenb lena ab ab,one unittests checks see range set correctly reading log file i like test var range however range range evaluates false python is straightforward way test equivalence ranges python,3 try following in numpyapplyalongaxisnumpylinalgnorm out array d array the computes l norm for different norm could use something like in numpyapplyalongaxislambda rownumpylinalgnormroword out array,i d matrix i want take norm row but i use numpylinalgnormx directly takes norm whole matrix i take norm row using loop taking norm xi takes huge time since i k rows any suggestions find quicker way or possible apply nplinalgnorm row matrix,3 note perimosocordiae shows numpy version nplinalgnormx axis fastest way compute lnorm if computing lnorm could compute directly using axis argument sum along rows npsumnpabsxaxis lpnorms computed similarly course it considerably faster npapplyalongaxis though perhaps convenient in timeit npapplyalongaxisnplinalgnorm x loops best us per loop in timeit npsumnpabsxaxis loops best us per loop other ord forms norm computed directly similar speedups in timeit npapplyalongaxislambda rownplinalgnormroword x loops best us per loop in timeit npsumabsx axis loops best us per loop,i d matrix i want take norm row but i use numpylinalgnormx directly takes norm whole matrix i take norm row using loop taking norm xi takes huge time since i k rows any suggestions find quicker way or possible apply nplinalgnorm row matrix,3 you use segmentation algorithm based graph partition method for example use random walker but alter weights following way for every pixel vi let gi pixel color while original algorithm defines wij wij expbetagi gj you set wij gi gj,i d numpy array i want find non rectangular bounding box around specific values array rectangular bounding box already solved questionhow select locations unique elements numpy array bounding box around lets consider following example array the result bit complicated for one unique value we want construct indices way zero values within extremas considered within region in sense region segment problem exactly similar value exception zeros inside region it defining boundary region it noted region consist unique value zero by construction problem nonunique values lying within one another perhaps contour finding problem image image processing sensei sure one find region we want search bunch feature feature lie certain regions for example detect sift we want find sift features lie one unique area without comparison features please let know clarifications edit it important note connected component problem in connected component one region actually consist homogeneous values in case zeros value so merely detecting region constrained unique value it also important note inside region arbitrary values single value like zero depicting background thanks lot,1 thanks on numpy giving error i upgraded git version works fine,if i define structured array import numpy np x nparray o dtypenpdtype step int symbol s index int seems fine i import numpylibrecfunctions rec recappendfieldsx x x index gives typeerror object type numpyint len presumably xshape rather how i append columns structured array,1 google maps returns response iso encoding you need decode data bytestring passing simplejson jsondata simplejsonloadsdatadecode iso,i trying retrieve data google maps api django app req httpmapsgooglecommapsnavqfromlondontomanchester data urlliburlopenreqread jsondata simplejsonloadsdata however gives following error unicodedecodeerror utf codec decode byte xa position unexpected code byte is easy way around any advice appreciated thanks,1 sure easy import datetime datetimedatetimenowtime datetimetime datetimedatetimenowtime datetimetime false datetimedatetimenowtime datetimetime true,when function runs i need check current system time past pm something currenttime datetimedatetimenow currenttime code represent hours stuff edit clarification orders sent software handles pickingpacking orders distribution center if order sent system order needs get flagged picked following day so function needs run orders imported,2 datetimedatetimenowhour pass,when function runs i need check current system time past pm something currenttime datetimedatetimenow currenttime code represent hours stuff edit clarification orders sent software handles pickingpacking orders distribution center if order sent system order needs get flagged picked following day so function needs run orders imported,3 yes perfectly valid validation model that django folks added forms always used process saving models validation done forms problems of course people worked around limitation past overriding save method including validation way however new model validation semantic gives hook validation process actually using form the docs pretty clearly say model validation fullclean run modelformisvalid called however use modelform want additional processing need call fullclean manually you putting overridden save wrong approach remember explicit better implicit besides save called many places ways case modelform actually end running fullclean twice way that said since docs say modelform fullclean automatically i figured would make sense see handles errors in postclean method starting line djangoformsmodels clean model instance fields try selfinstancecleanfieldsexcludeexclude except validationerror e selfupdateerrorsemessagedict call model instance clean method try selfinstanceclean except validationerror e selfupdateerrorsnonfielderrors emessages in turn code updateerrors starts line module def updateerrorsself messagedict k v messagedictitems k nonfielderrors selferrorssetdefaultk selferrorclassextendv remove data cleaneddata dict since invalid k selfcleaneddata del selfcleaneddatak nonfielderrors messagedict messages messagedictnonfielderrors selferrorssetdefaultnonfielderrors selferrorclassextendmessages you play code bit give good starting point combining form model validation errors,please help understand following choices i made idiomaticgood improve model validation form validation i prefer use new model validation form validation whenever possible seems dry fundamental way create rules data two examples simple calendarentry model start must end period must less endstart is idiomaticgood put model level put forms if modelform best answer case using multiple models form edit i realize multiple modelforms actually used together transferring model validation form modelform edit it turns reinventing plumbing model validation form validation necessary situation solutions show let assume moment model validation errors i directly transferred displayed directly user ie ignore translating model validation errors userfriendly form validation errors this one working way i came one place helper functions viewwithaform formisvalid instance save overridden fullclean optional exclusions try instancesave except validationerror e nfe emessagedictnonfielderrors one big question mark instanceerrors errorlistnfe big question mark seems unnatural formisvalid return response code standard format send user form new form errors model errors return form as commented code is idiomaticgood way transfer model errors form b is idiomaticgood way test new form errors note this example uses nonfield errors i think could equally apply field errors,2 i issue windows i posted google app engine forum official response i got the dev server support yet currently way test based code appengine,gae looks excellent longwaited features however working yet i downloaded installed gae using degenerate aaa app test here roughly appyaml various changes made testing appyaml application aaa mystical creation version alpha runtime python apiversion threadsafe true handlers url media staticdir media url faviconico staticfiles mediaimagesfaviconico upload mediaimagesfaviconico url admin script aaaapp login admin url script aaaapp skipfiles appyaml libraries name django version name jinja version latest name yaml version latest i running mac os x lion i hypothesize i actually using python runtime spite declaration appyaml use i quite sure validate theory errors i encountered consistent these errors reproduced python path when google app engine python path set app engine runs using python to fix i set python path usrbinpython google app engine preferences wsgi i get following error applicationsgoogleappenginelauncherappcontentsresources googleappenginedefaultbundlecontentsresourcesgoogleappengine googleappenginetoolsdevappserverpy getparentpackageselfgoogleappenginetoolsdevappserverhardenedmoduleshook object fullname aaaapp selffindmodulefullname none raise importerror could find module fullname return selfmoduledictparentmodulefullname builtin importerror type exceptionsimporterror fullname aaaapp type exceptionsimporterror could find module aaaapp args could find module aaaapp message could find module aaaapp where i tried aaaapp aaapy googleappenginedist import uselibrary uselibrary django otherwise still get django djangocorehandlers import wsgi app wsgiwsgihandler aaa initpy content aaaaaapy content note i continue run cgi appyaml aaapy modified mutatis mutandis however nevertheless results errors jinja when i run import jinja i get importerror django without googleappenginedist import uselibrary uselibrary django i end django theory given following httpcodegooglecomappenginedocspythontoolslibrarieshtml states the uselibrary function provided googleappenginedist package unavailable python uselibrary works uselibrary required libraries django version declaration set django version only django included python runtime per librarieshtml link i manually specify python python path order gae use python wsgi load application properly jinja cannot imported i believe i really using python gae runtime ie appyaml declaration ignored gae sdk i hope helpful description i grateful thoughts may happening – potential solutions,3 it seems using objects best values you modify code way time need new roll instantiate new die why keeping instance time want display roll instantiate new label maybe aware update label text tkinter widget using configure method this would mean need grid instance first time by way grid returns none if want keep reference result label use two lines label instantiation selfresult labelselfroot textt first creating instance selfresultgridrow colum stickyw placing selfroot try update code like you certainly feel need move code init function self write question well,i sure i right track i started gui programming python i buttons entries worked the main problem i method rolls die places result def rollself selfdie dieintselfsidesget gets label selfdieroll intselfmodget gets label selfresult labelselfroot texttgridrow column stickyw is problem fact i reinstantiating label old one shouldn old label text destroyed frame show new label place,1 another way rangesequal strastrb the string representation indicates start end step ranges this question makes think perhaps python provide way get attributes range object,one unittests checks see range set correctly reading log file i like test var range however range range evaluates false python is straightforward way test equivalence ranges python,1 you override default behaviour ftp server using custom ftphandler overriding ftphandlerftptypefiletype method way force server serve file binary mode selfcurrenttype,we devices run proprietary ftp client they retrieve media files avi videos images well xml files web service utilizing python based ftp server the problem i ftp client wants download media files ascii mode instead binary mode i like continue use python ftp server pyftpdlib i figure way force client use binary mode i skimmed ftp rfc looking commandresponse sequence would allow ftp server tell ftp client use binary instead ascii does commandresponse sequence exist,1 a twist question involves asking check function name would available method since duck typing considered pythonic simple hasmethodobj somemethod seems duck typing seems best done trying try objsomemethod except try something else if someone wants function check programmatically object method certain variable name following function mentioned def hasmethodobj methodname return hasattrobj methodname callablegetattrobj methodname but python least need get callable back removed a discussion want bringing back found python bug entry resurrect callable eg def callableobj return isinstanceobj collectionscallable this straight mentioned python bugtracker other sources stackoverflow mention callable lambda hasattro call isinstanceo collectionscallable adds hasattr call both work fine use case bstr b spam str eggs hasmethodstr decode false hasmethodbstr decode true for details look already cited question,how check function method object for example def checkmethodf checkmethodlambda x x false checkmethodsomeclasssomemethod true there special attributes methods helloworld example eg imself self etc can i rely nicer way,2 considering selfpath could potentially hierarchical probably something like following import urlparse urlparseurlparseselfpath urlparseparseqsoquery,i using python basehttprequesthandler when i implement doget method i find parsing hand selfpath selfpath looks something like parametervalueampothersome how i parse order get dict like parameter value thanks,3 it seems surfarray object backed numpy arrays chances getting faster relying native methods take look numpyargmax you might need transform array luminosity matrix first nested loops xd maybe need reshaping get planes average simple matrix operations or instead working rgb could switch image format easier work like hsv grayscale,alright hopefully someone help i loss i working game python uses camera main controller to play game move simple light around controls game so far i managed get camera image surface display screen but comes finding light program slowed crawl my first attempt used surfacegetatxy function actual code example maxl point mysurface getcameraimg rangemysurfacegetwidth j rangemysurfacegetheight color mysurfacegetatij lum getlumcolorrcolorgcolorb iflummaxl maxl lum point ij this horrendously slow i started research a quick check pygame docs showed getting pixels time using method would slow so i started trying using surfarray maxl point mysurface getcameraimg ar pygamesurfarrayarraydmysurface rangelenar j rangelenari color arij lum getlumcolorcolorcolor iflummaxl maxl lum point ij however also slow a quick double check surfarray docs showed pygamesurfarraypixelsdsurface would faster actual value copied unfortunately camera image bit format so question in pygame quick way read all pixels i able read every pixel lum calculation maxcolormincolor see lum max lum thank time,1 joinuser name user users,im using users winnetnetgroupgetusersip none get local users system the output tuple name u administrator name u guest name u tom i want clean prints administrator guest tom i tried using strip replace cant use tuples is way convert string manipulate even simpler way go,2 input name u administrator name u guest name u tom inlist input names x name x inlist print names u administrator u guest u tom,im using users winnetnetgroupgetusersip none get local users system the output tuple name u administrator name u guest name u tom i want clean prints administrator guest tom i tried using strip replace cant use tuples is way convert string manipulate even simpler way go,1 this end comma users winnetnetgroupgetusersip none the trailing comma turns result single item tuple containing result tuple the data want users print users name u administrator name u guest name u tom to unpack list dictionaries use generator expression users winnetnetgroupgetusersip none print joind name users,im using users winnetnetgroupgetusersip none get local users system the output tuple name u administrator name u guest name u tom i want clean prints administrator guest tom i tried using strip replace cant use tuples is way convert string manipulate even simpler way go,2 areas array def isinareaxy areanum return areasroundx roundy areanum is going of course might want bounds checking,i d array lets suppose connected region non rectangular consider following example array in array ones connected i know coordinates stored lets say numpy array list elements xy now i want query arbitrary points lies area the point could also float in case float coordinates values round nearest integer pixel value thanks lot,1 check preferences pydev editor code style code formatter check right trim lines check box,ideally eclipse remove trailing whitespace i save file i know option cjava plugins eclipse i couldnt find one pydev is one if whats easiest way achieve,3 stumbled accros usefull site httpandreigmxhomedeanyedit hope could help,ideally eclipse remove trailing whitespace i save file i know option cjava plugins eclipse i couldnt find one pydev is one if whats easiest way achieve,3 rename exceptionlog temporary filename process temp file i assuming temperamental web app simply recreate exceptionlog exist,i working temperamental web app i going name it runs problems time time writes stack traces error messages exceptionlog file i want know problems timely manner i got python script scans log regularly hooray cron if size exceptionlog greater zero script dumps contents file email moves exceptionarchivelog my current tactic read file send email write exception archive necessary steps successful target opentargetlog w targetclose zorch original log however since i predict system write exceptionlog least one point script i could lose data system could write something log i read existing data decided overwrite file also i learned painful experience exceptionlog exist temperamental web app recreate drop exception data floor so naã¯ve solution rename recreate log file pushes problem layer the core question how i transfermovereadwriteerase data one text file another way new data written file script executing zero minimal chance losing data i suspect either hard problem solved problem i heard solution i extend app either management skeptical tinkering plus python i start scratch additional context meserver uname linux serverexamplecom elsmp smp thu jul edt gnulinux meserver python python may gcc red hat linux it running cruddy shared hosting part i call temperamental i also call worse things running python this would probably easier i modern python work i going go variation kevin answer since i control crontab i going script look anything right timestamp range operate this side benefit relevant information live python script single source truth,1 import itertools key group itgroupbycursor lambda row rowroadtype seccolpairs itgroupbygroup lambda row rowsecondcolumn row pairs print formattrowroadtypesrowsecondcolumn print print here two examples help grok groupby listg k g itgroupby aaaabbbccd a a a a b b b c c d above items grouped together now add key function keyfunc keyfunclambda x x datarange listg kg itgroupbydatakeyfunc k kg itgroupbydatakeyfunc now instead grouping items data group according keyfuncx x data,i playing groupby function itertools module like days k g groupbydata keyfunc i really trouble understanding syntax i tried variety different things i really know put data keyfunc get return groups data i want print statement what i looping rows access table i set variable cursor search sorted access table pull column i want row cursor print rowroadtype this returns trunk road trunk road trunk road trunk road collector highway collector highway access road access road access road access road access road access road access road major road major highway i want group values together return string value prints something like trunk road trunk road trunk road trunk road collector highway collector highway access road access road access road access road access road access road access road major road major highway finally i want group second column based new groups i get something like trunk road m trunk road m trunk road m trunk road m collector highway m collector highway m access road m access road m access road m access road m access road m access road m access road m major road m major highway m i know probably way less difficult i made i feel simple answer i completely stumped i seem find example internet explains groupby syntax way i understand please feel f,1 there way avoid changing app id request old id aliased requests oldappidappspotcom handled new application if serving application domain course app id irrelevant the masterslave datastore almost certainly never supported python google recommend use i use term deprecated since expressed plans actually remove kill huge number existing applications using certainly want much discourage use,for tons reasons i would like go ahead switch python the new python version requires using high replication datastore as far i see converting really possible way create new app new id copy datastore changing app id something i keen is way around app id changing or workaround expected near future will version eventually support masterslave datastore i suppose appengine users happily changing id,3 i would avoid deleting exception log web app still running just scan log updates without making changes lastknownsizeoffile saved somewhere persists executions script sizefile lastknownsizeoffile found update amounttoread sizefile lastknownsizeoffile fileseeklastknownsizeoffile newdata filereadamounttoread exceptionarchivewritenewdata emailmenewdata lastknownsizeoffile amounttoread if worried log file grow large way delete periodically lowactivity hours say am unlikely app writing anything,i working temperamental web app i going name it runs problems time time writes stack traces error messages exceptionlog file i want know problems timely manner i got python script scans log regularly hooray cron if size exceptionlog greater zero script dumps contents file email moves exceptionarchivelog my current tactic read file send email write exception archive necessary steps successful target opentargetlog w targetclose zorch original log however since i predict system write exceptionlog least one point script i could lose data system could write something log i read existing data decided overwrite file also i learned painful experience exceptionlog exist temperamental web app recreate drop exception data floor so naã¯ve solution rename recreate log file pushes problem layer the core question how i transfermovereadwriteerase data one text file another way new data written file script executing zero minimal chance losing data i suspect either hard problem solved problem i heard solution i extend app either management skeptical tinkering plus python i start scratch additional context meserver uname linux serverexamplecom elsmp smp thu jul edt gnulinux meserver python python may gcc red hat linux it running cruddy shared hosting part i call temperamental i also call worse things running python this would probably easier i modern python work i going go variation kevin answer since i control crontab i going script look anything right timestamp range operate this side benefit relevant information live python script single source truth,1 you want repr function print reprs,consider line python code this string nr whitespace how i make print give this string nr whitespace instead this string whitespace,1 want raw string rthis string nr whitespace transform special characters representation reprs,consider line python code this string nr whitespace how i make print give this string nr whitespace instead this string whitespace,3 print sencode stringescape,consider line python code this string nr whitespace how i make print give this string nr whitespace instead this string whitespace,3 you use python formatting capabilities print string raw form print r you also create string raw form like r this string nr whitespace python handle escaping backslashes exactly get print outputs this string nr whitespace,consider line python code this string nr whitespace how i make print give this string nr whitespace instead this string whitespace,1 your xcorn zcorn values repeat consider caching result computations take look timeit profile modules get information taking computational time,i trying calculate gravity effect buried object calculating effect side body summing contributions get one measurement one station repeating number stations code follows body square code calculates clockwise around goes x back x coordinates grav xsiarange xcorn zcorn gamma n kg rho kg grav itertime def procedure siarangelenx cycles position ttimeclock sumlines n siarangelenxcorncycles corners x xcornnxi x xcornnxi z zcornn depth corner since observations surface z zcornn r z x r z x o siarctanzx o siarctanzx denom zz denom denom e alpha xxdenom beta xzxzdenom factor betaalpha term silogrrlog base term alphaoo sumlines sumlines factortermterm sumlines sumlinesgammarho gravappendsumlines timeclock dt tt itertimeappenddt any help speeding loop would appreciated thanks,1 it inefficient access individual elements numpy array python loop for example python loop xrange lena ai would much slower nparange lena you could use better algorithm less time complexity use vector operations numpy arrays example but quicker way might compile code using cython cython boundscheckfalse wraparoundfalse proceduremodulepyx import numpy np cimport numpy np ctypedef npfloatt dtypet def procedurenpndarraydtypetndim x npndarraydtypetndim xcorn cdef pyssizet j dtypet x x z z r r o o npndarraydtypetndim grav npemptylikex rangexshape j rangexcornshape x xcornjxi x xcornjxi gravi return grav it necessary define types need significant speed compared python define least types arrays loop indexes you could use cprofile cython supports instead manual calls timeclock to call procedure usrbinenv python import pyximport pyximportinstall pip install cython import numpy np proceduremodule import procedure x nparange xcorn nparray grav procedurex xcorn,i trying calculate gravity effect buried object calculating effect side body summing contributions get one measurement one station repeating number stations code follows body square code calculates clockwise around goes x back x coordinates grav xsiarange xcorn zcorn gamma n kg rho kg grav itertime def procedure siarangelenx cycles position ttimeclock sumlines n siarangelenxcorncycles corners x xcornnxi x xcornnxi z zcornn depth corner since observations surface z zcornn r z x r z x o siarctanzx o siarctanzx denom zz denom denom e alpha xxdenom beta xzxzdenom factor betaalpha term silogrrlog base term alphaoo sumlines sumlines factortermterm sumlines sumlinesgammarho gravappendsumlines timeclock dt tt itertimeappenddt any help speeding loop would appreciated thanks,1 it looks like might running mongodb server one thing frequently trips server shut uncleanly refuse start remove mongodlock file data directory,i trying run simple connection pymongo keeps returning connection refused here i tried pymongo import connection connection connection localhost i get traceback recent call last file stdin line module file usrlocallibpythondistpackagespymongopylinux ieggpymongoconnectionpy line init selffindnode file usrlocallibpythondistpackagespymongopylinux ieggpymongoconnectionpy line findnode raise autoreconnect joinerrors pymongoerrorsautoreconnect could connect localhost errno connection refused how i fix,3 you overriding parse method instead implementing new parseitem method,since nothing far working i started new project python scrapyctlpy startproject nu i followed tutorial exactly created folders new spider scrapycontribspiders import crawlspider rule scrapycontriblinkextractorssgml import sgmllinkextractor scrapyselector import htmlxpathselector scrapyitem import item nuitems import nuitem urls import u class nuspidercrawlspider domainname wcase starturls httpwwwwhitecasecomaabbas names hxsselect tdclassaltrowahref aw u namespop rules rulesgmllinkextractorallowu callback parseitem def parseself response selflog hi item page responseurl hxs htmlxpathselectorresponse item item item school hxsselect tdclassmaincolumntda jdsd return item spider nuspider i run cpythonscriptsnupython scrapyctlpy crawl wcase i get nu error could find spider domain wcase the spiders least recognized scrapy one what i wrong thanks help,1 the idea behind itertoolsgroupby solve basic problem i want iterate sequence analyze thing depending analysis process thing different way groupby separates sequence groups preserving order original sequence itertools import groupby groupbyxrange lambda v v results x listx x print strresults the prints you notice order get results list i extra processing what groupby actually gives meant iteration groupbyxrange lambda v v print strinext the prints itertoolsgrouper object xbfd so idea program say key valueiter inext test key pass valueiter correct processing functionmethod so value well continue test key within processing functions tell stop groupby stop subiterator automatically what groupby unlike group by clause sql ensure everything key value original iterable processed key values repeat groupby this justified objective preserve order original sequence accumulate everything memory for example groupbyxrange lambda v v note modulo division results x listx x print strresults the prints the key values repeat subiterator produces single datum this worstcase scenario terms performance groupby means follow certain model working tool so something like groupbyxrange lambda v v results dictx listx x beware dict print strresults correct know priori key values never repeat,i playing groupby function itertools module like days k g groupbydata keyfunc i really trouble understanding syntax i tried variety different things i really know put data keyfunc get return groups data i want print statement what i looping rows access table i set variable cursor search sorted access table pull column i want row cursor print rowroadtype this returns trunk road trunk road trunk road trunk road collector highway collector highway access road access road access road access road access road access road access road major road major highway i want group values together return string value prints something like trunk road trunk road trunk road trunk road collector highway collector highway access road access road access road access road access road access road access road major road major highway finally i want group second column based new groups i get something like trunk road m trunk road m trunk road m trunk road m collector highway m collector highway m access road m access road m access road m access road m access road m access road m access road m major road m major highway m i know probably way less difficult i made i feel simple answer i completely stumped i seem find example internet explains groupby syntax way i understand please feel f,1 okay i guess get one login attempt object poplib the solution move declaration m loop i swear i tried posting i must stuffed somehow,i writing script login hotmail it asks user enter password get password right well if get password wrong first time however valid password work subsequent attempts this i using user enter password import poplib m poplibpopssl poplivecom connect hotmail pop server msetdebuglevel success false user emailhotmailcom success false try password rawinputpassword museruser mpasspassword except print invalid credentials else print successful login success true here output debug level python myprogrampy password password cmd user emailhotmailcom put user emailhotmailcom get ok password requiredrn resp ok password required cmd pass password put pass password get ok mailbox messagesrn resp ok mailbox messages successful login python myprogrampy password cmd user emailhotmailcom put user emailhotmailcom get ok password requiredrn resp ok password required cmd pass put pass get err authentication failedrn resp err authentication failed invalid credentials password password cmd user emailhotmailcom put user emailhotmailcom get ok password requiredrn resp ok password required cmd pass password put pass password invalid credentials what i missing i note i new python,1 you need commit transaction import pyodbc con pyodbcconnectr drivermicrosoft access driver mdb accdbdbqzdatainstrumentstestdbaccdb providermsdasql cur concursor string create table testtablesymbol varchar leverage double shares integer price double curexecutestring concommit,i trying create tables ms access db python using pyodbc i run script tables created errors given my code usrbinenv python import pyodbc con pyodbcconnectr drivermicrosoft access driver mdb accdbdbqzdatainstrumentstestdbaccdb providermsdasql cur concursor string create table testtablesymbol varchar leverage double shares integer price double curexecutestring what could wrong,3 if datatype going get used often might worth creating class overwriting operators works seamlessly that way exception handling still internal datatype gives plenty flexibility define things like example differences number days february march moving month month,in ada define custom data type type dayofmonth range so create dayofmonth variable hold int this nice keep conditional checks want update value proper exception handling is easy way similar thing python,1 they show url form using get method using post processing values server side,i trying make user registration login application i working using form htmlform methodget actionlogin email address input nameemail typetextbr password input namepassword typepasswordbr input typesubmit valuesubmit form html however user name password show url submit button httplocalhostloginemailamppasswordampsubmitsubmit how i stop happening,1 if backwardcompatible equivalent possible i would handle making multiplecontext statement set singlecontext nested statements open atxt open btxt b domanyamazingthingsa b edit address edit if insist nesting extra statements always use contextlib import contextlib contextlibnestedopenatxt openbtxt b domanyamazingthingsab as using multiple statements futureimported possible far i know,i like convenience multiple context statement python open atxt open btxt b domanyamazingthingsa b however i need maintain compatibility brought via future i unable find anything multiple context version backported documentation is something i missed edit i aware possible nest statements i asking possible use multiple statements,3 your shell disappears program finishes end program rawinput enter finish line console stay allowing see result,i successfully converted py script exe problem wont get executed i press exe icon a black screen pops fraction second disappears i tried executing command prompt get executed run i click exe directly just want know error placing exe file due i encountering problem setuppy distutilscore import setup import pyexe setupconsolemyscriptpy python setuppy pyexe help python setuppy pyexe,1 there efficient ways syntactically might shortest words open myfile readsplit if memory concern going want load entire thing memory instead iterating,i need iterate words large file consists single long long line i aware methods iterating file line line however applicable case single line structure any alternatives,1 it really depends definition word but try f fileyourfilenamehereread word fsplit something word print word this use whitespace characters word boundaries of course remember properly open close file quick example,i need iterate words large file consists single long long line i aware methods iterating file line line however applicable case single line structure any alternatives,3 long long line i assume line big reasonably fit memory want kind buffering first bad format kind control file make one word per line if use something like line true word space line linepartition space a word found yield word else a word found read chunk data file nextchunk inputfileread nextchunk add chunk line line word nextchunk else no data yield last word return yield wordrstrip n return,i need iterate words large file consists single long long line i aware methods iterating file line line however applicable case single line structure any alternatives,2 you created three different empty lists you created one empty list created new list three references empty list to fix problem use code instead listy range running example code gives result probably expected listy range listy listy listyappend listy listyappend listy,i encountered i think strange behavior python i like somebody explain possible i created empty d list listy print listy the following works i expect listy yields listyappend yields however i append one empty lists python appends all sublists follows listyappend yields can anyone explain behavior occurs,3 it said listy in words three list references refer list instance,i encountered i think strange behavior python i like somebody explain possible i created empty d list listy print listy the following works i expect listy yields listyappend yields however i append one empty lists python appends all sublists follows listyappend yields can anyone explain behavior occurs,3 the problem trying solve called collaborative filtering neural networks one stateoftheart neural network method deep belief networks restricted boltzman machines for fast python implementation gpu cuda see another option pybrain academic papers specific problem this probably stateoftheart neural networks collaborative filtering movies salakhutdinov r mnih a hinton g restricted boltzman machines collaborative filtering to appear proceedings th international conference machine learning pdf a hopfield network implemented python huang z chen h zeng d applying associative retrieval techniques alleviate sparsity problem collaborative filtering acm transactions information systems tois acm pdf a thesis collaborative filtering restricted boltzman machines say python practical job g louppe collaborative ltering scalable approaches using restricted boltzmann machines master thesis universite de liege pdf neural networks currently stateoftheart collaborative filtering and simplest widespread solutions regarding comment reason using nns little data neural networks inherent advantagedisadvantage case therefore might want consider simpler machine learning approaches other machine learning techniques the best methods today mix knearest neighbors matrix factorization if locked python take look pysuggest python wrapper suggest recommendation engine pyrsvd primarily aimed applications collaborative filtering particular netflix competition if open try open source technologies look open source collaborative filtering frameworks httpwwwinfoanarchyorgencollaborativefiltering,i planning implementing document ranker uses neural networks how one rate document taking consideration ratings similar articles any good python libraries can anyone recommend good book ai python code edit i planning make recommendation engine would make recommendations similar users well using data clustered using tags user would given chance vote articles there hundred thousand articles documents would clustered based tags given keyword articles would fetched based tags passed neural network ranking,3 your two groupby examples done exact way except choice key itertools import groupby operator import attrgetter key rows groupbycursor keyattrgetter roadtype row rows print rowroadtype print key rows groupbycursor keyattrgetter roadtype othercolumn row rows print rowroadtype rowothercolumn print in cases key result attrgetter actually need iterating rows grouped key of course works correctly cursor sorted key group,i playing groupby function itertools module like days k g groupbydata keyfunc i really trouble understanding syntax i tried variety different things i really know put data keyfunc get return groups data i want print statement what i looping rows access table i set variable cursor search sorted access table pull column i want row cursor print rowroadtype this returns trunk road trunk road trunk road trunk road collector highway collector highway access road access road access road access road access road access road access road major road major highway i want group values together return string value prints something like trunk road trunk road trunk road trunk road collector highway collector highway access road access road access road access road access road access road access road major road major highway finally i want group second column based new groups i get something like trunk road m trunk road m trunk road m trunk road m collector highway m collector highway m access road m access road m access road m access road m access road m access road m access road m major road m major highway m i know probably way less difficult i made i feel simple answer i completely stumped i seem find example internet explains groupby syntax way i understand please feel f,1 here solution subclassing normalize to use norm midpointnormmidpoint imshowx normnorm here class numpy import matplotlib import cbook class midpointnormnormalize def initself midpoint vminnone vmaxnone clipfalse normalizeinitselfvmin vmax clip selfmidpoint midpoint def callself value clipnone clip none clip selfclip result isscalar selfprocessvaluevalue selfautoscalenoneresult vmin vmax midpoint selfvmin selfvmax selfmidpoint vmin midpoint vmax raise valueerrormidpoint must maxvalue minvalue elif vmin vmax resultfill or masked or elif vmin vmax raise valueerrormaxvalue must bigger minvalue else vmin floatvmin vmax floatvmax clip mask magetmaskresult result maarraynpclipresultfilledvmax vmin vmax maskmask division slow take shortcut resdat resultdata first scale range resdat midpoint resdatresdat absvmax midpoint resdatresdat absvmin midpoint resdat resdat result maarrayresdat maskresultmask copyfalse isscalar result result return result def inverseself value selfscaled raise valueerrornot invertible scaled vmin vmax midpoint selfvmin selfvmax selfmidpoint mplcbookiterablevalue val maasarrayvalue val val valval absvmax midpoint valval absvmin midpoint val midpoint return val else val val val return valabsvminmidpoint midpoint else return valabsvmaxmidpoint midpoint,i want set middle point colormap ie data goes want zero middle i think way subclassing normalize using norm find example clear exactly implement,3 i used groupby function itertools module also i used window function future import printfunction itertools import tee izip groupby def groupbyiterable used convert second iterable element groupby result list groupbyiterable yield ilisti def windowiterablen els teeiterablen iel enumerateels rangei nextel none return izipels def compressiterable windowgroupbyiterable creates iterator yield elements following manner ge flag false reset flag print nwindow formatge value ge yield values first element window print a formatvalue yield value ge gege the central element window replaced flag true flag correct last window processing ge replacing central element window print b formatge yield ge nextitnone skip element advanced element forloop giving net advances processing last elements last window flagfalse the central element last window processed proccessing value ge print c formatvalue yield value value ge the last element window print d formatvalue yield value print ninput formata output listcompressa print proram output formatoutput print goal output format the code debugging messages i live since make easier understand works just delete need the output input window a window a b b window a window a a a window a a b b b window a a window a b b b d proram output goal output update here refactored version future import printfunction itertools import tee izip groupby def groupbyiterable groupbyiterable yield ilentuplei def windowiterablen els teeiterablen iel enumerateels rangei nextel none return izipels def subsiterable windowgroupbyiterable left middle right yield leftleft middle leftright yield leftmiddle nextitnone notmiddle leftright yield middlemiddle yield rightright def chainediterable l subsiterable el l yield el print ninput formata output listchaineda print proram output formatoutput print goal output format,d numpy array lets look following example in array unique entries considered except value we want fill values unique entry resultant look like could easily done looking pythonic way thanks lot,1 so right pass multiple blocks however pass variable back caller act upon therefore something like macro test caller caller b endmacro callwhich test hello elif b world endif endcall to describe detail callwhich defines caller takes one argument when macro refers caller passes caller identifier block content actually wants caller return the caller act upon it elegant fool proof works,i java programmer learning pythonjinja my biggest beef jinja macros limitation single caller example could following jsp tags tag def attribute nametitle fragmenttrue div class title titlediv div class body jspdobodydiv usage mytag jspattribute name title cif test blah this sometimescif jspattribute jspbody cif test something dynamic contentcif jspbody mytag want stress body content title attribute content dynamic also hacks setting variables dynamic content passing lets look jinja macro thing macro mytagtitle caller div class title title div div class body caller div endmacro wait cannot easily put dynamic content title attribute call mytagtitle imagine putting content involves loops ifs whatnot something dynamic content endif endcall problem newbie shortcoming jinja,2 for questions like python documentation first stop specifically look section string formatting it lists string format codes one complex numbers what format real imaginary parts number separately using xreal ximag print bi form,for project one classes output numbers five decimal placesit possible output complex number i unable figure output complex number five decimal places for floats i know print fvariablename is something similar complex numbers,2 n j print f fi nreal nimag,for project one classes output numbers five decimal placesit possible output complex number i unable figure output complex number five decimal places for floats i know print fvariablename is something similar complex numbers,1 this help httpmailscipyorgpipermailnumpydiscussionnovemberhtml,i want work numpy arrays c extension many examples case uses structure pyarrayobject arraydata arraystrides arraystrides pointers order reach data i wanted reach array familiar tidier way indices like arrayij i proceed should i typecast bool arraydata work c array i created elements bools my function declaration finished course static pyobject xormaskingpyobject self pyobject args pyobject input pyobject mask pyobject adjacency pyobject state pyarrayobject arrmask pyarrayobject arradjacency pyarrayobject arrstate pyarrayobject arrnextstate double sum int counternode nnodes pyargparsetuple checks args pointers type o extracted extracts pyargparsetupleargs oooxormaskingc ampmask ampadjacency ampstate return null the pointer returned pyarraycontiguousfromobject typecasted pyarrayobject pointer array pointed address arrmask pyarrayobject pyarraycontiguousfromobjectmask pyarraybool arradjacency pyarrayobject pyarraycontiguousfromobjectadjacency pyarraybool arrstate pyarrayobject pyarraycontiguousfromobjectstate pyarraybool array null return null int nmask maskdimensions int nmask maskdimensions int nadjacency adjacencydimensions int nadjacency adjacencydimensions int nstate statedimensions int nnodes nstate dimensions match return null bool cmasknnodesnnodes nmask nmask nadjacency nadjacency nadjacency nmask nadjacency nadjacency return null the d arrays introduced follows arrayij arraydata iarraystrides jarraystrides counternode nmask rowstart arraydata iarraystrides pydecref return pyfloatfromdouble thanks,1 if want concert multiple sponsor sponsor able associated multiple concert want use manytomanyfield rather foreignkey see docs httpsdocsdjangoprojectcomendevrefmodelsfieldsmanytomanyfield the problem probably displaying sponsorsplease sure printing concert template selecting sponsors instead iterating concertinstancesponsorall queryset,i problem following simplified version models sponsormodelsmodel sponsorname modelscharfield concertsmodelsmodel artistname modelscharfield sponsor modelsmanytomanysponsor i go admin interface add new sponsor automatically shows concert sponsors show concerts that i want i want some sponsors some concerts i realize relationships problem i tried sponsormodelsmodel belongsto modelsforeignkeyconcerts sponsorname modelscharfield concertsmodelsmodel artistname modelscharfield but i reuse sponsors i add new one concert,1 i think mistaking possible values actually chosen sponsor concert model djangoadmin interface try python managepy shell yourappyourmodel import concerts concertsobjectssponsorsetall result contain selected sponsors model i bet see empty list,i problem following simplified version models sponsormodelsmodel sponsorname modelscharfield concertsmodelsmodel artistname modelscharfield sponsor modelsmanytomanysponsor i go admin interface add new sponsor automatically shows concert sponsors show concerts that i want i want some sponsors some concerts i realize relationships problem i tried sponsormodelsmodel belongsto modelsforeignkeyconcerts sponsorname modelscharfield concertsmodelsmodel artistname modelscharfield but i reuse sponsors i add new one concert,1 yes definitely still relevant although lot changed django since version internal parts concepts pro django deals mostly i hesitation recommending book really useful insight django works teaches useful methods well,i want dig deeper django internals official online documentation goes far toward end the reviews marty alchin pro django fantastic i read pro python really enjoyed however book based django v my company builds v is book still worthwhile how i best learn django metaprogramming beyond looking source code i also thanks,3 for initial rules from school years i would say make abstraction changes everyday equation unknown values sorry i know maths vocabulary english values previous day at day equations unknown values solution direct i guess change day may forgotten values elements different enough said use approximations round numbers for adapted rules too many unknown changing values case direct solution i know i would trust lior approach looks fine limited range prices quantities,i learning programming python algo’s trying work project i find interesting i created basic python scripts i’m sure approach solution game i trying build here’s game work users given items value for example apple pears oranges they get chance choose combo like ie apples pears oranges the output computer gets total valuein example currently the computer try guess which obviously won’t able get correctly first turn value quantityday valueday apple pears orange total the next turn user modify numbers total quantity percent may chose i’ll use example the prices fruit changeat random total value may change based alsofor simplicity i changing fruit prices example using example day game user returns value day here example quantityday changeday valueday quantityday changeday valueday i hope tables show right i manually space hopefully screen work let know i try upload screenshot i trying see i figure quantities timeassuming user patience keep entering numbers i know right restriction total value cannot i cannot within accuracy right user entering forever what i done far here’s solution farnot much basically i take values figure possible combos themi done part then i take possible combos put database dictionaryso example could dictionary entry apple pears oranges way apple pears oranges i time i get new number i list possibilities here’s i’m stuck is using rules i figure best possible solution i think i’ll need fitness function automatically compares two days data removes possibilities variance previous days data questions so question user changing total list probabilities i approach what i need learn is algorithms theories i use applicable or help understand mistake suggest rules i add make goal feasibleif current state i thinking adding fruits saying must pick least etc also i vague understanding genetic algorithms i thought i could use something i use i eager learn advice tips would greatly appreciatedjust please tell game impossible thanks advance update getting feedback hard solve so i thought i add another condition game interfere player doinggame stays everyday value fruits change pricerandomly would make easier solve because within movement certain fruit value changes combo probable time day anything possible getting close enough range almost impossible prices fruits change user choose change tover time range narrow narrow in example prices volatile enough i think i could brute force solution gave range guess i trying figure elegant solution solutions keep narrowing range time update after reading asking around i believe hidden markovviterbi problem tracks changes fruit prices well total sumweighting last data point heaviest i sure apply relationship though i think case could wrong least i starting suspect type machine learning problem update i created test casewith smaller numbers generator help automate user generated data i trying create graph see likely here code along total values comments users actually fruit quantities usrbinenv python import itertools fruit price data fruitpriceday apple pears oranges fruitpriceday apple pears oranges fruitpriceday apple pears oranges generate possibilities testingwarningwill scale large numbers def possibilitygeneratortargetsum apple pears oranges alldaypossible counter applerange range targetsum apple pearsrange range targetsum pears orangesrange range targetsum oranges j k itertoolsproductapplerange pearsrange orangesrange j k targetsum currentpossible print counter print apple iapple pears jpears oranges koranges currentpossible apple iapple currentpossible pears jpears currentpossible oranges koranges print currentpossible alldaypossiblecounter currentpossible counter counter return alldaypossible total sum returned user value fruits totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day graph graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges sample dict oranges apple pears oranges apple pears print graph,1 generally anything django remains relevant the changes dramatic hence version numbering pointreleases instead milestones anything written pre burned though the biggest change classbased views although oldstyle methodbased views still supported likely continue indefinitely try use classbased views instead see httpsdocsdjangoprojectcomendevtopicsclassbasedviews other i recommend simply quick lookup django docs features discussed pro django book you target docs release notify things changed changed,i want dig deeper django internals official online documentation goes far toward end the reviews marty alchin pro django fantastic i read pro python really enjoyed however book based django v my company builds v is book still worthwhile how i best learn django metaprogramming beyond looking source code i also thanks,1 in order get list available contract dates use yahoofinanceoptioncontracts to continue code i appreciated could print possible put options like xmldates yqlquery select yahoofinanceoptioncontracts symbolhyg dates attr xmldates print attrtag attrtext datesappendattrtext expiration dates xmlcontracts yqlquery select yahoofinanceoptions symbolhyg and expiration expiration option xmlcontracts optionattrib type p print put strike optionfindtext strikeprice lowball ask optionfindtext ask date expiration,i migrating yahoo finance csvscreenscraping interfaces use yql struggling yahoofinanceoptions table if i query options given symbol i find expiration dates associated options if i query symbol expiration i find expiration date associated chain options therein while i familiar cycle options expiration bootstrap given date poor solution one thing generate queries i much prefer introspect data since available screenscraped anybody know get yql i luck here python code i using xmletreeelementtree import elementtree import urllib urllib class yqlobject url httpqueryyahooapiscomvpublicyql env storedatatablesorgalltableswithkeys format xml classmethod def querycls string q urllibquotestring url clsurl amp join qs q envs clsenv formats clsformat resp urlliburlopenurl return elementtreefilerespgetrootfind results chain yqlquery select yahoofinanceoptions symbolwfc chainattrib option chain optionattrib attr option print attrtag attrtext,1 use itertoolsproduct in import itertools in listitproduct out,i list tuples two elements n how would i find combinations tuple selecting one element tuple time the example results itertoolscombinations gives combinations preserve selecting one element tuple thanks,3 did read itertools documentation import itertools l listitertoolsproductl,i list tuples two elements n how would i find combinations tuple selecting one element tuple time the example results itertoolscombinations gives combinations preserve selecting one element tuple thanks,1 unless i missing something problem description ok button command needs copy values entry fields listbox was tkinter import tk frame label entry button listbox def okbutton lidelete end rangelenfields liinsertend eiget root tk roottitlelistbox cf frameroot cfpack fields name address phone dob e f fields lene labelcf textfgridcolumn rowi stickye eappendentrycf width eigridcolumn rowi buttoncf textok commandokbuttongridcolumn row columnspan li listboxcf ligridcolumn row columnspan rootmainloop,i trying add entry toplevel window listbox main window so far i managed create button opens new window containing entry widgetsname address phone number dob is way i press ok button pop window four entries added listbox main window thanks,1 you may find xgoogle useful much seem asking,i asked question realizing general idea crawl save webpages part original question crawl save lot about pages internet with research i got choices go ahead scraping parsing listed bottom today i ran another ruby discussion scrape google search results this provides great alternative problem save effort crawling part the new question python scrape google search results given keyword case about finally get links parsing what best choices methods libraries go ahead measure easytolearn easytoimplement ps website exactly thing implemented closed ask money results i prefer opensource available learn python meanwhile oh btw advices parsing links search results would nice still easytolearn easytoimplement just started learning python p final update problem solved code using xgoogle please read note section order make xgoogle working import time random xgooglesearch import googlesearch searcherror f open atxt wb range wt randomuniform gs googlesearchabout gsresultsperpage gspage results gsgetresults try annnoy google random short wait timesleepwt print this dth iteration waited f seconds wt res results fwriteresurlencodeutf fwriten print done fclose note xgoogle answered mike pennington the latest version github work default already due changes google search results probably these two replies b home page tool give solution currently still working tweak but maybe day may stop working due google changeblock resources known far for scraping scrapy seems popular choice webapp called scraperwiki interesting another project extract library offlinelocal usage mechanize brought quite several times different discussions for parsing html beautifulsoup seems one popular choices of course lxml,3 idea pythonic means two cents import numpy np nparray find locations unique numbers b npwherea find unique numbers u ab iv zipb u try v vlast found sandwich ilast make sure something ailast v else make current unique value beginning next sandwich vlast ilast v except nameerror initialize first match vlast ilast v printa gives right answer,d numpy array lets look following example in array unique entries considered except value we want fill values unique entry resultant look like could easily done looking pythonic way thanks lot,1 you import cookielib seem like using cookiejar jar cookielibcookiejar opener urllibbuildopenerurllibhttpcookieprocessorjar then use opener initial form fetching login form submission i assume cookiebased protection value comes foil field match cookie comes headers another thing i noticed code assign notfoiled absrid instead foil was intentional also please favor use htmllib beautifulsoup instead parsing html manually,trying scrape content site python simple form authentication username password also hidden field called foil contains looks like randomly generated string time page loaded in order successfully login value must included content header post i tried scraping random string login page loads still redirects back login i valid username password site works update sporadically i would like send email something changes code working far import urllib urllib cookielibsubprocess url httpsexamplecomloginasp username blah password blah request urllibrequesturl opener urllibbuildopenerurllibhttphandlerdebuglevel predata openeropenrequestreadlines line predata iffoil line foils linesplit notfoiled foils queryargs location qstring absrid notfoiled id username pin password submit sign in requestwheader urllibrequest httpsexamplecomloginasp requestwheaderadddataurlliburlencodequeryargs print request method data requestwheadergetmethod print print outgoing data print requestwheadergetdata print print server response print urlliburlopenrequestwheaderread rawres urlliburlopenrequestwheaderread the form looks like form nameloginform methodpost actionhttpsexamplecomloginaspxxampampampamppswd input typehidden namelocation value input typehidden nameqstring value input typehidden nameabsrid value input typehidden namefoil valuefcmo input typetext nameid maxlength size value mask descid requiredtrue input typesubmit namesubmit valuesign in onclickreturn checkformloginform input typepassword namepin size maxlength descpin requiredtrue,1 you asked question implicitly asked question how i force setuptools install test dependencies specified testsrequire parameter python environment running install i answer question you cannot specify test requirements installed the whole point testsrequire parameter specify dependencies required installation package running tests imagine many consumers might want install package run tests if want test requirements included installation i would include installrequires parameter for example testrequirements pytest dingus setup testsrequire testrequirements installrequires usual install requirements testrequirements as far i know parameter pass force behavior without changing setup script,when i run python setuppy test dependencies listed testsrequire setuppy downloaded current directory i would like dependencies installed sitepackages dependencies listed requires i run python setuppy install,3 not sure trying achieve first serialize anything json especially replace parts string serialized second uniqueid one value looking if pass query uniqueid foofind id uniqueid or two values like search uniqueid ids uniqueidsplit foofind id ids,i trying create following query python connection i mongodb dbdealfindid by using writing following code import json uniqueid query jsondumpsids uniqueid unfortunately creates string results i get returned results mongodb querying manually using string created variable query actually returns results anyone know i might get working pymongo,1 there twill lib emulating browser i used necessity login google email account while great tool great idea pretty old seems lack support nowadays latest version released it might useful want retrieve results require cookiehandling authentication likely twill one best choices purposes btw based mechanize as parsing right beautifulsoup scrapy great one cool things behind beautifulsoup handle invalid html unlike genshi example,i asked question realizing general idea crawl save webpages part original question crawl save lot about pages internet with research i got choices go ahead scraping parsing listed bottom today i ran another ruby discussion scrape google search results this provides great alternative problem save effort crawling part the new question python scrape google search results given keyword case about finally get links parsing what best choices methods libraries go ahead measure easytolearn easytoimplement ps website exactly thing implemented closed ask money results i prefer opensource available learn python meanwhile oh btw advices parsing links search results would nice still easytolearn easytoimplement just started learning python p final update problem solved code using xgoogle please read note section order make xgoogle working import time random xgooglesearch import googlesearch searcherror f open atxt wb range wt randomuniform gs googlesearchabout gsresultsperpage gspage results gsgetresults try annnoy google random short wait timesleepwt print this dth iteration waited f seconds wt res results fwriteresurlencodeutf fwriten print done fclose note xgoogle answered mike pennington the latest version github work default already due changes google search results probably these two replies b home page tool give solution currently still working tweak but maybe day may stop working due google changeblock resources known far for scraping scrapy seems popular choice webapp called scraperwiki interesting another project extract library offlinelocal usage mechanize brought quite several times different discussions for parsing html beautifulsoup seems one popular choices of course lxml,1 bash uses internal hash table optimize path lookups when install new program name existing program python case earlier path bash know continues use old one the executable full path search prints intended result to fix run command hash python this delete python bash hash table force full path search next time invoke alternatively also run hash r clear hash table entirely the type builtin tell given command interpreted if says command hashed means bash going skip path search executable,can anyone explain python could getting run default machine it looks like python points seems like giving correct information python version python python optlocalbinpython optlocalbinpython version python ls l optlocalbinpython lrwxrxrx root admin oct optlocalbinpython optlocalbinpython when i generate error i see really getting run why could python errormakingargument unknown option e usage libraryframeworkspythonframeworkversionsresourcespythonappcontentsmacospython option c cmd mod file arg try python h information and i correct edit from suggestions comments alias alias cp cp alias gcc gcc wall type python python optlocalbinpython,3 a signed java applet given correct permissions approved user run browser context access files databases however java applets browser almost never used today i java disabled browser years microsoft browsers offer activex way running native code browser i know whether anybody uses today either google nativeclient another method running native code works google browsers time not sure whether allows direct access files,is possible integrate java python objective c directly firefox browser in particular real native tasks writing files connecting local database better yet directly calling systems level code notably post native code execution somewhat slanted towards windows elsewhere stackoverflow firefox extension native code execution,2 if possible trying python much stronger distinction unicode bytes failing need subclass streamwriter example import codecs class strictutfwritercodecsstreamwriter a streamwriter utf requires written objects unicode encode codecsutfencode def writeself object isinstanceobject unicode raise valueerror write requires unicode object return codecsstreamwriterwriteself object,the python codecs module provides streamwriter classes transparently encoding output streams for instance outstream codecsgetwriter utf sysstdout outstreamwriteu u outstreamwrite aokn i want fail outstreamclose however problem i default streamwriter except str objects well unicode objects if program writing str stream bug i want fail is way make happen without writing streamwriter enforces type objects written also i want solution sensitive sysstdoutencoding sysstdoutisatty localegetpreferredencoding sysgetfilesystemencoding osenvironpythonioencoding whatever ways python trying clever,2 pythonext brings python support firefox httpcodegooglecomppythonext i sure quickly update firefox rapid releases need install extension work trusted context ie extension right,is possible integrate java python objective c directly firefox browser in particular real native tasks writing files connecting local database better yet directly calling systems level code notably post native code execution somewhat slanted towards windows elsewhere stackoverflow firefox extension native code execution,1 calling eureadelf command python done elegant readable approach since python stresses readability i say pythonic approach,i trying extract buildid elf file linux kernel module right using subprocesscheckoutput eureadelf n filenamesplit i wondering pythony way achieve result thanks alex,1 textproperty indexed filtered use stringproperty need index,not sure going wrong i trying query simple string datastore query always comes empty modelspy googleappengineext import db googleappengineapi import datastoretypes class postdbmodel author dbtextproperty title dbtextproperty slug dbtextproperty slug str mainpy import wsgirefhandlers googleappengineext import webapp googleappengineextwebapp import util models import import logging import os osenviron djangosettingsmodule settings googleappenginedist import uselibrary uselibrary django djangotemplatedefaultfilters import slugify class mainhandlerwebapprequesthandler def getself store random posts title road perfect car wax title ways get perfect car wax slug slugifytitle slug slugifytitle post postauthortom tomton titletitle slugstrslug post postauthorjohn jonston titletitle slugstrslug posts list postsappendpost postsappendpost dbputposts use filter find post q postall qfilterslug strslug qfilterslug roadtotheperfectcarwax result qfetch empty logginginforesult result selfresponseoutwrite p classitems sp resultauthor resulttitle application webappwsgiapplication mainhandler debugtrue def main wsgirefhandlerscgihandlerrunapplication utilrunwsgiappapplication name main main the output datastore viewer clearly shows right though none tom tomton roadtotheperfectcarwax road perfect car wax none john jonston waystogetaperfectcarwax ways get perfect car wax i tried using app engine versions,1 it place speak worth recommendations i wrote book django mind precisely make sure stayed relevant long possible the aspects django i documented still present functional general aspects python also still valid they may grown additional options along way removed time soon changed backwardincompatible way that said i covered examples best practices also workarounds things django support time because new features added django since released necessarily still best approaches anymore so feel free read factual descriptions things work take recommendations grain salt always consult official documentation latest features,i want dig deeper django internals official online documentation goes far toward end the reviews marty alchin pro django fantastic i read pro python really enjoyed however book based django v my company builds v is book still worthwhile how i best learn django metaprogramming beyond looking source code i also thanks,3 so fact core feature mako templates python it widely used feature important pretty critical custom template tags mention httpwwwmakotemplatesorgdocsdefshtmlcallingadefwithembeddedcontentandorotherdefs jsp one several template systems mako draws inspiration,i java programmer learning pythonjinja my biggest beef jinja macros limitation single caller example could following jsp tags tag def attribute nametitle fragmenttrue div class title titlediv div class body jspdobodydiv usage mytag jspattribute name title cif test blah this sometimescif jspattribute jspbody cif test something dynamic contentcif jspbody mytag want stress body content title attribute content dynamic also hacks setting variables dynamic content passing lets look jinja macro thing macro mytagtitle caller div class title title div div class body caller div endmacro wait cannot easily put dynamic content title attribute call mytagtitle imagine putting content involves loops ifs whatnot something dynamic content endif endcall problem newbie shortcoming jinja,3 try converting string first x result sheetwriterowstrx sheetwriterowstrx,i trying write list cell using python xlwt is possible i currently getting error exception unexpected data type type list the code x result sheetwriterowx sheetwriterowx x list thanks,2 you use runtime local sdk threadsafe mode application defined like script yourapp instead use script yourmainscriptpy for jinja webapp available sdk download place sdk base directory default added syspath you able test multithreading capabilities everything else simply make changes appyaml yourmainscriptpy deploy edit also i osenvironu appengineruntime u python yourmainscriptpy force sdk use webapp,gae looks excellent longwaited features however working yet i downloaded installed gae using degenerate aaa app test here roughly appyaml various changes made testing appyaml application aaa mystical creation version alpha runtime python apiversion threadsafe true handlers url media staticdir media url faviconico staticfiles mediaimagesfaviconico upload mediaimagesfaviconico url admin script aaaapp login admin url script aaaapp skipfiles appyaml libraries name django version name jinja version latest name yaml version latest i running mac os x lion i hypothesize i actually using python runtime spite declaration appyaml use i quite sure validate theory errors i encountered consistent these errors reproduced python path when google app engine python path set app engine runs using python to fix i set python path usrbinpython google app engine preferences wsgi i get following error applicationsgoogleappenginelauncherappcontentsresources googleappenginedefaultbundlecontentsresourcesgoogleappengine googleappenginetoolsdevappserverpy getparentpackageselfgoogleappenginetoolsdevappserverhardenedmoduleshook object fullname aaaapp selffindmodulefullname none raise importerror could find module fullname return selfmoduledictparentmodulefullname builtin importerror type exceptionsimporterror fullname aaaapp type exceptionsimporterror could find module aaaapp args could find module aaaapp message could find module aaaapp where i tried aaaapp aaapy googleappenginedist import uselibrary uselibrary django otherwise still get django djangocorehandlers import wsgi app wsgiwsgihandler aaa initpy content aaaaaapy content note i continue run cgi appyaml aaapy modified mutatis mutandis however nevertheless results errors jinja when i run import jinja i get importerror django without googleappenginedist import uselibrary uselibrary django i end django theory given following httpcodegooglecomappenginedocspythontoolslibrarieshtml states the uselibrary function provided googleappenginedist package unavailable python uselibrary works uselibrary required libraries django version declaration set django version only django included python runtime per librarieshtml link i manually specify python python path order gae use python wsgi load application properly jinja cannot imported i believe i really using python gae runtime ie appyaml declaration ignored gae sdk i hope helpful description i grateful thoughts may happening – potential solutions,2 local variables exist outside enclosing function every time call function getting whole new variable number value count assignments run if want variables outlive function two options make globals make function method class variables instance variables class globals approach number value number count def getcount global number value count value value etc class approach class fooobject def initself selfnumber selfvalue number selfcount def getcount selfvalue selfvalue etc note class approach need use self access instance variables,i function defines number determines last digit formula based last number until number reaches yes project euler problem function runs original number decreased function run already realise painfully bad method know exactly get correct answer make code alot sexier quicker find answer code def getcount number value number count value value count value elif value count value elif value count value elif value count value elif value count value elif value value value count elif value value value count elif value value value count elif value value value count elif value value value count print count number getcount getcount but run gives answer twice instead minusing stays missing something i working back million figured higher stepcount would higher number eventually proven correct wrong james edit i solved issue code number def getcount value number count value value count value elif value count value elif value count value elif value count value elif value count value elif value value value count elif value value value count elif value value value count elif value value value count elif value value value count print number count num num num getcount number although seriously seriously bad super slow run neeeded shall find way make faster find way give direct answer,2 finally i got answer to setup plurk api first need python setuptoolgoogle download afterwards move directory plurk api placed cmd mode type python setuppy notice need install python install python setuptool sample code test install plurk api successfully coding utf plurkoauthplurkapi import plurkapi query beauty plurk plurkapi your app key your app secret plurks plurkcallapi appplurksearchsearch query query p plurksplurks print pcontent,i try fetch data plurk using search function httpwwwplurkcomapisearch i know i provide app key app secret i registered application but i read official document httpwwwplurkcomapi python library provides httpsgithubcomclsungplurkoauth i still even know start i downloaded library i sure install therefore know call apis can someone teach start calling plurk api i want search things thanks and i sorry poor english,1 using generator saves memory xrange instead range python x anyway i came it similar ntosum without need compress def fns n yield else xranges j fn yield j l listf print total permutations lenl first last list l l print output total permutations,i trying generate possible lists length n sum s i written code anything large particular i want n s i run memory overflow errors i looking either better solution problem way improve code i run n s these two programs work tandem create possible number combinations nested lists rework right format some sample output reproduced i know code best i engineer trade i know i know coding exactly forte i appreciate help provide edit i wanted clarify thing first ok zero lists lists contain multiples number order numbers lists matters def ntosumns creates nested list possible lists length n sum s n base case return s else l x ranges create sublist possible entry s l xntosumnsx create sublist value recursively return l def compressnl designed take list generated ntosum takes input ntosum list l flattens list top level list leading set n prefix list grows climb sublists typel int base case exposed pure integer return nl take integer prepend leading set n else q x l look every sublist q compressnxx sublist create top level lists recursively return q note append x leading set n ntosum compressntosum,2 this post old still turns searches mac homebrew python i thought i add useful information i problem op different module uwsgi i learned abandon homebrew homebrew fact install python framework tell brew uninstall python uninstalling usrlocalcellarpython brew install python universal framework well,i trying run modwsgi apache using nondefault python installation mac os x after downloading modwsgi source i run sudo apachectl k stop configure withpythonusrlocalcellarpythonbinpython make sudo make install i start apache sudo apachectl k start when i cat varloghttpderrorlog i see mon dec warn modwsgi compiled python mon dec warn modwsgi runtime using python mon dec notice apache unix dav modwsgi python configured resuming normal operations when i run otool l modwsgiso see modwsgiso systemlibraryframeworkspythonframeworkversionspython compatibility version current version usrliblibsystembdylib compatibility version current version what gives why linking system framework here output modwsgi configure build commands archimedesmodwsgi awolf configure withpythonusrlocalcellarpythonbinpython checking apxs checking apxs optapachebinapxs checking apache version configure creating configstatus configstatus creating makefile archimedesmodwsgi awolf make optapachebinapxs c iusrlocalcellarpythonincludepython dndebug wc arch x modwsgic lusrlocalcellarpythonlib lusrlocalcellarpythonlibpythonconfig arch x lpython ldl librarywebserverbuildlibtool silent modecompile gcc preferpic ddarwin dsigprocmasksetsthreadmask nocppprecomp g o ioptapacheinclude ioptapacheinclude ioptapacheinclude arch x iusrlocalcellarpythonincludepython dndebug c modwsgilo modwsgic ampamp touch modwsgislo in file included usrlocalcellarpythonincludepythonpythonh modwsgic usrlocalcellarpythonincludepythonmodsupporth warning pyargparsetuple unrecognized format function type librarywebserverbuildlibtool silent modelink gcc modwsgila rpath optapachemodules module avoidversion modwsgilo lusrlocalcellarpythonlib lusrlocalcellarpythonlibpythonconfig arch x lpython ldl archimedesmodwsgi awolf sudo make install password optapachebinapxs s libexecdiroptapachemodules n modwsgi modwsgila librarywebserverbuildinstdsosh shlibtool librarywebserverbuildlibtool modwsgila optapachemodules librarywebserverbuildlibtool modeinstall cp modwsgila optapachemodules cp libsmodwsgiso optapachemodulesmodwsgiso cp libsmodwsgilai optapachemodulesmodwsgila cp libsmodwsgia optapachemodulesmodwsgia chmod optapachemodulesmodwsgia ranlib optapachemodulesmodwsgia,1 the xlrd documentation states clearly from excel onwards text excel spreadsheets stored unicode since likely reading files newer containing unicode codepoints anyway it therefore necessary keep content cells unicode within python convert ascii str function use code book openworkbook filexls sheettwo booksheetbyindex make sure writing unicode encoded utf open outputfile w rangesheettwonrows z toprint uformatting data im writing important stuff right unicodesheettwocellzyvalue u formatting unicodesheettwocellzxvalue u donen outwritetoprintencode utf,i reading large amount data excel spreadsheet i read reformat rewrite spreadsheet using following general structure book openworkbook filexls sheettwo booksheetbyindex open outputfile w rangesheettwonrows z toprint formatting data im writing important stuff right strsheettwocellzyvalue formatting strsheettwocellzxvalueencode utf done outwritetoprint outwriten x arbitrary cells case x less arbitrary containing utf characters so far i using encode utf cells i know errors otherwise foresee error without using utf my question basically disadvantage using encode utf cells even unnecessary efficiency issue main issue works even utf character place if errors would occur i lump encode utf onto every cell read i probably end,2 just simple example using mayavi mlab interface with geologic data even mayavi import mlab import geoprobe vol geoprobevolume volumesexamplevol data volload data d numpy array uint fig mlabfigurebgcolor fgcolor size grid mlabpipelinescalarfielddata have things display kilometers vertical exxageration each voxel actually represents meter volume gridspacing voldxw voldyw voldz now let display cut planes these interactive set dragged around volume if prefer noninteractive cut planes look mlabpipelinescalarcutplane instead orientations x x z startingpositions volnx volnx volny volnz orientation startpos ziporientations startingpositions plane mlabpipelineimageplanewidgetgrid colormap gray planeorientation saxes orientation sliceindexstartpos high values black low values white planemodulemanagerscalarlutmanagerreverselut true mlabshow the data dataformathandling code geoprobe module available httpcodegooglecomppythongeoprobe while i agree learning vtk better long run get upandrunning quite quickly mayavi the big advantage jump hoops get data vtk format tvtk mayavi allow directly use numpy arrays,in day job phd student i geological modeling in spare time mainly fun i learning python trying write simple program view d geocellular models the geocellular model d grid every grid cell value shown right figure so i would want viewer able display d grid model like picture right side as well i would like able display cross sections model x z directions shown left figure i would also want models able rotate around three axes zoom i done preliminary investigation mainly seems like visvis vtk two potential options i trying use wxpython main gui looks like options work wxpython far i tell questions am i right i say i think visvis vtk would work i want is one preferable which two options would easiest implement is another option i also consider keep mind i newish python new wxpython,3 it trying connect computer running port connection refused are sure server running if use netcat testing nc l k p some implementations may require omit p flag,i trying wrap head around sockets work i trying pick apart sample code i found page simple client socket program since basic sample code i assumed errors i try compile i get following error message file clientpy line clientsocketconnect localhost file line connect socketerror errno connection refused i googled pretty much every part error people similar problems seem helped changing port number using connect instead bind things none applied situation any help greatly appreciated since i new network programming fairly new python by way code case link work whatever reason client example import socket clientsocket socketsocketsocketafinet socketsockstream clientsocketconnect localhost data clientsocketrecv data q data q clientsocketclose break else print recieved data data rawinput send type q q quit data q data q clientsocketsenddata else clientsocketsenddata clientsocketclose break,3 it looks like client trying connect nonexistent server in shell window run nc l running python code it act server listening port connect then play typing python window seeing appear terminal vice versa,i trying wrap head around sockets work i trying pick apart sample code i found page simple client socket program since basic sample code i assumed errors i try compile i get following error message file clientpy line clientsocketconnect localhost file line connect socketerror errno connection refused i googled pretty much every part error people similar problems seem helped changing port number using connect instead bind things none applied situation any help greatly appreciated since i new network programming fairly new python by way code case link work whatever reason client example import socket clientsocket socketsocketsocketafinet socketsockstream clientsocketconnect localhost data clientsocketrecv data q data q clientsocketclose break else print recieved data data rawinput send type q q quit data q data q clientsocketsenddata else clientsocketsenddata clientsocketclose break,1 you might confusing compilation execution python compilation step as soon type python myprogrampy program runs case tries connect open port giving error server program listening it sounds like familiar twostep languages require compilation produce executable — thus confusing python runtime compilaint “i find anyone listening port ” compiletime error but fact python code fine need bring listener running,i trying wrap head around sockets work i trying pick apart sample code i found page simple client socket program since basic sample code i assumed errors i try compile i get following error message file clientpy line clientsocketconnect localhost file line connect socketerror errno connection refused i googled pretty much every part error people similar problems seem helped changing port number using connect instead bind things none applied situation any help greatly appreciated since i new network programming fairly new python by way code case link work whatever reason client example import socket clientsocket socketsocketsocketafinet socketsockstream clientsocketconnect localhost data clientsocketrecv data q data q clientsocketclose break else print recieved data data rawinput send type q q quit data q data q clientsocketsenddata else clientsocketsenddata clientsocketclose break,2 try def displayself selfimagedisplay photoimagefile cimagegif x xrange selfimagedisplaywidth xrange selfimagedisplayheight raw selfimagedisplaygetx rgb tuple intcomponent component rawsplit selfimagedisplayput xxx rgb x c canvasself width height cpack cgridpadxpady column row ccreateimage image selfimagedisplay anchor nw edit new version faster optimizations justin peel def displayself selfimagedisplay photoimagefile cimagegif wrange xrange selfimagedisplaywidth hrange xrange selfimagedisplayheight get selfimagedisplayget put selfimagedisplayput def convertpixelraw return xxx tuple intcomponent component rawsplit hrange put joinconvertpixelgetx x wrange c canvasself width height cpack cgridpadx pady column row ccreateimage imageselfimagedisplay anchornw,i attempted today create python code invert colors gif image using tkinter library the code works exactly i expected takes seconds run ghz processor i trouble seeing i could change optimize basically i loop every pixel image grab color values convert list integers order manipulate mathematically invert color value new color value old color value convert back string photoimage put method process rewrite image finally display inverted image i think change i mean looping every single pixel must part slowness process completely necessary tkinter import import tkmessagebox class guiframeworkframe def initself masternone frameinitself master selfgridpadx pady selfbtndisplay buttonself textdisplay commandselfdisplay selfbtndisplaygridrow column def displayself b selfimagedisplay photoimagefile cimagegif x range selfimagedisplaywidth range selfimagedisplayheight value selfimagedisplaygetxy value try c inti except bappendinta bappendinta range bi bi selfimagedisplayput xxx tupleb xy b c canvasself width height cpack cgridpadxpady column row ccreateimage image selfimagedisplay anchor nw name main guiframe guiframework guiframemainloop thanks advance help seth,2 you need use npybool rather pyarraybool also need using numpy header rather numeric header still using numeric header like one questions,i numpy array bools code i wish write c extension when i try get contiguous array order use c routine i use arrmask pyarrayobject pyarraycontiguousfromobjectmask pyarraybool but i get compiler error pyarraybool declared xormaskingc error ‘pyarraybool’ undeclared first use function why is type undeclared if i introduce array bools c thanks,1 this equivalent trying may slightly readable optionsfilename none none optionssearchand optionssearchnot optionssearchstart optionssearchthen parsererrorusage sysexit,i set arguments dest searchand searchnot searchstart searchthen filename the code i catch error optionsfilename none optionssearchand none optionssearchnot none optionssearchstart none optionssearchthen none parsererrorusage sysexit it may seem like silly mistake someone tell going edit i added end make sure closes properly still says invalid syntax optionsfilename none optionssearchand none optionssearchnot none optionssearchstart none optionssearchthen none edit here i far import optparse optionparser usage useage prog options parser optionparserusage parseraddoptiona typestring destsearchand helpfind all lines file word and word parseraddoptionb typestring destsearchnot helpsearch find lines contain words word parseraddoptionc typestring destsearchstart helpsearch find line starts word word parseraddoptiond typestring destsearchthen helpsearch find line word followed word parseraddoptionf file typestring destfilename helpfile name optionsfilename none optionssearchand none optionssearchnot none optionssearchstart none optionssearchthen none after code run python scriptpy hi bye i get invalid syntax statement,1 re jason answer note contentfile accepts strings filelike object here one djangocorefilesbase import class streamfilecontentfile django provide file wrapper suitable filelike objects eg stringio def initself stream supercontentfile selfinitstream streamseek selfsize streamtell now stuff like photoimagesavename streamfileio,class mymodelmodelsmodel image modelsfilefielduploadtoblagh blagh spam i file memory i want save via django filefield save method like photoimagesavename buffer second arg django file i tried use stringio extend djangocorefilesfile thus implement method chunks i wrapped file object like buffile filebuffer name first argument file photoimagesavename buffile but file methods use size name fields supplied file stringio define i found link dead,3 i reproduce the exact code downloaded picture i using python it either server time internet connection,i problem dowloading image flickrcomthe python function urlliburlretrieve always return error errno socket error operation timed example import urllib url httpfarmstaticflickrcomedogif urlliburlretrieveurlctmpgif i chineseand i dont know time anything speed internet china now falied downing gif thx any suggestion appreciated,1 simple answer course write this module python module built use without lot work real answer probably everything want already whole philosophy django dry don repeat yourself builtin handle situation use instead reinventing wheel you certainly write method authentication presented good argument post just poured docs feel comfortable conforming enough see current tools available work if time define whywhy need accomplish going the builtin session users groups fantastic take time learn work together,till i used django default authenticate login method login code projectsee code login code def loginrequest requestmethod post username requestpostget username password requestpostget password iflenusernamestrip return rendertoresponse loginhtml errormessage username empty username username contextinstancerequestcontextrequest iflenpasswordstrip return rendertoresponse loginhtml errormessage password empty username username contextinstancerequestcontextrequest authuser authenticateusernameusername passwordpassword authuser authuserisactive try loginrequest authuser except runtimeerror typeerror nameerror errmessage errormessage runtimeerror typeerror nameerror capturloglogdatarequest loginerror login errmessage else capturloglogdatarequest login login successfully logged in return httpresponseredirectreverse indexhome else return rendertoresponse loginhtml errormessage invalid user username username contextinstance requestcontextrequest return rendertoresponse loginhtml contextinstancerequestcontextrequest this code works well i dont want use django default methodinstead thati wanna use method check authentication loginis possible i add lines codes authentication authuser authenticatecheckusername password def authenticatecheckusernamenone passwordnone try username user userobjectsgetemailusername else user userobjectsgetusernameusername except userdoesnotexist return none check password usercheckpasswordpassword return user then i tries loginrequest user work it shows error line ie backend found is possible write manual code authentication amp login rather using django default method thanks advance,1 yes python type except class modulepackage,i something like import mynewclass can i add method mynewclass something like following concept def newmethodselfx return x selfy mynewclassnewmethod newmethod i using cpython,2 assigning self inside method updates variable self points method update object to load instead return newly loaded object classmethod function try code like import pickle class patientobject def initself name selfname name def saveself location filename thefile openstrlocationstrfilename pkl wb pickledumpselfthefile thefileclose classmethod def loadcls location filename thefile openstrlocationstrfilename pkl rb pickleloadthefile thefileclose return p patientbob print pname save patient psavectemp bob load patient could new session l patientloadctemp bob print lname,i trying pickle patient object using thefile openstrlocationstrfilename pkl wb pickledumpselfthefile thefileclose this works well successfully writes file desired but when i try load data thumb i get eof error xor loads old data present thumb i know old data coming considering pickle contains correct saved data loading operation thefile open mediasuperhrethumbpatientpkl r self pickleloadthefile thefileclose an example would i change attribute desired object save the attribute clearly saved pickle file i reload pickle file another computer read pickle loads old data i checked see reading pickle are subtle nuances pickles i missing or i using wrong read write arguments pickle saving loading,1 could model class class essaymodel authors modelsmanytomanyfieldauthor essayauthor property def stateself selfauthorscount return selfauthorsstate else return null i think annotate queryset fly case especially use one author multiple logic another option would use extra construct complex sql query additional data,class authormodel state modelscharfield st class essaymodel authors modelsmanytomanyfieldauthor essayauthor mylist essay a essay b essay c essay a mylist queryset i want add another property instances essay mylist state author it assumed states books one author equivalent thus essay authors matter author used thus i want able essay mylist essaystate ak the annotate method useful numericfloat values i cannot use if i use generator inject property i reconstruct queryset,1 you need pair element a corresponding element b mod x x zipa b,i need little bit help homework problem school using python the prompt pretty simple i seem figure remab returns list ab ab etc rem x range y j j range remxy rem rem i created snippet code sort works quite def remab return a b b b right definition working first value sequence i think due a i need way make ax i sure also i pretty sure i use range somewhere definition well if anyone could help tell i missing would extremely grateful thank you john,3 settextcolour setbackgroundcolour methods entire listctrl items for items use valid report mode getitemtextcolouridxitem setitemtextcolouridxitem col insertitemindex item item instance wxlistitem one insertitem methods add new row listctrl setstringitemindex col label imageid index col parameters row column indexes cell allows setting strings selected column other insert methods work first column reference wxpython action noel rappin robin dunn,trying write string listctrl i understand logic completely is proper way selfrightpanel wxlistctrlspliter stylewxlcreport selfrightpanelinsertcolumn linenumber selfrightpanelinsertcolumn log selfrightpanelsetcolumnwidth selfrightpanelsetcolumnwidth def writeconsoleselfstr item wxlistitem itemsettextstr itemsettextcolourwxred itemsetbackgroundcolourwxblack index selfrightpanelgetitemcount selfrightpanelinsertitemitem selfrightpanelsetstringitemindex strindex selfrightpanelsetstringitemindex itemgettext why text displayed color why different methods display text listctrl listctrlinsertitem listctrlsetstringitem i think insertitem loads item listsetstring displays item contentnot sure,3 the line statement parseraddoptionf file typestring destfilename helpfile name closing python interpreter usually complains syntax errors next lineso get syntax error line advisable check preceding line well,i set arguments dest searchand searchnot searchstart searchthen filename the code i catch error optionsfilename none optionssearchand none optionssearchnot none optionssearchstart none optionssearchthen none parsererrorusage sysexit it may seem like silly mistake someone tell going edit i added end make sure closes properly still says invalid syntax optionsfilename none optionssearchand none optionssearchnot none optionssearchstart none optionssearchthen none edit here i far import optparse optionparser usage useage prog options parser optionparserusage parseraddoptiona typestring destsearchand helpfind all lines file word and word parseraddoptionb typestring destsearchnot helpsearch find lines contain words word parseraddoptionc typestring destsearchstart helpsearch find line starts word word parseraddoptiond typestring destsearchthen helpsearch find line word followed word parseraddoptionf file typestring destfilename helpfile name optionsfilename none optionssearchand none optionssearchnot none optionssearchstart none optionssearchthen none after code run python scriptpy hi bye i get invalid syntax statement,2 in particular real native tasks writing files connecting local database better yet directly calling systems level code you need extra language firefox extensions already writing files connecting local sqlite database calling system libraries directly i would recommend attempting write extension anything javascript several possibilities create lot trouble worth if anything could create native library call javascript code via jsctypes see link,is possible integrate java python objective c directly firefox browser in particular real native tasks writing files connecting local database better yet directly calling systems level code notably post native code execution somewhat slanted towards windows elsewhere stackoverflow firefox extension native code execution,2 in python import statement used modules classes import class need something like mymodule import myclass more point question answer yes in python classes regular objects class method function stored object attribute attributes object instances python moreover dynamic add new object attributes runtime fact combined previous one means add new method class runtime class myclass def initself x selfx x obj myclass def newmethodself print x attribute selfx myclassnewmethod newmethod objnewmethod how work when type objnewmethod python following look newmethod inside object obj not finding instance attribute try looking inside class object available objclass find function now bit trickery python notice found function therefore wrap closure create called bound method this needed call objnewmethod want call myclassnewmethodobj words binding function obj create bound method takes care adding self parameter this bound method returned objnewmethod finally called ending line code if search class also succeed instead parent classes also searched specific order find inherited methods attributes therefore things little bit complex,i something like import mynewclass can i add method mynewclass something like following concept def newmethodselfx return x selfy mynewclassnewmethod newmethod i using cpython,3 you reinvent wheel python csv module perfect job import csv csvfile open deggscsv rb csvreader csvreadercsvfile row csvreader print row csvfileclose see python csv,i csv file contains following values spampankspamspamspam spamspamspamspam and using following python code read particular column line open deggscsv rb columns linesplit print columns the output gives spam spam expecting spampank spam please help,3 well first i think rolling solution need urllib httplib anyways case require generic rest client check httpsgithubcomscastillosiesta however think feature set library work web services shall probably using oauth etc also i like fact written httplib pain compared httplib still work handle lot redirections etc,is standard way getting json data restful service using python i need use kerberos authentication snippet would help,2 it possible pack one line projectobjectsfiltertagsincurrentprojecttagsallannotatecount name orderby namecount or broken steps tags currentprojecttagsall matches projectobjectsfiltertagsintagsannotatecount name results matchesorderby namecount the logic goes follows currentproject instance project want relations the filter selects projects tags current project the annotate adds variable return values counts number similar names as projects match multiple tags returned multiple times value indicative number matches the results sorted annotated namecount variable to get top results list capped using,i project tag models application manytomany relationship on project page i want list additional projects tags common how i perform query class tagmodelsmodel name modelscharfieldmaxlength class projectmodelsmodel name modelscharfieldmaxlength tags modelsmanytomanyfieldtag,2 i would give requests library try essentially much easier use wrapper around standard library modules ie urllib httplib etc would use thing for example fetch json data url requires basic authentication would look like import requests response requestsget httpthedataisherecom auth user password data responsejson for kerberos authentication requests project reqestskerberos library provides kerberos authentication class use requests import requests requestskerberos import httpkerberosauth response requestsget httpthedataisherecom authhttpkerberosauth data responsejson,is standard way getting json data restful service using python i need use kerberos authentication snippet would help,3 something like work unless i missing point import json import urllib jsonloadurlliburlopenurl,is standard way getting json data restful service using python i need use kerberos authentication snippet would help,3 that completely depends a if merely invokes mapping protocol use problem if requires details type passed chance fail run correctly,function a gets ordinary dict argument processing def adict return now i class inherited ordinary dict class class mydictdict def getitemself key return dictgetitemself key def setitemself key val dictsetitemself key val then i use mydict instead ordinary dict mydict mydict amydict specifically case a xmlrpc serialization error says cannot marshal mydict,1 you want operatormethodcaller or course list generator comprehension,i need something functionally equivalent foo foos bar foogetbar do something bar my first instinct use map work bar mapgetbar foos do something bar is i trying accomplish possible map do i need use list comprehension instead what pythonic idiom,3 you could use descriptor class selectobject def getselfobjobjtype xobjtype obj none else obj def selectwhere printxwhere return select class booksobject selectselect book books booksselectwhere asdf bookselectwhere asdf yields class mainbooks asdf mainbooks object xbdec asdf,i class books method select also instance class called book i want able booksselectwhere bookselectwhere class books def selectobj printobj book books booksselectwhere asdf bookselectwhere asdf the obviously work select instance bound method traceback recent call last file testpy line module booksselectwhere asdf typeerror select takes exactly arguments given a working code class books staticmethod def selectobj printobj book books booksselectbooks asdf booksselectbook asdf and get vicwicprojectssnippets python testpy class mainbooks asdf mainbooks object xfdd asdf but manually pass class instance first argument select method want if make select class method class books classmethod def selectobj printobj book books booksselectwhere asdf bookselectwhere asdf i always get class first argument vicwicprojectssnippets python testpy class mainbooks asdf class mainbooks asdf but want get instance second case so way accomplish want without manually passing classinstance first argument static method,1 you basically need make http request service parse body response i like use httplib import httplib http import json try urlparse import urlparse except importerror urllibparse import urlparse headers accept applicationjson contenttype applicationjson charsetutf uri httpyourservicecom path pathtoresource target urlparseuripath method get body h httphttp if need authentication example auth haddcredentialsauthuser authpassword response content hrequest targetgeturl method body headers assume content json reply parse content json module data jsonloadscontent,is standard way getting json data restful service using python i need use kerberos authentication snippet would help,3 either lambda bar maplambda foo foogetbar foos methodcaller import operator getbar operatormethodcaller getbar bar mapgetbar foos generator expression bar foogetbar foo foos,i need something functionally equivalent foo foos bar foogetbar do something bar my first instinct use map work bar mapgetbar foos do something bar is i trying accomplish possible map do i need use list comprehension instead what pythonic idiom,3 this modified code work bar maplambda f fgetbar foos do something bar you provide lambda function simply providing getbar work accessible instance class fgetbar never,i need something functionally equivalent foo foos bar foogetbar do something bar my first instinct use map work bar mapgetbar foos do something bar is i trying accomplish possible map do i need use list comprehension instead what pythonic idiom,1 you use lambda bar maplambda foo foogetbar foos do something bar,i need something functionally equivalent foo foos bar foogetbar do something bar my first instinct use map work bar mapgetbar foos do something bar is i trying accomplish possible map do i need use list comprehension instead what pythonic idiom,1 httpdocspythonorglibraryfunctionshtmlid return “identity” object this integer long integer guaranteed unique constant object lifetime two objects nonoverlapping lifetimes may id value python implementation detail this address object memory why think ids would constant,i really confuse behavior id function ironpython differ python let show following code in ironpython hello lens ida lens ida as see id result changed every calls in python however changed in python hello lens ida lens ida i know id function returns object identification numberid single parameter why two python interpreters give different result,1 cpython cache constant small integers used whenever needed this pool integers optimisation improves performance new object need allocated every small integer needed evidently ironpython handles differently that said id function returns number uniquely identifies object you use see whether two names bound object you cannot use value see whether two objects equal sense,i really confuse behavior id function ironpython differ python let show following code in ironpython hello lens ida lens ida as see id result changed every calls in python however changed in python hello lens ida lens ida i know id function returns object identification numberid single parameter why two python interpreters give different result,1 i use sniff autodetect import csv dialect csvsniffersnifffilereadline fileseek filereadline fileseek fieldnames assignatura professor grup reader csvdictreaderfile fieldnamesfieldnames dialectdialect row reader codifranja unicoderow assignatura iso edited if planning create csv python read excel need create file locale delimiter but python csv module use locale httpmailpythonorgpipermailcsvmayhtml andreas this could really simple implement using locale module but i took short look locale module seems like way get list separator sign probably posix complaint a workaround may write delimiters configuration file python user client instalation based locale desktop computer read delimiters python make csv file also write vbscript code creates excel file exports csv look delimiter time need create python csv file perhaps elegant solution use schemaini httpmsdnmicrosoftcomenuslibrarywindowsdesktopmsvvsaspx you generate csv file foleder schemaini file,detect list separator users machine python csv file needs created users machine list separator must detected automatically excel read csv file i found excel takes csv elements separator regional options numbers list separator locale module python used detect cultural settings localelocaleconv contain list separator opening csv writer dialect excel help any idea get correct separator edit the following code seems work accept upvotes solution mine import locale langlocale localegetdefaultlocale localesetlocalelocalelcall langlocale dp localelocaleconv decimalpoint delimiter dp delimiter,1 use dictionary animals keys objects items example animals animals cat objectone animal cat animalsanimalfunct,so i one function object class objectone def functself do stuff and i would like i create two instaces object dog objectone cat objectone when variable animal created contains cat would run catfunct and variable contains dog would run dogfunct any way thanks advance guys ev d to clarify i use statement i gain different instances object i want add stuff final code call object function something like animalfunct in animal variable instance object thanks guys,1 you synchronously asynchronous system but solve problem using threads the basic idea start thread wait channel whenever comes wait calls callback function returned message returned message queue you deal message however want callback function def registercallbackchannel callback this method sets thread deals asynchronous callback message could routed exchange def wait try channelwait except exception e printproblem waiting publish channel stre channelreturnedmessagesempty returnedmessage channelreturnedmessagesget processreturnedmessagethread threadtargetcallback argsreturnedmessage processreturnedmessagethreadstart wait waiting threadtargetwait waitingstart,i like make sure message delivered queue to i adding mandatory param basicpublish what else i receive basicreturn message message successfully delivered i use channelwait listen basicreturn message successfully delivered wait function hangs forever there timeout on hand when i call channelwait channelreturnedmessages remain empty even message delivered i use pyamqplib version any solution welcome,1 solution using descriptor decorator class classorinstancemethod def initself method selfmethod method def getself obj objtype x obj objtype def wrappedargs kwargs return selfmethodx args kwargs return wrapped class books classorinstancemethod def selectobj printobj book books booksselectwhere asdf bookselectwhere asdf result class mainbooks asdf mainbooks object x asdf,i class books method select also instance class called book i want able booksselectwhere bookselectwhere class books def selectobj printobj book books booksselectwhere asdf bookselectwhere asdf the obviously work select instance bound method traceback recent call last file testpy line module booksselectwhere asdf typeerror select takes exactly arguments given a working code class books staticmethod def selectobj printobj book books booksselectbooks asdf booksselectbook asdf and get vicwicprojectssnippets python testpy class mainbooks asdf mainbooks object xfdd asdf but manually pass class instance first argument select method want if make select class method class books classmethod def selectobj printobj book books booksselectwhere asdf bookselectwhere asdf i always get class first argument vicwicprojectssnippets python testpy class mainbooks asdf class mainbooks asdf but want get instance second case so way accomplish want without manually passing classinstance first argument static method,1 you seem trying cram many things view what i following create view generates xml every request view generate xml scratch create view uses timeline widget points xml enable django caching layer annotate xml view appropriately eg cachepage if reason need xml time generation html seem indicate title directly call xml view html one eg cachepage def xmlrequest generate xml def htmlrequest xml xmlrequest generate timeline xml of course nothing stopping manually caching disk easier use django facilities,what i trying use simile timeline django app the timeline requires data xml file now i know render view html and i probably figure render view xml but would one render pull xml data html file xml file exist disk since generated django thanks edit the line takes xml javascript looks like timelineloadxmlstaticexamplexml functionxmlurl eventsourceloadxmlxmlurl i need path since inserting xml directly string work but path exists since xml file never actually exists disk,1 if know ancestor simply test bspam aspam false bham aham true and find list base classes look python list base classes hierarchy i shall also point need class design probably wrong you care things oop unless creating object inspector something like,i want tell inherited methods apart overloaded newly defined methods is possible python example class aobject def spamself print a spam def hamself print a ham class ba def spamself print overloaded spam def eggsself print newly defined eggs desired functionality magicmethodbspam overloaded magicmethodbham inherited magicmethodbeggs newly defined is magic method like example way tell types method implementations apart,3 what really solves problem put input use rawinput instead liste inp rawinput skriv et tall mellom og inp leni inp rawinput skriv et tall mellom og may want change text iinp t print du er videre til neste rom print du er naa rom strj j j elif iinp b print du falt et bunnlost hull og er na break elif iinp f print du dode en felle break elif iinp m print du slapp unna break,liste inp input skriv et tall mellom og inp leni print hooooore elif iinp t print du er videre til neste rom print du er naa rom strj j j elif iinp b print du falt et bunnlost hull og er na break elif iinp f print du dode en felle break elif iinp m print du slapp unna break if user enters number greater length array i want make structure stop possible that way araay wont run away counter j i solved problem using statement but still interested i solve using statement if iinp t i want operate def spillliste j j lenliste inp input skriv et tall mellom og strlenlistei inp lenlistei print hooooore inp input skriv et tall mellom og denne gangen elif listeiinp t print du er videre til neste rom fordi denne doren var trygg print du er naa rom strj j j elif listeiinp b print her er det et hull ikke ga elif listeiinp f print her er det en felle elif listeiinp m print du slapp unna break this code see,1 i sure good idea probably using hasattr dict def magicmethodclazz method method clazzdict not defined clazz inherited return inherited elif hasattrsuperclazz method present parent overloaded return overloaded else not present parent newly defined return newly defined,i want tell inherited methods apart overloaded newly defined methods is possible python example class aobject def spamself print a spam def hamself print a ham class ba def spamself print overloaded spam def eggsself print newly defined eggs desired functionality magicmethodbspam overloaded magicmethodbham inherited magicmethodbeggs newly defined is magic method like example way tell types method implementations apart,3 a general way python def getclassmethod try return methodimclass except attributeerror return methodclass def magicmethodmethod methodcls getclassmethod methodname methodclsdict return inherited cls methodclsmro methodname clsdict return overloaded return newly defined test example class aobject def spamself print a spam def hamself print a ham class ba def spamself print overloaded spam def eggsself print newly defined eggs magicmethodbspam overloaded magicmethodbham inherited magicmethodbeggs newly defined magicmethodbinit inherited,i want tell inherited methods apart overloaded newly defined methods is possible python example class aobject def spamself print a spam def hamself print a ham class ba def spamself print overloaded spam def eggsself print newly defined eggs desired functionality magicmethodbspam overloaded magicmethodbham inherited magicmethodbeggs newly defined is magic method like example way tell types method implementations apart,2 cygpath w you read manual page switches among w windows u unix absolute path you need careful escaping make sure path argument single shell word,im writing python script executed cygwin one things calling pgdump passing file name problem pythoncygwin passing posix path windows version pgdump know something call convert posix path windows path want convert path cygdrivecusersmecodemyprojpybuildscriptsrcsnapshooterworkingssosql cusersmecodemyprojpybuildscriptsrcsnapshooterworkingssosql,1 a multiprocessingprocess pterminate in cases i want kill thread want use flagslockssignalssemaphoreseventswhatever i promote threads full blown processes for code makes use threads overhead bad eg comes handy easily terminate helper threads execute blocking io the conversion trivial in related code replace threadingthread multiprocessingprocess queuequeue multiprocessingqueue add required calls pterminate parent process wants kill child p python doc,is possible terminate running thread without settingchecking flagssemaphoresetc,3 write xls file xlwt take use locale module heuristics import locale localesetlocalelocalelcall set user locale c englishaustralia decptchr localelocaleconv decimalpoint decptchr listdelimiter else listdelimiter print reprdecptchr reprlistdelimiter localesetlocalelocalelcall frenchfrance frenchfrance decptchr localelocaleconv decimalpoint decptchr listdelimiter else listdelimiter print reprdecptchr reprlistdelimiter,detect list separator users machine python csv file needs created users machine list separator must detected automatically excel read csv file i found excel takes csv elements separator regional options numbers list separator locale module python used detect cultural settings localelocaleconv contain list separator opening csv writer dialect excel help any idea get correct separator edit the following code seems work accept upvotes solution mine import locale langlocale localegetdefaultlocale localesetlocalelocalelcall langlocale dp localelocaleconv decimalpoint delimiter dp delimiter,1 import regex urp p line president p barack obama p met microsoft founder p bill gates p yesterday person refindallregex line printperson yields barack obama bill gates the regex urubpudubufpud exactly unicode u pp except harder read the first bracketed group p tells characters list p match similarly second bracketed group p that want so remove outer enclosing square brackets also remove stray front p to protect literal brackets p escape brackets backslash p to return words inside tags place grouping parentheses around,i trying extract occurrences tagged words string using regex python or simply i want extract every piece text inside pp tags here attempt regex urubpudubufpud line president p barack obama p met microsoft founder p bill gates p yesterday person refindallpattern line printing person produces president p p p bill gates p what correct regex get p barack obama p p bill gates p barrack obama bill gates thanks,3 try match refinditerrpp subject match start matchstart match end exclusive matchend matched text matchgroup,i trying extract occurrences tagged words string using regex python or simply i want extract every piece text inside pp tags here attempt regex urubpudubufpud line president p barack obama p met microsoft founder p bill gates p yesterday person refindallpattern line printing person produces president p p p bill gates p what correct regex get p barack obama p p bill gates p barrack obama bill gates thanks,3 your question clear i assuming want find every piece text inside pp tags import line president p barack obama p met microsoft founder p bill gates p yesterday refindall pssp line barack obama bill gates,i trying extract occurrences tagged words string using regex python or simply i want extract every piece text inside pp tags here attempt regex urubpudubufpud line president p barack obama p met microsoft founder p bill gates p yesterday person refindallpattern line printing person produces president p p p bill gates p what correct regex get p barack obama p p bill gates p barrack obama bill gates thanks,1 replace pattern regex urpwsp,i trying extract occurrences tagged words string using regex python or simply i want extract every piece text inside pp tags here attempt regex urubpudubufpud line president p barack obama p met microsoft founder p bill gates p yesterday person refindallpattern line printing person produces president p p p bill gates p what correct regex get p barack obama p p bill gates p barrack obama bill gates thanks,1 cv might well support must mix versions like you must use version built version built i seem think cv python library depends c library case mix libraries like cv need recompiled version that said type fatal error suggests bug cv library however mixing versions like result undefined it might work chance might fail randomly,i installed opencv via sudo brew install opencv then i added pythonpath profile brew info opencv says with env i checked path loaded now everytime i try import cv python gives following error fatal python error pythreadstateget current thread abort trap what i pythonpathusrlocallibpythonsitepackages actually points folder python python version i use cv supports,1 you probably querying innodb table another process inserts new data meantime if case mysql sever automatically starts new transaction connection since call dbconnectioncommit rollback anywhere forever stuck transaction innodb default settings make sure whenever query data always see result within one transaction so whatever process inserting table hidden daemon connection the solution simple instead calling dbdisconnect call dbconnectioncommit ends current starts new transaction,i written python daemon continuously polls mysql database it works fine i continuously connect reconnect database queries follows def connectself selfconnection mysqldbconnect selfcursor selfconnectioncursor return selfcursor def disconnectself selfcursorclose selfconnectionclose def getdata sqlcmd select selfcursorexecute sqlcmd params result selfcursorfetchall return result name main db prepaiddbdatabase dbconnection dbconnect data dbgetdata stuff dbdisconnect but i try keep database connection open i get empty query even though running i query db manually give query get result i expect name main db prepaiddbdatabase dbconnection dbconnect data dbgetdata stuff dbdisconnect i tried everything understand would disabled query cache added random xx query case mysql cache confused similar queries enabled mysql query logging query comes still returns empty set moved cursorconnect databaseconnect back getdata difference i would love clue i understanding,3 in addition hack suggested dave pass local macro result macro this especially useful know advance passed parameter defined locally come template variable macro dotagtitle body div class title title div div class body body div endmacro macro tagbody something dynamic content endif endmacro dotagtitle simple title bodytagbody macro tagtitle content involves loops ifs endmacro dotagtitledotitle bodytagbody,i java programmer learning pythonjinja my biggest beef jinja macros limitation single caller example could following jsp tags tag def attribute nametitle fragmenttrue div class title titlediv div class body jspdobodydiv usage mytag jspattribute name title cif test blah this sometimescif jspattribute jspbody cif test something dynamic contentcif jspbody mytag want stress body content title attribute content dynamic also hacks setting variables dynamic content passing lets look jinja macro thing macro mytagtitle caller div class title title div div class body caller div endmacro wait cannot easily put dynamic content title attribute call mytagtitle imagine putting content involves loops ifs whatnot something dynamic content endif endcall problem newbie shortcoming jinja,2 did try allocate big array like davep suggests in nempty valueerror traceback recent call last valueerror array big this bit python you would actually need ee gbytes memory one float needs bytes do really need whole array sorry read post properly your array k subslices already gbyte big maybe problem does work use instead last dimension another suggestion would try first resize array fill zeros resizea ones,i rather large hdf file generated pytables i attempting read cluster i running problem numpy i read individual chunk let go example the total shape array within hdf file in datashape out each entry array npfloat i node read slices size unfortunately numpy seems unable read million subslices i tried sequentially dividing slices slices size using following reduce get things working in reducelambda xy npappendxyaxis nparraydatai chunksize ichunksizedtypenpfloat xrangek in k chunksize this code works k otherwise i get following in reducelambda xy npappendxyaxis nparraydatai chunksize ichunksizedtypenpfloat xrangek floating point exception homemybox i tried using valgrind memcheck tool figure going seems pytables culprit the two main files show trace libhdfso file related blosc also note i k i get in ashape out but i append last subslice i get in npappendanparraydatachunksizechunksize dtypenpfloat in ashape out does anyone ideas thanks,1 supercdmselfsave cdm calls save method next class mro this may direct parent current class for info super works used refer documentation blog post,i working multiple inheritance code looks similar class document def saveself x print inside document x class cdmobject def saveselfx print inside cdm x supercdmselfsave cdm class contactscdm document def initself selfsave contacts this result i get i create instance contacts c contacts inside cdm contacts inside document cdm now weird possibly eye i might misunderstood something as see class contacts inherits cdm document i trying use save method cdm contacts but cdm inherits object super class method called save yet calls save function document class in program i working behaviour i want i worried theoretically work least i think do comments or i misunderstood python inheritance,1 mysqldbcursor object probably support commit given mysqldb manual connection objects hand since handle everything database class i guess commit code go just give code simon said def connectself selfconnection mysqldbconnect selfcursor selfconnectioncursor def disconnectself selfcursorclose selfconnectioncommit selfconnectionclose def commitself selfconnectioncommit def getdataself sqlcmd select selfcursorexecute sqlcmd params result selfcursorfetchall return result name main db prepaiddbdatabase dbconnect data dbgetdata stuff dbcommit dbdisconnect i sure probably also something like dbconnectioncommit loop instead calling newly defined function,i written python daemon continuously polls mysql database it works fine i continuously connect reconnect database queries follows def connectself selfconnection mysqldbconnect selfcursor selfconnectioncursor return selfcursor def disconnectself selfcursorclose selfconnectionclose def getdata sqlcmd select selfcursorexecute sqlcmd params result selfcursorfetchall return result name main db prepaiddbdatabase dbconnection dbconnect data dbgetdata stuff dbdisconnect but i try keep database connection open i get empty query even though running i query db manually give query get result i expect name main db prepaiddbdatabase dbconnection dbconnect data dbgetdata stuff dbdisconnect i tried everything understand would disabled query cache added random xx query case mysql cache confused similar queries enabled mysql query logging query comes still returns empty set moved cursorconnect databaseconnect back getdata difference i would love clue i understanding,1 i sure i understand exactly trying adding row usually harder creating model object adding session userchoices modelcompuserchoices do stuff userchoices metasessionadduserchoices metasessioncommit commit manually,been round houses one cant seem get right syntax all i want insert row table sqlalchemy the documentation doesnt make sense thought class sqlalchemysqlexpressioninserttable valuesnone inlinefalse bindnone prefixesnone returningnone kwargs the closest i come userchoices metasessionquerymodelcompuserchoicesfiltermodelcompuserchoicesinmptlusername postdict userid filtermodelcompuserchoicesinmptloptionid postdict leg userchoicesinsertmodelcompuserchoicesinmptlusernamepostdict userid modelcompuserchoicesinmptloptionidpostdict leg modelcompuserchoicesinmptlcompchoiceidnewchoicesi could someone please tell correct syntax,3 as python documentation says super return proxy object delegates method calls parent sibling class type in situation supercdmselfsave cdm call version save next method resolution order in case save method document class sibling class cdm ie second base class contacts a great practical explanation super found python’s super considered super,i working multiple inheritance code looks similar class document def saveself x print inside document x class cdmobject def saveselfx print inside cdm x supercdmselfsave cdm class contactscdm document def initself selfsave contacts this result i get i create instance contacts c contacts inside cdm contacts inside document cdm now weird possibly eye i might misunderstood something as see class contacts inherits cdm document i trying use save method cdm contacts but cdm inherits object super class method called save yet calls save function document class in program i working behaviour i want i worried theoretically work least i think do comments or i misunderstood python inheritance,2 one big plus pytables storage metadata like variables etc if run simulations often different parameters store results array entry h file we use store measurement data experiment scripts get data self contained btw if need look quickly hdf file use hdfview it java app free hdfgroup it easy install,i recently came across pytables find cool it clear superior csv format large data sets i running simulations using python the output large say columns rows if someone experience suggest format would convenient long run data sets large pytables data manipulation capabilities browsing data vitables browser much functionality say excel used csv similarly find one better importing exporting data working mainly python is one convenient terms file organization any comments issues would helpful thanks,1 def forminvalidself form return httpresponseredirectselfgetsuccessurl but i know use form,i following code i want forminvalid method return page successurl i considering subclassing createview i want know public opinion how realize thing described class programnewcreateview formclass programform templatename programsprogramlisthtml successurl manageprograms def forminvalidself form how return selfsuccessurl return superprogramnew selfforminvalidform sultan,1 your data already list if want print array notation replace result list printresult print list you really call list list though list reserved word list confusingly similar incidentally listappendstrfirststrsecond strthirdstrfourth strbwstrvalue strsecondvaluestrhfs much comprehensible use python features like join listappendjoinfirst second third fourth bw value secondvalue hfs fact since variables groups regular expression could shorten whole thing listappendjoinmgroups,using regexp i searching text file contains data i get output similar here i get example i need array like the sample code usrbinpython import log recompile deleted file number first second third fourth bw value dabcdefx secondvalue dlm hfs dls logfile openlogtxt rreadlines list line logfile logmatchline first int mgroup second int mgroup third int mgroup fourth int mgroup bw int mgroup value int mgroup secondvalue float mgroup hfs float mgroup listappendstrfirststrsecond strthirdstrfourth strbwstrvalue strsecondvaluestrhfs result list printresult i use sysstdoutwrite display one single line print item but i put one array like array any help would appreciated,3 have tried print list if want string result strlist,using regexp i searching text file contains data i get output similar here i get example i need array like the sample code usrbinpython import log recompile deleted file number first second third fourth bw value dabcdefx secondvalue dlm hfs dls logfile openlogtxt rreadlines list line logfile logmatchline first int mgroup second int mgroup third int mgroup fourth int mgroup bw int mgroup value int mgroup secondvalue float mgroup hfs float mgroup listappendstrfirststrsecond strthirdstrfourth strbwstrvalue strsecondvaluestrhfs result list printresult i use sysstdoutwrite display one single line print item but i put one array like array any help would appreciated,1 disclaimer this answer tested windows freebsd but used modules work systems i believe working answer question works here code i hacked solve problem linux it combination several stackoverflow threads research python documents main characteristics code uses processes threads blocking io reliably pterminated implements retriggerable timeout watchdog restarts counting whenever output happens implements longterm timeout watchdog limit overall runtime can feed stdin although i need feed onetime short strings can capture stdoutstderr usual popen means only stdout coded stderr redirected stdout easily separated it almost realtime checks every seconds output but could decrease remove waiting interval easily lots debugging printouts still enabled see whats happening the code dependency enum implemented code could easily changed work without it used distinguish two timeouts use separate exceptions like here code usual feedback highly appreciated edit jun code actually working python module runcmd implements class launch shell commands killed timeout timeouts reset line output use inside script import runcmd returncode runcmdruncmd ls l etc timeoutruntime timeoutnooutput stdinstringgo import multiprocessing import queue import subprocess import time import enum def timestamp return timestrftime ymdhms class errorruncmdexception pass class errorruncmdtimeouterrorruncmd pass class enqueueoutputmultiprocessingprocess def initself queue multiprocessingprocessinitself selfout selfqueue queue selfdaemon true def runself try line iterselfoutreadline b print worker read line selfqueueputline except valueerror pass readline closed file selfoutclose class enqueueinputmultiprocessingprocess def initself inp iterable multiprocessingprocessinitself selfinp inp selfiterable iterable selfdaemon true def runself printwriting stdin line selfiterable selfinpwritebytesline utf selfinpclose printwriting stdin done class runcmd runcmd class launch shell commands captures returns stdout kills child given amount timeoutruntime wallclock seconds can also kill timeoutretriggerable wallclock seconds this second timer reset whenever child output returncode runcmd ls l etc timeoutruntime timeoutnooutput stdinstringgo timeout enumenum no retriggerable runtime def initself cmd timeoutruntime timeoutretriggerable stdinnone selfdbg false selfcmd cmd selftimeoutretriggerable timeoutretriggerable selftimeoutruntime timeoutruntime selftimeouthit selftimeoutno selfstdout cmd yield output selfstdin stdin def readqueueself q timelastoutput none try bstr qgetfalse nonblocking selfdbg print chars read formatlenbstr timelastoutput timetime selfstdout bstr except queueempty print queue empty pass return timelastoutput def goself selfstdin pstdin subprocesspipe else pstdin none p subprocesspopenselfcmd shellfalse stdoutsubprocesspipe stderrsubprocessstdout stdinpstdin pin none pstdin pin enqueueinputpstdin selfstdin n pinstart q multiprocessingqueue pout enqueueoutputpstdout q poutstart try selfdbg print beginning subprocess timeout formatselftimeoutretriggerable selftimeoutruntime timeasctime timebegin timetime timelastoutput timebegin secondspassed selfstdout b true ensure loop executed least child cmds may exit fast still produce output ppoll none qempty false selfdbg print secs passed overall chars read formatsecondspassed selftimeoutretriggerable selftimeoutruntime lenselfstdout tlo selfreadqueueq tlo timelastoutput tlo timetime timelastoutput selftimeoutretriggerable selftimeouthit selftimeoutretriggerable raise errorruncmdtimeoutself timebegin selftimeoutruntime selftimeouthit selftimeoutruntime raise errorruncmdtimeoutself qempty timesleep final try get lastmillisecond output selfreadqueueq finally selfclosep pout pin return selfreturncode selfstdout def closeself p procs selfdbg selftimeouthit selftimeoutno print a timeout occured formattimestamp selftimeouthit else print no timeout occured formattimestamp process proc proc procs proc try processterminate except print process termination raised trouble formattimestamp raise try pstdinclose except pass selfdbg print closed stdin formattimestamp try pstdoutclose if closed fds hang around except pass selfdbg print closed stdout formattimestamp pstderrclose osfdlimit exceeded cause nasty exception try pterminate important close fds prior terminating process note are nonfreed resources except pass selfdbg print closed popen formattimestamp try selfstdout selfstdoutdecode utf except pass selfreturncode preturncode selfdbg print closed formattimestamp use import runcmd cmd ls l etc worker runcmdruncmdcmd limit runtime wallclock seconds limit runtime last output wallclk secs stdin input string returncode workergo workertimeouthit workertimeoutno print a timeout occured formatworkertimeouthit else print no timeout occured printrunning returned chars outputformatcmd returncode lenout print output printout command first argument list command arguments it used popenshellfalse call timeouts seconds there currently code disable timeouts set timeoutnooutput timeruntime effectively disable retriggerable timeoutnooutput stdinstring string sent command standard input set none command need input if string provided final n appended,i want execute process limit executiontime timeout seconds grab output produced process and i want windows linux freebsd i tried implementing three different ways cmd without timeout subprocesspipe output capture behaviour operates expected support timeout need timeout cmdto with timeout subprocesspipe output capture behaviour blocks subprocess execution output bytes cmdtotf with timeout tempfilenamedtemporaryfile output capture behaviour operates expected uses temporary files disk these available closer inspection as seen output timeoutcode blocks execution subprocess using subprocessingpipe output subprocess bytes the subprocess documentation states expected calling processwait using subprocessingpipe however warnings given using processpoll going wrong i solution cmdtotf use tempfile module tradeoff writes output disk something i would really like avoid so questions what i wrong cmdto is way i want without using tempfiles keeping output memory script generate bunch output expgenpy usrbinenv python import sys output bintsysargv print output three different implementations cmd cmdto cmdtotf wrappers around subprocessingpopen usrbinenv python import subprocess time tempfile bufsize def cmdcmdline timeout execute cmdline uses subprocessing subprocesspipe p subprocesspopen cmdline bufsize bufsize shell false stdin subprocesspipe stdout subprocesspipe stderr subprocesspipe err pcommunicate returncode preturncode return returncode err def cmdtocmdline timeout execute cmdline limit execution time timeout seconds uses subprocessing subprocesspipe p subprocesspopen cmdline bufsize bufsize shell false stdin subprocesspipe stdout subprocesspipe stderr subprocesspipe tbegin timetime monitor execution time secondspassed ppoll none secondspassed timeout secondspassed timetime tbegin timesleep secondspassed timeout try pstdoutclose if closed fds hang around pstderrclose osfdlimit exceeded cause nasty exception pterminate important close fds prior terminating process note are nonfreed resources except pass raise timeoutinterrupt err pcommunicate returncode preturncode return returncode err def cmdtotfcmdline timeout execute cmdline limit execution time timeout seconds uses subprocessing tempfile instead subprocessingpipe output tempfilenamedtemporaryfiledeletefalse error tempfilenamedtemporaryfiledeletefalse p subprocesspopen cmdline bufsize shell false stdin none stdout output stderr error tbegin timetime monitor execution time secondspassed ppoll none secondspassed timeout secondspassed timetime tbegin timesleep secondspassed timeout try pstdoutclose if closed fds hang around pstderrclose osfdlimit exceeded cause nasty exception pterminate important close fds prior terminating process note are nonfreed resources except pass raise timeoutinterrupt pwait returncode preturncode fd openoutputname fdread fdclose fd openerrorname err fdread fdclose errorclose outputclose return returncode err name main implementations cmd cmdto cmdtotf bytes str timeouts timeout timeouts size bytes implementations tbegin timetime secondspassed rc err output expgenpy size timeout secondspassed timetime tbegin filler lenifuncname print ss timeoutd iosizes secondsf reprifuncname filler timeout size secondspassed output execution cmd timeout iosize seconds cmdto timeout iosize seconds cmdtotf timeout iosize seconds cmd timeout iosize seconds cmdto timeout iosize seconds cmdtotf timeout iosize seconds cmd timeout iosize seconds cmdto timeout iosize seconds cmdtotf timeout iosize seconds,1 have look awesome urllib wrapper web scraping httpsgithubcommattsehpythonwebblobmasterwebpy,i asked question realizing general idea crawl save webpages part original question crawl save lot about pages internet with research i got choices go ahead scraping parsing listed bottom today i ran another ruby discussion scrape google search results this provides great alternative problem save effort crawling part the new question python scrape google search results given keyword case about finally get links parsing what best choices methods libraries go ahead measure easytolearn easytoimplement ps website exactly thing implemented closed ask money results i prefer opensource available learn python meanwhile oh btw advices parsing links search results would nice still easytolearn easytoimplement just started learning python p final update problem solved code using xgoogle please read note section order make xgoogle working import time random xgooglesearch import googlesearch searcherror f open atxt wb range wt randomuniform gs googlesearchabout gsresultsperpage gspage results gsgetresults try annnoy google random short wait timesleepwt print this dth iteration waited f seconds wt res results fwriteresurlencodeutf fwriten print done fclose note xgoogle answered mike pennington the latest version github work default already due changes google search results probably these two replies b home page tool give solution currently still working tweak but maybe day may stop working due google changeblock resources known far for scraping scrapy seems popular choice webapp called scraperwiki interesting another project extract library offlinelocal usage mechanize brought quite several times different discussions for parsing html beautifulsoup seems one popular choices of course lxml,1 memory use could reduced using generator instead list list instead tuple need read whole file memory def readfilepath delim return lnsplitdelim ln openf r you rely garbage collector close file though as returning tuples necessary since lists tiny fraction faster constructing tuple minute cost importantly lines split variablesize sequences conceptually lists speed improved going ccython level i guess strsplit hard beat since written c list comprehensions afaik fastest loop construct python more importantly clear pythonic code i try optimizing apart generator bit,what best way read file break lines delimeter data returned list tuples can method beaten can done fasterusing less memory def readfilefilepath delim openfilepath r f return tuplelinesplitdelim line f,2 i finally found problem came i file called statpy apparently creating conflict libstatpy unfortunately error message obscure and i understand pydev behaves differently pythonexe,i work pydev quite suddenly i cannot run python programs within eclipse pydev version anymore any python program i ran run as python run fails wioth fatal python error pyinitialize initialize sys standard streams traceback recent call last file cpythonlibiopy line module this application requested runtime terminate unusual way please contact application support team information i still run program command line eclipse i one version python i changed python files since last time worked they encoded utf i upgraded eclipse pydev since last time worked python installed cpython defined environment variable pythonpath my xp system updated today kb any idea,1 if give script ipy extension ipython special syntax like ls work ipython myscriptipy,it convenient use shell escape interactive environment ipython possible call python script containing shell escape ipython,1 your posted code reads entire file builds copy file memory single list file contents split tuples one tuple per line since ask use less memory may need generator function def readfilefilepath delim openfilepath r f line f yield tuplelinesplitdelim but there major caveat you iterate tuples returned readfile linesastuples readfilemydata linedata linesastuples something this okay far generator list look but let say file going contain lots floating point numbers iteration file computed overall average numbers you could use something code calculate overall sum number numbers compute average but let say wanted iterate time find differences average value you think add another loop linedata linesastuples another thing but loop never anything linesastuples consumed bam this big difference generators lists at point code generator completely consumed special exception raised loop simply nothing continues silently in many cases list would get back iterated case conversion readfile generator would fine but want persistent list access multiple times using generator give problems since iterate generator my suggestion make readlines generator little view world yields incremental bit file nice memoryefficient put burden retention data onto caller caller needs refer returned data multiple times caller simply build list generator easily done python using listreadfile filedat,what best way read file break lines delimeter data returned list tuples can method beaten can done fasterusing less memory def readfilefilepath delim openfilepath r f return tuplelinesplitdelim line f,3 authorbooks selfrequestget books split,i need save value input type text stringlistproperty property google appengine python if i try authorbooks selfrequestget books authorput then i get property books must list error i need work following text input books separated commas the da vinci code angels amp demons fahrenheit thanks help,2 i think decorators could used check link combining descriptors class decorators validation for different approach check duck typing,i writing interface used two applications this interface use dosomethingrequest dosomethingresponse classes communication is library model validation example like django model i basically want able say something like object a must text property type str number property type int items property type list in dry way i looking something like following better class myembeddedmodelclassembeddedmodel text textfieldrequired true class mymodelmodel text textfieldrequired true number intfielddefault items listfieldembeddedmodel mymodel atext aaaa anumber aitems myembeddedmodelclassbbbb myembeddedmodelclasscccc myembeddedmodelclassdddd avalidate i know i write i rather use library available i bit new,1 i know way the thing i could imagine would work would return needs inside function,i would like know way writing module code without add another indentation level whole module code module code condition rest module code big i looking something like module code condition i need something like return rest module code big note i want throw exception import pass normally,1 yep exactly global works it seems right done way modules python standard library fileinput example,my text editor choice extensible python plugins it requires extend classes override methods the general structure looks similar snippet note function signature fixed ftpclient supposed shared instances classes ftpclient none class ftpfilecommandsublimeplugintextcommand def runself args global ftpclient reference variable outer scope selfftpclient ftplibftp foo login stuff class ftpfileeventlistenersublimeplugineventlistener def runself args global ftpclient selfftpclientquit both classes supposed one variable common what best practice order share variables edit based madjars answer ftpfilecommandrun called first instanciates ftpclient works like charm ftpfileeventlistenerrun called later reference ftpclient perfectly still none using global keyword add variable member self,2 run similar problem today i using basic authentication website i developing i authenticate users here things use debug problem i used slumberin httplib testing purposes i ran ipython shell see responses i receiving slumber actually uses httplib beneath covers acted similarly i used tcpdump later tcpflow shows information much readable form see really sent received if want gui see wireshark alternatives i tested website curl i used curl usernamepassword worked correctly showed requested page but slumber httplib still working i tested website browserspydk see differences important thing browserspy website works basic authentication web site i could compare two i read lot places need send http not authorized browser tool using could send usernamepassword provided but i know also needed wwwauthenticate field header so missing piece what made whole situation odd testing i would see httplib send basic authentication headers requests tcpflow would show it turns library send usernamepassword authentication first request if status and wwwauthenticate response credentials sent second request requests domain so sum application may correct might returning standard headers status code client send credentials use debug tools find also debug mode httplib set httplibdebuglevel debug information printed standard output this much helpful using tcpdump higher level hope helps someone,i slamming head wall one i trying every example reading every last bit i find online basic http authorization urllib i figure causing specific error adding frustration code works one page yet another logging wwwmysitecomadm goes absolutely smooth it authenticates problem yet i change address httpmysitecomadmitemsphpnampc i receive error h aligncenter classtealaddedit itemsh pstrongclientstrong ppstrongeventstrong pp classerrornot enough information complete taskp p classerrorthis fatal error i exiting nowp searching google lead zero information error the adm frame set page i sure relevant here current code import urllib urllib import sys import import base urlparse import urlparse theurl httpxxxxxmediacomadmitemsphpnampc username xxxx password xxxx passman urllibhttppasswordmgrwithdefaultrealm passmanaddpasswordnone theurlusernamepassword authhandler urllibhttpbasicauthhandlerpassman opener urllibbuildopenerauthhandler urllibinstallopeneropener pagehandle urlliburlopentheurl url httpxxxxxxxmediacomadmitemsphpnampc values avaudiocd avaudiocddiscount avaudiocdprice productname python test frmsubmit submit opener urllibbuildopenerurllibhttpcookieprocessor data urlliburlencodevalues req urllibrequesturl data response urlliburlopenreq this one many versions i tried i followed every example urllib missing manual still receive error can anyone point i wrong,1 if want enforce interfaces use designbycontract probably want zopeinterface library despite name reflects origins zope actually tied framework quite usable outside,i writing interface used two applications this interface use dosomethingrequest dosomethingresponse classes communication is library model validation example like django model i basically want able say something like object a must text property type str number property type int items property type list in dry way i looking something like following better class myembeddedmodelclassembeddedmodel text textfieldrequired true class mymodelmodel text textfieldrequired true number intfielddefault items listfieldembeddedmodel mymodel atext aaaa anumber aitems myembeddedmodelclassbbbb myembeddedmodelclasscccc myembeddedmodelclassdddd avalidate i know i write i rather use library available i bit new,2 if string ascii characters call encode this give str python like b abc bytes python abc encode ascii if rather putting binary data source create data file open rb read,i writing module supposed work python i need define binary string usually would something like data b abc code code fails python invalid syntax how i write code way work versions python note binary contain kind characters xff important,1 if single shared variable global simplest solution but note variable needs declared global assigned if global variable object call methods modify attributes etc without declaring global first an alternative using global variables use class attributes accessed using classmethods for example class ftpfileobject client none classmethod def clientcls return clsclient classmethod def setclientcls client clsclient client class ftpfilecommandftpfile sublimeplugintextcommand def runself args client selfclient class ftpfileeventlistenerftpfile sublimeplugineventlistener def runself args client selfclient,my text editor choice extensible python plugins it requires extend classes override methods the general structure looks similar snippet note function signature fixed ftpclient supposed shared instances classes ftpclient none class ftpfilecommandsublimeplugintextcommand def runself args global ftpclient reference variable outer scope selfftpclient ftplibftp foo login stuff class ftpfileeventlistenersublimeplugineventlistener def runself args global ftpclient selfftpclientquit both classes supposed one variable common what best practice order share variables edit based madjars answer ftpfilecommandrun called first instanciates ftpclient works like charm ftpfileeventlistenerrun called later reference ftpclient perfectly still none using global keyword add variable member self,1 def replaceit process placeholder iterit true item itnext item placeholder yield item else yield processitem pcount try true item itnext item placeholder pcount else rangepcount yield processplaceholder pcount yield processitem except stopiteration rangepcount yield placeholder use like x x replacea lambda n n,let take list example special value it placeholder i made generator replaces placeholder inside list it works expected but i need process beginning placeholders ending placeholders yield intact so i tried modify generator work python future import printfunction itertools import tee izip ifilterfalse def replaceiterableplaceholder enumerateiterable position needed logic middle list ifilterfalselambda x xplaceholder create iterator deletes placeholders ileftright enumeratewindowit slide filtered list window elements leaving beginning placeholders intact j rangeleft yield placeholder some logic for the middle of the list works well need leave trailing placeholders intact the interim values converted list ease comprehension code iterable enumerateiterable ifilterfalselambda x xplaceholder listenumeratewindowit so see listenumeratewindowit contains index leading nonplaceholder value contain information many trailing placeholder initial iterator listenumeratewindowit ends value index last nonplaceholder value give information many placeholders left i managed process leading placeholders relying enumerateiterable yields position initial iterator value persists first yielded value ifilterfalse but i spent quite lot time trying figure thing trailing placeholders the problem ifilterfalse swallows last placeholder values enumerateiterable i see way access possible leading placeholders since first generated value ifilterfalse contained index value enumerateiterable question what best way correct code process trailing placeholders as goal create code means i already done using different technique i want solve task tinkering bit wit code complete rewriting it training real task additional information window code my code nearly answer nye but code author make inplace modifications initial list and i want create generator yielding values resultant list code furthermore i want generator accept iterables parameter lists example may accept iterator reads values file one one with lists parameter task becomes simpler since scan list end this real task i solve life it training full code httpcodepadorgujcomy,1 i know solution i guess could put code internal module import condition met,i would like know way writing module code without add another indentation level whole module code module code condition rest module code big i looking something like module code condition i need something like return rest module code big note i want throw exception import pass normally,3 why imagelocationstartswithubuntuimagesusubuntulucidiserve as else usubuntuamilisti none then checking image name none simple,i try get specific list ami store array list usubuntuamilist image enumerateconngetallimages imagelocationstartswithubuntuimagesusubuntulucidiserve print imagename usubuntuamilisti imagename how check array position existing ami i check using way work userinput rawinputselect try usubuntuamilist usubuntuamilistuserinput print usubuntuamilistlocation except print does exist alternative i also tried checking using way both ways work usubuntuamilistinput none print usubuntuamilistinput else print does exist any ideas if better alternative solve i would like heard,1 in code global ftpclient reference variable outer scope selfftpclient ftplibftp foo declare ftpclient global variable this means lives module level classes example the second line wrong you wanted assign global variable instead set instance attribute name it global ftpclient ftpclient ftplibftp foo but let suggest different approach a common practice put stuff inside class since shared instances class class ftpfilecommandsublimeplugintextcommand ftpclient none def runself args ftpfilecommandftpclient ftplibftp foo login stuff notice method use self might well class method class ftpfilecommandsublimeplugintextcommand ftpclient none classmethod def runcls args clsftpclient ftplibftp foo login stuff this way get class first argument use access ftp client without using class name,my text editor choice extensible python plugins it requires extend classes override methods the general structure looks similar snippet note function signature fixed ftpclient supposed shared instances classes ftpclient none class ftpfilecommandsublimeplugintextcommand def runself args global ftpclient reference variable outer scope selfftpclient ftplibftp foo login stuff class ftpfileeventlistenersublimeplugineventlistener def runself args global ftpclient selfftpclientquit both classes supposed one variable common what best practice order share variables edit based madjars answer ftpfilecommandrun called first instanciates ftpclient works like charm ftpfileeventlistenerrun called later reference ftpclient perfectly still none using global keyword add variable member self,1 you going royal pains construct valid mime message msg ditching sending simple string emailmessage instead you probably begin understanding proper mime structure looks like a multipart message contents add text part want text part the following edit script missing pieces added i attempted send resulting message emailmimemultipart import mimemultipart emailmimetext import mimetext added emailmimeimage import mimeimage attachment bobjpg msg mimemultipart msgto msgfrom msgsubject subject msgtext mimetext bsbbrimg srccidsbr body attachment html msgattachmsgtext added edited previous line fp openattachment rb img mimeimagefpread fpclose imgaddheader contentid formatattachment msgattachimg print msgasstring exit,i currently program randomly select quotes list email i trying embed image email well i come across problem i attach email quotes longer work i researched online solutions working note i using python any guidance would appreciated import smtplib emailmimemultipart import mimemultipart emailmimeimage import mimeimage attachment bobjpg msg mimemultipart msgto toaddr msgfrom fromaddr msgsubject subjectheader msgtext mimetextbsbbrimg srccidbobjpgbr html body fp openattachment rb img mimeimagefpread fpclose msgattachimg emailmessage snsns subjectheader body img emailmessage sns subjectheader body emailrezi smtplibsmtpmailserver mailserverport emailrezisetdebuglevel emailreziloginmailusername mailpassword emailrezisendmailfromaddr toaddr emailmessage emailrezisendmailfromaddr toaddr msgasstring emailreziquit as tell code i tried different ways referencing,3 emm the list elements numbered i counted list i see elements sometimes i even forget possible start counting,i making simple checkers and order keep track locations checkers move i created list add locations locations however i try execute program i always get ld locations list index range so i thought maybe list contain certain amount numbers so i created second locations list added rows e h split list but i still receive error index range ld variable storing location row d column,1 you basic understanding problem locations lenlocations locations first element locations last element locations exist traceback recent call last file stdin line module indexerror list index range the elements locations go elements total,i making simple checkers and order keep track locations checkers move i created list add locations locations however i try execute program i always get ld locations list index range so i thought maybe list contain certain amount numbers so i created second locations list added rows e h split list but i still receive error index range ld variable storing location row d column,3 you change loginhandler accept post request like class loginhandlertornadowebrequesthandler def postself emailaddress selfgetargument email password selfgetargument password emailaddress loginresponse error true msg please enter email address elif password loginresponse error true msg please enter password else loginresponse error true msg thank you selfwriteloginresponse,i trying post tornado web server keep getting error not sure going wrong i fairly new python i searching month finally decided give go tornado web server import tornadohttpserver import tornadoioloop import tornadooptions import tornadoweb tornadooptions import define options import os import string time import sleep datetime import datetime import hashlib import json tornadooptions import define options defineport default helprun given port typeint class mainhandlertornadowebrequesthandler def getself selfwritehello world class loginhandlertornadowebrequesthandler def getself emailaddress selfgetargument email password selfgetargument password emailaddress loginresponse error true msg please enter email address elif password loginresponse error true msg please enter password else loginresponse error true msg thank you selfresponseheaders contenttype applicationjson selfresponseoutwritejsondumpsloginresponse def main tornadooptionsparsecommandline application tornadowebapplication r mainhandler rlogin loginhandler httpserver tornadohttpserverhttpserverapplication httpserverlistenoptionsport tornadoioloopioloopinstancestart name main main html form idloginform actionhttpwwwmydomaincomserverlogin methodpost label classgrey forlogemail addresslabelbr input typetext nameemail stylewidth idemailbr label classgrey forpwdpasswordlabelbr input typepassword namepassword stylewidth idpasswordbr label input nameremember typecheckbox checkedchecked value ampnbspremember melabelbr br input typesubmit idloginbtn namelogin valuelogin classbuttonbr hrefforgotpasswordphpforgot passworda form,3 list indexes start so list items access indexes locations refers nd item exist,i making simple checkers and order keep track locations checkers move i created list add locations locations however i try execute program i always get ld locations list index range so i thought maybe list contain certain amount numbers so i created second locations list added rows e h split list but i still receive error index range ld variable storing location row d column,2 the largest index list indexes lists languages start zero so index index if trying index end list python i suggest index locations if trying use len need subtract locationslenlocations,i making simple checkers and order keep track locations checkers move i created list add locations locations however i try execute program i always get ld locations list index range so i thought maybe list contain certain amount numbers so i created second locations list added rows e h split list but i still receive error index range ld variable storing location row d column,1 compare get ospathrealpathc windows saves current directory drive c without slash refers root drive the python docs ospathjoin mention note windows since current directory drive ospathjoinc foo represents path relative current directory drive c cfoo cfoo,ospathrealpathc cpythonapp ospathrealpathe e my current directory cpythonapp it seems os defaults current directory i give unknown path name something like oslistdir work e c,3 because interpolating regularlygridded data look using scipyndimagemapcoordinates as quick example import numpy np import scipyndimage ndimage interpfactor nx ny nz array nprandomrandint sizenx ny nz if familiar mgrid httpdocsscipyorgdocnumpyreferencegeneratednumpymgridhtml newindicies npmgridnxinterpfactornxj ny nz order indicates bilinear interpolation default cubic interpolation we also indicating output array dtype original array otherwise new float array would created interparray ndimagemapcoordinatesarray newindicies order outputarraydtype interparray interparrayreshapeinterpfactor nx ny nz,i array i want interpolate st axes at moment i like example import numpy np scipyinterpolate import interpd array nprandomrandint size newarray npzeros x nparange xnew nparange x j x f interpdx array j newarray j fxnew the data i use represents years day averaged values latitude longitude domain i want create array daily values i also tried using splines i really know work much faster is way without using loops if loops must used ways speed thank advance suggestions,3 you need create signal signature slot targeting selfnewtext qtcorepyqtsignalqtcoreqstring then connect gui settext slot selfnewtextconnectmytextsettext and emit whenever need code selfnewtextemitmy text here,hello i trying figure get data worker class i server code running threaded process i want send data server pyqt gui i variable gui code selfmytext qtextedit server code i send data gui only problem i know set signals right p selfemitsignal mytext mytextsettextmsg any ideas cheers,1 well played little code read documentation answer problem def createtableself rows selftablenamerowcount columns selftablenamecolumncount rangerows j rangecolumns item selfcelltext execute line every item need locked itemsetflagsqtcoreqtitemisenabled selfuitablenamesetitemi j item solved problem canâ´t select edit cell,following code defining gui app class ui object def setupui selftablename qtguiqtablewidgetselflayoutwidget selftablenamesetobjectnamefromutftwhistoricodisciplinas selftablenamesetcolumncount selftablenamesetrowcount following code app class mainwindowqtguiqmainwindow def initself selfui ui selfuisetupuiself selfcreatetable creating tw cell def cellselfvar item qtguiqtablewidgetitem itemsettextvar return item def createtableself rows selftablenamerowcount columns selftablenamecolumncount rangerows j rangecolumns item selfcelltext selfuitablenamesetitemi j item i want able add new rows columns edit want lock cells already code expand table make cells read keeping others read write found link qt how make column qtablewidget read solution problem c python solution similar edit removed answer post pasted answer,3 first look signalsslots concept works original qt documentation good start then working pyqt try use new style signals slots they pythonic here small example might work omitting obvious parts class myworkerqtcoreqthread register signal class variable first mysignal qtcorepyqtsignalqtcoreqstring init stuff def somefunctionself emit signal parameter selfmysignalemitmsg gui class mywindowqtguiqmainwindow def initself usual init stuff gui setup selfmytext qtextedit worker selfworker myworker register signal slot selfworkermysignalconnectselfmytextsettext,hello i trying figure get data worker class i server code running threaded process i want send data server pyqt gui i variable gui code selfmytext qtextedit server code i send data gui only problem i know set signals right p selfemitsignal mytext mytextsettextmsg any ideas cheers,1 xmldomminidom xml parser html parser therefore know html entities common xml html ampquot ampamp amplt ampgt ampapos try beautifulsoup,i summarize minidom appears like named entities appropriate resolution here code illustrates situation sample html body hun ejemploh pme llamo juan fulano hernampaacutendezp body html sample samplereplaceampaacute amp import xmldomminidom dom xmldomminidomparsestringsample dom xmldomminidomparsestringsample briefly html includes aacute similar expressed named entities minidom complains xmlparsersexpatexpaterror undefined entity how i respond do i replace named entities corresponding literal constants use parser minidom which somehow encoding assignment convince minidom named entities cool not feasible convince author xhtml eschew named entities,3 the repr return string describes object if possible valid python expression evaluates equal object this true builtin types like int str x foo evalreprx x true if possible string uniquely describing object the default repr example class fooobject pass reprfoo mainfoo object xae it uses object address memory uniquely identify of course address tell us much object useful override repr return string describing object state the object state defined objects contains makes sense include repr this exactly list dict repr bar foo bar mainfoo object xa in case state column properties want use repr you use r formatting inserts repr argument def reprself return stats descriptionr mystatr selfdescription selfmystat an equivalent using new formatting def reprself return stats descriptiondescriptionr mystatmystatr formatself,i quite new python currently i need repr sqlalchemy class i integer column accept null value sqlalchemy converts none for example class statsbase tablename stats description columnstring mystat columninteger nullabletrue what correct way represent mystat field repr function sqlalchemy returns none,3 if user identity span tenants apps keep user entities common namespace default namespace works fine default request begins anything specific tenant eg authorization user identity specific tenant stored convenient i find putting tenant namespace simplifies queries would otherwise specify filter,app multiple tenants gae master tenant let people register create subapptenant creator owner app best way manage user accounts lets say usera creates appa userb creates appb users apps user owner app created access users app userb wants give access user app best way model situation store members completely separate namespace validate users session switching constantly namespaces think best place keep permissions specific user app actual app tenant rather user object tips best practices thank,1 the driver actually responsible generating objectid value fairly straightforward i assume database stored python variable db import bson myrow att att att att att att att att refid bsonobjectid dbcollectionainsertattmyrow att attmyrow att idrefid dbcollectionbinsertattmyrow att attmyrow att refidrefid,given following row four attributes att att att att att att att att i want store row two collections mongodb the id collectiona used foreign key relational db how efficiently implement mongodb pymongo collectiona att att att att id objectideeadcd collectionb att att att att refid objectideeadcd id objectidefebffccce i seen solution posted javascript however time insert document collectiona first query id inserted document operations is better way,1 you probably want look paramiko module there copy files ssh using paramiko recipe using might helpful,i using python transfer via scp database large number files one servers i transfer files odd ssh config rules stop many ssh requests single location the upshot python script currently looping files copying via ossystem hangs files transferred is way python could open ssh connection server file transferred require instance ssh login thanks,1 check sftp python module paramiko you multiple file transfers single session,i using python transfer via scp database large number files one servers i transfer files odd ssh config rules stop many ssh requests single location the upshot python script currently looping files copying via ossystem hangs files transferred is way python could open ssh connection server file transferred require instance ssh login thanks,1 in preferences look pydev interpreter python whichever using make sure webapp listed libraries tab system libs if add clicking new folder right click apply wait relook functions note webapp part default libraries must installed separately here link download,i attempting try google app engine python being familiar eclipse i decided use pydev after trouble i hello world program working almost it cannot find webapp import telling unresolved i followed instructions i find google app engine libraries linked i think i searched webapp potential import cannot find anywhere library files i really new python general even newer google app engine i certain simple problem exacerbated newness i running osx running eclipse indigo service release i latest version pydev available download tuesday evening,3 this exploding indexes,i list property taglist dbstringlistproperty this working fine far today i tried write list items i got too many indexed properties entity error i think case exploding indexes this query query mainall queryfilterurl url queryfilterowner user reading documentation understanding error triggered cases items list if triggered items i wrong i fix thanks update code query mainall queryfilterurl url queryfilterowner user e queryget e etaglist usertaglist epitch pitchoriginal etitle titleascii eput mainid ekeyid else try newitem main url url taglist usertaglist pitch pitchoriginal owner user title unicodetitle utf title titleascii display true error occurs logs newitemput and list usertaglist u box u jquery u working u enter u initially u text u showing u javascript u overflow u focus u stack u field u impossible u input u hidden u element u toggling u toggled,2 yes fine another alternative try fhandle zipfilezipfilezipfilename code except zipfilebadzipfile zipfilelargezipfile e printe else fhandle printopen successfully this prevents accidentally catching exception body statement except handler,zipfilename notexistpy try zipfilezipfilezipfilename fhandle printopen successfully except zipfilebadzipfile zipfilelargezipfile e printe is correct way handle exception throw statement,1 yes would want handle exceptions inside statement contextmanagers implement behavior behind statement handle exceptions properly clean resources used object here snippet relevant documentation if block raises exception context manager’s exit method called three arguments exception details type value traceback values returned sysexcinfo also none exception occurred the method’s return value controls whether exception reraised false value reraises exception true result suppressing you’ll rarely want suppress exception author code containing ‘with‘ statement never realize anything went wrong,zipfilename notexistpy try zipfilezipfilezipfilename fhandle printopen successfully except zipfilebadzipfile zipfilelargezipfile e printe is correct way handle exception throw statement,2 if page content dependencies events occur pageload ie facebook loginlogout best bet may use jquery ajax load andor reload dependent elements separately,i tried make user variable available serveside i noticed page behaves way i want i reload so i force page reload facebook connect disconnect any idea code i tried obvious javascript created loop can help thanks load doctype html html xmlnsfbhttpswwwfacebookcomfbml head title test facebook sdk title head body div idfbrootdiv scriptfunctiond id var js fjs dgetelementsbytagnames dgetelementbyidid return js dcreateelements jsid id jssrc connectfacebooknetenusalljsxfbmlampappid fjsparentnodeinsertbeforejs fjs document script facebookjssdk scriptdiv classfbloginbutton autologoutlinktrue datashowfacestrue datawidth datamaxrowsdiv greeting user currentuser twittername div iduserident span trans welcome busernickname user currentusernameescape endif user currentuser twittername endif bspan div fbloginbutton autologoutlinktruelogoutfbloginbutton else fbloginbutton autologoutlinktruelogin facebookfbloginbutton endif body html update i removed javascript cookies since needed pure python solution oauth enable scenario login facebook how add facebook oauth provider here i make login facebook website oauth instead javascript cookie python oauth facebook far i tell working class fbuserdbmodel id dbstringpropertyrequiredtrue created dbdatetimepropertyautonowaddtrue updated dbdatetimepropertyautonowtrue name dbstringpropertyrequiredtrue profileurl dbstringproperty accesstoken dbstringpropertyrequiredtrue name dbstringpropertyrequiredtrue picture dbstringproperty email dbstringproperty friends dbstringlistproperty class inpageinhandler def getself selfrequestget code args dict code selfrequestget code clientid facebookconffacebookappid clientsecret facebookconffacebookappsecret redirecturi httpwwwkoolbusinesscom loggingdebugclientidstrargs file urlliburlopenhttpsgraphfacebookcomoauthaccesstoken urlliburlencodeargs try loggingdebugreading file tokenresponse fileread loggingdebugread filestrtokenresponse finally fileclose accesstoken cgiparseqstokenresponseaccesstoken graph maingraphapiaccesstoken user graphgetobjectme write accesstoken datastore fbuser mainfbusergetbykeynameuserid loggingdebugfbuser strfbuser fbuser fbuser mainfbuserkeynamestruserid idstruserid nameusername profileurluserlink accesstokenaccesstoken fbuserput elif fbuseraccesstoken accesstoken fbuseraccesstoken accesstoken fbuserput the login link hrefhttpswwwfacebookcomdialogoauthclientidampredirecturihttphostimg srcimgloginwithfacebookpnga redirects allows pick accesstoken method logout straightforward hrefhttpswwwfacebookcomlogoutphpnexthttpwwwkoolbusinesscomampaccesstokenaccesstoken trans log,1 this problem defined tfirstlist ndimensional array for example tfirstlist works tfirstlist produces exception if using ndimensional data n datasets color keyword argument color kwarg must also ndimensional one color per dataset for example case color b r,i simply save data files read draw histogram however appears mistake though i changed nothing original code actually could anyone tell wrong thanks lot here code hist f pltfigure plthisttfirstlist bins normed true histtype step cumulative true color g label first answer pltaxvlinex ymin ymax color r linestyle label min pltaxvlinex ymin ymax color c linestyle label hour pltlegend pltylabel percentage answered questions pltxlabel minutes elapsed questions posted plttitle cumulative histogram time elapsed n questions receive answer first hrs pltylim pltxlim fshow f pltfigure plthisttfirstlist bins normed true histtype step cumulative true color g label first answer pltaxvlinex ymin ymax color r linestyle label hours pltaxvlinex ymin ymax color c linestyle label day pltlegendloc pltylabel percentage answered questions pltxlabel minutes elapsed questions posted plttitle cumulative histogram time elapsed n questions receive answer first pltylim pltxlim fshow and fulltext error plthisttfirstlist bins normed true histtype step cumulative true color b label first answer file cpythonlibsitepackagesmatplotlibpyplotpy line hist ret axhistx bins range normed weights cumulative bottom histtype align orientation rwidth log color label kwargs file cpythonlibsitepackagesmatplotlibaxespy line hist raise valueerrorcolor kwarg must one color per dataset valueerror color kwarg must one color per dataset,3 does param contain command limiter python case i assume newline n also listtobinary termtobinary feels kinda wrong termtobinary directly including newline sufficient,based chapter otp action book cesarini book i wrote erlang code erlang pparam dbgstartingn cmd python testpy port openportspawncmd streamline exitstatus dbgopened port wn port payload termtobinarylisttobinaryintegertolistparam erlangportcommandport payload dbgsent command port wn payload dbgready receive results command wn payload receive port data data dbgreceived data wn data result text binarytotermdata blah binarytolisttext ioformatpn blah other ioformatunexpected data pn other end python import sys def main true line sysstdinreadlinestrip line stopgood return elif line stopbad return sysstdoutwritepython got sysstdoutwriteline sysstdoutwriten sysstdoutflush name main sysexitmain the erlang code suspends recieve clause never gets message i also checked python regular linux shell prints every user input python got where mistake why erlang code get anything back,1 i reproduced behavior python windows xp this appears bug occurs attempt read without seeking first that tmpwrite test tmpseek tmpread test vs tmpwrite test tmpread xxxxpfilepyrxxxxgxxxsx blah blah blah tmpseek tmpread testxxxxpfilepyrxxxxgxxxsx blah blah blah edit for kicks i also checked windows build xp install behavior seen xp cygwin version bug present,for small python script i would like use temporary file tempfile module somehow give expected behavior i know i wrong bug python default jun msc v bit intel win type help copyright credits license information import tempfile tmp tempfiletemporaryfile tmpread tmpwrite test tmpread pxfdxxxxxxxxxxxx ommitted alternatively i tried text mode behavior still strange python default jun msc v bit intel win type help copyright credits license information import tempfile tmp tempfiletemporaryfile wt tmpread tmpwrite test tmpread xxaxbxint long hasha used insteadn ix ommitted tmpseek tmpreadline testxxaxbxint long hasha used insteadn any help appreciated additional information python bit current python xy distribution running windows enterprise x machine in test run python created temporary file name tmpvyocxj temporary directory dtempmyusername several python processes running the commands typed i tried reproduce script the behavior unchanged python processes running update this behavior limited tempfile module also normal fileread filewrite operations according cpython guys functions call underlying libc fread routines in cstandard exact behavior read write without seek flush undefined ie every implementation lead different results,3 your two examples exactly equivalent the matlab example concatenating two lists new list making copy time whereas python appending items list without making copy every time now fact write exact python equivalent matlab code eg mine mine newitem but making copy evergrowing list time which lists append method also extend for similar reasons rather building string concatenation pythonistas recommend append individual strings list use join by way python lists always allocated space extra items always need grown new item appended,in matlab type algorithm growing arrays advised mine mine minerandn end whereas seems many examples python show kind algorithm really bad example though import numpyrandom rand mine range mineappendrandrandom i wonder difference,1 apparently matplotlib code sample output below screenshot demonstrating,is python library generating sankey diagrams i seen list sankey diagram applications libraries none python,3 you use dictionary special case c r return randrange lenlist this constant it could generated program start u p this covers majority cases c return dc some special cases c right center else left center,i code c getch c r return randrange lenmylist c u return c b return c w return c return c return c e return c k return c g return c p return c right center else left center can i make code snippet compact how would write better thank,3 the difference in matlab every iteration loop reallocates matrix increase size one copies entire contents newly allocated space python lists work like more space allocated needed given point allocated space grows manner guarantees appends done amortized constant time that said i think difference largely cultural it common large numeric matrices matlab growing matrices one element one rowcolumn time would indeed expensive on hand one would use python list list lists represent large matrix would slow would make poor use memory numerical python ndarray would used instead ndarray would offer exactly tradeoffs matlab matrix,in matlab type algorithm growing arrays advised mine mine minerandn end whereas seems many examples python show kind algorithm really bad example though import numpyrandom rand mine range mineappendrandrandom i wonder difference,3 check python release notes specifics you notice syntax differences issues especially beginning you worried learning one learn basically also python good backwards compatible almost everything would would work there noticeable differences python x x changes syntax way things work even learned python able figure matter minutes understand differences,newb coder i decided dive headfirst python discovered different versions python python etc could someone please tell difference i learn older version would relearn newer version update libraries stuff sorry seems trivial i new,3 doing call plotmonth function solved leak import gc gccollect,i written small webapp using flask framework involves plotting using matplotlib the problem every time i create plot process consumes memory i deployed app using modwsgi wsgi file looking simply like yourapplication import app application the problems start i access url creates plot the function creates plotter object initilized takes relevant data sqlite database data consist integers equally many datetime objects creates plot using matplotlib returning stringio object displayed screen this end function the whole class seen canvas figurecanvasfig pngoutput stringiostringio canvasprintpngpngoutput return pngoutputgetvalue when i visit site process created mb reserved memory the first time i create plot grows mb mb time i use plotter class the default settings using process consumed way much memory mb within minutes i allowed mb i new things involved web frameworks apache databases i feeling things might going wrong ideas highly appreciated thanks,1 a technique handy linux system using domain sockets import socket import sys import time def getlockprocessname without holding reference socket somewhere gets garbage collected function exits getlocklocksocket socketsocketsocketafunix socketsockdgram try getlocklocksocketbind processname print i got lock except socketerror print lock exists sysexit getlock runningtest true timesleep it atomic avoids problem lock files lying around process gets sent sigkill you read documentation socketclose sockets automatically closed garbage collected,i python daemon running part web app how i quickly check using python daemon running launch i want way fix crashes daemon script run manually automatically run soon called stay running how check using python script running,3 i agree dictionary way go the problem mark answer dictionary gets rebuilt every function call the way around define dict outside function def foo c getch c foomydict return foomydictc else todo special cases foomydict u p foo ready use,i code c getch c r return randrange lenmylist c u return c b return c w return c return c return c e return c k return c g return c p return c right center else left center can i make code snippet compact how would write better thank,1 numhits numouts range atbats randompickab hit numhits else numouts print numhits numouts,working python i trying work way plotting random walk but first i trouble summing number results i get random generator the first piece code def randompicksomelist probabilities x randomuniform cumulativeprobability item itemprobability zipsomelist probabilities cumulativeprobability itemprobability x cumulativeprobability break return item in case list hit out respective probabilities given b this code returns hit probability out probability i code create rough sim player batting average based probabilities def battingaverageatbats somelista probabilitiesb rangeatbats randompicka b hit hit randompicka b print f hit elif randompicka b out randompicka b print f out when i run i get random generation many atbats i choose but i would like able sum number instances hit i able figure i tried use code similar changing randompick return probability instead item avail def battingaverageatbats somelista probabilitiesb numhits numouts rangeatbats randompicka b hit hit randompicka b numhits hit elif randompicka b out randompicka b numouts print numhits numouts any help would greatly appreciated also anyone know good resource learn monte carlo simulations,1 to honest i struggling follow logic code long day couple pointers when things like randompicka b hit elif randompicka b out calling randompick twice conducting two independent simulations instead one as result could neither two branches get executed to fix call randompick store result branch result as problem python allows return multiple values function this might useful def randompicksomelist probabilities decide item probability return item probability you call like item prob randompicka b use item prob,working python i trying work way plotting random walk but first i trouble summing number results i get random generator the first piece code def randompicksomelist probabilities x randomuniform cumulativeprobability item itemprobability zipsomelist probabilities cumulativeprobability itemprobability x cumulativeprobability break return item in case list hit out respective probabilities given b this code returns hit probability out probability i code create rough sim player batting average based probabilities def battingaverageatbats somelista probabilitiesb rangeatbats randompicka b hit hit randompicka b print f hit elif randompicka b out randompicka b print f out when i run i get random generation many atbats i choose but i would like able sum number instances hit i able figure i tried use code similar changing randompick return probability instead item avail def battingaverageatbats somelista probabilitiesb numhits numouts rangeatbats randompicka b hit hit randompicka b numhits hit elif randompicka b out randompicka b numouts print numhits numouts any help would greatly appreciated also anyone know good resource learn monte carlo simulations,1 the best generalpurpose option nix system use sort filea fileb uniq u but need use python your code reopens inner file every iteration outer file open outside loop using nested loop less efficient looping first storing found values comparing second values def buildsetfilename a set stores collection unique items both adding items searching quick perfect application found set openfilename f line f gives us first two elements list tuples unlike lists cannot changed requirement anything stored set foundaddtuplesortedlinesplit return found setmore buildset rwsnmoretxt setdel buildset rwsndeletedtxt open resultstxt w outfile using open files ensures properly closed even code raises exception res setmore setdel the computes elements setmore setdel outfilewrite joinres n,i would like compare two text files three columns one file rows another rows i want different rows stored different file i created first file rows using random network generator rows edges third column weight first second columns source destination nodes file format files i tried compare two files line line generate difference another file find difference two text files one item per line httpwwwdaniwebcomsoftwaredevelopmentpythonthreadspost neither worked i think problem string comparison i would like compare numbers first column second column if different i want write third file any help much appreciated update i posting following code i tried mk posted comment f openresultstxtw line filerwsnmoretxt rwsncount line linesplit src line dest line row filerwsndeletedtxt row rowsplit row row ifs src dest fwritestrs fwrite fwritestrd fwrite n fclose,3 in pyexe script specify windows myscriptpy instead console myscriptpy like setup windows myscriptpy options pyexe unbuffered true optimize see pyexe list of options,when trying compile gui program using pyexe whenever i load gui black box appears behind is anyway prevent,1 you need use windows option setup rather console option setup windows rpmapp console rpmapp dbmigrate zipfile commonbin options options datafiles files cmdclass pyexe filecollector here i actually console enabled debugging i uncomment windows option i finish building deployment,when trying compile gui program using pyexe whenever i load gui black box appears behind is anyway prevent,1 you returning anything mysqlconnect function so returns none when db mysqlconnectlocalhost “root” “test” “mydbt db becomes none try changing db mbconnecthosthostnameuserusernamepasswdpassworddbdbname return mbconnecthosthostnameuserusernamepasswdpassworddbdbname that said i sure defining function make single thing useful better something like import mysqldb mb import mayacmds cmds db mbconnecthostlocalhostuser“root”passwd“test”db“mydbt dbcursor dbcursor dbcursorexecuteselect maya,i using maya bit mysql bit windows bit machine i tried connect maya mysqldb python so copied connector files mayapythonlibsite packages i able import mysqldb module without error but tried call cursor object querying i found maya recognizing cursor object here sample code import mysqldb mb import mayacmds cmds def mysqlconnecthostname username password dbname db mbconnecthosthostnameuserusernamepasswdpassworddbdbname db mysqlconnectlocalhost “root” “test” “mydbt dbcursor dbcursor dbcursorexecuteselect maya but code throws following error error attributeerror ‘nonetype’ object attribute ‘cursor’ i tried verifying envpath variables replacing connector files problem persists since beginner unable identify exact issue i request valuable suggestions,1 appending arrays matlab apparently inefficient runs quadratic time whereas python corresponding list operation much highly optimized appends o list becomes full point size list doubled make room on operation this means appends become increasingly efficient list grows longer overall efficiency o amortized these kinds optimizations could probably also achieved matlab seems done automatically for even better performance python also collectionsdeque container class supports efficient appending removal either end o directions,in matlab type algorithm growing arrays advised mine mine minerandn end whereas seems many examples python show kind algorithm really bad example though import numpyrandom rand mine range mineappendrandrandom i wonder difference,2 your matlab code better written compare following implementations preallocation tic x zeros xi end toc appending tic x xend end toc concatenation tic x x x end toc i get following results elapsed time seconds preallocated vectormatrix elapsed time seconds appending using end syntax elapsed time seconds appending using concatenation note tested rb introduced improvements growing matrices without preallocation you also check previous answer solution combines preallocation still allowing dynamic growing idea allocategrow large block sizes on side note python lists optimized appending items end if insert items beginning get different timings example timeit import timeit timeit xinsert x number timeit xappend x number xinsertlenx,in matlab type algorithm growing arrays advised mine mine minerandn end whereas seems many examples python show kind algorithm really bad example though import numpyrandom rand mine range mineappendrandrandom i wonder difference,1 solution after looking problem little talking colleague seems though problem lies trying pass response object javascript for interested i solved problem little careful rerouting data viewspy in viewspy i added couple lines code main view would set variables two extra views one csv one json response objects holding data these two extra views would called respective buttons pressed returning httpresponse prompting user download main view function def viewrequest do stuff get data string get data needed formats jsondata jsontojsonfiledatastring filename set values external view new part returnjsonjsondata jsondata render main template return rendertoresponse maintemplatehtml someform aform regulardata datastring secondary view to return json data to user new part def returnjsonrequest simply return response return returnjsonjsondata templatehtml then button pressed user anchor linked via url secondary django view present download option user li class button href url clientviewsreturnjson json li urlspy lastly i pointed url patterns view urlpatterns patterns r somesite viewsview r somesitejson viewsreturnjson so far method worked great if anyone suggestions better method i would certainly open hear,problem overview i creating djangobased client intent returning data web service the goal project return data user web service based values selected user form upon form submit query string generated sent web service page data returned string currently data displayed user browser i want provide functionality would allow user click button download data question how could i return data user click button browser download how i make different options data available ie applicationjson textcsv current notworking implementation i attempting failing following viewspy returning rendertoresponse object template to template i pass form data various forms def viewrequest do stuff get data string get data needed formats see utilspy jsondata jsontojsonfiledatastring filename return rendertoresponse templatehtml someform aform regulardata stringdata jsondata jsondata utilspy contains functions take data string return response objects this part i unsure i correctly i call functions view get jsondata csvdata proper formats original data string def jsontojsonfiledatastring filename get data json thedata jsondumpsdatastring prepare return json file response httpresponsethedata mimetype applicationjson response contentdisposition attachment filename strfilename json return response return response templatehtml i currently passing responses template this i really lost yet begun find good solution i expect i need use javascript return variables jsondata csvdata user button clicked i attempted use onclick action anchor class using javascript return django variable response really working li class button href databuttons onclick javascriptalert test test li li class button href databuttons onclick javascript var jsondata return json li i put test part well test whether alert would work it however i click button json data nothing happens am i approaching completely wrong or something small i missing,2 your entire command line processed java command jclasspath indeed valid command line option java you really try follow exact steps tutorial missing several important steps kind making steps,i tried run htmlunit jython following tutorial httpblogdatabigbangcomwebscrapingajaxandjavascriptsites work i unable import comgargoylesoftvare packages html files htmlunit folder i need import somehow the tutorial says run python script like optjythonjython jclasspath htmlunitlib gartnerpy i try run java jar usersadamjythonjythonjar jclasspath htmlunitlib gartnerpy my problem i getting unknown option jclasspath but even word jclasspath parameter jythonorg i would very glad advice i running jython standalone v snow leopard,1 use docmultibuild page header method defined onlaterpages global totalpages docpage totalpages totalpages docpage else canvasdrawstring mm mm seite dd docpagetotalpages,i trying add simple page x report made reportlab i found old post maybe six years later something straightforward emerged i found recipe i use resulting pdf missing images,2 rawinput returns strings if mean integers use intx convert ints,how display numbers integer python for example number rawinput write one number number rawinput write number result number number print the sum numbers result display result operatio n,1 you want result intnumber intnumber rawinput returns strings,how display numbers integer python for example number rawinput write one number number rawinput write number result number number print the sum numbers result display result operatio n,2 functions return resources need cleaned documentation explains csvreader open file otherwise create closable resource the open call statement takes care closing,i new python feel confused i call close for instance consider example csv documentation import csv open somecsv rb f reader csvreaderf row reader print row there readerclose end task q how i find whether function call need followed close call,2 the time need call close must release system resources byinlarge true file handles general objects csv reader closed,i new python feel confused i call close for instance consider example csv documentation import csv open somecsv rb f reader csvreaderf row reader print row there readerclose end task q how i find whether function call need followed close call,1 you strongly consider renaming list variable something already used cgetch cr return randrange lenmylist return dictu b w e k g p ocentergetc center,i code c getch c r return randrange lenmylist c u return c b return c w return c return c return c e return c k return c g return c p return c right center else left center can i make code snippet compact how would write better thank,1 you returning raw queryset getowners python calling repr insert string the best bet formatting within getowners def getownersself owners return u joinunicodeo owners,i trying populate form list plans here unicode plans model def unicodeself label id members plan type selfid selfgetowners selfplantype return unicodelabel now i call getowners shown def getownersself owners selfplanmembersetfilterownershiptypecodeinprimaryjoint return owners but output shows planmember name membershiptypeplanmember name etc etc how i go displaying output without brackets along lines name membershiptype name membershiptype etc,1 the php pack function format n means unsigned bit bigendian integer the corresponding python structpack format l the images posted protocol show connectionid bit unsigned integer python structpack format q so clisocket socketsocketsocketafinet socketsockdgram connectionidx action transactionid randomrandrange transactionid printtransactionid packetstructpackqllconnectionidactiontransactionid printreprpacket xxxx xxxxxxxxx clisocketsendtopacket trackeristoleit res clisocketrecv actiontransactionidconnectionidstructunpackllqres printaction printtransactionid printconnectionid,i trying convert php code python all values send network byte order big endian basically request protocol specification response corresponding php code corresponding doc transactionid mtrand currentconnid xxxxxxxx fp fsockopentracker port errno errstr packet currentconnid packn packn transactionid fwritefppacket i trying find corresponding code doc python transactionid randomrandrange packet xxxxxxxx packet packet structpacki structpacki transactionid clisocket socketsocketsocketafinet socketsockdgram clisocketsendtopacket trackeristoleit in response i get transactionid i sent request i getting so guess i packing using correct format also python documentation clear php the protocol specifies use big endian format amp php doc clearly states ones bigendian sadly i could comprehend format use python please help choosing corrent format edit not getting responses i would say import struct import socket import random clisocket socketsocketsocketafinet socketsockdgram packet xxxxxxxx transactionid randomrandrange print transactionid packet packetstructpacki packet packetstructpacki transactionid clisocketsendtopacket trackeristoleit res clisocketrecv print structunpacki res according protocol specification i returned integer,2 this considered bad form use import python cases either use import myfunc else import mylib then need something mylib lap something else for help finding things current namespace check pprint library dir builtin locals builtin globals builtin,as example say i variable defined may multiple import import etc is way figure one variables namespace defined edit thanks i already understand import often considered poor form that question though case i write it nice way find variable came,3 no names defined blah import retain information came the values might clue example classes module attribute may defined one module imported another count values expect,as example say i variable defined may multiple import import etc is way figure one variables namespace defined edit thanks i already understand import often considered poor form that question though case i write it nice way find variable came,2 is possible yes course but problems making graphs coding algorithms deal separating algorithm data type might make easier here couple suggestions create use abstract data type graph code coloring algorithm graph interface vary graph implementation list matrix forms if want use graphs need implement quick google search turned python graph library,how i implement graph colouring python using adjacency matrix is possible i implemented using list but problems i want implement using matrix can anybody give answer suggestions,1 i think going single regex use unless really nasty i think solution might natural language processing certainly packages using might simple essentially want take sentence like x iswas y figure part name part list job titles parts irrelevant maybe look sequences words either capitalized small words like uw uwofand note space the u means next single character first character w group uppercase haven tested seems like work this may nontrivial problem,i extracting information certain companies reuters using python i able get officerexecutive names biographies compensation page now i want extract previous position titles companies biography section looks something like mr donald t grimes senior vice president chief financial officer treasurer wolverine world wide inc since may from executive vice president chief financial officer keystone automotive operations inc distributor automotive accessories equipment prior keystone mr grimes held series senior corporate divisional finance roles brownforman corporation manufacturer marketer premium wines spirits during employment brownforman mr grimes vice president director beverage finance vice president director corporate planning analysis senior vice president chief financial officer brownforman spirits america i use simple regex get years i loss write regex get titles company name well i know string format inconsistent i would take answer works least cases here output i would like executive vice president chief financial officer keystone automotive operations,1 basically trying pass string matplotlib several convenience functions converting date strings internal datetime representation try something like matplotlibdates import datestrnum time datestrnumtabledatetime axplotdatetime tablevalues plotdate plot automatically formats xaxis time eg hour day month etc labels if rather use plot bar etc instead call axplottime axbar usual call axxaxisdate afterwards set date labels,i posted question qgisuser forum might technical thus i take chance try well my plan qgis plugin reads plots time series data corresponding selected points vector layerthe points represents different measuring stations i need quickly view time series one sometimes several stations plot consequently i need python read time series data spatialite table plot matplotlibplot pyspatialite import dbapi sqlite import numpy np import matplotlibpyplot plt import datetime mypath rcdatadbtestmytestdbsqlite conn sqliteconnectmypathdetecttypessqliteparsedecltypessqliteparsecolnames curs conncursor sql rselect date date datetime levelmasl from mytable rs cursexecutesql recs rsfetchall myformat datetime datetimedatetime values float table nparrayrecs dtypemyformat tabletableviewnprecarray fig pltfigure ax figaddsubplot axplottabledatetime tablevalues but seems like i get correct data types since matplotlib accept datetime a print table shown i guess small u indicates unicode datetime print table recarrayu u dtype datetime o values i programmer absolutely complete python spatialite beginner help would much appreciated jk,1 i think one problems listremove removes first occurrence element there could still empty strings list from documentation remove first item list whose value x it error item to remove empty strings list could use list comprehension instead linelist x x linelist x filter identity function passing none first argument linelist filternone linelist,i trying format tab delimited txt file rows columns i trying simply ignore rows empty values i write output file i lenlist method length list equals number columns line gets written output file but i check length lines even though i removed empty strings very frustrating here code import sys os inputfilename sysargv outputfilename ospathsplitextinputfilenameeditedtxt try infile openinputfilename r outfile openoutputfilename w line infilereadline outfilewriteline line infile linelist linesplit print linelist linelist linelistremove lenlinelist print lenlinelist outfilewriteline infileclose outfileclose except ioerror print inputfilename exist thanks help when i create experimental list interactive window use list removes when i run code still,1 i dont know python mention dont seem checking whitespace characters what r n top why dont try trimming line checking,i trying format tab delimited txt file rows columns i trying simply ignore rows empty values i write output file i lenlist method length list equals number columns line gets written output file but i check length lines even though i removed empty strings very frustrating here code import sys os inputfilename sysargv outputfilename ospathsplitextinputfilenameeditedtxt try infile openinputfilename r outfile openoutputfilename w line infilereadline outfilewriteline line infile linelist linesplit print linelist linelist linelistremove lenlinelist print lenlinelist outfilewriteline infileclose outfileclose except ioerror print inputfilename exist thanks help when i create experimental list interactive window use list removes when i run code still,1 i sure nice way work import tornadoweb import tornadohttpserver class testparamshandlertornadowebrequesthandler def getself param param param param param param else default param param param else default selfwrite param param param param param param my initial answer i think following better class testparamshandlertornadowebrequesthandler def getself params selfwriteparams application tornadowebapplication rtestpparampparampparam testparamshandler rtestpparampparampparam testparamshandler httpserver tornadohttpserverhttpserverapplication httpserverlisten tornadoioloopioloopinstancestart,i trying figure implement url optional url parameters i figured aspnet mvc constraints current project eliminated so i looking baseparamparamparam param param optional is simply regex pattern handlers section,3 assuming python x x ab xvalues b xvalues b,to start code import requests import json url r httpsomeurl p requestsposturl print pstatuscode data jsonloadp entry data print entry print data the output program follows note values sanitized ab is way get value b applied variable since post always return ab i really care since basically constant,1 there framework called jboss drools java runtime monitoring assert business rules answers second part question however i unsure framework python,is performance code maintenance issue using assert part standard code instead using debugging purposes is assert x x less zero better worse x raise exception x less zero also way set business rule like x raise error always checked without tryexceptfinally anytime throughout code x less error raised like set assert x start function anywhere within function x becomes less exception raised,1 if check documentation operator module find multiplication operator mul also i believe definition coprime relies definitions previous problems,from python problemset i would like test following functions seems mult coprime could defined i tried importing math help any recommendations import itertools def primefactorsvalue value itertoolschainiter xrangeintvalue thisthis value break value value break value yield yield value primefactors generator object primefactors x def primefactorsmultn res listprimefactorsn return sortedfact rescountfact fact setres primefactorsmult def totientn operator import mul n return return reducemul p pm pm primefactorsmultn totient,1 i would recommend following six import b that requires six module course if want another version import sys sysversion def bx return x else import codecs def bx return codecslatinencodex more info these solutions essentially work clean fast going get support byte values none solutions,i writing module supposed work python i need define binary string usually would something like data b abc code code fails python invalid syntax how i write code way work versions python note binary contain kind characters xff important,2 this worked grab gevent installer unofficial windows binaries python extension packages install greenlet site and bit windows machine trouble installing read,however gevent depends upon greenlet msi version i found fails install egg refuses install the msi version fails follows cwindowssystemeasyinstall greenlet installdir cpythonlibsitepackages searching greenlet reading httppypipythonorgsimplegreenlet reading httpbitbucketorgambroffgreenlet reading httpundefinedorgpythongreenlet best match greenlet downloading httppypipythonorgpackagessourceggreenletgreenlettargzmdddffeeebfaecd processing greenlettargz running greenletsetuppy q bdistegg distdir cusersianappdatalocaltempeasyinstallepggreenleteggdisttmpmqhun cpythonlibdistutilsdistpy userwarning unknown distribution option repository warningswarnmsg greenletc greenletc fatal error c idb illegal extension pdb file error setup script exited error command cprogram files xmicrosoft visual studio vcbinclexe failed exit status cwindowssystem i guess means i wrong version vs is anything else i use i want get pyqt gui lock database reached takes ages reply,3 use regular expression script surpress anything beginning outputting or pipe whole output script grep v surpress lines negative,i trying format tab delimited text file negative values data set i trying ignore lines data negative values showing i want write output file rows data positive values is anyway wild character looks strings i would rather convert list floats i get away here code without mention negative values yet import sys os inputfilename sysargv outputfilename ospathsplitextinputfilenameeditedtxt try infile openinputfilename r outfile openoutputfilename w line infilereadline outfilewriteline line infile line linestrip linelist linesplit linelist line line linelist line print linelist print lenlinelist lenlinelist print linelist line joinlinelist line line n outfilewriteline infileclose outfileclose except ioerror print inputfilename exist i already help gotten rid empty values data file nine columns now i trying get rid rows negative values,1 sortof example zopeinterfacecommonidatetime import print idatemodule zopeinterfacecommonidatetime print attributemodule zopeinterfaceinterface the module attribute may seem surprising since imported attribute type defined looking zopeinterfacecommonidatetypepy see zopeinterface import interface attribute explains value module you also run problems instances types imported modules suppose create attribute instance named att att attribute foo print attmodule zopeinterfaceinterface again learning type came variable defined quite possibly biggest reason use wildcard imports know getting pollute namespace possibly clobber typesvariables class attributeobject foo print attributefoo zopeinterfacecommonidatetime import print attributefoo traceback recent call last file stdin line module attributeerror type object attribute attribute foo even today import works without collision guarantee happen future updates package imported,as example say i variable defined may multiple import import etc is way figure one variables namespace defined edit thanks i already understand import often considered poor form that question though case i write it nice way find variable came,1 first really lock user accounts server but really want monitor activity within file system got couple options write script parse bash history logout save log time poor install iwatch point locations monitor write script record pertinent information whenever something changes log file if want monitor user activity watching shoulder little harder especially things sftp actually make entries bashhistory it entirely different subsystem the best thing monitor areas filesystem users access changes log another reason lock users linux user folders reason everybody gets sandbox touch,i work server along number people unexplained occurrences change files symlinks etc unfortunately level file system rights is straightforward way capture activity loginlogout time i know last command shows files changed deleted added etc symlinks created changed deleted i wondering straight forward something like bash python direction go thanks help,1 here api specification simplepresence api setpresence call httptelepathyfreedesktoporgspecconnectioninterfacesimplepresencehtmlmethodsetpresence i think problem trying set presence invalid status allow set status one connection manager recognises eg available you set whatever like message so code read something like simplepresencesetpresenceavailable status,i getting error i try setting status empathy dbus using python code i got different sources getting status clementine music player import dbus clementine lives session bus sessionbus dbussessionbus get clementine player object get interface object otherwise type full interface name every method call player sessionbusgetobject orgmprisclementine player iface dbusinterfaceplayer dbusinterface orgfreedesktopmediaplayer call method interface metadata ifacegetmetadata print metadatatitle metadataartist status metadatatitle metadataartist code httpsgithubcomenglakupferblobmasterkupferpluginempathypy import os import subprocess import sys import time import pynotify pn takes long time empathy willing accept statuses empathystartupseconds def showusage print nusage print sysargv joinstatuseskeys def setstatusstatus try activatestatus notifysetstatusstatus except indexerror print missing required parameter showusage except valueerror err print err showusage def notifysetstatusstatus success pniniticonsummarybody success raise error i like icon even relevant icon notificationkeyboardbrightnesslow pnnotificationempathy tried set status status iconshow def main give empathy time start setstatusstatus def text return text all code derived httpsgithubcomenglakupferblobmasterkupferpluginempathypy accountmanagerpath orgfreedesktoptelepathyaccountmanager accountmanageriface orgfreedesktoptelepathyaccountmanager accountiface orgfreedesktoptelepathyaccount channelgroupiface orgfreedesktoptelepathychannelinterfacegroup contactiface orgfreedesktoptelepathyconnectioninterfacecontacts simplepresenceiface orgfreedesktoptelepathyconnectioninterfacesimplepresence dbuspropsiface orgfreedesktopdbusproperties channeldispatcheriface orgfreedesktoptelepathychanneldispatcher channeldispatcherpath orgfreedesktoptelepathychanneldispatcher channeltype orgfreedesktoptelepathychannelchanneltype channeltypetext orgfreedesktoptelepathychanneltypetext channeltargethandle orgfreedesktoptelepathychanneltargethandle channeltargethandletype orgfreedesktoptelepathychanneltargethandletype empathyclientiface orgfreedesktoptelepathyclientempathy empathyaccountkey empathyaccount empathycontactid empathycontactid attributes alias orgfreedesktoptelepathyconnectioninterfacealiasingalias presence orgfreedesktoptelepathyconnectioninterfacesimplepresencepresence contactcaps orgfreedesktoptelepathyconnectioninterfacecontactcapabilitiesdraftcaps jid orgfreedesktoptelepathyconnectioncontactid caps orgfreedesktoptelepathyconnectioninterfacecapabilitiescaps def createdbusconnection sbus dbussessionbus proxyobj sbusgetobjectaccountmanageriface accountmanagerpath dbusiface dbusinterfaceproxyobj dbuspropsiface return dbusiface def activatestatus bus dbussessionbus interface createdbusconnection validaccount interfacegetaccountmanageriface validaccounts account busgetobjectaccountmanageriface validaccount connectionstatus accountgetaccountiface connectionstatus connectionstatus continue connectionpath accountgetaccountiface connection connectioniface connectionpathreplace connection busgetobjectconnectioniface connectionpath simplepresence dbusinterfaceconnection simplepresenceiface try simplepresencesetpresencestatus status except dbusexceptionsdbusexception printstatus supported validaccount print simplepresence main i run script i get following error phanindraphanindra python clementinepy onelove blue clementinepy gtkwarning unable locate theme engine modulepath pixmap onelove blue supported orgfreedesktoptelepathyaccountgabblejabberabcdgmailecom i something wrong functions deprecated,1 are sure adding fake doesnt change anything managepy migrate blog fake drop table blogblog manually mysql console,i going tutorial django i followed every step still i get error every time i try migrate the initial migration works trying migrate i get rootdebiansitestumblog managepy migrate blog traceback recent call last file managepy line module executemanagersettings file usrlibpymodulespythondjangocoremanagementinitpy line executemanager utilityexecute file usrlibpymodulespythondjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file usrlibpymodulespythondjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file usrlibpymodulespythondjangocoremanagementbasepy line execute output selfhandleargs options file usrlibpymodulespythonsouthmanagementcommandsmigratepy line handle deleteghosts deleteghosts file usrlibpymodulespythonsouthmigrationinitpy line migrateapp success migratormigratemanytarget workplan database file usrlibpymodulespythonsouthmigrationmigratorspy line migratemany result migratorclassmigratemanymigrator target migrations database file usrlibpymodulespythonsouthmigrationmigratorspy line migratemany result selfmigratemigration database file usrlibpymodulespythonsouthmigrationmigratorspy line migrate result selfrunmigration file usrlibpymodulespythonsouthmigrationmigratorspy line run return selfrunmigrationmigration file usrlibpymodulespythonsouthmigrationmigratorspy line runmigration migrationfunction file usrlibpymodulespythonsouthmigrationmigratorspy line lambda return lambda directionorm file sitetumblogblogmigrationsinitialpy line forwards name selfgf djangodbmodelsfieldscharfield maxlength file usrlibpymodulespythonsouthdbgenericpy line createtable joincol col columns col file usrlibpymodulespythonsouthdbgenericpy line execute cursorexecutesql params file usrlibpymodulespythondjangodbbackendsutilpy line execute return selfcursorexecutesql params file usrlibpymodulespythondjangodbbackendsmysqlbasepy line execute return selfcursorexecutequery args file usrlibpymodulespythonmysqldbcursorspy line execute selferrorhandlerself exc value file usrlibpymodulespythonmysqldbconnectionspy line defaulterrorhandler raise errorclass errorvalue mysqlexceptionsoperationalerror table blogblog already exists i searched around found adding fake skip error change thing what problem i fix,2 i personal experience project page mlabwrap seems indicate fit needs from project page mlabwrap highlevel python matlabâ® bridge lets matlab look like normal python library,i full functional matlab program i need make python script i call specific function matlab program i using python version i try install pymat work reason i look questions recommend pymat old maintained,2 the example gave need close file opened handled similar using c now example would close import csv f open somecsv rb reader csvreaderf row reader print row fclose the two effectively thing takes care failures run make sure file handle f closed if problem open close still open file resource edit the import csv f open somecsv rb try reader csvreaderf row reader print row finally fclose,i new python feel confused i call close for instance consider example csv documentation import csv open somecsv rb f reader csvreaderf row reader print row there readerclose end task q how i find whether function call need followed close call,1 you use sage pythonbased system interface matlab,i full functional matlab program i need make python script i call specific function matlab program i using python version i try install pymat work reason i look questions recommend pymat old maintained,1 you run code following manner order get output python filenamepy username,in python i run code sys import argv script username argv prompt print hi i script username script i get error traceback recent call last script username argv valueerror need value unpack what error mean,1 you need call appcfg vacuumindexes order delete indexes longer defined indexyaml,this follow earlier question this model class maindbmodel url dbstringproperty taglist dbstringlistproperty totalvalue dbintegerpropertydefault pitch dbtextproperty owner dbuserproperty title dbstringproperty date dbdatetimepropertyautonowaddtrue display dbbooleanproperty indexyaml indexes kind main properties name display name date direction desc kind main properties name display name owner name date direction desc kind main properties name owner name date kind main properties name owner name date direction desc kind main properties name taglist name date direction desc kind main properties name taglist name taglist name taglist name totalvalue direction desc kind main properties name taglist name taglist name totalvalue direction desc kind main properties name taglist name totalvalue kind main properties name taglist name totalvalue direction desc i removed property totalvalue back i see still indexed what correct procedure remove indexes involving totalvalue thanks,1 if want scrape use scraper module like mechanize httpwwwsearchsourceforgenetmechanize,what would best way emulate ie browser python scraping i found script httpwwwmayukhbosecompythoniecindexphp wondering anything updated able fill forms thanks,1 django derives label form field corresponding variable name humanizes for example field called myvariable would translate my variable the simplest way fix would give humanreadable name field server formsmodelchoicefieldqueryset serversobjectsall requiredfalse however also pass string use label via form field label parameter r formsmodelchoicefieldqueryset serversobjectsall requiredfalse label select server,the view def gridserverdropdownsearchrequest r requestget requestget r r requestget r servers serversobjectsgetnamer drives serversdrivessetall memory serversmemorysetall return rendertoresponse gridserverdropdownsearchresultshtml servers servers query r drives drives memory memory else return rendertoresponse gridsearchformhtml error true the form class serverdropdownformformsform r formsmodelchoicefieldqueryset serversobjectsall requiredfalse the template div form actionserverdropdownsearch methodget formastable input type submit value submit form div the resulting dropdown form works flawlessly however immediately left dropdown list r capital r i know r specified code if i replace incidence r say z z appears however why get capitalized is default case specified engine how i hide r instead indicate select a server something descriptive thanks advance,2 python stop reading file another process completed writing if i waiting file another process i usually process write different file name once process finished writing closes renames file file name expecting that way i get partial file,my knowledge file buffers work fairly weak forgive simple mindedness question i piece code python waits file appear reads try f open filetxt fclose print message received break except timesleep where filetxt file written another program however i suspicion python reading file closing handle file filetxt completely written i even call close program writing file should even possible if case way i detect reading program listed whether buffers flushed i call fclose,1 to check whether file exists use ospathexists maybe ospathisfile require regular file on unix directory entry created file opened writeappend but bytes written file actually show point view reader io flushed there normal way asking whether pending io file least unix,my knowledge file buffers work fairly weak forgive simple mindedness question i piece code python waits file appear reads try f open filetxt fclose print message received break except timesleep where filetxt file written another program however i suspicion python reading file closing handle file filetxt completely written i even call close program writing file should even possible if case way i detect reading program listed whether buffers flushed i call fclose,1 don use whileloop purpose there better way though details depend os linux inotify you write simple pyinotify script watch directory react inclosewrite events occur file closed osx fsevents windows similar facilities,my knowledge file buffers work fairly weak forgive simple mindedness question i piece code python waits file appear reads try f open filetxt fclose print message received break except timesleep where filetxt file written another program however i suspicion python reading file closing handle file filetxt completely written i even call close program writing file should even possible if case way i detect reading program listed whether buffers flushed i call fclose,2 python ordered dictionary looking for example collections import ordereddict data str str str str ordereddata ordereddictsorteddataitems ordereddata ordereddict str str str str you still deal ordereddict way deal normal dictionary ordereddata str ordereddata str ordereddata ordereddict str str str str str also work kind key ints required,basically i dictionary keys ints highest keys end list lower keys start sort like list note i use list reasons i go,2 if willing use syntax like obj happy could use getitem setitem def getitemself key key selftraitskeys raise keyerror return traitskey def setitemself key value key selftraitskeys raise keyerror traitskey value if really want objtraits happy could define subclass dict make objtraits instance subclass the subclass would override getitem setitem see ps to subclass dict inherit collectionsmutablemapping dict otherwise dictupdate would call new setitem import collections class traitsdictcollectionsmutablemappingdict def getitemselfkey return dictgetitemselfkey def setitemself key value value intvalue value raise valueerror v range formatvvalue dictsetitemselfkeyvalue def delitemself key dictdelitemselfkey def iterself return dictiterself def lenself return dictlenself def containsself x return dictcontainsselfx class personobject def initself selftraitstraitsdict happy worker honest pperson printptraits happy ptraits happy printptraits happy ptraits happy valueerror range,i pretty new python anything flatout bad please point i object dictionary traits happy worker honest the value trait int range new traits allowed added i want gettersetters i make sure constraints kept here i made getter setter def gettraitself key key selftraitskeys raise keyerror return traitskey def settraitself key value key selftraitskeys raise keyerror value intvalue value value raise valueerror traitskey value i read website property method but i see easy way make use gettingsetting values inside dictionary is better way ideally i would like usage object objtraits happy would invoke setter method throw valueerror since,3 friends always implement functions boundingrect paint want display graph scene qt documentation says to write graphics item first create subclass qgraphicsitem start implementing two pure virtual public functions boundingrect returns estimate area painted item paint implements actual painting for example class simpleitem public qgraphicsitem public qrectf boundingrect const qreal penwidth return qrectf penwidth penwidth penwidth penwidth void paintqpainter painter const qstyleoptiongraphicsitem option qwidget widget painterdrawroundedrect,how i create class extend qgraphicsitem define new kind item i trying usrbinpython import sys pyqt import qtgui class nodeqtguiqgraphicsitem def initself parent selfsetflagqtguiqgraphicsitemitemismovable app qtguiqapplicationsysargv scene qtguiqgraphicsscene sceneaddtexttest sceneadditemnode view qtguiqgraphicsviewscene viewshow sysexitappexec get error traceback recent call last file primopy line module sceneadditemnode file primopy line init selfsetflagqtguiqgraphicsitemitemismovable runtimeerror underlying cc object deleted what i wrong i call qgraphicsitem constructor inside init method node qgraphicsitem abstract class,1 the problem tables migration trying create already exist database they must created syncdb get syncdb later start using south app previous migration it suspicious name migration initial what migrations to fix problem first make sure duplicate migrations example initial creates tables initial tries you need one initial migration app next ones record changes schema then remove tables database create something like might work managepy migrate appname fake managepy migrate appname zero managepy migrate appname if fails existing new tables migration drop tables hand mysql console,i going tutorial django i followed every step still i get error every time i try migrate the initial migration works trying migrate i get rootdebiansitestumblog managepy migrate blog traceback recent call last file managepy line module executemanagersettings file usrlibpymodulespythondjangocoremanagementinitpy line executemanager utilityexecute file usrlibpymodulespythondjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file usrlibpymodulespythondjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file usrlibpymodulespythondjangocoremanagementbasepy line execute output selfhandleargs options file usrlibpymodulespythonsouthmanagementcommandsmigratepy line handle deleteghosts deleteghosts file usrlibpymodulespythonsouthmigrationinitpy line migrateapp success migratormigratemanytarget workplan database file usrlibpymodulespythonsouthmigrationmigratorspy line migratemany result migratorclassmigratemanymigrator target migrations database file usrlibpymodulespythonsouthmigrationmigratorspy line migratemany result selfmigratemigration database file usrlibpymodulespythonsouthmigrationmigratorspy line migrate result selfrunmigration file usrlibpymodulespythonsouthmigrationmigratorspy line run return selfrunmigrationmigration file usrlibpymodulespythonsouthmigrationmigratorspy line runmigration migrationfunction file usrlibpymodulespythonsouthmigrationmigratorspy line lambda return lambda directionorm file sitetumblogblogmigrationsinitialpy line forwards name selfgf djangodbmodelsfieldscharfield maxlength file usrlibpymodulespythonsouthdbgenericpy line createtable joincol col columns col file usrlibpymodulespythonsouthdbgenericpy line execute cursorexecutesql params file usrlibpymodulespythondjangodbbackendsutilpy line execute return selfcursorexecutesql params file usrlibpymodulespythondjangodbbackendsmysqlbasepy line execute return selfcursorexecutequery args file usrlibpymodulespythonmysqldbcursorspy line execute selferrorhandlerself exc value file usrlibpymodulespythonmysqldbconnectionspy line defaulterrorhandler raise errorclass errorvalue mysqlexceptionsoperationalerror table blogblog already exists i searched around found adding fake skip error change thing what problem i fix,2 what actually going migrations if getting error simply createtable called twice blogblog blogblog already existed database initial migration perhaps leftover previous attempt creating blog never got migrated zero if error occurring initial migration completes likely artifact remove database manually try if initial migration succeeds later migration fails find duplicate createtable blogblog,i going tutorial django i followed every step still i get error every time i try migrate the initial migration works trying migrate i get rootdebiansitestumblog managepy migrate blog traceback recent call last file managepy line module executemanagersettings file usrlibpymodulespythondjangocoremanagementinitpy line executemanager utilityexecute file usrlibpymodulespythondjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file usrlibpymodulespythondjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file usrlibpymodulespythondjangocoremanagementbasepy line execute output selfhandleargs options file usrlibpymodulespythonsouthmanagementcommandsmigratepy line handle deleteghosts deleteghosts file usrlibpymodulespythonsouthmigrationinitpy line migrateapp success migratormigratemanytarget workplan database file usrlibpymodulespythonsouthmigrationmigratorspy line migratemany result migratorclassmigratemanymigrator target migrations database file usrlibpymodulespythonsouthmigrationmigratorspy line migratemany result selfmigratemigration database file usrlibpymodulespythonsouthmigrationmigratorspy line migrate result selfrunmigration file usrlibpymodulespythonsouthmigrationmigratorspy line run return selfrunmigrationmigration file usrlibpymodulespythonsouthmigrationmigratorspy line runmigration migrationfunction file usrlibpymodulespythonsouthmigrationmigratorspy line lambda return lambda directionorm file sitetumblogblogmigrationsinitialpy line forwards name selfgf djangodbmodelsfieldscharfield maxlength file usrlibpymodulespythonsouthdbgenericpy line createtable joincol col columns col file usrlibpymodulespythonsouthdbgenericpy line execute cursorexecutesql params file usrlibpymodulespythondjangodbbackendsutilpy line execute return selfcursorexecutesql params file usrlibpymodulespythondjangodbbackendsmysqlbasepy line execute return selfcursorexecutequery args file usrlibpymodulespythonmysqldbcursorspy line execute selferrorhandlerself exc value file usrlibpymodulespythonmysqldbconnectionspy line defaulterrorhandler raise errorclass errorvalue mysqlexceptionsoperationalerror table blogblog already exists i searched around found adding fake skip error change thing what problem i fix,1 some obvious tips come mind first do use keys method checking existence key instead key selftraitskeys use key selftraits do explicitly throw keyerror exception thrown try access inexistent key your code could look like changes def gettraitself key return traitskey def settraitself key value key selftraits raise keyerror value intvalue value value raise valueerror traitskey value ps i check correctness code thoroughly may issues,i pretty new python anything flatout bad please point i object dictionary traits happy worker honest the value trait int range new traits allowed added i want gettersetters i make sure constraints kept here i made getter setter def gettraitself key key selftraitskeys raise keyerror return traitskey def settraitself key value key selftraitskeys raise keyerror value intvalue value value raise valueerror traitskey value i read website property method but i see easy way make use gettingsetting values inside dictionary is better way ideally i would like usage object objtraits happy would invoke setter method throw valueerror since,1 sure use mytextctrlgetvalue parse string something like beautifulsoup xmldomminidom htmlparser etc beautifulsoup import beautifulsoup lets say text inside textctrl htmlheadtitlepage titletitleheadbodyp idfirstpara aligncenterthis paragraph bonebp idsecondpara alignblahthis paragraph btwobhtml htmlstr mytextctrlgetvalue soup beautifulsouphtmlstr soupcontentsname u html soupcontentscontentsname u head head soupcontentscontents headparentname u html headnext titlepage titletitle headnextsiblingname u body headnextsiblingcontents p idfirstpara aligncenterthis paragraph bonebp headnextsiblingcontentsnextsibling p idsecondpara alignblahthis paragraph btwobp,is possible library allow parse html code inside wxtextctrl widget,1 no would appear inspecting source distutilsfilelist work parsing manifestin shows line split purely whitespace determine action parameters here source python def parsetemplatelineself line words linesplit action words action include exclude globalinclude globalexclude elif action recursiveinclude recursiveexclude lenwords raise distutilstemplateerror expects dir pattern pattern action dir convertpathwords patterns mapconvertpath words,i inherited code directory names embedded spaces i option renaming directory let say name directory embedded spaces now i trying access files directory manifestin file i tried following recursiveinclude embedded spaces dat recursiveinclude embedded spaces dat recursiveinclude embedded spaces dat these give errors something along lines warning files found matching spaces directory embedded i workaround recursiveinclude embedded dat i wondering less hackish way encode spaces manifestin directory names,1 we working updating neojdjango integration work neojrestclient fruits labor github quick comments blog there pros cons integration the obviously impacting use rest client get use remote database losing quite bit performancewise otoh integration works alongside relational database still use djangocontrib stuff relies original orm handles indexing query sets pretty nicely to want using neodjango simply get neojrestclient based node model instance modelinstancenode newproperty something we still cranking making integration dynamic supporting traversalsetc pythonic way currently important improving performance if interested i love feedback,so i looking django neoj integration much what i want know i model like one if i want add new property model would simple nodesetproperty newproperty something moreover queries django would work how traversing made i would appreciate response d thanks,3 we updated old django integration use neojrestclient called neodjango we made major improvements old integration using successfully build scholrly it quite production something the library allows model definition query sets automated indexing works alongside relational database still use contrib modules based standard orm i posted bit elsewhere stackoverflow interested,i planning implement recommendation engine details given python preferred choice along neoj database can anyone please point integration neoj web framework like django done is possible integrate like php integrates mysql thanks advance,2 i wrote program play game of course i automate human side i believe i way i invalidate approach played real human i approached machine learning perspective treated problem hidden markov model total price observation my solution use particle filter this solution written python using numpy scipy i stated assumptions i made either explicitly comments implicitly code i also set additional constraints sake getting code run automated fashion it particularly optimized i tried err side comprehensibility rather speed each iteration outputs current true quantities guess i pipe output file i review easily an interesting extension would plot output graph either d fruits d fruits then would able see particle filter hone solution update edited code include updated parameters tweaking included plotting calls using matplotlib via pylab plotting works linuxgnome mileage may vary defaulted numfruits plotting support just comment pylab calls remove plotting able change numfruits anything does good job estimating current fxn represented unknownquantities x prices totalprice in d fruits line d fruits plane seems little data particle filter reliably hone correct quantities need little smarts top particle filter really bring together historical information you could try converting particle filter nd rdorder update i playing around code lot i tried bunch things present final program i making starting burn idea changes the particles use floating points rather integers not sure meaningful effect general solution rounding integers done making guess plotting shows true quantities green square current guess red square currently believed particles shown blue dots sized much believe this makes really easy see well algorithm working plotting also tested working win bit added parameters turning offon quantity changing price changing of course interesting it pretty dang good job noted really tough problem getting exact answer hard turning changequantities produces simplest case you get appreciation difficulty problem running fruits changequantities see quickly hones correct answer see harder increase number fruit you also get perspective difficulty keeping changequantities adjusting maxquantitychange small values large values one situation struggles dimension one fruit quantity gets close zero because using average particles guess always skew away hard boundary like zero in general makes great particle filter tutorial future import division import random import numpy import scipystats import pylab assume guesser knows prices total guesser must determine quantities all pylab graphing comment undesired graphing graphs first fruits first dimensions numfruits maxquantitychange maximum percentage change total quantity fruit change per iteration maxquantity bound sake instantiating variables minquantitytotal prevent degenerate conditions quantities hit maxfruitprice bound sake instantiating variables numparticles newparticles num new particles introduce iteration guessing numiterations max iterations run changequantities true changeprices true change individual fruit quantities random amount time never exceed changing fruit quantity maxquantitychange def updatequantitiesquantities oldtotal maxsumquantities minquantitytotal newtotal oldtotal maxchange intoldtotal maxquantitychange randomrandom stop randomly changeindex randomrandint lenquantities changeval randomrandintmaxchangemaxchange quantitieschangeindex changeval prevent negative quantities quantitieschangeindex changeval newtotal changeval absnewtotal oldtotal maxquantitychange quantitieschangeindex changeval reverse change def totalpriceprices quantities return sumpricesquantities def sampleparticlesetparticles fruitprices currenttotal numtosample assign weight particle using observation observation currenttotal weight probability particle guess given current observation determined looking distance hyperplane line plane hyperplane probability density fxn normal distribution centered variance distancestocurrenthyperplane absnumpydotparticle fruitpricescurrenttotalnumpylinalgnormfruitprices particle particles weights numpyarrayscipystatsnormpdfdistancestocurrenthyperplanep variance p rangenumparticles weightsum sumweights no need normalize relative weights fine sample unnormalized create new particle set weighted weights beliefparticles beliefweights p range numtosample sample randomuniform weightsum sum across weights exceed sample weight summed index particle use psum pi psum sample pi psum weightspi beliefparticlesappendparticlespi beliefweightsappendweightspi return beliefparticles numpyarraybeliefweights generates new particles around equation current prices total better particle generation uniformly random def generatenewparticlescurrenttotal fruitprices numtogenerate newparticles maxvalues intcurrenttotalfruitpricesn n rangenumfruits p range numtogenerate newparticle numpyarrayrandomuniformmaxvaluesn n rangenumfruits newparticle currenttotal sumnewparticleifruitpricesi range numfruits fruitprices newparticlesappendnewparticle return newparticles initialize data structures represents users first round quantity selection fruitprices numpyarrayrandomrandintmaxfruitprice n rangenumfruits fruitquantities numpyarrayrandomrandintmaxquantity n rangenumfruits currenttotal totalpricefruitprices fruitquantities success false particles generatenewparticlescurrenttotal fruitprices numparticles numpyarrayrandomrandintmaxquantity n rangenumfruits p rangenumparticles guess numpyaverageparticles axis guess numpyarrayintroundguessn n rangenumfruits print truth strfruitquantities print guess strguess pylabion pylabdraw pylabscatterp p particles p p particles pylabscatterfruitquantities fruitquantities c g marker pylabscatterguess guess c r marker pylabxlim maxquantity pylabylim maxquantity pylabdraw guess fruitquantitiesall rangenumiterations print changeprices fruitprices numpyarrayrandomrandintmaxfruitprice n rangenumfruits changequantities updatequantitiesfruitquantities mapupdatequantities particles particle filter prediction print truth strfruitquantities currenttotal totalpricefruitprices fruitquantities guesser turn particle filter prediction done changequantities true update beliefparticles beliefweights sampleparticlesetparticles fruitprices currenttotal numparticlesnewparticles newparticles generatenewparticlescurrenttotal fruitprices newparticles make guess guess numpyaveragebeliefparticles axis weightsbeliefweights could optimize removing outliers try using median guess numpyarrayintroundguessn n rangenumfruits convert integers print guess strguess pylabcla pylabscatterp p newparticles p p newparticles c plot new particles pylabscatterp p beliefparticles p p beliefparticles sbeliefweights plot current particles pylabscatterfruitquantities fruitquantities c g marker plot truth pylabscatterguess guess c r marker plot current guess pylabxlim maxquantity pylabylim maxquantity pylabdraw guess fruitquantitiesall success true break attach new particles existing particles next run beliefparticlesextendnewparticles particles beliefparticles else success true success print correct quantities guessed else print unable get correct answer within numiterations iterations pylabioff pylabshow,i learning programming python algo’s trying work project i find interesting i created basic python scripts i’m sure approach solution game i trying build here’s game work users given items value for example apple pears oranges they get chance choose combo like ie apples pears oranges the output computer gets total valuein example currently the computer try guess which obviously won’t able get correctly first turn value quantityday valueday apple pears orange total the next turn user modify numbers total quantity percent may chose i’ll use example the prices fruit changeat random total value may change based alsofor simplicity i changing fruit prices example using example day game user returns value day here example quantityday changeday valueday quantityday changeday valueday i hope tables show right i manually space hopefully screen work let know i try upload screenshot i trying see i figure quantities timeassuming user patience keep entering numbers i know right restriction total value cannot i cannot within accuracy right user entering forever what i done far here’s solution farnot much basically i take values figure possible combos themi done part then i take possible combos put database dictionaryso example could dictionary entry apple pears oranges way apple pears oranges i time i get new number i list possibilities here’s i’m stuck is using rules i figure best possible solution i think i’ll need fitness function automatically compares two days data removes possibilities variance previous days data questions so question user changing total list probabilities i approach what i need learn is algorithms theories i use applicable or help understand mistake suggest rules i add make goal feasibleif current state i thinking adding fruits saying must pick least etc also i vague understanding genetic algorithms i thought i could use something i use i eager learn advice tips would greatly appreciatedjust please tell game impossible thanks advance update getting feedback hard solve so i thought i add another condition game interfere player doinggame stays everyday value fruits change pricerandomly would make easier solve because within movement certain fruit value changes combo probable time day anything possible getting close enough range almost impossible prices fruits change user choose change tover time range narrow narrow in example prices volatile enough i think i could brute force solution gave range guess i trying figure elegant solution solutions keep narrowing range time update after reading asking around i believe hidden markovviterbi problem tracks changes fruit prices well total sumweighting last data point heaviest i sure apply relationship though i think case could wrong least i starting suspect type machine learning problem update i created test casewith smaller numbers generator help automate user generated data i trying create graph see likely here code along total values comments users actually fruit quantities usrbinenv python import itertools fruit price data fruitpriceday apple pears oranges fruitpriceday apple pears oranges fruitpriceday apple pears oranges generate possibilities testingwarningwill scale large numbers def possibilitygeneratortargetsum apple pears oranges alldaypossible counter applerange range targetsum apple pearsrange range targetsum pears orangesrange range targetsum oranges j k itertoolsproductapplerange pearsrange orangesrange j k targetsum currentpossible print counter print apple iapple pears jpears oranges koranges currentpossible apple iapple currentpossible pears jpears currentpossible oranges koranges print currentpossible alldaypossiblecounter currentpossible counter counter return alldaypossible total sum returned user value fruits totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day totalsumday computer know users quantities apple pears oranges current prices day graph graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges graph day possibilitygeneratortotalsumday fruitpriceday apple fruitpriceday pears fruitpriceday oranges sample dict oranges apple pears oranges apple pears print graph,2 new traits allowed added the natural way use object instead dictionary set class slots the value trait int range i want gettersetters i make sure constraints kept the natural way use object instead dictionary write gettersetter logic part class wrap properties since properties work way refactoring write code generates property given attribute name the following probably overengineered def onetotenattr def getobj return getattrobj attr def setobj val val intval val raise valueerror setattrobj attr val return propertyget set def createtraitsclasstraits class traitsobject slots trait trait traits trait traits localstrait onetoten trait def initself kwargs k v kwargsitems setattrself k v trait traits assert hasattrself trait missing trait init def reprself return traitss join trait getattrself trait trait traits return traits exampletype createtraitsclass happy worker honest exampleinstance exampletypehappy worker honest set traits object exampleinstance,i pretty new python anything flatout bad please point i object dictionary traits happy worker honest the value trait int range new traits allowed added i want gettersetters i make sure constraints kept here i made getter setter def gettraitself key key selftraitskeys raise keyerror return traitskey def settraitself key value key selftraitskeys raise keyerror value intvalue value value raise valueerror traitskey value i read website property method but i see easy way make use gettingsetting values inside dictionary is better way ideally i would like usage object objtraits happy would invoke setter method throw valueerror since,1 from docs o object pyobject store python object without conversion c object pointer the c program thus receives actual object passed the object’s reference count increased the pointer stored null o object typeobject pyobject store python object c object pointer this similar o you returning stolen reference increment first,i writing code trying get used c api numpy arrays include pythonh include numpyarrayobjecth include stdioh include stdboolh static char doc document static pyarrayobject tracepyobject self pyobject args pyarrayobject matin pyargparsetupleargs oamppyarraytype ampmatin return null printfa return matin static pymethoddef tracemethods trace trace methvarargs doc null null null pymodinitfunc inittracevoid void pyinitmoduletrace tracemethods importarray this strippeddown version i want able get object type pyarrayobject return back unfortunately gives segfault also linux bit python,1 you need generate xml view just create xml template render string write result temp file,what i trying use simile timeline django app the timeline requires data xml file now i know render view html and i probably figure render view xml but would one render pull xml data html file xml file exist disk since generated django thanks edit the line takes xml javascript looks like timelineloadxmlstaticexamplexml functionxmlurl eventsourceloadxmlxmlurl i need path since inserting xml directly string work but path exists since xml file never actually exists disk,1 your modwsgi likely compiled python you cannot use virtualenv one python version modwsgi compiled different python version read httpcodegooglecompmodwsgiwikicheckingyourinstallationpythonsharedlibrary checks document,i created two python environments virtualenv usrlocalpythonenvbaseline usrlocalpythonenvdjango both created nositepackages i installed django django environment easyinstall my wsgiconf file line set python interpreter wsgipythonhome usrlocalpythonenvbaseline my djangowsgi file starts like import site siteaddsitedir usrlocalpythonenvdjangolibpythonsitepackages import os import sys but i try visit site i get error httpderrorlog contains error traceback recent call last error file serviceusrlocaldjangoappsapachedjangowsgi line error import site error importerror no module named site i lost python interpreter import standard library i even sure check httpd even using interpreter usrlocalpythonenvbaseline would good start edit unrelated i quite torn whether i post serverfault advice front appreciated edit so i able get debug information thanks httpcodegooglecompmodwsgiwikidebuggingtechniques i changed djangowsgi script contain import sys def applicationenviron startresponse status ok output hello world print environ wsgierrors syspath print environ wsgierrors sysprefix print environ wsgierrors sysexecutable responseheaders contenttype textplain contentlength strlenoutput startresponsestatus responseheaders return output this put python interpreter information varloghttpderrorlog the error output error usrlocalpythonenvbaselinelibpythonzip usrlocalpythonenvbaselinelibpython usrlocalpythonenvbaselinelibpythonplatlinux usrlocalpythonenvbaselinelibpythonlibtk usrlocalpythonenvbaselinelibpythonlibdynload error usrlocalpythonenvbaseline error usrbinpython so syspath sysexecutable point problem for reason syspath using lib files exist baseline even contain lib directory created python sysexecutable shows modwsgi still running default usrbinpython interpreter interpreter usrlocalpythonenvbaselinebin not sure case least i know bit edit this solved django still lists python executable usrbinpython even though far i tell since python version using usrlocalbinpython is normal,2 something mentioned useful adding suffix day i decoupled suffix logic use number like dates import time def numsuffixn returns suffix given int suf th st nd rd n absn wise guy tens intstrn units n tens tens return suf teens th elif units return sufunits else return suf th def daysuffixt returns suffix given structtime day return numsuffixttmmday examples print numsuffix print numsuffix print numsuffix print print daysuffixtimestrptime dec b print daysuffixtimestrptime nov b print daysuffixtimestrptime oct b print daysuffixtimestrptime sep b print daysuffixtimestrptime nov b print daysuffixtimestrptime oct b y​​​​​​​,short simple i got huge list datetimes like strings jun pm aug am i going shoving back proper datetime fields database i need magic real datetime objects any help even kick right direction would appreciated edit this going django orm i use sql conversion insert,3 user class datastore make player child this work newplayer modelplayeruserusersgetcurrentuser publicname john newplayerput usr usersgetcurrentuser john modelplayerallfilter user usrfetch print johnnickname john note getcurrentuser getcurrentuser source,i attempting lookup user entity related current user i seem able find user get stored database when i creating user first time call i make looks like following newplayer modelplayerparentmodeluserkey userusersgetcurrentuser publicname nickname newplayerput where modelplayer element i trying lookup modeluserkey gets global ancestor user key when i go look i following modelplayerallfilter user usrancestoruserkeyfetch the model player class looks like class playerdbmodel user dbuserproperty publicname dbstringproperty this returns empty list every time what i wrong i starting question determinism point,1 if already using multiprocessing cores max load little benefit adding threads waiting around processor depending algorithm may beneficial use one type dependent,suppose i core machine embarrassingly parallel program i use lots numpy dot products addition numpy arrays i use multiprocessing would nobrainer make sure numpy built version blas uses multithreading however i using multiprocessing cores working hard times in case benefit using multithreading blas most operations blas type type,1 you axessetaspect for example import matplotlibpyplot plt f pltfigure x fgca xsetaspectequal xplotrangerange pltshow,i need match resolution x yaxes matplotlib linear function yx would plot exactly deg line mathematically plotted circle rxy would appear round this i plotting geographical data would like given distance measured along xaxis equal distance measured along yaxis i rather new matplotlib problems finding answer documentation edit this could accomplished manually setting pixelsperunitratio axes is possible if,2 for complete implementation reading value atom feed import urllib import base xmldomminidom import parse def gmailunreadcountuser password takes gmail user name password returns unread messages count integer build authentication string bauth baseencodestringss user password auth basic bauth build request req urllibrequesthttpsmailgooglecommailfeedatom reqaddheaderauthorization auth handle urlliburlopenreq build xml dom tree feed dom parsehandle handleclose get fullcount xml object countobj domgetelementsbytagnamefullcount get text convert integer return intcountobjfirstchildwholetext,how i check number unread gmail message inbox short python script bonus points retrieving password file,3 since slicing behavior built python syntax i recommend putting simple statement loop k idx ik idx raise indexerror list index range print listsidx,i nested lists represents table sorts i would like access element n rows that easy however problem i would like catch anything outside table react but afaics negative indices get interpreted slicing case get wrapped around here example lists rangelenlists k print listsik print indexerror list index range what i would like first call throws indexerror well something triggered program could react any thoughts,1 inside chkifexists would return three variables like return filename hashcolumn filepathnum you would retrieve calling function like filename hashcolumn filepathnum chkifexists you function scope without needing global variables technically need parenthesis either in fact i sure i included but works either way heck,i wrote code order check three files whichever files exist run scan file file exist worry run scan available files produce proper output file available files the program i working includes following code def inputscananswer scannumber rawinputenter scan type number return scannumber this function checks three files exist assign specific values hashcolumn filepathnum def chkifexists list filecsv filecsv filecsv filename list ospathisfilefilename filename filecsv hashcolumn filepathnum filename filecsv hashcolumn filepathnum filename filecsv hashcolumn filepathnum print filename hashcolumn filepathnum def scanchoicescannumber scannumber chkifexists onlinescanfilename filename onlinescanresultscsv hashcolumn filepathnum giving errors elif scannumber print scan elif scannumber print scan else print oops invalid selection please try def onlinescanfiletoscan resultsfile hashcolumn filepathnum web scraping stuff done function the error i run global name filename defined i realize problem i attempting send local variables chkifexists onlinescan parameters i tried using return filename return hashcolumn return filepathnum end chkifexists function working either is anyway i trying onlinescanfilename filename onlinescanresultscsv hashcolumn filepathnum line without using global variables i know discouraged i hoping i go another way also hashcolumn filepathnum parameters onlinescan anything,2 you looking radd class myclassobject def initself value selfvalue value def raddself print radd selfvalue return selfvalue myclass print radd if object left addition support adding object right object right checked radd magic method,i class vecd see httppastebincomyybczq currently i allow vecd i wondering i proceed overload operator way i get following output vecd code required hint direction i look something general useful specific implementation i need implement thing multiplication subtraction etc,3 you want use add possibly radd iadd methods check httpdocspythonorgreferencedatamodelhtmlobjectadd details,i class vecd see httppastebincomyybczq currently i allow vecd i wondering i proceed overload operator way i get following output vecd code required hint direction i look something general useful specific implementation i need implement thing multiplication subtraction etc,2 implement radd when call vecd long float method addy vecd reflected version radd called,i class vecd see httppastebincomyybczq currently i allow vecd i wondering i proceed overload operator way i get following output vecd code required hint direction i look something general useful specific implementation i need implement thing multiplication subtraction etc,2 just supply sufficiently clever function key sorting lambda x tupleyz z zipint str str int xsplit qsubacolumncnumb a c,i really complicated data files i processed file processed i used ordereddictionary capture keys values each ordereddictionary appended list final result list dictionaries because diversity data captured files many keys common enough uncommon keys make exporting data excel complicated i hoping i really need push data consistent structure each key structure like qsubacolumnnumb example i qsubdcolumncnumb we translate key follows question subitem d column c instance because subitem d column c instance must subitema column b instance however one source files might populated data values keys range example source file might terminate qsubdcolumncnumb i iterate list dictionaries pull unique key instances i use csvdictwriter column headings plan sort resulting list unique column headings i seem make sort work specifically i need sort results look like qsubacolumncnumb qsubbcolumncnumb qsubacolumncnumb qsubbcolumncnumb qsubccolumncnumb qsubdcolumncnumb dot dot dot qsubacolumncnumb qsubbcolumncnumb qsubccolumncnumb qsubdcolumncnumb the big issue i know i open particular set files many questions answered many subquestions answered many columns associated question subquestion many instances exist particular combination questions subquestions columns i want using python i able reduce lines sas code last little bit i start writing csv file i seem figure any observations would appreciated my plan find unique keys iterating list dictionaries sort keys correctly i create csv file using keys column headings i know i find unique keys push manually sort read sorted file back seems clumsy,2 how running doctests without nose if cd package directory attempt run run problems full import i able get simple doctest fullyqualified imports running nosetests builtin doctest runner here setup project structure └── mypackage ├── initpy └── modpy here contents modpy file foo providing module example import mypackagemod mypackagemodfoo bar def foo return bar directory project root i run tests python doctest v mypackagepy items tests init tests items passed failed test passed trying import mypackagemod expecting nothing ok trying mypackagemodfoo expecting bar ok items tests modfoo items passed tests tests mod tests items passed failed test passed and nosetests nosetests withdoctest ran test ok if i try run doctest within mypackage directory i get error i suspect happening case finally i think make difference i running python,in doctests module i would like reference module full namespace example hpmyfunc and i would like avoid cluttering doctests writing import healpy hp doctests i run doctesttestmod i know i use globs keyword provide i run nose i use setup function is another standard way could work,2 you could use regular expression extract different parts key use sort eg import names qsubacolumncnumb qsubbcolumncnumb qsubbcolumncnumb qsubacolumncnumb qsubdcolumncnumb qsubbcolumncnumb qsubccolumncnumb qsubccolumncnumb qsubacolumncnumb qsubdcolumncnumb split def keyname matchrecompiler qdsubwcolumnwnumbd match sure actual order adjust priorities accordingly return tuplefvalue f value zipstr int int str matchnamegroup name names print name namessortkeykey print name names print name to explain keyextracting process know keys certain pattern a regular expression works great r qdsubwcolumnwnumbd digits letters letters digits group group group group in regular expressions parts string wrapped parens groups represents decimal digit means one previous character so means one decimal digits w corresponds letter provided string matches pattern could get easy access grouping string using group method you could access multiple groups including group numbers eg match qsubbcolumncnumb mgroup mgroup b mgroup c this similar ignacio approach lot strict pattern once wrap head around creating appropriate key sorting simple,i really complicated data files i processed file processed i used ordereddictionary capture keys values each ordereddictionary appended list final result list dictionaries because diversity data captured files many keys common enough uncommon keys make exporting data excel complicated i hoping i really need push data consistent structure each key structure like qsubacolumnnumb example i qsubdcolumncnumb we translate key follows question subitem d column c instance because subitem d column c instance must subitema column b instance however one source files might populated data values keys range example source file might terminate qsubdcolumncnumb i iterate list dictionaries pull unique key instances i use csvdictwriter column headings plan sort resulting list unique column headings i seem make sort work specifically i need sort results look like qsubacolumncnumb qsubbcolumncnumb qsubacolumncnumb qsubbcolumncnumb qsubccolumncnumb qsubdcolumncnumb dot dot dot qsubacolumncnumb qsubbcolumncnumb qsubccolumncnumb qsubdcolumncnumb the big issue i know i open particular set files many questions answered many subquestions answered many columns associated question subquestion many instances exist particular combination questions subquestions columns i want using python i able reduce lines sas code last little bit i start writing csv file i seem figure any observations would appreciated my plan find unique keys iterating list dictionaries sort keys correctly i create csv file using keys column headings i know i find unique keys push manually sort read sorted file back seems clumsy,1 class kindeditorformstextarea class media css settingsstaticroot editorthemesdefaultdefaultcss js settingsstaticroot editorkindeditorminjs settingsstaticroot editorlangzhcnjs def initself attrs attrs rel kind superkindeditor selfinitattrs class newsadminformformsmodelform pass class meta model news widgets body kindeditor class newsadminadminmodeladmin form newsadminform adminsiteregisternews newsadmin,i would like know best way replace standard textarea field rich text editor django admin,1 the problem trying solve well known researched find large amount research paper describing approaches algorithms google terms named entity extraction relationship extraction some good starting points chapter book natural language processing python fact entire book would probably helpful chapter online this paper named entity relation mining using wikipedia this paper dd novel algorithms relationship mining describes mining job titles organizations one examples these links i found interesting ton probably better ones get started,i extracting information certain companies reuters using python i able get officerexecutive names biographies compensation page now i want extract previous position titles companies biography section looks something like mr donald t grimes senior vice president chief financial officer treasurer wolverine world wide inc since may from executive vice president chief financial officer keystone automotive operations inc distributor automotive accessories equipment prior keystone mr grimes held series senior corporate divisional finance roles brownforman corporation manufacturer marketer premium wines spirits during employment brownforman mr grimes vice president director beverage finance vice president director corporate planning analysis senior vice president chief financial officer brownforman spirits america i use simple regex get years i loss write regex get titles company name well i know string format inconsistent i would take answer works least cases here output i would like executive vice president chief financial officer keystone automotive operations,1 i error stdlib sources found my fix install xcode retry eclipse pydev auto config method no error pydev running ok,i trying use eclipse python editor i install latest version pydev try set interpreter python field preferences mac my python version path usrbinpython when i enter i select items add system pythonpath i get following error message error python stdlib found it seems python lib folder contains standard library found selected instal process this folder contains files threadingpy tracebackpy required pydev function properly must contain actual source files pyc files so i tell eclipse interpreter path any help would great i tried reinstalling pydev already luck thanks following praveen answer my python library librarypythonsitepackages when i enter usrbinpython interpreter field eclipse asks paths i would like add system pythonpath one checkbox items exactly path so i check along boxes click ok i get error,2 sounds like want pandas group aggregate,i r code i need port python however r magic dataframe ddply keeping finding good way python sample data r x dataframedcccrepc b c v sample computation ddplyx transform vvminvmaxvminv sample output c v v b c b c so question pythonistas would you data structure couple important dimensions for c eachd compute vminvmaxvminv associate corresponding dc pair feel free use whatever data structures want long quick reasonably large datasets fit memory,2 you define property available object assign note i change code convenience sqlalchemyextdeclarative import declarativebase sqlalchemy import column integer datetime string datetime import datetime base declarativebase class userbase firstname column firstname string middlename column middlename string lastname column lastname string def getname self firstname selffirstname selffirstname none else middlename selfmiddlename selfmiddlename none else lastname selflastname selflastname none else return joinfirstname middlename lastnamestrip def setname selfstring firstname middlename lastname splitstring stringsplit lensplitstring firstname string elif lensplitstring firstname lastname splitstring elif lensplitstring firstname middlename lastname splitstring else lensplitstring firstname splitstring lastname splitstring middlename joinsplitstring selffirstname firstname selfmiddlename middlename selflastname lastname name propertygetnamesetname so firstname middlename lastname class attributes when define property needs instance object in userfirstname out column firstname string in username out property object xfef in example see difference until set property fields property always empty you give in u user in uname first middle last in uname out first middle last in ufirstname out first after use property this help understand problem your property associated instance cant access class,i class sys import stderr elixir import types import class userentity usingoptionstablenameusers firstname fieldstring middlename fieldstring lastname fieldstring def getname self firstname selffirstname selffirstname none else middlename selfmiddlename selfmiddlename none else lastname selflastname selflastname none else return joinfirstname middlename lastnamestrip def setname selfstring firstname middlename lastname splitstring stringsplit lensplitstring firstname string elif lensplitstring firstname lastname splitstring elif lensplitstring firstname middlename lastname splitstring else lensplitstring firstname splitstring lastname splitstring middlename joinsplitstring selffirstname firstname selfmiddlename middlename selflastname lastname name propertygetnamesetname i like run query follows def getuseruser found none typeuser inttypestringtype typeuser stringtype oruserfirstnameuser usermiddlenameuser userlastnameuser usernameuser qry userqueryfilterwhere elif typeuser inttype oruseriduser useremployeeiduser qry userqueryfilterwhere try found qryone except noresultfound print stderr couldn find user elif typeuser user founduser return found however resultant sql query looks something like following select usersfirstname as usersfirstname usersmiddlename as usersmiddlename userslastname as userslastname from users where usersfirstname joseph or usersmiddlename m or userslastname schmoe or false notice false place username field i getting error sqlalchemyexcoperationalerror operationalerror column false i think i like sql query look like following select usersname from users where usersname joseph m schmoe edit the desiredsecond sql query incorrect i really wanted sort passive way create name field within database corresponds concatenate firstname middlename lastname edit i believe following get almost however i still struggling proper expression edit looks like works i need so i including answer,1 amain nothing namemain block the former calls function named main module latter executes block current module name main ie module called script usrbinenv python apy def func print reprname namemain print script func compare module executed script function called imported module python apy script main python c import print via import afunc via import see section modules python tutorial to get output subprocess could use subprocesscheckoutput function import sys subprocess import checkoutput qx args output qxsysexecutable barpy args print output,i script apy usrbinenv python def fooarg arg return intarg intarg name main import sys print foosysargv sysargv i want make script run first script write output apy file arguments well i want make automateoutputsrcarglist generate kind output i write outfile import sys def automateoutputsrc arglist return def printtofile src outfile arglist print printing file outfile openoutfile w opensrc r line outwriteline sclose outwrite n run time example n outwriteautomatesrc arglist outwrite n outclose try src sysargv outfile sysargv arglist sysargv automatesrc arglist printtofilesrcoutfilearglist except print error print usage python automateruntimepy scriptname outfile args i tried searching around far i understand pass arguments using ossystem arguments i also tried import amain there i get nameerror name main defined update i researched found subprocess i quite close cracking seems the following code work i would like pass args instead manually passing src barpy args proc subprocesspopen python src stdoutsubprocesspipe stderrsubprocessstdout print proccommunicate,1 this function statement name main if want main function define one import sys def main print foosysargv sysargv then call need name main main,i script apy usrbinenv python def fooarg arg return intarg intarg name main import sys print foosysargv sysargv i want make script run first script write output apy file arguments well i want make automateoutputsrcarglist generate kind output i write outfile import sys def automateoutputsrc arglist return def printtofile src outfile arglist print printing file outfile openoutfile w opensrc r line outwriteline sclose outwrite n run time example n outwriteautomatesrc arglist outwrite n outclose try src sysargv outfile sysargv arglist sysargv automatesrc arglist printtofilesrcoutfilearglist except print error print usage python automateruntimepy scriptname outfile args i tried searching around far i understand pass arguments using ossystem arguments i also tried import amain there i get nameerror name main defined update i researched found subprocess i quite close cracking seems the following code work i would like pass args instead manually passing src barpy args proc subprocesspopen python src stdoutsubprocesspipe stderrsubprocessstdout print proccommunicate,1 you need use cvloadimagem instead cvloadimage in import cv in import numpy np in x cvloadimagem imtif in im npasarrayx in imshape out,i rgb image i want convert numpy array i following im cvloadimageabctiff numpyasarrayim creates array shape i assume iplimage object how thanks,3 there different ways pass data views actually much different problem passing data different scripts amp course concepts interprocess communication come well some things come mind get request first request hits viewsend data browser browser redirects view post request suggested same flow suitable data involved django session variables this simplest implement clientside cookies can used limitations much data stored shared memory web server level tricky done rest api if standalone server server rest api invoke views message queues again standalone server possible maybe even message queues would work ie first view api takes requests pushes queue process pop messages hit second view another api this would decouple first second view api possibly manage load better cache maybe cache like memcached act mediator but one going route better use django sessions hides whole lot implementation details scale concern memcached redis good options persistent storage store data persistent storage mechanism like mysql this decouples request taking part probably client facing api processing part db middle nosql storages speed writes order hundreds thousands per sec mysql performance would become bottleneck ways get around tweaking mysql config easy then considering nosql db could alternative eg dynamodb redis hbase etc stream processing like storm aws kinesis could option usecase realtime computation in fact could use aws lambda middle serverless compute module would read call second view api write data file next view read file real ugly this probably never ever done putting point something done cant think will update get hope helps someway,i wondering best way passing data views is better create invisible fields pass using post i encode urls or bettereasier way sorry question stupid i pretty new web programming thanks,3 def opencvimageasarrayim interface image opencv native format numpy array note slicing trick modifying output array also change opencv image data want copy use copy method array import numpy np w h n imwidth imheight imchannels modes l rgb rgba n modes raise standarderror unsupported number channels formatn npasarrayim n else npasarrayim bgr rgb return,i rgb image i want convert numpy array i following im cvloadimageabctiff numpyasarrayim creates array shape i assume iplimage object how thanks,1 you use astliteraleval import ast astliteraleval,i string i like able convert tuple the built tuple function work purposes treats character individual item i want able convert programmatically,3 using csv library read data convert list lists append k relevant list write import csv data csvreaderopeninputcsv l listdata lappendk ourwriter csvwriteropenoutputcsv wb ourwriterwriterowsl while csv library completely necessary toy case often good use approach scales well,i csv file following contents abcd wxyz and want update csv file contents abcdk wxyz can someone please share python code update process,1 as provided full html page option right either using stringfind regular expressions but standard way finding using xpath see question use xpath python you obtain xpath element using inspect element feature firefox for ex want find xpath username stackoverflow site open firefox login website amp rightclick usernameshadyabhi case select inspect element keep mouse tag right click copy xpath,im making small python script auto logon website but stuck i looking print terminal small part html located within tag html file site td classh align right ampnbspampnbspjohn appleseedtdtdampnbspa hrefmembersmyaccountphpimg border srctbsvimagesmyaccountgif altmy accountatd but i extract print name john appleseed i using pythons mechanize mac way,1 exectuting module anything you make imports define globals define function if want see something printed must call function import random import time coin health pcname def displayintro print you wake bound cell wall shackles displayintro interpreter reaches line warm welcome printed,i recently got learning python i close idle save work when i come back open idle open saved work go test f run module module doesnt produce error codes doesnt even print simple print commands ever type new project quickly commands works fine previously saved work anyone ideas os windows home may help know i previously installed edit turns code run command python either code seems fine post import random import time coin health pcname def displayintro print you wake bound cell wall shackles,1 there two points make sure python buffer output try running python u openport using termtobinary binarytoterm work since assume python able encodedecode erlang external term format seem case if want go route check erlport,based chapter otp action book cesarini book i wrote erlang code erlang pparam dbgstartingn cmd python testpy port openportspawncmd streamline exitstatus dbgopened port wn port payload termtobinarylisttobinaryintegertolistparam erlangportcommandport payload dbgsent command port wn payload dbgready receive results command wn payload receive port data data dbgreceived data wn data result text binarytotermdata blah binarytolisttext ioformatpn blah other ioformatunexpected data pn other end python import sys def main true line sysstdinreadlinestrip line stopgood return elif line stopbad return sysstdoutwritepython got sysstdoutwriteline sysstdoutwriten sysstdoutflush name main sysexitmain the erlang code suspends recieve clause never gets message i also checked python regular linux shell prints every user input python got where mistake why erlang code get anything back,1 you use parser extract information document i suggest use lxml module here example lxml import etree stringio import stringio parser etreehtmlparser tree etreeparsestringiotd classh align right ampnbspampnbspjohn appleseedtdtdampnbspa hrefmembersmyaccountphpimg border srctbsvimagesmyaccountgif altmy accountatdparser treexpathstringstrip u john appleseed more information lxml,im making small python script auto logon website but stuck i looking print terminal small part html located within tag html file site td classh align right ampnbspampnbspjohn appleseedtdtdampnbspa hrefmembersmyaccountphpimg border srctbsvimagesmyaccountgif altmy accountatd but i extract print name john appleseed i using pythons mechanize mac way,1 what wrong nesting simple elif chain def ackm n return n elif return n elif return n elif return n elif n return ackm else return ackm ackm n python code readable programmer personal choice question if i pick one examples i go ack since backslashes indicate everything one big statement without bloating expression like bracket opinion,what think best way writing method calculating ackermann function value this function incorporates several short cuts simplest method calculating value speeds calculation considerably reducing amount recursive calls end long expression the versions use the line continuation character bracketed nested functions a single outer set braces does version seem better i curious def ackm n return n m else n m else n m else n m else ackm n else ackm ackm n def ackm n return n m else n m else n m else n m else ackm n else ackm ackm n def ackm n return n m else n m else n m else n m else ackm n else ackm ackm n ack ack ack true,2 don afraid multiple returns also try avoid capital letters local variables def ackm n return n return n return n return n n return ackm return ackm ackm n,what think best way writing method calculating ackermann function value this function incorporates several short cuts simplest method calculating value speeds calculation considerably reducing amount recursive calls end long expression the versions use the line continuation character bracketed nested functions a single outer set braces does version seem better i curious def ackm n return n m else n m else n m else n m else ackm n else ackm ackm n def ackm n return n m else n m else n m else n m else ackm n else ackm ackm n def ackm n return n m else n m else n m else n m else ackm n else ackm ackm n ack ack ack true,2 you need look accesscontrolrolemanagerpy module details sharing tab plone friendly wrapper around api to add roles given userid call manageaddlocalroles contextmanageaddlocalroles userid role role the two important methods managesetlocalrolesuserid roles replace current set roles completely managedellocalrolesuserid delete roles getlocalrolesforuseriduserid could handy see local roles already defined you want reindex security information changes contextreindexobjectsecurity,i want set sharing rights many folders using python script plone site,3 you keep references input output following bind method input called update validation method treatment needed end method update output directly using reference internal functions configure else there maybe better way using var classes i would,i trying write gui following structure relevant parts window vbox hbox frame input scrolledwindow treeview liststore output as soon input received list computed output how i send list liststore displayed do i need drag references parent element along every element or easier way,2 pyc files c extensions compatible python versions install pylauncher use python shebang scripts work libre office from link provided answer openofficeorg development pyuno windows—which python question terms let call version python installed openoffice oopython let call version python installed separately cpython example systempython you need know six things sucessfully import uno module systempython interpreter the oopython version number your systempython version number must oopython version number emphasis mine,i python installed windows i installed libre office comes python hence able import uno unohelper even setting environment variables i need python thus cannot revert back python earlier python working open office i recently changed libreoffice python activepython is way make python import uno unohelper libreoffice thanks advance,1 just factor testing function call three tests class testfoounittesttestcase def dotestself foo foodosomething def testfoorhorseself foo foohorsefoo selfdotestfoo i try anything clever test logic stays simple enought obviously bugfree,i trouble figuring proper way using pythons unittest framework i currently different implementations data structure class unittests test various things class follows import foohorse import foosnake import foomoose import unittest foo foohorsefoo foo foosnakefoo foo foomoosefoo class testfoounittesttestcase def testsomethingself foodosomething def testsomethingelseself etc name main unittestmain how i refactor code tests run foosnakefoo foomoosefoo foohorsefoo,1 use read readsome function istream eg stdvectorchar buffer myfilereadampbuffer stdcopybufferbegin bufferend stdostreamiteratorintstdcout,i currently trying make analog python function def readtwosymbolsfdescr returnfileread myfile open mytexttxt rb twosymbols readtwosymbolsmyfile printtwosymbols is way c that i tried include iostream include string include fstream using namespace std string readtwobytesfstream file string byte byte byte fileget byte fileget string twobytes byte byte return twobytes int main fstream myfilemytexttxt iosbasein iosbasebinary string twobytes readtwobytesmyfile cout twobytes endl return however fails how i using c,1 change function definition notice amp sign string readtwobytesfstream amp file,i currently trying make analog python function def readtwosymbolsfdescr returnfileread myfile open mytexttxt rb twosymbols readtwosymbolsmyfile printtwosymbols is way c that i tried include iostream include string include fstream using namespace std string readtwobytesfstream file string byte byte byte fileget byte fileget string twobytes byte byte return twobytes int main fstream myfilemytexttxt iosbasein iosbasebinary string twobytes readtwobytesmyfile cout twobytes endl return however fails how i using c,1 mechanize good fetching html once want extract information html could use example beautifulsoup see also answer similar question web mining scraping crawling what toollibrary i use depending td located html unclear question could use following code html html fetched beautifulsoup import beautifulsoup soup beautifulsouphtml use gets td elements cols soupfindall td gets td elements class h cols soupfindall td attrsclass h print colsrendercontents print content first td element,im making small python script auto logon website but stuck i looking print terminal small part html located within tag html file site td classh align right ampnbspampnbspjohn appleseedtdtdampnbspa hrefmembersmyaccountphpimg border srctbsvimagesmyaccountgif altmy accountatd but i extract print name john appleseed i using pythons mechanize mac way,3 vivek pointed pass fstream value passing things value makes copies rather runs copy constructor may may actually make deep copy once fix iostream actually cute cuddly they detect type asking read amount data if char use stream operators read byte worth string readtwobytesfstreamamp file char byte byte file byte byte string twobytes twobytes byte twobytes byte return twobytes nim seems trying give generalized answer perhaps show c vs python it answering question nbytes except hardcoded looks like overkill it done easier nice know flexiblity thereno if new c io might find answer question i bothered write day interesting contrast methods suggested answers output error input isnt number c,i currently trying make analog python function def readtwosymbolsfdescr returnfileread myfile open mytexttxt rb twosymbols readtwosymbolsmyfile printtwosymbols is way c that i tried include iostream include string include fstream using namespace std string readtwobytesfstream file string byte byte byte fileget byte fileget string twobytes byte byte return twobytes int main fstream myfilemytexttxt iosbasein iosbasebinary string twobytes readtwobytesmyfile cout twobytes endl return however fails how i using c,1 you need itertoolsproduct itertools import product vals productlistadictvalues vals l l ln tuple,ok dynamic i mean unknown runtime dict adict adict adictnxy i know many n i want loop follows l adict l adict ln adictn stuff l l ln combination any suggestions i relatively new python please gentle although i program php btw i using python,3 did remember import request not sure using looks like flask flask import request,basically i want return contents createuser register function use save database i complete beginner what i misunderstanding def register form signupformrequestform requestmethod post formvalidate createuser username formusernamedata email formemaildata password formpassworddata flash thanks registering return createuser redirecturlfor loggedinhtml return rendertemplate getstartedhtml formform createuser register docid docrev dbsavecreateuser,1 you use lxml parse html extract json import lxmletreejson htmlbodyscript typetextjavascript myjsonobject name steve city new york scriptbodyhtml js lxmletreehtmlsfind bodyscript text jsoncode jspartition strip jsonloadsjsoncode u city u new york u name u steve,i need parse html document contains javascript code json object something like html head head body script typetextjavascript myjsonobject name steve city new york script phello worldp body html how i extract myjsonobject value python,2 python nltk perfect tools sort wordlist nltk comes corpora english language extract frequency information the following code print given wordlist order word frequency brown corpus import nltk nltkcorpus import brown wordlist corpushousethepeterasdf collect frequency information brown corpus might take seconds freqs nltkfreqdistwlower w brownwords sort wordlist word frequency wordlistsorted sortedwordlist keylambda x freqsxlower reversetrue print sorted list w wordlistsorted print w output house peter corpus asdf if want use different corpus get information look chapter nltk book,i list english words approx i like sort usage occur literature newspaper blogs etc can i sort python language i heard nltk closest library i know could help or task tool thank,3 first need convert real lists l split then use sets intersection result setl amp setl amp setl,ok another python question i dict adict adict adictn n could limit keys sequence how i extract intersect csv items so case answer would thanks,2 functools import reduce python reducelambda x xintersectiony setxsplit x adictvalues,ok another python question i dict adict adict adictn n could limit keys sequence how i extract intersect csv items so case answer would thanks,2 python set ideal task consider following pseudo code intersections none value adictvalues temp setintnum num valuesplit intersections none intersections temp else intersections intersectionsintersectiontemp print intersections,ok another python question i dict adict adict adictn n could limit keys sequence how i extract intersect csv items so case answer would thanks,1 the exec function return last line result command the print statement python except python automatically adds newline end this reason feel nothing happened you catch whole output way execusrlocalpythonbinpython myfilepy amp output printroutput,i trying call simple python script usrlocalpythonbinpython print hello world following php script php echo execusrlocalpythonbinpython myfilepy but nothing happened please tell wrong i also checked thread i could solve problem question solved i forgot give permission access usrlocalpythonbinpython after i problem solved thank much help,1 you might need little careful assumption code actually used multithreaded blas calls relatively numpy operators actually use underlying blas relatively blas calls actually multithreaded numpydot uses either blas dot gemv gemm depending operation gemm usually multithreaded rarely performance benefit on on blas calls if limiting level level blas operations i doubt actually using multithreaded blas calls even using numpy implementation built mulithreaded blas like atlas mkl,suppose i core machine embarrassingly parallel program i use lots numpy dot products addition numpy arrays i use multiprocessing would nobrainer make sure numpy built version blas uses multithreading however i using multiprocessing cores working hard times in case benefit using multithreading blas most operations blas type type,3 your code looks good however i see check login successful response mechsubmit look content response make sure login successful are sure site works without javascript there could hidden field set javascript,trying mechanize scrape content https asp site looks login page submission works i get returned but i try open url presumably using cookie captured login i get redirected back login page error session expired the last print i see i get redirected import mechanize useragent mozilla x u linux trtr rv gecko pardus firefox mech mechanizebrowser mechaddheaders useragent useragent mechopenhttpswwwexamplecomloginasp mechselectformloginform mech id blah mech pin blah response mechsubmit truecontent mechopenhttpswwwexamplecomcontent print truecontentgeturl,1 kind obvious point run python script terminal does actually run make sure script executable whatever user php running chmod myfilepy safe chmod usrlocalpythonbinpython also make sure python script directory php script method calling requires try changing php script tell see edited php path python script either full path relative php script pythonscript myfilepy path python executable either full path relative php script pythonexec usrlocalpythonbinpython check file exists php permission execute clearstatcache fileexistspythonexec exitthe python executable pythonexec exist isexecutablepythonexec exitthe python executable pythonexec executable fileexistspythonscript exitthe python script file pythonscript exist execute redirect stderr stdout see error messages well execpythonexec pythonscript amp output show output script printroutput,i trying call simple python script usrlocalpythonbinpython print hello world following php script php echo execusrlocalpythonbinpython myfilepy but nothing happened please tell wrong i also checked thread i could solve problem question solved i forgot give permission access usrlocalpythonbinpython after i problem solved thank much help,1 same idea drtyrsa making sure order right itertools import product vals product adicti sortedadictkeys print vals,ok dynamic i mean unknown runtime dict adict adict adictnxy i know many n i want loop follows l adict l adict ln adictn stuff l l ln combination any suggestions i relatively new python please gentle although i program php btw i using python,3 if appear anywhere column e if must appear start column example estartswith alternatively column always contains colonseparated values esplit the last one strictest three would personal preference,i file like chr t c dpafcidpmqfq gtplgq chr g t dpafcidpmqfqpve gtplgq chr a c dpafcidpmqfq gtplgq chr g c dpafcidpmqfqpve gtplgq chr c t dpafcidpmqfqpve gtplgq i would like make loop finds lines th column this script i wrote pilup open libarytssortedpilup rb open selecttxt wb ch data ch edatasplit e i know wrong since e means column exact see sample data i put i always somthing like i wanted know i use make statement work properly is symbol says contain i couldn’t find anywhere thanks advance,3 first open selecttxt wb delete file contents i assume iterating pilup you use operator test whether occurs anywhere tenth element e alternatively use startswith check whether tenth element well starts estartswith,i file like chr t c dpafcidpmqfq gtplgq chr g t dpafcidpmqfqpve gtplgq chr a c dpafcidpmqfq gtplgq chr g c dpafcidpmqfqpve gtplgq chr c t dpafcidpmqfqpve gtplgq i would like make loop finds lines th column this script i wrote pilup open libarytssortedpilup rb open selecttxt wb ch data ch edatasplit e i know wrong since e means column exact see sample data i put i always somthing like i wanted know i use make statement work properly is symbol says contain i couldn’t find anywhere thanks advance,1 i believe efficient quick way accomplish separate server process receives text replies results posttag function whatever function want,i using natural language toolkit python useful function called postag you run nltkpostag list words tokenized sentence return list tuples word sentence part speech pos well thats great i need run every time runs ajax call website unfortunately function lot initial overhead takes seconds everything needs work once i call nltkpostag run fast but each time i make ajax call load function so i wondering way make persist i load every time someone comes page updates ajax call i tried pickling work i looked shelve seems like similar pickle hope someone help thanks,1 just use one lock without expiration create periodic investigator task checks whether everything ok another task died unexpectedly fixes lock issue as plus take look,i already read respective article celery docs cookbook creating tasks however i completely like solution suggested i long running tasks minutes hour possibly even thus choosing lockexpire setting seem reliable turns small i get two tasks running simultaneously big celery process dies reason i need manually delete locking cache key the idea comes mind i could use two different locks one created fcntllockf different celery worker processes another one threadinglock task gets executed celery process however two locks seems somewhat excessive so question would simplest solution problem it crossplatform support linux,1 terminating program makes sockets automatically close however tcp ports still kept use the unix socket faq really long explanation section for testing purposes may best ask arbitrary port ask successive ones like output port console,i learning use sockets python quite often program crashes i ctrlc server socket somehow stays listening port this obviously stops program listening port starts back i keep changing i guessing i need socketclose somewhere,1 you could try atexit module import atexit function closesocket sclose atexitregisterclosesocket if issue delays port becoming available testing i would suggest setting soreuseaddr allow port bound immediately instead waiting timeouts tcp stack ssetsockoptsocketsolsocket socketsoreuseaddr,i learning use sockets python quite often program crashes i ctrlc server socket somehow stays listening port this obviously stops program listening port starts back i keep changing i guessing i need socketclose somewhere,3 random import sample mylist anthony kris james vinny joe samplemylist kris vinny,import random mylist anthony kris james vinny joe randomlist randomrandrangelenmylist randomlist randomrandrangelenmylist name mylistrandomlist name mylistrandomlist print the group consist name name is code question person trying print two random names mylist course current code occasionally print two the solution given may use answering i tried things help i python expert i think straight moment,1 use randomsample import random mylist anthony kris james vinny joe randomsamplemylist james vinny,import random mylist anthony kris james vinny joe randomlist randomrandrangelenmylist randomlist randomrandrangelenmylist name mylistrandomlist name mylistrandomlist print the group consist name name is code question person trying print two random names mylist course current code occasionally print two the solution given may use answering i tried things help i python expert i think straight moment,3 you use randomsample setting k randomsamplepopulation k chooses k unique random elements population sequence,import random mylist anthony kris james vinny joe randomlist randomrandrangelenmylist randomlist randomrandrangelenmylist name mylistrandomlist name mylistrandomlist print the group consist name name is code question person trying print two random names mylist course current code occasionally print two the solution given may use answering i tried things help i python expert i think straight moment,1 it probably combination using relative path file permissions try changing line f openproxytxta absolute path eg f opencusersfoodesktopproxytxta make sure effective user running cgi script permission write absolute path choose,i using cgi python proxy solve crossdomain issue ajax request want log key info request url save info file server i i tried python logging module file io module neither seems work environment cpythonpythonexe u import urllib import cgi import sys os f openproxytxta method osenvironrequestmethod fwritemethod n method post qs osenvironquerystring cgiparseqsqs dhaskeyurl url durl else fs cgifieldstorage url fsgetvalue url try urlliburlopenurl fwriteurl n fclose except exception e print status unexpected error print contenttype textplain print print some unexpected error occurred error text e proxytxt file still blank request clientend,1 you could use regular expression rematchr dd this returns match object input correct none the regex matches one digits optionally followed dot exactly two digits this tweaked required i capture requirements precisely problem statement somewhat open interpretation,what best way validate input currency without currency symbols my valid inputs form,1 don name things keywords even find work around probably end biting later use synonym add prefixsuffix instead eg start finish begin end datefrom dateto,i got simple form django looks something like class searchformformsform text formscharfield formsdatefield formsdatefield which fails syntaxerror python keyword i rather change name field it fits better alternatives i fussy appears end user the form using get field name visible url i realize i could use something like instead i initially thought might way explicitly provide field name cases like eg by supplying name whatever parameter field constructor it turn at moment i using dynamic form generation get around issue bad still bit hack class searchformformsform text formscharfield formsdatefield formsdatefield def initself args kwargs supersearchform selfinitargs kwargs selffields selffields del selffields is elegant way form field named python keyword,2 how simply using format tryexcept wrong values fformatfloat fformatfloat fformatfloat try fformatfloat€ except valueerror fail fail note simply cuts number behind second number behind decimal point you specific showing us examples desired behaviour,what best way validate input currency without currency symbols my valid inputs form,2 indeed pandas right i believe tool python it bit less magical plyr using groupby functionality df dataframe c nptile b c v nparange ipython in df out c v b c b c now write small transform function def fgroup v group v group v v vmin vmax vmin return group note also handles nas since v variable pandas series object now group column apply f in dfgroupby applyf out c v v b c b c,i r code i need port python however r magic dataframe ddply keeping finding good way python sample data r x dataframedcccrepc b c v sample computation ddplyx transform vvminvmaxvminv sample output c v v b c b c so question pythonistas would you data structure couple important dimensions for c eachd compute vminvmaxvminv associate corresponding dc pair feel free use whatever data structures want long quick reasonably large datasets fit memory,3 python many languages treat numbers starting octal notation valid octal see chapter python language reference,i noticed padding allowed python i wondering choice made for example work how thank much answers,3 it numbers starting octal numbers octal figures go doing perfectly accepted octal lead contain,i noticed padding allowed python i wondering choice made for example work how thank much answers,1 to expand nos said file stdin line syntaxerror invalid token so octal decimal octal knows digits so possible,i noticed padding allowed python i wondering choice made for example work how thank much answers,2 to even pedantic python doc consistent answer would mypath ospathjoin c ossep sourcedir since also need ossep posix root path mypath ospathjoinossep usr lib,i trying learn python making program output script i want use ospathjoin pretty confused according docs i say ospathjoin c sourcedir i get csourcedir according docs normal right but i use copytree command python output desired way example import shutil src ospathjoin c src dst ospathjoin c dst shutilcopytreesrc dst here error code i get windowserror error the system cannot find path specified csrc if i wrap ospathjoin ospathnormpath i get error if ospathjoin used way i confused purpose according pages suggested stack overflow slashes used joinmdashthat correct i assume,3 when using shortcut syntax dbtableid id refers record id dbtable actually refer existing record used insert new record also gae record ids start get incremented first inserted record id you either textobj dbdbfilesselectfirst textobjid dbfilesinserthashname namename pathname textobj dbfilestextobjid finally deploying gae make sure run app locally using gae sdk appserver order properly generate indexyaml file discussed,i started using webpy google appengine app mine for reason i unable saveretrieve data using dal here code i using at end dbpy aeoid import middleware aeoid import users import json dbdefinetable files dbfield name text dbfield path text dbfield version text defaultlive dbfield hash text dbfield data text dbfield meta text defaultjsondumps date strrequestnow dbfield contributors text defaultjsondumpsusersgetcurrentuser dbfield lasttime datetime defaultrequestnow in controller name test dbfiles dicthashname namename pathname textobj dbfiles textobj none print fail internal server error here textobj always none reason what i wrong edit i using appengine sdk python windows,1 match matches beginning string use search finditer findall also note greedy you might want change regex r hspanspan in summary following works import import urllib p urlliburlopenhttpsprungeusqzhu page pread pos pagefindhspan print pagepospos c recompiler hspanspan print csearchpagegroup,import import urllib p urlliburlopenhttpsprungeusqzhu page pread pos pagefindhspan print pagepospos c recompiler hspanspan print cmatchpagegroup when i run shadyabhiarchlinux python temppy hspanhousesehdtvxvidlolavispan traceback recent call last file temppy line module print cmatchpagegroup attributeerror nonetype object attribute group shadyabhiarchlinux if i find string using stringfind problem i use regex i tried looking httpdocspythonorghowtoregexhtmlregexhowto help,3 try js data items id it would appear may multiple items structure if like extract item ids list following item id item js data items,trouble simple question apiversion data startindex items id yvauozmzu title trailer lisbela eo prisioneiro know get info id string tried make import simplejson json typejs type dict js jsonloadsa print js data items id syntax error syntax invalid could i get info supposed easy i making wrong,3 simple answer use pandas in df readcsv foocsv indexcolnone in df out var var var in dfdf var isin out var var var in df var df var in df out var var var var in dft out var var var var in dftocsv foocsv in cat foocsv indexvarvarvarvar,i working r several years r strong data manipulation i learning python i would like know manipulate data using python basically data sets organized data frames eg excel sheet i would like know example kind basic data manipulation task done using python read csv file like following var var var subset data var make new variable var var transpose data write csv file your help example appreciated,3 note tornadoioloopperiodiccallback takes cycle time integer ms httprequest object configured connecttimeout andor requesttimeout float seconds see doc users browsing internet feel responses instant delays less ms click response wikipedia see serverfault question normal latency values ioerror stream closed validly raised inform connection timed without completing accurately called callback manually pipe open yet this good since abnormal latency ms expect fetches complete reliably raise value once got timeout set something sane consider wrapping fetches tryexcept retry loop normal exception expect occur production just careful set retry limit since using async framework let handle async callback instead running said callback fixed interval epollkqueue efficient supported framework import ioloop def handlerequestresponse responseerror print error responseerror else print responsebody ioloopioloopinstancestop httpclient httpclientasynchttpclient httpclientfetchhttpwwwgooglecom handlerequest ioloopioloopinstancestart copied verbatim doc if go route gotcha code request queue maximum open connections enforced otherwise likely end race condition serious scraping it yr since i touched tornado please let know inaccuracies response i revise,i using tornadohttpclientasynchttpclientfetch fetch domains list when i put domains fetch big interval example works good i decrease inerval next exception occurs time time traceback recent call last file homecrchemistpythonlibpythonsitepackagestornadosimplehttpclientpy line cleanup yield file homecrchemistpythonlibpythonsitepackagestornadostackcontextpy line wrapped callbackargs kwargs file homecrchemistpythonlibpythonsitepackagestornadosimplehttpclientpy line onchunklength selfonchunkdata file homecrchemistpythonlibpythonsitepackagestornadoiostreampy line readbytes selfcheckclosed file homecrchemistpythonlibpythonsitepackagestornadoiostreampy line checkclosed raise ioerrorstream closed ioerror stream closed what reason behavior code looks like def fetchdomaindomain httpclient asynchttpclient request httprequest http domain useragentcrawleruseragent httpclientfetchrequest handledomain class domainfetcherobject def initself domainsiterator selfdomains domainsiterator def callself try domain nextselfdomains except stopiteration domaingeneratorstop ioloopioloopinstancestop else fetchdomaindomain domaingenerator ioloopperiodiccallbackdomainfetcherdomains domaingeneratorstart,1 the latter equivalent normalizedscores u l linkscoresitems normalizedscoresu floatl maxscore,while working awesome book programming collective intelligence toby segaran i encountered techniques index assignments i entirely familiar take example createkey joinsortedstrwi wi wordids normalizedscores dictufloatlmaxscore ul linkscoresitems all nested tuples indexes bit confused what actually assigned varibles i assumed obviously join one comes string latter if someone could explain mechanics loops i really appreciate i assume pretty common techniques new python i suppose ask moment shame thanks,1 ufloatmaxscore ul linkscoresitems this creates list iterating tuples linkscoresitems computing u floatlmaxscore tuple dictthis list creates dict entries result list comprehension u floatlmaxscore item linkscores as another example creating dict list tuples l dictl,while working awesome book programming collective intelligence toby segaran i encountered techniques index assignments i entirely familiar take example createkey joinsortedstrwi wi wordids normalizedscores dictufloatlmaxscore ul linkscoresitems all nested tuples indexes bit confused what actually assigned varibles i assumed obviously join one comes string latter if someone could explain mechanics loops i really appreciate i assume pretty common techniques new python i suppose ask moment shame thanks,1 let take first one strwi wi wordids takes element wordids converts string sorted sorts lexicographically join merges sorted word ids single string underscores entries now second one normalizedscores dictufloatmaxscore ul linkscoresitems linkscores dictionary dictionarylike object ul linkscoresitems iterates entries dictionary entry assigning key value u l ufloatmaxscore tuple first element u second element maxscore looks like might typo floatlmaxscore would make sense note lowercase letter el place one dict constructs dictionary list tuples first element tuple taken key second taken value in short makes copy dictionary preserving keys dividing value maxscore,while working awesome book programming collective intelligence toby segaran i encountered techniques index assignments i entirely familiar take example createkey joinsortedstrwi wi wordids normalizedscores dictufloatlmaxscore ul linkscoresitems all nested tuples indexes bit confused what actually assigned varibles i assumed obviously join one comes string latter if someone could explain mechanics loops i really appreciate i assume pretty common techniques new python i suppose ask moment shame thanks,2 strwi wi wordids list comprehension strwi wi wordids wi wordids aappendstrwi so createkey joinsortedstrwi wi wordids creates list strings item wordids sorts list joins big string using separator as agf rightly noted also use generator expression looks like list comprehension parentheses instead brackets this avoids construction list need later except iterating and already parentheses like case sorted simply remove brackets however special case getting performance benefit fact slower i timed sorted need build list anyway looks bit nicer createkey joinsortedstrwi wi wordids normalizedscores dictufloatlmaxscore ul linkscoresitems iterates items dictionary linkscores item keyvalue pair it creates list key lmaxscore tuples turns list back dictionary however since python could also use dict comprehensions normalizedscores ufloatlmaxscore ul linkscoresitems here timing data python import timeit timeittimeitstmta joinsortedstrx x n setupimport random n randomrandint range timeittimeitstmta joinsortedstrx x n setupimport random n randomrandint range python import timeit timeittimeitstmta joinsortedstrx x n setupimport random n randomrandint range timeittimeitstmta joinsortedstrx x n setupimport random n randomrandint range,while working awesome book programming collective intelligence toby segaran i encountered techniques index assignments i entirely familiar take example createkey joinsortedstrwi wi wordids normalizedscores dictufloatlmaxscore ul linkscoresitems all nested tuples indexes bit confused what actually assigned varibles i assumed obviously join one comes string latter if someone could explain mechanics loops i really appreciate i assume pretty common techniques new python i suppose ask moment shame thanks,3 here example firstexample wordids createkey joinsortedstrwi wi wordids print createkey what iterating list loop sorting list joins sorted values string separating values,while working awesome book programming collective intelligence toby segaran i encountered techniques index assignments i entirely familiar take example createkey joinsortedstrwi wi wordids normalizedscores dictufloatlmaxscore ul linkscoresitems all nested tuples indexes bit confused what actually assigned varibles i assumed obviously join one comes string latter if someone could explain mechanics loops i really appreciate i assume pretty common techniques new python i suppose ask moment shame thanks,1 the weirdlooking business happening inside brackets called list comprehension basically really concise way building list mylist strwi wi wordids equivalent mylist wi wordids mylistappendstrwi sorted sorts list join gives string list items separated underscores like itemitemitem the second assignment complicatedconcise going linkscores looks like dictionary items method returns list key value tuples dictionary so ul linkscoresitems looping list for tuples create new tuple containing u floatlmaxscore add list so step basically changes item value list list item normalized value tuples the dict function turns back dictionary the overall result take values dict normalize there may easiermore verbose way way benefit looking cool i prefer crazy stuff list comprehensions hurts readability feel bad feel like writing kind thing,while working awesome book programming collective intelligence toby segaran i encountered techniques index assignments i entirely familiar take example createkey joinsortedstrwi wi wordids normalizedscores dictufloatlmaxscore ul linkscoresitems all nested tuples indexes bit confused what actually assigned varibles i assumed obviously join one comes string latter if someone could explain mechanics loops i really appreciate i assume pretty common techniques new python i suppose ask moment shame thanks,1 using syntax escapes included text default help defend xss injection attacks instead use structure prefix tell rendering engine escape text divstructure bodydiv,i started project python web framwork pyramid using template engine chameleon i beginner frameworks i use customer i follow steps order install framework i started coding training purpose my first application stupid simple crud application what i initpy i view following code configaddview myenglishdictionaryviewsmodify routename modifyroute renderer templatesbasept basept main template header footer div following code divbodydiv file viewpy view lines like following body render templateslistpt list list project myproject requestrequest return body body listpt content embedded basept all seemed work good but update libraries i see template correctly instead actual html code html entities ampltdiv classclearampgtampltdivampgt obviously page look well the problems seems render method since html basept template displayed correctly,3 pil python imaging library numpy work well together i use following functions import image import numpy np def loadimage infilename img imageopen infilename imgload data npasarray img dtypeint return data def saveimage npdata outfilename img imagefromarray npasarray npclipnpdata dtypeuint l imgsave outfilename the imagefromarray little ugly i clip incoming data convert bytes create grayscale image i mostly work gray an rgb image would something like outimg imagefromarray yccuint rgb outimgsave ycctif,i rgb image i want convert numpy array i following im cvloadimageabctiff numpyasarrayim creates array shape i assume iplimage object how thanks,3 you actually adding new axes matplotlib detecting already plot position returning instead new axes object check ax newax object there probably reason want also call newax pltaxes call figaddsubplotnewax you thing twice edit with newer i think versions matplotlib accomplish thing example using label kwarg figaddsubplot eg newax figaddsubplot label unique string import matplotlibpyplot plt fig pltfigure ax figaddsubplot if call pltaxes equivalently figaddsubplot matplotlib return ax it create new axis unless call figaddaxes reset figseen newax figaddaxesaxgetposition frameonfalse axplotrange r newaxplotrange g newaxaxis equal pltshow of course looks awful asking i guessing earlier questions want add second xaxis if completely different thing if want yaxes linked something like somewhat verbose import matplotlibpyplot plt fig ax pltsubplots newax axtwiny make room bottom figsubplotsadjustbottom i guessing want bottom newaxsetframeontrue newaxpatchsetvisiblefalse newaxxaxissetticksposition bottom newaxxaxissetlabelposition bottom newaxspines bottom setposition outward axplotrange r newaxplotrange g axsetxlabel red thing newaxsetxlabel green thing pltshow if want hidden unlinked yaxis entirely new xaxis something like import matplotlibpyplot plt import numpy np fig ax pltsubplots figsubplotsadjustbottom newax figaddaxesaxgetposition newaxpatchsetvisiblefalse newaxyaxissetvisiblefalse spinename spine newaxspinesiteritems spinename bottom spinesetvisiblefalse newaxspines bottom setposition outward axplotrange r x nplinspace nppi newaxplotx npcosx g pltshow note yaxis values anything plotted newax never shown if wanted could even take one step independent x axes i quite sure point would looks neat import matplotlibpyplot plt import numpy np fig ax pltsubplots figsubplotsadjustbottom right newax figaddaxesaxgetposition newaxpatchsetvisiblefalse newaxyaxissetlabelposition right newaxyaxissetticksposition right newaxspines bottom setposition outward axplotrange r axsetxlabel red xaxis color red axsetylabel red yaxis color red x nplinspace nppi newaxplotx npcosx g newaxsetxlabel green xaxis color green newaxsetylabel green yaxis color green pltshow you also add extra spine bottom plot sometimes easier especially want ticks numerical things along not plug one answers much example how i plot multiple x y axes matplotlib as one last thing sure look parasite axes examples want different x axes linked specific transformation,define data x nplinspacenppi npsinx plot fig pltfigure ax pltaxes figaddsubplotax axplotxy add second axis newax pltaxesaxisbg none gives valueerror unknown element even though thing i describe i also see works error thing newax pltaxes figaddsubplotnewax newaxsetaxisbgcolor none however turns background color original figure gray whatever figure background i understand i thought would make newax transparent except axes box around figure even i switch order thing pltclose fig pltfigure newax pltaxes figaddsubplotnewax newaxsetaxisbgcolor none ax pltaxes figaddsubplotax axplotxy this surprising i thought background one would overlaid either case newax background appears visible least color i see what going,3 is looking accomplish open datatxt moder datafile fieldnames character string value value reader csvdictreaderdatafile fieldnamesfieldnames delimitert completedict row reader chardict completedictsetdefaultrow character valueslist chardictsetdefaultrow string values introw value floatrow value valueslistappendvalues pprintpprintcompletedict note example value want value also appears include single quotes around strings part string may need clean,i trying read data create nested dictionary dictionaries there similar question i seem figure adapt solution particular problem i would grateful someone could explain solution problem basically i file looks like a abc b tex b tex e yet a abc i need create complex dictionary looks like completedict a abc b tex e yet i create inner dictionary i figure create outer dictionary here code inner dictionary open datatxt moder datafile fieldnames character string value value reader csvdictreaderdatafile fieldnamesfieldnames delimitert innerdict row reader values introw value floatrow value string row string string innerdict innerdictstringappendvalues else innerdictstring values could someone explain create outer dictionary the idea i read file create inner dictionary reread file create outer dictionary surely must easier way thanks advance help,3 if several words comes back search need calculate damerau levenshtein distance several times value input strings consider using dictionary hashmap cache results here implementation c private static dictionaryint dictionaryint int dameraulevenshteindictionary new dictionaryint dictionaryint int public static int dameraulevenshteindistancewithdictionarycachingstring word string word dictionaryint int worddictionary dameraulevenshteindictionarytrygetvaluewordgethashcode worddictionary int distance worddictionarytrygetvaluewordgethashcode distance the distance already dictionary return distance else the word found dictionary matching word found distance dameraulevenshteindistanceword word dameraulevenshteindictionarywordgethashcodeaddwordgethashcode distance return distance else the word found dictionary must add entry dictionary match int distance dameraulevenshteindistanceword word dictionaryint int dictionarytoadd new dictionaryintint dictionarytoaddaddwordgethashcode distance dameraulevenshteindictionaryaddwordgethashcode dictionarytoadd return distance,i following cython implementation calculating damerau–levenshtein distance strings based wikipedia article currently slow needs i list strings i find typos list i would glad anyone could suggest algorithmic improvements pythoncython magic could reduce runtime script i really care much space uses time takes calculate according profiling script using strings spends complete runtime sec dameraulevenshteindistance function i ideas make faster def dameraulevenshteindistancea b h source sequence b comparing sequence h matrix store metrics currently nested list cdef int inflenalenbijxijddb alphabet getalphabetab lena lena lenb lenb inf lena lenb da x xrange lenalphabet xrange lena db j xrange lenb daalphabetbj j db ai bj db j hij min hijd hij hij hijiijj daalphabetai return hlenalenb cdef getalphabetwords construct alphabet lists found tuple words sequential identifier word cdef int alphabet wordlist words letter wordlist letter alphabet alphabetletter return alphabet,1 i problem here code def gccontentgenomefile nbases totalbases gc line genomefilexreadlines nbases countseq n totalbases lenline gc countline g c gcpercent floatgctotalbases nbases return gcpercent return invalid syntax i simply failed close bracket following code gcpercent floatgctotalbases nbases hope helps,i getting invalid syntax error python script statement f openfilename r return return syntaxerror invalid syntax i sure exactly wrong i python newbie greatly appreciate someone please help i using version,3 the microsoft wave format fairly well documented see httpsccrmastanfordeducoursesprojectswaveformat example it take much write file parser open interpret data get information require that said almost certainly done i sure someone give easier answer,i asked everything title i wave file written pyaudio input audio i want convert float data corresponding sound level amplitude fourier transformation etc anyone idea convert wave data float,1 given cat datatxt a abc b tex b tex e yet a abc this import csv open datatxt moder datafile fieldnames character string value value reader csvdictreaderdatafile fieldnamesfieldnames delimitert row reader crow character values introw value floatrow value row string c dc dc dcs dcsappendvalues print produces a abc b tex e yet,i trying read data create nested dictionary dictionaries there similar question i seem figure adapt solution particular problem i would grateful someone could explain solution problem basically i file looks like a abc b tex b tex e yet a abc i need create complex dictionary looks like completedict a abc b tex e yet i create inner dictionary i figure create outer dictionary here code inner dictionary open datatxt moder datafile fieldnames character string value value reader csvdictreaderdatafile fieldnamesfieldnames delimitert innerdict row reader values introw value floatrow value string row string string innerdict innerdictstringappendvalues else innerdictstring values could someone explain create outer dictionary the idea i read file create inner dictionary reread file create outer dictionary surely must easier way thanks advance help,1 use defaultdict collections import defaultdict completedict defaultdictlambda defaultdictlist open datatxt moderb datafile reader csvreaderdatafile delimitert c v v reader completedictcsappendv v,i trying read data create nested dictionary dictionaries there similar question i seem figure adapt solution particular problem i would grateful someone could explain solution problem basically i file looks like a abc b tex b tex e yet a abc i need create complex dictionary looks like completedict a abc b tex e yet i create inner dictionary i figure create outer dictionary here code inner dictionary open datatxt moder datafile fieldnames character string value value reader csvdictreaderdatafile fieldnamesfieldnames delimitert innerdict row reader values introw value floatrow value string row string string innerdict innerdictstringappendvalues else innerdictstring values could someone explain create outer dictionary the idea i read file create inner dictionary reread file create outer dictionary surely must easier way thanks advance help,1 i problem running pythonserverpy i changed line transport tsockettserversocket transport tsockettserversocket server started running,hi i trying write simple thrift server python named pythonserverpy single method returns string learning purposes the server code i following errors thrift python libraries i run server has anyone experienced problem suggest workaround the execution output starting server traceback recent call last file homedaeworkspacebasictestenvironmentvsrcpythonserverpy line module serverserve file usrlibpythonsitepackagesthriftservertserverpy line serve file usrlibpythonsitepackagesthrifttransporttsocketpy line listen file usrlibpythonsitepackagesthrifttransporttsocketpy line resolveaddr typeerror getaddrinfo argument must string none pythonserverjava port import myservice myserv ttypes import thrift files thrifttransport import tsocket thrifttransport import ttransport thriftprotocol import tbinaryprotocol thriftserver import tserver server implementation class myhandler return server message def sendmessageself text print text return in garage set handler implementation handler myhandler processor myservprocessorhandler transport tsockettserversocketport tfactory ttransporttbufferedtransportfactory pfactory tbinaryprotocoltbinaryprotocolfactory set server server tservertthreadedserverprocessor transport tfactory pfactory print starting server serverserve line goes here,2 try img src optrackedobjectimageurl alt,i trying display image name loop template this i template loop i thought work op trackedobjects opismine div stylefloatleft div img src optrackedobjectimage alt href url trackprofile optrackedobjectid optrackedobject abr div div endif endfor i know opismine true name shows here viewspy loginrequired def profilerequest user requestuser trackedobjects usertrackedobjectpermsallorderby ismine context trackedobjects trackedobjects return rendertoresponse accountsprofilehtml requestcontextrequest context finally modelspy name modelscharfieldmaxlength image modelsimagefielduploadto imgtrackedobjectimages nulltrue blanktrue update now i use anser adding url onto end i get three broken image icons now i checked path goes correct image would server issue possibly or something along lines,3 while question already answered several times simple solution problem listed yet x b b c z zupdatex zupdatey it fast z evil z mentioned easy understand change,i two python dictionaries i want write single expression returns two dictionaries merged the update method would i need returned result instead modifying dict inplace x b b c z xupdatey print z none x b c how i get final merged dict z x to extraclear lastonewins conflicthandling dictupdate i looking well,3 if reload module within create infinite loop would reload module reload module etc in mymainpy might able import mod reloadmod modtest i guess without code samples hard gauge exactly why must reload module work without module,note i accepted answer real question marked compile error i voted toreltwiddler answer gave workaround i like understand problem i simple module contains selftest code to facilitate use interactive session selftest code reloads module this works ok pydev runas running interactive window manually amending syspath importing pydev ide still gives compile redx error line import mod the reason i import mod name must resolvable whatever context running test order reload succeed for instance import mymain fresh interactive window call reload would fail without import since name mod known is way i fix mod one part much larger project consistently marked notcompiling makes development difficult module problem modpy def test run selftest first force reload module test mod import mod compile error here import imp mod impreloadmod testimpl def testimpl self test since i reload i change code rerun interactive window seperate function reload test effect code printinputenter extra bootstrap module used pydev i runas mymainpy import mod modtest pydevproject pythonpath appears correct folder root workspace since actually run pydev ok definitely correct mydirectory thanks,1 use pillow friendly pil fork it offers full setuptools compatibility faster release cycle no image code changes differ pil ie aims track pil image code changes make none changes without reporting upstream windows binaries if pil ever exactly pillow fork die until happens pillow disclaimer i fork author pillow created mainly make job easier although great see folks using edit pillow released march it offers python support many bug fixesenhancements while still attempt track changes upstream pil unfortunately fortunately depending look pillow begun drift away pil,when i install pil using easyinstall buildout installs way i must import image pil import image however i aptget install pythonimaging use pip e testpil install pil work fine here examples i trying install pil using virtualenv virtualenv nositepackages testpil testpilbineasyinstall pil testpilbinpython python r feb gcc apple inc build darwin type help copyright credits license information import pil traceback recent call last file stdin line module importerror no module named pil i see easyinstall pack pil egg pip same thing buildbot uses eggs how could i install pil properly using easyinstall buildout,3 i would probably go snaxib answer however prefer keep current format eclipse ignore error adding unresoledimport end line hit ctrl auto fill,note i accepted answer real question marked compile error i voted toreltwiddler answer gave workaround i like understand problem i simple module contains selftest code to facilitate use interactive session selftest code reloads module this works ok pydev runas running interactive window manually amending syspath importing pydev ide still gives compile redx error line import mod the reason i import mod name must resolvable whatever context running test order reload succeed for instance import mymain fresh interactive window call reload would fail without import since name mod known is way i fix mod one part much larger project consistently marked notcompiling makes development difficult module problem modpy def test run selftest first force reload module test mod import mod compile error here import imp mod impreloadmod testimpl def testimpl self test since i reload i change code rerun interactive window seperate function reload test effect code printinputenter extra bootstrap module used pydev i runas mymainpy import mod modtest pydevproject pythonpath appears correct folder root workspace since actually run pydev ok definitely correct mydirectory thanks,1 remember indices start zero with mind may clearer change string in out in out in out as see slice start correct index take correct negative stride step reaches beginning string,so i really get deal stride parameter slicing for example produces produce produce,2 the easiest way explain probably address examples this takes whole string then works backward every character this also working backward every character starting position number again working backward every character begin position end positions the slicing syntax startendstep if start omitted step negative starts end string,so i really get deal stride parameter slicing for example produces produce produce,3 that syntax stringstartendstep produces start last character this provide position slice would executed so go back characters last one reaches first one produces told python start nd character index string told python go back steps position which case python would obviously return this python tried go back steps already hit first character string one step you able figure one but i explain anyway so told python start third character index go back steps reaches first character so start go back steps accidentally first character happens reached so python give,so i really get deal stride parameter slicing for example produces produce produce,1 ahhhh it helpful posting app engine mention results dev server production the dev server performance characteristics production servers best way profile application in fact i believe indexes used dev server single threaded handle concurrent requests in fact app makes calls work,i trying optimize code i got problem i quite understand on every page web app list notifications much like facebook new ticker so every request i run code beggining notificationquery dbqueryticker keysonlytrue filter friends selfcurrentuserkeyname selfnotificationsfuture notificationqueryrun then i find good spot i call middle function notificationkeys futureparent future selfnotificationsfuture selfnotifications dbgetasyncnotificationkeys finally i fetch end contextupdate notifications selfnotificationsgetresult every thing works great except if i call middle function end request function i get dumb spot and if i call i think optimized spot i get smart spot as see api usage doubled making optimization what going call number first snippet cases call number dumb spot second snippet call number smart spot second snippet this last switch nothing problem i tested pd does google charge time query idle update the problem seems devserver i tried example smart version appspot i got queries appspot here everything works expected things get called run getasync block stuff as i said issue devserver still would nice see feature working localhost effective profiling,1 if want write simple recursive function use stack stack root dirs files oswalkfoo stack rootstartswithstack print postaction stackpop print preaction root stackappendroot stack print postaction stackpop writing function probably gives readable code though def walkdir print preaction dir name oslistdirdir fullname ospathjoindir name ospathisdirfullname walkfullname print postaction dir,python oswalk function almost i want i need pre posttraversal action directory eg tree foo foobar foobarbaz fooquux i want sequence preaction foo preaction foobar preaction foobarbaz postaction foobarbaz postaction foobar preaction fooquux postaction fooquux postaction foo how i wo writing function,1 loads work json import loads loads one two three two,my project currently receiving json message python i need get bits information for purposes lets set simple json string jsonstr one two three so far i generating json requests using list jsondumps opposite i think i need use jsonloads i much luck could anyone provide snippet would return input two example,1 very simple import json j jsonloads one two three print j two,my project currently receiving json message python i need get bits information for purposes lets set simple json string jsonstr one two three so far i generating json requests using list jsondumps opposite i think i need use jsonloads i much luck could anyone provide snippet would return input two example,3 for old python versions since using strings oneliner i think pattern would probably using dictionaries def sorteduniqyourlist table yourlist tables none k tablekeys ksort return k adapted ancient activestate code snippet thread alex martelli wrote several comments httpcodeactivestatecomrecipes a shorter way list comprehensions def sortuniqalist modlist dsetdefaultii alist modlistsort return modlist aside steven neat yet slightly unattractive one liner i think heads toward fewest lines idiomatic way python thanks steven rumbalski comments nd version condensed python zip function def sortuniqalist modlist dictzipalistalistkeys modlistsort return modlist if listsort operate side effect one liner,in python ask neatest way sort list remove duplicates i obviously write function would sort iterate wondering idiomatic oneliner edit the list short efficiency concern also elements immutable,3 adding separate answer discussion snaxib answer formatting have one module change testmystuff another update changes thetest testmystuffpy def go import thetest reloadthetest thetestruntest thetestpy def runtest run tests change things often printinputenter now iteractive shell able run testmystuffgo thetest reload every time run,note i accepted answer real question marked compile error i voted toreltwiddler answer gave workaround i like understand problem i simple module contains selftest code to facilitate use interactive session selftest code reloads module this works ok pydev runas running interactive window manually amending syspath importing pydev ide still gives compile redx error line import mod the reason i import mod name must resolvable whatever context running test order reload succeed for instance import mymain fresh interactive window call reload would fail without import since name mod known is way i fix mod one part much larger project consistently marked notcompiling makes development difficult module problem modpy def test run selftest first force reload module test mod import mod compile error here import imp mod impreloadmod testimpl def testimpl self test since i reload i change code rerun interactive window seperate function reload test effect code printinputenter extra bootstrap module used pydev i runas mymainpy import mod modtest pydevproject pythonpath appears correct folder root workspace since actually run pydev ok definitely correct mydirectory thanks,1 sometimes json string for example getting json url like j urlliburlopen httpsitecomdatajson need use jsonload jsonloads jobj jsonloadj easy forget string,my project currently receiving json message python i need get bits information for purposes lets set simple json string jsonstr one two three so far i generating json requests using list jsondumps opposite i think i need use jsonloads i much luck could anyone provide snippet would return input two example,3 you gtk using gtkoverlay if upgrade summary oldfashioned way connect exposeevent signal drawingarea paint information using cairo when information changes trigger redraw drawing area using widgetqueuedraw make sure handler runs handler draws actual video onto drawing area this work labels noninteractive gui elements if want actual functioning gui element hover video rather complicated i know i think fixed guarantees zorder i suspect buttons whatnot overpainted video drawn onto drawing area maybe triggering redraw exposeevent handler work,i project built python pygtk pygst gstreamer i video working perfectly gtkdrawingarea object however i need display gui elements over video playing please ask trust right appear behind in code video objects gtkdrawingarea declared put gtkfixed first following everything else so i do i need change object gstreamer playing i know possiblei seen gstreamer programs things like buttons labels sitting top video thanks advance,1 idiomatic oneliner no here nonidiomatic buttugly oneliner x localssetitem xsort x dsetitemy none true if simple twoliner acceptable x x dictmapnonexkeys xsort or make two small helper functions works sequence def uniqueit return dictmapnoneitkeys def sortedit alist item item alistsort return alist print sortedunique gives and finally semipythonic one liner x xsort zipx x none,in python ask neatest way sort list remove duplicates i obviously write function would sort iterate wondering idiomatic oneliner edit the list short efficiency concern also elements immutable,3 i know convenient way natively normally considered problem something python devs would want build i think way fine you could even subclass int builtin type override add sub etc operator methods include functionality might overkill,python two integer datatypes int long automatically converts necessary especially order avoid integer overflow i simulating c function python wondering standard ways reenable integer overflow for nonce i used overflowpoint maxint value overflowpoint value overflowpoint is standard way thing,2 i thought fdot would slower since create temporary array denominator i assumed step skipped fnodot for worth creating temporary array skipped fnodot slower uses less memory elementwise operations arrays size faster numpy worry striding dimensions size etc arrays operations use broadcasting generally bit slower operations if memory spare creating temporary copy give speedup use memory for example comparing three functions import numpy np import timeit def fnodotx return x def fdotx denom npdoty npones return x denom def finplacex x return x num x nponesnum nponesnum func fdot fnodot finplace timeittimeit sxy func number setup main import xyfdot fnodot finplace print func time print this yields similar timings results fdot time fnodot time finplace time however compare memory usage things become bit clearer the combined size x arrays mb mb bit ints there additional mb overhead import numpy etc returning x new array ie x require another mb array runs fdot we creating temporary array expect see mb mb memory usage and see runs fnodot if temporary array created expect peak memory usage mb mb exactly see so x creating additional num x temporary array division thus division takes quite bit longer would operating two arrays size runs finplace if modify x inplace save even memory main concern basically numpy tries conserve memory expense speed cases,numpy allows matrices different sizes addedmultiplieddivided provided certain broadcasting rules followed also creation temporary arrays major speed impediment numpy the following timit results surprise mewhat going in def fnodotmatarr return matarr in def fdotmatarr denominator scipydotarr scipyones return matdenominator in mat scipyrand in arr scipyrand in timeit temp fnodotmatarr loops best ms per loop in timeit temp fdotmatarr loops best ms per loop i thought fdot would slower since create temporary array denominator i assumed step skipped fnodot i note times scale linearly array size length billion fnodot slightly worse linear fdot,3 i think basic idea sound needs tweaks function overflow sysmaxint sysmaxint exceeded several times result single operation negative values sysmaxint also need considered with mind i came following import sys def intoverflowval sysmaxint val sysmaxint val val sysmaxint sysmaxint sysmaxint return val,python two integer datatypes int long automatically converts necessary especially order avoid integer overflow i simulating c function python wondering standard ways reenable integer overflow for nonce i used overflowpoint maxint value overflowpoint value overflowpoint is standard way thing,3 most wave files pcm bit integer format what want parse header known format check link xophmeister read data take integer values convert float integer values range need convert values floating points i code python however c code excerpt pcm data bit integer convert float bit short pbuffer shortpreadbuffer const float oneovershortmax ef unsigned int uframeread dwread mfmtformatnblockalign unsigned int uframecount mfmtformatnchannels short iin pbufferi outpbufferi floatiin oneovershortmax be careful stereo files stereo pcm data wave files interleaved meaning data looks like lrlrlrlrlrlrlrlr instead llllllllrrrrrrrr you may may need deinterleave depending data,i asked everything title i wave file written pyaudio input audio i want convert float data corresponding sound level amplitude fourier transformation etc anyone idea convert wave data float,2 does function use division right bitshifting if need worry overflows stage calculation always get correct answer modulo before returning result division right bitshifting normalize back standard integer range using something like import sys halfn sysmaxint n halfn def normalizevalue return value halfn n halfn,python two integer datatypes int long automatically converts necessary especially order avoid integer overflow i simulating c function python wondering standard ways reenable integer overflow for nonce i used overflowpoint maxint value overflowpoint value overflowpoint is standard way thing,2 it appears issue related version mysql box when compiling python mysql component uses mysqlconfig usually lives usrlocalmysqlbin determine flags pass cc compiling mysql component if bit version mysql running get version component even bit version python as example i following version mysql usrlocalmysqlosxx i running usrlocalmysqlosxx changing bit version mysql machine running sudo pip install mysqlpython fixed problem you run following command verify going build mysql component usrlocalmysqlbinmysqlconfig cflags you see something like iusrlocalmysqlinclude os g fnocommon fnostrictaliasing arch x,i time read many sites subject suspect i junk lying causing problem but this error i import mysqldb python import mysqldb librarypythonsitepackagesmysqlpythoncpymacosxuniversaleggmysqlpy userwarning module mysql already imported librarypythonsitepackagesmysqlpythoncpymacosxuniversaleggmysqlpyc usersphoebebrdownloadsmysqlpythonc added syspath traceback recent call last file stdin line module file mysqldbinitpy line module import mysql file buildbdistmacosxuniversaleggmysqlpy line module file buildbdistmacosxuniversaleggmysqlpy line bootstrap importerror dlopenusersphoebebrpythoneggsmysqlpythoncpymacosxuniversaleggtmpmysqlso suitable image found did find usersphoebebrpythoneggsmysqlpythoncpymacosxuniversaleggtmpmysqlso macho wrong architecture i trying bit checked file python usrbinpython macho universal binary architectures usrbinpython architecture x macho bit executable x usrbinpython architecture macho executable usrbinpython architecture ppc macho executable ppc file mysql usrlocalmysqlbinmysql macho bit executable x have set default version python python python r feb gcc apple inc build darwin tried deleting build directory python setuppy clean renamed pythonsitepackages could try pick update deleted everything followed instructions httpstackoverflowcomquestionsdjangomysqlonmacossnowleopard installing using macports but basically still get error traceback recent call last file stdin line module file optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagesmysqldbinitpy line module import mysql importerror dlopenoptlocallibraryframeworkspythonframeworkversionslibpythonsitepackagesmysqlso suitable image found did find optlocallibraryframeworkspythonframeworkversionslibpythonsitepackagesmysqlso macho wrong architecture,1 c dostuff c rawinput do want contine yn clowerstartswith c true else c false,ask user option wants mode inputwould like count vowel consonant vowel consonant mode modestrip mode modelower tell user input entered valid mode consonant mode vowel mode inputthat correct would like count vowel consonant vowel consonant get word user word inputplease enter word vowelcount consonantcount letter word letter aeiouaeiou vowelcount letter word letter bcdfghjklmnpqrstvwxyzbcdfghjklmnpqrstvwxyz consonantcount mode consonant printwordcontains consonantcount consonant mode vowel printwordcontains vowelcount vowel program starts asks user whether want count vowels consonants stored mode if user provides input consonant vowel program interprets error reasks input program asks word depending mode number consonants vowels calculated reported user program asks another word available if steps repeated otherwise continue step depending mode average vowels per word average consonants per word reported user im stuck step know ask another word repeat process,1 sqlalchemyexthybrid import hybridproperty hybridproperty def name self firstname selffirstname selffirstname none else middlename selfmiddlename selfmiddlename none else lastname selflastname selflastname none else return joinfirstname middlename lastnamestrip namesetter def name selfstring firstname middlename lastname splitstring stringsplit lensplitstring firstname string elif lensplitstring firstname lastname splitstring elif lensplitstring firstname middlename lastname splitstring else lensplitstring firstname splitstring lastname splitstring middlename joinsplitstring selffirstname firstname selfmiddlename middlename selflastname lastname the expression part nameexpression def name cls f clsfirstname clsmiddlename l clslastname return f l,i class sys import stderr elixir import types import class userentity usingoptionstablenameusers firstname fieldstring middlename fieldstring lastname fieldstring def getname self firstname selffirstname selffirstname none else middlename selfmiddlename selfmiddlename none else lastname selflastname selflastname none else return joinfirstname middlename lastnamestrip def setname selfstring firstname middlename lastname splitstring stringsplit lensplitstring firstname string elif lensplitstring firstname lastname splitstring elif lensplitstring firstname middlename lastname splitstring else lensplitstring firstname splitstring lastname splitstring middlename joinsplitstring selffirstname firstname selfmiddlename middlename selflastname lastname name propertygetnamesetname i like run query follows def getuseruser found none typeuser inttypestringtype typeuser stringtype oruserfirstnameuser usermiddlenameuser userlastnameuser usernameuser qry userqueryfilterwhere elif typeuser inttype oruseriduser useremployeeiduser qry userqueryfilterwhere try found qryone except noresultfound print stderr couldn find user elif typeuser user founduser return found however resultant sql query looks something like following select usersfirstname as usersfirstname usersmiddlename as usersmiddlename userslastname as userslastname from users where usersfirstname joseph or usersmiddlename m or userslastname schmoe or false notice false place username field i getting error sqlalchemyexcoperationalerror operationalerror column false i think i like sql query look like following select usersname from users where usersname joseph m schmoe edit the desiredsecond sql query incorrect i really wanted sort passive way create name field within database corresponds concatenate firstname middlename lastname edit i believe following get almost however i still struggling proper expression edit looks like works i need so i including answer,1 the settext method replaces current text need use append method instead note methods automatically add trailing newline import sys pyqt import qtgui class windowqtguiqwidget def initself qtguiqwidgetinitself layout qtguiqvboxlayoutself selfbutton qtguiqpushbutton test selfedit qtguiqtextedit layoutaddwidgetselfedit layoutaddwidgetselfbutton selfbuttonclickedconnectselfhandletest def handletestself selfeditappend spam spam spam spam spam name main app qtguiqapplicationsysargv win window winshow sysexitappexec,hello i experiencing rather strange issue pyqt qtextedit when i enter string qlineedit adds say i enter another first string disappears i assume thats i appending text any idea i relevant code selfmytextsettextstrselfuser strselflinetext n important one selfmysignalemitselfdecryptmymessagestrmsgstrip n edit i figured i needed use qtextcursor selfcursor qtextcursorselfmytextdocument selfcursorinserttextstrselfuser strselflinetext n cheers,3 try format line loggingformatterasctimes levelnames messages filenameslinenos ymd hms python logger formatter use standard python string formatting rules,i currently trying right align logging level field python logger output debug starting smtphandlerspy info first things first smtphandlerspy warning end smtphandlerspy debug ending smtphandlerspy instead looks like debug starting smtphandlerspy info first things first smtphandlerspy warning end smtphandlerspy debug ending smtphandlerspy the format line first block loggingformatterasctimes levelnames messages filenameslinenos ymd hms if i know max level length eg critical i right align spaces i trying figure achieve the following fails levelnames characters substitution happen later if i use something like formatlevelnames works padding i need want loggingformatterasctimes formatlevelnames messages filenameslinenos ymd hms short subclassing formatter anyone way achieve,1 like loggingformatterasctimes levelnames messages filenameslinenos ymd hms,i currently trying right align logging level field python logger output debug starting smtphandlerspy info first things first smtphandlerspy warning end smtphandlerspy debug ending smtphandlerspy instead looks like debug starting smtphandlerspy info first things first smtphandlerspy warning end smtphandlerspy debug ending smtphandlerspy the format line first block loggingformatterasctimes levelnames messages filenameslinenos ymd hms if i know max level length eg critical i right align spaces i trying figure achieve the following fails levelnames characters substitution happen later if i use something like formatlevelnames works padding i need want loggingformatterasctimes formatlevelnames messages filenameslinenos ymd hms short subclassing formatter anyone way achieve,3 i believe looking templatetag template tag as linkedto doc states since template system concept escaping display one bits used template tags must use templatetag tag for example p templatetag openvariable text templatetag closevariable p appear p text p,django treats var variable template how i escape var django treat variable p text p should prints exactly,3 i similar problem seems stem gdkpixmap i solution yet edit i solved problem using gtkgdkpixbufnewfromxpmdata generate pixbuf instead gdkpixmap cairo operations i know use size roundr parameters maybe fill gdkpixmap color replace gtkgdkpixbufaddalpha pixbuf generated,i using pygtk i want draw something inside cellrenderer i using cellrendererpixbuff working the problem drawing transparency output bad mixed screenshot httppostimageorgimagefijd my code def pixbufsqfromcolorcolor size roundr rounded square specified color pmap gdkpixmapnone size size depth cr pmapcairocreate crrectangle size size fillcolorcr crmovetoroundr crlinetosizeroundr crarcsizeroundr roundr roundr pi pi right corner crlinetosize sizeroundr crarcsizeroundr sizeroundr roundr pi right corner crlinetoroundr size crarcroundr sizeroundr roundr pi pi left corner crlineto roundr crarcroundr roundr roundr pi pi left corner crclosepath fillcolorcr color pbuf gdkpixbufgdkcolorspacergb true size size colormap gtkgdkcolormapgetsystem colormap selfgetscreengetsystemcolormap colormap pmapgetcolormap pbufgetfromdrawablepmap colormap size size return pbuf return gdkpixbufgetfromdrawablepmap gdkcolorspacergb size size and function used groupnode selftreestoreappend groupenable pixbufsqfromcolorgroupcolor grouptitle and used functions def setcolorcr color arguments setsourcergb setsourcergba must lencolor crsetsourcergbcolor color color elif lencolor crsetsourcergbacolor color color color else raise valueerror bad color strcolor def fillcolorcr color setcolorcr color crfill,1 you try escaping html character escapes like amp amp pampamp text ampampp try inside browser,django treats var variable template how i escape var django treat variable p text p should prints exactly,3 the argument passed battingaverage number atbats you histograms atbats per histogram oh need fix formatting code indentation messed your code think i think wanting battingaverage return final batting average returns list batting averages one atbat then plotting list i think want return single number battingaverage want accumulate list printbas function move pylabhist loop i suppose homework in words i think want something like hit out b def battingaverageatbats resultsa probabilitiesb numhits numouts rangeatbats randompickresults probabilities hit numhits else numouts ba floatnumhitsfloatnumhitsfloatnumouts return ba def printbas battingaverages battingaverage range pylabhistbattingaverages bins though code still needs cleanup,working python i trying plot histogram numbers generated runthroughs random walk but i use pylabhistbattingaverage bins i get weird multicolored histogram goes close runs walk maximum able go yaxis would here code hit out b def battingaverageatbats somelista probabilitiesb numhits numouts currentba rangeatbats randompicka b hit numhits else numouts ba floatnumhitsfloatnumhitsfloatnumouts currentbaappendba return currentba def printbas range battingaverage battingaverage pylabhistbattingaverage bins what wrong histogram let know anything needs clarification i best,1 i think make sphinx aware djangosettingsmodule environment variable so export djangosettingsmodulemysitesettings whatever right value then execute make html terminal session,i django project i document using rest docstrings following help diagloags within ide later build html documentation using sphinx my documentation shows properly within ide pycharm however i configure sphinx generate html documentation here structure project saassapp django project path docs dir sphinx confpy sphinx config file settingspy django settings studyview django app any ideas an examle confpy file would useful thank edit my project name saassapp module i trying make doc called studyview sphinx confpy file httppastebincomhtydcrr sphinx index file httppastebincomburtq result make html httppastebincommwjjee,2 you customize editor ipython uses edit command configure ipython use notepad ipython creates ipythonprofiledefault folder user folder case cuserszkipythonprofiledefault to configure ipython use notepad create ipythonprofiledefaultipythonconfigpy following c getconfig use dos style path cprogra bit system points cprogram files x cterminalinteractiveshelleditor cprogranotepanotepaexe set editor qt console wish use cipythonwidgeteditor cprogranotepanotepaexe you start ipython use edit command run notepad ipython saving closing notepad execute file ipython if mind installing pyqt pyzmq i believe pygments least ipython dev ipython qt console works really well frankly nicest interactive environment get python you paste directly ipython adjust indentation shifting padded code,i often use r analyze data really enjoy notepad along npptor especially npptor enables run part code without much hassle i highlight snippet r code run press f then code magically runs r console now i required use python analyze data i know ipython great work interactively always annoying copy snippet python code manually paste ipython console also indentation often mixed thus entire lines failed run note i want run selected lines codes entire file so i looking programpluginmacro similar npptor working pythonipython console i searched web find one some plugins nice exactly i want for example python script enables extending notepad outside various run extensions enables entire file run python,3 personally i would split color space main colors pixel i increment closest colored bucket one at end color bucket highest amount pixels wins basically think median instead average you really care colors image whereas averaging colors usually gives whole new color,i images different colors background majority images white if main color image one different colors i like associated i seen similar questions like image color detection using python ask average color algorithm i pretty much copied code using python image library histograms gotten work i find reliable determining main colors any ideas or libraries could address thanks advance edit thanks guys pretty much said thing create buckets increase bucket count nearest pixel image i seem getting lot images returning white beige also background images is way work around ignore background thanks,1 another option would add word joiner zero width nobreak space curly bracket pamp text ampp,django treats var variable template how i escape var django treat variable p text p should prints exactly,1 setting certificates mercurial described httpmercurialseleniccomwikicacertificates on page note says use openssl iis generate certificates apparently iis selfsigned certificates validate ssl library used mercurial if install tortoisehg mercurial certificates read hgrcdcacertpm this means must add selfsigned certificate otherwise efficient way get help troubleshooting installation via mercurial irc,we small company microsoft shop currently using subversion visualsvn installed pretty easy setup btw i currently evaluating mercurial branching nightmare svn so first followed httpwwwfiregardencomsoftwarehostingmercurialrepoiiswindowsserverrxpythonisapicgi latest mercurial source code python got error failed import callback module hgwebdirwsgi the specified module could found scratched followed httpwwwjeremyskinnercoukmercurialoniis worked reached step enabling ssl problem even setup ssl certs using openssl httpwwwdylanbeattienetdocsopenssliissslhowtohtml still nothing error get urlerror errno an existing connection forcibly closed remote host command returned code server side hgwebconfig collections crepositoryhg crepositoryhg web pushssl false allowpush baseurl hg cacerts webconfig xml version encodingutf configuration systemwebserver handlers add namepython pathcgi verb modulescgimodule scriptprocessorcpythonpythonexe u ampquotsampquot resourcetypeunspecified handlers rewrite rules rule namerewrite hgweb patternsyntaxwildcard match url conditions add inputrequestfilename matchtypeisfile negatetrue conditions action typerewrite urlhgwebcgir rule rules rewrite security requestfiltering requestlimits maxallowedcontentlength requestfiltering security systemwebserver systemweb httpruntime executiontimeout maxrequestlength systemweb client side hgrc paths default httpswebtesthgtest hostfingerprints webtest deadfd edit i tried install machg macbook test used httpmachghelpjasonfharriscomkbconnectionshowdoiaddaservercertificateorfingerprintforhttps walkthrough works eliminates serverieserver push amp pull http amp https sure windowstortoisehg problem following steps tortoisehg gives nothing edit one finding even clone using https works http i tried clone one codeplex projects using https worksthis really frustrating am missing something help appreciated,1 this errors mean actually using python probably python also installed environment used execute code,i using python request library one projects everything works fine local system i python django i created environment test serverpython django using wsgi now i get weird syntax errors for example line resultappendkencode utf isinstancek unicode else k syntaxerror invalid syntax here another config import settings syntaxerror invalid syntax i guessing something wsgi sure exactly can someone please help solve issue thanks,1 lots lots misconceptions the string quote unicode it byte string encoded utf you convert unicode decoding unicodename namedecode utf when print value unicodename console see one two things unicodename u alamxe print unicodename alamã© here see typing name pressing enter shows representation unicode code points this typing print reprunicodename however print unicodename prints actual characters ie behind scenes encodes correct encoding terminal prints result but irrelevant unicode strings represented internally as soon want store database file anywhere need encode and likely encoding choose utf originally name alamxcxa print name alamã© as see using original nondecoded version name repr print show codes characters so converting unicode actually makes really correct character so want store database nothing nothing sqlite accepts utf input stores data utf format disk so absolutely conversion needed store original value name database,i need insert series names like alamxcxa list i save sqlite database i know i render names correctly tiping print evalreprnamedecodeutf but i insert list i use print other way without print,3 since trying match small number preexisting colors try different approach test image colors see one closest match as match i start resizing image smaller size reduce amount work perception color image dependent amount detail for pixel smaller image find colors closest if within threshold bump counter color at end whichever highest count winner,i images different colors background majority images white if main color image one different colors i like associated i seen similar questions like image color detection using python ask average color algorithm i pretty much copied code using python image library histograms gotten work i find reliable determining main colors any ideas or libraries could address thanks advance edit thanks guys pretty much said thing create buckets increase bucket count nearest pixel image i seem getting lot images returning white beige also background images is way work around ignore background thanks,1 if using system python go ahead add line bashprofile export versionerpythonpreferbityes,i thirdparty library interface xerox finite state tools come universal binaries two variants internally ppc variant i also python interface library uses ctypes but i try run example code provided python interface i get error complaining library wrong architecture importerror dlopenusersarneswliblibxcfsmdylib suitable image found did find usersarneswliblibxcfsmdylib macho wrong architecture from i gather python executables x variant internally addition two versions library prefer run mode is way force python executable start version rather x one scripts,2 you use getcolors function get list colors image it returns list tuples form n color n number times color color occurs image to get maximum occurring color pass list max function pil import image im imageopentestjpg maximgetcolorsimsizeimsize note i passed imsizeimsize getcolors function maximum maxcolors value see docs details,i images different colors background majority images white if main color image one different colors i like associated i seen similar questions like image color detection using python ask average color algorithm i pretty much copied code using python image library histograms gotten work i find reliable determining main colors any ideas or libraries could address thanks advance edit thanks guys pretty much said thing create buckets increase bucket count nearest pixel image i seem getting lot images returning white beige also background images is way work around ignore background thanks,3 i think difficult feed script one line time look syssettrace set function invoked line execution you also set c api using pyevalsettrace slightly different form,my goal ultimately execute python script manipulates values c program one line time returning execution c program statements python script right i attempting feed python interpreter script one line time but wants context i idea construct can anyone point good tutorials documentation good i chose answer closely answered question i believe may enough control applications an answer works applications might involve lowerlevel calls python api please answer question answer grants control execution i asked another question following one i encountered different problems afterwards closely related link python c api stopping execution continuing later,2 store original mixedcase string plain text column use data type text varchar without length modifier rather varcharn they essentially varcharn set arbitrary length limit pain want change later read manual related answer peter eisentraut serverfaultse create functional unique index lowerstring that major point create unique index myidx on mytbllowername if try insert mixed case name already lower case get unique key violation error for fast equality searches use query like select from mytbl where lowername foo foo lower case course use expression index query planner recognizes compatibility fast as aside may want upgrade recent version postgresql there lots important fixes since more official postgres versioning site,i basically username unique case insensitive case matters displaying provided user i following requirements field charfield compatible field unique case insensitive field needs searchable ignoring case avoid using iexact easily forgotten field stored case intact preferably enforced database level preferably avoid storing extra field is possible django the solution i came somehow override model manager use extra field always use iexact searches i django postgresql,3 followup december it looks like pyposterous longer works my scripts fail pyposterous fails unit tests bummer pyposterous indeed give tools answer question i thought i share others here script i wrote import datetime import pyposterous pyposterous import cursor api pyposterousapiusername username password passwd ddatetimedatetimetodaystrftimeybdhm filename reportposts strd txt logopenfilename w post cursormethodapireadposts startpage parameters hostname spectrawiki try print log print log postauthor postdate posttitle except attributeerror pass no comments except unicodeencodeerror pass it crude script gets basic job done,as college teacher stem i like i use technology enhance learning experience students i doubly like allows introduce cool tech during last year i couple classes make posts posterous site httpspectrawikiposterouscom post comments posts others this required course i saddled keeping track class activity i hoped i could download site content way gives data i need posted posted posted article comment posterous functionality a responsive posterous tech suggested i look api but i coder i know enough coding html php matlab python r mathematica respect really know so i ask stack overflow community could i hack together something eg python script api get data i looking listed are tutorials would lead steps building script i never used api i really know begin thanks advance pointers edit for example posterous api reference example like curl x put user youexamplecompassword apitokenyour token posttitlenew title httpposterouscomapisitesposts talks api restful how i modify curl command return type information posterous site i probably handle authentication flags token flag but using flags i could use pointer,1 try send user agent header w mechanize,i trying run automated functional tests using python twill the tests verify application oauth login connection endpoints work properly luckily twitter mind twillmechanize accessing twittercom however facebook like fact i using twill access facebookcom i get incompatible browser response i simply want access oauth dialog page either allow deny application i testing is way configure twillmechanize facebook think standard browser,1 it turns actually memory error as winston ewert pointed i fact feeding negative parameters images resize method even though python documentation says memory errors problems memory error gets thrown give negative params resize my suspicion pil heavily leverages c libraries lead leaks invalid input since library bounds checking error simply bubbles,i using pil python image library image manipulation specifically i stitching images together my code seems work fine images small quantities sometime i getting memoryerror the part particularly strange i manipulations bit images work images kb i making lot calls imageresize i surprised significant issues here stack track traceback recent call last file testpy line module pprintscalematrixdown inpt file usersjeremykarmeldesktoppythonmergerpy line scalematrixdown return shrinkrowrow rowwidthoverflowrow row matrix file usersjeremykarmeldesktoppythonmergerpy line shrinkrow rest shrinkimim pixelsperim im rowremainingpixels file usersjeremykarmeldesktoppythonmergerpy line shrinkim return imresizeimsize numpix imsize numpix file librarypythonsitepackagespilimagepy line resize im selfimresizesize resample memoryerror keep mind images less x pixels i much dead end really sure proceed what i release memory should i calling del operator something simpler i thanks advance help,3 as others said csv package contains great objects handle file io without writing lot lowlevel code however i would implement time requirement using cron job rather sleeping application available it flexible susceptible single unexpected crash stops application watching,i started learning python recently hrs ago here scenario i get mails every hours remote measurement site measurement values the files csv format filenames xxcsv yycsv these data two instruments continuously running different sampling intervals the files stored local folders i want develop script would read file example xxcsv write new csv file data after hours script run read new file xxcsv append data new csv file created i want make script run infinite loop script checks new file adds csv file the file contains ‘date’ ‘time’ ‘value’ fields can please help telling modules i look writing script if examples i would really thankful,1 if want time component use date datetime,i want convert date object representing i use strptime includes time i dont need how best avoid datetimedatetimestrptime ymd print,2 you use date method datetimedatetimestrptime ymd print ddate,i want convert date object representing i use strptime includes time i dont need how best avoid datetimedatetimestrptime ymd print,3 these lines justintv python client library relevant def sendrequestself request tokennone requestsignrequestoauthsignaturemethodhmacsha selfconsumer token conn selfgetconn connection requested requesthttpmethod post connrequest post requesthttpurl bodyrequesttopostdata else connrequest get requesthttpurl headersrequesttoheader return conngetresponse error occurs def getconnself return httplibhttpconnectionsd selfhost selfport timeout notice httplibhttpconnection passed timeout change code take timeout make sure define happens timeout occurs,the oauth library linked justintv python library page locks python processes indefinitely random times this happens randomly often one servers i positive due anything code i pasting part stack dump related justintv python library oauth file homehonstreamshonstreamswebsitejtvclientpy line get return selfsendrequestrequest token file homehonstreamshonstreamswebsitejtvclientpy line sendrequest return conngetresponse file usrlibpythonhttplibpy line getresponse responsebegin file usrlibpythonhttplibpy line begin version status reason selfreadstatus file usrlibpythonhttplibpy line readstatus line selffpreadline file usrlibpythonsocketpy line readline data recv keyboardinterrupt the bottom line stuck keyboardinterrupt i stay line ever least days i let run i interested way socketpy lock even though timeout set some times time way prevented here bit information rootfoo python version python rootfoo uname linux foobarno genericpae ubuntu smp fri apr utc gnulinux,1 i know old question still comes near top google search topic i think i add little value when i first learning python i put little idea significant white space languages use inflexible that said i impressed python ability understand variety indentation styles when considering style use new project i think important keep two things mind first important understand python interprets indentation bryan oakley mentioned possibility offbyone errors using tabs actually possible default interpreter settings there better explanation learning python o rielly media basically variable changed including comment top source file tabwidth defines tab width when python encounters tab increases indentation distance next multiple tabwidth thus space followed tab entered along left file next multiple tabwidth if tab entered thing happens in way safe editor configured properly use tabs even mix tabs spaces as long set editor tab stops width python tabwidth declaration absent it generally bad idea use editor tab width spaces unless specify tabwidth file second much syntactic design python encourage code readability consistent style programmers project that said question becomes particular project make code readable people working project certainly good idea keep consistent indentation style depending platform editor used project different style may make sense different projects if compelling reason conform pep makes sense conform people expect i encountered projects use mix tabs spaces successfully basically spaces used indent small sections fact indented section relatively unimportant tabs used draw reader attention large structural feature for example classes begin tab simple conditional checks inside function use spaces tabs also useful dealing large blocks text indented multiple levels when drop levels indentation far easier line proper tab line proper number spaces if project use pep recommended style probably best write style guide file somewhere indentation pattern remains consistent people read explicitly configure editor match also pythonx option issue warnings mixed tabs spaces tt issue error this applied mixed tabs spaces inside scope python assumes tt far i found way disable check,i always used tabs indentation i python programming but i came across question so someone pointed python programmers use spaces instead tabs minimize editortoeditor mistakes how make difference are reasons one would use spaces instead tabs python or simply true should i switch editor insert spaces instead tabs right away keep going like i used,3 what seeing likely iteration overhead small dimension numpy versions dealt efficiently operations involving contiguous arrays shape the effect goes away size last dimension increases to see effect contiguity in import numpy in numpyversion out in arrcont numpyrandomrand in arrcont numpyrandomrand in arrnoncont numpyrandomrand in arrbcast numpyrandomrand in timeit arrcont arrcont loops best ms per loop in timeit arrnoncont arrcont loops best ms per loop in timeit arrbcast arrcont loops best ms per loop the situation however much improved numpy in import numpy in numpyversion out in arrcont numpyrandomrand in arrcont numpyrandomrand in arrnoncont numpyrandomrand in arrbcast numpyrandomrand in timeit arrcont arrcont loops best ms per loop in timeit arrnoncont arrcont loops best ms per loop in timeit arrbcast arrcont loops best ms per loop all timings probably accurate ms note also temporaries expensive in timeit arrcontcopy loops best us per loop edit note also arrnoncont sort contiguous stride itemsize inner loop unraveled numpy make fast contiguous array with broadcasting really noncontiguous array numpyrandomrand inner loop cannot unraveled cases slightly slower improving would still possible numpy emitted tailored machine code fly loop least yet,numpy allows matrices different sizes addedmultiplieddivided provided certain broadcasting rules followed also creation temporary arrays major speed impediment numpy the following timit results surprise mewhat going in def fnodotmatarr return matarr in def fdotmatarr denominator scipydotarr scipyones return matdenominator in mat scipyrand in arr scipyrand in timeit temp fnodotmatarr loops best ms per loop in timeit temp fdotmatarr loops best ms per loop i thought fdot would slower since create temporary array denominator i assumed step skipped fnodot i note times scale linearly array size length billion fnodot slightly worse linear fdot,1 i deal lot raw images bit bit grayscale i found loading raw image numpy array converting image usually works if problem byte order numpy arraybyteswap command take care conversion pil image object this code taken program works read bit raw images pil sceneinfile opensceneinfilefullname rb sceneimagearray fromfilesceneinfiledtypeuintcountrowscolumns sceneimage imagefrombuffericolumnsrows sceneimagearrayastype i raw i in second line changing uint uint load byte instead byte raw image in third line image cast byte integer pil routines seem work better type,i gb image i got nasa i wanted write decoder using python pil the page i got image states following the data formatted singlechannel bit integer two byte long signed raw binary file bigendian byte order header here documentation writing image decoder i much experience dealing images python i total loss,1 def normalizearr arrarrastype float arrmax arr return arr,please consider reproducible example pil import image import numpy np import scipymisc sm import matplotlibpyplot plt import matplotlibimage mpimg import matplotlibcbook cbook import urllib datafile cbookgetsampledata lenajpg lenapil imageopendatafile lenapilnp npasarraylenapil lenascipy smlena lenatmp open lenatmppng wb lenatmpwriteurlliburlopen httpoptipngsourceforgenetpngtechimglenapng read lenatmpclose lenampl mpimgimread lenatmppng sminfolenapilnp sminfolenascipy sminfolenampl output sminfolenapilnp class ndarray shape strides itemsize aligned true contiguous true fortran false data pointer xbecl byteorder little byteswap false type uint sminfolenascipy class ndarray shape strides itemsize aligned true contiguous true fortran false data pointer xbfdl byteorder little byteswap false type int sminfolenampl class ndarray shape strides itemsize aligned true contiguous true fortran false data pointer xbcbl byteorder little byteswap false type float arrays different shape type for additional processing i would like arrays represented last variable lenampl transform array values normalized float type what best way,1 python php you want urllibquote instead,why i getting error trying urlencode string callback httplocalhostapplicationauthtwittertwittercallback urlliburlencodecallback traceback recent call last file stdin line module file usrlibpythonurllibpy line urlencode raise typeerror typeerror valid nonstring sequence mapping object,3 with overriding model manager two options first create new lookup method class mymodelmanagermodelsmanager def getbyusernameself username return selfgetusernameiexactusername class mymodelmodelsmodel objects mymodelmanager then use getbyusername blah instead getusername blah worry forgetting iexact of course requires remember use getbyusername the second option much hackier convoluted i hesitant even suggest completeness sake i override filter get forget iexact querying username add class mymodelmanagermodelsmanager def filterself kwargs username kwargs kwargs usernameiexact kwargs username del kwargs username return supermymodelmanager selffilterkwargs def getself kwargs username kwargs kwargs usernameiexact kwargs username del kwargs username return supermymodelmanager selfgetkwargs class mymodelmodelsmodel objects mymodelmanager,i basically username unique case insensitive case matters displaying provided user i following requirements field charfield compatible field unique case insensitive field needs searchable ignoring case avoid using iexact easily forgotten field stored case intact preferably enforced database level preferably avoid storing extra field is possible django the solution i came somehow override model manager use extra field always use iexact searches i django postgresql,3 that function urlencodequery doseq encode sequence twoelement tuples dictionary url query string are looking urllibquotecallback,why i getting error trying urlencode string callback httplocalhostapplicationauthtwittertwittercallback urlliburlencodecallback traceback recent call last file stdin line module file usrlibpythonurllibpy line urlencode raise typeerror typeerror valid nonstring sequence mapping object,3 i guess want static code analysis how many locations code call function this hard dynamic languages like python many ways functions may called otherwise proper name even python bytecode compiler know always function going called place may even change execution and standard oo polymorphism consider def doublefxf x return fx print doublefxmathsqrt f stdinreadline print doublefxgetattrmath f no way static analyses tool find functions math going called code even first example would hard reason second impossible the following tool static analysis regarding complexity httpsourceforgenetprojectspymetrics other analysis tools like pylint pychecker rather focus style probable errors,is tool able measure frequency function calls project counts aspects statistics purposes python code thank,1 i sure i fully understand goal months ago i wanted something similar i wanted able drive c application python scripts i win qt gcc it turns days gdb debugger gcc scripted via python it took lot reading days work worked well i add extra code c sources,my goal ultimately execute python script manipulates values c program one line time returning execution c program statements python script right i attempting feed python interpreter script one line time but wants context i idea construct can anyone point good tutorials documentation good i chose answer closely answered question i believe may enough control applications an answer works applications might involve lowerlevel calls python api please answer question answer grants control execution i asked another question following one i encountered different problems afterwards closely related link python c api stopping execution continuing later,1 the input function x evaluates input python code use rawinput function instead with input text because evaluated syntax error dot followed anything,hello use eclipse pydev i wondering sample code work trying use function printwelcome annoying program response response because response inputwhyn printohok output following welcome annoying program because traceback recent call last file userscalebmatthiasdocumentworkspacedevogellapythonfirstsimpprogrampy l ine module response inputwhyn file userscalebmatthiasdesktopeclipse pluginsorgpythonpydevpysrcpydevsitecustomizesitecustomizepy line input return evalrawinputprompt file string line because syntaxerror unexpected eof parsing,3 what using set intersection setcolumnvals amp setcolumnvals amp setcolumnvals that give values appear three columns,i currently using python i currently three columns excel document different integer values the amount values vary ranging thousands basically i looking scan column one compare value see appear column two three similarly i column see appear column one three etc my thinking populate content column respective list iterate list column run statement compare iteration value see exists list column my question efficient means running comparison as said within three columns number appear three columns may appear number occasions i looking identify numbers appear three columns thanks,1 the csv module help readingwriting files you want use infinite loop sleep something like true processnewfile nothing new file timesleep processnewfile need check new files tricky want try using file finished written something like work def checkfornewfiledirectoryincoming files file oslistdirdirectory file files break size osstatfilestatstsize filesfile datetimetimenow size datetimetimenow file lasttime lastsize filesitems currentsize osstatfilestatstsize currentsize lastsize filesfile currentsize continue lasttime timewithnowrites return file raise noneready now function keep track files incoming directory return filename dormant long enough reasonably sure complete need function actually process file move somewhere safekeeping def processnewfile try filename checkfornewfile raises valueerror file ready except noneready return infile openfilename rb csvfilein csvreaderinfile outfile openmastercsv rb csvfileout csvwriteroutfile row csvfilein csvfileoutwriterow csvfileoutclose csvfileinclose shutilmovefilename processed to put together complete imports globals import os import stat import shutil incoming somepathwithnewfiles processed somepathforprocessedfiles timewithnowrites minutes def checkfornewfiledirectoryincoming files file oslistdirdirectory file files break size osstatfilestatstsize filesfile datetimetimenow size datetimetimenow file lasttime lastsize filesitems currentsize osstatfilestatstsize currentsize lastsize filesfile currentsize continue lasttime timewithnowrites return file raise noneready def processnewfile try filename checkfornewfile raises valueerror file ready except noneready return infile openfilename rb csvfilein csvreaderinfile outfile openmastercsv rb csvfileout csvwriteroutfile row csvfilein csvfileoutwriterow csvfileoutclose csvfileinclose shutilmovefilename processed name main true processnewfile nothing new file timesleep this code currently untested may bug two error somewhere stop running hopefully help get going,i started learning python recently hrs ago here scenario i get mails every hours remote measurement site measurement values the files csv format filenames xxcsv yycsv these data two instruments continuously running different sampling intervals the files stored local folders i want develop script would read file example xxcsv write new csv file data after hours script run read new file xxcsv append data new csv file created i want make script run infinite loop script checks new file adds csv file the file contains ‘date’ ‘time’ ‘value’ fields can please help telling modules i look writing script if examples i would really thankful,1 urlstring membersbookingphpoperationmemberdayampcourseidampddatesssampcomp year rawinputenter year month rawinputenter month day rawinputenter day print urlstring year month day,i url mechanize python reads membersbookingphpoperationmemberdayampampcourseidampampddateampampcomp but i want change url depending data user inputs console eg year rawinputenter year month rawinputenter month day rawinputenter day and depending data user inputted code change url says ddateamp url i basically want change ddateyearmonthdatamp how i edit strings based users input in c point reference i would use ddateiiiampamp year month day something effect,1 you able use purposes in addition googling python awk brings results probably helpful,i trying convert shell scripts python code i stuck trying operation i process outputs text file file sections like running operation kdasdakdnaskdaksdma error present error kdmakmdasmdaksom this file could multiple lines operation error present otherwise next line another operation always crlf block i trying scan file find line contains error read operation caused error details error extrapolate text file save error log file so far find lines error simple code i able find example actually print lines necessarily ones contain error message ones came line error located using awk grep would straightforward python i really sure far able print line error prints would like control lines printed import fh open logsoutputtxt line fh error line print line tried look re module python also string modules far i found anything would allow would awk example look occurrence specific string turn print turn done can anyone point right direction tackle issue thanks,1 import ss qhvfgbhgozr yytuuuyuyuuuyuyuuyy jhfg tryy error jjfkhdjhfjh ttrtr aaaeeedddeedaeaeeaeeea jhzdgcoiua zfaozifh cohfgdyg fuo regx recompile rnerrorrn remultiline print regxsearchssgroups result yytuuuyuyuuuyuyuuyy jhfg tryy error jjfkhdjhfjh ttrtr aaaeeedddeedaeaeeaeeea,i trying convert shell scripts python code i stuck trying operation i process outputs text file file sections like running operation kdasdakdnaskdaksdma error present error kdmakmdasmdaksom this file could multiple lines operation error present otherwise next line another operation always crlf block i trying scan file find line contains error read operation caused error details error extrapolate text file save error log file so far find lines error simple code i able find example actually print lines necessarily ones contain error message ones came line error located using awk grep would straightforward python i really sure far able print line error prints would like control lines printed import fh open logsoutputtxt line fh error line print line tried look re module python also string modules far i found anything would allow would awk example look occurrence specific string turn print turn done can anyone point right direction tackle issue thanks,1 it pretty openended question numpy scipy gold standard numerical computation python,writing program python point looking package handles statistics is anything available thanks advance,2 you standard library i went source json module impossible use lazily without reimplementing,i like read multiple json objects filestream python one time unfortunately jsonload read endoffile seem way use read single object lazily iterate objects is way using standard library would ideal thirdparty library i use instead at moment i putting object separate line using jsonloadsfreadline i would really prefer need example use examplepy import myjson json import sys jsoniterloadsysstdin printworking typeo intxt foo bar baz example session python examplepy intxt working dict working int working int working list working int working int working int,1 import datauri dataimagepngbaseivborwkggoaaaansuheugaaaauaaaafcayaaacnbyblaaaaheleqvqipwgiaxdibkedhxgljnbaaotxlyohwaaaabjruerkjggg imgstr researchr base dataurigroup output open outputpng wb outputwriteimgstrdecode base outputclose need load pil import cstringio tempimg cstringiostringioimgstrdecode base im imageopentempimg,i trying get contents html canvas pass django server manipulated pil saved png here i far from html form user clicks update button canvas contents canvastodataurl gets dumped text box submitted via post form eventually automatic input typetext idcanvasdata namecanvasdata input type button valueupdate onclick jscriptupdatedata canvas idsketchcanvas script typetextjavascript function jscriptupdatedata canvasdata value canvas todataurl script the canvasdata form dataimagepngbaseivborwkggoaaaaetc gets sent then i deal django pil import image canvasdata requestpostget canvasdata im imagesomehowloadcanvasdata imsave canvaspng and stuck i figure get baseencoded data url load image usable form pil thanks edit code bottom comment dataimagepngbaseivborwk dstrip dataimagepngbase vborwk,3 inside django app easily use urllib json modules python standard library pull data urls parse json,i existing rest application serving either json xml i use framework play render templates directly i allowed arbitrary homework requirement invented forced use second layer consume process render rest objects i want use djangopython possible what recommend something i parsing json directly would nice is possible django i would like templating views level so something good templating language needed or i using something even lightweight like httpliburllib,1 if using ipython whos command builtin in whos variable type datainfo ndarray xx elems type int bytes b ndarray elems type int bytes kb np module module numpy likagesnumpyinitpy in general i highly recommend using ipython interactive work python numpyscipymatplotlibetc fernando perez others actively adding lot great features,i new numpy trying search function list variables along sizes matrix dimensions well memory usage find one i essentially looking equivalent whos command matlab octave does exist command python numpy thanks,3 this line incorrect syntax except ioerror errno strerror the correct form except ioerror err examine err attributes like errno etc i sure got original line valid python x syntax either,i random line generator program written python i need port python you give program option n number file argument tell randomly output number number lines file here source program usrbinpython import random sys optparse import optionparser class randline def initself filename f openfilename r selflines freadlines fclose def chooselineself return randomchoiceselflines def main versionmsg prog usagemsg prog option file file output randomly selected lines file parser optionparserversionversionmsg usageusagemsg parseraddoptionn numlines actionstore destnumlines default helpoutput numlines lines default options args parserparseargssysargv try numlines intoptionsnumlines except parsererrorinvalid numlines formatoptionsnumlines numlines parsererrornegative count formatnumlines lenargs parsererrorinput least one operand index rangelenargs inputfile argsindex try generator randlineinputfile index rangenumlines sysstdoutwritegeneratorchooseline except ioerror errno strerror parsererrorio error formaterrno strerror name main main when i run python python randlinepy n filetxt i get following error file randlinepy line except ioerror errno strerror syntaxerror invalid syntax can tell error means fix thanks,3 i attacked building tree potential additions finding cheapest option among here working albeit ugly unoptimized example httpsgistgithubcom the tree end pw nodes p number products wp average number warehouses per product,i dict whs id code code code id code code code id code code code id code code code what i need build new list look like submit codes code ids id id id codes code code code ids id what i far def parseavailableself whs separate whskeys submit lenseparate avail codes ids num item enumerateseparate lenavail codes avail codes whsitem avail ids appenditem else availall listsetavail codes amp setwhsitem print item availall lenavailall avail codes availall avail ids appenditem lenavail codes del separatenum submitappendavail return submit which returns ids id id codes code ids id codes code code code ids id codes code code code could work except id amp id combined ids id id codes code code curious easier approach i thought figure i could setup couple nested loops compare everything piece piece though seems rather unpythonic thank you advance,1 the recipe uses win api function createmutex create named mutex a mutex system object exists outside app process getlasterror returns erroralreadyexists createmutex called name already exists the recipe checks return value exits you change recipe use different string mutexname pick something unlikely else lock application able start,i using following recipe allow single instance application httpcodeactivestatecomrecipescreatingasingleinstanceapplication the recipe uses mutexname variable filled mutex value if i want create unique mutex i also recipe work can anyone explain thanks,1 the line except ioerror errno strerror relies little used obscure fact exceptions python iterable iterate parameters given exception iterating exception this course breaks explicit better implicit rule python removed python longer instead except ioerror e errno strerror eargs this clearer works versions python,i random line generator program written python i need port python you give program option n number file argument tell randomly output number number lines file here source program usrbinpython import random sys optparse import optionparser class randline def initself filename f openfilename r selflines freadlines fclose def chooselineself return randomchoiceselflines def main versionmsg prog usagemsg prog option file file output randomly selected lines file parser optionparserversionversionmsg usageusagemsg parseraddoptionn numlines actionstore destnumlines default helpoutput numlines lines default options args parserparseargssysargv try numlines intoptionsnumlines except parsererrorinvalid numlines formatoptionsnumlines numlines parsererrornegative count formatnumlines lenargs parsererrorinput least one operand index rangelenargs inputfile argsindex try generator randlineinputfile index rangenumlines sysstdoutwritegeneratorchooseline except ioerror errno strerror parsererrorio error formaterrno strerror name main main when i run python python randlinepy n filetxt i get following error file randlinepy line except ioerror errno strerror syntaxerror invalid syntax can tell error means fix thanks,3 why thread dosomethinguser ifgooduseruser else gooduser ifisuserbaneduser ifpasttimesincebanuser usergooduseruser elifisuserbad banuser banuseruser add userstart time hash isuserbanned check hash could check expired seperately care isuserbad check params set values hash,i got eventdriven chatbot i trying implement spam protection i want silence user behaving badly period time without blocking rest application here work userbehavingbadly ban user timesleep penaltyduration bad blocks entire application unban user ideally userbehavingbadly true i want start new thread nothing ban user sleep unban user thread disappears according i accomplish goal using following userbehavingbadly threadstartnewthread bansleepunban user penalty simple usually indicator good pretty simple everything i heard threads said bite unexpected ways my question is better way run simple delay loop without blocking rest application,2 use threading timer object like threadingtimer unban tstart seconds unban run then unban run thread,i got eventdriven chatbot i trying implement spam protection i want silence user behaving badly period time without blocking rest application here work userbehavingbadly ban user timesleep penaltyduration bad blocks entire application unban user ideally userbehavingbadly true i want start new thread nothing ban user sleep unban user thread disappears according i accomplish goal using following userbehavingbadly threadstartnewthread bansleepunban user penalty simple usually indicator good pretty simple everything i heard threads said bite unexpected ways my question is better way run simple delay loop without blocking rest application,1 instead starting thread ban put bans priority queue single thread sleeping unbanning code keeps two structures heapq allows quickly find soonest ban expire dict make possible quickly check user banned name import time import threading import heapq class bans def initself selflock threadinglock selfevent threadingevent selfheap selfdict selfthread threadingthreadtargetselfexpirationthread selfthreadsetdaemontrue selfthreadstart def banuserself name duration selflock timetime expiration nowduration heapqheappushselfheap expiration user selfdictuser expiration selfeventset def isuserbannedself user selflock timetime return selfdictgetuser none def expirationthreadself true selfeventwait selflock next user selfheap timetime duration nextnow duration timesleepduration selflock selfheap next heapqheappopselfheap del selfdictuser selfheap selfeventclear used like b bans bbanuserphil bisuserbannedphil,i got eventdriven chatbot i trying implement spam protection i want silence user behaving badly period time without blocking rest application here work userbehavingbadly ban user timesleep penaltyduration bad blocks entire application unban user ideally userbehavingbadly true i want start new thread nothing ban user sleep unban user thread disappears according i accomplish goal using following userbehavingbadly threadstartnewthread bansleepunban user penalty simple usually indicator good pretty simple everything i heard threads said bite unexpected ways my question is better way run simple delay loop without blocking rest application,3 you need actually initialize app class order anything the label go inside init method along widgets normally put widgets inside frame eg radiobuttonframe text going use frame need create and aligning radiobuttons anchorw instead centering makes look cleaner tkinter import import time class app def initself master w labelmaster text anxiety nervousness worry fear wpack v intvar radiobuttonmaster text variablev valuepacksidetop anchorw radiobuttonmaster text somewhat variablev valuepacksidetop anchorw radiobuttonmaster text moderatly variablev valuepacksidetop anchorw radiobuttonmaster text lot variablev valuepacksidetop anchorw selfbutton buttonmaster textback fgred commandselfbutton selfbuttonpacksidebottom selfbutton buttonmaster textnext fgred commandselfbutton selfbuttonpacksidebottom def buttonself print sam awesomegajonga def buttonself print python for the win gian says python filthy master tk app appmaster mastermainloop,my friend i working making window displays radio buttons text struggling add two buttons bottom here code tkinter import import time class app def initself master frame framemaster framepack v intvar radiobuttonmaster text variablev valuepacksidetop radiobuttonmaster text somewhat variablev valuepacksidetop radiobuttonmaster text moderatly variablev valuepacksidetop radiobuttonmaster text lot variablev valuepacksidetop selfbutton buttonmaster textback fgred commandselfbutton selfbuttonpacksidebottom selfbutton buttonmaster textnext fgred commandselfbutton selfbuttonpacksidebottom def buttonself print sam awesomegajonga def buttonself print python for the win gian says python filthy w labelmaster text anxiety nervousness worry fear wpack master tk mastermainloop running gives us following error traceback recent call last file volumeschrome usbstoragetkinker guiradiobutton examplepy line module w labelmaster text anxiety nervousness worry fear nameerror name master defined,1 add path libzbardll system path windows find zbarpyd loaded edit i installed application python library here make work without changing path control panel system configuration zbarpath ospathjoinosenviron programfiles zbar bin osenviron path formatosenviron path zbarpath import zbar zbarversion,i using python x tried install zbar module i downloaded current version zbar wininstaller httpzbarsourceforgenetdownloadhtml current version module pypi httppypipythonorgpypizbar zbar prompt webcam works fine soon i try import zbar python following error raises import zbar importerror dll load failed this happens i try binary windows installer module i also tried using setuppy always exits running install running build running buildext building zbar extension error none thank michael edit i also tried troubleshoot libsitepackageszbarpyd dependency walker raised libzbardll pythondll missing,3 how days sun mon tue wed thur fri sat print daysdayofweek also take look how i read date excel format python,i supposed get excel date dec day week print format the excel date thursday dec i able get i think method getting day using statements best approach this original script file please forgive roughness i checked i know solution right my problem getting efficient way get day suggestions get month final output we done date time module yetso i experiment code year month day yyear enintmonth yyen mmonth lminyintyintyinty dintm import math dmathfloordayyld final excel date dayofweekd print sd dayofweek print sun dayofweek print mon dayofweek printtue dayofweek print wed dayofweek print thur dayofweek print fri dayofweek print sat any help appreciated,2 creating list simple enough random import sample openproxylisttxt proxyfile proxies proxystrip proxy proxyfilereadlines proxies sampleproxies minlenproxies proxystr joinproxies then must use templating language one std lib httpdocspythonorglibrarystringhtmltemplatestrings create output file string included,this bit odd question i make best i i works writing script use proxies i ran problem automating part sucks last part everything i need i done example lets say i list proxies format stored txt file ect ect ect first part script i need randomize mix different orders making sure end one line second part randomizing taking first randomized proxies moving one line format ignoring proxies th separated without one beginning end third part i need new line proxies edit replace line file the line would currently look something like userprefextensionsproxytoolhttpproxies where see proxies line i need replace new batch proxies created end result looking something like userprefextensionsproxytoolclearcookiesonnewwindow true userprefextensionsproxytoolfirstrun false userprefextensionsproxytoolhttpproxies userprefextensionsproxytoolproxytype http userprefextensionsproxytoolreferer default i ask much i desperate i literally last hair project completing any help greatly appreciated thanks advance edit script complete credit goes zack bloom help i got little lazy python script works instead i created default prefs file empty proxy line outside python script default prefs file copied program python script magic replaces line proxies go newly compiled list thanks zack random import sample opencusersuseraccounttesttodaytxt proxyfile proxies proxystrip proxy proxyfilereadlines proxies sampleproxies minlenproxies proxystr joinproxies import fileinput import sys def replaceallfilesearchexpreplaceexp line fileinputinputfile inplace searchexp line line linereplacesearchexpreplaceexp sysstdoutwriteline replaceall cusersuseraccounttestprefsjs proxiesgohere proxystr,1 if anyone else ever similar problem try hardcoded solution import image import tkinter tk def cleanhexx return strhexx def renderimagetargetdatawh canvas tkcanvastargetwidthwheighth canvaspack x rangew rangeh c cleanhexdataxy cleanhexdataxy cleanhexdataxy canvascreatelinexyxyfillc im imageopenwhateverwhatever renderimagerootimloadimsizeimsize,when i run program canvas shows image canvas canvasframe width height bg white imagedata imageopen noartgif ppmf imagetkphotoimageimagedata canvascreateimage image ppmf anchor nw canvaspacksidebottom ideas ps i pil ver python the version tkinter comes python,1 the quantifier greedy meaning find longest possible match add force find shortest possible match refindallr text b b another way write regex explicitly exclude right angle brackets inside tag using instead refindallr text b b hrefwikibyten enter code heretitlebyte an advantage approach also match newlines n you get behavior add redotall flag refindallr text redotall b b hrefwikibyten enter code heretitlebyte to strip tags use resub resubr text flagsredotall a hex triplet sixdigit threebyte,i getting first paragraph pages trying extract words suitable tags keywords in paragraphs links i want remove tags for instance text a bhex tripletb sixdigit threea hrefwikibyte enter code heretitlebytebytea i want remove bba hrefwikibyte titlebytea end a hex triplet sixdigit threebyte a regex like work text a bhex tripletb sixdigit threea hrefwikibyte enter code heretitlebytebytea f refindallr text f bhex tripletb what best way i found several similar questions none i think solves particular problem update example beautifulsoup extract extract deletes tag including text must run tag separately soup beautifulsouptext sextract soup b bhex tripletb soup a sixdigit threea hrefwikibyte enter code heretitlebytebytea sextract soup hrefwikibyte enter code heretitlebytebytea soup a sixdigit three update for people question mentioned brendan long answer using htmlparser works best,1 the syntax error forgot colon replacement you actually invoke parser options available options parserparseargs if trying remove duplicates loop end try replacement selflines selflines listsetselflines selflinessort,i want truefalse option w program if option set i sorting output i following option added parseraddoptionw withoutreplacement actionstoretrue destreplacement defaultfalse helpoutpt lines without replacement replacement optionsreplacement replacement selflines selflinessort last selflines rangelenselflines last selflinesi del selflinesi else lastselflinesi when i run program i get following error file randlinepy line replacement syntaxerror invalid syntax can help figure correct syntax is parseraddoption programmed correctly,2 replacement needs replacement note colon,i want truefalse option w program if option set i sorting output i following option added parseraddoptionw withoutreplacement actionstoretrue destreplacement defaultfalse helpoutpt lines without replacement replacement optionsreplacement replacement selflines selflinessort last selflines rangelenselflines last selflinesi del selflinesi else lastselflinesi when i run program i get following error file randlinepy line replacement syntaxerror invalid syntax can help figure correct syntax is parseraddoption programmed correctly,1 see docs pangotabarray statement pangotabarray false creates tab array four tab stops position points what want tabs pangotabarray true tabssettab pangotableft desiredtabwidth textviewsettabtabs the value desiredtabwidth spaces however see function settabstopsinternal code gtksourceview see calculate width space,is way set tab width pygtk textview widget something spaces right i tried textviewsettabspangotabarray false however seems like i misunderstood docs what actual way thanks,1 beautiful soup answer problem try pretty awesome html parsing would become easy use text a bhex tripletb sixdigit threea hrefwikibyte enter code heretitlebytebytea soup beautifulsouptext joinsoupfindalltexttrue u a hex triplet sixdigit threebyte if text want extract enclosed outer tags like body body div idx div following illustration assumes text want extract enclosed within body tag now selectively extract text desired tags look documentation examples find many ways parsing dom text bodya bhex tripletb sixdigit threea hrefwikibyte enter code heretitlebytebytea body soup beautifulsouptext joinsoupbodyfindalltexttrue u a hex triplet sixdigit threebyte,i getting first paragraph pages trying extract words suitable tags keywords in paragraphs links i want remove tags for instance text a bhex tripletb sixdigit threea hrefwikibyte enter code heretitlebytebytea i want remove bba hrefwikibyte titlebytea end a hex triplet sixdigit threebyte a regex like work text a bhex tripletb sixdigit threea hrefwikibyte enter code heretitlebytebytea f refindallr text f bhex tripletb what best way i found several similar questions none i think solves particular problem update example beautifulsoup extract extract deletes tag including text must run tag separately soup beautifulsouptext sextract soup b bhex tripletb soup a sixdigit threea hrefwikibyte enter code heretitlebytebytea sextract soup hrefwikibyte enter code heretitlebytebytea soup a sixdigit three update for people question mentioned brendan long answer using htmlparser works best,2 you use newer opencv python interface i mistaken available since opencv it natively uses numpy arrays import cv im cvimreadabctiff print typeim result type numpyndarray,i rgb image i want convert numpy array i following im cvloadimageabctiff numpyasarrayim creates array shape i assume iplimage object how thanks,3 python allows mix spaces tabs indentation like def foo tab counts like eight spaces range tab counts like eight spaces spacespaceprinteach spacespacespacespacespacespacespacespaceprintdone line line python indentation level line tab line spaces printed console look like def foo range print printdone but editors allow set many spaces tab set four get def foo range print printdone the indentation still looks like indentation wrong python therefore allow indentation level ie line indented different ways you still mix tabs spaces indentation level this means def foo tab counts like eight spaces range tab counts like eight spaces spacespaceprinteach tab counts like eight spaces printdone work def foo tab counts like eight spaces range spacespacespacespacespacespacespacespacespacespaceprinteach tab counts like eight spaces printdone the way make way make indentation look weird set tab eight spaces indentation looks obviously incorrect notice tab indent spaces example realize insert tab four spaces def foo range printeach printdone of course solution problems written comments never use tabs i sure python still allows tabs good reason really,i trying run following code python written i pretty sure python f openfilename r selflines freadlines fclose selflines n selflinesappendn but i getting following error file randlinepy line selflines n taberror inconsistent use tabs spaces indentation can help figure correct syntax,3 i agree aix multiprocessing definitely way go regardless io bound read fast matter many parallel processes running but easily speedup consider following input directory contains several txt files project gutenberg import ospath multiprocessing import pool import sys import time def processfilename process one file count number lines words linecount wordcount openname r inp line inp linecount wordcountlenlinesplit return name linecount wordcount def processfilesparallelarg dirname names process file parallel via pollmap poolpool resultspoolmapprocessfile ospathjoindirname name name names def processfilesarg dirname names process file via map resultsmapprocessfile ospathjoindirname name name names name main starttimetime ospathwalk input processfiles none print processfiles timetimestart starttimetime ospathwalk input processfilesparallel none print processfilesparallel timetimestart when i run dual core machine noticeable x speedup python processfilespy processfiles processfilesparallel if files small enough fit memory lots processing done io bound see even better improvement,i trying read file python scan lines look terms write results let say counters term i need big amount files is possible multi threaded if yes so scenario like read file scan lines write counters output file files i read second question improve speed readwrite hope clear enough thanks ron,3 have read documentation if specify kx ky default values scipyinterpolatebisplrepx z wnone xbnone xenone ybnone yenone kx ky task snone epse txnone tynone fulloutput nxestnone nyestnone quiet and course lenx even give kx ky explicitly calling another problem your xy values form line define surface line therefore gives valueerror invalid inputs first fix data if data variation y skip spline d x z,i getting error message traceback recent call last file cpythontest line module tck interpolatebisplrepxyz file cpythonlibsitepackagesscipyinterpolatefitpackpy line bisplrep raise typeerror kxky must hold typeerror kxky must hold the error says lenx kxky how i solve here program import scipy import math import numpy scipy import interpolate x y numpyarrayilenx x numpyarrayx z numpyarray tck interpolatebisplrepxyz print interpolatebisplevtck,3 here complete answer duncan booth a list implemented array pointers objects contains every time call insert indx pointers already list moved position new one inserted beginning when call appendindx pointers copied enough space currently allocated block new element if space need copy existing elements put new element end update length field whenever new block allocated particular append faster insert extra space allocated case wish extend list if expected insert faster perhaps thought python used linkedlist implementation it practice applications list based implementation gives better performance nothing else i add actually,i written basic python snippets first insert values list reverse found huge difference speed execution insert append methods snippet l range lappendi lreverse time taken execute real ms user ms sys ms snippet l range linserti time taken execute real ms user ms sys ms i expected snippet perform much better snippet since performing reverse operation directly inserting numbers but time taken says otherwise i fail understand latter method takes time execute even though method looks elegant one explanation,3 note results depend precise python implementation cpython pypy automatically resize list overprovision space future appends thereby speed append furthermore internally lists chunks memory constant size heap sometimes lucky increase size chunk many cases object already for example assume allocated chunk size list abcd piece code allocated chunk size dictionary memory b c dictionary assume list elements another one added now simply resize list size memory b c e dictionary however need another element well thing acquire new space copy contents list memory dictionary b c e f note acquire space bulk aforementioned overprovisioning need resize potentially copy list every in contrast insert position always need copy list let insert x memory orig b c dictionary x b c ddictionary although enough space append x end move even copy may less expensive memory values,i written basic python snippets first insert values list reverse found huge difference speed execution insert append methods snippet l range lappendi lreverse time taken execute real ms user ms sys ms snippet l range linserti time taken execute real ms user ms sys ms i expected snippet perform much better snippet since performing reverse operation directly inserting numbers but time taken says otherwise i fail understand latter method takes time execute even though method looks elegant one explanation,3 create buildoutcfg root extends buildout conf directory buildout extendsconfbuildoutcfg i usually buildout config files example base developer deployment directory buildout i use method bootstrap file i need,i following folder structure bootstrappy setuppy conf buildoutcfg now i make running python bootstrappy puts generated folders bin eggs parts etc root instead conf folder,1 well need actually set n value aside zero how open filetxt f line f readlines necessary n floatlinesplit linesplit first number n print linerstrip rn rstrip remove existing eol line,i one text file follows columns i want extract values greater ideal output look like output to accomplish task wrote simple python script fopenfiletxtr n line freadlines floatn print line but reading data file i know simple task i able figure i going wrong can anybody help,1 if need datastructure efficient inserting start appending consider deque,i written basic python snippets first insert values list reverse found huge difference speed execution insert append methods snippet l range lappendi lreverse time taken execute real ms user ms sys ms snippet l range linserti time taken execute real ms user ms sys ms i expected snippet perform much better snippet since performing reverse operation directly inserting numbers but time taken says otherwise i fail understand latter method takes time execute even though method looks elegant one explanation,1 you writing file finally block exceptions raised caught except block the except bock executes exception raised try block the finally block always executes whatever happens also need initialising file variable none the use return except block skip finally block by nature cannot skipped want put cleanup code ie closing files so want use tryexceptfinally something like try f openfile w try fwrite hello world finally fclose except ioerror print oops a much cleaner way using statement try openoutput w outfile outfilewrite hello world except ioerror print oops,open new file write file none try file openfilepath w except ioerror msg unable create file disk fileclose return finally filewritehello world fileclose the code ripped function one user system reporting error line filewritehello world error attributeerror nonetype object attribute write question if python failed open given file except block executes return control getting transferred line throwing given error the value file variable none any pointers,3 except execute type ioerror finally part throws another error type attributeerror file none,open new file write file none try file openfilepath w except ioerror msg unable create file disk fileclose return finally filewritehello world fileclose the code ripped function one user system reporting error line filewritehello world error attributeerror nonetype object attribute write question if python failed open given file except block executes return control getting transferred line throwing given error the value file variable none any pointers,1 if file opened line file openfilepath w fails nothing gets assigned file then except clause runs nothing file fileclose fails the finally clause always runs even exception and since file still none get another exception you want else clause instead finally things happen exception try file openfilepath w except ioerror msg unable create file disk return else filewritehello world fileclose why else the python docs say the use else clause better adding additional code try clause avoids accidentally catching exception wasn’t raised code protected try except statement in words catch ioerror write close calls which good reason woudn “unable create file disk” – would different error one code prepared it good idea try handle errors,open new file write file none try file openfilepath w except ioerror msg unable create file disk fileclose return finally filewritehello world fileclose the code ripped function one user system reporting error line filewritehello world error attributeerror nonetype object attribute write question if python failed open given file except block executes return control getting transferred line throwing given error the value file variable none any pointers,3 logic including filewritehello world inside finally clause think must put try clause try file openfilepath w filewritehello world except ioerror printunable create file disk finally fileclose,open new file write file none try file openfilepath w except ioerror msg unable create file disk fileclose return finally filewritehello world fileclose the code ripped function one user system reporting error line filewritehello world error attributeerror nonetype object attribute write question if python failed open given file except block executes return control getting transferred line throwing given error the value file variable none any pointers,1 find text editor send regions code python ruby mongo session emacs i sure vim editors well this way edit save work still take advantage interactive shell below example randompick defined text file region selected sent ipython pressing ctrlc ctrl it shows ipython line starts in the next line shows ipython knows randompick for ipython opposed default python shell also cpaste allows cutandpaste multlineblocks code shell in cpaste pasting code enter alone line stop def randompickchoicesprobs cutoffsnpcumsumprobs idxcutoffssearchsortedrandomuniformcutoffs return choicesidx in,i bet came across problem like i use shells lot for python ruby irb mongo i use shortcurt like crta go begining crte end crtk clean end but i miss one thing when define multiline block ruby shell python shell miswrite something one statement rewrite almost everything history bring arrow becomes mess lines any tips make less painful,1 the base directory buildout always directory starting configuration file found case conf there two workarounds one easy one harder the first place bare buildoutcfg file root include file conf buildout extends confbuildoutcfg alternatively set directory options confbuildoutcfg file eggs developeggs parts bin directories buildout bindirectory bin partsdirectory parts eggsdirectory eggs developeggsdirectory developeggs that set directories parent conf directory eg directory bootstrap file however recipe still refers buildoutdirectory still use conf directory insead project root dir you cannot set option relative path must either let buildout set specify full path buildout directory fullpathtodirectory in opinion best using first option makes running bootstrap script easier anyway default looks buildoutcfg file current directory,i following folder structure bootstrappy setuppy conf buildoutcfg now i make running python bootstrappy puts generated folders bin eggs parts etc root instead conf folder,2 since already figured header use i recommend putting multiline string like an infinitely clever way make rnrn end header although technically inferior going rnrn rnrn tho shut rnrn n join rrr remember line http header must terminated rn since multiline strings already add n terminator end line needed r end line header post uploadphpfoobar httpr host localhostr useragent mozillar contenttype multipartformdata boundaryafbcadfebcfr afbcadfebcfr contentdisposition formdata namefiles filenameimagepngr contenttype imagepngr pngr ihdamp idax dr r bjr riendbr afbcadfebcfrnrn host hostname port port socket import socketafinet sockstream sconnecthost port ssendheader returndata srecv sclose print got back returndata and pretty much the real zen python actual coding part really simple real challenge coding i writing http program raw sockets it xchat script uses babelfishyahoocom translate messages irc foreign speakers,i trying post file within raw socket i read rfc i think i actually tested lot options i stuck by way i know i could use pycurl httplib etc i really want manualy here request post uploadphpfoobar http host localhost useragent mozilla contenttype multipartformdata boundaryafbcadfebcf afbcadfebcf contentdisposition formdata namefiles filenameimagepng contenttype imagepng png ihdamp idax d bj riendb afbcadfebcf all lines array joins njoinlines i tried n amp rn and i send crlf end i read images like f openfile rb filecontent true chunck fread filecontent chunck lenchunck break linesappendfilecontent any ideas,1 does mapping color values lognorm help see also example,i using pcolor matplotlib i use three dimensional array input i want arrange third array displayed log scale is option if i take logarithm third array plotting sub one values become negative pcolor longer works,1 although original version unutbu answer impressive seems bit overkill here simpler one text user locationny search dictpairsplit pair textsplit pair user location ny edit to insert search key keyword dict pair else keyword pairsplit pair textsplit user keyword search location ny,i want python parse string user locationny search then i use user string location string any existing way,2 since know program guess little so long io i expect conhost consume cpu so i hypothesise printing lot text console for example following program symptoms report true print hello world,i running python script windows i noticed even though python process takes cpu associated conhostexe process takes why how come large part cpu consumption conhost python process is way reduce cpu consumption besides optimizing code course update win bit python update the python program uses c package via swig python bindings the c package quickfix io network quite bit also prints console the python code prints several files which three suspect,2 import lxmlhtml lh text div classtest test br script typetextjavascriptscript hrefmailtoasdfadsfcomasdfadsfcoma div doclhfromstringtext printdocxpath astartswithhrefmailtotext asdfadsfcom,i following html code div classtest test br script typetextjavascriptscript hrefmailtoasdfadsfcomasdfadsfcoma div how get email address code using lxml,2 for ruby see pry works httpprygithubcom pry alternative irb pretty flexible hist command retrieve replay history it gives far control changing multiline statements see gist understand kind thing pry httpsgistgithubcom,i bet came across problem like i use shells lot for python ruby irb mongo i use shortcurt like crta go begining crte end crtk clean end but i miss one thing when define multiline block ruby shell python shell miswrite something one statement rewrite almost everything history bring arrow becomes mess lines any tips make less painful,1 please take look first answer now error message clear use bytes python strings used unicode python encode strings preferred encoding utf utf utf even one restricted bit encodings might call codepages the bytes wordlist file automatically decoded unicode python read file i suggest mupdatelineencodewordlistfileencoding encoded data pushed md algorithm encoded exactly like underlying file,i error traceback recent call last file pythonmdcrackerpy line module mupdateline typeerror unicodeobjects must encoded hashing i try execute code python import hashlib sys hashlibmd hash hashfile inputwhat file name hash resides wordlist inputwhat wordlist enter file name try hashdocument openhashfiler except ioerror printinvalid file rawinput sysexit else hash hashdocumentreadline hash hashreplacen try wordlistfile openwordlistr except ioerror printinvalid file rawinput sysexit else pass line wordlistfile hashlibmd flush buffer caused massive problem placed beginning script buffer kept getting overwritten thus comparing incorrect hashes line linereplacen mupdateline wordhash mhexdigest wordhashhash printcollision the word corresponding given hash line input sysexit printthe hash given correspond supplied word wordlist input sysexit,3 i needed way strip tags decode html entities plain text the following solution based eloff answer i use strips entities htmlparser import htmlparser import htmlentitydefs class htmltextextractorhtmlparser def initself htmlparserinitself selfresult def handledataself selfresultappendd def handlecharrefself number codepoint intnumber number u x u x else intnumber selfresultappendunichrcodepoint def handleentityrefself name codepoint htmlentitydefsnamecodepointname selfresultappendunichrcodepoint def gettextself return u joinselfresult def htmltotexthtml htmltextextractor sfeedhtml return sgettext a quick test html u hrefdemo emampnot uampxbampampxceema print reprhtmltotexthtml result u demo xac uububcuce error handling invalid html structure may cause htmlparseerror invalid named html entities ampapos valid xml xhtml plain html cause valueerror exception numeric html entities specifying code points outside unicode range acceptable python systems characters outside basic multilingual plane cause valueerror exception security note do confuse html stripping converting html plain text html sanitizing converting plain text html this answer remove html decode entities plain text – make result safe use html context example ampltscriptampgtalerthelloampltscriptampgt converted scriptalerthelloscript correct behavior obviously sufficient resulting plain text inserted html page the rule hard any time insert plaintext string html output always html escape using cgiescapes true even know contain html eg stripped html content however op asked printing result console case html escaping needed,mechanize import browser br browser bropen httpsomewebpage html brresponsereadlines line html print line when printing line html file i trying find way show contents html element formatting if finds hrefwhatevercomsome texta print text bhellob prints hello etc how would one go,3 datetime import datetime datetimefromtimestamp print,using python i retrieve value time date event knowing many seconds elapsed since i started datetime import timedelta timedeltaseconds print days ddd adays aseconds aseconds aseconds record seconds elapsed stored sqlite database,2 lineitem collectionsdefaultdictlist kv ditems nval refindallr linedw k outintnappendvalv mylist dictoutv v sortedout output expected item item item item fg item sd item f,i dictionary following format i know number lines items i going receive lineitem lineitem lineitem sd lineitem lineitem fg lineitem f what pythonic way parse list dictionaries following format item item item sd item item fg item f thanks advance,3 when using oauth fbinitoauthtrue login button setting cookie domain named fbsrappid encoded using app secret key contain user token anymore if really want avoid use java script client side simple way leverage presence cookie know user connected facebook perform authorization check dynamically display welcome message i use python working example give way search hope help,after login i want text welcome niklas display logging i reload page i understand make page display text server variable currentuser if i login press reload correct welcome message appears can help achieve i want why simple working example fb python javascript can i implement facebook connect without javascript if i use set cookie thank load doctype html html xmlnsfbhttpswwwfacebookcomfbml head title test facebook sdk title head body div idfbrootdiv script windowfbasyncinit function fbinit appid app id channelurl wwwkoolbusinesscomstaticchannelhtml channel file status true check login status cookie true enable cookies allow server access session oauth true enable oauth xfbml true parse xfbml load sdk asynchronously functiond var js id facebookjssdk dgetelementbyidid return js dcreateelement script jsid id jsasync true jssrc connectfacebooknetenusalljs dgetelementsbytagname head appendchildjs document script fbloginbutton autologoutlinktruefbloginbutton currentuser div iduserident span trans welcome b currentusernameescape bspan div endif body html here i get variable currentuser property def currentuserself hasattrself currentuser selfcurrentuser none cookie facebookgetuserfromcookie selfrequestcookies facebookconffacebookappid facebookconffacebookappsecret loggingdebuglogging cookiestrcookie cookie store local instance user data need roundtrip facebook every request user fbusergetbykeynamecookieuid loggingdebuguser struser loggingdebugusername strusername user graph facebookgraphapicookieaccesstoken profile graphgetobjectme user fbuserkeynamestrprofileid idstrprofileid nameprofilename profileurlprofilelink accesstokencookieaccesstoken userput elif useraccesstoken cookieaccesstoken useraccesstoken cookieaccesstoken userput selfcurrentuser user return selfcurrentuser,1 rreadline builtin types file objects filereadlinesize read one entire line file a trailing newline character kept string may absent file ends incomplete line if size argument present nonnegative maximum byte count including trailing newline incomplete line may returned when size empty string returned eof encountered immediately rreadline this first line filen rreadline second line filen rreadline,i receiving xml response api variable r print rread displays entire xml response i need take first line response convert string variable use loop substringing what best way capture first line,2 what want factory function opens file reads stuff needs read figure kind file initializes returns object appropriate class if want keep class want override new return object desired class instead class you could also using metaclass overriding call you change instance class instantiating well changing class attribute point desired class that work factory going familiar programmers read code,i looked many questions posted find answer problem i successful the problem might i know keywords i look so problem following i got program multilevel inheritance i trying figure best way would change class object subclass let say i following code class aobject def initself filename supera selfinit assignments class ba def initself filename superb selfinit assignments class ca def initself filename superc selfinit assignments i always want start initialising object class a depending type file used assignments may differ depending assignments i determine kind file so i want change class object whatever class suitable i know i could pass a object b c use copy deepcopy a assigning object reference change others change also i would need delete object a initialising b c class ba def initself filename obja none obja none selfdict copydeepcopyobjadict delobja else superb selfinitfilename also another possibility changing class attribute another class use kind update method new class i would like know two approaches recommended even better one thanks advance,2 because attribute abar foo attribute bar part object pointed a attribute foo you need either getattrfooa bar getattrgetattrfoo a bar the generic code accessing deep attributes split dot go last part found i writing memory tested def getattrdeepstart attr obj start part attrsplit obj getattrobj part return obj getattrdeepfoo abar,so playing around getattr code i discovered following myvariable fooabar worksbut something like b a myvariable getattrfoo b bar returns error foo contain attribute abar where i going wrong thanks,3 the equivalent myvariable fooabar using getattr would take steps aobject getattrfoo a myvariable getattraobject bar way myvariable getattrfoo b bar means myvariable getattrfoo bbar getattr lookups string bbar obviously exist,so playing around getattr code i discovered following myvariable fooabar worksbut something like b a myvariable getattrfoo b bar returns error foo contain attribute abar where i going wrong thanks,1 this code explain want class bobject def xself print b class aobject def xself print now create two objects b b ax bx b want become b object aclass typeb aclass b x attribute b class ax b,i looked many questions posted find answer problem i successful the problem might i know keywords i look so problem following i got program multilevel inheritance i trying figure best way would change class object subclass let say i following code class aobject def initself filename supera selfinit assignments class ba def initself filename superb selfinit assignments class ca def initself filename superc selfinit assignments i always want start initialising object class a depending type file used assignments may differ depending assignments i determine kind file so i want change class object whatever class suitable i know i could pass a object b c use copy deepcopy a assigning object reference change others change also i would need delete object a initialising b c class ba def initself filename obja none obja none selfdict copydeepcopyobjadict delobja else superb selfinitfilename also another possibility changing class attribute another class use kind update method new class i would like know two approaches recommended even better one thanks advance,1 the append function optional argument ignoreindex use join records together since index meaningful application,i try merge dataframes rows bigdatadataappenddata i get following error exception index cannot contain duplicate values the index first data frame starts second one i understand i modify index one data frame merging i know thank these two dataframes data meta particle ratio area type part touching part single part single part single clip part single part nuclei part single data meta particle ratio area type part single part dusts part single clip part nuclei part single part single first column index,3 yes int instance takes bytes system integers like object attributes ie pointers objects take additional memory space beyond used object value so bytes integer value bytes pointer class otherwise python know type object belonged start resolving attribute names inherited int class parents another object reference count used garbage collector the type int occupies bytes system pointers various methods attributes int class whatever housekeeping information python requires class the int class written c standard python implementation could go look source code see,sysgetsizeofint mean int occupies bytes sysgetsizeof bytes int object memory requirement i thought int python represented bytes reporting bytes please someone explain reporting bytes int uses bytes,3 from documentation sysgetsizeof getsizeof calls object’s sizeof method adds additional garbage collector overhead object managed garbage collector that might sysgetsizeof giving bytes as first line keep mind int object int type int int integer type integer an integer python actually takes many bytes needs need worry overflow type functionality handled i believe distinction valid builtin types userdefined objects type probably similar size instance type,sysgetsizeofint mean int occupies bytes sysgetsizeof bytes int object memory requirement i thought int python represented bytes reporting bytes please someone explain reporting bytes int uses bytes,1 python builtin function dir returns list names current local scope,i new numpy trying search function list variables along sizes matrix dimensions well memory usage find one i essentially looking equivalent whos command matlab octave does exist command python numpy thanks,2 pip freeze appears produce wrong results able modify requirementstxt githttpsgithubcommarianopyfiregitdbbbcbcffbfcacaaaeggpyfiredev,wanted use pyfire github library httpsgithubcommarianopyfire pip freeze produced e gitsshgitgithubcommarianopyfiregitdbbbcbcffbfcacaaaeggpyfiredev clone done install dependencies fails error code heroku run console check full error log experience ideas thanks lot advance,2 add failure call setup method def setupself try somethingthatmightfail except selffail,i test class class mytestunittesttestcase def setupself osmkdir def teardownself shutilrmtree def testoneself def testtwoself if something fails mkdir ran running setup testone still try run setup testtwo at point i get error mkdir rmtree run is way tell python unittest stop running current test setup fails i looking stop regular test failure,3 the signature signal testqstring pyqtpyobject so obviously str mapped qstring native python object types dict list mapped c type pyqtpyobject the list signal signatures obtained qmetaobject associated object test test metaobject testmetaobject rangemetaobjectmethodcount printmetaobjectmethodisignature,i need check signal presence listener emitted class testqobject test pyqtsignalstrdict def runself selfreceiverssignalteststrdict selftestemit blablabla the signal connected slot right successfully emits signals when checking signature signal method qobjectreceivers shows signal connected i understood reason incorrect signature i find method specify faithful signature signal,2 did install using sudo it odd easyinstall module would end documents and odd documents directory users level on os x i installed used beautifulsoup errors sudo pip install beautifulsoup python import beautifulsoup beautifulsoupfile librarypythonsitepackagesbeautifulsouppyc,i installed beautifulsoup mac using easyinstall errors and i run testpy file perfectly errors also but i try use beautifulsoup another file i get error traceback recent call last file usersconordesktoptestpy line module beautifulsoup import beautifulsoup importerror no module named beautifulsoup all i line beautifulsoup import beautifulsoup and gives error what going how i fix note testpy contains beautifulsoup import beautifulsoup afoo soup beautifulsoupa soupfindalla soupfindalla recursivefalse print soup edit ok i working away turns i move testpy file into folder beautifulsoup located documentsmechanizebeautifulsoup runs perfectly outside folder none files work what going one and i fix,1 and i write another plugin httpsgithubcomklenpythonmode old powerful screencast httpswwwyoutubecomwatchvoznpzcq,i looking suite plugins help finally switch vim fulltime right i using komodo good success vim bindings enough little errors i tired what i love komodo though code completion so i looking ordered importance code completion meaning ability code complete modulesfunctionsetc module pythonpath system modules bonus points showing docstrings completing jumpto class definition i guessing ctags manage automatically updating tags files project type management managing buffers ideally ability grep filename directory structure open bonus showing index class definitions buffer open bzr integration not super important since i drop shell,2 welcome pyside since qtextedit inherits qwidget would probably want set context menu policy custom supply popup menu httpwwwpysideorgdocspysidepysideqtguiqwidgethtmlpysideqtguipysideqtguiqwidgetcontextmenupolicy the reason suggest creating custom context qmenu isnt really accessible persistant object qtextedit its build fly basd context moment clicked im sure method overload gain acces qmenu shown i think best define completly,so pretty new pyside qt want know remove menuitem matter kind undo redo copy paste etc qtextedit standart context menu or tell way get qmenu object context menu then apply removeaction method menuitem tia,1 for write intensive operation like counters logs nosql solution always best choice personally i use mongodb kind tasks,i using python celery rabbitmq make web spider count number links page can database mysql written asynchronously is ok commit changes every row added required batch multiadd commit certain number rowsduration i prefer use sqlalchemy mysql unless recommended combination celeryrabbitmq i also see nosql couchdb recommended,1 if calculations computationally expensive python want scalability celery makes perfect sense gevent would make code efficient specific cases help terms scalability that also holds true use threads bear mind configure celery run worker pool gevent eventlet,i process sends financial tick data redis pubsub realtime now i want python application handle input data json instance calculations like moving average results i want send back via redis tasks calculations based results st task further i want trigger tasks regularly day second with complex unforseen structure issue i stumbled upon solutions like gevent celery threads but i wondering what options right way how i structure redis pubsub workertask stuff efficient way so suggestions welcome lines libraries used mentioned please share experiences techniques python structure best practice make use redis pubsub job best way,1 product takes variable number arguments need unpack list listproductnestedlist without list normally course,using itertoolsproduct function deep nested list list iterables want pass product function dont know format correctly clear want in k k product b out b b generated nestedlist input like nestedlist b instead get in k k productnestedlist out b,1 this template tag designed use jquery templates might trick it let wrap content want django interpret variables template tag,django treats var variable template how i escape var django treat variable p text p should prints exactly,1 ologn ologn asymptotically produce set functions the constant addition ignored like constant multiples they different terms usage space recursive binary search use logn space stack unless tailcalls removed compiler turned nonrecursive definition anyway algorithm loses significantly performance slicing expensive on,i need show differences iterative recursive binary search algorithms asymptotic runtime analysis far know worst case complexity ologn resources says recursive ologn i bit confused somebody help situation i also need improve python recursive binary search algorithm run equal time iterative one code written thanks def binarysearchalistitem lenalist return false else midpoint lenalist alistmidpoint item return true else itemalistmidpoint return binarysearchalistmidpointitem else return binarysearchalistmidpointitem,1 you store reference myclass object someobject you initialise reference make constructor myclass object parameter class someobject def initself reference selfreferencereference code access parents myvar selfreferencemyvar class myclass myvar myobject someobjectself as unutbu stated code running therefore detailed example class someobject def initself selfreferencenone def connectself reference selfreferencereference code access parents myvar def callself selfreferencemyvar class myclass myvar myobject someobject def connectself selfmyobjectconnectself name main myclass myclass myclassconnect myclassmyobjectcall printmyclassmyvar,i something like class someobject code access parents myvar class myclass myvar myobject someobject i need access myvar inside myobject is way i thank,3 you specify axis argument interpd import numpy np scipyinterpolate import interpd array nprandomrandint size x nplinspace xnew nplinspace newarray interpdx array axisxnew newarrayshape,i array i want interpolate st axes at moment i like example import numpy np scipyinterpolate import interpd array nprandomrandint size newarray npzeros x nparange xnew nparange x j x f interpdx array j newarray j fxnew the data i use represents years day averaged values latitude longitude domain i want create array daily values i also tried using splines i really know work much faster is way without using loops if loops must used ways speed thank advance suggestions,3 change selfsum selfsum multiprocessingvalue use selfsumvalue access change value class adderprocessmultiprocessingprocess def initself selfsum multiprocessingvalue def runself true number selfqueueget selfsumvalue number use selfsumvalue selfqueuetaskdone def getresultself selfqueuejoin return selfsumvalue use selfsumvalue the problem once call selfstart init main process forks child process all values copied now two versions p in main process psum in child process run method called psum augmented but main process calls pgetresult version p still psum equal so printed when want share float value processes need use sharing mechanism mpvalue see sharing state processes options share values,i trying use multiprocessing module python apparently something i understand i would expect class add numbers sent add return sum getresult method the code prints i like print what i missed import multiprocessing class adderprocessmultiprocessingprocess def initself multiprocessingprocessinitself selfsum selfqueue multiprocessingjoinablequeue selfdaemon true selfstart def runself true number selfqueueget selfsum number selfqueuetaskdone def addself number selfqueueputnumber def getresultself selfqueuejoin return selfsum p adderprocess padd padd print pgetresult ps this problem solved thanks answers just make easier readers complete working version import multiprocessing class adderprocessmultiprocessingprocess def initself multiprocessingprocessinitself selfsum multiprocessingvalue selfqueue multiprocessingjoinablequeue selfdaemon true selfstart def runself true number selfqueueget selfsumvalue number selfqueuetaskdone def addself number selfqueueputnumber def getresultself selfqueuejoin return selfsumvalue p adderprocess padd padd print pgetresult,3 like ip sysstdinreadline lenip print error chars sysexit,i wondering i might read less characters line python either user would enter exactly characters newline less newline it appears rawinput limit sysstdinread read hits characters regardless newline edit how would i stop characters just hard no more input allowed cannot type ideas max,2 normally stdin linebuffered means program running informed user typing user presses enter allows user use lineediting commands backspace without program anything extra however possible change terminal raw mode program informed every time user presses key then program act upon keypress whatever way appropriate in case implement line editing backspace one highlevel way use curses library,i wondering i might read less characters line python either user would enter exactly characters newline less newline it appears rawinput limit sysstdinread read hits characters regardless newline edit how would i stop characters just hard no more input allowed cannot type ideas max,1 selfsum process def runself true number selfqueueget print got queue number print before adding selfsum selfsum selfsum number print after adding selfsum selfsum selfqueuetaskdone jonhost mppy got queue before adding selfsum after adding selfsum got queue before adding selfsum after adding selfsum see multiprocessing sharing state processes get selfsum different processes,i trying use multiprocessing module python apparently something i understand i would expect class add numbers sent add return sum getresult method the code prints i like print what i missed import multiprocessing class adderprocessmultiprocessingprocess def initself multiprocessingprocessinitself selfsum selfqueue multiprocessingjoinablequeue selfdaemon true selfstart def runself true number selfqueueget selfsum number selfqueuetaskdone def addself number selfqueueputnumber def getresultself selfqueuejoin return selfsum p adderprocess padd padd print pgetresult ps this problem solved thanks answers just make easier readers complete working version import multiprocessing class adderprocessmultiprocessingprocess def initself multiprocessingprocessinitself selfsum multiprocessingvalue selfqueue multiprocessingjoinablequeue selfdaemon true selfstart def runself true number selfqueueget selfsumvalue number selfqueuetaskdone def addself number selfqueueputnumber def getresultself selfqueuejoin return selfsumvalue p adderprocess padd padd print pgetresult,1 you need specify want operate floating point numbers for example give floating point right performing integer operations edit could use float,i bit new python seem figure i wrong b print aba but calculator correct answer meaning lower b how i get decimals show i tried print decimalaba print floataba result works i make i wanted see anything i without changing variables i sure super easy i sure try any suggestions thanks,1 try converting one arguments float rather result print abfloata or upgrade python behaviour fixed b print aba by way want integer division python x use instead see pep change interested,i bit new python seem figure i wrong b print aba but calculator correct answer meaning lower b how i get decimals show i tried print decimalaba print floataba result works i make i wanted see anything i without changing variables i sure super easy i sure try any suggestions thanks,2 you performing division two integer operands python x means integer division that result integer you need known floating point division to force need least one operands division float for example print abfloata print floataba,i bit new python seem figure i wrong b print aba but calculator correct answer meaning lower b how i get decimals show i tried print decimalaba print floataba result works i make i wanted see anything i without changing variables i sure super easy i sure try any suggestions thanks,1 you might want look yahoo fantasy sports api httpdeveloperyahoocomfantasysportsguideindexhtml this kind data get would use trying get information available api ps you need get api key httpdeveloperyahoocomdashboardcreatekeyhtml,so i trying scrape yahoo gamechannelstartracker grab updates fantasy teams players get points make graphs excel the website url basically httpsportsyahoocomnflgamechannelappstamplid number end league id kinda new python i tried using beautiful soup first worked got code page game channel since requires javascript i got webkit ran gamechannel supposed telling update flash player wth date what,2 assuming using reasonably uptodate version matplotlib perhaps try something like import matplotlibpyplot plt make plot fig axes pltsubplotsnrows axesplotrange r axesplotrange bo set borders given color ax axes axtickparamscolor green labelcolor green spine axspinesvalues spinesetedgecolor green pltshow,this kind followup question post coloring axes ticks labels discussed i hope alright open new extended question changing color complete frame ticks axes around doubleplot via addsubplot axes ax ax results lot code this snippet changes color frame upper plot axspines bottom setcolor green axspines top setcolor green axspines left setcolor green axspines right setcolor green axxaxisgetticklines tsetcolor green axyaxisgetticklines tsetcolor green axxaxisgetticklines tsetcolor green axyaxisgetticklines tsetcolor green so changing frame color two plots two yaxes i would need lines code this looks like other methods i dug far matplotlibrc discussed changes globally locally i want plots different colors please discussions many colors plots matplotlibrc axes edgecolor green dig spines axis change also discussed really elegant i think child axgetchildren isinstancechild matplotlibspinesspine childsetcolor dddddd is elegant way condensing block something pythonic i using python matplotlib ubuntu,2 use break true sysstdinread n break etc,in c one ia b python appears one cannot sysstdinread n generates sysstdinread n syntaxerror invalid syntax is workaround,3 personally i like imm marks answers using break could also none def setax global x return setasysstdinread n print yo though i recommend,in c one ia b python appears one cannot sysstdinread n generates sysstdinread n syntaxerror invalid syntax is workaround,2 the grappelli skings tinymce come grappelli you also load js files tinymce coming grappelli tinymce find theme files relatively tinymce js you achieve pointing tinymcejsurl settingspy file right url eg tinymcejsurl staticurl grappellitinymcejscriptstinymcetinymcejs make sure run collectstatic static files settings correct,i setting tinymce filebrowser zinnia grappelli first time i think i everything setup properly seems i missing files i sure i find i getting errors following get statictinymcethemesadvancedskinsgrappellicontentcss http get statictinymcethemesadvancedskinsgrappelliuicss http get statictinymcepluginsgrappellieditorpluginjs http get statictinymcepluginsgrappellicontextmenueditorpluginjs http for reason pip installed version tinymce include file update i theme working missing downloaded version whatever reason i still getting get statictinymcepluginsgrappellieditorpluginjs http get statictinymcepluginsgrappellicontextmenueditorpluginjs http i seem folder tinymce plugin folder called grappeli i ran managepy collectstatic know files proper location thanks cg,1 simple sometext,how could i align text cuts first characters string fills rest whitespace eg ssometext space side thoughts,3 i know exactly floatinf gives float infinity greater number,in python want give set elements associated value use value comparisons i would want value infinite no matter number enter program number greater representation infinity,3 in python test floatinf in python import math test mathinf and test test test x will always true unless course pointed x also infinity nan number additionally python x only comparison ellipsis floatinf lesser eg float inf ellipsis would return true,in python want give set elements associated value use value comparisons i would want value infinite no matter number enter program number greater representation infinity,3 you also use rjust ljust strings in combination slicing get blablaljust blabla blablaljust blabla blablarjust blabla blablarjust blabla this quickly understood someone reading code string formatting variant much concise,how could i align text cuts first characters string fills rest whitespace eg ssometext space side thoughts,2 to get full control context menu first use qwidgetsetcontextmenupolicy change context meu policy qtcustomcontextmenu then connect handler qwidgetcustomcontextmenurequested signal in handler get standard context menu object using qtexteditcreatestandardcontextmenu method modify menu see fit show using qpoint passed signal handler like menuexectexteditviewportmaptoglobalpoint,so pretty new pyside qt want know remove menuitem matter kind undo redo copy paste etc qtextedit standart context menu or tell way get qmenu object context menu then apply removeaction method menuitem tia,2 eventstate holds or together states modifier keys so could try something like modifiers eventstate amp modifiersappend shift eventstate amp modifiersappend control etc print joinmodifiers see details,how i get full name event for example eventkeysym shows c event triggered controlc how i get control,2 use lookahead assertion p recompile spanprnpspan classfontdaz res psub data,i trying change string contains substrings thespanp pspan classfontcurrency currency at line break crlf the words code change i want replace second word starts lower case letter the thing changes code digit font i tried p recompile spanprnpspan classfontdaz res psub data working how i fix,1 this result resubsiazazazaz r subject applied thespanp pspan classfontcurrency produces currency although i would strongly suggest using regex xmlhtmlxhtml this generic regex remove elements capture text groups,i trying change string contains substrings thespanp pspan classfontcurrency currency at line break crlf the words code change i want replace second word starts lower case letter the thing changes code digit font i tried p recompile spanprnpspan classfontdaz res psub data working how i fix,1 i think use flag redotall means see nonprintable characters linebreaks regular characters so first line code would become p recompile spanppspan classfontdaz redotall two unescaped dots instead linebreak actually also remultiline everytime i problem like one end solving problem hope helps,i trying change string contains substrings thespanp pspan classfontcurrency currency at line break crlf the words code change i want replace second word starts lower case letter the thing changes code digit font i tried p recompile spanprnpspan classfontdaz res psub data working how i fix,1 to explain actually happens you try resize image negative width pil tries allocate negatively sized image fit resized image pil calls malloc negative amount memory hold negatively sized image malloc takes sizet unsigned as result negative memory request gets interpreted large number rather negative number malloc cannot allocate something large produces error to pil looks exactly like memory error reports so invalid inputs causing leaks bad behavior they result bad malloc request give pil could check negative sizes thus produce better error message perhaps figure worth already produces error message as happens actually running memory hard os try pretty hard keep process going using virtual memory your system bog gets point running memory so i found outofmemory errors caused requests negative amounts memory as far i recall real outofmemory errors i gotten java probably due use virtual machine,i using pil python image library image manipulation specifically i stitching images together my code seems work fine images small quantities sometime i getting memoryerror the part particularly strange i manipulations bit images work images kb i making lot calls imageresize i surprised significant issues here stack track traceback recent call last file testpy line module pprintscalematrixdown inpt file usersjeremykarmeldesktoppythonmergerpy line scalematrixdown return shrinkrowrow rowwidthoverflowrow row matrix file usersjeremykarmeldesktoppythonmergerpy line shrinkrow rest shrinkimim pixelsperim im rowremainingpixels file usersjeremykarmeldesktoppythonmergerpy line shrinkim return imresizeimsize numpix imsize numpix file librarypythonsitepackagespilimagepy line resize im selfimresizesize resample memoryerror keep mind images less x pixels i much dead end really sure proceed what i release memory should i calling del operator something simpler i thanks advance help,3 my first advise use factory methods although really want single method give something dispatch handling parameters def initself method args kw getattrself init methodargs kw def initcoponentsself r g b def initfromcolorself color and use like c color components c color fromcolor c while adds another parameter still way better type tests keeps stuff explicit it provides nice exceptions box illegal calls easily extendable even subclasses,is way python one constructor one method name differ number arguments accept types one arguments if would best way handle situations for example i made color class this class work basic example discuss lot unnecessary andor redundant stuff it would nice i could call constructor different objects list color object three integers constructor handles accordingly in basic example works cases args kwargs using class methods general way i came what would best practice like solution the constructor aside i would like implement add method i get method accept a plain integer added values three integers first added red value forth another color object red values added together etc edit i added alternative constructor initializer init basicly stuff i wanted but i stick first one factory methods seems clearer i also added add things mentioned i sure good style i try use iteration protocol fall back single value mode instead checking specific types maybe still ugly tho i taken look new thanks links my first quick try fails i filter rgb values args kwargs class list etc call superclass new right args rgb pass along init the call supercls self new works since i generate return object one i call intended original args get passed init working intended bails i could get rid init completly set values new i know feels like i abusing stuff i take good look metaclasses new first i guess source usrbinenv python coding utf class color object it strict accept i kinda like way def initself r g b selfr r selfg g selfb b maybe would better init the first may clear could handle way cases i like first though what think def initself obj selfr selfg selfb listobj this methods allows use lists longer items eg rgba coloralist would bail classmethod def fromlistcls alist r g b alist return clsr g b so could use dicts keys rgb keys coloradict would bail classmethod def fromdictcls adict return clsadict r adict g adict b this theoreticaly work every object iterable maybe intuitive duck typing rely object aslist methode similar classmethod def fromobjectcls obj return clsfromlistlistobj def strself return colors selfr selfg selfb def setrgbself r g b selfr r selfg g selfb b def getrgbself return selfr selfg selfb rgb propertygetrgb setrgb def aslistself return selfr selfg selfb def iterself return c c selfr selfg selfb we could add single value colorvalues list three values object supporting iterator protocoll one colorvalue def addself obj r g b selfr selfg selfb try ra ga ba listobj except typeerror ra ga ba obj r ra g ga b ba return colorcolorcheckrgbr g b staticmethod def checkrgbvals ret c vals c intc c minc c maxc retappendc return ret class coloralphacolor def initself r g b alpha colorinitself r g b selfalpha alpha def strself return colors selfr selfg selfb selfalpha name main l la r g b da r g b c color print c color ca coloralphala print ca color print c color print c color c colorl print c color c colorla print c fail c colord print c color c colorda print c fail print c colorfromobjectc print c color c colorfromobjectca print c color c colorfromlistl print c color c colorfromlistla print c color c colorfromdictd print c color c colorfromdictda print c color print print check colorcheckrgb xa check print c c color color print c ca c ca color color color,1 you would need install nodejs run separate piece code executes javascript code context emit html this possible using jsdom key extracting javascript code html page setting context correctly,i making web crawler getting link html easy part acquiring link result javascript easy can i get result javascript know link referred example how i retrieve link googlecom javascript code python doctype html html langen headhead body href idgoogto googlea body script documentgetelementbyid goog onclick function windowlocation httpgooglecom script html,1 assigning yield standard python it enables coroutines see httpdocspythonorgwhatsnewhtmlpepnewgeneratorfeatures,from following page httpcodegooglecompappenginepipelinewikigettingstarted i seen following code example use appengine pipeline class addonepipelinepipeline def runself number return number class addtwoandlogpipelinepipeline def runself number result yield addonenumber finalresult yield addoneresult yield logmessage the value finalresult works my questionconfusion yield statement right side is standard python syntaxusage special case allowedused pipeline model what happening,1 there way around class keyword always parsed people usually use class instead,i writing mako extension assist rendering forms i making excellent progress i ran one big stumbling block regarding css classes i want write code looks like fpform methodpost action classcssclass content fpform the function fpform refers looks simply like supportscaller def formcontext kwargs when i run code i get following exception syntaxexception syntaxerror invalid syntax unknown line ufpformmethodu post actionu classu cssclass line char this happens class attribute specified presumably mako converting attributes directly keyword arguments rather dictionary unpacking i tried passing special attrs argument function seems good way pass dict mako fpform methodpost action attrs class cssclass syntaxerror invalid syntax fpform methodpost action attrsdictclass cssclass won work pass class directly keyword argument so i get around i know i specify special attribute like cssclass convert class bit hack prevents library every producing form attribute cssclass,1 turned simpler i thought in manner i add popup menu qtableview widget i get header table object attach context menu way i regular context menu headers selftvhorizontalheader headerssetcontextmenupolicyqtcustomcontextmenu headerscustomcontextmenurequestedconnectselfheaderpopup,the sample code heavily influenced rightclick context menu appear user clicks cells table is possible different rightclick context menu rightclicks header table if i change code incorporate import import operator import os import sys pyqtqtcore import pyqtqtgui import def main app qapplicationsysargv w mywindow wshow sysexitappexec class mywindowqwidget def initself args qwidgetinitself args selftabledata apple red small apple red medium apple green small banana yellow large selfheader fruit color size create table selfcreatetable layout layout qvboxlayout layoutaddwidgetselftv selfsetlayoutlayout def popupself pos selftvselectionmodelselectionindexes print irow icolumn menu qmenu quitaction menuaddactionquit action menuexecselfmaptoglobalpos action quitaction qappquit def createtableself create view selftv qtableview selftvsetstylesheetgridlinecolor rgb selftvsetcontextmenupolicyqtcustomcontextmenu selftvcustomcontextmenurequestedconnectselfpopup set table model tm mytablemodelselftabledata selfheader self selftvsetmodeltm set minimum size selftvsetminimumsize hide grid selftvsetshowgridtrue set font font qfontcalibri body selftvsetfontfont hide vertical header vh selftvverticalheader vhsetvisiblefalse set horizontal header properties hh selftvhorizontalheader hhsetstretchlastsectiontrue set column width fit contents selftvresizecolumnstocontents set row height nrows lenselftabledata row xrangenrows selftvsetrowheightrow enable sorting selftvsetsortingenabledtrue return selftv class mytablemodelqabstracttablemodel def initself datain headerdata parentnone args datain list lists headerdata list strings qabstracttablemodelinitself parent args selfarraydata datain selfheaderdata headerdata def rowcountself parent return lenselfarraydata def columncountself parent return lenselfarraydata def dataself index role indexisvalid return qvariant elif role qtdisplayrole return qvariant return qvariantselfarraydataindexrowindexcolumn def headerdataself col orientation role orientation qthorizontal role qtdisplayrole return qvariantselfheaderdatacol return qvariant def sortself ncol order sort table given column number selfemitsignallayoutabouttobechanged selfarraydata sortedselfarraydata keyoperatoritemgetterncol order qtdescendingorder selfarraydatareverse selfemitsignallayoutchanged name main main,3 i would start jeff lamarche scripts github httpsgithubcomjlamarcheiosopenglesstufftreemasterblenderexport the blog post httpiphonedevelopmentblogspotcomblenderioshtml i recall fiddle blender version tuples blinfo dictionary,i coding simple android game opengl es require simple exporter blender really understand python add export scripts blender i tried tutorial httpenwikibooksorgwikiblenderdnoobtoproadvancedtutorialspythonscriptingexportscripts i get working blender i tried copying scriptsaddons directory blender detect i tried manually importing nothing happened i thinking written earlier version all i want write simple exporter exports simple static meshes format like following v vertex indices polygon uv vertex v v v v the tutorial i found made look really simple everything else i found seemed confusing if anyone could write quick exporter script i thankful point right direction and also get working blender thanks reading,1 i get work making sure move distance one issue code end try jump places make sure every move make one reverse till move distance become next destination hint manhattandistance,i working assignment found ai course page berkley website fun i need write depthfirst search pacman game find paththe problem pacman gets stuck i paste code first make i saying clear import util class searchproblem this class outlines structure search problem implement methods objectoriented terminology abstract class you need change anything class ever def getstartstateself returns start state search problem utilraisenotdefined def isgoalstateself state state search state returns true state valid goal state utilraisenotdefined def getsuccessorsself state state search state for given state return list triples successor action stepcost successor successor current state action action required get stepcost incremental cost expanding successor utilraisenotdefined def getcostofactionsself actions actions a list actions take this method returns total cost particular sequence actions the sequence must composed legal moves utilraisenotdefined def tinymazesearchproblem returns sequence moves solves tinymaze for maze sequence moves incorrect use tinymaze game import directions directionssouth w directionswest return sswswwsw def depthfirstsearchproblem search deepest nodes search tree first p your search algorithm needs return list actions reaches goal make sure implement graph search algorithm fig to get started might want try simple commands understand search problem passed print start problemgetstartstate print is start goal problemisgoalstateproblemgetstartstate print start successors problemgetsuccessorsproblemgetstartstate your code here start problemgetstartstate item start openitem state closed path problemisgoalstateopen true return state else open visit openpop closedappendvisit state pathappendstatepop problemisgoalstatevisit true print closed return path else successors problemgetsuccessorsvisit index successors ititerindex dataitnext data closed openappenddata stateappenditnext else print path now read code dfs see open list contains points i visit expanded the path file contains direction set pacman the problem arises i face condition successors i get unvisited pacman takes path leads dead end needs backtrace my open finds solution i able find way provide directions backtracing path list if go httpinsteecsberkeleyeducsspprojectssearchsearchhtml download zip paste code searchpy dfs search understand problem,1 here hack i far suggestions improvement welcome class tobject def initself kwds k v kwdsitems clsname selfclassname evalcompile class dummy passn class formatclsname k exec dummy dict dclsnamedict k nextk k k setattrself k v tx z ttx tty ttz,i run situation pseudo private class member names getting mangled using setattr exec in class t def initself kwargs selfx k v kwargsitems setattrself k v in tydict out tx i tried execselfs k v well result in class t def initself kwargs selfx k v kwargsitems execselfs k v in tzdict out tx z doing selfdictss selfclassname k v would work dict readonly attribute is another way i dynamically create psuedo private class members without hardcoding name mangling a better way phrase question what python “under hood” encounters double underscore selfx attribute set is magic function used mangling,1 you change loadimage function expect opened filelike object def loadimagef data fileread called two functions one expects path string contains data stringio import stringio def loadimagefrompathpath openpath rb f loadimagef def loadimagefromstrings sio stringios try loadimagesio finally sioclose,i design question i function loadimage loading image file now accepts string file path but i also want able load files physical disk eg generated procedurally i could accept string could know string file path file data i could add extra boolean argument specify sound clean any ideas it something like def loadimagefilepath file openfilepath rb data fileread stuff data the version would def loadimagedata stuff data how function accept filepath data guess,2 memcache like gae service done using remote procedure call response time generated if machinenetwork busy might lag the real question way calling memcache times single request there two ways go work around use getmulti retreive values possible use async memcache start retrving values wait use ready,please see appstats log randomly memcache calls take extraordinarily longer others these get calls memcached counters absolutely nothing different calls taking longer others any explanation,1 of course stops first match return function instead either populate array loop return end create generator using yield iteration raise stopiteration case nothing found the first approach simpler closer solution import os csv def chkifexists files acsv bcsv ccsv found fname files ospathisfilefname fname acsv hashcolumn filepathnum elif fname bcsv hashcolumn filepathnum elif fname ccsv hashcolumn filepathnum foundappend fname fname hashcolumn hashcolumn filepathnum filepathnum return found found chkifexists found print no files scan else f found print f fname f hashcolumn f filepathnum,python noob please gentle in current program i list files may may reside current directory if reside directory i want able assign values later used functions if file reside directory assigned values file exist anyway the code i far import os csv def chkifexists files acsv bcsv ccsv fname files ospathisfilefname fname acsv hashcolumn filepathnum elif fname bcsv hashcolumn filepathnum elif fname ccsv hashcolumn filepathnum return fname hashcolumn filepathnum def removedupesinfile outfile hashcolumn fname hashcolumn filepathnum chkifexists r fileinfile rb r csvreaderr w fileoutfile wb w csvwriterw hashes set row r rowhashcolumn wwriterowrow hashesaddrowhashcolumn rowhashcolumn hashes wwriterowrow hashesaddrowhashcolumn wclose rclose def bakcountorigfile origfile this function creates bak file original row count determine number rows removed osrenameorigfile origfilebak count lenopenorigfilebakreadlines print count osrenameorigfile origfile count lenopenorigfilereadlines print count print strcount count duplicate rows removed strorigfile def cleanandprettify print removing duplicate rows input files fname hashcolumn filepathnum chkifexists removedupesfname ospathsplitextfname csv hashcolumn bakcount fname ospathsplitextfname csv cleanandprettify the problem i running code runs list stops first valid file finds i sure i completely thinking wrong way i thought i right current output program acsv bcsv ccsv present directory removing duplicate rows input files duplicate rows removed acsv the desired output removing duplicate rows input files duplicate rows removed acsv duplicate rows removed bcsv duplicate rows removed ccsv continue next portion creating bak files the output program without csv files directory unboundlocalerror local variable hashcolumn referenced assignment,1 the checking condition using suggested way compare two strings python unless explicitly interning string use comparison guarantee would return true use instead alternatively following files acsv bcsv ccsv filedict acsv filedict bcsv filedict ccsv print fnamefiledictfname fname files filedicthaskeyfname ospathisfilefname,python noob please gentle in current program i list files may may reside current directory if reside directory i want able assign values later used functions if file reside directory assigned values file exist anyway the code i far import os csv def chkifexists files acsv bcsv ccsv fname files ospathisfilefname fname acsv hashcolumn filepathnum elif fname bcsv hashcolumn filepathnum elif fname ccsv hashcolumn filepathnum return fname hashcolumn filepathnum def removedupesinfile outfile hashcolumn fname hashcolumn filepathnum chkifexists r fileinfile rb r csvreaderr w fileoutfile wb w csvwriterw hashes set row r rowhashcolumn wwriterowrow hashesaddrowhashcolumn rowhashcolumn hashes wwriterowrow hashesaddrowhashcolumn wclose rclose def bakcountorigfile origfile this function creates bak file original row count determine number rows removed osrenameorigfile origfilebak count lenopenorigfilebakreadlines print count osrenameorigfile origfile count lenopenorigfilereadlines print count print strcount count duplicate rows removed strorigfile def cleanandprettify print removing duplicate rows input files fname hashcolumn filepathnum chkifexists removedupesfname ospathsplitextfname csv hashcolumn bakcount fname ospathsplitextfname csv cleanandprettify the problem i running code runs list stops first valid file finds i sure i completely thinking wrong way i thought i right current output program acsv bcsv ccsv present directory removing duplicate rows input files duplicate rows removed acsv the desired output removing duplicate rows input files duplicate rows removed acsv duplicate rows removed bcsv duplicate rows removed ccsv continue next portion creating bak files the output program without csv files directory unboundlocalerror local variable hashcolumn referenced assignment,1 it pretty simple generate sound memory eg the important part generating tone storing clip encompassed code generates tone assigns clip public void generatetone throws lineunavailableexception clipnull clipstop clipclose else clip audiosystemgetclip boolean addharmonic harmonicisselected int intsr integersamplerategetselecteditemintvalue int intfpw framesperwavelengthgetvalue float samplerate floatintsr oddly sound loop well less around wavelengths int wavelengths byte buf new byteintfpwwavelengths audioformat af new audioformat samplerate sample size bits channels true signed false bigendian int maxvol forint iintfpwwavelengths double angle floatifloatintfpwmathpi bufigetbytevalueangle ifaddharmonic bufigetbytevalueangle else bufi bufi try byte b buf audioinputstream ais new audioinputstream new bytearrayinputstreamb af buflength clipopen ais catchexception e eprintstacktrace beeperjava this self contained code shows gui seen it hybrid work either free floating frame embedded applet import javaawt import javaawtevent import javaxswing import javaxswingevent import javaxswingborder import javatextdecimalformat import javaxsoundsampled import javaiobytearrayinputstream beeper presents small loopable tone heard clicking code key it uses clip loop sound well access clip gain control author andrew thompson version license lgpl public class beeper extends japplet beeperpanel bp public void init bp new beeperpanel getcontentpaneaddbp validate string samplerate getparametersamplerate sampleratenull try int sr integerparseintsamplerate bpsetsampleratesr catchnumberformatexception usedefault string fpw getparameterfpw fpwnull try int fpw integerparseintfpw jslider slider bpgetframesperwavelengthslider slidersetvalue fpw catchnumberformatexception usedefault boolean harmonic getparameteraddharmonicnull bpsetaddharmonicharmonic bpsetupsound getparameterautoloopnull string loopcount getparameterloopcount loopcountnull try integer lc integerparseintloopcount bploop lcintvalue catchnumberformatexception donotloop public void stop bploopsoundfalse public static void mainstring args swingutilitiesinvokelaternew runnable public void run jframe f new jframebeeper fsetdefaultcloseoperation jframeexitonclose beeperpanel beeperpanel new beeperpanel fsetcontentpanebeeperpanel fpack fsetminimumsize fgetsize fsetlocationbyplatformtrue fsetvisibletrue the main ui beeper class beeperpanel extends jpanel jcombobox samplerate jslider framesperwavelength jlabel frequency jcheckbox harmonic clip clip decimalformat decimalformat new decimalformat beeperpanel supernew borderlayout use current os look feel try uimanagersetlookandfeel uimanagergetsystemlookandfeelclassname swingutilitiesupdatecomponenttreeuithis catch exception e eprintstacktrace setpreferredsize new dimension jpanel options new jpanel boxlayout bl new boxlayoutoptionsboxlayoutyaxis optionssetlayoutbl integer rates new integer new integer new integer new integer samplerate new jcomboboxrates sampleratesettooltiptextsamples per second sampleratesetselectedindex jpanel psamplerate new jpanelnew borderlayout psampleratesetbordernew titledbordersample rate psamplerateadd samplerate samplerateaddactionlistenernew actionlistener public void actionperformedactionevent ae setupsound optionsadd psamplerate framesperwavelength new jsliderjsliderhorizontal framesperwavelengthsetpainttickstrue framesperwavelengthsetmajortickspacing framesperwavelengthsetminortickspacing framesperwavelengthsettooltiptextframes per wavelength framesperwavelengthaddchangelistener new changelistener public void statechangedchangeevent ce setupsound jpanel pfpw new jpanel new borderlayout pfpwsetbordernew titledborderframes per wavelength pfpwadd framesperwavelength optionsadd pfpw jpanel bottomoption new jpanel new borderlayout harmonic new jcheckboxadd harmonic false harmonicsettooltiptext add harmonic second channel one octave harmonicaddactionlistener new actionlistener public void actionperformedactionevent ae setupsound bottomoptionadd harmonic borderlayoutwest frequency new jlabel bottomoptionadd frequency borderlayoutcenter optionsaddbottomoption add options borderlayoutnorth jpanel play new jpanelnew borderlayout playsetborder new emptyborder jbutton bplay new jbuttoncode key bplaysettooltiptextclick make tone dimension preferredsize bplaygetpreferredsize bplaysetpreferredsize new dimension intpreferredsizegetwidth intpreferredsizegetheight todo comment try keylistener bplaysetfocusablefalse bplayaddkeylistener new keyadapter override public void keypressedkeyevent ke loopsoundtrue bplayaddmouselistener new mouseadapter override public void mousepressedmouseevent loopsoundtrue override public void mousereleasedmouseevent loopsoundfalse playadd bplay try clip audiosystemgetclip final floatcontrol control floatcontrol clipgetcontrol floatcontroltypemastergain final jslider volume new jslider jslidervertical intcontrolgetminimum intcontrolgetmaximum intcontrolgetvalue volumesettooltiptextvolume beep volumeaddchangelistener new changelistener public void statechangedchangeevent ce controlsetvalue volumegetvalue playadd volume borderlayouteast catchexception e eprintstacktrace addplay borderlayoutcenter setupsound public void loopint loopcount clipnull cliploop loopcount public void setaddharmonicboolean addharmonic harmonicsetselectedaddharmonic provides slider determining frames per wavelength primarily allow easy adjustment host classes public jslider getframesperwavelengthslider return framesperwavelength sets sample rate one four allowable rates is ignored otherwise public void setsamplerateint sr switch sr case sampleratesetselectedindex break case sampleratesetselectedindex break case sampleratesetselectedindex break case sampleratesetselectedindex break default sets label current frequency settings public void setfrequencylabel float freq getfrequency harmonicisselected frequencysettext decimalformatformatfreq decimalformatformatfreqf hz else frequencysettext decimalformatformatfreq hz generate tone inform user settings public void setupsound try generatetone setfrequencylabel catchexception e eprintstacktrace provides frequency current settings sample rate amp frames per wavelength public float getfrequency integer sr integersamplerategetselecteditem int intst srintvalue int intfpw framesperwavelengthgetvalue return floatintstfloatintfpw loops current clip commence false passed public void loopsoundboolean commence commence clipsetframeposition cliploop cliploopcontinuously else clipstop generates tone assigns clip public void generatetone throws lineunavailableexception clipnull clipstop clipclose else clip audiosystemgetclip boolean addharmonic harmonicisselected int intsr integersamplerategetselecteditemintvalue int intfpw framesperwavelengthgetvalue float samplerate floatintsr oddly sound loop well less around wavelengths int wavelengths byte buf new byteintfpwwavelengths audioformat af new audioformat samplerate sample size bits channels true signed false bigendian int maxvol forint iintfpwwavelengths double angle floatifloatintfpwmathpi bufigetbytevalueangle ifaddharmonic bufigetbytevalueangle else bufi bufi try byte b buf audioinputstream ais new audioinputstream new bytearrayinputstreamb af buflength clipopen ais catchexception e eprintstacktrace provides byte value point sinusoidal wave private static byte getbytevaluedouble angle int maxvol return new integer intmathround mathsinanglemaxvol bytevalue,just wondering library java like module pyaudiere python simply allows create tones play like sample python code device audiereopendevice tone devicecreatetone create hz tone toneplay tonestop this simply assigns variable default sound device makes tone device plays stops are libraries like simple use i appreciate feedback thanks d,3 i wrote subscription list parser purpose it called listparser written python i tested opml file appears parse file perfectly it also make feeds labels available if ever used feedparser interface familiar import listparser lp lpparse httpsdldropboxcomugooglereadersubscriptionsxml lendfeeds dfeedsurl u httplongreadscomrss dfeedstags u reading it possible create file feed urls using script similar import listparser lp lpparse httpsdldropboxcomugooglereadersubscriptionsxml f open homeusernamerssawarerssfeedstxt w dfeeds fwriteiurl n fclose just replace username actual username done,i piece software called rssaware i trying use it basically desktop feedchecker checks rss feeds updated gives notification ubuntu notifyosd system however know feeds check list feed urls text file rssawarerssfeedstxt one list linebreak feed url something like httpexamplecomfeedxml httpothersiteorgfeedxml httpothergreatsitenetrssxml seems pretty simple right well list feeds i like use exported google reader opml file type xml i clue parse output feed urls it seems like pretty straight forward yet i stumped i love anyone could give implementation python ruby something i could quickly prompt a bash script would awesome thanks much help i really weak programmer would love learn basic parsing edit also opml file i trying extract feed urls,2 since python suggests using urllib instead urllib i take test urlliburlopen wget the result takes nearly time download filesometimes urllib performs even better the advantage wget lies dynamic progress bar show percent finished current download speed transferring the file size test mb i used cache module python i aware wget works downloading big size file,i task download gbs data website the data form gz files file mb size the easy way get files use wget r np a files url this donwload data recursive format mirrors website the donwload rate high mbsec but play around i also using python build urlparser downloading via python urlretrieve damm slow possible times slow wget the download rate kbsec i use htmlparser parsing href tags i sure happening are settings thanks,1 the reason might need instead vice versa string contains triple quote this string contains use triplesinglequotes this string contains use tripledoublequotes if string contains triplesinglequotes tripledoublequotes escape one extremely rare situation,learn python hard way exercise tabbycat ti tabbed persiancat i splitnon line backslashcat i cat fatcat i list cat food fishies catnipnt grass print tabbycat print persiancat print backslashcat print fatcat use triplesinglequote instead can see might use instead i see i might use instead it gives output can someone explain i would use triplesinglequote instead tripledoublequote what difference,3 to find error code replace code name formcleaneddata name qdict name name qobjs qqdictk formcleaneddatak k qdictkeys formcleaneddatagetk none searchresults groupobjectsselectrelatedfilterqobjs by one qnone kv formcleaneddataitems q q amp q k v else q q k v searchresults groupobjectsselectrelatedfilter q but really control query need write condition condition qs name formcleaneddata name name qname q namecontains name qsappendqname fromdate formcleaneddata fromdate fromdate qfrom q dategte fromdate qsappendqfrom todate formcleaneddata todate todate qtodate q dategte todate qsappendqtodate qnone x qs q q amp x else q x searchresults groupobjectsselectrelatedfilterq,i making search form django i struggling processing form view my code class searchformformsform name formscharfieldlabelname maxlength requiredfalse fields def searchrequest requestmethod post form searchformrequestpost formisvalid name formcleaneddata name qdict name name qobjs qqdictk formcleaneddatak k qdictkeys formcleaneddatagetk none searchresults groupobjectsselectrelatedfilterqobjs response success searchresults return httpresponsesimplejsondumpsresponse ensureasciifalse mimetype applicationjavascript else form searchform return rendertoresponsemainsearchhtml form form contextinstancerequestcontextrequest i get error cannot resolve keyword u name field choices datesubmitted id name parameters i realized field unicode tried converting str encode ascii still gives error i new django help would appreciated thanks,1 because ospathabspath ospathdirname ospathbasename hold rather ospathdirnamefilename ospathbasenamefilename filename both dirname basename split passed filename components without taking account current directory if want also consider current directory explicitly to get dirname absolute path use ospathdirnameospathabspathfile,i want get path current directory py file executing a simple file dtestpy code import os print osgetcwd print ospathbasenamefile print ospathabspathfile print ospathdirnamefile it wired output d testpy dtestpy empty i expecting results getcwd pathdirname given ospathabspath ospathdirname ospathbasename ospathdirnamefile returns empty,3 instead where keysopoint and keycrdgnssraw keycrdrawmeas i guess meant where keysopoint keycrdrawmeas and keycrdgnssraw keycrdrawmeas i also recommend start using join syntax makes errors join conditions less likely select name c c c numofepochs hdop vdop numofgpssats secondsfrom from tblcrdrawmeas join tblcrdgnssraw on keycrdgnssraw keycrdrawmeas join tblsopoints on keysopoint keycrdrawmeas this provides number benefits including easier read easier modify use outer joins need,i try select three tables one query three sql tables i select lines per table import sqlite database sqliteconnect ftsj cursor databasecursor cursorexecuteselect name c c c numofepochs hdop vdop numofgpssats secondsfrom tblsopoints tblcrdgnssraw tblcrdrawmeas keysopoint keycrdgnssraw keycrdrawmeas results cursorfetchall i try line enumerateresults print line gives lines when i select two tables one query everything ok i get lines how i select three tables one query get right number lines table loop multiplied number lines,2 this problem might related question python how i pass variable reference it how i work around issue you need pass value modified modify numbers cannot modified changed referring referring instead cannot cause become viceversa in case natural way also notice silly thing using bunch related similarlynamed variables parallel fix well replacing sequence the list type modifiable sequence you need pass list instead numeric quantity indicate element list replace except actually need pass list already part self class portfolioobject def initself selfquantity selfcash def strself return fselfquantity selfquantity selfquantity selfcash def buyself stocktobuy amounttobuy price commission selfquantitystocktobuy amounttobuy cost price amounttobuy selfcash cost commission for flexible solution might consider idea association stock names quantities stock knows stocks client might want future we simply using dict instead a constant commission cost also unrealistic percentage makes sense,i code i trying i figure modify instance attributes i use parameters calling method class portfolioobject def initself selfqtya selfqtyb selfqtyc selfcash def strself return fselfqtya selfqtyb selfqtyc selfcash def buyself stockqty qtytobuy price commission stockqty qtytobuy print stockqty buytransaction price qtytobuy selfcash buytransaction commission p portfolio pbuypqtya print p what seems happening new variable stockqty created buy called i would expect reference attribute qtya would passed instead value this problem might related question python how i pass variable reference how i work around issue,1 pry a ruby repl designed make kind thing less pain there options deal situation use amendline fix line dump current input buffer editor using edit command changes make editor brought back pry session savingquitting use hist replay replay correct lines replstrong text of options typically use amendline simple error edit involved have fun,i bet came across problem like i use shells lot for python ruby irb mongo i use shortcurt like crta go begining crte end crtk clean end but i miss one thing when define multiline block ruby shell python shell miswrite something one statement rewrite almost everything history bring arrow becomes mess lines any tips make less painful,2 get python default parameter value found default value retuned print dictgetname default name,i loaded json data apiresult variable now i need extract particular fields name surname city etc how i verify apiresult jsonloadssomejsondata apiresultget name something name apiresultget surname something surname apiresultget city something city is correct approach looks complicated is way get empty value value found,1 for modest graph sizes good python graphics library provide sufficient primitives address issue for example either pyglet pygame would suitable,i program written python using module networkx create dynamic graph it planer graph vertices remain constant edges change now i looking library allows two things fast quick manner preferably drawing vertices lattice points inside rectangle ie being able select edges vertices change color position weights etc shown picture thanks,1 c well could find one wireshark documentation python support httpwikiwiresharkorgpython,googling give great results is sort api wireshark abstracts away main source code develop programs interact deal data provides edit i appreciate suggestions different ways receive packets i want implement packet injection wireshark sniffing important part project however i sure suggested solution allows packet injection,1 by using ironpython xna instead c xna lose xna crossplatform capabilities you cannot run ironpython xbox windows phone see thread i also suspect able use crossplatform xna implementations eg exen also course performance disadvantage using ironpython instead c i say performance differences ironpython python implementations might implementations really used xna anyway other i really think functional differences if target windows xna ironpython fine game development although choosing xna platform serious project c probably better primary language choice better supported,i enjoy multimedia libraries python however i curious ironpython xna could contender game development is reason hear often also meant less topic regarding python ironpython i know languages may better suited i curious python jython cython ironpython etc,2 i made good experiences using timesleepseconds webdriverfirefoximplicitlywaitseconds the first one pretty obvious wait seconds stuff for selenium scripts sleep seconds range works i run laptop server time wait wider range i use implicitlywait i usually use implicitlywait really enough an implicit wait tell webdriver poll dom certain amount time trying find element elements immediately available the default setting once set implicit wait set life webdriver object instance,how i write function selenium wait table class identifier python i devil time learning use selenium python webdriver functions,3 you recreating entity time code look like this create object return usergetorinsertkeynameidd uniqueuserid iduniqueuserid name currentname this create object update properties you change value keyname user usergetorinsertkeynameidd uniqueuserid iduniqueuserid username name userput return user,i db model one property autonowaddtrue but looks like work i expected updated time put called i use keyname secondthirdn call put really create new record update here code class userdbmodel id dbintegerproperty added dbdatetimepropertyautonowaddtrue name dbstringproperty handler called several times def getself user userkeynameiduniqueuserid userid uniqueuserid username currentname userput,2 there good way preserve type sequence as guessed really want convert answer end type want it quite likely need think hard one shortcut might help decide convert types builtin sequences also constructors create sequences def stripcommonpathprefixseq blah blah return prefix typeseqresult,if i function operate sets lists return modified form sequence way preserve sequence type still use comprehension for example following i call stripcommonpathprefix set works undesired side effect converting set list is possible maintain type still using comprehension without directly check isinstance return correct type based if would cleanest way def commonpathprefixseq return ospathcommonprefixseqrpartitionospathsep ospathsep def stripcommonpathprefixseq prefix commonpathprefixseq prefixlen lenprefix return prefix pprefixlen p seq thankyou sorry basic question i starting learn python ps i using python,3 as said response comment optional installable component openoffice see introduction python ooo page openoffice wiki installation details,how make python python know pyuno libreoffice when i import uno python says knows module uno this question came question,1 here i inside libreoffice directory program directory pythonexe i use python version i import uno,how make python python know pyuno libreoffice when i import uno python says knows module uno this question came question,1 it sounds like trying create gui acts procedurally work guis procedural code run linearly functions call callbacks return values what asking unique tkinter this nature event based gui programming callbacks return anything caller event rather function roughly speaking must use global object sort store data typically called model it global variable might database object sort in case must exist globally must accessible whole gui often access provided third component called controller it interface gui view data model these three components make called modelviewcontroller pattern mvc the model view controller three different objects often gui controller object for small programs works quite well gui components talk directly data model for example could class represents window inherits tkintertoplevel it attribute represents data edited when user selects new main window something like selftileset tilesetfilename that sets attribute named tileset gui object named self instance tileset class specific given filename later functions manipulate data use selftileset access object for functions live outside main window object example save function main window either pass object argument use window object controller asking something tileset here brief example import tkinter tk import tkfiledialog import datetime class sampleapptktk def initself args kwargs tktkinitself args kwargs selfwindows menubar tkmenuself selfconfiguremenumenubar filemenu tkmenuself filemenuaddcommandlabelnew commandselfnewwindow filemenuaddcommandlabelsave all commandselfsaveall menubaraddcascadelabelwindow menufilemenu label tklabelself textselect new window menu labelpackpadx pady def saveallself ask window object acting view controller save data window selfwindows windowsave def newwindowself filename tkfiledialogaskopenfilename filename none selfwindowsappendtilewindowself filename class tilewindowtktoplevel def initself master filename tktoplevelinitself master selftitles tile editor filename selffilename filename create instance tileset methods class reference tile set selftileset tilesetfilename label tklabelself textmy filename filename labelpackpadx pady selfstatus tklabelself text anchorw selfstatuspacksidebottom fillx def saveself method acts controller data allowing objects request data saved datetimedatetimenow selfstatusconfiguretextsaved strnow class tilesetobject def initself filename selfdata name main app sampleapp appmainloop,hopefully fall general discussion topic since i like resolving issues efficient manner giant debate general approach gui programming absolute best so i started gui programming tkinter long story short code getting pretty ugly pretty quickly i trying create tilebased map editor video game my main issues seem inability callbacks return values inability transfer data windows easily i assume reason i see issues i using functions lot i using classes for instance load tileset window handled entirely functionally clicking menu option main window calls function loads new window from within window i create open file dialog looking image modify canvas displaying image i press enter key draws appropriate grid image function function function what looks like really bad practice inclusion extra arguments compensate for example i create tileset instance tileset class created sent back main window appropriate information displayed i list loaded tilesets global variable even bad practice everything dealing root window global scope yay callback functions return values i pass list argument load tileset window function passes argument create tileset function called click appropriate button window actually needed i add newly created tileset list passing arguments function hierarchy like seems like horrible idea it gets confusing horrible writing modular code generally seems unnecessary my attempt fixing problem would write class representing whole gui custom made window classes gui class create reference actually store relevant data that take care issues transferring data windows hopefully would cut gratuitous use lambda functions callbacks well but i wondering best way or least close i rather start rewriting end another system sloppy confusing different way i know methods bad i really know best approach would i getting lot advice specific things none structure program whole any help would greatly appreciated,3 for example i set time zone gmt import datetime time pytz tz pytzfixedoffset dt datetimedatetime tzinfopytzutc tm dtastimezonetztimetuple tm timestructtimetmyear tmmon tmmday tmhour tmmin tms ec tmwday tmyday tmisdst timemktimetm mktime takes time tuple based local time utc datetime object first adjusted local time,python import pytz import time import datetime timemktimedatetimedatetime tzinfopytzutctimetuple result boost auto boostposixtimeptimeboostgregoriandate auto b boostposixtimeptimeboostgregoriandate unix epoch boostposixtimetimeduration x b stdcerr xtotalseconds stdendl result difference hour why,1 urlparseparseqsl used parse parameters but likely since framework using one handle,i trying analyse different ways python connection webserver cgi fastcgi modpython wsgi django framework so many ways exist parse getpost parameters python are differ one connection another i saw question cgi django etc considered but fastcgi is way cgi and modpython wsgi i take interest usable popular ways getting request parameters it parsing particular parameter namevalue entire query string parsing where i read different apis there many connection methods frameworks i get confused thanks lot nikolai,1 goats variable names refer type,is better name list variables list since conflicted python reserved keyword then better naming inputlist sounds kinda awkward i know problemspecific say i quick sort function quicksortunsortedlist still kinda lengthy since list passed sorting function clearly unsorted context any idea,3 i like name plural whatever so example i list names i call names i write name names i think looks pretty nice but generally sanity name variables know name this convention added benefit typeagnostic like python names iterable object tuple dict custom iterable object you use name names tuple called nameslist would weird added comment there situations using canonical variable like index short loop ok usually used way if variable used one page worth code see entire lifetime give sensible name,is better name list variables list since conflicted python reserved keyword then better naming inputlist sounds kinda awkward i know problemspecific say i quick sort function quicksortunsortedlist still kinda lengthy since list passed sorting function clearly unsorted context any idea,3 why use unsorted i prefer names communicate ideas data types there special cases type variable important but cases obvious context like case quick sort obviously working list,is better name list variables list since conflicted python reserved keyword then better naming inputlist sounds kinda awkward i know problemspecific say i quick sort function quicksortunsortedlist still kinda lengthy since list passed sorting function clearly unsorted context any idea,1 what l,is better name list variables list since conflicted python reserved keyword then better naming inputlist sounds kinda awkward i know problemspecific say i quick sort function quicksortunsortedlist still kinda lengthy since list passed sorting function clearly unsorted context any idea,1 python stands readability so basically name variables promote readability see pep you general rule consistency break consistency following situations when applying rule would make code less readable even someone used reading code follows rules to consistent surrounding code also breaks maybe historic reasons although also opportunity clean someone else mess true xp style also use function naming rules lowercase words separated underscores necessary improve readability all taken pep,is better name list variables list since conflicted python reserved keyword then better naming inputlist sounds kinda awkward i know problemspecific say i quick sort function quicksortunsortedlist still kinda lengthy since list passed sorting function clearly unsorted context any idea,3 i use naming convention based descriptive name type i think i learned jeff atwood blog post i find goatslist goat goatslist goatbleat cowhash etc anything complicated listlisthashlist i make class,is better name list variables list since conflicted python reserved keyword then better naming inputlist sounds kinda awkward i know problemspecific say i quick sort function quicksortunsortedlist still kinda lengthy since list passed sorting function clearly unsorted context any idea,1 sqlite need sleep commit sqlite synchronous inprocess time commit returns operation completed but dangerous use sqlite one thread,i scripted update sqlite database clementine media player entries found end database corrupted so i strongly suspected write operations forloop enough time complete next loop starts i tested timesleep seconds update call seconds periodic commit this seems work whole process became really slow sample code commitinterval artistcounter artist allartists artistcounter record albumratings album record rating record dbcursorexecute update songs set rating where lowersongsartist and lowersongsalbum and rating rating artist album rating short sleep shortsleepsec timesleepshortsleepsec artistcounter commitinterval dbcommit artistcounter long sleep sleepsec print sleep seconds sleepsec timesleepsleepsec here questions should i really sleep update commit one how i calculate long i sleep calls thanks much,1 decorators special syntax rules decorators return mathematical description they callable your function partially applied starmap functools import partial itertools import starmap def foof return partialstarmap f,class fooobject def initselff selff f def callselfargslist def wrappedfargslist return selffargs args argslist return wrappedfargslist name main class abcobject foo def fabc return abc range b range c range data listzipabc printabcfdata i wrote years back when decorate function fx foo becomes flist xs what process called what what functional programming name its currying i know simple mapflist xs could done what decoratorsoperation decorating called mathematically,1 new versions pydev django integration try looking also might help defining libraries forced builtins i use get pyqt autocomplete working,today i reinstalled os ubuntu installed django pydev i ran one programs import django framework it works pydev detect project django simple django captcha python libraries what i fix problem actually i must say i configured pythonpath pydev,1 def findadjacentcoordsdb lat lon step find coords step range lat lon xxx disregard values near latitude longitude coordsrange latstep latstep lonstep lonstep return dbexecuteselect lat lon coords lat lat lon lon coordsrangefetchall full example rtree index note code include boundaries for efficient range queries millions coordinates might need sqlite rtree index for entries approach takes seconds function uses rtree requires less ms for entries âµs vs âµs rtreebased solution data test disclaimer the numbers code i posted i run machine,i table named coords following columns namelatlonund import sqlite database sqliteconnect geoidadb cursor databasecursor cursorexecuteselect lat lon und coords results cursorfetchall every line table stores coordinates one point g r distance point point always decimal equal what i would like achieve find nearest adjacent points around given latitude longitude decimal we keep mind latitude longitude four points fill quite simple condition excess lat lon adjacent point lat lon given point must lessequal treat value max radius divisive sought neighboring points given one example given point nearest adjacent points taken coords table given points stored another database c latitude c longitude database sqliteconnect ftsj cursor databasecursor cursorexecuteselect c c tblsopoints results cursorfetchall how i put query using python sorry code something wrong formating,1 if add custom manager model default manager objects created either add class definition stick using custom manager,fragment modelspy class hardwaretypemodelsmodel type modelscharfieldblank false maxlength verbosenametype description modelstextfieldblank true verbosenamedescription slug modelsslugfieldunique true maxlength verbosename slug class softwaretypemodelsmodel type modelscharfieldblank false maxlength verbosenametype description modelstextfieldblank true verbosenamedescription slug modelsslugfieldunique true maxlength verbosename slug sw softwaretypeobjectsgetslug unix sw softwaretype unix hw hardwaretypeobjectsgetslug printer traceback recent call last file console line module attributeerror type object hardwaretype attribute objects i see happens anyone help edit sorry sent code problem solved another class i hardwaretype modelsmanytomanyfieldhardwaretype verbosenamehardware type change hardwaretype hwtype works fine i know cause problem,3 you get list keys keys shuffle iterate list indexing original dict or use items shuffle iterate,how i iterate items dictionary random order i mean something randomshuffle dictionary,3 as ethan furman answered previous question in python represent calls functions represent indexing mapping so words probably want stepfield stactual my actual result,i want try add step details expected actual status etc qc run testcase testset python script living outside quality center i come till code given i know add step expected step actual result if anyone knows please help please i want qtp solutions thanks code script name addtsrunpy cpythonpythonexe this script lives locally windows machine python win installed ie dependencies windows machine python pythonwin installed ie qc account connectivity qcserver import wincomclient os tdc wincomclientdispatchtdapioletdconnection tdcinitconnection httpqcserverqcbin tdclogin username password tdcconnect domainname project tsfolder tdctestsettreemanagernodebypath roottestmesubfolder tslist tsfolderfindtestsets testset tsobject tslistitem tsdir ospathdirname testset tsname ospathbasename testset tsfolder tdctestsettreemanagernodebypathtsdir tslist tsfolderfindtestsetstsname tsobject tslistitem tstestfact tsobjecttstestfactory testsettestslist tstestfactnewlist tsinstance testsettestslistitem newitem tsinstancerunfactoryadditemnone newitem run object newitemstatus no run newitemname run newitempost newitemcopydesignsteps copy design steps newitempost steps newitemstepfactorynewlist step steps stepstatus not completed steppost how i change actual result i access actual expected result change stepfield stactual my actual result this works vb python syntax error traceback file interactive input line syntaxerror assign function call hope helps guys if know answer set actual result please help let know thanks amit,1 i would use regular expression import cartoon dan character desperate l dan mickey mouse print research joinl sresrematch object xaa l nothing print research joinl none where string search l list words if search function return none match,i list query terms boolean operator associated like say tom or jerry or desperate and dan or mickey and mouse okay i string containing userdefined input inputstr my question python way determine string defined user contains words query i tried tom jerry desperate dan mickey mouse cartoon dan character desperate print string but give output expect as see i care whether query terms ordered whether string can done am i missing something like library help achieve required functionality many thanks help,1 your data negative loglog plot positive,i need draw logarithmic plots data values already logarithmic scale however matplotlib somehow encounters infinity preparation loglog plot i believe isdecade function value close division occurs def isdecadexbase lx mathlogxmathlogbase return lxintlx any ideas deal problem this code example data set import matplotlibpyplot pyplot listx listy pyplotlogloglistx listy basex basey,1 the getattr method gives attribute given object since global functions attributes module use import functions funcname dosomething f getattrfunctions funcname f there need use import usually needed know module name advance,short version say i string str file functionspy i would like import method whose name stored str how i go i would like something like functionspy import str str evaluated import method str exist after googling i came close i hope funcname str tmp import functionspy globals locals funcname func put thanks advance edit tmi,1 assuming code import module tmp works final step simply func getattrtmp funcname,short version say i string str file functionspy i would like import method whose name stored str how i go i would like something like functionspy import str str evaluated import method str exist after googling i came close i hope funcname str tmp import functionspy globals locals funcname func put thanks advance edit tmi,2 as noted macports installs python version default optlocalbinpython if install python package via macports like basemap normally need run everything macports python don try mix match python instances packages include c extension modules depend packages include c libraries built way compatible way python interpreter built the python installers pythonorg bitonly built compatible range os x versions by default macports builds bit possible tailored systems the safest easiest option long term would switch using macports python ensuring packages need installed macports,i using mac os x i installed python using binary installer httpwwwpythonorg i using along scipy matplotlib scientific computing needs since march without problems recently i need matplotlib library called basemap i followed article httpsmodelinggurunasagovdocsdoc it states easiest way install basemap library macports fink so i tried install basemap via macports i executed command port install pymatplotlibbasemap seems install many things python etc so specific i used macports time using port install pymatplotlibbasemap since i using python the installation seem problems now i tested basemap properly installed running python code example uses basemap graphing but terminal says following coming back prompt traceback recent call last file basemaptestpy line module mpltoolkitsbasemap import basemap file libraryframeworkspythonframeworkversionslibpythonsitepackagesmpltoolkitsbasemapinitpy line module import geoslib netcdftime importerror dlopenlibraryframeworkspythonframeworkversionslibpythonsitepackagesgeoslibso symbol found geosarea referenced libraryframeworkspythonframeworkversionslibpythonsitepackagesgeoslibso expected dynamic lookup what may wrong i know macports installs python version i know effect problem,2 to check whether words list string anyword string word lst example construct list query removing or and query tom or jerry or desperate and dan or mickey and mouse lst term term querysplit term or and string cartoon dan character desperate print anyword string word lst if use research jro suggested forget escape words avoid collisions regex syntax import researchjoinmapreescape lst string print word list string the code assumes query meaning words contains if assuming and binds stronger or ie b c means b c could check whether string satisfies query def queryinstringquery string term querysplit or lst mapstrstrip termsplit and allword string word lst return true return false the could written concisely might less readable def queryinstringquery string return anyallwordstrip string word termsplit and term querysplit or example query tom or jerry and dan print queryinstringquery cartoon jerry false dan tom print queryinstringquery tom happy true tom print queryinstringquery dan likes jerry true jerry dan if want reject partial matches eg dan match danial instead word string could use research add b researchrbsb reescapeword string,i list query terms boolean operator associated like say tom or jerry or desperate and dan or mickey and mouse okay i string containing userdefined input inputstr my question python way determine string defined user contains words query i tried tom jerry desperate dan mickey mouse cartoon dan character desperate print string but give output expect as see i care whether query terms ordered whether string can done am i missing something like library help achieve required functionality many thanks help,1 your code works hw hardwaretypeobjectsgetslug hw hardwaretype hardwaretype object however using keyword type might little dangerous probably would like avoid using,fragment modelspy class hardwaretypemodelsmodel type modelscharfieldblank false maxlength verbosenametype description modelstextfieldblank true verbosenamedescription slug modelsslugfieldunique true maxlength verbosename slug class softwaretypemodelsmodel type modelscharfieldblank false maxlength verbosenametype description modelstextfieldblank true verbosenamedescription slug modelsslugfieldunique true maxlength verbosename slug sw softwaretypeobjectsgetslug unix sw softwaretype unix hw hardwaretypeobjectsgetslug printer traceback recent call last file console line module attributeerror type object hardwaretype attribute objects i see happens anyone help edit sorry sent code problem solved another class i hardwaretype modelsmanytomanyfieldhardwaretype verbosenamehardware type change hardwaretype hwtype works fine i know cause problem,1 if using doctest also specify nose run doctest plugin enabled this trick nosetests withdoctest doctestextensiontxt,when i run nosetests doctestextensiontxt i get ran tests ok why say tests i tests file readmetxt,2 for versions epd include pyhdf need install hdf separately however note pyhdf included versions epdin particular included bit windows epd bit os x epd though bit versions,in enthought python distribution i saw includes pyhdf numpy since includes pyhdf also include hdf i using pylab code moment because i want use module pyhdf package called pyhdfsd and prerequisites hdf library so i still need install hdf i want use pyhdfsd thanks,1 in code def removenonprimespalindromes palindrom palindromes isprimepalindrom palindromesremovepalindrom return palindromes you modifying remove list iterating this recommended may end removing different items intend instead consider list comprehension def removenonprimespalindromes return p p palindromes isprimep,i got something like palindromes course im generating def isprimenumber rangeintnumber numberi return true return false def removenonprimespalindromes palindrom palindromes isprimepalindrom palindromesremovepalindrom return palindromes palindromes removenonprimespalindromes and doesnt remove non primes i figure,3 your return values isprime opposite,i got something like palindromes course im generating def isprimenumber rangeintnumber numberi return true return false def removenonprimespalindromes palindrom palindromes isprimepalindrom palindromesremovepalindrom return palindromes palindromes removenonprimespalindromes and doesnt remove non primes i figure,2 yes text gets immediate text element tag instead get p tags use textcontent get text from lxmlhtml doc textcontent returns text content element including text content children markup so something like import lxmlhtml htmltree lxmlhtmlparse httpwwwgooglecomintlenaboutcorporateindexhtml ptags htmltreexpath p pcontent ptextcontent p ptags print pcontent,i asked question use lxml parse url get p elements back it resolved however fully achieve goal i need consider effect tags inside p the accepted answer provided acorn parse url get p back import lxmlhtml htmltree lxmlhtmlparse httpwwwgooglecomintlenaboutcorporateindexhtml print htmltreexpath ptext however htmltreexpath ptext tags inside p paragraph pieces returned also text tags ignored eg ptext hreflinkhyperlinked texta text currently using htmltreexpath ptext parsed text text more intuitively expected result text hyperlinked text text hence i would like know methods i use parse whole somehow fix interruptions type tags eg i looked lxml xpath documentation i suspect text ptext but i stuck clue change,2 in situation extract desired data z z logical negation boolean array z this logicalnotz,i would like delete selected columns numpyarray this i n array nan nan in print nan nan in z anyisnana axis in print z true false false true in deletea z axis out array nan in example goal delete columns contain nan i expect last command result array how i,1 xmletree import elementtree stringio import stringio c elementtreeiterparsestringio htmlphello hrefworldaphtml ae c print dumping elementtreedumpe print text etext print tail etail print tag etag if xml valid try installing lxml changing xmletree lxmletree hope helps,i asked question use lxml parse url get p elements back it resolved however fully achieve goal i need consider effect tags inside p the accepted answer provided acorn parse url get p back import lxmlhtml htmltree lxmlhtmlparse httpwwwgooglecomintlenaboutcorporateindexhtml print htmltreexpath ptext however htmltreexpath ptext tags inside p paragraph pieces returned also text tags ignored eg ptext hreflinkhyperlinked texta text currently using htmltreexpath ptext parsed text text more intuitively expected result text hyperlinked text text hence i would like know methods i use parse whole somehow fix interruptions type tags eg i looked lxml xpath documentation i suspect text ptext but i stuck clue change,1 you need reproject raster for example interactive python shell osgeo import gdal helpgdalreprojectimage a python example provided test suite more complete documentation provided c function gdalreprojectimage,i looking best way change resolution gdal raster dataset for example i raster pixel size i would like change pixel size interpolating values given pixel output raster so pixel input raster i would like pixels output raster share value if i run gdalwarp tr inputrastertif outputrastertif i get exactly result i looking i would assume i able replicate functionality gdal function i would prefer avoid using call python subprocess class possible,3 because implementation works looking previous character alphanumeric lower cases current character otherwise upper cases that say relatively simple purepython version looks like def titlestring result prevletter ch string prevletterisalpha resultappendchupper else resultappendchlower prevletter ch return joinresult,mystrmadam adam also tried comma mystrtitle madam i m adam i also tried comma this certainly incorrect why would apostrophe considered considered start new word is gotcha i assuming something wrong concept title,3 you could use stringcapwords capitalize words string eg abc â def abc def def capwordss sepnone â â capwordss sep string â â split argument words using split capitalize â â word using capitalize join capitalized words using â â join note replaces runs whitespace characters â â single space â â â â return sep joinxcapitalize x ssplitsep and since title localedependent check locale see intentional localelocaleconv returns database local conventions dictionary title return titlecased version string words start uppercase characters remaining cased characters lowercase for bit strings method localedependent,mystrmadam adam also tried comma mystrtitle madam i m adam i also tried comma this certainly incorrect why would apostrophe considered considered start new word is gotcha i assuming something wrong concept title,1 the title method capitalizes first letter word string makes rest lower case words identified substrings alphabetic characters separated nonalphabetic characters digits whitespace this lead unexpected behavior for example string xx converted xx instead xx httpenwikibooksorgwikipythonprogrammingstringstitlecupperclowercswapcaseccapitalize basically working intended since apostrophe indeed nonalphabetic get unexpected behavior outlined a bit googling shows people feel exactly best thing alternate implementations written see httpmuffinresearchcoukarchivestitlecasepytitlecaseinpython,mystrmadam adam also tried comma mystrtitle madam i m adam i also tried comma this certainly incorrect why would apostrophe considered considered start new word is gotcha i assuming something wrong concept title,1 the problem title case culturally dependent concept even english many corner cases fit see also httpbugspythonorgissue if want something better need think kinds texts want handle means others incorrectly write function,mystrmadam adam also tried comma mystrtitle madam i m adam i also tried comma this certainly incorrect why would apostrophe considered considered start new word is gotcha i assuming something wrong concept title,1 integer division n p syntax short n n p except value n modified directly supports,i researching information topic trial division i came across symbol python i got code example says n p i tell supposed mean research continues bring poor results terms webpages any help appreciated thank,3 floor division operator therefore simply inplace floor division operator,i researching information topic trial division i came across symbol python i got code example says n p i tell supposed mean research continues bring poor results terms webpages any help appreciated thank,1 when see operator followed performing operation assigning variable for example x means x x add x the operator specifically integer devision instead floating point division for example gives gives python therefore x means divide x integer division fashion store value back x it equivalent x x,i researching information topic trial division i came across symbol python i got code example says n p i tell supposed mean research continues bring poor results terms webpages any help appreciated thank,2 no lxml parse whole page guaranteed find individual bit parse whole page obviously download whole page but see also unutbu’s answer potential partial downloadingparsing approach and although i believe one make http requests part file i think via range header that’s guaranteed supported server side it’s shame http doesn’t include method sending xpath query server along page request results running query page sent back,i sure possible lxml documentation good can i example use something like import lxmlhtml lx x lxparse httpwebinfopagehtml xxpath somethinginteresting similar i download whole page if lxml python module,1 you could try incremental parsing import urllib import lxmlhtml lh request partial download url httpwwwpythonorg req urllibrequesturl reqheaders range bytesss f urlliburlopenreq contentfread printcontent incremental parsing parserlhhtmlparser parserfeedcontent x parserclose xxpath link printy yields element link dcaac element link dcadc element link dcbc,i sure possible lxml documentation good can i example use something like import lxmlhtml lx x lxparse httpwebinfopagehtml xxpath somethinginteresting similar i download whole page if lxml python module,2 i normally use mysolr projects httpmysolrredtunaorg,i want use lucene solr python there seems multiple apis purpose they seem suffer dependency hell stability issues solr doesnt ship python bindings anymore and i cant find documentation user familiar solr i leaning sunburnt pysolr solrpy mature is evaluation correct please recommend stable python bindings solr good standalone presuppose solr knowledge documentation or i learn interact servlet make use existing documentation,2 it boils two things import python function import package using string name package it returns new object represents imported package so foo import bar import package named bar store reference objects local object variable foo from pep declarenamespace mechanism splitting single python package across multiple directories disk so import pkgresources declarenamespacename import symbols pkgresources package add namespace whose name stored name if code mynamespaceinitpy name mynamespace symbols pkgresources added namespace package named mynamespace import used rather import extra symbol left named pkgresources see question discussion older mechanism achieving effect,in initpy files modules i saw single line import pkgresources declarenamespacename what people use suppose related dynamic importing creating namespace runtime,3 it looks like packing window canvas creating window object i honestly never done i think packing good when create widget object canvas expand fill canvas what need create binding configure event canvas this event fire whenever canvas changes size times you resize frame fit width canvas since say prefer using single frame nest rows inside probably easiest solution but single frame grow shrink fit canvas configure binding make sure configure scrollregion canvas adding frame canvas using createwindow it looks like forgetting commentedout code would definitely prevent canvas scrolling,i trying set scrollable series frames i nested canvas below i included sample code demonstrates problem however i three issues frame c seem expand horizontally fill canvas if i use multiple frames c canvas scrolls i try nest framerow single frame c canvas longer scrolls with multiple frames c last framerow cut buttons left right demonstrate behavior i get buttons nested canvas i prefer using single frame c nesting framerows i would need scrolling work properly import tkinter import framerow root tk roottitletesting containerframe frameroot containerframeconfigbgred containerframepacksidetop fillboth expand frame showing proper behavior framecontainerframe bgblack apacksidetop fillx expand btnleft buttona btnleftconfigtextleft btnleftpacksideleft fillx expand btnright buttona btnrightconfigtextright btnrightpacksideright fillx expand canvas canvas canvascontainerframe scrollbar scrollbarcontainerframe orientvertical scrollbarconfigcommandcanvasyview canvasconfigbgblue yscrollcommandscrollbarset scrollbarpacksideright filly canvaspacksideleft fillboth expand multiple frames within canvas framerow range c range r xrange cr framecanvas crconfigbggreen framerowr framerowframerow framerowrsetframecr framerowrsetrowr framerowrcreaterow crpacksidetop fillx expand canvascreatewindow r windowcr anchornw canvasconfigscrollregion canvasbboxall or single frame within canvas c framecanvas cconfigbggreen framerow range r xrange framerowr framerowframerow framerowrsetframec framerowrsetrowr framerowrcreaterow cpacksidetop fillx expand canvascreatewindow windowc anchornw rootmainloop the framerow class defined tkinter import class framerow frame default row def setframeself frame selfframe frame def setrowself row selfrow row def createrowself selfframerow frameselfframe selfframerowconfigbgyellow selfframerowpacksidetop fillx expand selfbtn buttonselfframerow selfbtnconfigtextbutton strselfrowa selfbtnpacksideleft fillx expand selfbtn buttonselfframerow selfbtnconfigtextbutton strselfrowb selfbtnpacksideright anchore fillx expand is something i missing getting frames c expand width canvas am i something wrong scrolling single frame c are decent tutorials examples show i thanks,1 convert string map int function mapint str,i writing program calculates check digit isbn number i read user input nine digits isbn integer variable multiply last digit second last digit how i split integer constituent digits as basic homework exercise i supposed use list,1 if option use free tools written python sympy might work could well simpler use mathematica,i integer matrices moderate size hundred rows i need solve equations form ax b b standard basis vector a one matrices i using numpylinalglstsq purpose rounding errors end significant how i carry exact symbolic computation ps i really need code efficient i concerned ease coding,1 always know solr independently client library like sunburnt pysolr solrpy etc just know relational databases using orm moreover orm documentation teach relational databases one would expect,i want use lucene solr python there seems multiple apis purpose they seem suffer dependency hell stability issues solr doesnt ship python bindings anymore and i cant find documentation user familiar solr i leaning sunburnt pysolr solrpy mature is evaluation correct please recommend stable python bindings solr good standalone presuppose solr knowledge documentation or i learn interact servlet make use existing documentation,3 i needed something similar simple logging environment following routine trick def findloggerbasefilenameself logger finds logger base filenames currently one logfile none parent loggerdict parent parentclassname rootlogger file name lives h loggerdict handlers hclassname timedrotatingfilehandler logfile hbasefilename else logfile selffindloggerbasefilenameparent return logfile i looking file used timedrotatingfilehandler might need change type handler search probably filehandler not sure would go sort complex logging environment,is way if loggingconfigfileconfig somelog setter getter just curious exists,3 note serious comment require solution vector integer looking something called integer least squares problem which believed nphard there heuristic solvers gets complicated,i integer matrices moderate size hundred rows i need solve equations form ax b b standard basis vector a one matrices i using numpylinalglstsq purpose rounding errors end significant how i carry exact symbolic computation ps i really need code efficient i concerned ease coding,1 need crlf newlinesquence try selftnetwriternrn hope helps,im using telnetlib python connect simple mail server send email everything works fine end enter data command submit body message order submit email server queue need type period new line end transaction snippet looks like selftnetwritenn selftnetreaduntil selftnet telnet session var readuntil waits ok response saying email sent queue email server way delivery however get ok response back connection times sec timeout flag email received inbox ideas ive also tried selftnetwriterawinputn ive also tried grabbing raw socket selfsockselftnetgetsocket selfsocksendn print selfsockrecv response ive also tried return carriage r combination n avail ideas thank george,1 each line example string something like punctuation words wstrippunctuation w linesplit wstrippunctuation listappendwords would probably okay first approximation although may cover every edge case way want ie hyphenated words words separated whitespace words trailing apostrophe etc the conditional avoid blank entries,i trying create program read text file create list lines words however able append line word help would appreciated problem text openfiletxtr line textreadlines sentence linestrip listappendsentence print list textclose example text i something i wanted append like i something thanks advance,1 where exactly getting variable in basic sense quite specified punctuation split line list words using linesplit splits every space if delimiters substitute instead space assign split var need append list brendan provided good solution strip basic punctuation alternatively could also use simple regex refindallr w file find words given file using yet another way take advantage pythons string library stringpunctuation particular str listline join word word str word stringpunctuation split,i trying create program read text file create list lines words however able append line word help would appreciated problem text openfiletxtr line textreadlines sentence linestrip listappendsentence print list textclose example text i something i wanted append like i something thanks advance,1 i would absolutely use full web server rather one built webpy although okay traffic remains low i think one built webpy supposed used debugging rather production it mostly matter preference servers use i like nginx uwsgi,i currently developing ios application needs backend pull data i implemented backend using python webpy pymongo i deployed everything ec instance assigned elastic ip instance ios devices call access backend launch application ssh nohup python mainpy amp everything works fine couple dozen users day potential grow data transferred rarely kilobytes i wondering proper way things for instance webpy website explain ways use webpy apache lightppd etc special cases i deploying backend using one full featured servers,1 something like would cover large number cases could tailored used symbols import text openfiletxtr line textreadlines sentence linestrip words resub resubazaz sentencesplit somelistappendwords print list textclose this would include capital lower case letters apostrophes sake contractions,i trying create program read text file create list lines words however able append line word help would appreciated problem text openfiletxtr line textreadlines sentence linestrip listappendsentence print list textclose example text i something i wanted append like i something thanks advance,1 once iterate itertoolscombinations object used iterate second time if need reuse proper way make list tuple all need give name assign variable sticks around comblist listcombobject don iterate if want iterate call list combobj don call list printi side note the standard way name object instances normal variables would combobj rather combobj see pep info to convert inner tuple list use list comprehension list builtin comblist comblist listitem item comblist,import itertools n combobj itertoolscombinationsn combobj itertoolscombinations object xcd listcombobj listcombobj this prints nothing printi how iterate combobj how convert,3 this brute force method gets job done code produce gradients borrowed pil import image imagedraw def channeli c size startfill stopfill calculate value single color channel single pixel return startfillc inti size stopfillc startfillc def colori size startfill stopfill calculate rgb value single pixel return tuplechanneli c size startfill stopfill c range def roundcornerradius draw round corner corner imagenew rgba radius radius draw imagedrawdrawcorner drawpieslice radius radius fillblue return corner def applygradtocornercorner gradient backwards false topbottom false width height cornersize widthiter rangewidth backwards widthiterreverse xrangeheight gradpos j widthiter topbottom pos ij else pos ji pix cornergetpixelpos gradpos pix cornerputpixelposgradientgradpos return corner def roundrectanglesize radius startfill stopfill runtopbottom false draw rounded rectangle width height size rectangle imagenew rgba size runtopbottom si height else si width gradient colori width startfill stopfill xrangesi runtopbottom modgrad xrangeheight modgrad gradienti width rectangleputdatamodgrad else rectangleputdatagradientheight origcorner roundcornerradius upper left corner origcorner applygradtocornercornergradientfalseruntopbottom rectanglepastecorner lower left runtopbottom gradientreverse backwards true else backwards false corner origcornerrotate applygradtocornercornergradientbackwardsruntopbottom rectanglepastecorner height radius lower right runtopbottom gradientreverse corner origcornerrotate applygradtocornercornergradienttrueruntopbottom rectanglepastecorner width radius height radius upper right runtopbottom gradientreverse backwards false else backwards true corner origcornerrotate applygradtocornercornergradientbackwardsruntopbottom rectanglepastecorner width radius return rectangle img roundrectangle true imgsavetestpng png running left right runtopbottom false running top bottom runtopbottom true,i trying use pil draw rectangle rounded corners gradient fill color i found cool web site httpwebarchiveorgwebhttpnadianacompiltutorialbasicadvanceddrawingdrawingroundedcornersrectangle shows draw solidcolor rounded rectangle i happy i want able draw one starts light red top goes dark red bottom my initial thought use code website draw rounded rectangle overlay second white black rectangle rounded rectangle using alpha blending everything i tried ends blowing face i seen nearmiss solutions using numpy i skilled enough commute code fragments successful solution i would grateful someone could show modify code link implement overlay idea show completely better solution getting rounded rectangle gradient fill python cheers ferris,3 figured thank suggestions for anyone wanting information implement pyecc check crypto wrapper i wrote github cryptowrapper httpsgithubcomfhrcryptowrapper,i working pyecc elliptic curve cryptography module python i find i wondering anyone example use module i try reading source i find anything stack overflow topic regarding python thanks,3 openfiletxtr f mapstrsplit f something,i trying create program read text file create list lines words however able append line word help would appreciated problem text openfiletxtr line textreadlines sentence linestrip listappendsentence print list textclose example text i something i wanted append like i something thanks advance,1 assuming using python put top file future import division always give float use old behaviour if using python already default behaviour,i want write function inputs two variables b returns ab float irrespective types b right i def fa b return floatafloatb is better way,3 there numlua since depends blaslapack fftw hdf luajit buy performance gain numlua per se,i thinking learning lua learned smaller language compared python efficient jit compiler implementation form luajit i would like know possible use lua way use python numpyscipy lua numpyscipy equivalent matplotlib equivalent,3 you need use mongrel handler serve wsgi application basically something translates messages mongrel zeromq socket wsgi environ there several i used mwsgi successfully past i think wsgid looks promising well,this attempt discover canonical answer something seems hard google right i writing web app pyramid i luxury deciding server stack look like i heard good things mongrel would like try using serve app however i figure mongrel manual google searches connect mongrel wsgi app do i roll existing solutions problem,1 you could simply force conversion one operands float type example def fa b return ab,i want write function inputs two variables b returns ab float irrespective types b right i def fa b return floatafloatb is better way,1 if want use standard library youre using use msvcrt get current keypress map frequency import msvcrt import time import winsound notes true key msvcrtgetch try note noteskey except keyerror note winsoundbeepnote timesleep,how i make program plays tone i define i hold key i play different notes winsoundbeep i think really helps,1 as general rule windows says needs file hard pressed get completely relinquish control while process running exclusive rights read write execute file files question i highly doubt effective hack running windows my personal suggestion would get live boot disk run linux either usb optical drive boot alternate os copy file merry way,i sure service process way disable stop a file i trying copy run system system require sys file if way python i would even ecstatic read response,1 by overwriting entity time effectively creating new record the distinction autonow autonowadd enforced model framework way acting differently based whether record already exists instead update existing record shay suggests,i db model one property autonowaddtrue but looks like work i expected updated time put called i use keyname secondthirdn call put really create new record update here code class userdbmodel id dbintegerproperty added dbdatetimepropertyautonowaddtrue name dbstringproperty handler called several times def getself user userkeynameiduniqueuserid userid uniqueuserid username currentname userput,1 a dict unordered set keyvalue pairs when iterate dict effectively random but explicitly randomize sequence keyvalue pairs need work different object ordered like list dictitems dictkeys dictvalues return lists shuffled itemsditems list tuples randomshuffleitems key value items print key value keysdkeys list keys randomshufflekeys key keys print key dkey or care keys valuesdvalues list values randomshufflevalues shuffles inplace value values print value you also sort random key value sortedditems keylambda x randomrandom print key value,how i iterate items dictionary random order i mean something randomshuffle dictionary,3 usually i would use columnproperty handle requirement eg class projectmastersbase billedtotal columnproperty select funcsum funccoalesceprojectinvoicesexpenseamount funccoalesceprojectinvoiceshoursamount masterprojectid projectinvoicesmasterprojectid projectinvoicesisvoid false projectinvoicesissubmit true label billedtotal deferredtrue after use like ordinary attribute eg result sessionquery projectmastersmasterprojectid projectmastersmasterprojectname projectmastersbilledtotallabel invoicetotal filterprojectmastersisactive,i struggling understand proper syntax executing subquery sqlalchemy value needs returned ie used where i using declarative approach there two models used class projectinvoicesbase invoiceid columnintegerunsignedtrue default primarykeytrue autoincrementtrue masterprojectid columnintegerunsignedtrue indextrue nullablefalse expenseamount columnnumeric default hoursamount columnnumeric default isvoid columnboolean default indextrue issubmit columnboolean default indextrue class projectmastersbase masterprojectid columnintegerunsignedtrue default primarykeytrue autoincrementtrue masterprojectname columnunicode masterprojectmemo columnunicodetext isactive columnboolean default indextrue the point query determine current amount invoiced project using subquery sum related invoices there reasons done subquery rather join i really need figure subquery issue this example current sa query sqry sessionquery funcsum funcifnullprojectinvoicesexpenseamount funcifnullprojectinvoiceshoursamount label billedtotal filterandprojectinvoicesisvoid projectinvoicesissubmit subquery result sessionquery projectmastersmasterprojectid projectmastersmasterprojectname sqrycolumnsbilledtotallabel invoicetotal filterprojectmastersisactive i feeling going embarrassing simple i seem crack code getting work i tried every sample i find mixed results if i leave correlate argument i receive following error alias object attribute masterprojectid i also tried adding following statement end subquery without luck correlateprojectmastersmasterprojectid projectinvoicesmasterprojectid if i include correlate argument i receive following error typeerror boolean value clause defined thanks help advance,3 you observed dealing entity instance model the option take code want execute copyandpaste modify work entity instead,trying use python geomodel class bulkloader i calling following postimportfunction works fine entity updated location field set properly def postprocessobjinputdict entityinstance bulkloadstate entityinstance location dbgeoptentityinstance latitude entityinstance longitude return entityinstance but i need call entityinstanceupdatelocation entity saves data store the entityinstance though entity subclass geomodel i clear there post back said inline code call function pass entity i know supposed mean thanks helpsample code,1 in functional language like haskell would partially applying map function function takes tuple arguments resulting function takes list argument tuples as jochen ritzel pointed another answer even python implement pretty trivially using functoolspartial therefore i suppose process called partial application map thing i aware particular name special case,class fooobject def initselff selff f def callselfargslist def wrappedfargslist return selffargs args argslist return wrappedfargslist name main class abcobject foo def fabc return abc range b range c range data listzipabc printabcfdata i wrote years back when decorate function fx foo becomes flist xs what process called what what functional programming name its currying i know simple mapflist xs could done what decoratorsoperation decorating called mathematically,1 change places v selfv becomes attribute object you see whatever value selected group radiobuttons selfv intvar radiobuttonmaster text somewhat variableselfv value once button button method print selfvget see value,here rough example multiple choice test i made it runs terminal i hoping make graphical user interface using tkinter print category anxious feelings print print anxiety nervousness worry fear baivar input please enter somewhat moderatly lot print print feeling things around strange unreal foggy baivar input please enter somewhat moderatly lot print print feeling detached part body baivar input please enter somewhat moderatly lot print depression test print print print sadness have feeling sad dumps bdcvar input please enter somewhat moderatly lot print print discouragement does future look hopeless bdcvar input please enter somewhat moderatly lot print print low selfesteem do feel worthless think failure bdcvar input please enter somewhat moderatly lot burns anxiety inventory category anxious feelings catvar baivar baivar baivar burns anxiety checklist baivar catvar burns depression checklist bdcvar bdcvar bdcvar bdcvar prints bai amp bdc print your bai baivaryour bdc bdcvar name rawinput please type name bai strinputplease enter bai bdc strinputplease enter bdc year strinputplease enter year month strinputplease enter month day strinputplease enter day timehour strinputplease enter current hour timeminute strinputplease enter current minutes ampm rawinput please enter pm file open burns inventory txt filewritename n filewriteday filewrite filewritemonth filewrite filewriteyear filewrite n filewrite n filewrite your bai filewritebai filewrite n filewrite your bdc filewritebdc filewrite n filewritetimehour filewrite filewritetimeminute filewrite n filewrite filewriteampm filewrite n fileclose i working days two teach use tkinter my friend i made rough example test might look like tkinter import import time class app def initself master w labelmaster text anxiety nervousness worry fear wpack v intvar radiobuttonmaster text variablev valuepacksidetop anchorw radiobuttonmaster text somewhat variablev valuepacksidetop anchorw radiobuttonmaster text moderatly variablev valuepacksidetop anchorw radiobuttonmaster text lot variablev valuepacksidetop anchorw selfbutton buttonmaster textback fgred commandselfbutton selfbuttonpacksidebottom selfbutton buttonmaster textnext fgred commandselfbutton selfbuttonpacksidebottom def buttonself print sam awesomegajonga def buttonself print python for the win gian says python filthy master tk app appmaster mastermainloop i think goals tkinter gui make radiobuttons assign either variablesbaivar baivar bai etc make next amp back buttons show different question every time press make page end test multiple input fields name date etc i make test i made software the test designed david burns available work book the feeling good book,1 the argparse module makes nuts long happy config file looks like command line i think advantage users learn one syntax setting fromfileprefixchars example makes myprog foobar equivalent myprog bazconf bazconf foo bar you even code look fooconf automatically modifying argv ospathexists fooconf argv fooconf argv args argparserparseargsargv the format configuration files modifiable making subclass argumentparser adding convertarglinetoargs method,python standard library modules configuration file parsing configparser environment variable reading osenviron commandline argument parsing argparse i want write program also has cascade option values default option values overridden config file options overridden environment variables overridden commandline options allows one configuration file locations specified command line eg configfile fooconf reads either instead additional usual configuration file this must still obey cascade allows option definitions single place determine parsing behaviour configuration files command line unifies parsed options single collection option values rest program access without caring came everything i need apparently python standard library work together smoothly how i achieve minimum deviation python standard library,3 using urllib easiest way fetch resources http server need set httpproxy environment variable if proxy unauthenticated something like export httpproxyhttpproxyport if proxy authenicating export httpproxyhttpusernamepasswordproxyport if want programattically manually using proxy handler,how would i go python i need establish stronger connection i may server,1 in addition peter note bear mind appstats way know asynchronous request actually completes except fetch result as result even fast calls look slow take long time request result,i trying optimize code i got problem i quite understand on every page web app list notifications much like facebook new ticker so every request i run code beggining notificationquery dbqueryticker keysonlytrue filter friends selfcurrentuserkeyname selfnotificationsfuture notificationqueryrun then i find good spot i call middle function notificationkeys futureparent future selfnotificationsfuture selfnotifications dbgetasyncnotificationkeys finally i fetch end contextupdate notifications selfnotificationsgetresult every thing works great except if i call middle function end request function i get dumb spot and if i call i think optimized spot i get smart spot as see api usage doubled making optimization what going call number first snippet cases call number dumb spot second snippet call number smart spot second snippet this last switch nothing problem i tested pd does google charge time query idle update the problem seems devserver i tried example smart version appspot i got queries appspot here everything works expected things get called run getasync block stuff as i said issue devserver still would nice see feature working localhost effective profiling,2 the current sdk support python runtime devappserver bundle new libraries like webapp if need libraries download include app need extra runtime features like multithreading pil need development production environment,i attempting try google app engine python being familiar eclipse i decided use pydev after trouble i hello world program working almost it cannot find webapp import telling unresolved i followed instructions i find google app engine libraries linked i think i searched webapp potential import cannot find anywhere library files i really new python general even newer google app engine i certain simple problem exacerbated newness i running osx running eclipse indigo service release i latest version pydev available download tuesday evening,2 dimensions use numbers dimension numpy lets access positions tuples shape pos myarray nponesshape myarraytuplepos return,i python newbie i confused access array element dynamically i list b i dynamically obtain length vary with help list i need update multidimensional array marr the length list array dimension matches given example basically i looking technique access multi dimensional array respect list b form marrb this marray also dynamically created i tried looking tutorials numpy figure solutionam i missing something thanks advance,1 you could create function like def arrayupdateb marr value lenb return arrayupdateb marrb value marrb value given b set value marr foo would call arrayupdateb marr foo,i python newbie i confused access array element dynamically i list b i dynamically obtain length vary with help list i need update multidimensional array marr the length list array dimension matches given example basically i looking technique access multi dimensional array respect list b form marrb this marray also dynamically created i tried looking tutorials numpy figure solutionam i missing something thanks advance,1 in addition adding pylab import need add show last line script ie gridtrue question actually display plot here i get adding show,i installed enthought epd bit windows i trying plot historical stock quote data using yahoo api all code i trying use blog post httpwwwtraineetradercomimportingstockdatafromyahoousingpython the ystockquotepy file works fine but second script plot google historical stock quote work this code website import ystockquote get quotes goog ystockquotegethistoricalprices goog create empty lists quick dirty googopen googclose googdate googhigh googlow googadj googvolume populate lists downloaded data range googdateappendgoogi googopenappendgoogi googhighappendgoogi googlowappendgoogi googcloseappendgoogi googvolumeappendgoogi googadjappendgoogi plotgoogadj titlegoogle adjusted close ylabelrgoog closing price usd fontsize xlabelrdate fontsize gridtrue i get following error nameerror name plot defined any tips i wrong or get run if i include pylab import top code i get error nothing happens,3 i believe python private attribute mangling compilation particular occurs stage parsed source abstract syntax tree rendering byte code this time execution vm knows name class within whose lexical scope function defined it mangles psuedoprivate attributes variables leaves everything else unchanged this couple implications string constants particular mangled setattrself x x left alone since mangling relies lexical scope function within source functions defined outside class inserted mangling done since information class belong known compiletime as far i know easy way determine runtime class function defined at least without lot inspect calls rely source reflection compare line numbers function class sources even approach reliable border cases cause erroneous results the process actually rather indelicate mangling try access x attribute object instance class function lexically defined within still mangle class letting store private class attrs instances objects i almost argue last point feature bug so variable mangling going done manually calculate mangled attr order call setattr regarding mangling done pymangle function uses following logic x gets underscore class name prepended eg test mangled attr testx the exception class name begins underscores stripped eg class test mangled attr still testx trailing underscores class name stripped to wrap function def mangleattrsource attr return public attrs unchanged attrstartswith attrendswith attr return attr source object get class hasattrsource bases source sourceclass mangle attr return ss sourcenamelstrip attr i know somewhat hardcodes name mangling least isolated single function it used mangle strings setattr able use win code setattrself mangleattrself x value note would set private attr typeself wanted set private attr specific class choose explicitly setattrself mangleattrsomecls x value alternately following mangleattr implementation uses eval always uses python current mangling logic though i think logic laid ever changed mangletemplate class cls staticmethod def mangle attr cls cls def mangleattrsource attr source object get class hasattrsource bases source sourceclass mangle attr tmp code mangletemplateformatclssourcename attrattr evalcompilecode exec tmp return tmp cls manglecodecovarnames note code attr needs funccode python older,i run situation pseudo private class member names getting mangled using setattr exec in class t def initself kwargs selfx k v kwargsitems setattrself k v in tydict out tx i tried execselfs k v well result in class t def initself kwargs selfx k v kwargsitems execselfs k v in tzdict out tx z doing selfdictss selfclassname k v would work dict readonly attribute is another way i dynamically create psuedo private class members without hardcoding name mangling a better way phrase question what python “under hood” encounters double underscore selfx attribute set is magic function used mangling,3 so want access digits integer like elements list easiest way i think n lastdigit intreprn convert n string accessing last element use int constructor convert back integer for floating point number n fstr reprn signifdigits fractdigits fstrsplit signiflastdigit intsignifdigits,is way get last digit number i trying find variables end like etc if i use text variable i simply put print number works variables textlike hello numbers with numbers i get error typeerror int object subscriptable i trying see better way deal numbers way i know solution convert string command i trying see another way i missed thanks much advance,3 addressing what python “under hood” encounters double underscore selfx attribute set is magic function used mangling afaik basically special cased compiler so bytecode name already mangled interpreter never sees unmangled name idea special handling needed this references setattr exec looking string dict work compiler sees strings know anything attribute access passes unchanged the interpreter knows nothing name mangling uses directly the times i needed get around i manually done name mangling hacky i found using private names generally bad idea unless case know need intended purpose allow inheritance hierarchy classes use attribute name copy per class peppering attribute names double underscores supposed private implementation details seems cause harm benefit i taken using single underscore hint external code touching,i run situation pseudo private class member names getting mangled using setattr exec in class t def initself kwargs selfx k v kwargsitems setattrself k v in tydict out tx i tried execselfs k v well result in class t def initself kwargs selfx k v kwargsitems execselfs k v in tzdict out tx z doing selfdictss selfclassname k v would work dict readonly attribute is another way i dynamically create psuedo private class members without hardcoding name mangling a better way phrase question what python “under hood” encounters double underscore selfx attribute set is magic function used mangling,2 i problem well attempting load etree via windows scripting host after trying different approaches i came across python change proposes new python modules longer embed manifests causes distribution problems msvc runtimes installed httpcommentsgmaneorggmanecomppythonlxmldevel httpbugspythonorgissue so i simply loaded pythonpathlibsitepackageslxmletreepyd resource hacker httpwwwangusjcomresourcehacker removed manifest resource embedded,i windows server r x it running python x django apache x wsgi it runs ok without lxml we using soaplib requires lxml i tried installing lxml several ways using easyinstall downloading win installation binary problem running site apache raises following error importerror dll load failed the specified module could found it raises error lxml import etree i googled solution found nothing useful some info i found that change pythonpython changes dlls included i used dependency walker find dlls missing the ones i found missing gpsvcdll ieshimsdll msvcrdll when i tried installing x redistributable package change anything i tried copying msvcrdll egg dir lxml created another error said coudn load dll i remember exact exception i generate needed it works running django internal server running managepy runserver how i resolve issue thanks,2 you find several examples httpzguidezeromqorgpageallchapterfourreliablerequestreply most patterns source code example client app server app several languages even python source code example i find useful look c source code version fully understand works i made use lazy pirate pattern httpzguidezeromqorgpylpclient memory i change something way loops retries order get work reliably it hard figure i added print statements see going,can anyone please post python example demonstrates use requestresponse messaging model utilizes zeromq queue i done lot online searching yet able locate example the article great job explaining concept queue unfortunately provide example,2 maybe numpy solution elaborate need without anything fancy i found following quick flash noticable wait items list import random lista randomchoiceabcdef range listb randomrandom range b ziplista listb dsetdefaulta appendb key print key sumdkeylendkey your milage might vary depending whether typical length lists whether couple times script whether hundredsthousands times,in past i faced dealing averaging two paired lists i used answers provided successfully however large items procedure somewhat slow i wondering using numpy would make faster i start two lists one floats one strings names b b c e e values i trying calculate mean identical values applying i get resultnames b c e resultvalues i put two lists result example also list name value tuples would suffice result b e what best way numpy,1 try pyqrnative it really actively developed the main issue documentation kind nonexistent a brief example seen project test code rosorg generated overview available classes functions,is library python encoding decoding qr codes searched old questions stackoverflow links dead links given working suggest python working qrcode library thanks,1 use wait until page contains element proper xpath locator for example given following html body div idmydiv table classmytable implementation table div body enter following keyword wait until page contains element tableclass mytable seconds unless i missed something need create new function,how i write function selenium wait table class identifier python i devil time learning use selenium python webdriver functions,1 with numpy write something use groupby functionality recgroupby function matplotlibmlab much slower for powerful groupby functionality maybe look pandas i compared answer michael dunn dictionary import numpy np import random matplotlibmlab import recgroupby lista randomchoiceabcdef range listb randomrandom range names nparraylista values nparraylistb def fdictlista listb b ziplista listb dsetdefaulta appendb avg key avgappendsumdkeylendkey return dkeys avg def fnumpynames values resultnames npuniquenames resultvalues npemptyresultnamesshape name enumerateresultnames resultvaluesi npmeanvaluesnames name return resultnames resultvalues this result three in fdictlista listb out c b e f in fnumpynames values out array b c e f dtype s array in recgroupbystructarray names values npmean resvalues out recarray b c e f dtype names s resvalues f and seems numpy little bit faster test predefined groupby function much slower in timeit fdictlista listb loops best ms per loop in timeit fnumpynames values loops best ms per loop in timeit recgroupbystructarray names values npmean values loops best ms per loop,in past i faced dealing averaging two paired lists i used answers provided successfully however large items procedure somewhat slow i wondering using numpy would make faster i start two lists one floats one strings names b b c e e values i trying calculate mean identical values applying i get resultnames b c e resultvalues i put two lists result example also list name value tuples would suffice result b e what best way numpy,2 if always run code admin json folder always relative point ospathjoin json filename if pythonscript folder ospathjoin json filename,my file structure looks something like root ├── admin │â â └── pythonscriptpy └── json └── targetfileout ok python file admin folder i trying save file json folder i done fine saving file admin folder i need go supposed go json folder the target relative i absolute target thanks,1 the best way poll ethernet interface statistics snmp it looks like using linux load snmpd options installing snmpd etcdefaultssnmpd make sure line snmpdopts looks like snmpdopts lsd lf devnull u snmp i smuxusmconfiquerydlmoddiskiolmsensorshrnetworksnmpenginesystemmibatinterfaceiftableipaddresstableifxtableipcputcptableudptableipsystemstatstableipsnmpmibtcpicmpudpprocmemorysnmpnotifytableinetnettomediatableipsystemstatstabledisk lsd p varrunsnmpdpid you might also need change ro community public see note set listening interfaces etcsnmpsnmpdconf loopback assuming functional snmpd point poll ifhcinbytes ifhcoutbytes see note interfaces question using pollbytespy snmp import vmanager import time def pollethmanagernone note nd arg getindex valid ifname value inbytes managergetindex ifhcinoctets eth outbytes managergetindex ifhcoutoctets eth return timetime intinbytes intoutbytes prep snmp manager object mgr vmanager localhost mgrindex ifname stats list insert condition instead true true statsappendpollethmgr print pollethmgr timesleep snmppy subprocess import popen pipe import class vmanagerobject def initself addr community public selfaddr addr selfcommunity community selfindex dict def bulkwalkself oid ifname cmd snmpbulkwalk v c osq c selfcommunity selfaddr oid po popencmd shelltrue stdoutpipe executable binbash output pocommunicate result dict line resplitr rn output linestrip continue idx value resplitr line idx idxreplaceoid resultidx value return result def bulkwalkindexself oid ifoutoctets result dict selfindexdict vals selfbulkwalkoidoid key val valsitems idx selfindexgetkey none idx none resultidx val else raise valueerror could find index selfindex else raise valueerror call index method calling bulkwalkindex return result def getindexself oid ifoutoctets index this method horribly inefficient improvement left exercise reader index return selfbulkwalkindexgetindex unknown else raise valueerror please include index get def indexself oid ifname selfindex selfbulkwalkoidoid end notes snmp vc uses cleartext authentication if worried security someone sniffing traffic change community restrict queries linux machine source ip address the perfect world would modify snmppy use snmpv encrypts sensitive data people use nonpublic community restrict snmp queries source ip ifhcinoctets ifhcoutoctets provide instantaneous values number bytes transferred interface if looking data transfer rate course additional math involved,there socket method getting ip given network interface import socket import fcntl import struct def getipaddressifname socketsocketsocketafinet socketsockdgram return socketinetntoafcntlioctl sfileno x siocgifaddr structpack ifname which returns following getipaddress lo getipaddress eth is similar method return network transfer interface i know i read procnetdev i love socket method,3 if wanna store file via fileobject would something like rootadmin root json rootjson myfile openjsontargetfile w myfilewritefoo myfileclose,my file structure looks something like root ├── admin │â â └── pythonscriptpy └── json └── targetfileout ok python file admin folder i trying save file json folder i done fine saving file admin folder i need go supposed go json folder the target relative i absolute target thanks,2 you might want read python method objects python self sort like c except put method declaration what happens declare function inside class “becomes” method when get method object becomes bound method first argument self fixed object got try class fooobject def doself print x instance foo print foodo prints unbound method foodo print instancedo prints bound method foodo these equivalent foodoinstance instancedo no extra magic happening threading case regular python,following code class foo def initselfx selfx x def doself printselfx foo foo foo foo tthreadingthreadtargetfoodo tthreadingthreadtargetfoodo tstart tstart i using member function instantiated object target thread i wondering works ie threading module something special detect member function opposed normal function wo object context end callablereference i think usual callback mechanism like ftplibretrlines et al accept plain global functions is better stay away alltogether slarti ps coming cc exposed behaviour new although welcome,2 this currently implemented boto version available check source github you use session token passing token key word argument securitytoken botoconnects i think session token implemented elsewhere soon well,in boto s modules s connection constructor takes access key secret key is connection object exists also takes session token,1 check whitespace consistent ie mixing tabs spaces if editor supports i suggest make expand tabs spaces this avoids confusion also copypasting code in vim se tabstop shiftwidth expandtab retab,ok piece script def start print while exploring ruins recently abandoned castle stumble apon entrance appears dungeon you carrying i keep getting error userubuntudocumentspython python dungeonpy file dungeonpy line def start indentationerror expected indented block i know probably obvious anyone clue i wrong hear i tried replacing indent spaces tabs still gives error i appreciate answers,1 make sure mixing tabs spaces indentation your string missing closing quote further def start actually indented file it indented question python seems complaining,ok piece script def start print while exploring ruins recently abandoned castle stumble apon entrance appears dungeon you carrying i keep getting error userubuntudocumentspython python dungeonpy file dungeonpy line def start indentationerror expected indented block i know probably obvious anyone clue i wrong hear i tried replacing indent spaces tabs still gives error i appreciate answers,3 are sure tab character position try open vi add tab check fine,ok piece script def start print while exploring ruins recently abandoned castle stumble apon entrance appears dungeon you carrying i keep getting error userubuntudocumentspython python dungeonpy file dungeonpy line def start indentationerror expected indented block i know probably obvious anyone clue i wrong hear i tried replacing indent spaces tabs still gives error i appreciate answers,1 looks like expects def start indented what code look like,ok piece script def start print while exploring ruins recently abandoned castle stumble apon entrance appears dungeon you carrying i keep getting error userubuntudocumentspython python dungeonpy file dungeonpy line def start indentationerror expected indented block i know probably obvious anyone clue i wrong hear i tried replacing indent spaces tabs still gives error i appreciate answers,1 try looking code line is unfinished block line ending if yes put something block – pass statement,ok piece script def start print while exploring ruins recently abandoned castle stumble apon entrance appears dungeon you carrying i keep getting error userubuntudocumentspython python dungeonpy file dungeonpy line def start indentationerror expected indented block i know probably obvious anyone clue i wrong hear i tried replacing indent spaces tabs still gives error i appreciate answers,1 foodo foodo bound methods i suggest look following documentation links httpdocspythonorglibrarystdtypeshtmlmethods introduction httpdocspythonorgreferencedatamodelhtml depth excerpt second link when bound userdefined method object called underlying function imfunc called inserting class instance imself front argument list for instance c class contains definition function f x instance c calling xf equivalent calling cfx,following code class foo def initselfx selfx x def doself printselfx foo foo foo foo tthreadingthreadtargetfoodo tthreadingthreadtargetfoodo tstart tstart i using member function instantiated object target thread i wondering works ie threading module something special detect member function opposed normal function wo object context end callablereference i think usual callback mechanism like ftplibretrlines et al accept plain global functions is better stay away alltogether slarti ps coming cc exposed behaviour new although welcome,1 cdef functions accessed python code that fast calling functions python always slow the solution using cpdef instead accessible python fast called c or call python code,i want wrap simple function double fooint int b double div double double b b b return div trying cdef pyfooint c int res fooc ampd return res i want return list values using cdef work gives erroe attributeerror attribute pyfoo if instead cdef use def cpdef works is way cython using cdef,3 the problem seems cdef creates function c signature c call semantics they cannot called python cpdef used provide python wrapper around cdef function look way cython providing bridge c python cdef c end bridge cpdef python end bridge there nice talk cython,i want wrap simple function double fooint int b double div double double b b b return div trying cdef pyfooint c int res fooc ampd return res i want return list values using cdef work gives erroe attributeerror attribute pyfoo if instead cdef use def cpdef works is way cython using cdef,1 doublequotes inside singlequotes escaped vice versa the parser removes backslash example i love bugs i love bugs,combine r doublequote singlequote escapes print compare r notice r prints way write file prints way like see this i wrote exercise mybugs guido said r moved i love bugs mybugs stallman said moved i love bugs print mybugs print mybugs output guido said i love bugs moved stallman said i love bugs moved question r print everything way i write py file example prints instead line why,1 suppose wrote class c class foo int x public fooint x x x void stdcout x foo f foo here ampfoodo would pointer member function would need foo instance able call suppose could pass around fdo need anything else call f this exactly bound member python passing foodo passing method call instance onm call this problem addressed c either proprietary extensions borland closures libraries boostbind,following code class foo def initselfx selfx x def doself printselfx foo foo foo foo tthreadingthreadtargetfoodo tthreadingthreadtargetfoodo tstart tstart i using member function instantiated object target thread i wondering works ie threading module something special detect member function opposed normal function wo object context end callablereference i think usual callback mechanism like ftplibretrlines et al accept plain global functions is better stay away alltogether slarti ps coming cc exposed behaviour new although welcome,1 surely gettext best solution want localization remember use placeholders instead concatenating strings like example regarding whitelabeling all customerdependent content also localizable gettext fine hit two birds one stone plus gettext somewhat standard localization tools professionals work without issues i guess however things really localizable like pictures i suggest keep kind predefined structure content customer insert content without touch code eg logo always named logopng fixed size it common practice keep msgid po files equal text source language works well short simple sentences in case long sentences special characters html tags i would suggest using id like resultmessage manually populating master resource file eg english this makes file bit less selfdescribing takes little effort long run best solution want stay sane keep resource files small possible to keep files sync master translated number tools i wrote keeping resources synced,my product must independent brandlogo send localized message i need localizations english portuguese i might need later easy add translation app gets used eg russian site able send welcome emails russian name site brand uses app i supposse i want something like whitelabel product should i use gettext instead messagebody dear adname nthank registering selfcurrentlogo to edit adclick edit menu selfcurrentlogo vi adkeyid nwe invite visit home page find latest information new business announcements us from also upload videos music images n contact preferences please select your contact preferencesninformation contactnif like also add us facebook appsfacebookcomkoolbusiness result example added domain brandlogo use forwarded message from date sun oct pm subject honda zoomer to fridgekoolbusinesscom dear niklas r thank registering wwwkoolbusinesscom to edit adclick edit menuwwwkoolbusinesscomvi we invite visit home page find latest information new business announcements us from also upload videos music images contact preferences please select your contact preferences information contact if like also add us facebook appsfacebookcomkoolbusiness what think here message builds the exact contents important important works many languages you gettext i think case simple i source since english portuguese going main languages app time maybe add spanish french swedish nontechnical job writing translations update since gettext appears choice i wonder implementation things particular whether include html display special character like ampersand i currenly using renders correct output code right djangopo msgid accessories ampamp parts msgstr partes ampamp acessã³rios msgid entire brasil msgstr amptodo brasilamp msgid you post ads free you search classified advertisements professionals well private individuals cars property employment pieces furniture electronics others msgstr href ai anãºnciosa site montaocombr sã£o colocados manualmente pelo usuã¡rio aqui bra href li todosa os anãºncios sã£o revistos pela equipe montaocombr o anãºncio serã¡ visã­vel durante dois messes grã¡tis for new email translation i could use gettext i must get variables translation right could tricky anyway i trying start sketch localized many languages msgid dear snthank registering to edit adclick edit menusvis nwe invite visit home page find latest information new business announcements us from also upload videos music images n contact preferences please select your contact preferencesninformation contactnif like also add us facebook appsfacebookcomkoolbusiness msgstr however experience says much better make cron jobs one translation one cron job many translations since request could accidentally get wrong cookie due cookie cooruption likewise so translation task also completeness consistency even though first attempt works english easily exandable languages complete localization gettext something i think good,1 just iterate file open hugefile hf line hf important line printline this require o memory to read stdin simply iterate sysstdin instead hf import sys line sysstdin important line printline,we couple huge files greater size ram disk i want read line line python output results terminal i gone i looking methods wait till entire file read memory i would using commands cat filename python myscriptpy python myscriptpy filename how read stdin python how i write unix filter python,2 this standard behavior file objects python openmyfiletxt r myfile line myfile something current line line sysstdin something current line,we couple huge files greater size ram disk i want read line line python output results terminal i gone i looking methods wait till entire file read memory i would using commands cat filename python myscriptpy python myscriptpy filename how read stdin python how i write unix filter python,3 the division operator rather also backslash special meaning inside python string either escape another backslash use raw string r,i problems python program i creating maths working solutions i getting syntaxerror unexpected character line continuation character python code printlength sides strlengthlength strlengthlength units my problem i tried work using python,1 currently really possible pydev please enter feature request see httppydevorgabouthtml details report,is way make eclipsepydev highlight python builtin functions for example python idle highlights int list pydev i using eclipse pydev,1 the backslash line continuation character error message talking newline characterswhitespace allowed next nonwhitespace continues interrupted line print this long string fit single line outside string backslash appear way for division want slash if want write verbatim backslash string escape doubling in code using twice printlength sides strlengthlength inside string treated literal strlengthlength outside string treated line cont character newline follows fail units,i problems python program i creating maths working solutions i getting syntaxerror unexpected character line continuation character python code printlength sides strlengthlength strlengthlength units my problem i tried work using python,2 the division operator,i problems python program i creating maths working solutions i getting syntaxerror unexpected character line continuation character python code printlength sides strlengthlength strlengthlength units my problem i tried work using python,3 several ways write string literals python single double quotes singleline multiline raw normal none preserved string though parser parses information remains presented source even need source could generate string dynamically say reading file asking user turning number string so repr string python guesses way format look like literal the rules uses simple string contains single quotes double quotes uses singleline doublequote nonraw literal in cases uses singleline singlequote nonraw literal stated another way python prefers single quotes formatting string single quotes double quotes repr string without backslash escaping quotes using double quoted string remember repr return typed know typed might never typed it returns something parsed back value the identity x evalreprx x reprevalx repr magical either objects implement repr way preserves constraint repr mostly used providing useful debugging information generating python code,combine r doublequote singlequote escapes print compare r notice r prints way write file prints way like see this i wrote exercise mybugs guido said r moved i love bugs mybugs stallman said moved i love bugs print mybugs print mybugs output guido said i love bugs moved stallman said i love bugs moved question r print everything way i write py file example prints instead line why,2 shebang best solution see python installed type terminal python get something like usrlocalbinpython nothing shows first install python top script insert usrlocalbinpython,textmate seems use builtin python version i assume syspath work how configure use instead i already installed package i use idle interactive sessions i need use textmate thanks,1 you could try something like modelclasses workattachment workattachmentfilebased workattachmentpicture def updateattachmentcountonsavesender instance kwargs instanceworkattachmentcount instanceworksave modelclass modelclasses postsaveconnectupdateattachmentcountonsave sendermodelclass dispatchuidattpostsavemodelclassname disclaimer i tested,i model inheritance levels django class workattachmentmodelsmodel abstract class holds fields required attachment work modelsforeignkeywork added modelsdatetimefielddefaultdatetimedatetimenow views modelsintegerfielddefault class meta abstract true class workattachmentfilebasedworkattachment another base class file based attachments description modelscharfieldmaxlength blanktrue size modelsintegerfieldverbosename size bytes class meta abstract true class workattachmentpictureworkattachmentfilebased picture attached work image modelsimagefielduploadto worksimages widthfield width heightfield height width modelsintegerfield height modelsintegerfield there many different models inherited workattachmentfilebased workattachment i want create signal would update attachmentcount field parent work attachment created it would logical think signal made parent sender workattachment would run inherited models here code receiverpostsave senderworkattachment dispatchuidattpostsave def updateattachmentcountonsavesender instance kwargs update file count work attachment saved instanceworkattachmentcount instanceworksave is way make signal work models inherited workattachment python django prealpha ps i tried one solutions i found net work,3 solution override save method modelform def saveself committrue authors selfcleaneddata authors authorsappendauthorobjectsgetfirstnametfirstname b superbookform selfsavecommitcommit authors bauthorsadda bsave,i created basic django app contains booksauthorspublishers per django book trying use modelform create means modify existing books problem authors field manytomanyfield i choose choice modelform simply wipes existing selection save new one modelspy class bookmodelsmodel title modelscharfieldmaxlength authors modelsmanytomanyfieldauthor publisher modelsforeignkeypublisher publicationdate modelsdatefield def unicodeself return selftitle class bookformmodelform class meta model book authors formsmodelmultiplechoicefieldquerysetauthorobjectsall requiredfalse viewspy def editbookrequest bnone instance none b none instance bookobjectsgettitleb requestmethod post form bookformrequestpost instanceinstance formisvalid formsave return httpresponseredirect contactthanks else form bookforminstanceinstance return rendertoresponse bookformhtml form form cheers edit i found several articles encourage following viewspy authors formsavecommitfalse authorsuser requestuser authorssave formsavemm but still luck hard,1 everything wanted know graphs python httpwikipythonorgmoinpythongraphapi several authors deprecated packages graphs recommend package httpnetworkxlanlgovindexhtml it convert graph numpy matrix scipy sparse matrix etc,disclaimer the author post limited knowledge c python sufficient knowledge java ruby an example opencl programming guide book uses following openclcustomized graph data structure dijkstra algorithm run opencl device void generaterandomgraphgraphdata graph int numvertices int neighborspervertex graphvertexcount numvertices graphvertexarray int mallocgraphvertexcount sizeofint graphedgecount numvertices neighborspervertex graphedgearray intmallocgraphedgecount sizeofint graphweightarray floatmallocgraphedgecount sizeoffloat forint graphvertexcount graphvertexarrayi neighborspervertex forint graphedgecount graphedgearrayi rand graphvertexcount graphweightarrayi floatrand f this data structure based example accelerating large graph algorithms gpu using cuda paper pawan harish p j narayanan basically three arrays vertex array v vertex points neighbour vertices edge array e neighbours vertex follow neighbours vertex immediately array e the third array edge weights two specific opencl related arrays how i represent data structure pythonnumpy i would like use pyopencl,1 i think mean output get this classic problem floating point arithmetic number exactly expressible floating pointer number binary would infinite sequence digits ⠓ decimal this nicely explained page floating point arithmetic python documentation the documentation round explicitly mentions problem,while using round produced output rather in stackoverflow i read best way deal use string formatting upon output if way even round function it even consistent across numbers as numbers gives correct output,3 did check inband registration already the specification httpxmpporgextensionsxephtml if configure ejabberd allow inband registration client able create account exist yet,is possible talk ejabberd interface python xmpp client like sleekxmpp create user exist can someone advice best approach,1 looks like want create daemons python please refer following answer understand write python how create daemon python for monitoring thing implement something check pid written pid file alive using psutil rpint suggested,i series python producers pulling data various sources at moment i starting one manually via terminal i need figure robust system i like create local browser based dashboard i use start stop monitor python processes so using ubuntu would i go starting python script system process opposed terminal window one also order monitor status producer i planning using broker rabbitmq reddis log changes errors i monitor via web dashboard the problem i producer crashes whatever reason still show running dashboard should i create kind supervisor responsible spawning monitoring individual producer i appreciate suggestions i achieve,2 the uid guaranteed unique store one locally,i working application supposed connect imap account read emails pick emails sent lets say mark supposed respond mark automatic response got mate tomorrow difference tomorrow respond email i sure achieve best way i thought storing processed ids table record last check date but i feel best cs solutions,1 you modify headers request xmlrpclib client create custom transport class sendhost method i think modify header add cookie recieved edit check,how i use xmlrpclib python script connect xmlrpc service requires authentication without using xmlrpc authentication to specific i use drupal course service modules i use methods like nodecreate authentication http address server required shibboleth sso i would like use services way loggin shibboleth xmlrpc i simulate regular living user actions parse html etc i managed get cookie login successful ready variable now i want login services via xmlrpclibserver using cookie i obtained different way is possible,1 it seems lxml turn depends libxml c library lxml python wrapper libxml c library how i install c library mingw environment i continue building lxml try tutorial httpwwwpokorradecodingcompilelibxmlmingwhtml for lxml include references libxml headers also link binaries,my python application required lxml when i tried installing lxml vcvrsallbat found error after digging around interwebs i found i needed install mingw add path variable modify distutilscfg use compiler it worked point tried download lxml sources compile fails error reads fatal error libxmlxmlversionh no file directory it seems lxml turn depends libxml c library how i install c library mingw environment i continue building lxml thanks,1 it exponentiation operator in example result b th power check last entry table section,i read following python code ab i know several languages like cccjava even googled operator without results b means,3 simple means power b means power b,i read following python code ab i know several languages like cccjava even googled operator without results b means,3 it python power operator you write pow b,i read following python code ab i know several languages like cccjava even googled operator without results b means,3 it means b languages or mathpow using math module see operator documentation httpdocspythonorglibrarystdtypeshtmlnumerictypesintfloatlongcomplex,i read following python code ab i know several languages like cccjava even googled operator without results b means,1 this means raise power b see httpdocspythonorglibrarystdtypeshtmlnumerictypesintfloatlongcomplex,i read following python code ab i know several languages like cccjava even googled operator without results b means,1 i tried following ubuntu i guess work system well if using glade saving file select save as option instead save prompted enter file name file browser displayed here bottom left corner see selection options file format like file formats gtkbuilder libglade sorry cant upload image select gtkbuilder option save filenamexml choice that to cross check generated file glade file gtkbuilder compatible xml file xml format root node glade file gladeinterface whereas gtkbuilder compatible xml file interface if existing glade file look gtkbuilderconvert script convert gtkbuilder compatible xml file hope helps,i trying design window glade i want use python code using gtkbuilder i somehow generate gtkbuilder xml when i save something glade i get glade file can please help i generate gtkbuilder xml rpm q glade gladefcx thank,1 try browserexecutescript instead seleniumgeteval see answer example,i totally new selenium i want execute javascript snippet following codeas commented code please help selenium import webdriver import selenium seleniumcommonexceptions import nosuchelementexception seleniumwebdrivercommonkeys import keys import time patch rawinputenter patch numbern rel rawinputenter releasen plat rawinputenter portn browser webdriverfirefox browsergetxxxxxxxxxxxxxxxxx pdtfamily browserfindelementbyidprodfamilyid pdtfamilysendkeysdatabase amp tools keystab timesleep pdt browserfindelementbyidproductid pdtsendkeysintelligent agent keystab timesleep pdt browserfindelementbyidpatchcachechkbxid pdtsendkeyskeysspace timesleep pdt browserfindelementbyidmidf pdtsendkeysplat pdt browserfindelementbyidmidg pdtsendkeysamerican english here i want execute javascript submitform patchcacheadd event ok return false browserclose if i use seleniumgetevalsubmitform patchcacheadd event ok return false errors attributeerror module object attribute geteval i,3 afaik builtin implementation a straightforward solution would import collections def depthfirstsearchnode getchildren depth yield node depth child getchildrennode in upcoming python following written yield depthfirstsearchchild getchildren depth n depthfirstsearchchild getchildren depth yield n def breadthfirstsearchnode getchildren depth queue collectionsdequenode depth queue node depth queuepopleft queueextendn depth n getchildrennode yield node depth then easily use follows def domgetchildrennode nodelist nodegetnodelist rangenodelistgetlength yield nodelistitemi node depth depthfirstsearchsomedomelement domgetchildren something,i actually using jython pretty new python way things when i use javaxswingtreedefaultmutabletreenode i simply go depthbreadthfirstenumeration but i stuff dom tree eg xml equivalent strikes must elegant powerful way pythonjython using recursive generator hopefully i want general purpose utility methods essentially enumeration type tree object throw might supply method gives children given node case orgwcdomnode would getchildnodes might want second optional param would specify depth breadth to surprise i able find simple answer googling looking example,1 having problem found two definitive solutions i thought worth posting another answer this problem mysql default transaction mode django opens transaction start means default see changes made database demonstrate like run django shell terminal mymodelobjectsgetidmyfield u old and another terminal mymodelobjectsgetidmyfield u old mymodelobjectsgetid amyfield new asave mymodelobjectsgetidmyfield u new back terminal demonstrate problem still read old value database mymodelobjectsgetidmyfield u old now terminal demonstrate solution djangodb import transaction transactioncommitmanually def flushtransaction transactioncommit mymodelobjectsgetidmyfield u old flushtransaction mymodelobjectsgetidmyfield u new the new data read here code easy paste block docstring djangodb import transaction transactioncommitmanually def flushtransaction flush current transaction read stale data use long running processes make sure fresh data read database this problem mysql default transaction mode you fix setting transactionisolation readcommitted mycnf calling function appropriate moment transactioncommit the alternative solution change mycnf mysql change default transaction mode transactionisolation readcommitted note relatively new feature mysql consequences binary logging slaving you could also put django connection preamble wanted update years later now django turned autocommit mysql longer problem the example works fine without flushtransaction code whether mysql repeatableread default readcommitted transaction isolation mode what happening previous versions django ran non autocommit mode first select statement opened transaction since mysql default mode repeatableread means updates database read subsequent select statements hence need flushtransaction code stops transaction starts new one there still reasons might want use readcommitted transaction isolation though if put terminal transaction wanted see writes terminal would need readcommitted the flushtransaction code produces deprecation warning django i recommend remove,i using django database models process called http request the process supposed poll new data every seconds processing i loop sleeps seconds gets unhandled data database what i seeing first fetch process never sees new data i ran tests looks like django caching results even though i building new querysets every time to verify i python shell mymodelobjectscount here i added data another process mymodelobjectscount mymodelobjectsupdate mymodelobjectscount as see adding new data change result count however calling manager update method seems fix problem i find documentation update method idea bad things might my question i seeing caching behavior contradicts django docs say and i prevent happening,3 you use set keep track already processed words words set result word stringsplit word words result result word wordsaddword print result,following example string calvin klein design dress calvin klein how i remove second two duplicates calvin klein the result look like string calvin klein design dress second duplicates removed sequence words changed,1 def uniquelistl ulist ulistappendx x l x ulist return ulist acalvin klein design dress calvin klein joinuniquelistasplit,following example string calvin klein design dress calvin klein how i remove second two duplicates calvin klein the result look like string calvin klein design dress second duplicates removed sequence words changed,3 wxpython key events here wxpython docs page subject httpwwwwxpythonorgdocsapiwxkeyeventclasshtml wxpython wrap every single thing wxwidgets the developers think needed wrap stuff already great support python thus see python socket support httpdocspythonorglibrarysockethtml httpdocspythonorghowtosocketshtml httpdocspythonorglibrarysocketserverhtml and want get really heavy look twisted framework there several articles using wxpython httptwistedmatrixcomdocumentscurrentcorehowtochoosingreactorhtml httpwikiwxpythonorgwxpythonandtwisted httpcodeactivestatecomrecipesusingwxpythonwithtwistedpython,i want write gui application listens keyboard events client side generated events network port server side generated events i could use high level advice some additional info i using wxpython module gui i could set socket nonblocking mode way i keep polling socket keeping executing recv command i earlier i recall used considerable resources i could use thread module since i familiar i try avoid maybe i advice would appreciated,1 in python could use collectionsordereddict collections import ordereddict calvin klein design dress calvin klein print joinordereddictww w ssplitkeys,following example string calvin klein design dress calvin klein how i remove second two duplicates calvin klein the result look like string calvin klein design dress second duplicates removed sequence words changed,1 cut paste itertools recipes itertools import ifilterfalse def uniqueeverseeniterable keynone list unique elements preserving order remember elements ever seen uniqueeverseen aaaabbbccdaabbb a b c d uniqueeverseen abbccad strlower a b c d seen set seenadd seenadd key none element ifilterfalseseencontains iterable seenaddelement yield element else element iterable k keyelement k seen seenaddk yield element i really wish could go ahead make module recipes soon i much like able itertoolsrecipes import uniqueeverseen instead using cutandpaste every time i need something use like def uniquewordsstring ignorecasefalse key none ignorecase key strlower return joinuniqueeverseenstringsplit keykey string uniquewordsstring,following example string calvin klein design dress calvin klein how i remove second two duplicates calvin klein the result look like string calvin klein design dress second duplicates removed sequence words changed,3 have three lists one condition loop input set loop sorting tuple correct target list this perform on linear time fastest possible asymptotic runtime problem it also loop list,i seeking fastest way extract tuple members list conditions example from list tuple eg i need extract members first tuple position second tuple position last tuple position which extract example first condition nothing second condition last condition this example small i need perform list thousands tuples from code i produced answers results sec mynaive like proposed emil vikstrã¶m mynaive tim pietzcker don import itertools operator time copy operator import itemgetter def combinationswithreplacementcountsn r a n examplen individualsballs a genotypesboxes size n r indices itertoolscombinationsrangesize n print indices starts index index indices stops indices size yield tuplemapoperatorsub stops starts xp listcombinationswithreplacementcounts small case atimetime temp n xp n xp xp minnn minnn minnn tempappendi atimetime n xp n xp xpcopy copydeepcopyxp xp minnn minnn minnn xpcopyremovei atimetime n xp n xp output xp tminnn tminnn tminnn atimetime n xp n xp l sortedxp keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem l sortedlfitered keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem l sortedlfitered keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem atimetime print soluce mynaive like proposed emil vikstrã¶maa print soluce mynaiveaa print soluce tim pietzckeraa print soluce donaa,2 string calvin klein design dress calvin klein def uniquifystring output seen set word stringsplit word seen outputappendword seenaddword return joinoutput print uniquifystring,following example string calvin klein design dress calvin klein how i remove second two duplicates calvin klein the result look like string calvin klein design dress second duplicates removed sequence words changed,2 l output l output this fast evaluated false third condition so example list comparisons necessary you might save time memory depending filtered data use generator expression instead l item l something item,i seeking fastest way extract tuple members list conditions example from list tuple eg i need extract members first tuple position second tuple position last tuple position which extract example first condition nothing second condition last condition this example small i need perform list thousands tuples from code i produced answers results sec mynaive like proposed emil vikstrã¶m mynaive tim pietzcker don import itertools operator time copy operator import itemgetter def combinationswithreplacementcountsn r a n examplen individualsballs a genotypesboxes size n r indices itertoolscombinationsrangesize n print indices starts index index indices stops indices size yield tuplemapoperatorsub stops starts xp listcombinationswithreplacementcounts small case atimetime temp n xp n xp xp minnn minnn minnn tempappendi atimetime n xp n xp xpcopy copydeepcopyxp xp minnn minnn minnn xpcopyremovei atimetime n xp n xp output xp tminnn tminnn tminnn atimetime n xp n xp l sortedxp keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem l sortedlfitered keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem l sortedlfitered keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem atimetime print soluce mynaive like proposed emil vikstrã¶maa print soluce mynaiveaa print soluce tim pietzckeraa print soluce donaa,2 ok it took delving werkzeugrouting flaskhelpersurlfor code i figured you change endpoint route words name route approutecanonicalpath endpointfoocanonical approutealternatepath def foo return hi approutewheee def bar return canonical path alternative urlforfoocanonical urlforfoo produce canonical path canonicalpath alternative alternatepath there drawback approach flask always binds last defined route endpoint defined implicitly foo code guess happens redefine endpoint all urlfor oldendpoint throw werkzeugroutingbuilderror so i guess right solution whole issue defining canonical path last name alternative since urlfor foo used canonical path options rather defining endpoint alternative path use urlfor approute alternativepath endpoint fooalternative dont wanna mess endpoint want urlfor foo pointing canonical path approute canonicalpath def foo pass approute wheee def bar return canonical path alternative urlforfoo urlforfooalternative,so i method accessible multiple routes approutecanonicalpath approutealternatepath def foo return hi now i call urlforfoo know i get first route,3 you could use operator mongodb fetch rows iterate mongodocuments mongocollectionfind medicalobjectid resultset doc mongodocuments print mongodocuments i tested comment doesnt work edit mongodocuments mongocollectionfindmedicalobjectid strpqr print nn thisdocument mongodocuments print thisdocument,edit i somewhat distilled question mongodocuments mongocollectionfindmedicalobjectid print nn thisdocument mongodocuments print thisdocument print pqr mongodocuments mongocollectionfindmedicalobjectid pqr print nn thisdocument mongodocuments print thisdocument my problem first code chunk i use number key query works but second chunk i use variable get output i beginner python pymongo please bear i list row i want query mongodb collection entry list the collection format collection pk attribute attribute attribute i want call mongodb connection iterate entry list rowipk return attributes output ie mongodocuments mongocollectionfind pk row mongodocuments mongocollectionfind pk row the code i row resultset print row mongodocuments mongocollectionfind medicalobjectid row print mongodocuments thisdocument mongodocuments print print thisdocument however get output i going wrong print mongodocuments get pymongocursorcursor object xe,2 if care order resulting items i suggest lookup sorted list break condition first nonmatching item would skip list tails operator import itemgetter l lsource sortedl keyitemgetter reversetrue lfitered item l item break lfitered appenditem l sortedl keyitemgetter reversetrue,i seeking fastest way extract tuple members list conditions example from list tuple eg i need extract members first tuple position second tuple position last tuple position which extract example first condition nothing second condition last condition this example small i need perform list thousands tuples from code i produced answers results sec mynaive like proposed emil vikstrã¶m mynaive tim pietzcker don import itertools operator time copy operator import itemgetter def combinationswithreplacementcountsn r a n examplen individualsballs a genotypesboxes size n r indices itertoolscombinationsrangesize n print indices starts index index indices stops indices size yield tuplemapoperatorsub stops starts xp listcombinationswithreplacementcounts small case atimetime temp n xp n xp xp minnn minnn minnn tempappendi atimetime n xp n xp xpcopy copydeepcopyxp xp minnn minnn minnn xpcopyremovei atimetime n xp n xp output xp tminnn tminnn tminnn atimetime n xp n xp l sortedxp keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem l sortedlfitered keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem l sortedlfitered keyitemgetter reversetrue lfitered item l item minnn break lfiteredappenditem atimetime print soluce mynaive like proposed emil vikstrã¶maa print soluce mynaiveaa print soluce tim pietzckeraa print soluce donaa,1 you need pass quote ascii str string instead unicode string you porbbley need call termencode utf pass result quote,i build customized search web page using search engine like for client side encode search terms send server using httpxxxappspotcomsearchqencodeuicomponentqterms at server sideappengine python decoding text using urllib like qterms urllibunquoteplusqterms encoded sterms using qterms urllibquoteplusqterms send qtermsto another server server get xml response above designs works well pure engilsh words pass non english words givin error like traceback recent call last file basepythonruntimepythonlibversionsgoogleappengineextwebappwebapppy line call handlergetgroups file basedatahomeappsssearchepicsearchpy line get qterms urllibquoteplusqterms file basepythonruntimepythondistlibpythonurllibpy line quoteplus return quotes safe file basepythonruntimepythondistlibpythonurllibpy line quote res mapsafemapgetitem keyerror u uc,1 string calvin klein design dress calvin klein words stringsplit print joinsortedsetwords keywordsindex this sorts set unique words string word index original list words,following example string calvin klein design dress calvin klein how i remove second two duplicates calvin klein the result look like string calvin klein design dress second duplicates removed sequence words changed,3 this pretty nasty problem actually stream lines pattern match across multiple lines braces also pattern match json it sort jsonpreparse followed json parse json comparison formats easy parse always necessary go parsing library nevertheless solve conflicting issues generators rescue the beauty generators problem like stack top gradually abstracting away difficulty problem whilst maintaining laziness i also considered using mechanism passing back values generator send fortunately found i need use to solve first problems need sort streamingfinditer streaming version refinditer my attempt pulls lines needed uncomment debug statement see whilst still returning matches i actually modified slightly yield nonmatched lines well matches marked first part yielded tuple import def streamingfinditerpatstream stream print read next line researchpats yield break yield mgroup resplitpats with possible match braces account time whether braces balanced return either simple compound objects appropriate braces whitespaceesc bracesesc joinbraces balancemapdictzipbraces bracespat bracesesc nobracespat bracesesc untilbracespatnobracespatbracespat def simpleorcompoundobjectsstream obj unbalanced cm streamingfinditerrecompileuntilbracespatstream c remainder line returned nothing interesting unbalanced yield else obj c match returned unbalanced yield obj else obj unbalanced balancemapm unbalanced yield obj obj this returns tuples follows string simple nonbraced objects easy parse compound objects basically nasty part done we final level parsing see fit for example use jeremy roman iterload function thanks parsing single line def streamingiterloadstream co simpleorcompoundobjectsstream x iterloado yield x test opentestjsonw ofwrite hello goodbye animals dog lots mice cat ofclose f opentestjsonr streamiterloadfreadlines print fclose i get results turn debug line see pulls lines needed u hello u goodbye u animals u dog u lots mice u cat this work situations due implementation json library impossible work entirely correctly without reimplementing parser,i like read multiple json objects filestream python one time unfortunately jsonload read endoffile seem way use read single object lazily iterate objects is way using standard library would ideal thirdparty library i use instead at moment i putting object separate line using jsonloadsfreadline i would really prefer need example use examplepy import myjson json import sys jsoniterloadsysstdin printworking typeo intxt foo bar baz example session python examplepy intxt working dict working int working int working list working int working int working int,3 python strings immutable in python string object immutable time string assigned variable new object created memory represent new value wikipedia doc immutability specific python example one simple way get behavior want wrap string class thusly class myclass somestr any val a myclass asomestr bob ba bsomestr alice printasomestr printbsomestr output alice alice so ba assignment creates shallow copy the two variables a amp b point object,i need convince bad idea i want assign second name variable whose contents may change a bob ba wrong function i want figure something works a alice print a print b i want a b print alice instead b prints bob a prints alice why i want in code i using one name bit data makes sense processing different name makes sense user input argparse seems want assign variable name based command line option so i want use one name data entered another name processed i would prefer avoid copying one fallback position,3 i argue processing part separate module input part neither reason know input data store appropriate place pass processing part parameter using whatever name want,i need convince bad idea i want assign second name variable whose contents may change a bob ba wrong function i want figure something works a alice print a print b i want a b print alice instead b prints bob a prints alice why i want in code i using one name bit data makes sense processing different name makes sense user input argparse seems want assign variable name based command line option so i want use one name data entered another name processed i would prefer avoid copying one fallback position,1 you values python consider variables names references eg lists dictionaries abob ba a alice print a b print alice twice,i need convince bad idea i want assign second name variable whose contents may change a bob ba wrong function i want figure something works a alice print a print b i want a b print alice instead b prints bob a prints alice why i want in code i using one name bit data makes sense processing different name makes sense user input argparse seems want assign variable name based command line option so i want use one name data entered another name processed i would prefer avoid copying one fallback position,1 the problem matches subsection first thing make sure inside title we need make sure beginning match otherwise first three ignored subtitle matched this trick means matches preceded we also end make sure gives final result refindall xremultiline mainsection nsome text heren mainsection ntext goes heren you could also remove check end title replace newline that may better sure new line end title refindall n xremultiline mainsection some text heren mainsection text goes heren edit section recompiler result mo sectionsearchx previousend previoussection none mo none start mostart previoussection resultappendprevioussection xpreviousendstart previoussection mogroup previousend moend mo sectionsearchx previousend resultappendprevioussection xpreviousend print result it simple looks repeatedly search section title previous one add result text beginning title end previous one adjust suit style needs the result mainsection nsome text nsubsection nother text nn mainsection ntext goes nsubsecttion nother text goes,i text similar following mainsection some text subsection other text mainsection text goes subsecttion other text goes in text mainsection different names everything user wants same goes subsections what want regex get text mainsection including subsection one yes wikipage all mainsections names start end all subsections name regex recompile remultiline regexfindalltext but returns separate section meaning perfectly returns mainsection sees subsection i hope someone help bugging time edit the result mainsection some text herensubsection other text heren mainsection text goes herensubsecttion other text goes heren edit i rewritten code use regex i came conclusion easy enough parse which makes bit readable so code def createtokensfromtexttext sections cursection none curlines line textsplit n line linestrip linestartswith linestartswith cursection sectionsappend cursection n joincurlines curlines cursection line continue cursection curlinesappendline cursection sectionsappend cursection n joincurlines return sections thanks everyone help all answers provided helped lot,1 i used doug hellman multipartform class blog upload files mail server sucessfully httppymotwcomurllibindexhtmlmoduleurllib hopefully use well,need upload image file use multipartposthandlerpy people suggest still work code params upload openjpg rb rb opener urllibbuildopenermultipartposthandler res openeropenurl params code multipartposthander def multipartencodevars files boundary none buffer none boundary none boundary mimetoolschooseboundary buffer none buffer forkey value vars buffer srn boundary buffer contentdisposition formdata names key buffer rnrn value rn forkey fd files filesize osfstatfdfilenostatstsize filename fdnamesplit contenttype mimetypesguesstypefilename applicationoctetstream buffer srn boundary buffer contentdisposition formdata names filenamesrn key filename buffer contenttype srn contenttype buffer contentlength srn filesize fdseek buffer rn fdread rn buffer srnrn boundary return boundary buffer multipartencode callablemultipartencode httpsrequest httprequest error appears buffer rn fdread rn error ascii codec decode byte xff position ordinal range problem scrowed lot please help thx,1 if negative numbers lyst alice john sally print sortedlyst keylambda k intk kisdigit else k here version rely cpython details works python sortedlyst keylambda k intk kisdigit else k here key tuple the first item tuple number text causes numbers sort text then second item tuple value causes values sorted appropriately within group i originally used floatinf make text items sort numbers approach inspired tom zych answer simpler faster if want string sorting case sensitive add lower sortedlyst keylambda k intk kisdigit else klower,i list strings represent integers well names the default string compare following sorted alice john sally alice john sally i would like sort list follows alice john sally means sort strings represent integer numerically sort real strings alphabetically append list i tried compare method i know determine cleanly string represents integer without tryexcept thanks advance,3 the following works python python l alice john sally num alpha numappendelem elemisdigit else alphaappendelem elem l result sortednum keyint sortedalpha printresult it avoids comparing strings ints partitioning list the reason avoid comparison either fully specified python prohibited python,i list strings represent integers well names the default string compare following sorted alice john sally alice john sally i would like sort list follows alice john sally means sort strings represent integer numerically sort real strings alphabetically append list i tried compare method i know determine cleanly string represents integer without tryexcept thanks advance,3 this work versions sort take key function def sortkeys try n ints return n except valueerror return,i list strings represent integers well names the default string compare following sorted alice john sally alice john sally i would like sort list follows alice john sally means sort strings represent integer numerically sort real strings alphabetically append list i tried compare method i know determine cleanly string represents integer without tryexcept thanks advance,3 if really want convinced bad idea maybe argparse example want rename variable used differently option name use dest option argparseaddargument only one examples doc parser argparseargumentparser parseraddargument foo dest bar parserparseargs foo xxx split namespacebar xxx,i need convince bad idea i want assign second name variable whose contents may change a bob ba wrong function i want figure something works a alice print a print b i want a b print alice instead b prints bob a prints alice why i want in code i using one name bit data makes sense processing different name makes sense user input argparse seems want assign variable name based command line option so i want use one name data entered another name processed i would prefer avoid copying one fallback position,2 here i understand question b c collections functions consume data type a what want group functions logically i suggest one following separate functions classes b c operate a hasa relationship the functionsmethods could static need separate functions modules b c creating toplevel function definitions i think inheritance would bad solution problem i think isa relationship,i trying something along lines class a def init self xnone ynone selfx x selfy class b a def dosomethinginbscontext self print in b class c a def dosomethingincscontext self print in c a b bdosomethinginbscontext c cdosomethingincscontext as expected code generate error typeerror unbound method dosomethinginbscontext must called b instance first argument got a instance instead the underlying reason design a container data say table b c set operations a both b c operate data conceptually distinct set operations performed data i could club operations b c inside a i want create separation concepts as example table i perform different sets operations may grouped say calculus trignometry so atable b calculus ctrignometry this reminded modelviewcontroller paradigm slight twist i came following solutions b c implemented conceptually different classes viewcontroller maintain reference instance a operate instance since b c group together methods a create modules functions operate instance a i like either solutions much slightly better i sure bettercleanermore pythonic way solve problem any pointers,3 move state additional class make instance attribute a class stateobject def init self xnone ynone selfx x selfy class aobject def init self statenone selfstate state class b a def init self statenone superb selfinitstate def dosomethinginbscontext self print selfstatex class c a def init self statenone superc selfinitstate def dosomethingincscontext self print selfstatey state b bs c cs bdosomethinginbscontext cdosomethingincscontext,i trying something along lines class a def init self xnone ynone selfx x selfy class b a def dosomethinginbscontext self print in b class c a def dosomethingincscontext self print in c a b bdosomethinginbscontext c cdosomethingincscontext as expected code generate error typeerror unbound method dosomethinginbscontext must called b instance first argument got a instance instead the underlying reason design a container data say table b c set operations a both b c operate data conceptually distinct set operations performed data i could club operations b c inside a i want create separation concepts as example table i perform different sets operations may grouped say calculus trignometry so atable b calculus ctrignometry this reminded modelviewcontroller paradigm slight twist i came following solutions b c implemented conceptually different classes viewcontroller maintain reference instance a operate instance since b c group together methods a create modules functions operate instance a i like either solutions much slightly better i sure bettercleanermore pythonic way solve problem any pointers,1 how make rotatable attribute vector class class vectorobject def initselfvrotatablefalse selfvalue v selfrotatable rotatable and use properties access values easily class vectorsobject def initself v v v selfvectors vectorvvectorvrotatabletruevectorvrotatabletrue property def vself return selfvectorsvalue property def vself return selfvectorsvalue property def vself return selfvectorsvalue def rotateself angle vector selfvectors vectorrotatable vectorvalue dorotatevectorvalue angle class morevectorsvectors def initself v args kwargs supermorevectors selfinitargs kwargs selfvectorsappendvectorvrotatabletrue property def vself return selfvectorsvalue,i want group attributes instances class would easy iterate attributes belonging group the obvious answer would put list dict i able access attributes object i would prefer some code make clear i want here i actually list real attributes class vectorsobject def initself v v v selfv v selfv v selfv v selfrotatable v v def rotateself angle v selfrotable newvector dorotategetattrself v angle setattrself v newvector class morevectorsvectors def initself v args kwargs supermorevectors selfinitargs kwargs selfv v selfrotableappend v now calling rotate know vectors rotate i add vectors list dynamically however job look elegant i manage list is simpler way write i thought storing attributes dictionary group key use properties let access items dictionary attributes that would clean enough i know set properties dynamically inside method,2 i created git repository demonstrate solve problem httpsgithubcomsmokedicepydbustree the code rather slow use call backs if anyone would like improve code please post push repository,how i print tree available information dbus bus name interface method signature interface method signature method signature bus name interface method signature,1 as written i made two mistakes code therefore nothing wrong logging module configuration i made the blank spaces added obscure statement code somewhere deep subfunction once removed logging output nice therefore i close subject the redirection console logging stderr permitted highlight easily thanks commenters,edit the blank spaces added obscure statement code somewhere deep subfunction once removed logging output nice therefore i close subject the redirection console logging stderr permitted highlight easily thanks commenters i using python logging module handle logging project log file standard output this works quite nice based config file different logging levels problem standard output lines starting blank spaces this seems linked time elapsed two writings something like one space per second for sure i made error logging config file i really ease i cannot identify changing logging level set change anything could someone bring help report file content info ptool ptool launched commandline info ptool starting instantiation tools info ptool initialization completed info ptool execution started warning ptool process project file crc check failed info ptool xsd version check passed process error ptool xsd validation failed process info ptool process call found id short name info libtoolsitool importing acicd info libtoolsitool importing acicd info libtoolsvtool verifying project standard output info ptool ptool launched commandline info ptool starting instantiation tools info ptool initialization completed info ptool execution started warning ptool process project file crc check failed info ptool xsd version check passed process project error ptool xsd validation failed process project info ptool process call found id short info libtoolsitool importing acicd info libtoolsitool importing acicd info libtoolsvtool verifying project error ptool crc found projectrep info libtoolsgtool generating binary error ptool crc found projectreports info libtoolslaf writer laf writing started note lines starting blank space here i configure logging module module ptoolpy defining logging logconfig loggingconf loggingconfigfileconfigospathjoinospathsplitfile resources logconfig logger logginggetlogger ptool adding message loggerinfo message logger logging configuration file loggingconf loggers keysrootptool handlers keysconsolehandlerlogfilehandler formatters keysconsoleformatterfileformatter loggerroot leveldebug handlersconsolehandlerlogfilehandler loggerptool leveldebug handlersconsolehandlerlogfilehandler qualnameptool propagate handlerconsolehandler classstreamhandler levelinfo formatterconsoleformatter argssysstdout handlerlogfilehandler classfilehandler leveldebug formatterfileformatter args ptoollogtxt w formatterfileformatter formatasctimes levelnames names messages datefmt formatterconsoleformatter formatlevelnames names messages datefmt,1 basically say different threads django app access conflict one reading value somevar another modifying so seem solving wrong problem really need design application way access conflicts happen an ideal solution would shared state use threadinglocal store data accessible one current thread you sort affinity issues though one request goes thread next request client minutes later goes another thread see data set previous request another solution would using database serialize changes take sqlite almost weightless supports transactions one change locks somevar record update another transaction would change fail you sort meaningful manner it would help described bigger problem solving,i simple problem i developing something i need classes accessing common variables like somevarfoo class asomeparent def evalclassself global somevar return somevar def indexrequestinputsomevar global somevar somevarinputsomevar return httpresponseaevalclass problem that code runs django every request code still running somevar reiceve new value if requests happen overlap i enp values somevar one request set another request solution what came mind use instances single class class parent somevarnone def setsomevarselfsomevar selfsomevarsomevar class asomeparent note parent class not parent def evalclassself here i would like retrieve somehow somevar return somevar def indexrequestinputsomevar pparent psetsomevarinputsomevar return httpresponsepaevalclass note i cannot pass variables classes able access enclosing parent class sympy function classes need passed sympy interpreter thank advance,1 i think i figured as usual adding deleting widgets need call layout parent case scrolled panel getting new children you also call setupscrolling recalculate much space whether needs scrollbars here example works windows import wx import wxlibscrolledpanel scrolled class myformwxframe def initself wxframeinitself none wxidany tutorial size add panel looks correct platforms selfpanel wxpanelself wxidany scrolled panel stuff selfscrolledpanel scrolledscrolledpanelselfpanel style wxtabtraversalwxsunkenborder namepanel selfscrolledpanelsetautolayout selfscrolledpanelsetupscrolling words a quick brown insane fox jumped over fence ziplined coversplit selfspsizer wxboxsizerwxvertical word words text wxtextctrlselfscrolledpanel valueword selfspsizeraddtext selfscrolledpanelsetsizerselfspsizer btn wxbuttonselfpanel labeladd widget btnbindwxevtbutton selfonadd panelsizer wxboxsizerwxvertical panelsizeraddspacer panelsizeraddselfscrolledpanel wxexpand panelsizeraddbtn selfpanelsetsizerpanelsizer def onaddself event print onadd newtext wxtextctrlselfscrolledpanel valuenew text selfspsizeraddnewtext selfscrolledpanellayout selfscrolledpanelsetupscrolling run program name main app wxappfalse frame myformshow appmainloop,i toying seem figure selfpanel wxpanelself wxidany i scrolledpanel inside panel scroll selfpanel wxpanelself wxidany selfsteppanel wxscrollpanelscrolledpanelselfpanel stylewxexpand selfsteppanelsetupscrollingscrolltotopfalse sizer wxboxsizerwxvertical selfsteppanelsetsizerandfitsizer update function goes like sizer selfsteppanelgetsizer add widgets selfsteppanelsetsizerandfitsizer i add widgets sizer later user clicks button i tried auto layout fitinside update seem scroll steppanel i add widgets edit adding info the idea selfpanel area top scroll another panel lower portion scrolls selfsteppanel appears steppanel grows viewable area selfpanel edit solved see comment,1 days special function numpynantonuma,replacement value another within operation arrays search within array replace value another example array nan nan nan nan nan nan nan replace nan thanks response,3 in bsonobjectid out bsonobjectidobjectid they exactly thing,i generated objectid two different methods follows userubuntu python python r apr gcc linux type help copyright credits license information method one bsonobjectid import objectid ida objectid printida ecbdca method two import bson idb bsonobjectid printidb eccadca question what difference two methods when i use thank,2 first known i know little python i never programmed formally codepad said works goes d sorry expression complex ss this asked i believe codepad code import wikitext mainsection some text subsection other text mainsection text goes subsecttion other text goes outputarray refindall ss wikitext print outputarray produces result mainsection nsome text herensubsectionnother text herenn mainsection ntext goes herensubsecttionnother text goes edit broken expression essentially says first look behind assert equals sign match two equals signs capture one characters equals sign match two equals signs then verify equals signs following start capturing group ss match zero any character even crlf be lazy look ahead verify either end or i look behind equals sign two equals signs one characters equals signs two equals signs verify equals signs following end lookahead group end capturing group line line specify capturing groups main section title main section content respectively line begs lot explanation pretty fluent regex the s inside character class match anything whitespace whitespace ie anything whatsoever one alternative using operator depending upon compiler options ability specify options might might match crlf carriagereturnlinefeed since want match multiple lines easiest way ensure match the end means match zero instances anything character class be lazy about it lazy quantifiers sometimes called reluctant opposite default greedy quantifier without following consume source character unless source follows cannot matched part expression follows lazy quantifier in words consume characters finds either end source text or another main section specified exactly two two equals signs either side one characters equals sign including whitespace without lazy operator would try consume entire source text backtrack could match one things expression end source section header line lookahead specifies expression follwoing able matched consumed end edit afaik complex order properly exclude subsections if want match section name section content named groups try psectionnamepsectioncontentss if like i break just ask edit see edit end edit,i text similar following mainsection some text subsection other text mainsection text goes subsecttion other text goes in text mainsection different names everything user wants same goes subsections what want regex get text mainsection including subsection one yes wikipage all mainsections names start end all subsections name regex recompile remultiline regexfindalltext but returns separate section meaning perfectly returns mainsection sees subsection i hope someone help bugging time edit the result mainsection some text herensubsection other text heren mainsection text goes herensubsecttion other text goes heren edit i rewritten code use regex i came conclusion easy enough parse which makes bit readable so code def createtokensfromtexttext sections cursection none curlines line textsplit n line linestrip linestartswith linestartswith cursection sectionsappend cursection n joincurlines curlines cursection line continue cursection curlinesappendline cursection sectionsappend cursection n joincurlines return sections thanks everyone help all answers provided helped lot,1 you matching match number three digits including leading zeroes,if i example regex string abcpsomeintdd is easy way determine group numberint i know int say needed processed somewhere else needed deduced match object,1 mgroupwhicheveryouwantisdigit,if i example regex string abcpsomeintdd is easy way determine group numberint i know int say needed processed somewhere else needed deduced match object,2 pyramid much flexible authentication system and yes want something simple like django usergrouppermission concept flexible might scary pyramid user object makes assumptions store data orm use therefore something like contribauth you need hashsalt passwords using library cryptacular passlib found pypi as far wanting usergrouppermissions within pyramid system achievable pretty simply defining rootfactory acl maps groups permissions permissions assigned views thus pretty static usually if like groups pyramid calls principals dynamic also achievable i suggest looking pyramid wiki tutorial well shootout demo there also couple thirdparty packages assisting authorization within pyramid plan using sqlalchemy apex full stack solution zigguratfoundations lowerlevel layer sqlalchemy help set users groups application your question fairly high level authorization hard problem i stop avoid regurgitating tutorials resources already exist pyramid tutorials several thirdparty examples if specific questions please feel free ask another question,i building webapp needed choose django pyramid i decided go pyramid i understand pyramid comes authenticationauthorization framework looks nice but i seen anywhere pyramid usersgroupspermissions defined in django things come free i using sqlalchemy wondering similar usersgroupspermissions already built i import i rather define objectsmappings hashsalting passwords django definitions things pretty much i need can anyone point something i use or i need roll,3 i think best bet use posix standard interface eg getent via httppypipythonorgpypigetent package getentpasswd work pretty much analogous getpwent system call edit if remotely probably means install python packages hosts might want read contents etcpasswd parse something like assuming ssh command path set public key authentication import subprocess users p subprocesspopen ssh host name ip address cat etcpasswd stdoutsubprocesspipe passwd pstdoutreadlines line passwd fields linesplit uid intfields uid uid usersappendfields print users,i created python script retrieve local users windows machines network i used winnet library i need mac linux machines i search still nothing long list mac linux user groups meet around house does anyone suggested library look,3 you prevmiles miles milest miles prevmiles guarantees milest try switching order two lines,i trying read file contains city names odometer reading much fuel left the contents text file kennewick br bentoncity br prosser br grandview br sunnyside br granger br toppenish br wapato br uniongap br yakima br selah br ellensburg br thorp br rosyln br easton br northbend br preston br issaquah br eastgate br mercerisland br seattle br part assignment subtracting current readthrough last readthrough values stored variable miles def busroute path c ext txt lines stopname miles prevmiles milest fuel mpg filename inputplease enter file name the file path c extension txt required infile openpath filename ext r lines infile stopname miles fuel linessplit miles floatmiles fuel floatfuel prevmiles miles milest miles prevmiles miles printsince last stop floatmilest miles my problem i trying store lastread value miles variable called prevmiles subtract prevmiles last mileage read current reading miles keeps subtracting current miles current miles obviously making value i want printed,1 what wrong module import needed object explicit better implicit,i large python code many modules classes i special class whose single instance needed everywhere throughout code threaded application instance class also holds thread local storage locks etc it bit uncomfortable always populate instance every imported module i know using globals best practice anyway import hook python i hooking instance available every modules without extra work it work normal imports mod import import constructs if possible suggest better solution certenly fun pass instance constructors every classes etc inheritance also help since i modules without classes also i need single instance class class master def importmoduleself name mod importname modm self return mod master currently i thinking something like i use mimportmodule import modules modules instance master class name available i use mimportmodule etc but i give use normal import statements i write examplemod mmoduleimportexamplemod instead import examplemod sure i assign examplemodm,1 there two transformations performed original function converted function three arguments function takes tuple conversion function tuple function takes list tuples first transformation in haskell function called uncurry documented this twoargument version versions could easily created second transformation also haskell sets functions lift names here page haskell wiki lifting i think page explains better i could lifting concept allows transform function corresponding function within another usually general setting so case lifting function operating tuples operating list tuples notes op asked mathematical name decorators i know would i heard haskell supposed like executable mathematics i think haskell terminology good starting point ymmv op asked fp name processes again i know i assume haskell terminology acceptable,class fooobject def initselff selff f def callselfargslist def wrappedfargslist return selffargs args argslist return wrappedfargslist name main class abcobject foo def fabc return abc range b range c range data listzipabc printabcfdata i wrote years back when decorate function fx foo becomes flist xs what process called what what functional programming name its currying i know simple mapflist xs could done what decoratorsoperation decorating called mathematically,2 certainly fun pass instance constructors every classes you set global class module like config import myappenviromentinitpy class thatsingleinstanceclass pass create singleton object directly function init module singleton thatsingleinstanceclass myappsomewherepy need use object importing myappenviroment import singleton class someclass def initself need pass object print always object singleton,i large python code many modules classes i special class whose single instance needed everywhere throughout code threaded application instance class also holds thread local storage locks etc it bit uncomfortable always populate instance every imported module i know using globals best practice anyway import hook python i hooking instance available every modules without extra work it work normal imports mod import import constructs if possible suggest better solution certenly fun pass instance constructors every classes etc inheritance also help since i modules without classes also i need single instance class class master def importmoduleself name mod importname modm self return mod master currently i thinking something like i use mimportmodule import modules modules instance master class name available i use mimportmodule etc but i give use normal import statements i write examplemod mmoduleimportexamplemod instead import examplemod sure i assign examplemodm,2 in example represent exponation also used unpacking operators instance using list variables unknown length args function i new programming python i difficulty using example perhaps one experienced users demonstrate,i read following python code ab i know several languages like cccjava even googled operator without results b means,3 don forget pack buttons frame selfb buttonframeimageselfemptycommandselfmakemove selfbpacksideleft,i currently working making python version game connect four it going pretty basic using tkinter interface i think i code laid i getting errors currently creating actual game board right i coded make first row gameboard x showing here code tkinter import class cell def initselfcellnumframegame selfemptyphotoimagefile emptygif selfblackphotoimagefile blackgif selfredphotoimagefile redgif selfb buttonframeimageselfemptycommandselfmakemove selfframe frame selfgame game selfnum cellnum def packself selfgamesquarepack def makemoveself player selfgameplayer selfplayer black selfbconfigimageselfblack num selfnum selfgamemovesplayerappendnum selfgamefreeremovenum selfplayer red else selfbconfigimageselfred selfplayer black selfturninfoconfigtextplayer turn def restartself selfbconfigimageselfempty class game def initself selfwin tk selfwintitle connect four selfwinconfigbgblue selfcells selffree range selfmoves x o selfrow frameselfwin range selfcellsappendcelliselfrowself selfplayer black selftitleframe frameselfwin selftitle labelselfwintextconnect fourfontfg white bg blue selfmiddlerow frameselfwin selfturninfo labelselfmiddlerowtextselfplayer turn fontfg white bg blue selfbottomrow frameselfwin selfquitbutton buttonselfbottomrow textquit commandselfwindestroy font selfplaybutton buttonselfbottomrow textplay again commandselfrestart font selftitleframepack selftitlepack selfrowpack selfturninfopack selfmiddlerowpack selfbottomrowpack selfquitbuttonpacksideleft selfplaybuttonpacksideright selfwinmainloop def restartself selfplayer black selfturninfoconfigtextselfplayer turn selffree range selfmoves black red c selfcells crestart game game does anyone see obvious errors causing gameboard buttons show or errors general thanks,2 data food rent bills put days together datasort aggregate days itertools import groupby operator import itemgetter grouped groupbydata keyitemgetter sum values day summed day sumval val daygroup day daygroup grouped get max print maxsummed keyitemgetter,i know i list list defined like listdaytypeexpense day expense int type string i need find max expense day an example list food rent bills i need sum elements day find day highest expenses the result day total expenses,1 two things going need initialize stopname prevmiles fuel first line file need swap two lines assign miles prevmiles here updated function def busroute path c ext txt lines stopname miles prevmiles milest fuel mpg filename inputplease enter file name extensionstrip infile openpath filename ext r stopname prevmiles fuel infilereadlinesplit prevmiles floatprevmiles fuel floatfuel lines infile stopname miles fuel linessplit miles floatmiles fuel floatfuel milest miles prevmiles prevmiles miles miles printsince last stop floatmilest miles,i trying read file contains city names odometer reading much fuel left the contents text file kennewick br bentoncity br prosser br grandview br sunnyside br granger br toppenish br wapato br uniongap br yakima br selah br ellensburg br thorp br rosyln br easton br northbend br preston br issaquah br eastgate br mercerisland br seattle br part assignment subtracting current readthrough last readthrough values stored variable miles def busroute path c ext txt lines stopname miles prevmiles milest fuel mpg filename inputplease enter file name the file path c extension txt required infile openpath filename ext r lines infile stopname miles fuel linessplit miles floatmiles fuel floatfuel prevmiles miles milest miles prevmiles miles printsince last stop floatmilest miles my problem i trying store lastread value miles variable called prevmiles subtract prevmiles last mileage read current reading miles keeps subtracting current miles current miles obviously making value i want printed,1 isn defaultdict easy import pprint collections import defaultdict operator import itemgetter l food rent bills defaultdictint item l ditem item pprintpprintdictd print maxditeritems keyitemgetter result,i know i list list defined like listdaytypeexpense day expense int type string i need find max expense day an example list food rent bills i need sum elements day find day highest expenses the result day total expenses,3 it looks like quite sizer add signature correct it sizeraddwidget proportion flags border you keep skipping proportion specifying border if instead yearnavigationboxaddsc wxexpandwxtop it put spinner pixels top frame whatever widget added one you places skipping proportion flag putting random stuff place you want go change here couple tutorials httpwwwblogpythonlibraryorgawxpythonsizerstutorial httpwikiwxpythonorgusingsizers,i trying create basic dateselectorcalendar wxpython so far i managed add necessary widgets grid i struggling get positioned properly although numerous things i fully understand i getting particularly frustrated wxspinctrl widget seems surrounded massive border despite fact none specified can anyone tell remove i want spin control couple pixels away top frame text february number pixels away bottom control i tried manner approaches none seem effect import wx import calendar monthnameaskey january february march april may june july august september october november december def getmonthnumbernameasstring return monthnameaskeygetnameasstring class examplewxframe def initself parent title superexample selfinitparent titletitlesize selfinitui selfcentre selfshow def inituiself selfpanel wxpanelself mainsizer wxboxsizerwxvertical fgs wxflexgridsizerrows cols fgs blank space filler wxstatictextselfpanel label fgsaddfiller fgs creating containers vsizer wxboxsizerwxvertical yearnavigationbox wxboxsizerwxhorizontal monthnavigationbox wxboxsizerwxhorizontal year navigation sc wxspinctrlselfpanel size scsetrange scsetvalue yearnavigationboxaddsc wxall wxexpandwxtop month navigation monthdown wxstatictextselfpanel label monthup wxstatictextselfpanel label monthname wxstatictextselfpanel wxidany labelfebruary monthnavigationboxaddmonthdown monthnavigationboxaddmonthname monthnavigationboxaddmonthup vsizeraddyearnavigationbox vsizeraddmonthnavigationbox fgsaddvsizer fgs date month writ large date wxstatictextselfpanel wxidany label stylewxaligncenter datefont wxfont wxdefault wxnormal wxbold datesetfontdatefont fgsadddate fgs date grid datesquaresizer wxgridsizerrows cols hgap vgap dayfont wxfont wxdefault wxnormal wxbold days mon tue wed thu fri sat sun item days day wxstatictextselfpanel wxidany labelitem daysetfontdayfont datesquaresizeraddday getmonthnumbermonthnamegetlabel griddata listcalendarcalendaritermonthdaysy lengriddata griddataappend griddata square wxstatictextselfpanel wxidany labelstri squaresetfontdayfont datesquaresizeraddsquare wxidany fgsadddatesquaresizer mainsizeraddfgs wxall selfpanelsetsizermainsizer mainsizerfitself name main app wxapp examplenone title appmainloop,1 each makes loop code two loops years inside – processes years first line file years second etc this error running go fix somehow another one pop soon enough now please borrow good python book library spend time reading exercises or join course get knowledgeable friend review code stackoverflow might help get specific problem sadly teach concepts you wrong path nothing trouble ahead continue like you go back learn basics bit better make much easier long run computers tedious repetitive tasks you never type giant list numbers numbered variables get familiar lists lists lists range function use descriptive names variables abbreviations this python like things clear and put statement line semicolons look ugly these things important want share code get help organize thoughts study documentation csv module use reader also writer get familiar list slicing particularly line variety learn statement files if thing ifelif move common place here becoming good programmer one day,i spread sheets climate data essentially i need transpose parts rows columns vice versa unfortunately format somewhat awkward the data came columns year month number days month type climate data row successive columns representing daily value succeeded preceded associated flag terms value flags day month although months vary length shorter months filled null values last columns what i want processing modeling purposes spreadsheetcsv file columns follows year month day month ie number five columns representing type climate data precip snow snow water tmax tmin if i could get columns appropriate flag values well would great priority so i written code unpack rows lists probably inefficiently i new representing year month type climate variable variable value flag flag based location row corresponding day import matplotlibmlab mlab matplotlibpyplot import figure show import numpy np import scipy import csv durham cuserslocaluserdesktopdrought datamymetdataushcndurhamcsv txt met station durham outputstationtxtnewcsv infileopendurham r outfileopenoutput w writercsvwriteroutfile yr mon var unit flag flag value valu flg flg prcp snow snwd tmax tmin row line infile stationid variable units year month days flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flag flag value flaglinesplit yrintyear monintmonth varvariable unitunits yr range mon range var prcp valufloati value flgflag flgflag j range prcpappendvaluj elif var snow valufloati value flgflag flgflag j range snowappendvaluj elif var snwd valufloati value flgflag flgflag j range snwdappendvaluj elif var tmax valufloati value flgflag flgflag j range tmaxappendvaluj elif var tmin valufloati value flgflag flgflag j range tminappendvaluj rowyr mon j prcpj snowj snwdj tmaxj tminj writerwriterowrow infileclose outfileclose now leaving aside i get memory error i run i take away climate variables i get successfully get csv file format i want the problem every single month every single year reports climate data values data month january the code calling data appropriate variable appropriate day repeating data month month i sure i gone wrong suggestionshelp would much appreciated,1 try properties jclass javautilproperties props properties propssetproperty foo bar,i attempting instantiate properties object jpype encountering difficulty the commands props jclass javautilproperties propssetproperty foo bar return following runtimeerror no matching overloads found srcnativecommonjpmethodcpp i attempted various forms arguments str foo jstring foo javalangstring foo nothing seems work setting properties classes general approach jpype works fine eg problems javalangsystemsetproperty foo bar any suggestions would appreciated,1 consider class myconfigdict dict def getitem self key try return super myconfigdict self getitem key except keyerror e raise myconfigerror emessage something like may allow wrap every access extended exception,i writing scripts used nonpython users i config class dictionaries i like able raise custom exception keyerror is elegant way writing method raises exception checking value dictionary here example class configerrorexception pass class config def initself selfcars bmw m honda civic def getcarself name try return selfcarsname except keyerror e raise configerrorcar exist name conf config print car confcars bmw print car confcars mercedes here output car m traceback recent call last file testpy line print car confcars mercedes keyerror mercedes i know i write method like configgetcar raise custom exception i like able raise custom exception directly trying access configcars dictionary i like actually dictionaries config i need raise custom exception one dictionaries would like keep data access consistent dictionaries note this using python,3 unittesttestcaseshortdescription returns description test none description provided the default implementation method returns first line test method’s docstring available none unittesttestcaseid return string identifying specific test case this usually full name test method including module class name hopefully one useful needs,how i get currently running testcase name testsuite collection testcases tests executed sequentially order adding test testsuite collection when i add tests testsuite collection i preview object i get currently executing test tests running maybe variable holds information example def suite testsuite unittesttestsuite testsuiteaddtestflightstestcases testselreservationonewaywizzairtransfer testsuiteaddtestflightstestcases testselreservationonewaywizzairtransfer testsuiteaddtestflightstestcases testselreservationroundwizzairtransfer testsuiteaddtestflightstestcases testselreservationonewaytairtransfer testsuiteaddtestflightstestcases testselreservationroundtairtransfer testsuiteaddtestflightstestcases testselreservationonewaywizzaircreditcard testsuiteaddtestflightstestcases testselreservationonewaytaircreditcard testsuiteaddtestflightstestcases testselreservationroundwizzairtransfer testsuiteaddtestflightstestcases testselreservationonewaywizzairtransfer testsuiteaddtestflightstestcases testselreservationonewayeasyjettransfer testsuiteaddtestflightstestcases testselreservationonewayryanairtransfer testsuiteaddtestflightstestcases testselreservationroundryanaircreditcard testsuiteaddtestflightstestcases testselreservationonewaytairduplicated testsuiteaddtestflightstestcases testreservationwrongcardlowcost testsuiteaddtestflightstestcases testselreservationonewaytaircreditcard testsuiteaddtestflightstestcases testselreservationonewaytairwrongcreditcard return testsuite name main result unittesttexttestrunnerverbosityrunsuite sysexitnot resultwassuccessful tests executed using seleniumrc framework,3 you sorting strings instead integers case smaller to sort integers convert activites sortedactivitieskey lambda itemintitem print activities results,print activities activities sortedactivitieskey lambda itemitem print activities activities case list tuples like startnumberfinishnumber output code according list values sorted according increasing order finishnumberwhen tried code shell i got following outputi sure second list sorted according increasing order finishnumberplease help understanding,3 your items compared strings numbers thus since character comes lexicographically makes sense comes you need cast value int first activities sortedactivitieskey lambda itemintitem,print activities activities sortedactivitieskey lambda itemitem print activities activities case list tuples like startnumberfinishnumber output code according list values sorted according increasing order finishnumberwhen tried code shell i got following outputi sure second list sorted according increasing order finishnumberplease help understanding,3 it storing number number string the string comes string try activities sortedactivities keylambda inti,print activities activities sortedactivitieskey lambda itemitem print activities activities case list tuples like startnumberfinishnumber output code according list values sorted according increasing order finishnumberwhen tried code shell i got following outputi sure second list sorted according increasing order finishnumberplease help understanding,1 you sorting strings numbers strings get sorted character character so example greater character larger you fix fly simply casting item integer activities sortedactivitieskey lambda item intitem,print activities activities sortedactivitieskey lambda itemitem print activities activities case list tuples like startnumberfinishnumber output code according list values sorted according increasing order finishnumberwhen tried code shell i got following outputi sure second list sorted according increasing order finishnumberplease help understanding,1 intadd intadd intadd you also use operatoradd obtain generic function adding python operator import add add add b ab if want get addition method specific integer instead int type see gnibbler comment question to get bound add method integer use parentheses prevent treated decimal point eg add another way would add space eg add i think obscure an example oneadd add oneadd,is way python get addition object operator integers python store somewhere,3 import operator helpoperatoradd help builtin function add module operator add adda b same b,is way python get addition object operator integers python store somewhere,2 be aware javautildategettime gives milliseconds since epoch jython like cpython gives seconds since epoch so need divide values given javautildate from jython faq,i new jython convert datetime type jython javautildate thank,1 pointed comment see nd entry post i made connect via code well via glade lead calls if ran similar problem check,i got simple callback function switches label pygtk button def langselecthandlerself widget callbackdatanone selflang fr selflang de print changed de widgetsetlabeldeutsch else selflang fr print changed fr widgetsetlabelfranã§ais the button connected like selflangselectconnectclicked selflangselecthandler i verified duplicate call using random numbers generated call different my problem callback gets executed twice therefore switches back old value change visible why hell case prevented thanks julian,1 are sure fabric module ssh duration ls command that equivalent ssh host ls lht tmp this commandline open remote shell run ls lht command shutdown but i suspect fabric library might equivalent ssh host host ls lht tmp of course providing real tty different ssh options allow keeping connection open without interactive tty this would desirable certain cases eg run lots commands host technique reuse existing ssh session instead opening new session every time check documentation arguments enable disable session caching,i service spawns threads the threads started providing target function it would appear thread die function ends i know thread makes ssh connections paramiko via fabric i lsof i see ssh connections still active function completes how i make sure thread dies target function completes here example i working time import sleep threading import thread fabricapi import run settings def threadfunchost settingshoststringhost run ls lht tmp def spawnthreadhost thread targetthreadfunc argshost tstart spawnthread nodeexamplecom true sleep and i run sudo lsof grep ssh another terminal code infinite loop i see following even i know thread exist anymore python daharon u ipv tcp nodeexamplecomssh established python daharon u ipv tcp nodeexamplecomssh established python daharon u ipv tcp nodeexamplecomssh established python daharon u ipv tcp nodeexamplecomssh established python daharon u ipv tcp nodeexamplecomssh established python daharon u ipv tcp nodeexamplecomssh established,1 concatenate stringcharstring,quick way place string front another string python example let say string pple how would i put string start string,2 here quick example string string,quick way place string front another string python example let say string pple how would i put string start string,1 strg pple char char strg apple strg char strg strg apple,quick way place string front another string python example let say string pple how would i put string start string,2 this may problem i i using version python interpreter local environment when i switched works fine,edit i gave go appengine seems like actually works problem dev server i would still interested understanding happening i using appengine mapper api mapreduce problem imports here file structure ├── ost appyaml srcappyaml ├── ost doc ├── ost fabfilepy ├── ost gae homeostdevgae ├── ost info ├── ost license ├── ost readme ├── ost runclean ├── ost rundeploy ├── ost runpylint ├── ost runtests ├── ost src │â â ├── ost admin │â â ├── ost appyaml │â â ├── ost datapy │â â ├── ost dhandler │â â ├── ost dshtml │â â ├── ost generatorpy │â â ├── ost initpy │â â ├── ost libpy │â â ├── ost mainpy │â â ├── ost mapperspy │â â ├── ost mapreduceyaml │â â ├── ost parserpy │â â └── ost static ├── ost test │â â └── ost testdatapy └── ost todo my appyaml application removed version runtime python apiversion builtins datastoreadmin appstats handlers url remoteapi script pythonlibgoogleappengineextremoteapihandlerpy login admin url admin script adminadminpy login admin url dhandler script dhandlerdhandlerpy url mapreduce script pythonlibgoogleappengineextmapreducemainpy login admin url static staticdir static url script mainpy my mapreduceyaml mapreduce name insertdomainmapper params name donecallback value dhandlerinsertjobdone mapper inputreader googleappengineextmapreduceinputreadersblobstorelineinputreader handler mappersinsertdomain params name blobkeys default finally mapperspy googleappengineextmapreduce import operation op data import registereddomain makekey cleandomain def insertdomainbyteoffset line domain line todo domain validity check clean domain domain cleandomaindomain create domain entity domainentity registereddomainkeynamemakekeydomain yield put operation yield opdbputdomainentity now problem although i load mapreduce page job available soon i try start job i get following error page importerror could find inputreaders path googleappengineextmapreduce here complete stack trace debug devappserverpy executing cgi env httpaccept texthtmlapplicationxhtmlxmlapplicationxmlqq httpconnection keepalive contenttype applicationxwwwformurlencoded httpcookie devappserverlogintestexamplecomtrue httpacceptcharset isoutfqq currentversionid servers oftware development scriptname userorganization requestmethod get httphost pathinfo mapreducestatus serverprotocol http querystring tz utc http cachecontrol maxage useremail testexamplecom userisadmin contentlength userid httpuseragent mozilla windows nt wow applewebkit khtml like g ecko chrome safari applicationid devdomainsandwich servername remote addr gatewayinterface cgi httpacceptlanguage enusenq sdkversion pathtranslated homeostdevgaegoogleappengineextmapreducemainpy serverport authdomain gmailcom debug devappserverpy reusing main function module googleappengineextmapr educemain info devappserverpy get mapreducestatus http debug devappserverindexpy no need update indexyaml debug devappserverpy matched mapreducebasecss cgi dispatcher path py thonlibgoogleappengineextmapreducemainpy debug devappserverpy executing cgi env httpaccept textcssq httpconnection keepalive contenttype applicationxwwwformurlen coded httpreferer httpmapreducestatus httpacceptcharset isoutfqq currentversionid serversoftware development scriptname userorganization requestmethod get httphost pathinfo mapreducebasecss serverprotocol ht tp querystring tz utc useremail testexamplecom userisadmin contentlength userid httpuseragent mozilla windows nt wow applewebkit k html like gecko chrome safari applicationid devdomainsandwich httpcookie devapp serverlogintestexamplecomtrue servername remoteaddr gatewayinterface cgi httpacceptlanguage enusenq sdkversion pathtranslated homeostdevgaegoogleappengineextmapreducemainpy serverport authdomain gmailcom debug devappserverpy reusing main function module googleappengineextmapr educemain info devappserverpy get mapreducebasecss http debug devappserverindexpy no need update indexyaml debug devappserverpy matched mapreducejqueryjs cgi dispatcher path p ythonlibgoogleappengineextmapreducemainpy debug devappserverpy executing cgi env httpaccept httpconnection keepalive contenttype applicationxwwwformurlencoded httpr eferer httpmapreducestatus httpacceptcharset isoutfqq current versionid serversoftware development scriptname userorganization requestmeth od get httphost pathinfo mapreducejqueryjs serverprotocol http quer ystring tz utc useremail testexamplecom userisadmin contentlength userid httpuseragent mozilla windows nt wow applewebkit khtml like gec ko chrome safari applicationid devdomainsandwich httpcookie devappserverlogin testexamplecomtrue servername remoteaddr gatewayinter face cgi httpacceptlanguage enusenq sdkversion pathtranslated homeostde vgaegoogleappengineextmapreducemainpy serverport authdomain gmailcom debug devappserverpy reusing main function module googleappengineextmapr educemain info devappserverpy get mapreducejqueryjs http debug devappserverindexpy no need update indexyaml debug devappserverpy matched mapreducestatusjs cgi dispatcher path p ythonlibgoogleappengineextmapreducemainpy debug devappserverpy executing cgi env httpaccept httpconnection keepalive contenttype applicationxwwwformurlencoded httpr eferer httpmapreducestatus httpacceptcharset isoutfqq current versionid serversoftware development scriptname userorganization requestmeth od get httphost pathinfo mapreducestatusjs serverprotocol http quer ystring tz utc useremail testexamplecom userisadmin contentlength userid httpuseragent mozilla windows nt wow applewebkit khtml like gec ko chrome safari applicationid devdomainsandwich httpcookie devappserverlogin testexamplecomtrue servername remoteaddr gatewayinter face cgi httpacceptlanguage enusenq sdkversion pathtranslated homeostde vgaegoogleappengineextmapreducemainpy serverport authdomain gmailcom debug devappserverpy reusing main function module googleappengineextmapr educemain info devappserverpy get mapreducestatusjs http debug devappserverindexpy no need update indexyaml debug devappserverpy matched mapreducecommandlistconfigs cgi dispatcher w ith path pythonlibgoogleappengineextmapreducemainpy debug devappserverpy executing cgi env httpaccept textplain httpconnection keepalive userisadmin httpcookie devappser verlogintestexamplecomtrue currentversionid serversoftware developme nt scriptname userorganization userid requestmethod get h ttphost pathinfo mapreducecommandlistconfigs serverprotocol http querys tring tz utc httpxrequestedwith xmlhttprequest useremail testexamplecom contentlengt h httpacceptcharset isoutfqq httpuseragent mozilla windows nt wo w applewebkit khtml like gecko chrome safari applicationid devdomainsandwich httpreferer httpmapreducestatus servername remoteaddr contenttype applicationxwwwformurlencoded gatewayinterface cgi httpacceptlanguage enuse nq sdkversion pathtranslated homeostdevgaegoogleappengineextmapreducemainpy se rverport authdomain gmailcom debug devappserverpy reusing main function module googleappengineextmapr educemain info devappserverpy get mapreducecommandlistconfigs http debug devappserverindexpy no need update indexyaml debug devappserverpy matched mapreducecommandlistjobs cgi dispatcher path pythonlibgoogleappengineextmapreducemainpy debug devappserverpy executing cgi env httpaccept textplain httpconnection keepalive userisadmin httpcookie devappser verlogintestexamplecomtrue currentversionid serversoftware developme nt scriptname userorganization userid requestmethod get h ttphost pathinfo mapreducecommandlistjobs serverprotocol http querystri ng tz utc httpxrequestedwith xmlhttprequest useremail testexamplecom contentlength httpacceptcharset isoutfqq httpuseragent mozilla windows nt wow applewebkit khtml like gecko chrome safari applicationid devdomainsandwich httpreferer httpmapreducestatus servername remoteaddr con tenttype applicationxwwwformurlencoded gatewayinterface cgi httpacceptlanguage enusenq sdkversion pathtranslated homeostdevgaegoogleappengineextmapreducemainpy serve rport authdomain gmailcom debug devappserverpy reusing main function module googleappengineextmapr educemain info devappserverpy get mapreducecommandlistjobs http debug devappserverindexpy no need update indexyaml debug devappserverpy matched faviconico cgi dispatcher path mainpy debug devappserverpy executing cgi env httpaccept httpconnection keepalive contenttype applicationxwwwformurlencoded httpc ookie devappserverlogintestexamplecomtrue httpacceptcharset isoutf qq currentversionid serversoftware development scriptname userorgani zation requestmethod get httphost pathinfo faviconico serverprotocol http querystring tz utc useremail testexamplecom userisadmin contentlengt h userid httpuseragent mozilla windows nt wow applewebkit khtml like gecko chrome safari applicationid devdomainsandwich servername remoteaddr gatewayinterface cgi httpacceptlanguage enusenq sdkv ersion pathtranslated homeostdevdomainsandwichsrcmainpy serverport authdomai n gmailcom debug devappserverpy reusing main function module main info devappserverpy get faviconico http debug devappserverindexpy no need update indexyaml debug devappserverpy matched mapreducecommandstartjob cgi dispatcher path pythonlibgoogleappengineextmapreducemainpy debug devappserverpy executing cgi env httpcookie devappserverlogintestexamplecomtrue serversoftware development scriptname requestmethod post pathinfo mapreducecommandstartjob httporigin htt p serverprotocol http querystring contentlength httpacceptcharse t isoutfqq httpuseragent mozilla windows nt wow applewebkit kht ml like gecko chrome safari tz utc httpreferer httpmapreducestat us servername remoteaddr sdkversion pathtranslated homeostde vgaegoogleappengineextmapreducemainpy serverport userisadmin httpxrequestedwith xmlhttprequest currentversionid userorganization userid httph ost httpconnection keepalive useremail testexamplecom httpaccept textplai n applicationid devdomainsandwich gatewayinterface cgi httpacceptlanguage enusen q contenttype applicationxwwwformurlencoded authdomain gmailcom debug devappserverpy reusing main function module googleappengineextmapr educemain debug devappserverpy could import io disallowed cextension builtin odule debug utilpy could import blobstorelineinputreader googleappengineextma preduceinputreaders will try recursively traceback recent call last file homeostdevgaegoogleappengineextmapreduceutilpy line forname result importmodulename none none shortname file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodule return selffindandloadmodulesubmodule fullname searchpath file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line findandloadmodule description file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodulerestricted description file homeostdevgaegoogleappengineextmapreduceinputreaderspy line module import zipfile file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodule return selffindandloadmodulesubmodule fullname searchpath file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line findandloadmodule description file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodulerestricted description file usrlibpythonzipfilepy line module import io file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodule return selffindandloadmodulesubmodule fullname searchpath file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line findandloadmodule description file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodulerestricted description file usrlibpythoniopy line module import io importerror no module named io debug devappserverpy could import io disallowed cextension builtin odule debug utilpy could import inputreaders googleappengineextmapreduce wi try recursively traceback recent call last file homeostdevgaegoogleappengineextmapreduceutilpy line forname result importmodulename none none shortname file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodule return selffindandloadmodulesubmodule fullname searchpath file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line findandloadmodule description file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodulerestricted description file homeostdevgaegoogleappengineextmapreduceinputreaderspy line module import zipfile file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodule return selffindandloadmodulesubmodule fullname searchpath file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line findandloadmodule description file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodulerestricted description file usrlibpythonzipfilepy line module import io file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodule return selffindandloadmodulesubmodule fullname searchpath file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line findandloadmodule description file homeostdevgaegoogleappenginetoolsdevappserverpy line decorate return funcself args kwargs file homeostdevgaegoogleappenginetoolsdevappserverpy line loadmodulerestricted description file usrlibpythoniopy line module import io importerror no module named io error basehandlerpy error jsonhandler returning exception traceback recent call last file homeostdevgaegoogleappengineextmapreducebasehandlerpy line handlewrapper selfhandle file homeostdevgaegoogleappengineextmapreducehandlerspy line handle appmapperparamsgetapp file homeostdevgaegoogleappengineextmapreducehandlerspy line startmap mapperinputreaderclass mapperspecinputreaderclass file homeostdevgaegoogleappengineextmapreducemodelpy line inputreaderclass return utilfornameselfinputreaderspec file homeostdevgaegoogleappengineextmapreduceutilpy line forname module fornamemodulename recursivetrue file homeostdevgaegoogleappengineextmapreduceutilpy line forname shortname modulename importerror could find inputreaders path googleappengineextmapreduce info devappserverpy post mapreducecommandstartjob http debug devappserverindexpy no need update indexyaml,1 few quick things your urls old outdated function well proper urls use ssl api subdomain httpsapitwittercomoauthrequesttoken httpsapitwittercomoauthauthorize httpsapitwittercomoauthaccesstoken it unclear looking code whether performing headerbased oauth querystringbased oauth i recommend headerbased oauth dramatically separates concerns makes easier discover wrongness happens make sure send dynamic oauthcallback value oauthrequesttoken step correctly percentencoded also make sure placeholder httpbased callback application record devtwittercomapps,so i setup twitter application people reply tweets inside app i callback url i try override everything seems go fine however now i problem getting override callback work app runs multiple sub domains servers based stage development i would like override callback current url when i override callback twitter attempts send user back page i get page says sorry page doesn’t exist url looks something like httpstwittercomoauthhttpaauthtwitterftwittercallbackoauthtokenvalueampoauthverifiervalue here python code using library oauth httpsgithubcomsimplegeopythonoauth setup twitter authorization object requesttokenurl httptwittercomoauthrequesttoken accesstokenurl httptwittercomoauthaccesstoken authorizeurl httptwittercomoauthauthenticate consumer oauthconsumerconsumerkey consumersecret client oauthclientconsumer get request token callbackurl urllibquotestwittercallback selfrequesturl resp content clientrequestrequesttokenurl post bodyurlliburlencode oauthcallback callbackurl resp status raise exceptioninvalid response resp status requesttoken dicturlparseparseqslcontent tmpldict callbackurl callbackurl tmpldict oauthtoken requesttoken oauthtoken tmpldict twitauthurl soauthtokens authorizeurl requesttoken oauthtoken qargsurlparseqsselfrequesturltruefalse oauthverifier qargs oauthverifier qargs oauthverifier else oauthverifier none oauthverifier token oauthtokenrequesttoken oauthtoken requesttoken oauthtokensecret tokensetverifieroauthverifier client oauthclientconsumertoken resp content clientrequestaccesstokenurl get accesstoken dicturlparseparseqslcontent current flow user click authorization url hit allow access twitter twitter displays redirecting back application cannot find page url like example,2 i use code similar one cycle different linestyles by default colours repeat plots idx ds datasets idx plotds elif idx plotds linestyle else plotds linestyle idx,i know cycle list colors matplotlib but possible something similar line styles plain dotted dashed etc i need graphs would easier read printed any suggestions,1 something else found something similar scipymatplotlib luai sure active development last release january gslshell leverages gsl library plotting capabilities like matlab scipymatplotlib,i thinking learning lua learned smaller language compared python efficient jit compiler implementation form luajit i would like know possible use lua way use python numpyscipy lua numpyscipy equivalent matplotlib equivalent,3 indent objaddfieldname fieldvalue part else statement,i patched appengineconfig enable foreign characters blobstoreuploadhandler webappdjangoversion import base import quopri webob import multidict def fromfieldstoragecls fs obj cls fslist fslist none nothing parse field fslist fieldfilename objaddfieldname field else first set common charset utf commoncharset utf second check contenttransferencoding decode value appropriately fieldvalue fieldvalue transferencoding fieldheadersget contenttransferencoding none transferencoding base fieldvalue basebdecodefieldvalue transferencoding quotedprintable fieldvalue quopridecodestringfieldvalue fieldtypeoptionshaskey charset fieldtypeoptions charset commoncharset decode charset specified multipart encode charset specified top level fieldstorage fieldvalue fieldvaluedecode fieldtypeoptions charset encodecommoncharset todo should take care fieldname objaddfieldname fieldvalue return obj multidictmultidictfromfieldstorage classmethodfromfieldstorage now i get error performing upload form one file is i also need text values if i remove patch appengineconfig upload works foreign charcater breaks should i try adding hidden variable everyting submitted file thanks good idea traceback recent call last file basepythonruntimepythonlibversionsgoogleappengineextwebappwebapppy line call handlerpostgroups file basedatahomeappssmontaoprojectdeleteoreditmainpy line post upload selfgetuploads file basepythonruntimepythonlibversionsgoogleappengineextwebappblobstorehandlerspy line getuploads key value selfrequestparamsitems file basepythonruntimepythonlibversionswebobinitpy line params params selfstrparams file basepythonruntimepythonlibversionswebobinitpy line strparams return nestedmultidictselfstrget selfstrpost file basepythonruntimepythonlibversionswebobinitpy line strpost vars multidictfromfieldstoragefs file basedatahomeappssmontaoprojectdeleteoreditappengineconfigpy line fromfieldstorage objaddfieldname fieldvalue unboundlocalerror local variable fieldvalue referenced assignment,1 just use stringreplace line whateverxmltextsplitlines whatever arbitrary loop linefindenabled print replacing enabled line line linereplaceenabled disabled a better solution though may use xml parser xmldomminidom change attribute parsing,i trying replace string xml file python for example i want change enabled disbabled sglobalmethodsecurity securedannotationsenabled is best search replace whole line or way replaced enabled line i find line matches,1 how i split file despite circular dependency option break cycles put base class module derived classes additional modules functions operating derived classes yet another module option ignore cycles import modulespackages global namespace ie foopy class bar frobs quuxen should never imported foo import bar use import foo refer foobar functions needed,i single python module contains classes a a a a a derive a a contains functions operate a a this works fine one py file but file grown quite long i would like split a a files how i split file despite circular dependency,1 modapy class a modapy import moda class amodaa modapy import moda class amodaa modfull moda import a moda import a moda import a even a processes as as fine thanks duck typing need import actual names,i single python module contains classes a a a a a derive a a contains functions operate a a this works fine one py file but file grown quite long i would like split a a files how i split file despite circular dependency,3 a simple way could line fileh line linereplaceenabled disabled oufwriteline you need explicitly find enabled string replacing however since xml file i would suggest using xml parser modify,i trying replace string xml file python for example i want change enabled disbabled sglobalmethodsecurity securedannotationsenabled is best search replace whole line or way replaced enabled line i find line matches,2 if thing stopping using pyqt passing strings signals latest syntax make choice much easier the old syntax still used looks like selfconnectselfaction signal triggered selfhandler but new style signals much pythonic selfactiontriggeredconnectselfhandler,i thinking developing app os x using python i know objective c want learn right i know like python i trying determine gui toolkit use i already bit experience pyqt much i also seen pyobjc cocoapython seem allow use cocoa ui components python i curious anyone input pyobjc stacks pyqt i would giving cross platform abilities i sure i would gaining i leaning towards pyqt right wanted see thought my big dislike pyqt pass around strings signals slots is pyobjc similar,2 i know nose tried using else except clause ie else assert false,i testing exceptions nose here example def testdeleteuserusernotfoundself test exception raised trying delete nonexistent users try selfclientdeleteuser make nose fail except usernotfoundexception assert true the assert executed exception raised exception raised executed is anything i put commented line exception raised nose report failure,1 something like might trick import matplotlibpyplot plt itertools import cycle lines linecycler cyclelines pltfigure range x rangeii pltplotrangexnextlinecycler pltshow result,i know cycle list colors matplotlib but possible something similar line styles plain dotted dashed etc i need graphs would easier read printed any suggestions,3 def testdeleteuserusernotfoundself test exception raised trying delete nonexistent users try selfclientdeleteuser assert false except usernotfoundexception assert true the semantics try except imply flow execution leaves try block exception assert false run exception raised also execution reenter try block except block done running run trouble ↓ statements ↓ exception try ↚──────────→ except ↓ │ statements ←───────────┘ ↓,i testing exceptions nose here example def testdeleteuserusernotfoundself test exception raised trying delete nonexistent users try selfclientdeleteuser make nose fail except usernotfoundexception assert true the assert executed exception raised exception raised executed is anything i put commented line exception raised nose report failure,3 the simple way get exact functionality would python scripts invoke hcitool command line but custom solution use pybluez send hci command packets commands generate for example hcitool rssi causes hci read rssi command sent local bt adapter parses result with pybluez open hci socket construct command packets parse results if access bt spec defines command packet formats either look source code hcitool see sending use hcidump to use hcidump run hcidump terminal sniff local hci command traffic use another terminal commands via hcitool with hcidump able capture raw packet transactions use reference want generate pybluez this example httpcodegooglecomppybluezsourcebrowsetrunkexamplesadvancedinquirywithrssipy shows deal hci sockets manually forming command packets parsing results you need customize commands want use,are pybluez wrapper functions lower level bt functionality i find anything docs what i need use equivalent functionality lping single ping hcitool cc hcitool rssi hcitool lq hcitool tpl hcitool dc is way access pybluez actually wrapper andor scriptable language,1 look broader solution problem convert data str int immediately input work int otherwise continually bumping little problems like format data str output this principle applies generally eg working nonascii string data utf unicode utf try manipulate undecoded text,print activities activities sortedactivitieskey lambda itemitem print activities activities case list tuples like startnumberfinishnumber output code according list values sorted according increasing order finishnumberwhen tried code shell i got following outputi sure second list sorted according increasing order finishnumberplease help understanding,1 java sometimes all implementations datainput methods use eofexception instead return values in case way use usual sentinel value,i really confused the standard approach java throw exceptions abnormal conditions use signal endofiterator examples effective java item use exceptions exceptional conditions javaspecialists newsletter flow control we never cause exception otherwise preventable i seen code instead checking bounds assumed data correct runtimeexceptions caught here example bad code please code like public class antipattern public static void mainstring args try int true systemoutprintlnargsi catch arrayindexoutofboundsexception e done whereas standard use idiom python eg stopiteration exception stopiteration raised iterator‘s next method signal values this derived exception rather standarderror since considered error normal application why bad java good python,1 check ffileno fi you ever close file descriptor second correct on unix first causes error fclose osclosefi traceback recent call last file stdin line module oserror errno bad file descriptor,which following correct fi path tempfilemkstemp f osfdopenfi w fwriteres fclose osclosefi fi path tempfilemkstemp f osfdopenfi w fwriteres fclose,3 python java vastly different approaches exceptions in python exceptions normal look eafp easier ask forgiveness permission python glossary also check wikipedia say stopiteration example eafp – go ahead get next thing iterator fails handle error if code readable nonlocal exit python use exception you write checks deal failures things work there absolutely nothing shameful fact encouraged unlike java now specific case stopiteration consider generator functions def generator yield print side effect yield to support kind hasnext method generator would check next value triggering print asked the value exception raised would remembered iterator if hasnext called twice first one would trigger side effect or next value could always precomputed even needed i find python semantics – computing whenever next value needed – nicest alternative of course java resumable generators hard compare but anecdotal evidence stopiteration generalizes better hasnext,i really confused the standard approach java throw exceptions abnormal conditions use signal endofiterator examples effective java item use exceptions exceptional conditions javaspecialists newsletter flow control we never cause exception otherwise preventable i seen code instead checking bounds assumed data correct runtimeexceptions caught here example bad code please code like public class antipattern public static void mainstring args try int true systemoutprintlnargsi catch arrayindexoutofboundsexception e done whereas standard use idiom python eg stopiteration exception stopiteration raised iterator‘s next method signal values this derived exception rather standarderror since considered error normal application why bad java good python,3 i would fi path tempfilemkstemp f osfdopenfi w try fwriteres finally fclose,which following correct fi path tempfilemkstemp f osfdopenfi w fwriteres fclose osclosefi fi path tempfilemkstemp f osfdopenfi w fwriteres fclose,1 if sufficiently recent python golf osfdopentempfilemkstemp f fwriteres,which following correct fi path tempfilemkstemp f osfdopenfi w fwriteres fclose osclosefi fi path tempfilemkstemp f osfdopenfi w fwriteres fclose,1 i think need use import codecs codecsopen instead plain open savehtml method handle utf docs see python unicode howto complete explanation hope helps,i modified python babelizer help translate english chinese httpcodeactivestatecomrecipes r babelizerpy api simple access babelfishaltavistacom requires python better see use httpbabelmrfeinbergcom api simple access babelfishaltavistacom summary import babelizer print joinbabelizeravailablelanguages print babelizertranslate how much doggie window english french def babelcallbackphrase print phrase sysstdoutflush babelizerbabelize i love reigning knight english german callback babelcallback availablelanguages a list languages available use babelfish translate phrase fromlang tolang uses babelfish translate phrase fromlang tolang babelizephrase fromlang throughlang limit callback none uses babelfish translate back forth fromlang throughlang either changes occur translation limit iterations reached whichever comes first takes optional callback function receive single parameter next translation without callback returns list successive translations it guaranteed work english one two languages given either translation methods both translation methods throw exceptions subclasses babelizererror they include languagenotavailableerror thrown attempt use unknown language babelfishchangederror thrown babelfishaltavistacom changes detail layout babelizer longer parse results submit correct form infrequent occurance babelizerioerror thrown various networking io errors version id babelizerpyv administrator exp author jonathan feinberg jdfpoboxcom import string urllib import httplib urllib import sys various patterns i encountered looking babelfish result we try turn based relative number times i seen patterns anyone provide heuristic knowing one use this includes altavista employees recompiler nameq recompiler td bgcolorwhite recompiler strongbr div idresultdiv stylepaddingemdivdiv recompiler div idresultdiv stylepaddingemdivdiv reu languages english en french fr spanish es german de italian portugese pt chinese zh all available language names availablelanguages xtitle x languageskeys calling translate babelize raise babelizererror class babelizererrorexception pass class languagenotavailableerrorbabelizererror pass class babelfishchangederrorbabelizererror pass class babelizerioerrorbabelizererror pass def savehtmltxt f open pagehtml wb fwritetxt fclose def cleantext return joinstringreplacetextstrip n split def translatephrase fromlang tolang phrase cleanphrase try fromcode languagesfromlanglower tocode languagestolanglower except keyerror lang raise languagenotavailableerrorlang html try params urlliburlencode ei utf doit done fr bfres intl tt urltext trtext phrase lp fromcode tocode btntrtxt translate headers contenttype applicationxwwwformurlencodedaccept textplain conn httplibhttpconnectionbabelfishyahoocom connrequestpost httpbabelfishyahoocomtranslatetxt params headers response conngetresponse html responseread savehtmlhtml connclose response urlliburlopen httpbabelfishyahoocomtranslatetxt params except ioerror raise babelizerioerrorcouldn talk server print html regex match regexsearchhtml match break match raise babelfishchangederrorcan recognize translated string return matchgroup return cleanmatchgroup def babelizephrase fromlanguage throughlanguage limit callback none phrase cleanphrase seen phrase callback callbackphrase else results phrase flip fromlanguage throughlanguage throughlanguage fromlanguage next fromlanguage rangelimit phrase translatephrase next flipnext seenhaskeyphrase break seenphrase callback callbackphrase else resultsappendphrase next flipnext callback return results name main import sys def printerx print x sysstdoutflush babelizei take sort treatment doggie english french callback printer end httpcodeactivestatecomrecipes test code import babelizer print joinbabelizeravailablelanguages result babelizertranslate how much dog window english chinese f open resulttxt wb fwriteresult fclose print result the result expected inside div block i modded script save html response what i found utf characters turned nul do i need take special care treating utf response,1 most likely need set relay see get output mailq command would show unsuccessful sending messages take look article set smarthost postfixosx article using gmail smarthost postfix,i trying send email using python program receive send emails python and i activated local postfix smtp server localhost verified active suing instructions httpwwwphasetechnologycomnode i set recipients sender email address the program runs however i receiving mail i read i may need set relay the example i read gmail is i need if i osx,1 unlikely as cannot install binaries google app engine environment would need build entire speech recognition engine scratch this would nontrival if limited google app engine however python bindings existing packages sphinx,first know language google used create speech text search create speech text django google apps engine using python vbnet programmer yes know applications usually created java created jython django app would like introduce feature use ispeech free similar services working apis like working apis honest unless facebook google api looking see python jython library prefer python found far pyspeech works windows vps linux good,3 import networkx nx import matplotlibpyplot plt gnxgraph gaddedgesfrom a b a c b d c d nxdrawg pltshow gremovenode b nxdrawg pltshow to remove multiple nodes also graphremovenodesfrom method,i dataset i uploading graph various timeframes trying figure relationships i want delete nodes edges i sure command remove delete nodes any idea,3 documentation covers graphremovenoden remove node n graphremovenodesfromnodes remove multiple nodes for example in gnetworkxgraph in gaddnodesfrom in gnodes out in gremovenode in gnodes out,i dataset i uploading graph various timeframes trying figure relationships i want delete nodes edges i sure command remove delete nodes any idea,2 it csv module causing problem take look output servrespread try using servrespreadlines instead,i trying read data google fusion tables api python using csv library it seems like querying api returns csv data i try use csvreader seems mangle data split every character rather commas newlines am i missing step here sample i made illustrate using public table usrbinpython import csv import urllib urllib requesturl httpswwwgooglecomfusiontablesapiquery query select from limit url ss requesturl urlliburlencode sql query servreq urllibrequesturlurl servresp urlliburlopenservreq reader csvreaderservrespread row reader print row prints character cell column headings ultimately i using csvdictreader class base reader shows issue well,1 there nothing stops using exceptions like java looks ugly least java developer the main reason stacktraces exceptions expensive possibly also java developers might slightly concerned spending computing resources python developers java also rather clean language would say fundamentalistic one reasons nice language see comment anyway fundamentalists normal people thinks using exceptions normal flow the right way but besides recent jvm detects generating lot stacktraces spot code actually throw exceptions without speed things,i really confused the standard approach java throw exceptions abnormal conditions use signal endofiterator examples effective java item use exceptions exceptional conditions javaspecialists newsletter flow control we never cause exception otherwise preventable i seen code instead checking bounds assumed data correct runtimeexceptions caught here example bad code please code like public class antipattern public static void mainstring args try int true systemoutprintlnargsi catch arrayindexoutofboundsexception e done whereas standard use idiom python eg stopiteration exception stopiteration raised iterator‘s next method signal values this derived exception rather standarderror since considered error normal application why bad java good python,1 csvreader takes filelike object change reader csvreaderservrespread reader csvreaderservresp alternatively could reader csvdictreaderservresp,i trying read data google fusion tables api python using csv library it seems like querying api returns csv data i try use csvreader seems mangle data split every character rather commas newlines am i missing step here sample i made illustrate using public table usrbinpython import csv import urllib urllib requesturl httpswwwgooglecomfusiontablesapiquery query select from limit url ss requesturl urlliburlencode sql query servreq urllibrequesturlurl servresp urlliburlopenservreq reader csvreaderservrespread row reader print row prints character cell column headings ultimately i using csvdictreader class base reader shows issue well,1 you calculated wchill beginning program row col that number evaluated beginning change if want wchill change based rowcolumn printing currently need call line wchill round col row colrow right print values row column change edit i trying say wchill magically changing need recalculate every time rowcolumn changes,this stumped several hours i close end i tried several different variations comes weird ways i also found different times problem asked none seem problem i seem the question problem i seen output code the calculation carrying across columns respective row calculation keeps taking values row col apparently keeps outputting value the code def windchill row col wchill round col row colrow print end head range col range print col f end printn head row range lenstrrow printrow mph end else printrow mph end print roundwchill end col head printn print print this outputs f f f f f f f f f mph mph mph mph mph mph mph mph mph mph mph now obviously values supposed different increment mph wind speed supposed calculate values across columns row the table calculations supposed look similar table httpwwwnwsnoaagovoswindchillindexshtml,1 oftentimes also function extract xml string for example minidom parsestring lxml etreexml if content make filelike object stringio stringio import stringio content formgetvalue filename fileh stringiocontent you call filehread iterate if must file disk use tempfilemkstemp import tempfile content formgetvalue filename tmpf tmpfn tempfilemkstemp tmpfwritecontent tmpfclose now give tmpfn function expecting filename osunlinktmpfn finally delete file,i form input tag submit button input typefile namefilename size i python file handles post def postself the file i receiving form xml file python post function i want send fooxml another function going validate using minixsv my question i retrieve file i tried form cgifieldstorage inputfile formgetvalue filename puts content inputfile i fooxml file per se i pass minisxv function request xml file text update i found function accepts text instead input file thanks anyway,1 the reason recommended java exception handling generally expensive process recover when exception thrown causes jvm go backtrack order provide stack trace never good thing performance in short language misuse usually cleaner efficient way handling logic consider following code try int x servicegetvalue ifx throw new numbertoobigexceptiontoo big else throw new numbertoosmallexceptiontoo small catch numbertoobigexception e systemoutprintlni think big catch numbertoosmallexception e systemoutprintlni think small a better approach use use java intended control logic ifx systemoutprintlni think big else systemoutprintlni think small as see comparing two snippets exception handling kind ridiculous overkill sample intends a better approach example posted would something like string args one two three forstring arg args systemoutprintlnargs exceptions better used things really go wrong like ioexceptionno space left device classnotfoundexceptioncan find code run noroutetohostexceptioncan connect host,i really confused the standard approach java throw exceptions abnormal conditions use signal endofiterator examples effective java item use exceptions exceptional conditions javaspecialists newsletter flow control we never cause exception otherwise preventable i seen code instead checking bounds assumed data correct runtimeexceptions caught here example bad code please code like public class antipattern public static void mainstring args try int true systemoutprintlnargsi catch arrayindexoutofboundsexception e done whereas standard use idiom python eg stopiteration exception stopiteration raised iterator‘s next method signal values this derived exception rather standarderror since considered error normal application why bad java good python,1 this worked djangoutilsencoding import smartstr content smartstrcontent,i want parse xml document so i stored xml document class xmldocsdbexpando id dbintegerproperty namedbstringproperty contentdbblobproperty now code parser makeparser curhandler basketballhandler parsersetcontenthandlercurhandler q xmldocsall parserparsestringiostringioqcontent i getting error ascii codec encode character u xef position ordinal range traceback recent call last file basepythonruntimepythonlibversionsgoogleappengineextwebappinitpy line call handlerpostgroups file basedatahomeappsparsepythonmapreducebasehandlerpy line post selfhandle file basedatahomeappsparsepythonmapreducehandlerspy line handle scanaborted selfprocessentityentity ctx file basedatahomeappsparsepythonmapreducehandlerspy line processentity handlerentity file basedatahomeappsparsepythonparsexmlpy line process parserparsestringiostringioqcontent file basepythonruntimepythondistlibpythonxmlsaxexpatreaderpy line parse xmlreaderincrementalparserparseself source file basepythonruntimepythondistlibpythonxmlsaxxmlreaderpy line parse selffeedbuffer file basepythonruntimepythondistlibpythonxmlsaxexpatreaderpy line feed selfparserparsedata isfinal file basedatahomeappsparsepythonparsexmlpy line characters print ch unicodeencodeerror ascii codec encode character u xef position ordinal range,3 i rolled top httplib discovering urllib things,i tried urllib pycurl i looking twisted new http client but i found urllib difficult perform file upload pycurl multi looks right unpythonic twisted http client support persistent connection check file upload capability is alternative,1 install pythondev package,i trying install setproctitle i tried downloading package using setuppy install i tried easyinstall neither method works come something looks like sudo easyinstall setproctitle searching setproctitle reading httppypipythonorgsimplesetproctitle reading httpcodegooglecomppysetproctitle best match setproctitle downloading httppypipythonorgpackagessourcessetproctitlesetproctitlezipmdfacbddbbfbe processing setproctitlezip running setproctitlesetuppy q bdistegg distdir tmpeasyinstallplavsetproctitleeggdisttmptjtzk in file included srcspth srcsetproctitlec srcsptpythonh error pythonh no file directory srcsetproctitlec error expected ‘’ ‘’ ‘’ ‘asm’ ‘attribute’ ‘’ token srcsetproctitlec error expected ‘’ ‘’ ‘’ ‘asm’ ‘attribute’ ‘’ token srcsetproctitlec error expected ‘’ ‘’ ‘’ ‘asm’ ‘attribute’ ‘’ token srcsetproctitlec error array type incomplete element type srcsetproctitlec error ‘pycfunction’ undeclared function srcsetproctitlec error expected ‘’ ‘sptsetproctitle’ srcsetproctitlec error expected ‘’ ‘sptgetproctitle’ srcsetproctitlec error expected ‘’ ‘’ ‘’ ‘asm’ ‘attribute’ ‘initsetproctitle’ error setup script exited error command gcc failed exit status i really sure going i installed easily i running fresh installation ubuntu any help would appreciated,3 the current development version provide variable number arguments inclusion tag the patch described httpscodedjangoprojectcomticket it released see release notes,i trying write django inclusion tag takes arbitrary number arguments registerinclusiontag sohtml def tablefieldargs fields arg args fieldsappendarg return fields fields however i call django template engine tablefield formhr formbp formosat i get error tablefield takes arguments is yet another limitation django template engine,1 it architecturally possible current sdk cc toolchains far i tell they python repl running browserbased client complete standard library sqlite httplackingrhoticityblogspotcompythonstandardlibraryinnativehtml,would possible write native client application python go could run browser,3 try import os ossystemmycommand this works wget progressbar rewrites one line screen works correctly way i suppose would work git others well,here specific question i looking slightly general solution i writing shell script python assist various config tasks including performing git clone various repositories when i call git clone good way supply git display output directly terminal progress bars etc just piping subprocess stdout sysstdout cut git behavior involves rewriting portion terminal indicate progress so really good enough import sys subprocess process subprocesspopengit clone recursive httpsgithubcommyrepogit shelltrue stdoutsysstdout stderrsubprocesspipe i looking answer use gitpython rather i looking general technique i apply config tasks thanks,1 older everything ever i stumbled problem today anyone else i ran python cpythonscriptspywinpostinstallpy install commandline change values fit that worked python cpythonscriptspywinpostinstallpy install copied pythoncomdll cwindowssystempythoncomdll copied pythoncomloaderdll cwindowssystempythoncomloaderdll copied pywintypesdll cwindowssystempywintypesdll registered pythoninterpreter registered pythondictionary registered python softwarepythonpythoncorehelpnonenone softwarepythonpythoncorehelppythonwinreferencenone cpythonlibsitepackagespywinchm pythonwin registered context menu creating directory cpythonlibsitepackageswincomgenpy shortcut pythonwin created shortcut documentation created the pywin extensions successfully installed on winxp sp,i created python executables pyexe bit python interpreter bit python interpreter in program i use module pywin com i dl ed installed bit bit versions program prior creating executable the bit exe works fine bit one following problem traceback recent call last file programpy line module file wincominitpyc line module file winapipyc line module file winapipyc line load importerror dll load failed the specified procedure could found i tried versions running source directly ie python programpy cpythonpythonexe programpy work fine note i tested bit exe bit windows computer bit exe bit windows xp computer,2 assuming using modpython responsecontenttype textxml or responsecontenttype texthtml httpwwwmodpythonorglivecurrentdochtmlpyapimprequestmemhtml contenttype string the content type modpython maintains internal flag reqcontenttypeset keep track whether contenttype set manually within python the publisher handler uses flag following way contenttype explicitly set attempts guess content type examining first bytes output if want pretty xml output text file use beautifulsoup prettify xml,how i display html page xml i set python texthtml i writing html responseoutwrite,1 i suspect imported wrong datetime datetime import datetime instead use import datetime,i trying compile old code import datetime isinstancevalue datetimedate but i got error isinstance arg must class type tuple classes types python executable usrbinpython python version what i missing,3 you format fixedpoint number f formata,i number prints exponential form printa e how make print normal form,3 you use print formatting print f number digits want decimal point,i number prints exponential form printa e how make print normal form,1 you want override init method like save method call selfgetthumbs call superphoto self init args kwargs alternately could look peoples solution problem sorlthumbnail djangoimagekit easythumbnails sort like combination two,i totally completely new programming please forgive probably stupid question i beating head past couple days i two models photos thumbnails i trying come easy dynamic way get thumbnail links photo i come function getthumbs i like run automatically model called basically i get photogetsurl thumbname soon model available below modelspy any help nudge right direction even google blah would greatly appreciated thanks class photomodelsmodel name modelscharfieldmaxlength originalimage modelsimagefielduploadto photos caption modelstextfieldnulltrue blanktrue titleslug modelsslugfieldnulltrue blanktrue uniquetrue rootfilename modelscharfieldmaxlength editablefalse blanktrue numviews modelspositiveintegerfieldeditablefalse default def unicodeself return selfname thumbnails thumbnailobjectsall def createthumbsself thumbnail selfthumbnails fname settingsmediaroot selfrootfilename thumbnailname jpg existsfname none else timg imageopenselforiginalimagepath tfit imageopsfittimg thumbnailheightthumbnailwidth imageantialias tfitsavefnamejpeg def saveself args kwargs selfrootfilename selforiginalimagenamestrip photosjpg superphoto selfsaveargs kwargs selfcreatethumbs def getthumbsself thumb selfthumbnails setattrself get thumbname url thumbs selfrootfilename thumbname jpg,1 use skipkeys option jsonencoder skips items encode alternatively create default method jsoneddata object see docs,why list numbers kind object it seems like trying compensate design flaw as matter fact i want work way i want keep data already encoded jsoneddata i want json module give way insert raw item data rather defaults encoded jsoneddata could reuseable code thanks import json import io class jsoneddata def initself data selfdata data def main try chunk jsonjsonencoderiterencodejsoneddatau print chunk except typeerror pass except come method make print continue printed data something like,2 put try except inside loop around jsonjsonencoderencodeitem print lst jsoneddatau item enumeratelst â â try â â â â chunk jsonjsonencoderencodeitem â â except typeerror pass else print chunk finally dont print last item lst lenlst print print,why list numbers kind object it seems like trying compensate design flaw as matter fact i want work way i want keep data already encoded jsoneddata i want json module give way insert raw item data rather defaults encoded jsoneddata could reuseable code thanks import json import io class jsoneddata def initself data selfdata data def main try chunk jsonjsonencoderiterencodejsoneddatau print chunk except typeerror pass except come method make print continue printed data something like,2 from docs urlliburlencode query doseq convert mapping object sequence twoelement tuples “percentencoded” string series keyvalue pairs separated amp characters a dict mapping,after using cgiparseqs convert result dictionary back query string looking something similar urlliburlencode,3 for windows head portable python httpportablepythoncom see various options for linux mac need install usb drive systems usually come python preinstalled if need specific packages systems bring usb together command line script load one call virtualenv systems good go be aware never bullet proof depending python version usingbringing packages,i want install python flash drive virtual environment i develop code wherever i is possible way i use flash drive windowsmaclinux computers,2 you need positional arguments cnames symbols,curexecute insert into company values cname symbol startdate enddate cname company symbol company startdate startdate enddate enddate trying run line computer results string formatting error valueerror unsupported format character xc index it seems concerning i checked parenthesis properly nested none enclosing errant,3 what imm said also may want use built query formatting part mysqldb curexecuteinsert into company values company company startdate enddate,curexecute insert into company values cname symbol startdate enddate cname company symbol company startdate startdate enddate enddate trying run line computer results string formatting error valueerror unsupported format character xc index it seems concerning i checked parenthesis properly nested none enclosing errant,1 the easiest way avoid crashes anomalous behavior sorts ensure main thread handles gui you could try finding locking critical code blocks opinion losing game much easier synchronize processing threads main thread using events run selftimerevtwait wait main thread unblock selftimerevtclear process stuff put results queue shared variables processing thread def tickself run update gui queued data shared variables selftimerevtset unblock processing thread selfrootafterms selftick reschedule gui update main thread,i program time lapse maker two threads updates wxstaticbitmap when two threads access wxstaticbitmap crashes error python xcbioc pollforevent assertion long eventsequence long dpyrequest failed i tried google search answer i tried solve i still figure simple piece code reproduces error actual program usrbinenv python import wx import timeospathglobthreading class myframewxframe def initself args kwds kwdsstyle wxdefaultframestyle wxframeinitself args kwds selfbitmap wxstaticbitmapself wxnullbitmap selfsetproperties selfdolayout wxcallafterselfimg def setpropertiesself selfsettitleframe def dolayoutself sizer wxboxsizerwxvertical sizeraddselfbitmap selfsetsizersizer sizerfitself selflayout def imgself thread threadingthreadtargetselfimg threadstart thread threadingthreadtargetselfimg threadstart def imgself frames globglobpathtopngspng framessort rangelenframes ospathisfileframesi print framesi wxyield timesleep wxcallafterselfbitmapsetbitmapwxbitmapframesi wxbitmaptypeany wxcallafterselfupdate def imgself frames globglobpathtopngspng framessort rangelenframes ospathisfileframesi print framesi wxyield timesleep wxcallafterselfbitmapsetbitmapwxbitmapframesi wxbitmaptypeany wxcallafterselfupdate name main app wxpysimpleapp wxinitallimagehandlers frame myframenone appsettopwindowframe frameshow appmainloop i solved wxpostevent see answer,2 if look partition function formulas section partiton number theory page wikipedia see simple way find partition number instead best bet probably sum p slightly simpler memory hogging large numbers lenlistp using existing function also note want able save values returned p yield ing p p want make copy yield list change you see listp returns list empty list repeated fore info partitioning see partitioning python,i defined recursive function takes number n returns list lists numbers sum number partitions def pn base case recursion zero sum empty list n yield return p pn pappend yield p ppop p lenp p p p yield p i wondering make function return number partitions number n for example p would return,2 you running jython code inside r environment looking way send attachment using jython language r since jython basically python way send email attachment python how send email attachments python you hack together code,i desiring send email r attachment using gmail i found sendmailr work gmail requires authentication i get work gmail i assume true unless someone tells i wrong case i post r output error message i found code snippet found link as site suggests code formatted send attachments i got send email i like extend code send attachments email correspondence author code unable extend code send attachments i want send emails r using gmail i windows user beta version r the code sends emails attachments requirerjython rjython rjython rjythonexec import smtplib rjythonexecfrom emailmimetext import mimetext rjythonexecimport emailutils mailc email settings fromaddr bigbirdgmailcom toaddrs oscarthegrouchgmailcom msg mimetext this body message msg from emailutilsformataddr sender name fromaddr msg to emailutilsformataddr recipient name toaddrs msg subject simple test message smtp server credentials username bigbirdgmailcom password pw set smtp server send email eg google mail smtp server server smtplibsmtp smtpgmailcom serverehlo serverstarttls serverehlo serverloginusernamepassword serversendmailfromaddr toaddrs msgasstring serverquit jythonexecrjythonmail note message cross posted talkstatscom i receive reply members telling wish could help if i receive workable solution also post well,3 you looking something exactly like urlliburlencode however call parseqs distinct parseqsl dictionary keys unique query variable names values lists values name in order pass information urlliburlencode must flatten lists here list comprehenshion tuples querypairs kv kvlist diteritems v vlist urlliburlencodequerypairs,after using cgiparseqs convert result dictionary back query string looking something similar urlliburlencode,3 take look package sendmailr send attachments to make sendmail work gmail mac would require additional fiddling around find instructions using google search,i desiring send email r attachment using gmail i found sendmailr work gmail requires authentication i get work gmail i assume true unless someone tells i wrong case i post r output error message i found code snippet found link as site suggests code formatted send attachments i got send email i like extend code send attachments email correspondence author code unable extend code send attachments i want send emails r using gmail i windows user beta version r the code sends emails attachments requirerjython rjython rjython rjythonexec import smtplib rjythonexecfrom emailmimetext import mimetext rjythonexecimport emailutils mailc email settings fromaddr bigbirdgmailcom toaddrs oscarthegrouchgmailcom msg mimetext this body message msg from emailutilsformataddr sender name fromaddr msg to emailutilsformataddr recipient name toaddrs msg subject simple test message smtp server credentials username bigbirdgmailcom password pw set smtp server send email eg google mail smtp server server smtplibsmtp smtpgmailcom serverehlo serverstarttls serverehlo serverloginusernamepassword serversendmailfromaddr toaddrs msgasstring serverquit jythonexecrjythonmail note message cross posted talkstatscom i receive reply members telling wish could help if i receive workable solution also post well,1 you could use list comprehension like something key value key value something key b however looks like trying reinvent dictionary reason if ordered use dictionary something digitaltext b bbbbbbb c del something b if need ordered use collectionsordereddict rather dict collections import ordereddict something ordereddict digitaltext b bbbbbbb c del something b with dictionary need back format question call items dictionary assuming something ordereddict already deleted item plain dict might different order deleted item would still somethingitems digitaltext c additionally convert list like question kind dictionary pass dict digitaltext b bbbbbbb c digitaltext b bbbbbbb c,if i following data type digitaltext b bbbbbbb c how i remove item b output look like digitaltext c how i also check b exists deleting i tried b xxxx find i new python,3 solved best help joe kington thanks lot insert original code question mytimestring row table mytimestringappendtabledatetimei numtimedatestrnummytimestring axplotdatenumtime tablevalues there certainly elegant solutions row works,i posted question qgisuser forum might technical thus i take chance try well my plan qgis plugin reads plots time series data corresponding selected points vector layerthe points represents different measuring stations i need quickly view time series one sometimes several stations plot consequently i need python read time series data spatialite table plot matplotlibplot pyspatialite import dbapi sqlite import numpy np import matplotlibpyplot plt import datetime mypath rcdatadbtestmytestdbsqlite conn sqliteconnectmypathdetecttypessqliteparsedecltypessqliteparsecolnames curs conncursor sql rselect date date datetime levelmasl from mytable rs cursexecutesql recs rsfetchall myformat datetime datetimedatetime values float table nparrayrecs dtypemyformat tabletableviewnprecarray fig pltfigure ax figaddsubplot axplottabledatetime tablevalues but seems like i get correct data types since matplotlib accept datetime a print table shown i guess small u indicates unicode datetime print table recarrayu u dtype datetime o values i programmer absolutely complete python spatialite beginner help would much appreciated jk,1 if file attribute means probably built python library executable exist independently disk,i trying find location module i searched python folder still find i know import math mathpath traceback recent call last file pyshell line module mathpath attributeerror module object attribute path mathfile traceback recent call last file pyshell line module mathfile attributeerror module object attribute file,3 if module specific program put directory main script from documentation when module named spam imported interpreter searches file named spampy directory containing input script list directories specified environment variable pythonpath i would recommend read entire tutorial modules it pretty short lot useful info,i wondering python modules work say i want make python program custom modules package would i put relation main py fileand would i load using usual way,3 here explanation initpy needed the initpy files required make python treat directories containing packages done prevent directories common name string unintentionally hiding valid modules occur later module search path in simplest case initpy empty file also execute initialization code package set variable described later as i recommended another poster tutorial modules pretty informative,in python directory containing one modules sometimes initpy directory treated python package correct what differences init makes also another q python module python codefile related possibly independent files set classes functions variables,2 in addition contents initpy becomes contents package treated module ie contents somepackageinitpy found dirsomepackage import somepackage modules python code speciallycrafted c code could artificial construct injected executable loads python vm,in python directory containing one modules sometimes initpy directory treated python package correct what differences init makes also another q python module python codefile related possibly independent files set classes functions variables,1 you use stringio file object instead regular file well pil imageopen imagesave there also frombuffer function,i would like image conversionrewriting pil using ram memory i image bytes ram i would like convert format possibly i know i like saving file system name i would like using ram without touching file system i found examples any help would appreciated thanks,2 i think djangocelery work did look tables made djangocelery ie djcelerytaskstate holds data given task like state workerid for periodic tasks table called djceleryperiodictask in django view access taskmeta object djcelerymodels import taskmeta task taskmetaobjectsgettaskidtaskid print taskstatus,in django python app i launch jobs celery task manager when job launched return object lets call instance class x lets check job retrieve return value errors thrown several people someday i hope able use web interface time therefore several instances class x may exist time corresponding job queued running parallel it difficult come way hold onto x objects i cannot use global variable dictionary allows look x objects key celery uses different processes different threads would modify copy global table causing mayhem subsequently i received great advice use memcached share memory across tasks i got working able set get integer string values processes the trouble great deal debugging today i learned memcached set get seem work classes this best guess perhaps hood memcached serializes objects shared memory class x understandably cannot serialized points live data status job serial version may date ie may point wrong place loaded attempts use sqlite database similarly fruitless could i figure serialize objects database fields using django modelspy file i would stuck problem handles launched jobs need stay ram somehow use fancy os tricks underneath update jobs finish fail my best guess despite advice thankfully got far i launching job external queue instance sunoracle grid engine however i come good way without using system call i thought may bad style potentially insecure how keep track jobs launch django django celery do launch simply putting job arguments database another job polls database runs jobs thanks lot help i quite lost,1 you could create thedict dictamountpaidap paiddatepd methodmethod commentscomments also template code make sense you iterating keys dict using body edit key thedict val thedictkey input namekey valueval endfor endfor,i new python django wondering i would go making dict lists my lists ap requestpostgetlist amountpaid pd requestpostgetlist paiddate method requestpostgetlist method comments requestpostgetlist comments how would i make dictionary i could loop django template thedict iamountpaid endfor thanks advance update hmm i sure i posted question properly in php i following array fields foriicountpost amountpaid echo post amountpaid echo post paiddate all form fields input text fields how would i django,1 you quite easily listen udp port standard socket module examples available as first step data could go simple python list lists optimized appending data removing first elements takes much time might want time time plot mean time last whatever elements list plotting conveniently done famous matplotlib plotting library matplotlibpyplotplotdatalist since want real time might find animation examples useful if need optimize data acquisition speed also famous numpy arraymanipulation library directly interpret data stream array numbers matplotlib plot arrays numpyfrombuffer function,i little c program continuously acquiring stream data sending via udp real time different computer the basic framework i originally set laid in addition however i like visualize real time data acquired to end i thinking using python various plotting libraries my question difficult would let python access essentially first first circular buffer c program for concreteness let assume samples buffer does idea letting python continuous peek dynamic c array even sound reasonablepossible if sort plotting options best suited problem thanks,1 python dict syntax simple it keyvalue pairs inside pair curly braces like thedict amountpaid requestpostgetlist amountpaid paiddate requestpostgetlist paiddate method requestpostgetlist method comments requestpostgetlist comments following update looks like want dict zip post requestpost lists zippostgetlist amountpaid postgetlist paiddate postgetlist method postgetlist comments amountpaid paiddate method comments lists print amountpaid print paiddate et cetera,i new python django wondering i would go making dict lists my lists ap requestpostgetlist amountpaid pd requestpostgetlist paiddate method requestpostgetlist method comments requestpostgetlist comments how would i make dictionary i could loop django template thedict iamountpaid endfor thanks advance update hmm i sure i posted question properly in php i following array fields foriicountpost amountpaid echo post amountpaid echo post paiddate all form fields input text fields how would i django,1 try else find first element matches mid sortedsamplesmid attr desiredattr mid iterate element match found mid lensortedsamples sortedsamplesmidattr desiredattr newlistappendsortedobjectsmid mid this runs om time number objects desired attribute,i extremely large list objects i need find identical attribute anyobjectanyattribute append new list so i presorted run binary search algo i found object matching attribute problem one objects neighbours i figure clean way running loop contiguous objects appended my code pasted low high lensortedobjects low high mid low high sortedobjectsmidattr desiredattr low mid elif sortedsamplesmidattr desiredattr high mid else newlistappendsortedobjectsmid break so i need write new code last else block would iterate objects attributes append sounds like loop would needed possible run loop limited iterations like c i want iterate whole list would slower one requirements script fast efficient it run really large sets data looking execution times hrs thanks advance,2 if going perform search often create list attribute attrlist oattr sortedobjects use bisect module import bisect lefti bisectbisectleftattrlist desiredattr righti bisectbisectrightattrlist desiredattr lefti newlist sortedobjectsleftirighti,i extremely large list objects i need find identical attribute anyobjectanyattribute append new list so i presorted run binary search algo i found object matching attribute problem one objects neighbours i figure clean way running loop contiguous objects appended my code pasted low high lensortedobjects low high mid low high sortedobjectsmidattr desiredattr low mid elif sortedsamplesmidattr desiredattr high mid else newlistappendsortedobjectsmid break so i need write new code last else block would iterate objects attributes append sounds like loop would needed possible run loop limited iterations like c i want iterate whole list would slower one requirements script fast efficient it run really large sets data looking execution times hrs thanks advance,1 see httpreadthedocsorgdocsscrapyenlatesttopicsspidershtmlhighlightalloweddomainsscrapyspiderbasespideralloweddomains alloweddomains an optional list strings containing domains spider allowed crawl requests urls belonging domain names specified list won’t followed offsitemiddleware enabled so long activate offsitemiddleware settings matter leave alloweddomains completely check settingspy whether offsitemiddleware activated it activated want allow spider crawl domain,i using scrapy extract data certain websitesthe problem spider crawl webpage initial starturls crawl urls webpage i copied spider exactly scrapyspider import basespider scrapycontriblinkextractorssgml import sgmllinkextractor scrapyselector import htmlxpathselector scrapyhttp import request scrapyutilsresponse import getbaseurl scrapyutilsurl import urljoinrfc nextlinkitems import nextlinkitem class nextlinkspiderbasespider name nextlink alloweddomains nextlink starturls httpwwwdmozorgcomputersprogramminglanguagespythonbooks def parseself response hxs htmlxpathselectorresponse sites hxsselect bodydivdivdivulliahref site sites relativeurl siteextract url selfurljoinresponserelativeurl yield requesturl callback selfparsetext def parsetextself response log openlogtxt logwritetest parsetext called hxs htmlxpathselectorresponse items texts hxsselect div extract text texts item nextlinkitem item text text itemsappenditem log openlogtxt logwritetext return items def urljoinself response url helper convert relative urls absolute return urljoinrfcresponseurl url responseencoding i use logtxt test parsetext calledhowever i runned spider nothing logtxt,1 u u c u u u u ujoina u c strujoina c,want join unicode python list example u u c u u u u want string looks like c how would join,3 in function gasdev declare ran external function as link function importing module fail instead remove declaration ran gasdev case ran call uses explicit interface ran function module everything works,i need wrap simply fortran code fpy the fortran module testf module util contains function gasdevidum implicit none integerkind intentinout idum realkind gasdev ran printidum gasdev ranidum return end function function ranidum implicit none integerkind intentinout idum realkind ran printidum rand return end function end module util i wrap fpy test c testf i import python in import test prompted error saying importerror testso undefined symbol ran any ideas fix thanks,3 the count expression countp count brackets not sure problem thought i point,i trying receive properties whose labels contain certain string i use following query select p l countp count where someobj p p httpwwwworgrdfsyntaxnsproperty p httpwwwworgrdfschemalabel l l bifcontains string filter langl en filter isliteralsomeobj order by desccount limit when issueing query public dbpedia endpoint httpdbpediaorgsparql works returns i want however i sparqlwrapper python script i keep getting file ethesissemwebpy line findword results sparqlqueryconvert file buildbdistlinuxieggsparqlwrapperwrapperpy line query return queryresultselfquery file buildbdistlinuxieggsparqlwrapperwrapperpy line query raise e httperror http error sparql request failed i tried variations query without counting sorting without limiting i keep getting http i think endpoint instable i problem queries script stops query similar queries retrieve objects work fine public endpoint script select l counts count where someobj p httpwwwworgrdfschemalabel l l bifcontains computer filter regexstrs httpdbpediaorgresourcecategory filter regexstrs httpdbpediaorgresourcelist filter regexstrs httpswopencycorg filter langl en filter isliteralsomeobj order by desccount limit any idea could causing or idea i could retrieve specific error thanks advance,1 it windows issue python version library version issue dateutil written support python python x both cases contain bugs used python x in first case dateutilparserparse iostringio class allows unicode arguments code reads isinstanceinstream str instream stringioinstream in second case dateutilparserparseunicode look timelex class contains next method python way indicating object supports iteration protocol in python x name method next check versions python library linux windows from project website pythondateutiltargz python pythondateutiltargz python,i sure really simple solution i still fairly new python i trying use dateutilparserparse parse string timestamp import dateutilparser dateutilparserparse print this works fine linux server windows test box gives error import dateutilparser dateutilparserparse traceback recent call last file stdin line module file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line parse return defaultparserparsetimestr kwargs file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line parse res selfparsetimestr kwargs file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line parse l timelexsplittimestr file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line split return listclss file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line init instream stringioinstream typeerror initialvalue must unicode none str if i try giving dateutilparserparse unicode string work windows box either dateutilparserparseunicode traceback recent call last file stdin line module file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line parse return defaultparserparsetimestr kwargs file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line parse res selfparsetimestr kwargs file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line parse l timelexsplittimestr file cpythonlibsitepackagespythondateutilpyeggdateutilparserpy line split return listclss typeerror iter returned noniterator type timelex yet also works linux box,3 use wxauiauimanagersaveperspective wxauiauimanagerloadperspective load save layout data assuming consistent set panes load saved for wxpython saveperspective return string store somewhere pass loadperspective this may work reliably i number problems documentation wxwidgets httpdocswxwidgetsorgwxwxauimanagerhtmlwxauimanagersaveperspective httpdocswxwidgetsorgwxwxauimanagerhtmlwxauimanagerloadperspective for single pane manager use savepaneinfo loadpaneinfo wxauiauimanager,how save position wxaui panels ini file examples methods getposition getsize give defaultsizes positions,2 as often happens really asking problem actually need solve done things certain wrong way asking get problem got if i understand correctly got set fields amountpaid paiddate method comments field appears multiple times form got one set values entry you presumably trying sort list dicts row well right way go django you using formsets give one form row table ie exactly want achieve,i new python django wondering i would go making dict lists my lists ap requestpostgetlist amountpaid pd requestpostgetlist paiddate method requestpostgetlist method comments requestpostgetlist comments how would i make dictionary i could loop django template thedict iamountpaid endfor thanks advance update hmm i sure i posted question properly in php i following array fields foriicountpost amountpaid echo post amountpaid echo post paiddate all form fields input text fields how would i django,1 unfortunately pydev feature thinking bit would implemented i come way implement solution changing property one i use i need feature work global variable said case instead global variable i usually holder instance contains variables case still possible create property work slowdog different question related watchpoints actually works pydev,i global variable i know changed good value bad value somewhere i know i like find i would like debugger eclipsepydev break time code writes global variable something akin hardware breakpoints ollydbg one trick i found sometimes works situation refactor variable property set breakpoint property setter access variable goes setter i get i want debugger this working case ideas,1 you iterating iterable simultaneously modifying iterable so one loop completed pointer may necessarily pointing next item original set iterating if isprimepalindrom returns true remove one item length list reduced one consider situation palindromes palindrom value palindrom actually pointing palindromes after loop palindrome pointing palindromes meanwhile since removed palindromes since prime now palindromes palindrom palindromes you see value never touched the moral never manipulate iterable iterating it like cutting branch tree sitting way function name isnotprime rather isprime reflect checking,i got something like palindromes course im generating def isprimenumber rangeintnumber numberi return true return false def removenonprimespalindromes palindrom palindromes isprimepalindrom palindromesremovepalindrom return palindromes palindromes removenonprimespalindromes and doesnt remove non primes i figure,1 meta just realized question still unanswered i idea really happened guess this probably caused failing use keyfile connecting machine plaintext password ssh connection disabled proper usage would fab keyfilepem fabrictask,i using fabric run following def staging use staging environment remote host envuser ubuntu envenvironment staging envhosts hostdev setuppath def bootstrap initialize remote host environment virtualenv deploy update require root providedby staging production run mkdir p roots env run mkdir p ospathjoinenvhome www log createvirtualenv deploy updaterequirements but i get ubuntuhostdevprojectsprojname fab staging bootstrap hostdev run mkdir p homeubuntuwwwstaging password ubuntuhostdev why fabric asking password this default ubuntu root user password sudoers files what going,3 there intellij idea plugins time tracking far i see none updated pycharm compatibility you try contact author time tracker plugin ask update pycharm compatibility httppluginsintellijnetpluginideaampid,i checked httpcodegooglecomprabbiteclipse eclipse time tracking stuff automatically does pycharm something similar,1 store vat jsondumpsstore vat store vat true,i want convert python boolean js boolean literal this i working store dictvattrue store vat storeupdate vat true else storeupdate vat false is less verbose way replace code snippet,3 i think time error dbpedia part looks different graphs when trying dbpedia web interface always includes uri graph querying so try adding query select p l countp count from httpdbpediaorg where someobj p p httpwwwworgrdfsyntaxnsproperty p httpwwwworgrdfschemalabel l l bifcontains string filter langl en filter isliteralsomeobj order by desccount limit try tried using following python script import sys import urlliburllib def queryequeryeprsoftlimittrue try params urlliburlencode query query opener urllibbuildopenerurllibhttphandler request urllibrequestepr params requestaddheader accept applicationjson requestgetmethod lambda get url openeropenrequest data urlread return data except exception e tracebackprintexcfilesysstdout raise e,i trying receive properties whose labels contain certain string i use following query select p l countp count where someobj p p httpwwwworgrdfsyntaxnsproperty p httpwwwworgrdfschemalabel l l bifcontains string filter langl en filter isliteralsomeobj order by desccount limit when issueing query public dbpedia endpoint httpdbpediaorgsparql works returns i want however i sparqlwrapper python script i keep getting file ethesissemwebpy line findword results sparqlqueryconvert file buildbdistlinuxieggsparqlwrapperwrapperpy line query return queryresultselfquery file buildbdistlinuxieggsparqlwrapperwrapperpy line query raise e httperror http error sparql request failed i tried variations query without counting sorting without limiting i keep getting http i think endpoint instable i problem queries script stops query similar queries retrieve objects work fine public endpoint script select l counts count where someobj p httpwwwworgrdfschemalabel l l bifcontains computer filter regexstrs httpdbpediaorgresourcecategory filter regexstrs httpdbpediaorgresourcelist filter regexstrs httpswopencycorg filter langl en filter isliteralsomeobj order by desccount limit any idea could causing or idea i could retrieve specific error thanks advance,1 use power zip function list comprehensions list b c e f g h list p q r u v w print b b ziplist list,beginner python i nested lists i want merge list b c e f g h list pq r u v w output i looking list p q b c r e f g h u v w can done without external libraries note lenlist lenlist,3 operator import add list mapadd list list,beginner python i nested lists i want merge list b c e f g h list pq r u v w output i looking list p q b c r e f g h u v w can done without external libraries note lenlist lenlist,1 the super function takes derived class first parameter base class superperson selfcallsomeinfo if need use base class directly beware break multiple inheritance unless sure want parentcallself someinfo,i like call parent call method inherited class code looks like usrbinenv python class parentobject def callself name print hello world name class personparent def callself someinfo superparent selfcallsomeinfo p person pinfo and i get file testpy line call superparent selfcallsomeinfo attributeerror super object attribute call and i figure somebody please help thanks,3 you use namelist extract sample considering directories import zipfile import ospath import os zfile zipfilezipfiletestzip name zfilenamelist dirname filename ospathsplitname print decompressing filename dirname ospathexistsdirname osmakedirsdirname zfileextractname dirname,i hard time figuring unzip zip file extract included i restricted using server can someone please provide simple code example,3 i suggest use open flash chart these simple use,i looking develop interactive charts applications using python i pretty much decided matplotlib charting library as i newcomer python web development i looking good starting point matplotlib web development using python the best thing i found till httpwwwpacktpubcommatplotlibpythondevelopmentbookutmsourcematplotlibsourceforgenetamputmmediumlinkamputmcontentpodamputmcampaignmdb can anyone recoomend sources free paid,1 not fully tested okay import os zipfile import zipfile zipinfo class zipcompatzipfile def initself args kwargs zipfileinitself args kwargs def extractself member pathnone pwdnone isinstancemember zipinfo member selfgetinfomember path none path osgetcwd return selfextractmembermember path def extractallself pathnone membersnone pwdnone members none members selfnamelist zipinfo members selfextractzipinfo path def extractmemberself member targetpath targetpath ospathsep ospathaltsep lenospathsplitdrivetargetpath targetpath targetpath memberfilename targetpath ospathjointargetpath memberfilename else targetpath ospathjointargetpath memberfilename targetpath ospathnormpathtargetpath upperdirs ospathdirnametargetpath upperdirs ospathexistsupperdirs osmakedirsupperdirs memberfilename ospathisdirtargetpath osmkdirtargetpath return targetpath target filetargetpath wb try targetwriteselfreadmemberfilename finally targetclose return targetpath,i hard time figuring unzip zip file extract included i restricted using server can someone please provide simple code example,1 result testcaseproductundertesttestcaseversionundertesttestcasenametestcaseresultstestcaselasttestendtestcaseparenttestcaselevel result maplambda xxnone null strx result mecsvoutputwritejoinresult n,i requirement drop test results csv reporting in python test code i value variables filled python way none i asked replace null csv reporting tool i thinking easy probably solved hundred times here code i came field testcaseproductundertesttestcaseversionundertesttestcasenametestcaseresultstestcaselasttestendtestcaseparenttestcaselevel field none field null mecsvoutputwritesssssssn testcaseproductundertesttestcaseversionundertesttestcasenametestcaseresultstestcaselasttestendtestcaseparenttestcaselevel unfortunately changes field within scope loop how i change scope write statement i would quite happy write null leave variables unchanged i work either way,2 do like fields strfield null field testcaseproductundertesttestcaseversionundertesttestcasenametestcaseresultstestcaselasttestendtestcaseparenttestcaselevel mecsvoutputwritesn joinfields or even powerfull use generator object instead fields strfield null field testcaseproductundertesttestcaseversionundertesttestcasenametestcaseresultstestcaselasttestendtestcaseparenttestcaselevel,i requirement drop test results csv reporting in python test code i value variables filled python way none i asked replace null csv reporting tool i thinking easy probably solved hundred times here code i came field testcaseproductundertesttestcaseversionundertesttestcasenametestcaseresultstestcaselasttestendtestcaseparenttestcaselevel field none field null mecsvoutputwritesssssssn testcaseproductundertesttestcaseversionundertesttestcasenametestcaseresultstestcaselasttestendtestcaseparenttestcaselevel unfortunately changes field within scope loop how i change scope write statement i would quite happy write null leave variables unchanged i work either way,1 create shellscript activates virtual environment runs python script background also python module virtual environment import activate environment i virtualenv working moment i check search activate something similar virtual environment find edit added minimal debian initd script the absolute minimal script needed start daemon computer boots binsh pathtoprogram amp the amp makes program run background wont stop rest boot process for complete script copy etcinitdskeleton edit new file the important part edit block beginning begin init info end init info used updatercd program name daemon daemonargs variables hopefully needed making startupscript activate script sudo updatercd name script defaults sudo updatercd name script enable and start sudo updatercd name script start the name script name full path,i seen lot scripts daemonizing python script linux much information use could anyone guide i currently lengthy python script listens socket incoming message correct format accepts stores database the script opens socket listens true job work to daemonize would i modify current script call separate script i seen examples got neither work also i using virtualenv might root problems hints using daemonized scripts,3 the first two bytes pyc file magic number tells version bytecodes the word stored littleendian format known values pythonimportc merged aix python python edit added little endian hex values comparison first two bytes igor popov method jimbob python xe python xe python xe python xcc python xc python xc python xaeb python xaeb python xaeb python xded python xbf python xf python xbf python xf python xf python b xdf python xf python xf astbranch python xbf python xcf changed withcleanup opcode python b xf fix wrong code x python b xff fix wrong code x yield python c xaf fix wrong lnotab loops storing constants removed python c xbf fix wrong code x listcompgenexp python xcf peephole optimizations storemap opcode python xdf withcleanup optimization python xdbf optimize list comprehensionschange listappend python xef optimize conditional branches introduce popjumpiffalse popjumpiftrue python xeff introduce setupwith python xff introduce buildset python xf introduce mapadd setadd python xbb xcb removed unaryconvert xccb added buildset xdb added keywordonly parameters xeb added signature annotations xeab print becomes function xfb pep metaclass syntax xfb string literals become unicode xffb pep raise changes xc pep make file name unicode xc kill str interning xdc merge see xfc file points source file python xc withcleanup optimization python xbc lexical exception stacking including popexcept python xc optimize list set dict comprehensions change listappend setadd add mapadd python xfc optimize conditional branches introduce popjumpiffalse popjumpiftrue python xc add setupwith tag cpython python xc add duptoptwo remove duptopx rotfour tag cpython python xcc add deletederef,is way know python version pyc file compiled,3 you get magic number python follows python v python python import imp impgetmagicencode hex dfda to get magic number pyc file following f open testpyc magic fread magicencode hex bfda f open testpyc magic fread magicencode hex dfda by comparing magic numbers know python version generated pyc file,is way know python version pyc file compiled,3 try ackslate setting celeryackslate task messages acknowledged task executed with may able rerun tasks easily,i taskrecursivetask schedule task executed seconds later reason task crashes needs rerun i catched nearly every scenario never know happen future i first made repeated taskmanagetasks checks status recursivetask check run long time succesfully completed feel right so would solve problem,1 run script administrator right click script select run administrator script lacks permissions execute ostmpfile edit as i see using interpreter simply run interpreter administrator if accessing though terminal running terminal administrator sufficient,i trying use generateds windows uses ostmpfile unfortunately ostmpfile work oneclickcos cusersmarcindocumentsoneclickcosxsdpython python default jun msc v bit amd win type help copyright credits license information import os ostmpfile traceback recent call last file stdin line module oserror errno permission denied i got temp directories set full control everyone problem what could causing,2 as griffin pointed problem ostmpfile tries create file root directory if like run script administrator use ostmpnam handle file warning use tmpnam vulnerable symlink attacks,i trying use generateds windows uses ostmpfile unfortunately ostmpfile work oneclickcos cusersmarcindocumentsoneclickcosxsdpython python default jun msc v bit amd win type help copyright credits license information import os ostmpfile traceback recent call last file stdin line module oserror errno permission denied i got temp directories set full control everyone problem what could causing,1 pandad applications run browser provided user pandad plugin see section iii pandad manual distributing pandad applications pygame cannot run browser thus cannot integrated rails application i rails experience i would surprised rails let munge html needed,this might sound like vague question wanted know integrate python code rails application more specifically game coded something like pygame might pushing far say pandad could make someone could play browser rails app one paragraph answer link reading material fine,1 you setting class properties using instance for example class aobject xa print xa prints xa xa prints aa prints,calling setfields i expect the code context django model i suspect i made python error class fooeditmodelform class meta model foo client call setfields fields a b def setfieldsself pro set fields correctly status pro selfmetafields a b x else selfmetafields a y z w,1 answering last case bind method class instance methodtype import types class myclassobject def initself selfmymethod typesmethodtypemymethod self,let say i method class def mymethodself selfmark knopfler class mysubclassobject mymethod mymethod i think ways use mymethod within another class case if i want access mymethod within yet another class like class myclassobject def initself selfmysubclass mysubclass i correct thinking allow use mymethod instance like myinst myclass myinstmysubclassmymethod this seems work like i expect i like case class myclassobject mysubclass mysubclass myinst myclass myinst myclass myinstmysubclassmymethod i understand previous line apply mymethod myinst myinst is correct case another way get mymethod attribute myclass class myclassobject mymethod mymethod i understand i multiple instances myclass applying mymethod affect instance bound is correct case last one class myclassobject def initself selfmymethod mymethod problem final method seems create mymethod unbound method suit needs is way add existing method bound instance method class definition ok that please let know four cases makes sense use thanks,1 you treating class method like function choose one def sendmailrequest messagesend class mainhandlerwebapprequesthandler def postself sendmailselfrequest or class mainhandlerwebapprequesthandler def sendmailself request selfrequest messagesend def postself selfsendmail,i mainpy looking like usrbinenv python import cgi googleappengineext import webapp googleappengineextwebapputil import runwsgiapp googleappengineextwebapp import util imports sending mail googleappengineapi import mail googleappengineapi import users message mailemailmessagesendersupport xyzgmailcom subjectemail messageto info infoxyzcom messagehtml htmlheadheadbody dear bibnfo br br messagebr br please let us know questionsbr br the flxlmonlinecom support team bodyhtml class mainhandlerwebapprequesthandler def getself selfresponseoutwrite html body form actionsign methodpost p label fornamenamelabel input typetext namename p p label foremailemaillabel input typeemail nameemail p p label formessagemessagelabel textarea namemessagetextarea p divinput typesubmit valuesign guestbookdiv form body html def postself selfresponseoutwrite htmlbodyyou wrotepre selfresponseoutwritecgiescapeselfrequestget message selfresponseoutwrite prebodyhtml sendmailselfrequest def sendmailrequest messagesend application webappwsgiapplication mainhandler sign mainhandler debugtrue def main utilrunwsgiappapplication name main main as see i trying call another class method called sendemail inside post this gives compilation error any idea i going wrong thanks advance btr naidu,1 you integer division try something like n rangen pii floatin powfloatin,i code n rangen pii in powin but division operations getting rounded nearest integer how i instruct python floatingpoint division,3 add line top script future import division this allow division integers give floats usual division operator if also need perform integer division use this standard behavior python,i code n rangen pii in powin but division operations getting rounded nearest integer how i instruct python floatingpoint division,3 the problem got resolved i called commit follows connmssqlcommit immediately curmssqlexecuteqryins line usrbinpython import pymssql ms import mysqldb mdb import sys connection mssql connmssqlmsconnecthost user sa password hostailpw database hostail asdicttrue connection mysql connmysqlmdbconnect localhost root trail trail cursor mssql curmssqlconnmssqlcursor cursor mysql curmysqlconnmysqlcursormdbcursorsdictcursor curmysqlexecute select from clinicsmapping get data mysql server rowmysql curmysql print rowmysql clinicname rowmysql cliniccode curmssqlexecutemanyinsert into clinics valuesss rowmysql clinicname rowmysql cliniccode names rowmysql clinicname codes rowmysql cliniccode qryinsinsert into clinicsnamecodevalues strnamesstrcodes curmssqlexecuteqryins connmssqlcommit i called commit persists data put autocommit truei called connmssqlcommit script close mssql connection connmssqlclose close mysql connection connmysqlclose,this python script connects mysql database mssql r database mysql database runs linux ubuntu mssql runs windows the script runs linux ubuntu usrbinpython import pymssql ms import mysqldb mdb import sys connection mssql connection mssql connmssqlmsconnecthost user sa password hostailpw database hostail asdicttrue connection mysql connection mysql connmysqlmdbconnect localhost root trail trail cursor mssql cursor mssql curmssqlconnmssqlcursor cursor mysql cursor mysql curmysqlconnmysqlcursormdbcursorsdictcursor curmysqlexecute select from clinicsmapping get data mysql get data mysql server rowmysql curmysql print rowmysql clinicname rowmysql cliniccode curmssqlexecutemanyinsert into clinics valuesss rowmysql clinicname rowmysql cliniccode names rowmysql clinicname codes rowmysql cliniccode qryinsinsert into clinicsnamecodevalues strnamesstrcodes curmssqlexecuteqryins print rowmysql clinicname rowmysql cliniccode when i print qryins i get query executes perfect mssql r query editor print qryins close mssql connection close mssql connection connmssqlclose close mysql connection close mysql connection connmysqlclose,1 this classical masterslave parallel pattern also known farm task farm there billion ways implement here way implement using mpi maybe inspirational implementing zeromq,i using zeromq solve problem involves several hundred potentially thousands clients request tasks carried each client would request specific task carried results completed whould returned back client issued request these actors i identified far pattern i come client actor requests unit work job carried controller actor loadbalances jobs accross available engines engine actor receives job request controller publishes result back client i still yet worked engine gets mesage back client i guessing one way implemented using zeromq would client push job messages one socket controller subscribe completed results published engine another socket controller pull job messages client one socket publish job messages engines another socket clearly forwarding device engine subscribe job messages one socket publish result another socket it would helpful someone provide skeletonsnippet show outline pattern may implemented using zeromq framework the code snippet c c php python c edit after reading task farms suggested akappa i think problem indeed modelled task farm i modified original actors accordingly changed title it would still useful someone familiar zeromq sketch skeleton would show i use core components build framework,2 an interesting uptodate post found whats best soap client library python documentation unfortunately perfect soap library looking seems exist yet,i currently looking implementing client use existing extensive soap management api i looked different soap implementations like pysimplesoap suds while first problems parsing wsdl much recursions suds worked fine slow i really like module however seem several issues suds like high memory consumption wsdl parsing speed missing support wsdl attributes eg choice attribute while lot people actively committing bug reports patches release suds since also wiki roadmap look bit neglected for looks like suds longer maintained so questions does make sense base larger project suds soap client is suds fork already implements patches available ticketing system what alternatives available lower memory footprint easy use handle complex large wsdl files update november more two years passed turns original suds project really dead there releases since due fact lot people started forking suds distributions like debian deploying patched versions original suds package fix issues i recommend jurko actively maintained fork i used successfully it supports python addresses lot suds known problems release notes bug tracker available bitbucket package also available pypi installed using pip,3 the issue c runtime functions windows python seem cache value tz environment variable first time either time ctime called the following display time local time utc import time os timetime osenviron tz utc print timectime wing debugger calls time running appengine code initial value tz captured the workaround set tzutc environment variables via project properties dialog,under debugger logginginfotz it osenviron tz timectime tz utc it mon oct under app engine launcher logginginfotz it osenviron tz timectime tz utc it mon oct so i setup wrong this affects timectime data dropped debug database i like debugger run timeframe app engine launcher timestamps database debugger slower launcher i want use time,3 match refinditeriaz subject match start matchstart match end exclusive matchend matched text matchgroup this help iterate elements list edit you write part larger string that changes original question match refinditerribazb subject match start matchstart match end exclusive matchend matched text matchgroup this find list extract words inside,i sample string like hst akst pst mst cst est ast wat cet gmt eet cct awst jst east nzt i interested first set items brackets hst akst pst mst cst est ast wat cet gmt eet cct awst jst east nzt i would like parse set put list i working python,1 i usually use single underscore eg myvar protected c methodsattributes used derived classes use double underscore eg var used anybody else doubleunderscore names class definition level mangled overridden derived class eg class aobject def resultself public method return selfcalc def resultself public method return selfcalc def calcself protected method overridden derived class return def calcself private overridden return class ba def calcself return b def calcself return b a print aresultaresult b b print bresultbresult here seems derived class b overriding calc calc calc overridden name already mangled class name hence output b instead b b ultimately choose convention document also case base class override private way class ba def calcself return b def acalcself return b,i object oriented code python classes meant extended provide missing custom bits code la template method pattern also variables used super class client code using are style conventions abstract dull implementation super class would either pass raise nonimplemented exception methods attributes i browsing pep mentions prepending underscore private members intended used subclasses,3 first think mistaken say prepending underscore private members intended used subclasses actually prepending methodattribute underscore python convention mean methodattribute accessed outside class subclass i think forgot read double underscore used make methodattribute possible override class fooobject def fooself print foo def mainself selffoo class barfoo def fooself print bar bar bar barmain this print foo bar there another way declaring stub method way using abcabcmeta abcabstractmethod,i object oriented code python classes meant extended provide missing custom bits code la template method pattern also variables used super class client code using are style conventions abstract dull implementation super class would either pass raise nonimplemented exception methods attributes i browsing pep mentions prepending underscore private members intended used subclasses,3 there really naming convention methods name overridden otherwise overridden i think method overridden something trivial documenting accordingly good enough class myclass def amethod will overridden myderivedclass pass name mangling mention question useful nontrivial method overridden still want able access base version see documentation info example,i object oriented code python classes meant extended provide missing custom bits code la template method pattern also variables used super class client code using are style conventions abstract dull implementation super class would either pass raise nonimplemented exception methods attributes i browsing pep mentions prepending underscore private members intended used subclasses,1 i problem reverted liquid gem version workaround seems like bug version pygments support jekyll use sudo gem uninstall liquid sudo gem install liquid version,i using jekyll convert markdown pygments syntax highlighting here error maruku displays liquid error undefined method join n songinfo n song songsn songinfoappendsongname nstring the markup follows highlight python songinfo song songs songinfoappendsongname endhighlight testing pygments ipython produces errors any ideas thanks advance,3 integer integer work,in javascript one could integer ampamp integer documentwritesomething is possible python,2 yes like integer pass,in javascript one could integer ampamp integer documentwritesomething is possible python,2 python indeed allows thing integer integer python also smart enough handle integer stuff,in javascript one could integer ampamp integer documentwritesomething is possible python,3 python replaces usual cstyle boolean operators ampamp words respectively so things like islarge ishappy issmall isblue makes things readable,in javascript one could integer ampamp integer documentwritesomething is possible python,3 driverfindelementbyid foo clear,i got tests i checking proper error message appears text certain fields invalid one check validity certain textarea element empty if textarea already text i tell selenium clear field something like drivergetelementbyid foo clearfield,3 yeah basic idea autoloaded tables cannot declared without valid engine need separate initialization code model code ensure models imported setup engine connected metadata the link describes better looks like already taken correct approach sqlalchemy declarative syntax autoload reflection pylons,i pretty new pyramid i figure use autoloadtrue option pyramid i used pyramidroutesalchemy create project using paster the problem initpy file uses initializesql function defines basemetadatabind engine in one model classes i would like use autoloadtrue option using declarative base i always get following error sqlalchemyexcunboundexecutionerror no engine bound table metadata pass engine table via autoloadwithsomeengine associate metadata engine via metadatabindsomeengine actually basemetadatabind engine defined inside initializesql function i realy know order file loaded i almost sure initpy loaded model thus metadata already binded engine thus question use autoload within classes without changing whole init model structure if anyone hint thanks advance,1 please install sip module firstthis python cc lib tools pyqt lib,i upgraded python python ubuntu maverick meerkat i unable import pyqt austingerald python python r sep gcc linux type help copyright credits license information import pyqt traceback recent call last file stdin line module importerror no module named pyqt i installed python python pyqt pythonqt ubuntu repositories i installed pyqt back i installed python recently if i try python since shipped ubuntu command simply python works perfectly watch austingerald python python r sep gcc linux type help copyright credits license information import pyqt i know problem pyqt modules accessible python my question i get python find pyqt modules help note sorry belongs super user i programming i encountered problem,1 silentghost scipy python available beta httpsourceforgenetprojectsscipyfilesscipyb,i embark signal processing work using numpyscipy however i never used python know start i see currently two branches python world version x x being neophile i instinctively tend go newer one seems lot talk incompatibilities two numpy seems compatible python i find documents scipy would recommend go python could point resources get started i know cc ruby matlab stuff basically want use numpy instead matlab,2 on side note github recommends using redcarpet to use configure jekyll adding markdown redcarpet configyml then install redcarpet sudo gem install redcarpet development machine compile jekyll site,i using jekyll convert markdown pygments syntax highlighting here error maruku displays liquid error undefined method join n songinfo n song songsn songinfoappendsongname nstring the markup follows highlight python songinfo song songs songinfoappendsongname endhighlight testing pygments ipython produces errors any ideas thanks advance,1 after studying like i found solution ldapsetoptionldapoptxtlsrequirecert ldapoptxtlsnever l ldapinitializeldapsldap lsetoptionldapoptreferrals lsetoptionldapoptprotocolversion lsetoptionldapoptxtlsldapoptxtlsdemand lsetoption ldapoptxtlsdemand true lsetoption ldapoptdebuglevel lsimplebindsadmintestercompassword,good day in advance apologize english national forums resources help there need script changes creates user password ad after studying issue became clear password assign change establish encrypted connection server send password necessary encoding utfle in general problem second first problem python ldapteststarttlspy traceback recent call last file ldapteststarttlspy line module lsimplebinds cnadminouusersdctestdcru password file usrlibpythondistpackagesldapldapobjectpy line simplebinds msgid selfsimplebindwhocredserverctrlsclientctrls file usrlibpythondistpackagesldapldapobjectpy line simplebind return selfldapcallselflsimplebindwhocredencodecontroltuplesserverctrlsencodecontroltuplesclientctrls file usrlibpythondistpackagesldapldapobjectpy line ldapcall result funcargskwargs ldapserverdown info a tls packet unexpected length received desc can contact ldap server script code import ldap host ldapsldap l ldapinitializehost lsetoption ldapoptxtlsdemand true lsetoption ldapoptdebuglevel username someuser newpass newpasswrd newpassword newpassencodeutfle lsimplebinds cnadminouusersdctestdcru password modattrs ldapmodreplace unicodepwd newpassword ldapmodreplace unicodepwd newpassword lmodifys cnsdcusersdctestdcru username modattrs lunbinds print successfully changed password chances someone already solved similar problem yes script running centos use pywin possible thanks advance,3 in program trying import eg apy aexe specify import statement mssql well you might also need import couple modules decimal amp uuid get exe working,i python application shoud launched windows executable i using pyexe pymssql i used next build script generate application distutilscore import setup import mysqldb import fnmatch import os import pymssql import shutil import pyexe import glob name bgagent oldversion ver distdir dist name ver shutilrmtreedistdir true shutilrmtree dist name oldversion true osmkdirdistdir class targetobject a simple class holds information executable file def initself kw default class constructor update need selfdictupdatekw mysqldb dst ospathjoindistdir mysqldb copytreemysqldbpath dst pymssql sitepackagesdir ospathdirnamepymssqlfile pymssqlfiles pymssqlpy pymssqlpyc pymssqlpyo mssqlpyd egginfo globglobospathjoinsitepackagesdir mssql pymssqlfilesappendospathbasenameegginfo fname pymssqlfiles src ospathjoinsitepackagesdir fname dst ospathjoindistdir fname ifospathisfilesrc shutilcopysrc dst else shutilcopytreesrc dst includes mysqldb pymssql openssl excludes runwexe gtkagg tkagg bsddb curses email pywindebugger pywindebuggerdbgcon pywindialogs tcl tkconstants tkinter packages mysqldb pymssql openssl dllexcludes libgdkwindll libgobjectdll tcldll tkdll datafiles serverpem configini runbat ospathjoinospathsplitpymssqlfile ntwdblibdll iconresources bitmapresources otherresources myapptarget target build script runpy iconresources iconresources bitmapresources bitmapresources otherresources otherresources destbase name version ver companyname copyright name name setup datafiles datafiles options pyexe compressed optimize includes includes excludes excludes packages packages dllexcludes dllexcludes bundlefiles distdir distdir xref false skiparchive false ascii false custombootscript zipfile r libraryzip console windows myapptarget service comserver ctypescomserver build works i error i tried launch application file pymssqlpyo line module file pymssqlpyo line load file mssqlpxd line init pymssql pymssqlc importerror no module named mssql mssqlpyd pymssqlpyd files executable directory os version windows enterprice sp,1 this work referencing current module import sys sysmodulesname,i would like able dynamically retrieve current executing module class name within imported module here code foopy def f print name barpy foo import f def b f this obviously work name name module contains function what i would like access inside foo module name current executing module using foo so case would bar module imported foo i would like foo dynamically access name module edit the inspect module looks quite promising exactly i looking what i hoping sort global environmentlevel variable i could access would contain name current executing module not i unwilling traverse stack find information i thought python may exposed data already edit here i trying use i two different django applications need log errors file lets say called appone apptwo i also place i would like log files homehareapplogs in application given point i would like able import logger module call log function writes log string file however i would like create directory applogs name current application appone apptwo application log files go respective logging directories in order i thought best way would logger module access sort global variable denotes current application name responsible knowing location parent logging directory creating application logging directory yet exist,3 all produce number th least significant bit set bits set range print bin b b b b in code selfvisitedcorners bit mask four least significant bits correspond four corners each iteration loop sets corresponding bit selfvisitedcorners provided condition holds,i following code python range selfstart selfcornersi selfvisitedcorners i working coordinates selfstart selfcorners coordinates so code top i want check whether start corner if start corner i shift but shift work i want code i want understand code,2 generally using struct format string start one alignment specifiers the default native one differs machine machine therefore correct result structunpack h pp the representation big endian binary decimal bytes f f f e hexadecimal bytes you easily verify adding two results,i read binary file get array characters when converting two bytes integer i ordp ordp it works fine positive integers i get negative number work i know something first bit significant byte success i also understand something called struct reading i ended following code import struct p chr p chr structunpack h pp print stra becomes i swap p p i get,1 just formatting if long conditions i like way formatting islarge ishappy issmall isblue pass it fits nicely python comb formatting,in javascript one could integer ampamp integer documentwritesomething is possible python,3 functools import partial def nestedfuncsfuncs return partialreduce lambda arg func funcarg funcs sortedlistofdicts keynestedfuncsitemgetter name strstrip strlower,i want sort list dictionaries dictionary key i want distinguish upper lower case characters dict name peter phone dict name paul phone dict name klaus phone dict name krishna phone dict name ali phone dict name hans phone listofdicts dictdictdictdictdictdict keyfield name listofdictssortkeyitemgetterkeyfield combine keyitemgetterkeyfield keystrlower listfield listofdicts print listfieldkeyfield provide ali hans klaus krishna paul peter klaus peter ali hans krishna paul,2 it cannot done you make wrapper function ostensibly would use keyword arguments tried right unfortunately discovered python standard library functions take named parameters thus possible given current implementation partial without making another function run interference according acceptance pep accepted inclusion partial type constructor binding leftmost positional arguments keywords furthermore states note object called though function positional arguments appended provided constructor keyword arguments override augment provided constructor positional arguments keyword arguments supplied creating object calling because additional positional arguments appended would way supply preceding positional argument implementation however goes partially applying arguments right inserting arguments arbitrary positions creates problems pending discovery good implementation nonconfusing semantics i think ruled so apparently could table stands implemented way for sake disclosure emphasis quotes,basically i like functools import partial partialstrstartswith prefix traceback recent call last file stdin line module typeerror startswith takes keyword arguments but generally question fill specific positional arguments partial ps i realize i use lambda instead,3 function annotations make they used documentation def kineticenergymass kilograms velocity meters per second they used precondition checking def validatefunc locals var test funcannotationsitems value localsvar msg var tvalue ttest name formatvar value test assert testvalue msg def isintx return isinstancex int def betweenlo hi def betweenx return lo x hi return def fx isint validatef locals printx f traceback recent call last assertionerror var value test isint also see httpwwwpythonorgdevpepspep way implement type checking,function annotations pep i ran across snippet code demonstrating python function annotations the concept simple i think implemented python good uses perhaps so enlighten how works def fooa x b c list max function body everything following colon argument annotation information following annotation function return value foofuncannotations would return dictionary x b c list return what significance available,3 the reason cloudant forbids temp views scale you need create design document defined views here link design document like views defined httpmaxichtutilsdocumenthtmlactiondesignaction i sure couchdbpy might want try different python library here link section creating views couchquery httpmikealgithubcomcouchquerycreatingviews,there may obvious answer i seem find anywhere best way query couchdb databases stored cloudant servers i try using temporary views la couchdbpy instructions db johndoe dicttype person name john doe db maryjane dicttype person name mary jane db gotham dicttype city name gotham city mapfun functiondoc doctype person emitdocname null row dbquerymapfun print rowkey john doe mary jane while works locally hosted databases cloudant returns error couchdbhttpservererror forbidden temp views disabled cloudant i read cloudant tutorial querying querying syntax proposed seems clumsy obvious work python is easy way around,1 if know two sets values must one simplify set newd set explanation if set newd set sides true expression returns true if set newd set sides false expression returns true if set one side return false true result expression false,i range values lrud two variables newd containing one i need check newd subset lr ud i know i l r newd u d u d newd l r indeed returns false values lr ud true otherwise still i find much reduntant some suggestions dry approach,2 use values method blogobjectsvalues id name beatles blog tagline all latest beatles news blogobjectsvalues id name id name beatles blog,how i convert django queryset list dicts i found answer i wondering i missing sort common helper function everyone uses,3 you exactly define dictionaries look like likely referring querysetvalues from official django documentation returns valuesqueryset — queryset subclass returns dictionaries used iterable rather modelinstance objects each dictionaries represents object keys corresponding attribute names model objects,how i convert django queryset list dicts i found answer i wondering i missing sort common helper function everyone uses,1 have checked oauth python article information it says this reference describes use oauth python applications service provider,i want set rest api oauth provider authenticationi use python library setting oauth provider coded python runs app engine thanks,1 use canvasx canvasy methods giving argument zero compute xy upper left corner visible canvas then use math convert canvas coordinate something relative window upper left corner visible region x selfcanvascanvasx selfcanvascanvasy given canvas coordinate cxcy convert window coordinates wx cxx wy cyy for example canvas scrolled way top left x zero any canvas coordinate give window coordinate ie canvas xy correspond window coordinate if scrolled pixels right canvas coordinate translate window coordinate since pixel upper left corner window this gives value relative upper left corner canvas if need relative upper left corner whole window use winfox winfoy get coordinate canvas relative window little math or use winforootx winforooty get coordinates widget relative screen,is way convert canvas coordinates window coordinates tkinter it would opposite converting window canvas coordinate wich done like x canvascanvasxeventx thanks advance,3 the first respondent mentioned defaultdict define missing subclass dict class dictdict def missingself key return key dicta b z z also i like second respondent approach dicta b dget z z z,i want create python dictionary returns key value keys missing dictionary usage example dic smartdict dic one printdic one printdic b b,3 you writing image text mode python mangling line endings open wb mode write verbatim,i trying grab images embedded email the problem image save unreadable figure the email saved file load beginning code mimeversion received http tue oct pdt inreplyto bfdeabfdbcbedcfxildcforexmanagecom references bfdeabfdbcbedcfxildcforexmanagecom date tue oct deliveredto sshpizgmailcom messageid caebasxvmciajfaweafyfceqgtzzfddpmwxlqabursamailgmailcom subject openme from simeon shpiz sshpizgmailcom to sshpizgmailcom contenttype multipartrelated boundarycbafba cbafba contenttype multipartalternative boundarycbdafba cbdafba contenttype textplain charsetiso cbdafba contenttype texthtml charsetiso contenttransferencoding quotedprintable div dirdltrdiv classdgmailquotediv langdenus linkdblu e vlinkdpurpledivp classdmsonormalspan styledfontsize ptcolorfdimg widthd heightd srcdcidimagepng ccdcdaacspanspan styledfontsizeptcolorfd uuuuspanp div divdivbrdiv cbdafba cbafba contenttype imagepng nameimagepng contenttransferencoding base contentid imagepngccdcdaac xattachmentid ecacccecd ivborwkggoaaaansuheugaaaaaaaancaiaaaawvsgoaaaaaxnsriarscqaaaalwsflzaaao yaaadsmbrahypwaaaitjrefukfnjppwnxgikzwbvqfobobsmsgqrqqrcgysaniphzeimjj ybxbiseplyubjlqlslrfbywbnitexnfhyadmjulzcqgognrfruvjrypxanetbevxxjr sulifjifdtzegiibtmrkzgbrkivjxbswkjjysoccjisnwyattwwhahiozoaaaaasuvorkc yii cbafba the python code using import email beautifulsoup import beautifulsoup message emailmessagefromfileopenr cshpiztestmsg cidlist images part messagewalk strpartgetcontenttype texthtml soup beautifulsouppartgetpayloaddecodetrue cid soup img src cidlistappendcid part messagewalk partget contentid cidlist imagesappendpartgetfilenamepartgetpayloaddecodetrue name image images openr cshpiztests name w f fwriteimage the image saved unfortunately good no program opens i looked original new image files notepad difference looks line break generated copy present original difference though deleting line notepad make image openable the difference i described seen would appreciate assistance finding problem,1 a tabified dockwidget set selected tab like dockwidgetraise edit here runnable example based code question pyqt import qtcore qtgui class windowqtguiqmainwindow def initself qtguiqmainwindowinitself selfsetwindowtitle dock widgets selfbutton qtguiqpushbutton raise next tab self selfbuttonclickedconnectselfhandlebutton selfsetcentralwidgetselfbutton selfdocklist approvedadded false dockname red green yellow blue split dock qtguiqdockwidgetdockname docksetwidgetqtguiqlistwidget docksetallowedareasqtcoreqttopdockwidgetarea docksetfeaturesqtguiqdockwidgetdockwidgetmovable qtguiqdockwidgetdockwidgetfloatable selfadddockwidgetqtcoreqttopdockwidgetarea dock insertindex lenselfdocklist dockname green insertindex approvedadded true elif dockname yellow approvedadded insertindex else insertindex selfdocklistinsertinsertindex dock lenselfdocklist index range lenselfdocklist selftabifydockwidgetselfdocklistindex selfdocklistindex selfdocklistraise selfnextindex def handlebuttonself selfdocklistselfnextindexraise selfnextindex selfnextindex lenselfdocklist selfnextindex name main import sys app qtguiqapplicationsysargv window window windowshow sysexitappexec,h can someone please tell set tabbified qdockwidget pop front active dock in picture full tab selected contents visible i want set mouth tab selected tab contents visible code selfdocklist approvedadded false add new dock widgets dockname previewdictkeys previewlist previewdict dockname setup dock dock qdockwidget dockname docksetwidget previewwidget previewlist docksetallowedareas qttopdockwidgetarea docksetfeatures qdockwidgetdockwidgetmovable qdockwidgetdockwidgetfloatable add ui selfadddockwidget qttopdockwidgetarea dock add list insertindex len selfdocklist dockname approved insertindex approvedadded true elif dockname tfpathsuser approvedadded insertindex else insertindex selfdocklistinsert insertindex dock tabify dock widgets len selfdocklist index range lenselfdocklist selftabifydockwidget selfdocklistindex selfdocklistindex set tab pos list active selfdocklist print selfdocklistwindowtitle selfdocklistraise,1 correct values specified byte order matters struct uses bigendian mostsignificant byte first littleendian leastsignificant byte first import struct structpack h xffxfe structpack h xfexff pchr xfe pchr xff structunpack h pp structunpack h pp,i read binary file get array characters when converting two bytes integer i ordp ordp it works fine positive integers i get negative number work i know something first bit significant byte success i also understand something called struct reading i ended following code import struct p chr p chr structunpack h pp print stra becomes i swap p p i get,1 a thoughts no need semicolons end line endings no need build generator compute upward rounded numbers chunks avoid using buildup long strings instead let slicing list comprehensions work filelist debuglog errorlog recloglog total openfilename r read filename filelist compressedtotal zlibcompress jointotal hextotal compressedtotalencode hex msglist hextotalii range lenhextotal,i using python trying make variable called total adding three files then compress total convert hex split list strings maximum length characters currently i list files concatenating total way filelist debuglog errorlog recloglog total files filelist f openfiles r total total fread fclose compressedtotal zlibcompresstotal hextotal compressedtotalencode hex upto i feel efficiently but try split hextotal list strings called msglist but maximum length string msglist characters long lenhextotal checker else checker nmsgs intmathceillenhextotal nn strnmsgs msglist msgs rangenmsgs msgs nmsgs checker msglistappendhextotalmsgs else msglistappendhextotalmsgsmsgs there simpler way isnt pythonic im quite new python thanks lot,1 a single class ideally represent clear cohesive set behaviour sometimes always clear best fit case i would code steps distinct class function something like def buildurlfoo build url foo return theurl def getresponseurl connection read response return theresponse def parseresponseresponse parse response return parsedresponse response getresponsebuildurlfooobject stuffyouwant parseresponseresponse you thing class instead functions steps require internal logic would better served class construct eg might make sense url response parsing logic classes class urlobject def initself foo selfurl selfbuildurlfromfoofoo def buildurlfromfooself foo url stuff return theurl def urlstringself return selfurl class responsewrapperobject def initself response selfresponse response def parseself parsing logic return parsedresponse response responsewrappergetresponseurlfoo responseparse,i trying write class encapsulates logic build specific url based another class properties hostport information config file make connection parses response class fooobject def initself b selfa selfb b selfconnectid none selfresponse none def somethingthatrequiresbarself call bar pass methods should connection class bunch staticmethodsclassmethods return data i looking class barobject def buildurlself foo get hostport config build url based foo properties return url def connectself url connects url built return barparseresponsetheresponse def parseresponseself response parses response should i build object holds data i need i extract data connection class barobject def initself foo selfurl def buildurlself build url based foo properties selfurl something foo def parseresponseself response parses response def connectself url connects url built selfrawresponse urlliburlopenselfurlread selfparsedresponse selfparseresponseselfrawresponse even hybrid class barobject def initself foo selffoo foo selfurl selfbuildurl def buildurlself build url based foo properties selfurl something foo def parseresponseself response parses response classmethod def connectcls foo connects url built bar barfoo selfbuildurl selfrawresponse urlliburlopenselfurlread selfparsedresponse selfparseresponseselfrawresponse return bar,1 i complete pythonvirtualenv novice however i exact problem found solution worked i believe vary greatly depending upon way originally setup python amp virtualenv in case lion upgrade completely wiped contents librarypythonsitepackages left broken executables link contents folder usrlocalbin i believe root cause cryptic no module import errors reviewing bashhistory i originally used easyinstall install pip pip install virtualenv virtualenvwrapper once i repeated steps i able reenter old virtual environments still contained packages i installed note however shipped python default if packages require python change default python version first stepbystep i removed old virtualenv configuration commands shell startup scripts eg bashprofile start new terminal session optional choose version python wish use eg defaults write comappleversionerpython version sudo easyinstall pip it seems though librarypythonsitepackages requires administrator privileges i recall case least bash history reflect sudo pip install virtualenv sudo pip install virtualenvwrapper finally i reenabled virtualenv configuration commands i disabled step a new terminal session everything back way look pip freeze l see local packages virtual environment i think,i touched python virtualenv i believe i setup mbp virtualenv pip totally forgotten stuff works after installing lion i getting error i open new terminal window traceback recent call last file string line module importerror no module named virtualenvwrapperhookloader virtualenvwrappersh there problem running initialization hooks if python could import module virtualenvwrapperhookloader check virtualenv installed virtualenvwrapperpythonusrbinpython path set properly any tips fix trying easyinstall eventlet i got traceback recent call last file usrlocalbineasyinstall line module pkgresources import loadentrypoint file systemlibraryframeworkspythonframeworkversionsextraslibpythonpkgresourcespy line module parserequirementsrequires environment file systemlibraryframeworkspythonframeworkversionsextraslibpythonpkgresourcespy line resolve raise distributionnotfoundreq xxx put info pkgresourcesdistributionnotfound setuptoolsc,3 after reading data add file need create new file name want data addeddata data added writefile openhomesagecontenttxt w writefilewritejsondumpsdata,i want add new record end file json for contains coef term xxx im reading file like try jsondataopen homesagecontenttxt datajsonload jsondata except ioerror print can open file add new record end file,1 specifically wsgid probably need tell load generic wsgi application you know docs loading generic wsgi application implementing apploader would difficult if need help send email mailing list pleasure help,this attempt discover canonical answer something seems hard google right i writing web app pyramid i luxury deciding server stack look like i heard good things mongrel would like try using serve app however i figure mongrel manual google searches connect mongrel wsgi app do i roll existing solutions problem,1 you able use slicenone represent as index slicenone index index,i trying relate pythonnumpy indices two arrays different sizes i cannot pass index one small array large array subroutine for example i two numpy arrays ashape ashape i finding indices relating indices ie index numpywherea n i grab data i interested using dat aindex dat aindexindexindex resulting dat shapes datshape n datshape n to speed program i want pass index subroutine i cannot pass indexindexindex subroutine i cannot pass colon i believe solution would pass numerical equivalent subroutine i found answer any help thank much,2 if using mysqldb mysqldbconstantsfieldtype module contains constants field type print dirmysqldbconstantsfieldtype bit blob char date datetime decimal double enum float geometry int interval long longlong longblob mediumblob newdate newdecimal null set short string time timestamp tiny tinyblob varchar varstring year builtins doc file name package for example typecode indicates mysql double mysqldbconstantsfieldtypedouble this module noted documentation,using mysql backend basically want determine field type tables typecode cursordescription tuples what i get bunch different numbers comparing tables typecode values i manually put together set correspondences i many types type objects documented python book beazley namely string binary number datetime rowid i presume therefore different typecodes given things like decimal unsigned int etc i surprised able find info net generally what i want way automate process whereby input gui grid connected mysql table example determines type data table expecting column parses checks find whether legal value,1 import binascii f hexstr binasciibahexs hexstr or import binascii hexstr binasciihexlifys hexstr,i string binary string characters i would like convert binary first hex the string qqg qasavcdnaj how i go converting string python output hex format similar bfaf,3 as said shorthand slicenone you also use npsindexindexindex convenience syntax constructing slice tuples,i trying relate pythonnumpy indices two arrays different sizes i cannot pass index one small array large array subroutine for example i two numpy arrays ashape ashape i finding indices relating indices ie index numpywherea n i grab data i interested using dat aindex dat aindexindexindex resulting dat shapes datshape n datshape n to speed program i want pass index subroutine i cannot pass indexindexindex subroutine i cannot pass colon i believe solution would pass numerical equivalent subroutine i found answer any help thank much,1 the following invalid syntax print item mylist item you could perhaps achieve want using list comprehension mylist foobarbaz print item item mylist item foo bar baz,i trying print nonempty strings list i seem get work i wrong print item mylist item,3 you could create generator grab items list empty nonempties item item mylist item then loop print join string print joinnonempties,i trying print nonempty strings list i seem get work i wrong print item mylist item,1 the basic type codes described book defined dbapi specification the typecode must compare equal one type objects defined the trick multiple different type codes compare equal type object mysqldbconstantsfieldtypetimestamp mysqldbconstantsfieldtypedatetime mysqldbconstantsfieldtypetimestampmysqldbdatetime true mysqldbconstantsfieldtypedatetimemysqldbdatetime true mysqldbdatetime dbapiset how magic implemented outlined note dbapitypeobject dbapi spec a conventional interface might done subclasses this allows mysqldb offer richer information column whether dateandtime type whilst still allowing simple test string vs number of course start comparing mysqldbconstantsfieldtype types directly relying mysqldb functionality port databases,using mysql backend basically want determine field type tables typecode cursordescription tuples what i get bunch different numbers comparing tables typecode values i manually put together set correspondences i many types type objects documented python book beazley namely string binary number datetime rowid i presume therefore different typecodes given things like decimal unsigned int etc i surprised able find info net generally what i want way automate process whereby input gui grid connected mysql table example determines type data table expecting column parses checks find whether legal value,2 as workaround import numpy np scipysparselinalg import splu def spsolvea b alu splua npemptyashape bshape j xrangebshape outj alusolvebj return selfk selfpdotspsolvest ct but yes bug spsolve accept matrices however s large well use dense inverse,i trying calculate expression form k pcts implementation kalman filter all involved matrices sparse i would course like avoid calculating actual inverse i tried using import scipysparselinalg spln selfk selfpdotsplnspsolvest ct the problem spsolve expects second argument vector matrix edit clarification problem could matlab solved k p c s i looking method similar spsolve accept matrix second argument this could course done splitting c number column vectors ccn solving problem reassembling matrix i suspect cumbersome inefficient editamp the dimensions matrices typically around p⁶x sx cx⁶ p diagonal s symmetric c one element per row it used implementation kalman filter using sparse matrices see httpenwikipediaorgwikikalmanfilterthekalmanfilter,1 if using python newer use statement dealing files import json open contenttxt r f data jsonloadf data coef term xxx open contenttxt w f jsondumpdata f,i want add new record end file json for contains coef term xxx im reading file like try jsondataopen homesagecontenttxt datajsonload jsondata except ioerror print can open file add new record end file,1 you use sharedprefences datastore it pretty much need you need full sqlite power,shelve ultrasimple nosql persistence layer allows trivially persist mapping objects it commonly used package python allows trivially add persistence application it simplistic nature means somewhat limited surprisingly useful you map arbitrary hashable key onto serializable object does something like exist android i writing simple app i noticed i spending lot time faffing around table structures select amp insert statements that sort thing i almost never python since i usually kind nosql alternative i expecting work exactly way clearly python java languages different characteristics i want something nearly simple use requires less manual sql faffing one thing fairly trivial app i prefer introduce bare minimum additional project dependencies preference given solutions require nothing android apis,1 you said preference java api answers i probably get preference couchbase mobile best android nosql i ever come across httpwwwcouchbaseorggetcouchbasemobileforandroidcurrent,shelve ultrasimple nosql persistence layer allows trivially persist mapping objects it commonly used package python allows trivially add persistence application it simplistic nature means somewhat limited surprisingly useful you map arbitrary hashable key onto serializable object does something like exist android i writing simple app i noticed i spending lot time faffing around table structures select amp insert statements that sort thing i almost never python since i usually kind nosql alternative i expecting work exactly way clearly python java languages different characteristics i want something nearly simple use requires less manual sql faffing one thing fairly trivial app i prefer introduce bare minimum additional project dependencies preference given solutions require nothing android apis,1 in select function choice input check input second input choice the thing applies elifinput statement again input replaced choice or alternatively use rawinput jf suggested furthermore input function automatically converts integers really check choice similarly finally need form actually runs select function like name main select,ive working tempeture converter troubling conbining two programs celsius fahrenheit fahrenheit celsius get display menu print cant manage figure select converter tempeture converter def convert print conversions menu print celsius fahrenheit print fahrenheit celsius def select convert choice input enter choice number input cf elif input fc def fc fahrenheit input enter degrees fahrenheit celsius fahrenheit print fahrenheit fahrenheit celsius celsius def cf celsius input enter degrees celsius fahrenheit celsius print celsius celsius fahrenheit fahrenheit correction tempeture converter def convert print conversions menu print celsius fahrenheit print fahrenheit celsius def select convert choice input enter choice number choice cf elif choice fc def fc fahrenheit input enter degrees fahrenheit celsius fahrenheit print fahrenheit fahrenheit celsius celsius def cf celsius input enter degrees celsius fahrenheit celsius print celsius celsius fahrenheit fahrenheit,1 you using rawinput instead input input try wrap whatever type eval convert python code enter converted integer still trying compare strings combine paul mentioned choice instead input working solution also drop semicolons parentheses conditionals necessary python def select convert choice rawinput enter choice number choice cf elif choice fc,ive working tempeture converter troubling conbining two programs celsius fahrenheit fahrenheit celsius get display menu print cant manage figure select converter tempeture converter def convert print conversions menu print celsius fahrenheit print fahrenheit celsius def select convert choice input enter choice number input cf elif input fc def fc fahrenheit input enter degrees fahrenheit celsius fahrenheit print fahrenheit fahrenheit celsius celsius def cf celsius input enter degrees celsius fahrenheit celsius print celsius celsius fahrenheit fahrenheit correction tempeture converter def convert print conversions menu print celsius fahrenheit print fahrenheit celsius def select convert choice input enter choice number choice cf elif choice fc def fc fahrenheit input enter degrees fahrenheit celsius fahrenheit print fahrenheit fahrenheit celsius celsius def cf celsius input enter degrees celsius fahrenheit celsius print celsius celsius fahrenheit fahrenheit,1 use functoolscmptokey guarantee sorting behavior compare function the source function found python sorting how to document,on one hand easy see given key function one easily implement sort thing using compare function the reduction follows def comparexy return keyx keyy on know sure losing potential sortings restricting every kinds sort map elements using key for instance suppose i want sort list length tuples xy i insist following compare method def comparetuptup tup tup return tup return tup tup return else return now tell i translate compare corresponding key function sorting algorithm proceed way this contrived example kinds customised sorting show symmetry breaking algorithms search important,3 is way program rerun use converter convert fc get menu the simplest way wrap select function loop name main true select and select function maybe add option exit elif choice exit,ive working tempeture converter troubling conbining two programs celsius fahrenheit fahrenheit celsius get display menu print cant manage figure select converter tempeture converter def convert print conversions menu print celsius fahrenheit print fahrenheit celsius def select convert choice input enter choice number input cf elif input fc def fc fahrenheit input enter degrees fahrenheit celsius fahrenheit print fahrenheit fahrenheit celsius celsius def cf celsius input enter degrees celsius fahrenheit celsius print celsius celsius fahrenheit fahrenheit correction tempeture converter def convert print conversions menu print celsius fahrenheit print fahrenheit celsius def select convert choice input enter choice number choice cf elif choice fc def fc fahrenheit input enter degrees fahrenheit celsius fahrenheit print fahrenheit fahrenheit celsius celsius def cf celsius input enter degrees celsius fahrenheit celsius print celsius celsius fahrenheit fahrenheit,1 if code clear working application exits job scheduled executed see examples provided httpsbitbucketorgagronholmapschedulersrctipexamples,code codingutf apschedulerscheduler import scheduler import logging loggingbasicconfigfilename tmplog levelloggingdebug format levelnamesasctimes messages sched scheduler schedstart schedintervalscheduleseconds def jobfunction loggingdebug hello world schedaddintervaljobjobfunction seconds switch decorator still work log like debug looking jobs run debug no jobs waiting job added info added job jobfunction trigger interval next run job store default info shutting thread pool job jobfunction added nerver triggered,2 the filter builtin well suited exactly pass none instead function filternone abc def none ghi false jkl abc def ghi jkl details httpdocspythonorglibraryfunctionshtml,i trying print nonempty strings list i seem get work i wrong print item mylist item,1 you use collectionnamecreateindex api python httpapimongodborgpythonapipymongocollectionhtml if using javascript problem eval needs write lock creating index needs write lock i think use eval anything needs write lock due reason,i want add index mongo collection outside interactive mongo shell we building python i could set mongoengine however i greatly prefer set indexes directly can i use dbeval make happen,1 add username apikey parameters get variables make sure curl httplocalhostapivbooksusernameissackellyampapikeyadfljafal make sure follow instructions teh docs setting apikeyauthentication as alternative requiring sensitive data like password apikeyauthentication allows collect username amp machinegenerated api key tastypie ships special model purpose need ensure tastypie installedapps tastypie includes signal function use autocreate apikey objects hooking looks like djangocontribauthmodels import user djangodb import models tastypiemodels import createapikey modelssignalspostsaveconnectcreateapikey senderuser,i making internal api tastypie i tastypieauthentication import apikeyauthentication class myresourcemodelresource meta authentication apikeyauthentication with auth rules disabled api works great with i get unauthorized response matter i try i sure one things really obvious see action meantime please advise make request get,3 yes possible margin may raised window preferences general editors text editors print margin column and option break multilines may changed window preferences pydev editor code style imports allow multiline imports,pydev organize import wrap line char width like xyz import a b c d e f is way disable wrap extend width i tried increasing line width eclipse settings seem work i think specific java editors pydev,2 xyz import a b c d e f or xyz import a b c xyz import d e f if line wide shown wide read easily see why python pep specify maximum line length characters,pydev organize import wrap line char width like xyz import a b c d e f is way disable wrap extend width i tried increasing line width eclipse settings seem work i think specific java editors pydev,1 i think issue checking see players moves match one win conditions exactly this possible probably happen often example player might make moves count win winners get match also ever took player four moves would never get winner reason since found winners either what actually want find win conditions moves win condition made player this expressed like winner winners true move winner move selfgamemoves black false game ending logic break this shortened considerably following might harder follow anyallm selfgamemoves black w w winners game ending logic,i python version connect four coded except win function gravity below code determining game yet it function currently way game ends spots taken any ideas winners def makemoveself selfplayer selfgameplayer selfgameplayer black selfbconfigimageselfblack commandselfinvalidmove num selfnum selfgamemoves black appendnum selfgamefreeremovenum w selfwonselfgameplayer selfgamemoves black winners selfgameturninfoconfigtextselfgameplayer won elif selfgamefree selfgameturninfoconfigtext game draw else selfgameplayer red selfgameturninfoconfigtextselfgameplayer turn elif selfgameplayer red selfbconfigimageselfred commandselfinvalidmove num selfnum selfgamemoves red appendnum selfgamefreeremovenum w selfwonselfgameplayer containsselfgamemoves red winners selfgameturninfoconfigtextplayer won c selfgamecells cfreeze elif selfgamefree selfgameturninfoconfigtext game draw c selfgamecells cfreeze else selfgameplayer black selfgameturninfoconfigtextselfgameplayer turn,1 i successfully built macruby gui app xcode lion today following macruby tutorial apple site macruby also includes template xcode i python programmer really hoped use point i given pyobjc i use tk python quick little apps maybe switch macruby likely switch objectivec ruby pretty nice language though maybe macruby interest,xcode templates building cocoa subclasses python i recently upgraded xcode i cannot find i use languages besides c family c c objc xcode does anyone know,1 when i first saw question i read input command command input input function i assuming gathering data command line the problem taking input newlines stop accepting input the following example gets around waiting user hit ctrld this triggers exception rawinput function breaks loop text keep looping forever true try grab data user add back newline rawinput strips text rawinput n except eoferror encounter eof ctrld causes break loop break print text gathered dashed line print nn text obviously want warn user use ctrld stop entering text might bit awkward — already command prompt bad also i used rawinput gathers input exec input if looking execute results could replace print call exectext similar results,i trying write program accept user input pasted block text including multiple newlinescarriagereturns i trouble finding info python handle normal behavior input command complete soon first n encountered,2 csv import dictreader dictwriter openinputcsv r inputfile reader dictreaderfinputfile openoutputcsv w outputfile writer dictwriterfoutputfile fieldnamesreaderfieldnames row reader writerwriterowrow,for example csv columns id id date job no code i need write columns back order the dict jumbles order immediately i believe problem reader,3 you instantiate class test test test instance class test instead test test test class test testsay typeerror unbound method say must called test instance first argum ent got nothing instead curious try test test testsaytest testsaytest it works i gave class instance self unbound method absolutely recommended code way,for reason instances classes returning type errors saying insufficient arguments passed problem self this works fine class exampleclass def initself somemessage selfmessage somemessage print new exampleclass instance created message print selfmessage ex exampleclassmessage however almost every class i define call instance returns error the almost identical function class testobject def initself selfdefaultmsg message def sayself printselfdefaultmsg test test testsay returns type error saying needs argument i getting problem class pretty much every class i define i idea problem i updated python getting error i fairly new programming,2 you add parentheses instantiate class test test,for reason instances classes returning type errors saying insufficient arguments passed problem self this works fine class exampleclass def initself somemessage selfmessage somemessage print new exampleclass instance created message print selfmessage ex exampleclassmessage however almost every class i define call instance returns error the almost identical function class testobject def initself selfdefaultmsg message def sayself printselfdefaultmsg test test testsay returns type error saying needs argument i getting problem class pretty much every class i define i idea problem i updated python getting error i fairly new programming,1 you make use similar technique used infamous microsoft office quick start java quick start iirc even adobe fastsomething the trick try keep libraries program disk cache time you get simple crontab command programmed run hour the exact details depend system work something like crontab e python c pass although effective write simple python script imports modules program using ends,i prototyped command line application quick notetaking using python argparse right basically launches vim shoves buffer sqlite database the problem loading python slow machines ghz intel core duos basic functionality printing help menu startup take second i know code fine python perfectly fast interactive mode snappy python loads i mimic annoyance simple hello word time python c print hello world hello world real ms user ms sys ms of course problem unique python time erl noshell eval iofwritehello worldn initstop hello world real ms user ms sys ms my question how i speed initial execution python application i want program feel like git wc system i encounter problem python os x python os x note subsequent executions python erl much faster i already dogfooding program i want truly snappy update i tried running pypy find similar initial load time python systems seconds initial load half performance subsequent calls compared python os x pypy similar performance subsequent calls compared python os x pypy python update output dr jimbob suggestion seems trim initial load time python vsec print hello world installing zipimport hook import zipimport builtin installed zipimport hook import encodings directory systemlibraryframeworkspythonframeworkversionslibpythonencodings systemlibraryframeworkspythonframeworkversionslibpythonencodingsinitpyc matches systemlibraryframeworkspythonframeworkversionslibpythonencodingsinitpy import encodings precompiled systemlibraryframeworkspythonframeworkversionslibpythonencodingsinitpyc systemlibraryframeworkspythonframeworkversionslibpythoncodecspyc matches systemlibraryframeworkspythonframeworkversionslibpythoncodecspy import codecs precompiled systemlibraryframeworkspythonframeworkversionslibpythoncodecspyc import codecs builtin systemlibraryframeworkspythonframeworkversionslibpythonencodingsaliasespyc matches systemlibraryframeworkspythonframeworkversionslibpythonencodingsaliasespy import encodingsaliases precompiled systemlibraryframeworkspythonframeworkversionslibpythonencodingsaliasespyc systemlibraryframeworkspythonframeworkversionslibpythonencodingsutfpyc matches systemlibraryframeworkspythonframeworkversionslibpythonencodingsutfpy import encodingsutf precompiled systemlibraryframeworkspythonframeworkversionslibpythonencodingsutfpyc python r jun gcc apple inc build darwin hello world clear builtin clear syspath clear sysargv clear sysps clear sysps clear sysexitfunc clear sysexctype clear sysexcvalue clear sysexctraceback clear syslasttype clear syslastvalue clear syslasttraceback clear syspathhooks clear syspathimportercache clear sysmetapath clear sysflags clear sysfloatinfo restore sysstdin restore sysstdout restore sysstderr cleanup main cleanup zipimport cleanup codecs cleanup signal cleanup encodings cleanup encodingsutf cleanup encodingsaliases cleanup exceptions cleanup warnings cleanup codecs cleanup sys cleanup builtin cleanup ints unfreed ints cleanup floats real ms user ms sys ms,1 your test refers class rather instance class to create actual test instance instantiate add parentheses for example class fooobject pass foo class mainfoo foo mainfoo object xaeb the error message trying tell self object pass implicitly function argument case testsay would unbound method,for reason instances classes returning type errors saying insufficient arguments passed problem self this works fine class exampleclass def initself somemessage selfmessage somemessage print new exampleclass instance created message print selfmessage ex exampleclassmessage however almost every class i define call instance returns error the almost identical function class testobject def initself selfdefaultmsg message def sayself printselfdefaultmsg test test testsay returns type error saying needs argument i getting problem class pretty much every class i define i idea problem i updated python getting error i fairly new programming,1 python lists implemented internally arrays like java arraylist c stdvector etc removing element middle relatively slow subsequent elements reindexed see httpwwwlaurentlucecompostspythonlistimplementation since order elements seem relevant i recommend use randomrandint lenl choose index use li calculationli update th element,i need sample uniformly random number set fixed size calculation put new number back set the number samples needed large i tried store numbers list use randomchoice pick element remove append new element but way slow i thinking store numbers numpy array sample list indices index perform calculation are faster way process,3 relative first question use maximize figure manager figure manager figuremanagerwx instance equivalent methods case backends matplotlib import pyplot plt pltplot matplotliblineslined object xede mng pltgetcurrentfigmanager pltshow get normal size mngframemaximizetrue mpl window maximizes for second question i sure test problem solved setting position figure screen extended two monitors use setposition wxagg backend mngframesetpositionargs kwargs,i two questions regarding positioning mpl window using wxagg backend how create maximized window instead clicking window maximize time i two screens interestingly mpl windows tend open small screen how i force mplipythonwxxwindows open mpl windows nd bigger monitor thanks,3 from context sounds like trying run app devappserver the devappserver yet support python runtime development testing appspot,i import webob python runtime webob imports io io imports io blocked sdk is way whitelist io it obviously supposed blacklisted,1 you looking related fields httpdjangotastypiereadthedocsorgenlatestfieldshtmlrelationshipfields,i planning site django tastypie rest api i tough time figuring right way include child resources returned resource as sandbox i made small app ticket model ticketcomment model comments belong ticket i looked tastypie cookbook recipe nested resources httpdjangotastypiereadthedocsorgenlatestcookbookhtmlnestedresources i hard time understanding i the code uses djangoformsmodelsmodeltodict get comments ticket i thinking must gotcha somewhere is reason i i also cleanerfeeling pattern listed cookbook models follows ticketsmodelspy djangodb import models class ticketmodelsmodel title modelscharfieldmaxlength createts modelsdatetimefieldautonowaddtrue submitteremail modelsemailfield prioritychoices h high m medium l low priority modelscharfieldmaxlength choicesprioritychoices description modelstextfield statuschoices new new amp unclaimed wip work in progress res resolved cls closed status modelscharfieldmaxlength choicesstatuschoices def unicodeself return ticketds selfid selftitle class ticketcommentmodelsmodel ticket modelsforeignkeyticket commentts modelsdatetimefieldautonowaddtrue commenteremail modelsemailfield comment modelstextfield def unicodeself return ticketcommentdd selfticketid selfid resources follows ticketsapipy tastypie import fields tastypieresources import modelresource ticketsmodels import ticket ticketcomment djangoformsmodels import modeltodict class ticketresourcemodelresource class meta queryset ticketobjectsall resourcename ticket def dehydrateself bundle comments ticketcommentobjectsfilterticketbundledata id bundledata comments modeltodictc c comments return bundle class ticketcommentresourcemodelresource ticket fieldsforeignkeyticketresource ticket class meta queryset ticketcommentobjectsall resourcename comment output follows comments comment this first comment commenteremail meexamplecom id ticket comment this second comment commenteremail meexamplecom id ticket createts t description this first ticket id priority m resourceuri apivticket status new submitteremail meexamplecom title first ticket,3 this webkit rendered markup webkit happens rendering markup give others see duplicate option the problem actually changing value months choicesinsert every execution render method change,i using date selection widget registration form django for reason submit page validation errors first option element select duplicated this happens every refresh submitted page times first element repeated times even stranger widget consists selects day month year happens month select any input would greatly appreciated edit link page httpgfcbetasitecozaaccountsregister code import time import datetime import djangoformswidgets import widget select djangoutils import datetimesafe djangoutilsdates import monthsap months djangoutilssafestring import marksafe djangoutilsformats import getformat djangoconf import settings selectdatewidget redate recompiler ddddd class selectdatewidgetwidget a widget splits date input three select boxes this also serves example widget one html element hence implements valuefromdatadict nonevalue monthfield smonth dayfield sday yearfield syear def initself attrsnone yearsnone requiredtrue years optional listtuple years use year select box selfattrs attrs selfrequired required years selfyears years else thisyear datetimedatetodayyear selfyears listrange thisyear selfyearsreverse selfyears rangethisyear thisyear def renderself name value attrsnone try yearval monthval dayval valueyear valuemonth valueday except attributeerror yearval monthval dayval none isinstancevalue basestring settingsuseln try inputformat getformat dateinputformats python compatibility v datetimedatetimestrptimevalue inputformat would clearer datetimestrptime added python v datetimedatetimetimestrptimevalue inputformat yearval monthval dayval vyear vmonth vday except valueerror pass else match redatematchvalue match yearval monthval dayval intv v matchgroups choices selfyears yearhtml selfcreateselectname selfyearfield value yearval choices year dobyear choices monthsitems monthhtml selfcreateselectname selfmonthfield value monthval choices month dobmonth choices range dayhtml selfcreateselectname selfdayfield value dayval choices day dobday format getformat dateformat escaped false output char format escaped escaped false elif char escaped true elif char yy outputappendyearhtml elif char bfmmnn outputappendmonthhtml elif char dj outputappenddayhtml return marksafeu n joinoutput def idforlabelself id return smonth id idforlabel classmethodidforlabel def valuefromdatadictself data files name datagetselfyearfield name datagetselfmonthfield name datagetselfdayfield name return none settingsuseln inputformat getformat dateinputformats try datevalue datetimedateinty intm intd except valueerror pass else datevalue datetimesafenewdatedatevalue return datevaluestrftimeinputformat else return sss return datagetname none def createselectself name field value val choices nonevalue classname none id selfattrs id selfattrs id else id ids name selfrequired val choicesinsert nonevalue localattrs selfbuildattrsidfield id selectchoiceschoices selecthtml div class classname srenderfield name val localattrs div return selecthtml,1 have tried jsondumpslistdicts it comes box i sure simplejson would buy fact i think thing,i list dicts item list listdictsappenditemasdict how convert listdicts json string using simplejson making list dictionary object json,1 you need ensure reply nonetype illustrated sr returns none get timeout waiting response you also add timeout sr default timeout quite absurd purposes usrbinpython scapyall import timeout confverb ip range packet ipdst strip ttlicmp reply srpacket timeouttimeout reply none print replydst online else print timeout waiting packetipdst,i attempting write python script uses scapy module ping internal ip range determine ip online i got far usrbinpython scapyall import confverb ip range packet ipdst strip ttlicmp reply srpacket replysrc print replysrc online and program sit nothing i kill ctrlc i get error message traceback recent call last file sweeppy line module replysrc attributeerror nonetype object attribute src however i try single ip address instead range works like usrbinpython scapyall import confverb packet ipdst ttlicmp reply srpacket replysrc print replysrc online anyone know i fix problem or ideas i ping ip range scapy determine hosts online,3 itertoolsimap creates lazy list contains function evaluated md argument foo string the md calls evaluated point prepared along arguments i think called thunks when pass iterator function goes elements evaluating this happens faster explicit python evaluation first program implemented c everything happens c library code without returning interpreter iterator element,one pycon talks shared function trick explanation loop c could someone explain what trick behind use cases import itertools hashlib time md hashlibmd def run itertoolsrepeat foo mdupdatei timetime run timetime md hashlibmd def run anyitertoolsimapmdupdate itertoolsrepeat foo timetime run timetime,2 how using strsplit userinputlist inputenter name agesplit this creates list spaceseparated word input george split george then access part userinputlist george userinputlist is,let say i line inputenter name age how i make variable store section input lets say george george either standard variable list all i want able store user input separate elements list variable input words separated space would become separate elements variable is clear enough i using python,1 the former pythonic better ideomatic code execute block a false none,can i use a instead a none the latter seems verbose is difference,1 a prove false a false none lead undesired results,can i use a instead a none the latter seems verbose is difference,3 most guides i seen suggest use a unless reason specific there slight differences there values none return false example empty lists think really testing,can i use a instead a none the latter seems verbose is difference,3 neither python django memory use memcache directly redis preferred method something else,i plan use session store user preference data is cas like api session like one appengine the use case concurrent ajax calls might update object thus race conditions i using django,1 the term google titlecase the first hit titlecase package pip install titlecase python titlecase import titlecase titlecase spam eggs the spam eggs,i looking library properly capitalizes given string assuming title i know stringtitle capitalizes every work one capitalized anyone know libraries examples words capitalized titles propositions etc articles van de,3 given need append data later yaml might format looking it designed explicitly support appended data elements ala log file json deliberately proper subset language useful meta markup designed powerful crosslanguage serialization custom classes,i writing script python spit data organized list dicts name firstthing color blue flavour watermelon name secondthing color red name thirdthing color blue size huge i trying decide way store data file my considerations i like easy read write i load data back script manipulate i like nonpythonspecific format maybe later i want use data php something knows i like format easy append data if file list little dict items i want load memory add one item end my first try use pickle meets easy criteria pythondependent unpickle append repickle other formats i thought seem feasible objections json appending going annoying maybe shelve python specific csv like duct tape classy would probably work some kind light database like sqlite maybe getting fancy anybody arguments another format,1 the statement a call anonzero see special method names documentation use return value function here summary objectnonzeroself called implement truth value testing builtin operation bool return false true integer equivalents when method defined len called defined object considered true result nonzero if class defines neither len nonzero instances considered true on hand a none compares reference a none see whether,can i use a instead a none the latter seems verbose is difference,3 a lot functions return none appropriate results for example sqlalchemy query first method returns none rows result suppose selecting value might return need know whether actually whether query results a common idiom give function method optional argument default value none test value none see specified for example def spameggsnone eggs none eggs retrievefromconfigfile compare def spameggsnone eggs eggs retrievefromconfigfile in latter happens call spam spam the function would incorrectly detect passed value eggs would compute default value that probably want or imagine method like return list transactions given account if account exist might return none this different returning empty list would mean account exists recorded transactions finally back database stuff there big difference null empty string an empty string typically says value value nothing null says value entered in cases want use a none you checking specific value none value happens cast false,can i use a instead a none the latter seems verbose is difference,3 for cases i think json best bet use simplejson convert list dict json simple import simplejson json mylist name firstthing color blue flavour watermelon name secondthing color red name thirdthing color blue size huge output jsondumpsmylist ident the result json color blue flavour watermelon name firstthing color red name secondthing color blue name thirdthing size huge now json perfectly valid json string it json array so i think need hack remove since passing python list simplejson get json list back,i writing script python spit data organized list dicts name firstthing color blue flavour watermelon name secondthing color red name thirdthing color blue size huge i trying decide way store data file my considerations i like easy read write i load data back script manipulate i like nonpythonspecific format maybe later i want use data php something knows i like format easy append data if file list little dict items i want load memory add one item end my first try use pickle meets easy criteria pythondependent unpickle append repickle other formats i thought seem feasible objections json appending going annoying maybe shelve python specific csv like duct tape classy would probably work some kind light database like sqlite maybe getting fancy anybody arguments another format,1 it depends context i use a i expecting a sort collection i want execute block collection empty this allows caller pass wellbehaved collection empty i expect it also allows none false suppress execution block occasionally convenient calling code otoh i expect a completely arbitrary object could defaulted none i always use a none calling code could deliberately passed reference empty collection empty string valued numeric type boolean false class instance happens false boolean context and hand i expect a morespecific thing eg instance class i going call methods could defaulted none i consider default boolean conversion property class i mind enforcing subclasses i use a save fingers terrible burden typing extra characters,can i use a instead a none the latter seems verbose is difference,2 as written pep comparisons singletons like none always done never equality operators also beware writing x really mean x none eg testing whether variable argument defaults none set value the value might type container could false boolean context,can i use a instead a none the latter seems verbose is difference,3 python includes sqlite module inmemory option sqlite also manages concurrency assuring atomic commits,i plan use session store user preference data is cas like api session like one appengine the use case concurrent ajax calls might update object thus race conditions i using django,1 because posix allows treating path beginning two slashes implementationdefined manner in words foo necessarily mean thing foo posix systems from ieee std a pathname begins two successive slashes may interpreted implementationdefined manner although two leading slashes shall treated single slash see also bug report closed invalid,under unix ospathnormpath collapses multiple slashes single ones except exactly two slashes appear start path why exception to illustrate i get following transformations doubleslashstays doubleslashstays doubleslashgone doubleslashgone doubleslashgone doubleslashgone tripleslashgone tripleslashgone quadslashgone quadslashgone this seems strange i vaguely imagine useful smb mounts urls i think i care is hidden wisdom python behaviour i collapse leading update in view answer looks like best thing collapse either accept treat error,3 pickle work fine store dicts directly list making appending easier pickle import dump load f open storbin w dumpdicta f dumpdictb f dumpdictc f fclose in subsequent sessions append another dump directly end file f open storebin dumpdictd f fclose to read perform load repeatedly hit end file f open storbin r loadf loadf b loadf c loadf loadf traceback recent call last eoferror,i writing script python spit data organized list dicts name firstthing color blue flavour watermelon name secondthing color red name thirdthing color blue size huge i trying decide way store data file my considerations i like easy read write i load data back script manipulate i like nonpythonspecific format maybe later i want use data php something knows i like format easy append data if file list little dict items i want load memory add one item end my first try use pickle meets easy criteria pythondependent unpickle append repickle other formats i thought seem feasible objections json appending going annoying maybe shelve python specific csv like duct tape classy would probably work some kind light database like sqlite maybe getting fancy anybody arguments another format,1 i need sample uniformly random number set fixed size calculation put new number back set listsomeset store set list randrangelens choose random element x si yourcalculationx calculation si put new number back set,i need sample uniformly random number set fixed size calculation put new number back set the number samples needed large i tried store numbers list use randomchoice pick element remove append new element but way slow i thinking store numbers numpy array sample list indices index perform calculation are faster way process,2 libusb pyusb may worth taking look also,i work msp series mcu i designed gui using wxpython now i want control microcontroller gui i find modules python send data usb port microcontroller identify does exist module send receive data tofrom usb port thanks advance,1 i problem zopeinterface friends zopecomponent et al specifically problem pyexe searches discovers packages and zope packages installed zope namespace package result relies funky import logic pth files see zopeinterfacepynspkgpth order add subpackages python path have look sitepackages see i mean pyexe problems discovering kind package in end i manually repackage various zope packages i using stardard module setup sitepackages reran pyexe discovered everything problem it pita pyexe able handle packaging edge cases andor zope packages packaged pyexe friendly fashion best,i python app based twisted pygtk twisted depends zopeinterface i import directly unfortunately i try run app following error ends error log traceback recent call last file taskspy line module file uiinitpyc line module file twistedpythonlogpyc line module importerror no module named zopeinterface traceback recent call last file taskspy line module file uiinitpyc line module file twistedpythonlogpyc line module importerror no module named zopeinterface traceback recent call last file taskspy line module file uiinitpyc line module file twistedpythonlogpyc line module importerror no module named zopeinterface i tried adding every combination zopeinterface zope includes packages gives build time error running pyexe searching required modules cpythonlibsitepackagespyexebuildexepy deprecationwarning sets module deprecated import sets traceback recent call last file setuppy line module gtkui file cpythonlibdistutilscorepy line setup distruncommands file cpythonlibdistutilsdistpy line runcommands selfruncommandcmd file cpythonlibdistutilsdistpy line runcommand cmdobjrun file cpythonlibsitepackagespyexebuildexepy line run selfrun file cpythonlibsitepackagespyexebuildexepy line run selffindneededmodulesmf requiredfiles requiredmodules file cpythonlibsitepackagespyexebuildexepy line findneededmodules mfimporthookf file cpythonlibsitepackagespyexemfpy line importhook return baseimporthookselfnamecallerfromlistlevel file cpythonlibsitepackagespyexemfpy line importhook q tail selffindheadpackageparent name file cpythonlibsitepackagespyexemfpy line findheadpackage raise importerror no module named qname importerror no module named zope my setuppy distutilscore import setup import pyexe def finddatafilessourcetargetpatterns i elided i doubt relevant problem includes cairo pango pangocairo atk gobject gio packages encodings setup name myapp description my application version windows script ospathjoin ui taskspy iconresources ospathjoin ui data iconpackico options pyexe packages joinpackages includes joinincludes datafiles finddatafiles ui ui data gtkui how i get pyexe build,2 if installed python need install version setuptools newer fork distribute python instance each python instance must version the applesupplied system pythons come versions setuptools already installed,i mac os x lion i two python versions machine unfortunately i different purposes classes i trying install oauth module receiving following error simplegeopythonoauthfcca xanderflood python setuppy install traceback recent call last file setuppy line module setuptools import setup findpackages importerror no module named setuptools all research indicates problem occurs oauth currently compatible python however i checked doublechecked python starts terminal python starts terminal i installed many packages python way any ideas wrong fix,1 allbuttonspressed recently posted handy guide run devappserver python threadsafe set yes,gae looks excellent longwaited features however working yet i downloaded installed gae using degenerate aaa app test here roughly appyaml various changes made testing appyaml application aaa mystical creation version alpha runtime python apiversion threadsafe true handlers url media staticdir media url faviconico staticfiles mediaimagesfaviconico upload mediaimagesfaviconico url admin script aaaapp login admin url script aaaapp skipfiles appyaml libraries name django version name jinja version latest name yaml version latest i running mac os x lion i hypothesize i actually using python runtime spite declaration appyaml use i quite sure validate theory errors i encountered consistent these errors reproduced python path when google app engine python path set app engine runs using python to fix i set python path usrbinpython google app engine preferences wsgi i get following error applicationsgoogleappenginelauncherappcontentsresources googleappenginedefaultbundlecontentsresourcesgoogleappengine googleappenginetoolsdevappserverpy getparentpackageselfgoogleappenginetoolsdevappserverhardenedmoduleshook object fullname aaaapp selffindmodulefullname none raise importerror could find module fullname return selfmoduledictparentmodulefullname builtin importerror type exceptionsimporterror fullname aaaapp type exceptionsimporterror could find module aaaapp args could find module aaaapp message could find module aaaapp where i tried aaaapp aaapy googleappenginedist import uselibrary uselibrary django otherwise still get django djangocorehandlers import wsgi app wsgiwsgihandler aaa initpy content aaaaaapy content note i continue run cgi appyaml aaapy modified mutatis mutandis however nevertheless results errors jinja when i run import jinja i get importerror django without googleappenginedist import uselibrary uselibrary django i end django theory given following httpcodegooglecomappenginedocspythontoolslibrarieshtml states the uselibrary function provided googleappenginedist package unavailable python uselibrary works uselibrary required libraries django version declaration set django version only django included python runtime per librarieshtml link i manually specify python python path order gae use python wsgi load application properly jinja cannot imported i believe i really using python gae runtime ie appyaml declaration ignored gae sdk i hope helpful description i grateful thoughts may happening – potential solutions,1 repeated letters reduced single letters actually according rule need keys list created values also i would suggest use dict sets values also single ones hell hello it make usage dictionary much simpler import itertools values good god hell hello value values dsetdefault joink kv itgroupbyvalue setaddvalue god set god good hel set hell helo set hello,i following lists keys god hel helo values good god hell hello i want create dictionary like god set god good hel hell helo hello key determined reducing repeated letters value single letter how would i programmatically,2 managepy file excists project environment created starting project it purpose control project commands djangoadminpy script start project put anyhwhere shortcut via bash profile,i learning something djangoin tutorials read used djangoadminpy execute commands like syncdb startapp startproject others tutorials used managepy so exist important diference use djangoadminpy managepy,1 see djangoadminpy managepy django documentation managepy wrapper around djangoadminpy automatically created django project puts project package syspath sets djangosettingsmodule environment variable points project settingspy file so i think comfortable use managepy working django project,i learning something djangoin tutorials read used djangoadminpy execute commands like syncdb startapp startproject others tutorials used managepy so exist important diference use djangoadminpy managepy,3 python removes print keyword replaces function name so yes syntax python,i trying build dart windows xp according docs using python encounters error script file ddocuments settingsxxxmes documentsgoogledartdartpython toolsbui ldpy archia file toolsbuildpy line print unknown mode mode syntaxerror invalid syntax any hint solve can problem version python recent,2 use f open usersoutputtestdtxt w the string formatter operator works preceding string put directly behind i would recommend reformat whole block like open usersoutputtestdtxt w f line r try fwrite sn line except unicodeencodeerror pass then need fclose,i calling function need loop range calling function value range the max value returned different function findpagecount one i problem for makerequest i run values hardcoded works fine when i add loop pass integer two lines function i error listed bottom i think small formatting difference i success tracking far the goal pass value loop request xml string next page shown f open statement new file created page i appreciate help offered def makerequesti code call api removed xmlstring listfilteritemsfilteritem attribute pagenumber value filteritemssortitemssortitem attribute activityaudmemid sortorder sortitemslist f open usersoutputtestdtxt w line r try fwrite sn line except unicodeencodeerror pass fclose maxpage findpagecount range maxpage makerequesti i get following error f open line typeerror unsupported operand types file int,3 wild guess without testing f open usersoutputtestdtxt w,i calling function need loop range calling function value range the max value returned different function findpagecount one i problem for makerequest i run values hardcoded works fine when i add loop pass integer two lines function i error listed bottom i think small formatting difference i success tracking far the goal pass value loop request xml string next page shown f open statement new file created page i appreciate help offered def makerequesti code call api removed xmlstring listfilteritemsfilteritem attribute pagenumber value filteritemssortitemssortitem attribute activityaudmemid sortorder sortitemslist f open usersoutputtestdtxt w line r try fwrite sn line except unicodeencodeerror pass fclose maxpage findpagecount range maxpage makerequesti i get following error f open line typeerror unsupported operand types file int,2 di arr al asplit di elem al elem delem else delem print di note elemts stored alphabetical order dictionary,i strictly sorted list strings b bc bd e f fg fh fhi fhij this list similar tree representation so i need convert dict b c e f g h j as see keys dict parents values children upd i agree empty dict better none,3 what kind hz sound there many types waves hz sine saw square etc you could flute playing a might count assuming want sine wave looks like generate sound object pygamesndarraysamples i tested you create samples samples mathsin mathpi frequency samplerate xrange durationinsamples this hopefully basic sine wave stuff frequency desired frequency hz samplerate number samples second generated audio hz typical value durationinsamples length audio seconds audio hz sample rate it looks like might convert samples numpyarray passing pygamesndarraysamples the docs indicate audio match format returned pygamemixergetinit adjust samples appropriately basic idea mixergetinit tell samplerate variable whether need account stereo need adjust amplitude wave shift make samples integral number waves long loop,how i create hz sound plays smoothly forever using audio pygame i assume easy enough i want use stupid files accomplish task the final intent play note key held i asked another question any help would greatly appreciated i wasted great quantities time trying find answer,2 you try following import xmletreecelementtree etree pprint import pprint tree etreeparse findtitlexml value treegetiteratortag title print valuetext value treegetiteratortag page pprintvalueattrib it output something like python filepy title categories id newlength orglength outlinks stub urls,i using following statements print value title tag its working fine but i also want print page id is possible thanks mediawiki siteinfo sitenamewikisitename namespaces namespace key casefirstlettermedianamespace namespaces siteinfo page id orglength newlength stub categories outlinks urls titletitletitle categoriescategories linkslinks urls urls text books text page mediawiki here working code which print title tag values import xmletreecelementtree etree tree etreeparse findtitlexml value treegetiteratortag title print valuetext,1 if insist none leaf value use compact code mydict lambda defaultdictmydict mydict x mylist reducedefaultdictgetitem xsplit admittedly obvious code succinct,i strictly sorted list strings b bc bd e f fg fh fhi fhij this list similar tree representation so i need convert dict b c e f g h j as see keys dict parents values children upd i agree empty dict better none,3 did read readme file download source tarball httpprdownloadssourceforgenetlibdnetlibdnettargzdownload extract see readme windows xp for raw ethernet sending install winpcap driver dlls extract developer pack build directory httpwinpcappolitoitinstalldefaulthtm xxx unsupported for tunnel interface support install openvpn tapwin virtual ethernet adapter component windows installer let install alone httpopenvpnsourceforgenet for firewall support install hsc pktfilter service httpwwwhscfrressourcesoutilspktfilterindexhtmlen most windows developers use libdnet developer pack mingw msvc libraries instead building but really want know to build mingw native library cygwinmingw configure ampamp make to build microsoft visual c native library python module cygwinmingw configure cd python ampamp cpythonpythonexe setuppy build cd src ampamp lib outdnetlib obj as likely noticed need cygwinmingw i know whether want mingw native lib microsoft visual c native lib also note use cpythonpythonexe build if try come concrete problem i guess likely necessarly better put new question might better ask mailing list libdnet compilation problems,i trying use scapy win python i manage compile dependencies expect one help goal reaching executable dnetwinpyexe i promise update question scapy manual running scapy windows python v enthought python distribution update i managed compile mingw i using vs i make fixes libdnet actually work look like last time compiled windows vs i try updating scapy manual upload executables,2 support python added numpy version begin must downloadinstall newer version numpy,i similar question question still step behind i one version python installed windows sorry bit system i installed numpy following link suggested question the installation went fine i want import import numpy import errorno module named numpy i know probably super basic question i still learning thanks,3 you installed numpy version python use python you install numpy python x eg one httpsourceforgenetprojectsnumpyfilesnumpynumpywinsuperpackpythonexedownload for overview different versions see httpsourceforgenetprojectsnumpyfilesnumpy,i similar question question still step behind i one version python installed windows sorry bit system i installed numpy following link suggested question the installation went fine i want import import numpy import errorno module named numpy i know probably super basic question i still learning thanks,2 the reason else dx syntax error python assignment statement but conditional operator expects expressions every expression statement every statement expression,i new python i trying write x dx q dx compact way using ternary operator q dx x else dx gives syntax error what i missing,2 the conditional operator python used expressions assignments statements you use q dsetdefaultx get desired effect case see also documentation dictsetdefualt,i new python i trying write x dx q dx compact way using ternary operator q dx x else dx gives syntax error what i missing,3 in python assignments cannot occur expressions therefore write code like b c you looking setdefault q dsetdefaultx alternative use defaultdict,i new python i trying write x dx q dx compact way using ternary operator q dx x else dx gives syntax error what i missing,2 that setdefault q dsetdefaultx it exactly want return dx x key assign dx x yet key return,i new python i trying write x dx q dx compact way using ternary operator q dx x else dx gives syntax error what i missing,1 there complex example httpwikiwxpythonorgcxfreeze the lacking documentation options httpcxfreezesourceforgenetcxfreezehtml with cxfreeze i still get build output files single folder though unlike pyexe alternatives httpwwwblogpythonlibraryorgcategorypackaging,i using python cxfreeze windows system i created setuppy build executable everything works fine when cxfreeze runs moves everything build directory i files i would like included build directory how i here structure src setuppy janitorpy readmetxt chnagelogtxt helpers uncompress unrarexe unzipexe here snippet setup name janitor version description janitor author john doe authoremail johndoegmailcom url httpwwwthispageintentionallyleftblankorg datafiles helpersuncompress helpersuncompressunzipexe helpersuncompress helpersuncompressunrarexe readmetxt executables executable janitorpy initscript i seem get work do i need manifestin file,3 this works don know from dennis baker comment you not need model fields need first model fields you need fields unique names far i know use tablenamefield fieldname make sure unique fields i done fairly complex queries tables way always tie back single model – another solution use cursor however cursor changed list tuples list dictionaries i sure cleaner ways using iterators function works it takes string raw sql query returns list rendered used template djangodb import connection transaction def sqlselectsql cursor connectioncursor cursorexecutesql results cursorfetchall list row results dict field true try dictcursordescriptionfield strresultsifield field field except indexerror e break listappenddict return list,i need perform raw sql multiple tables i render result set for one table i would sql select mytable results mytableobjectsrawsql for multiple tables i sql select mytable myothertable results bigmodelobjectsrawsql but i really need create tablemodelclass bigmodel contains fields i may need i never actually store data table added i table myusers i table mylistings these defined modelspy the table mylistings foreign key myusers indicating created listing the sql select username listingtext mylistings myusers myusersid mylistingsmyuserid i want sql generate result set i use render page django the question do i create model contains fields username listingtext or better way still uses raw sql select of course actual queries complicated example the models i define modelspy become actual tables database hence use modeltable term not sure else refer sorry i use raw sql i found python table references work simple data models,1 modpython used try using multiple python interpreters process modwsgi might while frequently works okay extension modules support scipystats probably importing extension module we similar reports scipy mailing list concerning scipystats modpython check modwsgi documentation see configure use multiple interpreters process find different deployment strategy uses one interpreter per process app,i process creating djangopowered interface package relies heavily scipystatsstats scipy version called ovl during early development phases using djangos developmentserver problem after deployment using apache debian modwsgi causes serious problem whatever view i trying load browser starts loading keeps good minutes timeout page appears just importing scipy works make scipystatsstats even scipystats available this surprise documentation scipy init py stated subpackage stats needs imported explicitly however said subpackage cluster imports django web djangoshell without problem indeed shows dirscipy ipythonsession show like i kinda expected on command dirscipy returns different results coming web list strings including subpackage cluster normal ipython shell strings subpackage cluster surprise surprise django shell in django shell scipy attributes including cluster stats packages another thing i keep importing ovl package keeping scipystats imports bit distance one files app sometimes i get viewdoesnotexist error stating method index views module clearly one which reminds so i thinking rather ugly solutions editing scipy init import stats package appears normally dirscipy accessible scipystats i use old code snatching scipy stat subpackage making regular package perhaps using symlink i reluctant applying solutions however the fact cluster shows scipy django environment worries bit i thought maybe something wwwdata user logging web i know check did anyone else encounter parts or otherwise helpful thoughts oh another django deployment work,3 in general good idea take lot care get right since writes serialized might also adversely affect scalability i recommend writing separate files merging leaving separate files,i pipeline point splits work various subprocesses thing parallel thus output go file is risky say processes write file or python try retry sees resource occupied,3 this system dependent in windows resource locked get exception in linux write file two processes written data could mixed ideally cases use semaphores synchronize access shared resources if using semaphores heavy needs alternative write separate files edit as pointed eye later post resource manager another alternative handle concurrent writers,i pipeline point splits work various subprocesses thing parallel thus output go file is risky say processes write file or python try retry sees resource occupied,3 keep mind ubuntu using directory called libxlinuxgnu x architectures if using architecture need create symbolic link sudo ln libxlinuxgnulibzso liblibzso also thing others shared libraries,i seem install zlib properly i installed python source ubuntu edit bobince luper helped make sure install packages recompile python sudo aptitude install zlibgdev libreadlinedev libdbdev libncursesdev after installation i attempted install setuptoolspy sh setuptoolscpyegg traceback recent call last file string line module zipimportzipimporterror decompress data zlib available i installed zlib sudo aptitude install zlibc reading package lists done building dependency tree reading state information done reading extended state information initializing package states done the following new packages installed zlibc packages upgraded newly installed remove upgraded need get kb archives after unpacking kb used writing extended state information done get httparchiveubuntucomubuntu luciduniverse zlibc k kb fetched kb kbs selecting previously deselected package zlibc reading database files directories currently installed unpacking zlibc zlibckamddeb processing triggers mandb setting zlibc k reading package lists done building dependency tree reading state information done reading extended state information initializing package states done before recompiling python setuptools still install sh setuptoolscpyegg traceback recent call last file string line module zipimportzipimporterror decompress data zlib available i baffled i checked permissions lrwxrwxrwx root oct usrbinpython usrbinpython lrwxrwxrwx root oct usrbinpython usrlocalbinpython lrwxrwxrwx root oct usrbinpython python rwxrxrx root apr usrbinpython i noticed i added extra step i refactored llrwxrwxrwx root oct usrbinpython usrlocalbinpython lrwxrwxrwx root oct usrbinpython python rwxrxrx root apr usrbinpython so python default version still fails sh setuptoolscpyegg prefixusrlocalbinpython traceback recent call last file string line module zipimportzipimporterror decompress data zlib available where zlib located work properly find name zlib devnull homeusernamesourcespythonmoduleszlib homeusernamesourcespythondemozlib usernameservername thu oct sources find name zlibc devnull usrsharelintianoverrideszlibc usrsharedoczlibc,3 since fileconfig disables existing loggers default call loggingconfigfileconfigloggingcfg foo import foo call loggingconfigfileconfigloggingcfgdisableexistingloggers,i discovered different behavior python logging depending i use logging fileconfig logging programmatic config to demonstrate i created two minimal examples in first example i configuring logging programmatically this example works expected debug log message printed console foopy import logging logger logginggetloggername class fooobject def initself loggerdebug debug log foo loggingtestpy import loggingconfig foo import foo name main consolelogger loggingstreamhandler formatter loggingformatter asctimes names levelnames messages consolelogger loggingstreamhandler consoleloggersetlevelloggingdebug consoleloggersetformatterformatter rootlogger logginggetlogger rootloggeraddhandlerconsolelogger rootloggersetlevelloggingnotset prints debug log message console foo foo in second example i configuring logging fileconfig as far i see logconfigfile exact behavior but still debug log message not printed example foopy import logging logger logginggetloggername class fooobject def initself loggerdebug debug log foo loggingtestpy import loggingconfig foo import foo name main loggingconfigfileconfig loggingcfg not print debug log message console why foo foo loggingcfg loggers keys root loggerroot level notset handlers consolehandler formatters keys complex formattercomplex format asctimes names levelnames modules linenod messages handlers keys consolehandler handlerconsolehandler classstreamhandler leveldebug formattercomplex argssysstdout so second example using logging fileconfig not printing debug log message console,3 a better solution implement resource manager writer avoid opening file twice this manager could use threading synchronization mechanisms threadinglock avoid simultaneous access platforms,i pipeline point splits work various subprocesses thing parallel thus output go file is risky say processes write file or python try retry sees resource occupied,2 i looking solution short copying admin media files project changing admin static directory i think really alternative you copy media files new directory start server pass adminmedia command line argument like python managepy runserver adminmediamyadminmedia in case run production server admin media served good static serving server point new path reference docs httpsdocsdjangoprojectcomenrefdjangoadmindjangoadminoptionadminmedia,overriding admin templates easy creating folder admin templates directory copying whatever template files like override i simply want play admin style sheets however i made folder admin static files folder put cssbasecss unlike templates solution seem work so way override individual css files djangocontribadmin way override templates if nay would best solution overriding css files i looking solution short copying admin media files project changing admin static directory,1 i used solution get working kept duplicating path syspath write see happens i made little modification import sys flaskfirst sitesflaskfirst flaskfirst syspath syspathinsert flaskfirst app import app application app that way included,i issue deploying flask app apache using wsgi i posted error logs config files i tried moving things around renaming etc give internal server error not sure i getting import error any input suggestions appreciated thanks here apache errorlog sun sep error client modwsgi pid target wsgi script sitesflaskfirstwsgipy cannot loaded python module sun sep error client modwsgi pid exception occurred processing wsgi script sitesflaskfirstwsgipy sun sep error client traceback recent call last sun sep error client file sitesflaskfirstwsgipy line module sun sep error client app import app application sun sep error client importerror no module named app wsgipy this wsgipy app import app application apppy this apppy flask import flask rendertemplate import settings app flaskname appdebug settingsdebug viewshomepage import viewsevents import viewssubmit import viewsfeed import name main apprun here basics directory tree give idea flaskfirst static templates views initpy apppy wsgipy here apache virtualhost file virtualhost serveradmin sreustlegmailcom servername crathorg documentroot sitesflaskfirst wsgi settings wsgiscriptalias sitesflaskfirstwsgipy wsgidaemonprocess flaskfirst usersreustle groupgeneral processes threads wsgiprocessgroup flaskfirst static directories alias static sitesflaskfirststatic location static sethandler none location virtualhost,2 here via spherical coordinates mpltoolkitsmplotd import axesd import matplotlibpyplot plt import numpy np fig pltfigurefigsizepltfigaspect square figure ax figaddsubplot projection coefs coefficients ac x ac ac z radii corresponding coefficients rx ry rz npsqrtcoefs set spherical angles u nplinspace nppi v nplinspace nppi cartesian coordinates correspond spherical angles equation ellipsoid x rx npouternpcosu npsinv ry npouternpsinu npsinv z rz npouternponeslikeu npcosv plot axplotsurfacex z rstride cstride color b adjustment axes span maxradius maxrx ry rz axis xyz getattrax setlim formataxismaxradius maxradius pltshow the resulting plot similar the program actually produces nicer looking square graphics this solution strongly inspired example matplotlib gallery,does anyone sample code plotting ellipsoids there one sphere matplotlib site nothing ellipsoids i trying plot x z c c constant like defines ellipsoid i tried meshgridxy route reworked equation z one side sqrt problem the matplotlib sphere example works angles uv i sure work ellipsoid,3 you could give sympy computer algebra system written python give try eg sympy import symbol x symbol x x x ysubsx ysubsx,i wondering exists python module would allow something like x magicnumber xvalue x print xvalue print so magicnumber would implement special operator methods would return instances magicnumber keeping track operations performed is class edit clarification i want use module remember lot parameters arbitrary calculation user wishes perform so user set parameters use produce result then decides like alter parameter change reflected result immediately so simplified usage session one parameter instance would look like p myparams pdistance i use getattr setattr pspeed getattr returns magicnumber instances time pdistance pspeed edit clarification okay i i done start i provide context you engineer produce latex document detailing workings properties prototype gadget it task repeatedly different prototypes you write small latex python interface for prototype create python module generates requisite document in type latex code calculating variables needed calculations context after notice two problems the number variables parameters makes locals mess variable names hard remember you group categories keep track you sometimes need redo calculation spread last couple chapters dozen lines one parameters changed you find way avoid code duplication out problem comes original question,3 isn called function this may sound like simple answer i mean sincerely def yx return x aren thinking wrong direction one to address clarification class myparams distance speed def callself return selfdistance selfspeed p myparams pdistance these properties pspeed get returns magicnumber instances time p pspeed time p i guess i favor type solution although i see benefit sympy module preference i guess,i wondering exists python module would allow something like x magicnumber xvalue x print xvalue print so magicnumber would implement special operator methods would return instances magicnumber keeping track operations performed is class edit clarification i want use module remember lot parameters arbitrary calculation user wishes perform so user set parameters use produce result then decides like alter parameter change reflected result immediately so simplified usage session one parameter instance would look like p myparams pdistance i use getattr setattr pspeed getattr returns magicnumber instances time pdistance pspeed edit clarification okay i i done start i provide context you engineer produce latex document detailing workings properties prototype gadget it task repeatedly different prototypes you write small latex python interface for prototype create python module generates requisite document in type latex code calculating variables needed calculations context after notice two problems the number variables parameters makes locals mess variable names hard remember you group categories keep track you sometimes need redo calculation spread last couple chapters dozen lines one parameters changed you find way avoid code duplication out problem comes original question,3 magic lambda x eval x magic magic magic lambda x eval x magic magic,i wondering exists python module would allow something like x magicnumber xvalue x print xvalue print so magicnumber would implement special operator methods would return instances magicnumber keeping track operations performed is class edit clarification i want use module remember lot parameters arbitrary calculation user wishes perform so user set parameters use produce result then decides like alter parameter change reflected result immediately so simplified usage session one parameter instance would look like p myparams pdistance i use getattr setattr pspeed getattr returns magicnumber instances time pdistance pspeed edit clarification okay i i done start i provide context you engineer produce latex document detailing workings properties prototype gadget it task repeatedly different prototypes you write small latex python interface for prototype create python module generates requisite document in type latex code calculating variables needed calculations context after notice two problems the number variables parameters makes locals mess variable names hard remember you group categories keep track you sometimes need redo calculation spread last couple chapters dozen lines one parameters changed you find way avoid code duplication out problem comes original question,1 if add py pathext environment variable need batch script just add cpythonlib path set,pydoc work windows post httpstackoverflowcomquestionspydocisnotworkingwindowsxp last answer dave webb says create pydocbat file code python cpythonlibpydocpy after i create pydocbat placed pydoc command works command prompt ps adding cpythonlibpydocpy windows path system environment variables work even logging back work,1 the numpy reference documentation page indexing contains answers requires bit careful reading the answer indexing booleans equivalent indexing integer arrays obtained first transforming boolean arrays npnonzero therefore boolean arrays amnonzero mnonzero succeeds ie mnonzeroshape mnonzeroshape equivalent ai rangeashape mi mi i sure designed work like usually want to get intuitive result instead anpixm produces result equivalent aij j rangeashape mj rangeashape mi,why work anprandomrand xrangenparange yrangenparange atmpaxrange batmpnpindyrange anprandomrand xrangenparange yrangenparange baxrangenpindyrange,3 i think difficulty keep operators priority rather implementing class i suggest look different notation like reverse polish notation may help getting rid priority issues,i wondering exists python module would allow something like x magicnumber xvalue x print xvalue print so magicnumber would implement special operator methods would return instances magicnumber keeping track operations performed is class edit clarification i want use module remember lot parameters arbitrary calculation user wishes perform so user set parameters use produce result then decides like alter parameter change reflected result immediately so simplified usage session one parameter instance would look like p myparams pdistance i use getattr setattr pspeed getattr returns magicnumber instances time pdistance pspeed edit clarification okay i i done start i provide context you engineer produce latex document detailing workings properties prototype gadget it task repeatedly different prototypes you write small latex python interface for prototype create python module generates requisite document in type latex code calculating variables needed calculations context after notice two problems the number variables parameters makes locals mess variable names hard remember you group categories keep track you sometimes need redo calculation spread last couple chapters dozen lines one parameters changed you find way avoid code duplication out problem comes original question,1 an alternative npix convert boolean arrays integer arrays using npnonzero use npnewaxis create arrays right shape take advantage broadcasting import numpy np anprandomrand xrangenparange yrangenparange atmpaxrange bcorrectatmpnpindyrange mxrangenonzero mnpindyrangenonzero bamnpnewaxis assert npallclosebbcorrect banpixxrangenpindyrange assert npallclosebbcorrect npix tends slower double indexing the longform solution appears bit faster longform in timeit axrangenonzeronpnewaxis npindyrangenonzero loops best us per loop double indexing in timeit axrangenpindyrange loops best us per loop using npix in timeit anpixxrangenpindyrange loops best us per loop note it would good idea test timings machine since rankings might change depending version python numpy hardware,why work anprandomrand xrangenparange yrangenparange atmpaxrange batmpnpindyrange anprandomrand xrangenparange yrangenparange baxrangenpindyrange,2 you use httpsourceforgenetprojectsmysqlpython this exactly answer connection though,i trying create swig package python offers mysql connectivity but i try import package python i get following error mod imploadmodule imysqlconnection fp pathname description pdb importerror imysqlconnectionso undefined symbol mysqlinit i creating package using following commands probably i making blunder swig c python imysqlconnectionwrapcc imysqlconnectioni gcc fpic c imysqlconnectionwrapcc imysqlconnectionwrapo i usrincludepython mysqlconfig cflags mysqlconfig libs g gcc fpic c imysqlconnectioncc imysqlconnectiono i usrincludepython mysqlconfig cflags mysqlconfig libs g shared imysqlconnectionwrapo imysqlconnectiono imysqlconnectionso i able mysql connectivity i use class imysqlconnectioncc c main any help guidance much appreciated,1 you able return deferred listenforevent later handleevent fire returned deferred returned deferreds actually generate response,i twistedthrift server uses ttwisted protocol i want keep connections clients open given event happens i notified event twisted reactor via callback class servicehandlerobject interfaceimplementsserviceiface def listenforeventself a method defined thrift interface block thrift response event interest occurs i need somehow return immediately free reactor thread i want thrift call considered completed the current request needs marked waiting somehow def handleeventself a method called event interest occurs it callback method registered twisted reactor find waiting requests notify event occurred this cause thrift requests complete how i quickly return method handler object maintaining illusion blocking thrift call i initialize thrift handler twisted startup trigger def onstartup handler servicehandler processor serviceprocessorhandler server ttwistedthriftserverfactoryprocessorprocessor iprotfactorytbinaryprotocoltbinaryprotocolfactory reactorlistentcp server my client php connects socket new tsocket localhost transport new tframedtransportsocket protocol new tbinaryprotocoltransport client new serviceclientprotocol transportopen clientlistenforevent that last call clientlistenforevent successfully makes server runs servicehandlerlistenforevent even server method returns twistedinternetdeferdeferred instance client immediately receives empty array i get exception exception ttransportexception message tsocket timed reading bytes localhost local port,1 i guess need get key pressed user you achieve without pressing enter method like import termios os sys def getkey fd sysstdinfileno old termiostcgetattrfd new termiostcgetattrfd new new amp termiosicanon amp termiosecho newtermiosvmin newtermiosvtime termiostcsetattrfd termiostcsanow new c none try c osreadfd finally termiostcsetattrfd termiostcsaflush old return c then key tab key example something need implement display possibilities user if key print stdout oh course need getkey looped long user hits enter you also get method like rawinput get whole word sign sign display possibilities hit tab at least item start if achieve problems write edit the getword method look like def getword true getkey n break elif print possibilities else return word getword print word the issue i occuring right way display sign entered without enteres spaces print print,i like code autocompletion linux terminal the code work follows it list strings eg hello hi goodbye great in terminal user start typing match possibility gets hint possible strings choose similarly vim editor google incremental search eg starts typing h gets hint hello ow and better yet would would complete words beginning arbitrary part string thank advise,2 how different processes write output queue single process reads queue writes file,i pipeline point splits work various subprocesses thing parallel thus output go file is risky say processes write file or python try retry sees resource occupied,1 problem solved following key restaurantkeystr resultdatakey restaurant,i trying get model object datastore using key passed query string it worked however recently i named file restaurantprofilehtml restaurantprofilehtml i know part went wrong caused problem my restaurant key contains key however gae log i set custom debug see contains restaurant key passed handler result gae log restaurant key bound method restaurantkey persistencemodelrestaurant object xcdcacd can anyone tell got wrong the restaurant key seem passed handler hrefrestaurantprofilerestaurantkey key handler class class restaurantprofilehandlerwebapprequesthandler def getself restaurantkey selfrequestgetgetu restaurantkey loggingdebug restaurant key restaurantkey error invalid literal int base following def getrestaurantdetailsrestaurantkey restaurantkey restaurant dbkeyfrompath restaurant intrestaurantkey return dbgetrestaurant code retrieve key restaurant foundrestaurants resultdatarestaurantkey restaurant problem solved following key restaurantkeystr resultdatakey restaurant,1 i aware exactly asking if happy autocompletionsuggestions appearing tab used many shells quickly get running using readline module here quick example based doug hellmann pymotw writeup readline import readline class mycompleterobject custom completer def initself options selfoptions sortedoptions def completeself text state state first trigger build possible matches text cache matches entries start entered text selfmatches selfoptions sstartswithtext else text entered matches possible selfmatches selfoptions return match indexed state try return selfmatchesstate except indexerror return none completer mycompleterhello hi goodbye great readlinesetcompletercompletercomplete readlineparseandbind tab complete input rawinputinput print you entered input this results following behaviour tab representing tab key pressed input tabtab goodbye great hello hi input htabtab hello hi input hotabow in last line h o tab entered one possible match whole sentence auto completed check linked articles information readline and better yet would would complete words beginning completion arbitrary part string this achieved simply modifying match criteria completer function ie selfmatches selfoptions sstartswithtext something like selfmatches selfoptions text this give following behaviour input tabtab goodbye great hello hi input otabtab goodbye hello updates using history buffer mentioned comments a simple way create pseudomenu scrollingsearching load keywords history buffer you able scroll entries using updown arrow keys well use ctrl r perform reversesearch to try make following changes keywords hello hi goodbye great completer mycompleterkeywords readlinesetcompletercompletercomplete readlineparseandbind tab complete kw keywords readlineaddhistorykw input rawinputinput print you entered input when run script try typing ctrl r followed that return first match contains enter ctrl r next match to select entry press enter also try using updown keys scroll keywords,i like code autocompletion linux terminal the code work follows it list strings eg hello hi goodbye great in terminal user start typing match possibility gets hint possible strings choose similarly vim editor google incremental search eg starts typing h gets hint hello ow and better yet would would complete words beginning arbitrary part string thank advise,3 i think appname indicates source optional component syslog header the latest version sysloghandler python includes support appname called ident per c syslog api available earlier versions see python issue if prepend script name messages get desired effect for example loggererror foo what display eg foo what log,when i run mac import logginghandlers logger logginggetloggername loggersetlevelloggingdebug syslogaddress varrunsyslog loggeraddhandlerlogginghandlerssysloghandlersyslogaddress loggererrorwhat crap it shows like syslog oct nick unknown error what crap why unknown shouldn smart enough name script name,3 you could pass name attribute def mysortseq keyname sort getattrseqn keyname mysortpeople wealth getter functor def mysortseq keyfunc sort keyfuncseqn mysortpeople operatorattrgetter wealth i prefer latter approach generic for example easily allows computed keys,so i working sorting algorithm python its exact contents irrelevant question it uses list called people containing class instances function hardcoded sort list specific attribute wealth def mysortseq sorts seqnwealth mysortpeople now i like generalize function i could sort attribute def mysortseq key sorts seqnkey mysortpeople wealth but course throws error know consider wealth class attribute so possible,3 the generic attribute getter function getattr work gettattrobj name,so i working sorting algorithm python its exact contents irrelevant question it uses list called people containing class instances function hardcoded sort list specific attribute wealth def mysortseq sorts seqnwealth mysortpeople now i like generalize function i could sort attribute def mysortseq key sorts seqnkey mysortpeople wealth but course throws error know consider wealth class attribute so possible,1 what i achieve override basesitehtml template like block blockbots link relstylesheet typetextcss hrefmediacssmyadmincss blocksuper endblock i put css blockbots instead extrahead sure loaded end override others css,overriding admin templates easy creating folder admin templates directory copying whatever template files like override i simply want play admin style sheets however i made folder admin static files folder put cssbasecss unlike templates solution seem work so way override individual css files djangocontribadmin way override templates if nay would best solution overriding css files i looking solution short copying admin media files project changing admin static directory,3 i know sqlalchemy i would implement interface sessionquery method return query object methods like filter orderby etc each methods simply returns new query object taking account applied changes this allows method chaining first example your code example numerous problems one example obj someobject p proxyobj pa b pb print aperform prints b,i find interesting way sqlalchemy constructing query strings eg sessionquerymodeluser filtermodeluserage orderbymodeluserage as far i see applied kind proxy pattern in small project i need make similar string construction using oop approach so i tried reconstitute behavior firstly kind object one plenty similar objects class someobjectobject items none def initself selfitems def callself return joinselfitems selfitems none else def aself selfitemsappend return self def bself selfitemsappend b return self all methods object return self i call order unlimited number times secondly proxy object call subject methods perform method calls object see resulting string import operator class proxyobject def initself someobject selfsomeobject someobject def getattrself name selfmethod operatormethodcallername return self def callself args kw selfsomeobject selfmethodselfsomeobject args kw return self def performself return selfsomeobject and finally obj someobject p proxyobj print paabperform b what say implementation is better ways make desirable amount classes would make string cunstructing syntax ps sorry english primary language,1 actually looking proxy pattern builder pattern yes implementation imho classic one using fluent interface pattern,i find interesting way sqlalchemy constructing query strings eg sessionquerymodeluser filtermodeluserage orderbymodeluserage as far i see applied kind proxy pattern in small project i need make similar string construction using oop approach so i tried reconstitute behavior firstly kind object one plenty similar objects class someobjectobject items none def initself selfitems def callself return joinselfitems selfitems none else def aself selfitemsappend return self def bself selfitemsappend b return self all methods object return self i call order unlimited number times secondly proxy object call subject methods perform method calls object see resulting string import operator class proxyobject def initself someobject selfsomeobject someobject def getattrself name selfmethod operatormethodcallername return self def callself args kw selfsomeobject selfmethodselfsomeobject args kw return self def performself return selfsomeobject and finally obj someobject p proxyobj print paabperform b what say implementation is better ways make desirable amount classes would make string cunstructing syntax ps sorry english primary language,2 you investigate selenium ide you use python automate much firefox the forums point right direction this downloading issue persistent one good luck,i researching pywinauto pywin i want write script automate downloading file firefox when downloading file firefox show popup ask open save file choose option follow steps how i locate controls items popup using pywinauto pywin,1 you use csvreader custom dialect general solution lot details already sorted,for example file game tourney hand player luisgustavo call player otherplayer fold player otherother check i want get information best way possible remember files format what changes numbers players edit ok homework i done times i think best way openmyfile r myfile line myfile game line gamenumber linelinefind linefindtourney tourneynumber linelinefind tourney linefindhand handnumber linelinefind hand elif player line playername linelinefind linerfind playeraction linelinerfind the code works perfectly but i think good code must better way,1 read files two set use set difference eg setlinestrip line open atxt r b setlinestrip line open btxt r new open newtxt w newwrite n joina b,i two files list sites the master file called atxt processed file called btxt contents atxt wwwcnncom wwwgooglecom wwwgmailcom wwwiamvishalcom contents btxt wwwcnncom wwwgooglecom i want make python script compares searches files creates newtxt sites atxt yet appeared btxt as i new i lot reading site found great examples i managed get work done i afraid logic wrong pls see code processedfile openbtxt masterfile openatxt fopennewtxtw line processedfilereadlines line linestrip print line print we printing processed part linetwo masterfilereadlines linetwo linetwostrip print linetwo print printing master part linetwo line fwritelinetwon so new file newtxt contains sites atxt btxt expect first entry i also afraid logical buts i kept btxt sequence atxt code easily break sites sequence contents newtxt wwwgooglecom wwwgmailcom wwwiamvishalcom please advice i go i confused,2 if files small could use sets simplify code master setlinestrip line open atxt processed setlinestrip line open btxt name master processed print name,i two files list sites the master file called atxt processed file called btxt contents atxt wwwcnncom wwwgooglecom wwwgmailcom wwwiamvishalcom contents btxt wwwcnncom wwwgooglecom i want make python script compares searches files creates newtxt sites atxt yet appeared btxt as i new i lot reading site found great examples i managed get work done i afraid logic wrong pls see code processedfile openbtxt masterfile openatxt fopennewtxtw line processedfilereadlines line linestrip print line print we printing processed part linetwo masterfilereadlines linetwo linetwostrip print linetwo print printing master part linetwo line fwritelinetwon so new file newtxt contains sites atxt btxt expect first entry i also afraid logical buts i kept btxt sequence atxt code easily break sites sequence contents newtxt wwwgooglecom wwwgmailcom wwwiamvishalcom please advice i go i confused,1 try something like world bworldgravity dosleeptrue i look version looks like pass arguments like worldaabbboxdbaabb worldaabblowerbound worldaabbupperbound gravity world boxdbworldworldaabb gravity true,i installed python boxd b and create boxd world bworld simple example import boxd boxdbworld no matter i type function bworld i received error traceback recent call last file pyshell line module boxdbworld file cpythonlibsitepackagesboxdboxdpy line init boxdbworldswiginitselfboxdnewbworldargs typeerror newbworld expected arguments got,2 setopenatxt b setopenbtxt new opennewtxt w newwritejoina b,i two files list sites the master file called atxt processed file called btxt contents atxt wwwcnncom wwwgooglecom wwwgmailcom wwwiamvishalcom contents btxt wwwcnncom wwwgooglecom i want make python script compares searches files creates newtxt sites atxt yet appeared btxt as i new i lot reading site found great examples i managed get work done i afraid logic wrong pls see code processedfile openbtxt masterfile openatxt fopennewtxtw line processedfilereadlines line linestrip print line print we printing processed part linetwo masterfilereadlines linetwo linetwostrip print linetwo print printing master part linetwo line fwritelinetwon so new file newtxt contains sites atxt btxt expect first entry i also afraid logical buts i kept btxt sequence atxt code easily break sites sequence contents newtxt wwwgooglecom wwwgmailcom wwwiamvishalcom please advice i go i confused,1 in previous attempts i pursued regex option placing ends search string well recompile search string passing itthem expect luck thanks jathanism suggestion i reexamined using regex time thought expect er expecting regex i thinking string sure enough characters prompt string expect treating regex symbols exact escaping parens let expect job,i writing library support telnet ing remote server running apps things going swimmingly establishing connection getting data back parsing etc least swimmingly communicating programs via text interface one app change cursor enters properly leave original cursor fails i write apps i use when said app starts correctly works problem promptb hellox yes space end intentional response tnconncmdappnamen promptpromptb i would like use prompt change lack prompt change detect whether program failed start i figured would golden opportunity try telnetlib expect since expect allows one pass list strings match response i cannot however get work prompta hellox yes space end intentional promptb hello yes space end intentional tnconnwriteappnamen whichprompt mo response selftnconnexpectprompta promptb timeout the expect command always times whether apps starts sucessfully mo none response mumble mumblerrn stuffrnrnhello the docs say either string regex object passed expect i passing string i missing something a look telnetlib code shows calling research rematch seem issue can anyone please offer suggestions i wrong edit added parens prompt example better illustrate expect working expected,1 this stuff configurable see source not sure really documented,i using pyramidformalchemy well i trying use when requests come app i keep seeing pyramidformalchemy making strange assumptions request object my requests fail pyramidformalchemyviews starting line modelview class constructor following code def initself context request selfcontext context selfrequest request selfsession requestsessionfactory selffieldsetclass requestformsfieldset selfgridclass requestformsgrid the thing request object session sessionfactory it also forms here i done create rootfactory extends pyramidformalchemyresourcesmodels i call configformalchemyadmin passing rootfactory dbsession i created empty formspy file what i missing setup any ideas thanks,1 you read return rendertemplate pagehtml,we using flask one api i wondering anyone knew return http response for errors call flask import abort abort but i get lookuperror exception do i need create exception like docs,3 keep python installation carefull version launch making call explicit always check python version script import sys print sysversion if particular use python i recommend uninstalling,being quite cavalier i went latest version python unfortunately lacks matplotlib i desperately need i downloaded python my simple question weather i uninstall python i leave windows system,2 there permanent dtype really numpy arrays basically way viewing memory buffer views numpy sense different way slicing dicing memory buffer without making copy keep mind though giving lowlevel control way memory buffer interpreted for example import numpy np x nparange dtypenpint print an integer array x print but view float xviewnpfloat print it probably expected this yields an integer array but view float e e e e e e e e e e it probably expected so interpreting underlying bits original memory buffer floats case if wanted make new copy ints recasted floats use xastypenpfloat the reason views dtypes slicing returns view well though separate topic useful really nice tricks without duplicate things memory for example wanted convert floats ints place without duplicating memory use couple tricks views based unutbu answer question import numpy np x nparange dtypenpint print the original int array x we would used xastypenpfloat makes copy this if worried memory consumption handy xviewnpfloat x print the new float array print but old int array modified inplace print x print they views memory buffer similarly various lowlevel bittwiddling import numpy np x nparange dtypenpuint xviewnpuint print the original array x print viewed uint print which tricks now let interpret uint two streams uint b b nparange dtypenpuint print print b print x print notice original modified we duplicating memory anywhere to answer question better relative do want copy want view memory buffer different way as side note astype always makes copy regardless input output dtypes it often people actually want refer view eg want convert ints floats use astype view unless need micromanage memory usage,if i wanted change data type numpy array permanently reassignment best way here example illustrate syntax import numpy np x nparraydtype float x xviewdtype x float however i prefer change change data type place is way change dtype array inplace or better something similar x xviewdtype x floatcopy,3 im surprised nobody mentioned pyxll from website pyxll excel addin enables functions written python called excel python functions either exposed excel user defined functions called worksheets custom menu items macros,somebody really needs fix subjective questions evaluator i usually compile functions dll call excel that works fine well let say works unfortunatelly python cannot compiled i know pyexe i know make dll so way i appreciate ideas suggestions matter,2 i created github repository i improving optilude script make work soaplib the link httpsgithubcomfvieirawsdlsoaplib,i like generate stub soap web service class using python soaplib module based existing wsdl the idea generate mock third party web service does code generator exist must write martin,1 your best bet timebeing cython rather pypy it clevel performance add type declarations excellent integration numpy et al people currently working getting work well pypy ways yet,i like write performancesensitive application python executing pypy natural choice however significant portion code depends numpy scipy scikitlearn would possible embed cpython instance within running pypy program order call arrayoriented code if easiest way make pypy cpython talk,2 searches using bisect module return insertion point index an insertion point location two values it intended used like sinserti new value instead insertion points want search index values sequence the examples docs show httpdocspythonorglibrarybisecthtmlsearchingsortedlists of course works listofstrings sorted binary search probably already knew,i using bisectright search txt file each line text file contains following string word word tab number that two words separeted blank word word tab number i read file list readlines i using bisectright parameter word word word blankword find index list substring word word found bisectright seems finding correct places returns real index sub string situated instead index right shouldn bisectright return index right substring word blankword exists list could issue searching substring,1 x x treated true except empty data types false none x none works none,can i use a instead a none the latter seems verbose is difference,2 the argument pattern popen expect list strings nonshell calls string shell calls this easy fix given command cprogram filesmicrosoft visual studio vcbindumpbin exports dllfilepath either call subprocesspopen shelltrue process subprocesspopencommand stdouttempfile shelltrue use shlexsplit create argument list process subprocesspopenshlexsplitcommand stdouttempfile,i tried lot things reason i could get things working i trying run dumpbin utility ms vs using python script here i tried work tempfile open cwindowstemptempexportstxt w command cprogram filesmicrosoft visual studio vcbindumpbin exports dllfilepath process subprocesspopencommand stdouttempfile processwait tempfileclose tempfile open cwindowstemptempexportstxt w command cprogram filesmicrosoft visual studio vcbindumpbin exports dllfilepath process subprocesspopencommand stdouttempfile processwait tempfileclose tempfile open cwindowstemptempexportstxt w process subprocesspopen cprogram filesmicrosoft visual studio vcbindumpbin exports dllfilepath stdout tempfile processwait tempfileclose anyone idea trying dumpbin exports cwindowssystemkerneldll tempfiletxt correctly python,1 in pursuit canonical answer wsgi handlers i found looking way get mongrel serve wsgi app right looks like wsgid best bet django users terminally flawed others alternatives flawed the wsgid project yet lot things usable it seems active community around recommendation the mwsgi handler appears mostly one guy project looks alive i started writing foo i tried bar baz quite solve problem good place start featurelist looks good the mongrelwsgihandler project github commit year might functional i little wary the mongrelwsgi project bitbucket also commit year look like great candidate either brubeck entire web framework built mongrel python looks interesting discussions posts elsewhere topic librelist state wsgi handlers hacker news brubeck new python web framework running mongrel shedding bikes mongrel python library working spike labs deploying graphite mongrel dalton matos deploying your django application with mongrel wsgid,this attempt discover canonical answer something seems hard google right i writing web app pyramid i luxury deciding server stack look like i heard good things mongrel would like try using serve app however i figure mongrel manual google searches connect mongrel wsgi app do i roll existing solutions problem,3 i added example regular expression docs show write flexible tokenizer using regular expressions httpdocspythonorgpyklibraryrehtmlwritingatokenizer it shows buildup regex pieces ignore whitespace alternatively could consider two passes inputs first resub replace repeated whitespace whitespace tabs newlines series spaces etc single space after regexes actual parser much simpler good luck,i write regular expressions match tokenizable text cumbersome add amount whitespace insignificant required what i like function accepts regex list delimiter tokens add whitespace matching for example makewhitespaceregexfoowadelimiters return foossswssas maybe already better way achieve rather hacking existing regex i think using full parser generator would overkill i using python thanks,2 el treegetiteratortag page pageid elget id none returns second arg id exists pageid print pageid elfind title text else pprintelattrib edit updated commment thanks print pageid title time means title,i reading xml file using etree module im using following code print value page title tags my code working fine but i want little change if page id attribute id exists print value tag is possible thanks import xmletreecelementtree etree pprint import pprint tree etreeparse findtitlexml value treegetiteratortag title print valuetext value treegetiteratortag page pprintvalueattrib here xml file mediawiki siteinfo sitenamewikisitename namespaces namespace key casefirstlettermedianamespace namespaces siteinfo page id orglength newlength stub categories outlinks urls titletitletitle categoriescategories linkslinks urls urls text books text page mediawiki,1 test equality root sample …,i directory contains directories like sample sample sample etc i using oswalk access one one i facing difficulties root dirs files oswalkmypath sample root print root returns root sample sample sample etc sample directories i obtain sample directory may regex would good i dont know use,1 the elementget method used retrieve option attribute values tag pageid treefind page get id pageid print pageid,i reading xml file using etree module im using following code print value page title tags my code working fine but i want little change if page id attribute id exists print value tag is possible thanks import xmletreecelementtree etree pprint import pprint tree etreeparse findtitlexml value treegetiteratortag title print valuetext value treegetiteratortag page pprintvalueattrib here xml file mediawiki siteinfo sitenamewikisitename namespaces namespace key casefirstlettermedianamespace namespaces siteinfo page id orglength newlength stub categories outlinks urls titletitletitle categoriescategories linkslinks urls urls text books text page mediawiki,1 here first solution solution echo set testscriptpyexepy rem let create temporary python script prints info need echo future import printfunction import sys printsysexecutable printsysversion testscript echo python accessible system path python testscript echo echo python set handler python files testscript del testscript set testscript i run problem however when valid python interpreter associated python files trying open python file somescriptpy pops open with system dialog solving problem requires good knowledge batch files therefore trying come solution i asked following questions how prevent “open with” dialog window opening file command window how escape variables parentheses inside ifclause batch file why delayed expansion batch file working case how split double quoted strings embedded spaces deliminated spaces batch file improved version original batch file looks like solution b echo setlocal set testscriptpyexepy rem let create temporary python script prints info need echo future import printfunction import sys printsysexecutable printsysversion testscript echo python accessible system path python testscript echo echo python set handler python files rem we need check handler set registry exists prevent open with rem dialog box case exist rem ftype pythonfile hypothetical return value rem pythonfilepythonhomepythonexe f tokens delims ftype pythonfile set regentryi rem regentry variable everything equal sign rem pythonhomepythonexe set handler setlocal enabledelayedexpansion a regentry defined handler endlocal amp set handlera rem handler variable first token rem pythonhomepythonexe rem now expand environment variables might present rem handler path f delims echo handler set expandedhandleri exist expandedhandler testscript else handler expandedhandler set handlerexpandedhandler handler echo handler set handler exist del testscript this another take avoiding problems two solution echo setlocal echo python accessible system path python echo echo python set handler python source files py f skip tokens reg query hkcrpy set filetypek f skip tokens reg query hkcrfiletypeshellopencommand echo k improved version solution b echo setlocal enabledelayedexpansion echo python interpreter accessible system path python errorlevel python c future import printfunction import sys printsysversion echo echo python interpreter registered handler python source files py reg query hkcrpy nul amp errorlevel echo no hkeyclassesrootpy registry key found else f skip tokens reg query hkcrpy nul set filetypek filetypevalue set echo no file type set py extension else reg query hkcrfiletypeshellopencommand nul amp errorlevel echo no hkeyclassesrootfiletypeshellopencommand registry key found else f skip tokens reg query hkcrfiletypeshellopencommand nul set handlerk handlervalue set echo no command set filetype else echo handler,it display path executable version python scripts run direct invocation python python myscriptpy well scripts run directly myscriptpy script make many assumptions configuration system for instance handle situation might available python rationale i playing different ways setting environment running python scripts i thought would helpful script telling current configuration i concerned standard means provided os path environment variable association files types handlers assoc ftype commands well pathext environment variable this leaves pylauncher outside scope question,1 never ever ever ever ever build sql parameters like in fact important i going say never ever ever ever ever ever build sql parameters like you left wide open sql injection attack happens someone submits foo delete from pr prname field that right database faithfully execute two commands delete pr table django normally protects properly escaping input sql commands for reason chosen bypass orm sometimes need order formulate complex queries nothing complex queries show you something like groupquery groupobjectsall groupname formcleaneddata groupname groupname groupquery groupqueryfilternameicontainsgroupname org formcleaneddata org org groupquery groupqueryfilterorgnameorg,i problems processing form python django using raw sql querying i used httpsdocsdjangoprojectcomendevtopicsdbsql reference i getting errors trying iterate rawqueryset returned raw sql query any help would appreciated here part view class searchformformsform prname formscharfieldlabelpr name maxlength requiredfalse org formsmodelchoicefieldquerysetorgobjectsall requiredfalse groupname formscharfieldlabelunique submission name maxlength requiredfalse groupref formscharfieldlabelref maxlength requiredfalse groupurl formsurlfieldlabelurl requiredfalse def searchrequest requestmethod post form searchformrequestpost formisvalid pids gids fids loggingdebug hello filter first firstquery select from pr prname formcleaneddata prname prname loggingdebug hello firstquery name like prname else pass loggingdebug hello org formcleaneddata org org org orgobjectsgetname org orgid orgid firstquery orgid strorgid else pass firstquery firstqueryreplace and loggingdebug first query firstquery psearchresults pobjectsrawfirstquery loggingdebug first query psearchresults x psearchresults pidsappendxid loggingdebug pids pids filter group secondquery select from group groupname formcleaneddata groupname groupname secondquery name like groupname else pass groupref formcleaneddata groupref groupref secondquery ref like groupref else pass groupurl formcleaneddata groupurl groupurl secondquery methodurl like groupurl else pass secondquery secondqueryreplace and loggingdebug second query secondquery groupsearchresults predictiongroupobjectsrawsecondquery loggingdebug second query groupsearchresults x groupsearchresults gidsappendxid loggingdebug gids gids and error typeerror search enough arguments format string x psearchresults,1 you need set threshold level logger parserloggersetlevellogginginfo when logger created level set notset root logger created level warning see documentation,parserlogger logginggetloggercshelparserlogger loggingbasicconfig parserloggeraddhandlerrotatingfilehandler logfile mode maxbytes backupcount encodingnone delayfalse clientip user fbloggs parserloggerinfo protocol problem connection reset this would create file named logfile write anything if i change last line parserloggerwarning protocol problem connection reset would log message logfile properly i sure petty thing i missing i able figure,3 as name says qt designer interface design you cannot use write code actual application logic for need normal python editor the exact details use designer files python explained pyqt reference guide using qt designer btw uic pyqt compiling user interfaces c to compile user interfaces python need use pyuic this tool cannot run designer need run manually but recommended load user interface dynamically runtime using pyqtuic modules explained reference guide,i pyqt v installedwhen i draw layouts i want view code comes error unable launch uic snapshot i compile ui files manually cmdline but i dont know put code slotmethods signals where i set settings finding uic compile ui my installation pyuic where i define slotsmethods functoins signatures receiver objectsender i see edit signalsslots edit menu shows standard signalsslotsdoesn options define,3 your code work written however another way let python split lines line f use open instead file use need close file manually openkeywordstxt r f print joinlinerstrip line f know line ending,i keywords file i wanted replace new lines commas print filekeywordstxt rreadreplacen tried variations rn,1 try something like open myfile r myfile header myfilereadlinesplit gamenumber tourneynumber handnumber header header header line myfile playername playeraction linesplit this uses split docs much pythonic,for example file game tourney hand player luisgustavo call player otherplayer fold player otherother check i want get information best way possible remember files format what changes numbers players edit ok homework i done times i think best way openmyfile r myfile line myfile game line gamenumber linelinefind linefindtourney tourneynumber linelinefind tourney linefindhand handnumber linelinefind hand elif player line playername linelinefind linerfind playeraction linelinerfind the code works perfectly but i think good code must better way,1 the previous respondent gave correct answer however i send read regular logging docs instead take look logging howto guide httpdocspythonorghowtologginghtml that much friendly way get started,parserlogger logginggetloggercshelparserlogger loggingbasicconfig parserloggeraddhandlerrotatingfilehandler logfile mode maxbytes backupcount encodingnone delayfalse clientip user fbloggs parserloggerinfo protocol problem connection reset this would create file named logfile write anything if i change last line parserloggerwarning protocol problem connection reset would log message logfile properly i sure petty thing i missing i able figure,2 one big disadvantage java tracing gc time time stop world freeze application relatively long time full gc if heap big object tree complex freeze seconds also full gc visits whole object tree something probably quite inefficient another drawback way java gc tell jvm heap size want default good enough jvm derives value several thresholds trigger gc process much garbage stacking heap i presume actually main cause jerky feeling android based java even expensive cellphones comparison smoothness ios based objectivec using rc i love see jvm option enable rc memory management maybe keeping gc run last resort memory left,python uses reference count method handle object life time so object use immediately destroyed but java gcgarbage collector destroys objects longer used specific time why java choose strategy benefit is better python approach,1 your solution looks fine if want tweek bit use itertoolsimap instead map that collapse memory footprint o instead on,i dict containing lists keys dct b c what best way recognize whether length lists this solution import itertools lensetitertoolsimaplen dctviewvalues true similar false upd in reference raymondhettinger advice replace map itertoolsimap,3 the highlevel c api number tools executing pure python code c start looking httpdocspythonorgcapiveryhighhtmlpyrunstring,i working python script i using python logging module writing information log file see httpdocspythonorghowtologginghtml here small example also mentioned page import logging import loggingconfig loggingconfigfileconfig loggingconf create logger logger logginggetlogger simpleexample application code loggerinfo info message loggererror error message now i want create cextension python i want import program the question how i write information logfile ccode is way using loggingmodule python cextension thank comments,1 note ovgolovin solution much better i leaving answer discussion refers your solution fine could use generator expression uses less memory readable lensetlenx x dctviewvalues,i dict containing lists keys dct b c what best way recognize whether length lists this solution import itertools lensetitertoolsimaplen dctviewvalues true similar false upd in reference raymondhettinger advice replace map itertoolsimap,1 pretty straightforward itertools import permutations open listtxt f letters lstrip l f lstrip p permutationsletters print joinp output ab ac ad ba bc bd ca cb cd da db dc some notes the statement ensures file closed done letters generator expression many cases though one save read entire file the uses lstrip meant nicely handle accidental blank lines present input itertoolspermutations correct not itertoolscombinations considers ab ba include latter output happy pythoning,i searched found nothing help this example listtxt b c i want able get output like outputtxt ab ac ad ba bc bd ca cb cd etc,1 you could create metaclass adds behavior class created usecase simple enough extract dictionary directly need class mysqlconstants decimal tiny short long float double varsmysqlconstants module main short double decimal float long tiny doc none,bit surprised find answer one realworld reason asking i dictionary constants class class mysqlconstants decimal tiny short long float double etc i want dictionary i find constant given number easy enough fieldtypedic fieldtype dir mysqlconstants value getattr mysqlconstants fieldtype fieldtypedic value fieldtype would easy enough make static method mysqlconstants call going mysqlconstantscreatedic class definition statement executed i wondering whether way get method inevitably static run class nb i talking creating instance class created,1 from documentation newsdescriptiontruncatewords,i field like django template pnewsdescriptionp i wanna show first words field how i,3 here solution uses metaclass class constantdictmetatype def newcls name bases dct fieldtypedic dictv k k v dctitems kisupper dctfieldtypedic fieldtypedic return typenewcls name bases dct class mysqlconstants metaclass constantdictmeta decimal tiny short long float double mysqlconstantsfieldtypedic decimal tiny short long float double,bit surprised find answer one realworld reason asking i dictionary constants class class mysqlconstants decimal tiny short long float double etc i want dictionary i find constant given number easy enough fieldtypedic fieldtype dir mysqlconstants value getattr mysqlconstants fieldtype fieldtypedic value fieldtype would easy enough make static method mysqlconstants call going mysqlconstantscreatedic class definition statement executed i wondering whether way get method inevitably static run class nb i talking creating instance class created,2 to answer question directly yes class mysqlconstants decimal tiny short long float double def createdictcls fieldtypedic isinstancecls dict cls clsdict key value clsitems isinstancevalue int fieldtypedic value key cls fieldtypedic fieldtypedic createdictvars createdict classmethodcreatedict notice rewrite createdict particular assigning classmethod calling class creation if oneshot use method i would inclined go class mysqlconstants lookup local vars name enumerate decimal tiny short long float double split localname lookupi name del local name this creates names creates reverse lookup dictionary one nice tidy package,bit surprised find answer one realworld reason asking i dictionary constants class class mysqlconstants decimal tiny short long float double etc i want dictionary i find constant given number easy enough fieldtypedic fieldtype dir mysqlconstants value getattr mysqlconstants fieldtype fieldtypedic value fieldtype would easy enough make static method mysqlconstants call going mysqlconstantscreatedic class definition statement executed i wondering whether way get method inevitably static run class nb i talking creating instance class created,1 the plain python stuff exceptionally unlikely lead seg fault what sticks skypepy no idea comes i bet culprit,i got fairly simple python script import skypepy random import randint time import strftime sleep os import system interval def pickstatus try handler openlinestxt r lines handlerreadsplitn handlerclose rand randint lenlines line linesrand print strftimeymd im p strrand line system notifysend new status line skypecurrentuserprofilemoodtext line sleepinterval pickstatus except keyboardinterrupt pass name main skype skypepyskype skypeattach pickstatus when i run i sometimes get python randomstatuspy segmentation fault other times though script runs fine all python scripts also work fine this error really give enough context even know look any ideas even way get actual debug info would appreciated,2 first i would stick itervalues uses easy evaluation second i would wary relying using set since performs looking value set every iteration going dictionary it o overage on worse case o case length on length different according docs but difficult asses overhead using set i would use case fails finds first false value so first mismatch length would stop interating process while using set would go list end compare length dct b c lenght lendctitervaluesnext alllenvaluelenght value dctitervalues false dct b c lenght lendctitervaluesnext alllenvaluelenght value dctitervalues true the code optimized using iterator go first value twice dctitervalues length lennextit alllenvaluel value true,i dict containing lists keys dct b c what best way recognize whether length lists this solution import itertools lensetitertoolsimaplen dctviewvalues true similar false upd in reference raymondhettinger advice replace map itertoolsimap,2 seeing getorcreateuser uses default arguments set none def getorcreateuserid photonone firstnamenone lastnamenone nicknamenone organizationnone citynone countrynone you use class usercreationhandlerwebapprequesthandler def getself id selfrequestget id something set stuff call getorcreateuser else getorcreateuserid,is way simplify following code def getorcreateuserid photonone firstnamenone lastnamenone nicknamenone organizationnone citynone countrynone save user datastore class usercreationhandlerwebapprequesthandler def getself id selfrequestget id photo none firstname none lastname none nickname none organization none city none country none something calculations something calculations something assign id photo firstname etc values getorcreateuserid photo firstname lastname nickname organization city country i like assignments none,2 something like def getself id selfrequestget id userdetails something assign userdetails id userdetails photo userdetails firstname etc values getorcreateuserid userdetails,is way simplify following code def getorcreateuserid photonone firstnamenone lastnamenone nicknamenone organizationnone citynone countrynone save user datastore class usercreationhandlerwebapprequesthandler def getself id selfrequestget id photo none firstname none lastname none nickname none organization none city none country none something calculations something calculations something assign id photo firstname etc values getorcreateuserid photo firstname lastname nickname organization city country i like assignments none,3 i soft linked unopy unohelperpy seems work as root sudo cd usrlibpythondistpackages ln usrlibpythondistpackagesunopy ln usrlibpythondistpackagesunohelperpy,i working openerp module named reportopenoffice this module needs package pythonuno installed the problem versions python when i install package python use package pythonuno python i need use python is way install package python ps i ubuntu thank much,1 you simply make list dictionary add colors i know pylab works i found example might work pylab import cdict red green blue mycmap matplotlibcolorslinearsegmentedcolormap mycolormap cdict pcolorrandcmapmycmap colorbar,what quickest way get array colors python something i index pass color argument plotting pylab the best i come colors randomrandomrandom range solution generate wellspaced colors interpolated would preferable,1 source spaces tabs mixed block code think executed actually executed inside statement,i problems processing form python django there unusual behavior processing form below form part function processing form view i fairly new python django help much appreciated class searchformformsform prname formscharfieldlabelpr name maxlength requiredfalse org formsmodelchoicefieldquerysetorgobjectsall requiredfalse groupname formscharfieldlabelunique submission name maxlength requiredfalse groupref formscharfieldlabelref maxlength requiredfalse groupurl formsurlfieldlabelurl requiredfalse def searchrequest requestmethod post form searchformrequestpost formisvalid pids gids fids loggingdebug hello filter first firstquery select from pr prname formcleaneddata prname prname loggingdebug hello firstquery name like prname else pass loggingdebug hello org formcleaneddata org org org orgobjectsgetname org orgid orgid firstquery orgid strorgid else pass firstquery firstqueryreplace and loggingdebug first query firstquery psearchresults pobjectsrawfirstquery loggingdebug first query psearchresults x psearchresults pidsappendxid loggingdebug pids pids filter group secondquery select from group groupname formcleaneddata groupname groupname secondquery name like groupname else pass groupref formcleaneddata groupref groupref secondquery ref like groupref else pass groupurl formcleaneddata groupurl groupurl secondquery methodurl like groupurl else pass secondquery secondqueryreplace and loggingdebug second query secondquery groupsearchresults predictiongroupobjectsrawsecondquery loggingdebug second query groupsearchresults x groupsearchresults gidsappendxid loggingdebug gids gids when i enter prname form submit view enters first statement prints hello hello console skips hello skips second statement skips ahead secondquery secondqueryreplace and the debug output debug hello debug hello and error unboundlocalerror search local variable secondquery referenced assignment traceback file librarypythonsitepackagesdjangocorehandlersbasepy getresponse response callbackrequest callbackargs callbackkwargs file viewspy search secondquery secondqueryreplace and exception type unboundlocalerror search exception value local variable secondquery referenced assignment expected output debug hello debug hello debug hello debug first query select from pr firstquery debug first query psearchresults,1 it seems like matplotlib comes several builtin colormaps you get one using getcmap,what quickest way get array colors python something i index pass color argument plotting pylab the best i come colors randomrandomrandom range solution generate wellspaced colors interpolated would preferable,2 random import randint colors range colorsappend x randint xffffff result example ab df add ec cb ceff b ca cfd fccd ps thanks inerdia,what quickest way get array colors python something i index pass color argument plotting pylab the best i come colors randomrandomrandom range solution generate wellspaced colors interpolated would preferable,2 the problem first part sockets stream based message based you need come message abstraction layer top stream this way end pipe knows going onhow much data expect part one command guessing supposed happen,trying create gui client command line server however running annoying problems cant seem fix i sure actual problem sometimes code work times wont i think main problem originally tried selfdata srecv selfdata break else print selfdata then sending f files ssendf each f string filename i expected come recv side one file name recieved recv call instead one recv call got big chunk filenames assume chars worth which made impossible check end data thus loop never exited this code def getdataselfsize selfalldata gtkeventspending gtkmainiteration selfrecvdata selfsrecvsize selfalldata selfrecvdata selfalldatafindrnrneof print recieved end message selfrdata selfalldataselfalldatafindrnrneof break print all data recieved strlenselfrdata bytes print all data n selfrdata n selfinfiles selfrdataspliteos nf selfinfiles lennf selfaddmessageselfincomingiconnf at minute im trying get client read correctly server what want happen command list typed sent client server sends back data file appended list store times works ok times one files gets returned executes ok try type another command send whole gtk window geys program becomes unresponsive sorry cant explain question better ive tried alot different solutions give different errors someone could explain recv command may giving errors im sending data client ifcommands list whatpacketshouldlooklike print request list files address fil listfilespath f fil sdata f whatpacketshouldlooklike sdata eos newsocksendsdata eos print sent sdata newsocksendrnrneof whatpacketshouldlooklike rnrneof print print whatpacketshouldlooklike print,2 are strings names global variables if access value refenced global variable globals name replacing name string name variable course or better yet instead littering variable names global namespace could use dict node node rootnode node hips node childnode transformnode rightpirateleg node rootnode this makes easy map string names values,i probably going wrong i trying populate qtreeview sql data using qabstractitemmodel great deal trouble understanding tbh one tutorials i following simplest populates tree simply calling new instances node generating model list the node name parentnode this ok generating data within program this i follow however i want bring data table use string identify correct parentnode mainly i iterating records i able name one using separate variable it x recs node nodename parentnode when i i get obvious error message string isnt correct object methods is way using string derived table identify correct parent object either could somebody point direction basic qtreeview model tutorial designed enthusiastic necessary gifted learners rootnode nodehips childnode transformnoderightpirateleg rootnode childnode noderightpiratelegend childnode childnode cameranodeleftfemur rootnode childnode nodelefttibia childnode childnode nodeleftfoot childnode childnode lightnodeleftfootend childnode i realise i probably running i walk apologise advance ignorance,1 a good way confirm whether firewall issue perform telnet commandline destination host question telnet khcselabsumnedu trying and sometime later telnet connect address connection timed if hangs trying eventually times chances connection remote host specific port blocked firewall it could either network layer eg real firewall router accesslist host iptables hostbased filtering mechanisms access lab host might available within lab campus network talk professor network administrator someone know network find sure,for class project i trying socket programming python running basic issue i create tcp connection laptop lab machine which i hoping use server without even getting scripts i written i simply trying interpreter line commands success on lab machine khcselabsumnedu i type following python socket import sock socket sockbind socklisten sockaccept and laptop i type socket import sock socket sockconnect khcselabsumnedu at point machines block anything client times i send sigint this code pretty much exactly copied examples i found online mark lutz book programming python using server host name apparently uses os default fairly common if i run ends computer use localhost hostname works fine i suspect problem hostnames i using one ends i really sure could going wrong simple example does anyone idea,1 sikuli might perfect it based jython thus extended python java tools sikuli visual technology automate test graphical user interfaces gui using images screenshots sikuli includes sikuli script visual scripting api jython sikuli ide integrated development environment writing visual scripts screenshots easily edit if image well defined example easily matched without much image processing here i used matplotlib small image must exact cropped version large image target image x image matched x in import matplotlibpyplot pl in target plimreadrpng in match plimreadxxpng in targetshape out in matchshape out in range x range subx x suby subtarget targetsubysubysubxsubx match subtargetall print match found dd dd subxsubysubxsuby match found,in html page using image map i would like use python perl ruby c crawl find particular image separated transparency area another one click image found the image times what best way achieve edit french readers trick implemented see httpwwwsputnickareanetp,1 use abstraction layer pyro xmlrpc zeromq define protocol distinguish messages for example protocol send length message header string in case use struct module parse length binary format ask want go way i strongly recommend choosing one mentioned abstraction layers,trying create gui client command line server however running annoying problems cant seem fix i sure actual problem sometimes code work times wont i think main problem originally tried selfdata srecv selfdata break else print selfdata then sending f files ssendf each f string filename i expected come recv side one file name recieved recv call instead one recv call got big chunk filenames assume chars worth which made impossible check end data thus loop never exited this code def getdataselfsize selfalldata gtkeventspending gtkmainiteration selfrecvdata selfsrecvsize selfalldata selfrecvdata selfalldatafindrnrneof print recieved end message selfrdata selfalldataselfalldatafindrnrneof break print all data recieved strlenselfrdata bytes print all data n selfrdata n selfinfiles selfrdataspliteos nf selfinfiles lennf selfaddmessageselfincomingiconnf at minute im trying get client read correctly server what want happen command list typed sent client server sends back data file appended list store times works ok times one files gets returned executes ok try type another command send whole gtk window geys program becomes unresponsive sorry cant explain question better ive tried alot different solutions give different errors someone could explain recv command may giving errors im sending data client ifcommands list whatpacketshouldlooklike print request list files address fil listfilespath f fil sdata f whatpacketshouldlooklike sdata eos newsocksendsdata eos print sent sdata newsocksendrnrneof whatpacketshouldlooklike rnrneof print print whatpacketshouldlooklike print,1 you need assign something name longname use name foo longname foo bar cnamename longname cfunc i function no firstly call function yet the function call line gives error secondly function scope the name different global name i think makes sense move func method inside class definition the code said works better way,little problem try attach class object python i textfile file seperated list line the program read every line print name longname imagine textfile look like john n john travolta here bit code class name def initself name longname selfnamename selflongnamelongname def strself snameselfname sn longnameselflongname def func line file nameline longnameline n cnamename longname cfunc i get error message name longname defined i function it works i put function outside class like def func line file nameline longnameline n cnamename longname print c need help,1 you need extract edges vtkpolydata object edges vtkvtkextractedges edgessetinputtrianglepolydata edgemapper vtkvtkpolydatamapper edgemappersetinputedgesgetoutput edgeactor vtkvtkactor edgeactorsetmapperedgemapper edgeactorgetpropertysetcolor renaddactoredgeactor vtkvtkpolydatamappersetresolvecoincidenttopologytopolygonoffset first must extract edges via vtkextractedges filter you map results filter vtkpolydata object construct actor data we set color mesh red modifying actor directly the call vtkvtkpolydatamappersetresolvecoincidenttopologytopolygonoffset prevents edges fighting surfaces two geometric objects coincident tear due zbuffer precision issues for completeness sake whole code import vtk create rendering window renderer ren vtkvtkrenderer renwin vtkvtkrenderwindow renwinaddrendererren create renderwindowinteractor iren vtkvtkrenderwindowinteractor irensetrenderwindowrenwin create points points vtkvtkpoints pointsinsertnextpoint pointsinsertnextpoint pointsinsertnextpoint triangle vtkvtktriangle trianglegetpointidssetid trianglegetpointidssetid trianglegetpointidssetid triangles vtkvtkcellarray trianglesinsertnextcelltriangle polydata object trianglepolydata vtkvtkpolydata trianglepolydatasetpoints points trianglepolydatasetpolys triangles mapper mapper vtkvtkpolydatamapper mappersetinputtrianglepolydata actor actor vtkvtkactor actorsetmappermapper assign actor renderer renaddactoractor get edges mesh edges vtkvtkextractedges edgessetinputtrianglepolydata edgemapper vtkvtkpolydatamapper edgemappersetinputedgesgetoutput make actor edges edgeactor vtkvtkactor edgeactorsetmapperedgemapper make actor red ways also edgeactorgetpropertysetcolor renaddactoredgeactor avoid zbuffer fighting vtkvtkpolydatamappersetresolvecoincidenttopologytopolygonoffset enable user interface interactor ireninitialize renwinrender irenstart,i want display surface textured i want triangles boundaries visible surface different color lets say red i found following code vtk code samples display triangle boundaries filled triangles import vtk create rendering window renderer ren vtkvtkrenderer renwin vtkvtkrenderwindow renwinaddrendererren create renderwindowinteractor iren vtkvtkrenderwindowinteractor irensetrenderwindowrenwin create points points vtkvtkpoints pointsinsertnextpoint pointsinsertnextpoint pointsinsertnextpoint triangle vtkvtktriangle trianglegetpointidssetid trianglegetpointidssetid trianglegetpointidssetid triangles vtkvtkcellarray trianglesinsertnextcelltriangle polydata object trianglepolydata vtkvtkpolydata trianglepolydatasetpoints points trianglepolydatasetpolys triangles mapper mapper vtkvtkpolydatamapper mappersetinputtrianglepolydata actor actor vtkvtkactor actorsetmappermapper assign actor renderer renaddactoractor enable user interface interactor ireninitialize renwinrender irenstart can anybody please let know display triangle boundaries specific color i ideally want display triangles textured surface my data consist triangles it might also possible vertices triangles given vtk made visible i coding python thanks lot,2 the rfc defines applicationjson says an object unordered collection zero namevalue pairs and the names within object should unique it means alchemyapi return multiple subtype names inside object claim json you could try request xml format outputmodexml avoid ambiguity results convert duplicate keys values lists import simplejson json collections import defaultdict def multidictorderedpairs convert duplicate keys values lists read values lists defaultdictlist k v orderedpairs dkappendv unpack lists item k v ditems lenv dk v return dictd print jsonjsondecoderobjectpairshookmultidictdecodetext example text type person subtype athlete subtype awardwinner output u subtype u athlete u awardwinner u type u person,i using alchemy api app engine i using simplejson library parse responses the problem responses entries sme name status ok usage by accessing alchemyapi using information generated alchemyapi agreeing bound alchemyapi terms use httpwwwalchemyapicomcompanytermshtml url language english entities type person relevance count text michael jordan disambiguated name michael jordan subtype athlete subtype awardwinner subtype basketballplayer subtype halloffameinductee subtype olympicathlete subtype sportsleagueawardwinner subtype filmactor subtype tvactor dbpedia httpdbpediaorgresourcemichaeljordan freebase httprdffreebasecomnsguidacf umbel httpumbelorgumbelnewikipediamichaeljordan opencyc httpswopencycorgconceptmxrvvivqwpebgdrcnyyca yago httpmpiideyagoresourcemichaeljordan so problem subtype repeated dict loads returns tvactor rather list is anyway go around,3 using blob work import numpy pythonmagick import image blob image httpwwwmicroimagescomgalleryjppotholesjp b blob iwriteb gray numpyfromstringbdata uint reshapeirows icolumns,i working application among things need read satellite image one band per image process pixel data the format jpeg therefore i cannot use pil library simplifies everything i found pythonmagick library i perfectly read image extract value pixel but one pixel impythonmagickimagedirimage this slow aimpixelcolorjiintensity value intensity extracted one pixel aaintxmlvar reflectance values normalised range therefore i need forloop get pixel values images large i tried blob function get data crashes are better options how could i quickly get pixel data jpeg image save array,1 if want new class use instance test created pass part constructor newpy class new def initself one onerun testpy import new class test def initself return def runself return name main onetest two newnewone playing around globals great way break code without realizing it better explicitly pass reference want use,i two files one testpy import newpy class test def initself return def runself return name main onetest onerun newpy class new def initself onerun new now run python testpy i get error traceback recent call last file testpy line module import newpy file homephanindradesktopnewpy line module new file homephanindradesktopnewpy line init onerun nameerror global name one defined but i want use instance one new can i edit i want access variable testpy newpy process give back testpy isn possible,3 just thought i contribute odd lines code i build upon jim dennis answer mostly taking away hint symetric scoring i implemented minimax algorithm described mastermind wikipedia article knuth one exception i restrict next move current list possible solutions i found performance deteriorated badly taking possible solutions account step the current approach leaves worst case guesses combination found well second it perhaps important note i make restriction whatsoever hidden sequence allowing number repeats itertools import product tee random import choice colors red green blue yellow purple pink grey white black orange brown mauve gap holes def randomsolution generate random solution return tuplechoicecolors rangeholes def allsolutions generate possible solutions solution productteecolors holes yield solution def filtermatchingresultsolutionspace guess result filter solutions matches produce specific result guess solution solutionspace scoreguess solution result yield solution def scoreactual guess calculate score guess actual result black pin every color right position actuallist listactual guesslist listguess blackpositions number number pair enumeratezipactuallist guesslist pair pair number reversedblackpositions del actuallistnumber del guesslistnumber resultappend black white pin every color wrong position color guesslist color actuallist remove match score duplicate colors actuallistremovecolor resultappend white return tuple suitable dictionary key return tupleresult def minimaleliminatedsolutionspace solution for solution calculate many possibilities s would eliminated possible coloredwhite score the score guess least values resultcounter option solutionspace result scoresolution option result resultcounterkeys resultcounterresult else resultcounterresult return lensolutionspace maxresultcountervalues def bestmovesolutionspace determine best move solution space one restricts number hits elimforsolution dictminimaleliminatedsolutionspace solution solution solution solutionspace maxelimintated maxelimforsolutionkeys return elimforsolutionmaxelimintated def mainactual none solve game mastermind generate random hidden sequence actual none actual none actual randomsolution start game choosing n unique colors currentguess colorsholes initialize solution space solutions solutionspace allsolutions guesses true calculate current score currentscore scoreactual currentguess print joincurrentguess tt joincurrentscore currentscore tuple black holes print guesses guesses fort joinactual return guesses restrict solution space exactly hits currentscore currentguess solutionspace tuplefiltermatchingresultsolutionspace currentguess currentscore pick candidate limit search space currentguess bestmovesolutionspace guesses name main print maxmainsol sol allsolutions should anyone spot possible improvements code i would much interested suggestions,how would create algorithm solve following puzzle mastermind your opponent chosen four different colours set six yellow blue green red orange purple you must guess chosen order after guess opponent tells many colours guessed right colour right place blacks many right colour wrong place whites the game ends guess correctly blacks whites for example opponent chosen blue green orange red guess yellow blue green red get one black red two whites blue green you would get score guessing blue orange red purple i interested algorithm would choose optionally translate code preferably python i interested coded solutions clear easily understood concise efficient fast making guess effective least number guesses solve puzzle flexible easily answer questions algorithm eg worst case general easily adapted types puzzle mastermind i happy algorithm effective efficient provided poorly implemented however efficient effective algorithm implemented inflexibly impenetrably use i detailed solution python i posted means best approach please post i expecting essay,1 no using standard youtube api cannot programatically set thumbnail video however content partner access youtube cms partner manager enable apparently set video artwork i post details i run process,is possible specify thumbnail video uploaded via youtube api using recent version python library appears i create set thumbnail media group inserting video entry youtube however thumbnail specified not get set video i using code similar gdata import media gdatayoutube import youtubevideoentry gdatayoutubeservice import youtubeservice create thumbnail pass media group thumbnail mediathumbnailurl httpvalidimageurljpg mediagroup mediagroupthumbnailthumbnail title foo use media group create video entry entry youtubevideoentrymediamediagroup create service instance use login service youtubeservice serviceclientlogin get video file file open pathtovideomp rb push video youtube serviceinsertvideoentry entry file close file fileclose,1 you sort sorteda sortedb a counting sort could also efficient requires object hashable collections import counter b print countera counterb true,b amp b considered equal exactly elements different order the thing actual lists consist objects class instances integers,3 default cursor size mb maximum go mb try increase cursor size limit reached see get improvement also depends network handle,i actually working search engine project we working python mongodb i following problem i pymongo cursor excecuting find command mongo db the pymongo cursor around k results i noticed iteration pymongo cursor really slow compared normal iteration example list size i little benchmark iteration list k strings seconds iteration pymongo cursor k results seconds the difference really lot maybe problem amounts results i millons results time would unacceptable has anyone got idea pymongo cursors slow iterate any idea i iterate cursor less time some extra info python v pymongo v mongodb v bits,1 the best way sorting lists comparing using counter work objects hashable this straightforward integers sorteda sortedb it gets little trickier arbitrary objects if care object identity ie whether objects lists use id function sort key sorteda keyid sortedb keyid in python x actually need key parameter compare object object the ordering arbitrary stable works fine purpose matter order objects ordering lists in python though comparing objects different types disallowed many circumstances example compare strings integers objects various types best explicitly use object id if want compare objects list value hand first need define value means objects then need way provide key python consistent type one potential way would work lot arbitrary objects sort repr of course could waste lot extra time memory building repr strings large lists sorteda keyrepr sortedb keyrepr if objects types define lt object knows compare others then sort worry key parameter of course could also define hash use counter faster,b amp b considered equal exactly elements different order the thing actual lists consist objects class instances integers,2 what i done past create worker class processes data entries then i spin x number threads run copy worker class each item dataset gets pushed queue worker threads watching when items queue threads spin using method i able process data items using threads seconds when app singlethreaded would take significantly longer check httpdocspythonorglibraryqueuehtml,i two dictionaries data i created function acts rules engine analyze entries dictionaries things based specific metrics i setif helps entry dictionary node graph rules match i create edges here code i useits loop passes parts dictionary rules function i refactored code tutorial i read jobs def loadgraphdaycurrent dayprevious daycurrentcount graphdaycurrent daycurrentvalue graphdaycurrentdaycurrentcount daycount graphdayprevious dayvalue graphdaypreviousdaycount rulesdaycount dayvalue daycurrentcount daycurrentvalue daycurrent dayprevious p multiprocessingprocesstargetrules argsdaycount dayvalue daycurrentcount daycurrentvalue daycurrent dayprevious jobsappendp pstart print rules engine day daycurrentcount lengraphdaycurrentdaycurrentcountfloatlengraphdaycurrent the data i studying could rather largecould randomly generated i think day entries because time spend stage i wondering i could use cores i available help process faster because dictionary entry compared dictionary entry day i thought proceses could split code slower using normally i think creating new process every entry is way speed use cpus my problem i want pass entire dictionary one core get suck processing i would rather process split cpu way i maximum free cpus i totally new multiprocessing i sure something easy i missing any advicesuggestions reading material would great,1 no embed cpython inside pypy afaik you however use distributedparallel execution systems make pypy talk cpython both execnet pyro mention precise pypy cpython use case other packages python wiki parallel processing page probably suitable also delnan mentions current discussion pypy developers plan implementing numpy pypy include support scipy scikitlearn far,i like write performancesensitive application python executing pypy natural choice however significant portion code depends numpy scipy scikitlearn would possible embed cpython instance within running pypy program order call arrayoriented code if easiest way make pypy cpython talk,1 update the link i gave python apologies i forgot tag the docs mention blank lines values i suspect supported see also so question looks like python how read multiline properties file python from documentation values also span multiple lines long indented deeper first line value depending parser’s mode blank lines may treated parts multiline values ignored i know parser mode referring sure want doable on hand docs also mention emptylinesinvalues option seems indicate blank lines supported seems somewhat contradictory,the following file parsed configparser ticket description this multiline string as described official python wiki configparser examples helper function def configsectionmapsection dict options configoptionssection option options try dictoption configgetsection option dictoption debugprintskip option except printexception option dictoption none return dict the resulting value print configsectionmap ticket description this multiline string the expected value print configsectionmap ticket description this multiline string how i fix,1 to precisely attack problem i suggest measuring file read operation making convertxyz noop function timing result and measuring convert function changing read always return simple point calling conversion output number times really reading file and probably another run final postconversion output noop depending time going may make lot sense attack one you might able get local os interleaving writing output python stdout shell actual file io and similarly streaming file stdin eg cat oldformat python conversionpy outputfile what sort storage input output files the storage characteristics may lot performance python code update given output slowest storage pretty slow shared reads writes try adding buffering from python doc able add buffering adding third argument osopen call try something pretty large like,right i trying convert large quantity binary files points latitude longitude altitude format text based ecef cartesian format x z the problem right process slow i gigabytes stuff run data could coming i would like make bit code fast possible right code looks something like import mmap import sys import struct import time pointsize def getarguments lensysargv print not enough arguments example python tllargbinreaderpy inputfilenametllargbin outputfilename return none else return sysargv print getarguments def readtllargbinfilename outputcallback f openfilename r map mmapmmapffileno timeclock mapsize pointsize print file size aligned return xrangemapsizepointsize datalist structunpack db mapiipointsize writestr formatstringdatalist print dd points processed imapsize print time elapsed f timeclock mapclose def generatewritexyzfilename f openfilename w def writexyzwritestr fwritewritestr return writexyz def formatstringdatalist return f f f datalist datalistdatalist args getarguments args none readtllargbinargsgeneratewritexyzoutxyz convertxyz basically conversion formula httpenwikipediaorgwikigeodeticsystem i wondering would faster read things chunks mb one thread put bounded buffer different thread conversion string format final thread write string back file different harddisk i might jumping gun though i using python right testing i opposed switching i work files faster any suggestions would great thanks edit i profiled code cprofile time split string format io it seems i actually killed string format here profiler report function calls cpu seconds ordered standard name ncalls tottime percall cumtime percall filenamelinenofunction stringmodule tllargbinreaderpymodule tllargbinreaderpyreadtllargbin tllargbinreaderpygeneratewritexyz tllargbinreaderpyformatstring tllargbinreaderpygetarguments structunpack execfile len method close mmapmmap objects method disable lsprofprofiler objects method fileno file objects method size mmapmmap objects open timeclock is faster way format strings,1 if know items always hashable use counter on if know items always sortable use sorted on log n in general case rely able sort elements need fallback like unfortunately on lenalenb allacountibcounti,b amp b considered equal exactly elements different order the thing actual lists consist objects class instances integers,3 you get situation installed package required run turbogears app turbogears one required develop turbogears app tgdevtools running following command virtualenv install correct package easyinstall httpwwwturbogearsorgdownloadscurrentindex tgdevtools,i installing turbogears windows running virtual environment python i seeing paster quickstart option i run paster help instead output virtualenv cvirtualenvscriptspaster help usage pasterscriptpy pasteroptions command commandoptions options version show program version number exit pluginplugins add plugin list commands plugins egg specs also require egg h help show help message commands create create file layout python distribution help display help makeconfig install package create fresh config filedirectory points show information entry points post run request described application request run request described application serve serve described application setupapp setup application given config file turbogears tginfo show turbogears related projects versions so surprise i run virtualenv cvirtualenvscriptspaster quickstart i get command quickstart known may need run setuppy egginfo known commands create create file layout python distribution exe run executable files help display help makeconfig install package create fresh config filedirectory points show information entry points post run request described application request run request described application serve serve described application setupapp setup application given config file tginfo show turbogears related projects versions my questions why missing i get,1 remove pl request uri playlisturi httpgdatayoutubecomfeedsapiplaylistscdcda i sure youtube needs format needs you also replace playlistspl playlists string,i bit problem using python youtube api get title videos playlist i enviroment configured correctly also i copied example api documentation works added playlist id i try use one playlist i get error here code i wrote in example i try get titles videos import gdatayoutube import gdatayoutubeservice ytservice gdatayoutubeserviceyoutubeservice ytservicessl true typical playlist uri playlisturi httpgdatayoutubecomfeedsapiplaylistsplcdcda playlistvideofeed ytservicegetyoutubeplaylistvideofeedplaylisturi iterate feed would playlistvideoentry playlistvideofeedentry print playlistvideoentrytitletext here error i get requesterror status body invalid playlist id reason bad request i quite frustrated would appreciate help thank,2 tempfile subprocesscheckcall r cprogram filesmicrosoft visual studio vcbindumpbinexe exports dllfilepath stdouttempfile,i tried lot things reason i could get things working i trying run dumpbin utility ms vs using python script here i tried work tempfile open cwindowstemptempexportstxt w command cprogram filesmicrosoft visual studio vcbindumpbin exports dllfilepath process subprocesspopencommand stdouttempfile processwait tempfileclose tempfile open cwindowstemptempexportstxt w command cprogram filesmicrosoft visual studio vcbindumpbin exports dllfilepath process subprocesspopencommand stdouttempfile processwait tempfileclose tempfile open cwindowstemptempexportstxt w process subprocesspopen cprogram filesmicrosoft visual studio vcbindumpbin exports dllfilepath stdout tempfile processwait tempfileclose anyone idea trying dumpbin exports cwindowssystemkerneldll tempfiletxt correctly python,1 you need call drawline displayflip copying data buffer display lines drawn,ive following tutorial learn pygame code make window green the program also exposed draw red line across screen far sucessfull line appear suggestions usrbinenv python import pygame screen pygamedisplaysetmode running green red point point running event pygameeventpoll eventtype pygamequit running screenfillgreen pygamedisplayflip pygamedrawlinescreen red point point,1 on the counter method best objects hashable def compares return counters countert on log n the sorted method next best objects orderable def compares return sorteds sortedt on n if objects neither hashable orderable use equality def compares listt make mutable copy try elem tremoveelem except valueerror return false return,b amp b considered equal exactly elements different order the thing actual lists consist objects class instances integers,3 you use normal array d matrix you need give length dimension function in c file something z array length nn int fc int n const double const double b double z int n int j j n j zinj somefunctionaibj return n in python need use d array nn elements instead d matrix update d case z array length nnn int fc int n const double const double bconst double c double z int n int j j n j int k k n k zinjnk somefunctionaibjck return n,the example simple wrapping c code cython describes nicely evaluate function written c array passed numpy return result numpy array how would one go thing returning d array ie i like evaluate c function grid defined two numpy arrays return result numpy d array it would something like using functions link obviously one use double z i sure pass d numpy array c fccpp int fc int n const double const double b double z int n int j j n j zij somefunctionaibj return n this original pyx file see import numpy np cimport numpy np cdef extern fch int fc int n double double b double z z b def fpy n npndarraynpdoubletndim a npndarraynpdoubletndim b npndarraynpdoubletndim z wrap np arrays fc adata assert n lena lenb lenz fcret fc n double adata double bdata double zdata return fcret many thanks,1 there different problems code let start fundamental people already commented relation sends recv control part data returned recvcall need kind protocol case could simple terminating command strings n checking n server consume data now problems you using send without checking return size send guarantee data completely written need please use sendall by using recv blocking socket default server code may wait bytes received allow process messages get full chunk need use non blocking socket select module,trying create gui client command line server however running annoying problems cant seem fix i sure actual problem sometimes code work times wont i think main problem originally tried selfdata srecv selfdata break else print selfdata then sending f files ssendf each f string filename i expected come recv side one file name recieved recv call instead one recv call got big chunk filenames assume chars worth which made impossible check end data thus loop never exited this code def getdataselfsize selfalldata gtkeventspending gtkmainiteration selfrecvdata selfsrecvsize selfalldata selfrecvdata selfalldatafindrnrneof print recieved end message selfrdata selfalldataselfalldatafindrnrneof break print all data recieved strlenselfrdata bytes print all data n selfrdata n selfinfiles selfrdataspliteos nf selfinfiles lennf selfaddmessageselfincomingiconnf at minute im trying get client read correctly server what want happen command list typed sent client server sends back data file appended list store times works ok times one files gets returned executes ok try type another command send whole gtk window geys program becomes unresponsive sorry cant explain question better ive tried alot different solutions give different errors someone could explain recv command may giving errors im sending data client ifcommands list whatpacketshouldlooklike print request list files address fil listfilespath f fil sdata f whatpacketshouldlooklike sdata eos newsocksendsdata eos print sent sdata newsocksendrnrneof whatpacketshouldlooklike rnrneof print print whatpacketshouldlooklike print,1 buf fread dupdatebuf updates hash sequentially first bytes values file since iterating bytes produces int objects get following calls cause error encountered python dupdate dupdate dupdate dupdate want instead want def mdsumfilename openfilename mode rb f hashlibmd true buf fread smaller typical filesystem block buf break dupdatebuf return dhexdigest,with python following code computes md hexdigest content file edit well really answers shown i thought import hashlib def mdsumfilename f openfilename mode rb hashlibmd buf fread dupdatebuf return dhexdigest now i run code using python raise typeerror exception dupdatebuf typeerror object supporting buffer api required i figured i could make code run python python changing def mdsumfilename f openfilename mode r hashlibmd buf fread dupdatebufencode return dhexdigest now i still wonder original code stopped working it seems opening file using binary mode modifier returns integers instead strings encoded bytes i say typebuf returns int is behavior explained somewhere,3 also used function parameter pass variable number keyword arguments function example def xkwargs key value kwargsitems print key value xy z b prints z b,i read following python code ab i know several languages like cccjava even googled operator without results b means,2 i think wanted forloop make successive calls fread that done using iter functoolspartial import hashlib functools import partial def mdsumfilename openfilename mode rb f hashlibmd buf iterpartialfread b dupdatebuf return dhexdigest printmdsum utilspy,with python following code computes md hexdigest content file edit well really answers shown i thought import hashlib def mdsumfilename f openfilename mode rb hashlibmd buf fread dupdatebuf return dhexdigest now i run code using python raise typeerror exception dupdatebuf typeerror object supporting buffer api required i figured i could make code run python python changing def mdsumfilename f openfilename mode r hashlibmd buf fread dupdatebufencode return dhexdigest now i still wonder original code stopped working it seems opening file using binary mode modifier returns integers instead strings encoded bytes i say typebuf returns int is behavior explained somewhere,3 to remove duplicates using largest key sort dictionary iterator value the call dict use last key inserted import operator inverted dictvk kv sortedditeritems keyoperatoritemgetter,i want know would efficient method invert dictionaries python i also want get rid duplicate values comparing keys choosing larger smaller assuming compared here inverting dictionary inverted dictvk kv ditems,3 a solution send specific message eg exit string sample via queue terminate workerchild process normal as ctrlc signal send children need ignored here sample code multiprocessing import process queue def startprocessqueue true try queueget exit print cleaning worker add cleaning code break else print except keyboardinterrupt print ignore ctrlc worker name main queue queue process processtargetstartprocess argsqueue processstart queueput try processjoin except keyboardinterrupt print wait worker cleanup queueput exit processjoin kill anyway worker terminated seconds processjoin processisalive processterminate,given python program commented code alternatives i tried work multiprocessing import process queue multiprocessing import process joinablequeue queue def startprocessqueue queuecanceljointhread true print queueget name main queue queue queuecanceljointhread process processtargetstartprocess argsqueue processstart queueput processjoin when i kill program ctrlc happens python queuetestpy ctraceback recent call last file queuetestpy line module processjoin file pythonmultiprocessingprocesspy line join res selfpopenwaittimeout process process file pythonmultiprocessingforkingpy line wait traceback recent call last return selfpoll file pythonmultiprocessingforkingpy line poll pid sts oswaitpidselfpid flag file pythonmultiprocessingprocesspy line bootstrap keyboardinterrupt selfrun file pythonmultiprocessingprocesspy line run selftargetselfargs selfkwargs file queuetestpy line startprocess print queueget file pythonmultiprocessingqueuespy line get res selfrecv keyboardinterrupt i properly terminate two processess signal what i want achieve in nonminimal program second process holds socketserver needs additional interactive command line interface,1 i finally changed code version i find easy understand asking question but i probably change version suggested raymond hetting unsing functoolspartial import hashlib def chunksfilename chunksize f openfilename mode rb buf let go lenbuf buf freadchunksize yield buf def mdsumfilename hashlibmd buf chunksfilename dupdatebuf return dhexdigest,with python following code computes md hexdigest content file edit well really answers shown i thought import hashlib def mdsumfilename f openfilename mode rb hashlibmd buf fread dupdatebuf return dhexdigest now i run code using python raise typeerror exception dupdatebuf typeerror object supporting buffer api required i figured i could make code run python python changing def mdsumfilename f openfilename mode r hashlibmd buf fread dupdatebufencode return dhexdigest now i still wonder original code stopped working it seems opening file using binary mode modifier returns integers instead strings encoded bytes i say typebuf returns int is behavior explained somewhere,1 check urllib getting html url beautifulsoup htmlparser etc parse html then could use something like starting point script import time import urllib import beautifulsoup import htmlparser def getsourceurl postdata source req urllibrequesturl postdata try sock urlliburlopenreq except urlliburlerror exc handle error pass else source sockread finally try sockclose except pass return source def parsesourcesource pass parse source beautifulsouphtmlparser def main lastrun true timetime check hour passed since lastrun lastrun source getsourcesomeurlcom usermeampblahfoo lastrun timetime parsesourcesource else sleep seconds check time timesleep return name main sysexitmain here good article parsinghtmlwithpython,currently game different groups play prize gold every hour sometimes gold sometimes it posted facebook every hour gold group gold group times post due gold prize hour i want write small script check site hourly grab result gold group display back i wanting write python i learning would best language use and would i go all i really find information extracting links i want extract links text thanks help i appreciate,1 sorry i think process call take arguments correctly c involved proof create new windows form application make sure main signature looks like static void mainstring args make sure call main form named form looks like argsnull applicationrunnew form else applicationrunnew formargs add textbox form multiline property set true add button form run application then put code buttonclick function replace thenameofthecurrentapp string command thenameofthecurrentapp string arguments textboxtext systemdiagnosticsprocessstartinfo start new systemdiagnosticsprocessstartinfocommand arguments startwindowstyle systemdiagnosticsprocesswindowstylemaximized startcreatenowindow true startuseshellexecute true systemdiagnosticsprocess process systemdiagnosticsprocessstartstart add constructor form public formstring args initializecomponent textboxtext stringjoin args then run app insert muliple lines textbox click button the app appear textbox correctly filled line breaks,env net visual studio sp win xp sp python corporate image admin rights in c i want pass parameter commandline program parameter contains newlines it works python c when body contains newline c truncates result python passes correctly python code cmd selfapppath email subject subject from addressfrom to addressto body body cmdresult subprocesspopencmd stdoutsubprocesspipecommunicate c code string command path executable string arguments email from fromaddress to toaddress subject subjectline body emailbody systemdiagnosticsprocessstartinfo start new systemdiagnosticsprocessstartinfocommand arguments startwindowstyle systemdiagnosticsprocesswindowstylehidden startcreatenowindow false startuseshellexecute true systemdiagnosticsprocess process systemdiagnosticsprocessstartstart any idea update body python example emailbody c example contain string strings represented language update noticed command terminated correctly python code i added end line the code ran also tell app called sends body emailbody parameter content email body,1 if run crawl recordcachefile scraper able use replay scraper alternatively cache responses httpcachemiddleware including downloadermiddlewares downloadermiddlewares scrapycontribdownloadermiddlewarehttpcachehttpcachemiddleware if every time run scraper check file system first,i started using scrapy scrape websites if i later add new field model change parsing functions i like able replay downloaded raw data offline scrape it looks like scrapy ability store raw data replay file one point httpdevscrapyorgbrowserscrapytrunkscrapycommandcommandsreplaypyrev but functionality seems removed current version scrapy is another way achieve,3 the contacts rest api pretty straightforward the url httpsocialyahooapiscomvuserguidcontactsjson here script extract things you expand include authentication import urllib import json def getcontactsguid url httpsocialyahooapiscomvusercontactsjson formatguid page urlliburlopenurl return jsonloadpage contacts contact,is official way import contacts user address book yahoo for google really simple import gdata contactsservice gdatacontactsservicecontactsservice contactsserviceemail email contactsservicepassword password contactsserviceprogrammaticlogin query gdatacontactsservicecontactsquery querymaxresults googlecontactsmaxresults entries contactsservicegetcontactsfeedquerytouri is simple way yahoo i found solutions use api looks strange serious game example contactgrabber i found solutions require bbauth token djangofriends app but i want official clear way grab user contacts yahoo does exists upd finally i avoiding use yahoo api using djangoopeninviter purposes but i still looking examples importing user contacts using api,2 according docs enforce uniqueness database level i think generally making field unique imply index though could also simply check db level index exists everything indicates though,a field model foo modelsforeignkeyfoo automatically add database index column order make lookups faster that good well django docs state whether fields modelmeta uniquetogether receive treatment i happen model one char field listed uniquetogether requires index quick lookups i know hurt anything add duplicate dbindextrue field definition i curious,1 django localemiddleware tries determine locale given request replaces languagecode accordingly it goes following steps checks session session variable called djangolanguage set language given locale session if existing goes checks cookies similar variable set define name it existing goes tries determine language httpacceptlanguage header if possible go at last use languagecode setting given locale in steps except check language given languages setting tuple tuples representing language code language title make sure setoverwrite default since default would tuple available django languages if multiple languages django site make sure session cookies set correctly you could use django internal view setting language djangoviewsinsetlanguage if got one language if spanish usually need bother just make sure languages languagecode set it attempt set pages language browsers language provided languages additionally make sure usein true that default though make least sure set false somewhere,i cannot get translations show templates here i done in template file indexhtml i loaded used trans tag i want translations in project directory i rand managepy makemessages l es my djangopo file conflocaleeslcmessagesdjangopo i edited file translations i ran managepy compilemessages i set languagecode es settingspy added djangomiddlewarelocalelocalemiddleware middlewareclasses sessionmiddleware commonmiddleware restarted django refreshed page only english representations still showing what i wrong did i miss something,1 this line typeerror queue object support indexing indicating dict variable type queue probably dont want double check lines make sure properly assigning dict variable properly also never use type name variable name dict type use name dictionary variable use mydict something similar its possible using dict variable name setting variable dict object instead assigning value dict variable see stdtypes info dict class heres problem sending tasks queue rules expecting iterable type list tasks multiprocessingqueue worker rulestasks xrangenumconsumers def rulesdict â â daycount dict â â dayvalue dict â â daycurrentcount dict â â daycurrentvalue dict,i getting weird error using queuesmultiprocessing i basically function takes list parses i many times i thought would good idea spread cores i i tried setup queue working here code establish communication queues tasks multiprocessingqueue start consumers numconsumers multiprocessingcpucount print creating consumers numconsumers worker rulestasks xrangenumconsumers w consumers wstart def loadgraphdaycurrent dayprevious daycurrentcount graphdaycurrent daycurrentvalue graphdaycurrentdaycurrentcount daycount graphdayprevious dayvalue graphdaypreviousdaycount rulesdatatopass daycount dayvalue daycurrentcount daycurrentvalue daycurrent dayprevious tasksputrulesdatatopass tasksclose tasksjointhread i sure i wrong without using queue works fine the problem function requires multiple variables runbefore i sending individually decided bunch together list i queue please help thanks advance update requested traceback traceback recent call last file userslostsouldropboxcodelearningpythongamepy line module xrangenumconsumers file userslostsouldropboxcodelearningpythongamepy line rules daycount dict typeerror queue object support indexing basically i sending data function i called rules dict parsed like daycount dictdayvalue dictetc i basically trying compare two dictionaries queue nested loop pairs every entry togetheradding queue i hoping get processed cpu sit works right individually takes min using one cpu update here rules function its simple basically takes values passes functionsits version rules engine def rulesdict daycount dict dayvalue dict daycurrentcount dict daycurrentvalue dict daycurrent dict dayprevious dict exactsamedaycount dayvalue daycurrentcount daycurrentvalue daycurrent dayprevious withinfivepercentchangedaycount dayvalue daycurrentcount daycurrentvalue daycurrent dayprevious deletenonedgenodesdaycurrentcount daycurrentvalue daycurrent without queue works fine,1 you couple problems code first chkifexists return ing soon finds existing file never checks remaining names also files found hashcolumn filepathnum never set giving unboundlocalerror second calling chkifexists two places removedupes cleanandprettify so removedupes run every existing file every existing file want in fact since cleanandprettify verified file exists removedupes go whatever handed there least three ways handle case files found chkifexists raise exception flag cleanandprettify tracks files found turn results chkifexists list check emptiness in modified code i moved files dictionary name key value tuple hashcolumn filepathnum chkifexists accepts filenames look dictionary yield values file found files found nofilesfound exception raised here code import os csv store file attributes easy modifications format filename hashcolumn filepathnum files acsv bcsv ccsv class nofilesfoundexception no csv files found clean def chkifexistssomefiles load three yield filename found filesfound false fname hashcolumn filepathnum somefilesitems ospathisfilefname filesfound true yield fname hashcolumn filepathnum filesfound raise nofilesfound def removedupesinfile outfile hashcolumn filepathnum singlerun function r fileinfile rb r csvreaderr w fileoutfile wb w csvwriterw hashes set row r rowhashcolumn wwriterowrow hashesaddrowhashcolumn rowhashcolumn hashes wwriterowrow hashesaddrowhashcolumn wclose rclose def bakcountorigfile origfile this function creates bak file original row count determine number rows removed osrenameorigfile origfilebak count lenopenorigfilebakreadlines print count osrenameorigfile origfile count lenopenorigfilereadlines print count print strcount count duplicate rows removed strorigfile def cleanandprettify print removing duplicate rows input files try fname hashcolumn filepathnum chkifexistsfiles removedupes fname ospathsplitextfname csv hashcolumn filepathnum bakcount fname ospathsplitextfname csv except nofilesfound print files clean cleanandprettify unable test i a b c csv files hopefully get pointed right direction as see raise nofilesfound option uses flag method keep track files found list method def chkifexistssomefiles load three yield filename found fname hashcolumn filepathnum somefilesitems ospathisfilefname filesfound true yield fname hashcolumn filepathnum def cleanandprettify print removing duplicate rows input files foundfiles listchkifexistsfiles foundfiles print files clean else fname hashcolumn filepathnum foundfiles removedupes bakcount,python noob please gentle in current program i list files may may reside current directory if reside directory i want able assign values later used functions if file reside directory assigned values file exist anyway the code i far import os csv def chkifexists files acsv bcsv ccsv fname files ospathisfilefname fname acsv hashcolumn filepathnum elif fname bcsv hashcolumn filepathnum elif fname ccsv hashcolumn filepathnum return fname hashcolumn filepathnum def removedupesinfile outfile hashcolumn fname hashcolumn filepathnum chkifexists r fileinfile rb r csvreaderr w fileoutfile wb w csvwriterw hashes set row r rowhashcolumn wwriterowrow hashesaddrowhashcolumn rowhashcolumn hashes wwriterowrow hashesaddrowhashcolumn wclose rclose def bakcountorigfile origfile this function creates bak file original row count determine number rows removed osrenameorigfile origfilebak count lenopenorigfilebakreadlines print count osrenameorigfile origfile count lenopenorigfilereadlines print count print strcount count duplicate rows removed strorigfile def cleanandprettify print removing duplicate rows input files fname hashcolumn filepathnum chkifexists removedupesfname ospathsplitextfname csv hashcolumn bakcount fname ospathsplitextfname csv cleanandprettify the problem i running code runs list stops first valid file finds i sure i completely thinking wrong way i thought i right current output program acsv bcsv ccsv present directory removing duplicate rows input files duplicate rows removed acsv the desired output removing duplicate rows input files duplicate rows removed acsv duplicate rows removed bcsv duplicate rows removed ccsv continue next portion creating bak files the output program without csv files directory unboundlocalerror local variable hashcolumn referenced assignment,1 as big comment i added response the question quite clear do mean ask use cairo drawing draw onto gtk widgets firstly nothing called gtk pixbuf i think referring gdk pixbuf most drawing stuff gtk done gdk layer if want find windowing drawing mechanism image manipulation look gdk details these links hopefully help get insight cairogdk interaction although experience python bindings gtk gdk amp cairo nil i think google provide good resources look gdkcairo sample hope helps least bit,for benefit possibly educational use i would like make pygamelike api python cairo but i want exactly pygame i would instead like make semistatic drawing platform display one images using gtkgdk i would like imitate excellent api principles tikz latex package the pygame api bad i satisfied one particular issue i would like package handle window refresh drawing everything pixbuf cairo automatically redraw pixbuf window uncovered that way end programmer worry window refresh in fact end programmer write single class function straight sequence lines code draw smiley face say the graphics library also maintain everlonger list stored shape objects case tkinter at least i hope cairo intentions i succeeded drawing various things pycairo output imagemagick postscript so i okay pycairo unfortunately cairogtkpycairopygtk documentation i found i know written at moment i project euler type programmer bleeding edge ultraobjectoriented apis type programmer i like see clear explanation andor clear example okay i accepted one answer posted least little helpful but nutshell real point the point gdk make temporary double buffer draw things gdk including using cairo it expected handle expose event redraw everything but complicated image slow process especially python so would much nicer cairo could write permanent double buffer rather temporary one permanent double buffer would exposed gdk several developers wanted solution problem one projects seems kind solution google chromium ever noticed great window exposure google chrome instance linux so i look chromium source code see i easily addendum i see i confuse issue referring specifically pixbufs i really care pixbufs i changed question title what i really care creating permanent double buffer pixel array cairo gtkgdk instead temporary double buffer pixel array it seems easiest way make gtk window cairo surface make double buffer another cairo surface since i asked sample question class canvasgtkdrawingarea def initself supercanvas selfinit selfconnectexposeevent selfexpose selfsetsizerequestwidthheight def exposeself widget event cr widgetwindowcairocreate crsetsourcesurfacemybuffer crpaint another tricky issue quickly arose i wanted wysiswyg drawing environment immediately draws python asks draw extended animations however gtk examples set way event handling postponed i either call gtkmain or python i surprised discover rawinput also somehow flushes gtk event queue i found nice explanation python examples alternatives giving away event control gtk the simplest solution possibly one i adopt use flush event buffer whenever want gtkeventspending gtkmainiterationfalse there one final thing i need flush pixel buffer well event buffer it looks like one way windowqueuedraw,1 ospathsplit in fullpath dirblahdogtldr in ospathsplitfullpath out dirblah dogtldr in ospathsplitfullpath out dogtldr,i code filename tkfiledialogaskopenfilenameinitialdirlistscustom filetypesword list tldr all files if i file called dogtldr way get file name instead directory front right filename outputs something like dirblahdogtldr but i want dogtldr is way thanks,1 i sqlite user take grain salt rdbm support ansi standard informationschema views if run following query select from informationschemacolumns where tablename table you get table lists columns specified table it may take tweaking get output want hopefully start,i want get list column names table database using pragma i get list tuples lot unneeded information is way get column names so i might end something like column column column column the reason i absolutely need list i want search column name list get index index used lot code is way getting list like thanks,1 your big mistake need include readlines iterate inf openinfile mode r inf openoutfile mode w outf line infreadlines however whole section code probably tidied quite bit openinfile mode r inf openoutfile mode w outf lines line line infreadlines line enumeratelines read line data linesireplace split try datasplit chr b data c datasplit outfwrite n formata b c except indexerror pass,this code established previous post i trying adapt fit data but work here example file read tgacca tgacca chr line chr chr concordant read tgacca tgacca chr line this code following search line recognize string read go next line extract looks like chrnumbernumber then search next read etc so i chr nono multiple times read would take st one unfortunately i cannot figure get work import infile myfiletxt outfile outfiletxt pat recompiler read pat recompiler chrdd openinfile mode r inf openoutfile mode w outf line infreadlines linerstrip continue patsearchline patsearchline outfwrite joinmgroups n continue the output look like somebody throw bone please updated from answer below alright i uploading slightly modified version tim mcnamara i use it works well output recognize number two digit chr prints string last number openinfile mode r inf openoutfile mode w outf lines line line infreadlines line enumeratelines read line data linesireplace split try outfwrite n formatdata data data here i tried remove data avoid start output file work except indexerror continue here output obtained code start start string data number start i understand grabs thou start i tried modify code avoid work start start start how i fix two errors,1 as far i tell sqlite support informationschema instead sqlitemaster i think get list want one command you get information need using sql pragma use regex split format need select sql from sqlitemaster where name tablename gives something like create table tablename col integer primary key autoincrement not null col nvarchar not null col nvarchar not null or using pragma pragma tableinfotablename gives something like colinteger colnvarchar colnvarchar,i want get list column names table database using pragma i get list tuples lot unneeded information is way get column names so i might end something like column column column column the reason i absolutely need list i want search column name list get index index used lot code is way getting list like thanks,3 python native json support since via json module previous versions use external libraries simplejson common,just getting started python first goal create web service i plan using werkzeug however i writing client interface how would i go exchanging objects systems is anything similar json python edit a couple mentions json main problem i serialize class i sort thought json could class user def initself first last age selffirst first selflast last selfage age user userjohn doe jsondumpsuser typeerror mainuser instance xabbee json serializable i know serializing json necessarily class object still reference almost var mailingaddress address anywhere st city springfield postalcode alertthe package shipped postal code mailingaddresspostalcode,2 you use sqlite pep import sqlite connection sqliteconnect foosqlite cursor connectionexecute select bar cursordescription description columns names listmaplambda x x cursordescription alternatively could use list comprehension names description description cursordescription,i want get list column names table database using pragma i get list tuples lot unneeded information is way get column names so i might end something like column column column column the reason i absolutely need list i want search column name list get index index used lot code is way getting list like thanks,3 one logger multiple handlers achieve easily example import logging logger logginggetlogger myapp hdlr loggingfilehandler varmyapplog hdlr loggingfilehandler varmyapplog formatter loggingformatter asctimes levelnames messages hdlrsetformatterformatter hdlrsetformatterformatter loggeraddhandlerhdlr loggeraddhandlerhdlr loggersetlevellogginginfo loggerinfo log message,how i log file well wxpython txt ctrl background i wxpython gui based application enumerates python test files executes with help httpbroadcoderblogspotcomredirectingpythonloggingtohtml i able redirect python logging messages txtctrl however i also like redirect logging messages log files also i import testfiles like logginginfo started testid importstr reloadtestid testout testidmain in testfiles i simply use import logging logging messages get redirected txt ctrl however i would also like test log messages also redirected log file based name file how i redirect log messages if i use loggingbasicconfig test file messages still directed text ctrl my testguipy i import say python test files in test file files i simply use import logging i setup logger testguipy file selflogr logginggetlogger selflogrsetlevellogginginfo hdlr wxlogselflog hdlrsetformatterloggingformatter messages selflograddhandlerhdlr in test file i something like logger logginggetlogger fh loggingfilehandlerloghtmlmode w formatter loggingformatter messages fhsetformatterformatter loggeraddhandlerfh b logginginfo logginginfo b c ab logginginfo adding b c fhclose i get valueerror io operation closed file i run test,3 this scoping issue you misconstructed dataset causing composed two sets references list dataset x range x range,in following code i print row first loop bunch manipulations i see results i want however i exit first loop i find i get different result variable dataset i know scoping issue i cannot figure problem get desired result shown first print statement thanks help import random randomseed key datasetint int print results i need row dataset responserow xrangelenkey randomrandom keyiresponse rowiresponse else rowiresponse print row print results i get row dataset print row,1 python reference semantics your original dataset contains multiple references common sublists i also loss understand making initialization complex you could fix using xrange xrange the rest logic also needlessly complex we use conditional expression merge two assignments together using direct iteration instead iterating artificial list indices xrange that looks like row dataset response row k key rowi response randomrandom kresponse else response however still solution looking there really reason put zeros initialization data overwritten never read loop the indexing also clumsy a simpler solution start list first values sublists within loop construct rest sublist list comprehension prepend first element instead replacing elements dataset place use another list comprehension bind together that gives us import random randomseed key initialconditionsint int dataset randomrandom ki else k key initialconditions,in following code i print row first loop bunch manipulations i see results i want however i exit first loop i find i get different result variable dataset i know scoping issue i cannot figure problem get desired result shown first print statement thanks help import random randomseed key datasetint int print results i need row dataset responserow xrangelenkey randomrandom keyiresponse rowiresponse else rowiresponse print row print results i get row dataset print row,2 sounds like looking use pickle instead json pickles python specific handle user classes well dicts class user def initself first last age selffirst first selflast last selfage age user userjohn doe import pickle pickledumpsuser del user user pickleloadss reconstruct object print varsuser age last doe first john if need variant language independent look pyyaml yaml spec httpyamlorg,just getting started python first goal create web service i plan using werkzeug however i writing client interface how would i go exchanging objects systems is anything similar json python edit a couple mentions json main problem i serialize class i sort thought json could class user def initself first last age selffirst first selflast last selfage age user userjohn doe jsondumpsuser typeerror mainuser instance xabbee json serializable i know serializing json necessarily class object still reference almost var mailingaddress address anywhere st city springfield postalcode alertthe package shipped postal code mailingaddresspostalcode,1 you think completion key per connection data extended overlapped structure per io operation some people use extended overlapped structure both store information need extended overlapped structure i always stored reference counted object wraps socket completion key reference counted data buffer extended overlapped structure if interested see example iocp code c the completion key effectively opaque handle data io completion system give back completion occurs socket,i writing io completion port based server source code using windows dll api python using ctypes module but pretty direct usage api question directed knowledge iocp python as i understand documentation createiocompletionport specify user defined completion key call function file handle case socket associating created iocp when get around calling getqueuedcompletionstatus get completion key value along pointer overlapped object the completion key identify overlapped object request completed however let say i pass completion key createiocompletionport call overlapped object when overlapped object io completed arrives back getqueuedcompletionstatus completion key accompanies much larger bares resemblance original value am i misunderstanding completion key works must i wrong source code i linked,1 does python jython need installed task tracker node yes since executed task trackers do python jython modules need installed task tracker node if using rd party module installed task trackers well like geoip etc do task tracker nodes need know find modules if specify path via environment variable done task tracker as answer book programming pig register also used locate resources python udfs use pig latin scripts in case register jar rather python script contains udf the python script must current directory and also one important a caveat pig trace dependencies inside python scripts send needed python modules hadoop cluster you required make sure modules need reside task nodes cluster pythonpath environment variable set nodes udfs able find import this issue fixed writing yet released and using jython pig know system jython interpreter must include jythonjar classpath invoking pig this done setting pigclasspath environment variable as summary using streaming use ship command pig would send executable files cluster using udf long compiledcheck note jython rd party dependency already put pythonpath installed cluster udf would shipped cluster executed as tip would make life much easier put simple udf dependencies folder pig script registering hope would clear things,i using pig udfs written python the python scripts import modules standard python library i able run pig scrips call python udfs successfully local mode i run cluster appears pig generated hadoop job unable find imported modules what needs done for example does python jython need installed task tracker node do python jython modules need installed task tracker node do task tracker nodes need know find modules if specify path via environment variable done task tracker,3 it since i used kinterbasdb far i know able query command also used insert update delete ie nothing produces resultset so connectionexecuteimmediate cursorexecute work did actually try btw with firebird advisable mix ddl dml one transaction edit i realised might meant full ddl script multiple statements mean cannot need execute statement individually you might able use execute block statement may need modify script much would easier simply try split actual script individual statements,is way execute ddl script python kinterbasdb library firebird database basically i like replicate isql myscriptsql command,1 far simpler fact using metaclass classmethod turns needed class mysqlconstants decimal tiny short long float double def createdict dicforreversing fieldtypedic key value dicforreversingitems isinstancevalue int fieldtypedic value key return fieldtypedic fieldtypedic createdict vars thanks ethan furman particular showing things made happen creation class nb anticipate multiple values keys case mysqldb constants best way handle might follows enum char tiny interval enum def createdict dicforreversing fieldtypedic key value dicforreversingitems isinstancevalue int value fieldtypedic fieldtypedic value set fieldtypedic value add key return fieldtypedic fieldtypedic createdict vars,bit surprised find answer one realworld reason asking i dictionary constants class class mysqlconstants decimal tiny short long float double etc i want dictionary i find constant given number easy enough fieldtypedic fieldtype dir mysqlconstants value getattr mysqlconstants fieldtype fieldtypedic value fieldtype would easy enough make static method mysqlconstants call going mysqlconstantscreatedic class definition statement executed i wondering whether way get method inevitably static run class nb i talking creating instance class created,1 after looking source experimenting sphinx in confpy file create new methoddocumenter subclass here set new objtype make sure docstring indented remove title sphinxext import autodoc class simpledocumenterautodocmethoddocumenter objtype simple indent content contentindent add header docstring def adddirectiveheaderself sig pass then make sure added available documenters following function confpy def setupapp appaddautodocumentersimpledocumenter then want display method docstring use following format txt rst files just prefix objname auto autosimple modmyclassmymethod,i like include docstring specific function sphinx documentation however seem options display details without associated class function definitions using httpsphinxpocooorgextautodochtml i tried creating class outlined show docstring sphinx documentation i sure fits templating i also tried autodocprocessdocstring event handler luck so rather documentation displaying currently class modulemyclassparam this class doc string mymethod this method doc string i want display this method doc string my current template txt file autoclass modulemyclass members mymethod,3 below petr viktorin points problem original answer initial solution warning the values dictionary particular order if solution works n really returned order coincidence if use different version python create dicts different way might break i kind mortified i pick first place got rep use eryksun suggestion instead items somem split n dl my original incorrect answer don use unless list ordereddict items someasplit n adn mvalues dl,i list dict need convert list namedtuple preferred simple tuple split first variable whitespace what pythonic way i simplified code little comprehensions gen expressions itertools usage welcomed datain dl n first n second n third n forth simple algorithm collections import namedtuple namedtuple n items dl n mvalues asplit itemsappendsomea n output somea n first somea n second somea n third somea n forth,3 if using template absolutely required willing recreate template code use reportlab python generate pdf print see example make tables httpwwwblogpythonlibraryorgreportlabtablescreatingtablesinpdfswithpython also check invoice example httpsgithubcomradzhomefedexcommercialinvoice,i need allow users edit print clientrelated documents invoices another user fill print form select clients month much copies types documents heshe needs click print button next system algorithm result create new wordfriendly file user may manually edit later client formclients snapshot select row snapshots table client client month formmonth document generatefromtemplatesnapshot tpldocx formhowmuchcopiesoftypeofdocumentheorsheneeds result document document generatefromtemplatesnapshot tpldocx formhowmuchcopiesoftypeofdocumentheorsheneeds result document document generatefromtemplatesnapshot tpldocx formhowmuchcopiesoftypeofdocumentheorsheneeds result document document generatefromtemplatesnapshot tpldocx formhowmuchcopiesoftypeofdocumentheorsheneeds result document print result requirements ability edit result need wordfrindly format page breaks every document new page tables simple look invoice tpl example fontsize style bold example save text position my question generate file result there httpsgithubcommikemaccanapythondocx project sure work templates least generate tables i need or i save docx templates html use normal django templates sure combine together document create page breaks or may look another wordcompatible file formats ps better use python critical may use javaperlrubyphpbashetc install new ubuntucompatible packages,2 the frameinit needs passed parent class mytestframe tkframe tkframeinitself parent args kwargs runnable example import sys import tkinter tk etke wtkw ntkn stks def main app app appmastertitlesample application appmainloop class apptkframe def initself masternone tkframeinitself master selfgridstickynsew top selfwinfotoplevel toprowconfigure weight topcolumnconfigure weight selfrowconfigure weight selfcolumnconfigure weight selfcreatewidgets def createwidgetsself selff tkframeself height width bg green selffgridrow stickyew selff mytestframeself bg yellow height width selff tkframe self bg cyan height width selffgridrow stickyew selfquitbutton tkbuttonself textquit commandselfquit selfquitbuttongridrow column stickyew class mytestframe tkframe def initself parent cnf kw tkframeinitself parent cnf kw selfgridrow stickynsew selfrowconfigure weight selfcolumnconfigure weight selfmytext tktextself selfmytextgridrow stickynsew name main main,i problem either tkinter grid geometry manager custom classes most likely here code import sys tkinter import def main app app appmastertitlesample application appmainloop class appframe def initself masternone frameinitself master selfgridstickynsew top selfwinfotoplevel toprowconfigure weight topcolumnconfigure weight selfrowconfigure weight selfcolumnconfigure weight selfcreatewidgets def createwidgetsself selff frameself height width bg green selffgridrow column stickyew selff frame self bg yellow height width change selff mytestframe self selffgridrow sticky nsew selff frame self bg cyan height width selffgridrow sticky ew selfquitbutton button self textquit commandselfquit selfquitbuttongridrow column columnspan stickyew class mytestframe frame def init self parent frameinitself none selfmytext text self selfmytextgrid selftestframe frame self bg white height width selftestframegrid name main main now problem this piece code everything i want there three frames top frame selff middle frame selff bottom frame selff simple quit button top row bottom row frames resize horizontally column middle frame row row column receives weight resizing horizontally vertically everything good until i try implement class mytestframe whenever i try populate custom frame selff say text widget things go haywire it displays default text widget resizing goes funky grid placement crazy what going edit unutbu answer certainly helps class issue now grid manager placing text widget correctly inside middle frame selff however even i set sticky mytextgridsticky nsew expand correctly so i thought following by setting root window resizable def init constructor class app i set first row zeroth column app window would receive space allotment resizing selfrowconfigure weight selfcolumnconfigure weight now frame selff placed row receive resizing selffgridnsew now i populate custom frame text widget set occupy all space frame stating selfmytextgrid sticky nsew but text widget filling selff when i normally without custom class using sticky nsew attribute works correctly am i thinking correctly,2 you could simply defining class model form view local scope create instance directly you need make sure receive class model according name use django getmodel function simple example def myviewrequest modelname myappmymodel make sure app name also provided djangodbmodels import getmodel modelclass getmodelmodelnamesplit class mymodelformmodelform class meta model modelclass attributes form form mymodelform,i trying create generic views models i stuck creating modelform dynamically it way creating modelform model name string,2 it quite easy python b c aex bex cex zip elem elem col else none col b c elem setaunionb c seems direct worried speed i also noticed answer joining multiple iteratorars key sort applies def paditersargs iters iterx x args nexti iters true try key mini none except valueerror break val enumeratethis val key yield val thisi nextitersi none else yield none padded listpaditersa b c nextitem iterpaddednext print zipnextitem nextitem nextitem rangelenpadded you adapt need performance scale linearly,example table a b c i would like somehow temper gnumeric produce matching cells across columns a b c real example string values instead numbers easier explain numbers i think if trivial someone idea done python lists instead table columns gnumeric please post python solution,1 on linux use filesystem monitoring daemon like incron run command eg make tests every time file changed directory socalled inclosewrite event,i use cxxtest unittesting c code i would like time i change save code tests run simply make tests i know python nosy enables is generic program would allow cxxtest testing unit simply i need running single command files change it difficult write script like maybe tool already,1 if find needing search particular entities within commaseparated field probably consider whether correct format data perhaps foreign key separate table might appropriate,i model class comma separated integer field maps postgres integer array field class observationmodelsmodel frequencies modelscommaseparatedintegerfieldmaxlength what i want able use filter something else suitable interface comparison indexed value array example observationobjectsfilterfrequenciesequals i know i i see documentation index array field filter interface i want action performed sql database may code i know i use extra feature i want know better way thanks,1 since recursing subdirectories use oswalk import os def scandirspath root dirs files oswalkpath currentfile files print processing file currentfile exts png jpg anycurrentfilelowerendswithext ext exts osremoveospathjoinroot currentfile,i fairly new python i gotten code work fact intended however i wondering efficient way code perhaps enhance processing speed import os glob def scandirspath currentfile globglob ospathjoinpath ospathisdircurrentfile print got directory currentfile scandirscurrentfile print processing file currentfile png png jpg jpg currentfileendswithpng currentfileendswithjpg osremovecurrentfile scandirs cprogram files xmusicsongs right files takes quite time process every file check indeed ends png jpg,3 if program works speed acceptable i change otherwise could try unutbu answer generally i would leave away png png jpg jpg stuff i see purpose using strings directly and better test png instead png an even better solution would define extensions png jpg somewhere centally use anycurrentfileendswithext ext extensions osremovecurrentfile,i fairly new python i gotten code work fact intended however i wondering efficient way code perhaps enhance processing speed import os glob def scandirspath currentfile globglob ospathjoinpath ospathisdircurrentfile print got directory currentfile scandirscurrentfile print processing file currentfile png png jpg jpg currentfileendswithpng currentfileendswithjpg osremovecurrentfile scandirs cprogram files xmusicsongs right files takes quite time process every file check indeed ends png jpg,1 another option sure whether better worse others class somenamedtuple n def newcls args args args split return supersome clsnewcls args items listsomem dl btw i absolutely committed giving base class name subclass i like means resulting class converts string using name never particularly caused problems potentially could confusing debugging class names so care or idea using different tricks namedtuple n def makesomeargs args argscopy args args split return someargs items mapmakesome dl nb return list python,i list dict need convert list namedtuple preferred simple tuple split first variable whitespace what pythonic way i simplified code little comprehensions gen expressions itertools usage welcomed datain dl n first n second n third n forth simple algorithm collections import namedtuple namedtuple n items dl n mvalues asplit itemsappendsomea n output somea n first somea n second somea n third somea n forth,2 you could use teamcity it monitor code repository run automated builds unit tests changes detected includes decent web style interface emailing capability notify buildtest failures it also configured windows linux builds httpwwwjetbrainscomteamcity if thats bit heavyweight able configure build process run tests eg edit makefile linux obviously would still mean manually kicking build make changes i guess probably anyway,i use cxxtest unittesting c code i would like time i change save code tests run simply make tests i know python nosy enables is generic program would allow cxxtest testing unit simply i need running single command files change it difficult write script like maybe tool already,1 the duration equal number frames divided framerate frames per second import wave import contextlib fname tmptestwav contextlibclosingwaveopenfname r f frames fgetnframes rate fgetframerate duration frames floatrate printduration regarding edwards comment code produce channel wave file import math import wave import struct filename tmptestwav freq datasize frate amp nchannels sampwidth framerate intfrate nframes datasize comptype none compname compressed data mathsin mathpi freq x frate mathcos mathpi freq x frate x rangedatasize try wavfile waveopenfilename w wavfilesetparams nchannels sampwidth framerate nframes comptype compname values data v values wavfilewriteframesstructpack h intv amp finally wavfileclose if play resultant file audio player find seconds duration if run code also computes duration seconds so i believe number frames influenced number channels formula correct,i looking way find duration audio file wav python so far look python wave library mutagen pymedia pymad able get duration wav file pymad gave duration consistent thanks advance,3 this might trick www ww describes structure want problem also matches empty string thus assure least one nonspace character start get matched greedy operators lookahead start edit wrong paste,i looking regexp returns three matched groups string a b cd abcd words examples w the following python code prints unwanted nonenone i want a none none b c d using one regexp no added python code filtering recompiler ww finditer a b cd print mgroups,2 in addition answer provided detly know fields dicts hand construct namedtuple class namedtuple setk k dkeys dl,i list dict need convert list namedtuple preferred simple tuple split first variable whitespace what pythonic way i simplified code little comprehensions gen expressions itertools usage welcomed datain dl n first n second n third n forth simple algorithm collections import namedtuple namedtuple n items dl n mvalues asplit itemsappendsomea n output somea n first somea n second somea n third somea n forth,1 the best solution i found using pandas handles joins well pandas objects convert tofrom numpy arrays easily,suppose i two arrays import numpy np anparray b dtypeobject bnparray b c dtypeobject how i get cnparray none b c nonedtypeobject basically join using first column key thanks,1 i similar query recently i hoping using f objects i think possible timedelta relies db column would possible scheduleintervalseconds constant in end i query using orm extra wrote sql clause sql dateaddlastchecktimestamp interval scheduleintervalseconds second datenow tasksobjectsfilterqlastchecktimestampisnulltrue qlastchecktimestamp datetimetimedeltasecondsscheduleintervalseconds tasks taskobjectselectrelated schedule extrawheresql this uses dateadd function mysql docs you may need adjust different flavours sql the selectrelated required django join schedule table the select tasks lastchecktimestamp null i think use combine extra q object expand sql statement sql lastchecktimestamp null dateaddlastchecktimestamp interval scheduleintervalseconds second datenow,i simple model describe task period executions task class taskmodelsmodel lastchecktimestamp modelsdatetimefieldblanktrue nulltrue dbindextrue class taskschedulemodelsmodel task modelsonetoonefieldtask blankfalse nullfalse relatedname schedule intervalseconds modelsintegerfieldblankfalse nullfalse i want able query using django orm tasks fresh stale meaning due run according schedule i currently calculating specific record without orm via import datetime task taskobjectsgetid fresh tasklastchecktimestamp none datetimedatetimenow tasklastchecktimestamp datetimetimedeltasecondstaskscheduleintervalseconds how would i equivalent django orm i could query freshstale tasks eg this obviously work something like tasksobjectsfilterqlastchecktimestampisnulltrue qlastchecktimestamp datetimetimedeltasecondsscheduleintervalseconds,2 mysqlpython nothing special encodes argument prevent sql injections uses standard python operator replace placeholders encoded arguments if really want see result run code cursorexecute mysqldbconverters import getcodec def preparesqlcursor query argsnone args none query query tuple getcodeca cursorencodersdb args return query see definition execute starting line mysqldbcursorspy,i would like verify mysql string translated cursor cursorexecuteselect elements id elementid is way get computed sql string print preferably execution latter absolutely necessary i i learning python want make sure sql strings sanitized,1 if uniquetogether add index multiple column index if want one columns indexed individually i believe need specify dbindextrue field definition,a field model foo modelsforeignkeyfoo automatically add database index column order make lookups faster that good well django docs state whether fields modelmeta uniquetogether receive treatment i happen model one char field listed uniquetogether requires index quick lookups i know hurt anything add duplicate dbindextrue field definition i curious,3 i found something else i using mac address linux machineguid windows also something mac more details httpwwwserialsensecombloggeneratinguniquemachineids,i like get id unique computer python windows linux it could cpu id motherboard serial anything else i looked several modules pycpuid psi without luck any idea,1 yes as ferdinand pointed mysqldbcursorspy containing execute turn calls query this puts executed query selfexecuted so get cursorexecuted,i would like verify mysql string translated cursor cursorexecuteselect elements id elementid is way get computed sql string print preferably execution latter absolutely necessary i i learning python want make sure sql strings sanitized,3 one way get list identifiers python expression use ast module import ast class identifierextractorastnodevisitor def initself selfids set def visitnameself node selfidsaddnodeid extractor identifierextractor extractorvisitastparsecospix beta print extractorids prints set x cos pi beta you could also exclude names defined math module namespace print extractorids setvarsmath prints set beta x note i still clue might useful,matlab function called symvar takes string expression usually containing valid matlab instructions identifies variables these handledreplaced order evaluate expression for example symvar cospix beta returns beta x is similar functionality python here example i would use say i dataframe df case i referring pandas module i guess also applies numpy recordarray containing set variables eg abc i want user able add additional column specifying something like addfielddfdlogac internally function would recognize a c d variables extract a d dataframe perform calculation using eval similar add d new column dataframe thanks,2 the following snippet want import xmletree import elementtree open filmsxml f xml elementtreeparsef xmlfindall httpwwwmediawikiorgxmlexporttext print researchr sinfobox film ttext print mgroup the regular expression begins turns dotall option meaning matches newlines well character the two instances nongreedy matches charcter ie find shortest stretch zero characters rest expression matched,i using etree module i trying extract information around text tag here xml file i want text infobox film start infobox film copy text is possible thanks update xml file updated,1 you write custom templatetag register you take inspiration django load templatetag the problem would would also wrap loaded templatetags ifs one way around would register dummy functions nothing maybe log something fail silently code works even better create extra ifmoduleloaded module skips code inside depends use case,i working django app provides templates optional functionality certain apps available it possible load unavailable template tag library using standard load django tag trying results templatesyntaxerror has anyone come solution problem ie conditional tag lib loader i something like loadifavailable apptags ifloaded apptags endif,1 needed convert answers radians back degrees working code import math r radius earth brng bearing degrees converted radians distance km lat lat result i hoping lon long result i hoping lat mathradians current lat point converted radians lon mathradians current long point converted radians lat mathasin mathsinlatmathcosdr mathcoslatmathsindrmathcosbrng lon lon mathatanmathsinbrngmathsindrmathcoslat mathcosdrmathsinlatmathsinlat lat mathdegreeslat lon mathdegreeslon printlat printlon,given existing point latlong distance km bearing degrees converted radians i would like calculate new latlong this site crops i get formula work the formulas taken link lat asinsinlatcosdr coslatsindrcosî¸ lon lon atansinî¸sindrcoslat cosdr−sinlatsinlat the formula msexcel asin arc sin distance unit r radius earth unit hence dr angular distance radians atanab arc tanba î¸ bearing radians clockwise north here code i got python import math r radius earth brng bearing degrees converted radians distance km lat lat result i hoping lon long result i hoping lat mathpi current lat point converted radians lon mathpi current long point converted radians lat mathasin mathsinlatmathcosdr mathcoslatmathsindrmathcosbrng lon lon mathatanmathsinbrngmathsindrmathcoslat mathcosdrmathsinlatmathsinlat printlat printlon i get lat lon,3 if must use null modem built serial line networking support then use normal network methods psexec file share etc methods update,i vb application running number old windows machines sometimes application upgraded the way accomplish today use hyperterminal send file null modem cable replacing machines option point i want write application take care transferring updating app null modem without rewriting vb app this means i free use anything i see fit what alternatives these ones i think i like know i wrong proscons also i prefer avoid cc possible python pyexe another vb app cc edit some clarifications reading comments i want make process easy possible today remove dismantle computer connect keyboard fire hyperterminal get going that i want something automatic i open suggestion existing solutions given specific needs i think there ethernet computers either solution needs able run rs and replacing machines option point just trust,2 not admin ui modify url make filtering criterion complex for instance url click filter probably ends something like statusexacta you change statusinacm order see statuses the c encodes comma,currently filter option django admin interface for instance lets say filter by status is possible select multiple statuses filter results here screenshot filter can select multiple items list,3 as michael j barber suggested comments answer code uses groupby imap itertools module imap applies len function every list groupby gropes values chunks lengths so one chunk length lengths different if one chuck lengths means lengths lists second access groupby iterator yield stopiteration thus returning none default value next function the great benefit code imap groupby written c pretty fast itertools import imapgroupby dct b c dct b c def checklenghtsiterable groupbyimapleniterableitervalues nextitnone return true nextitnonenone else false printchecklenghtsdct printchecklenghtsdct,i dict containing lists keys dct b c what best way recognize whether length lists this solution import itertools lensetitertoolsimaplen dctviewvalues true similar false upd in reference raymondhettinger advice replace map itertoolsimap,1 you indeed getobject method like class yourviewdetailview queryset yourmodelobjectsall def getobjectself object superyourview selfgetobject objectviews objectviews objectsave return object,i generic listview item html list links detailview now i like increment mymodeldetailview object viewsfield integerfield click all i seem hand detailview getcontextdata so i update model action nb thinking loud middleware functionality edit ok seems i getobject getqueryset available empty print kwargs also updating integer field context data seems ugly unwanted runs times one click etc,1 for everything regions thing use numpy something like untested import numpy np npfromfilefile a dtypeuint b npfromfilefile b dtypeuint compute number bytes different differentbytes npsuma b compute sum differences difference npsuma b compute sum absolute value differences absolutedifference npsumnpabsa b in cases number bits changed better measurement change to compute make lookup array bitcountlookupbyte numberofbitsinbyte bitcountlookup bitcountlookup nparray binicount range dtypeuint numpy allows using array index computes xor pair bytes the result byte bit bits input differed bit otherwise bitdiffcount npsumbitcountlookupa b i find numpy function computing regions write using b input hard see question inspiration,usually order find two binary files different i use diff hexdump tools but situations two large binary files size given i would like see quantitative differences like number regions differences cumulative difference example files a b they diff regions cumulative difference ca c fe file a c c f c file b e c reg reg how i get information using standard gnu tools bash i better use simple python script other statistics files different also useful i know else measured entropy difference variance difference,1 you always put subclassa imports package initpy showed second listing then available directly package wrote first listing,i building project i run following problem i implemented several subclasses lines code semantically go together module i want import mymodule import subclassa subclassb but module file thousands lines makes maintaining code pretty nasty now i class separate file make easier maintain i use like subclassa import subclassa subclassb import subclassb make sense really awful is elegant solution if aforementioned better solution,3 i prefer second solution separate files the imports awful if bother much could encapsulate yet another file import classes secondhand file so main import would look like first solution sole contents mymodule file would code second solution,i building project i run following problem i implemented several subclasses lines code semantically go together module i want import mymodule import subclassa subclassb but module file thousands lines makes maintaining code pretty nasty now i class separate file make easier maintain i use like subclassa import subclassa subclassb import subclassb make sense really awful is elegant solution if aforementioned better solution,1 try threads threadingthreadtargetmyfunc rangen threads tstart threads tjoin threads list threadingthread instances this cause main thread wait worker threads done,i using ipython develop multithreaded socket based clientserver type thing the problem ipython tries give command prompt prompt threads finished running the debug text output thread lost is way ipython give new prompt threads finished running thanks,1 a busy loop right approach since obviously wastes cpu there threading constructs let communicate events instead see example httpdocspythonorglibrarythreadinghtmleventobjects,i python script opens websocket twitter api waits when event passed script via amq i need open new websocket connection immediately close old one soon new connection registered it looks something like stream twitterstream streamstart message brokerlisten message newstream twitterstream need close old connection soon new one connects somehow stream newstream i trying figure i establish callback order notify script new connection established the twitterstream class isrunning boolean variable i reference i thinking perhaps something like newstreamisrunning timesleep but seems kind messy does anyone know better way achieve,2 for future reference must better way somehow shot coding utf import whoosh whooshindex import createin whooshfields import whooshquery import whooshqparser import queryparser schema schemanametextstoredtrue idx createincidxname schema idxname writer idxwriter writeradddocumentnameuthis craaazy shit writeradddocumentnameuthis craaazy beer writeradddocumentnameuraphaã«l rocks writeradddocumentnameurockies mountains writercommit idxsearcher print fields listslexiconname qp queryparsername schemaschema termclassfuzzyterm range res ssearchfuzzytermname rocks maxdisti prefixlength lenres r res print potential match rname break else print pass sclose,i built large database banks mongodb i easily take information create indexes whoosh for example i like able match bank names eagle bank amp trust co missouri eagle bank trust company missouri the following code works simple fuzzy cannot achieve match whooshindex import createin whooshfields import schema schemanametextstoredtrue ix createinindexdir schema writer ixwriter testitems ueagle bank trust company missouri writeradddocumentnameitem writercommit whooshqparser import queryparser whooshquery import fuzzyterm ixsearcher qp queryparsername schemaixschema termclassfuzzyterm q qpparseueagle bank amp trust co missouri results ssearchq print results gives top results andfuzzyterm name u eagle boost minsimilarity prefixlength fuzzyterm name u bank boost minsimilarity prefixlength fuzzyterm name u trust boost minsimilarity prefixlength fuzzyterm name u co boost minsimilarity prefixlength fuzzyterm name u missouri boost minsimilarity prefixlength runtime is possible achieve i want whoosh if python based solutions i,1 the error seeing seems indicate transport framed twisted needs know length message beforehand also thrift servers support returning deferreds handlers even strange have tried returning defersucceedsome value see deferreds actually work you move check fully works deferdeferred reactorcalllater dcallback results return,i twistedthrift server uses ttwisted protocol i want keep connections clients open given event happens i notified event twisted reactor via callback class servicehandlerobject interfaceimplementsserviceiface def listenforeventself a method defined thrift interface block thrift response event interest occurs i need somehow return immediately free reactor thread i want thrift call considered completed the current request needs marked waiting somehow def handleeventself a method called event interest occurs it callback method registered twisted reactor find waiting requests notify event occurred this cause thrift requests complete how i quickly return method handler object maintaining illusion blocking thrift call i initialize thrift handler twisted startup trigger def onstartup handler servicehandler processor serviceprocessorhandler server ttwistedthriftserverfactoryprocessorprocessor iprotfactorytbinaryprotocoltbinaryprotocolfactory reactorlistentcp server my client php connects socket new tsocket localhost transport new tframedtransportsocket protocol new tbinaryprotocoltransport client new serviceclientprotocol transportopen clientlistenforevent that last call clientlistenforevent successfully makes server runs servicehandlerlistenforevent even server method returns twistedinternetdeferdeferred instance client immediately receives empty array i get exception exception ttransportexception message tsocket timed reading bytes localhost local port,1 b special meaning inside python string literal i recommend use raw strings whenever backslash embedded inside string r alpha,i using matplotlib produce graphics i using latex legends more specifically i trying use something like loglogxx r label alpha legend show however code present legend figure gets error i close image i using enthought package mac error comes pylabscipy the error appears exactly lpha char line col however use mu gamma works well i found problem beta alpha does anyone knows i believe python interpreting character i know i debug avoid,3 why change code insert time run something like curl cookie acsidyouracsidcookie httpyourappidappspotcompopulatepath sleep done command line the entries random anyway need remember state you get acsid cookie logging manually inspecting cookies browser the sleep requests prevent spinning gigantic number instances hitting shortterm quotas the task queue suggestion good something need automate onetime thing might well keep simple,i trying create store random codes local datastore trying appspot this model class promotioncode dbmodel code dbstringpropertyrequiredtrue and class handles populate request logged admin may use it creates random alphanumeric codes tries store datastore class populatewebapprequesthandler def generatecodeself chars stringletters stringdigits code range code code choicechars return codeupper def getself codes codelist range newcode selfgeneratecode promotioncode promotioncodecodenewcode codelistappendpromotioncode codes codes br newcode dbputcodelist selfresponseoutwritepopulating datastorebr selfresponseoutwritecodes i thought i could try batching put i created list codes codelist it takes minutes locally is possible faster without using bulkuploader option because i getting server error obviously or maybe consecutive calls steps,1 there whole website dedicated color schemes eclipse httpwwweclipsecolorthemesorg the color schemes site imported epf preference file directly alternatively via eclipse color theme plugin found httpmarketplaceeclipseorgcontenteclipsecolortheme,i looking eclipse themes similar following support pythonxhtmlcssjs default,2 tldr requestmethod never none real use particular case looking wrong thing generic httprequest djangohttpinitpy class httprequestobject def initself selfmethod none when plain httprequest instantiated method none but wsgirequest modpythonrequest call httprequestinit ever requests modwsgi djangocorehandlerswsgipy class wsgirequesthttphttprequest def initself environ selfmethod environ requestmethod upper the summary modwsgi requestmethod never none if warped way managed get environ requestmethod defined none request would fail requests modpython djangocorehandlersmodpythonpy class modpythonrequesthttphttprequest def getmethodself return selfmeta requestmethod upper method propertygetmethod same remarks wsgirequest apply can ever none test client djangotestclientrequestfactoryrequest instantiates wsgirequest called every time requestmethod defined environ uppercase string summary assert requestmethod none you looking error wrong place in case requestmethod post it failing requestmetaget contenttype none the reason contenttype header sent client request ask i familiar stuff,i trying figure issue related django httpsgithubcommikidjangojqueryfileuploaderintegrationdemoissues under conditions requestmethod none django,3 if i mistaken formula equivalent numpydotpunto punto punto write like save three multiplications theory slightly faster,import numpy def euclideanclassificationpunto punto return numpydotpunto punto numpydotpunto punto i trying improve performance function i know this function variant euclidean distance used pattern recognition,2 i finally got work without crashing localcursorexecutecall dbogetalarmeventhistoryfrequencytimerangetstarttend wrong syntax it localcursorexecutecall dbogetalarmeventhistoryfrequencytimerangetstarttend special attention made special symbols way parameters passed tstarttend localcursorexecute call dbogetalarmeventhistoryfrequencytimerange tstarttend,i using pyodbc connect sql server express database i created stored procedure sqlserver express takes string parameters eg storedprocinpu input parameters type datetime i tested stored proc using management studio return appropriate result however try call stored procedure pythoni using eclipse i get error pyodbcdataerror microsoftsql native clientinvalid character value cast specification sqlexecdirectw the function calling follows def getalarmfrequencytimetstarttend print tstart tend argumentststarttend localcursorconncursor localcursorexecutecall dbogetalarmeventhistoryfrequencytimerangetstarttend resultsetrowslocalcursorfetchall print there lenresultsetrows records singlerow resultsetrows print singlerow singlerow localcursorclose the line causing trouble localcursorexecutecall dbogetalarmeventhistoryfrequencytimerangetstarttend anyone help understand i pass multiple parameters stored procedure called using pyodbc do i need convert tstart tend datetime format first i trued strptime even succeeded though may using wrong,2 it safe call reloadhandler depends initialize connections if make connections inside handler yes garbage collected handler object falls scope but connecting inside main loop would i highly recommend something like dbconnection connect true socketsendhandlerdata dbconnection reason making expensive connection inside tight loop that said i recommend going entirely different architecture make listener process basically nothing listen udp datagrams sends messaging queue like rabbitmq waits reply message send results back client then write actual servers get requests messaging queue process send reply message back if want upgrade udp server launch new instance listening another port update firewall rules redirect incoming traffic new port reload rules kill old process voila seamless cutover the real win uncoupling backend since multiple processes listen messages frontend proxy service run several parallel different machines want to upgrade backend start new instance kill old one time least one instance running to scale proxy multiple instances running different ports different hosts configure firewall randomly redirect incoming datagrams one proxies to scale backend run instances,i python application precise network application go means kill pid since actually talks servers clients many € per minute downtime know usual system anyway hobby projects also work lot wsgi frameworks noticed problem even offpeak hours anyway imagine normal server using tcpudp put favourite wsgisipclassified information serveretc now perform git pull remote server goes new python files server files course only affect data processing actual sockets need reraise sockets touch way network part i usually use file monitors since prefer use signal wakeup internal app updater now imagine following code mysuperapp import handler true data socketrecv data socketsendhandlerdata lets imagine handler app db connections cache connections etc what best way update handler is safe call reloadhandler will break db connections will db connections survive restart will current transactions lost will create antimatter what bestpratice patterns guys usually use,2 select for update of supported this understandable considering mechanics sqlite row locking redundant entire database locked updating bit however would good future version sqlite supports sql interchageability reasons nothing else the functionality required ensure reserved lock placed database already excerpt httpsqliteorgcvstracwikipunsupportedsql think synchronize access whole database normal synchronization mechanism also apply file lock process synchronization etc,yesterday i working sqlalchemy stuff needed select update concept avoid race condition adding withlockmode update query works treat innodb postgres sqlite i end sneak sessionbindname sqlite sessionexecute begin immediate transaction select this seems work feels like cheating is better way,3 pandas based numpy arrays the key speed numpy arrays perform operations whole array never rowbyrow itembyitem for example close array want dayoverday percent change pctchange closeclose this computes entire array percent changes one statement instead pctchange row close pctchangeappend so try avoid python loop row enumerate entirely think perform calculations operations entire array dataframe whole rather rowbyrow,i want perform complex operations financial data dataframes sequential manner for example i using following msft csv file taken yahoo finance dateopenhighlowclosevolumeadj close i following usrbinenv python pandas import df readcsv tablecsv row enumeratedfvalues date dfindexi open high low close adjclose row perform analysis openclose based date etc is efficient way given focus speed pandas i would assume must special function iterate values manner one also retrieves index possibly generator memory efficient dfiteritems unfortunately iterates column column,3 use def test x args now test x one test x one two test x one two,i run several times i dealing lot methods accept list strings several times i accidentally passed single string gets broken apart list character used desired behavior def testab x xextenda xextendb return x x what i want happen testx test e i resort strange syntax testx list i would like work implicitly testx list test testx one two three one two three i really feel like pythonic way something involving duck typing i see i know i could use isinstance check string i feel like better way edit i using python,3 urls dictthingslug thinggetabsoluteurl thing things word objecttextsplit word urls resultappend href urlswords word else resultappendword,i working django project model list things throughout site i may unstructured text entered models on display page i would like parse unstructured text reference thingslug include link thinggetabsoluteurl i would assume app would need consist custom templatetag parses objecttext uses something like regular expression parser match thingslug terms dictionary things take example i thinga thingb would like thingc would modified i hrefthingsathingaa hrefthingsbthingba would like hrefthingscthingca if django app already great otherwise advice best accomplish appreciated i suggestions jquery well even though i familiar,1 i sorry say really one cases using isinstance makes sense however one answers suggests testing list backwards str python x unicode anomalous types ones test def testab x isinstanceb str b b xextenda xextendb return x python x test isinstanceb basestring,i run several times i dealing lot methods accept list strings several times i accidentally passed single string gets broken apart list character used desired behavior def testab x xextenda xextendb return x x what i want happen testx test e i resort strange syntax testx list i would like work implicitly testx list test testx one two three one two three i really feel like pythonic way something involving duck typing i see i know i could use isinstance check string i feel like better way edit i using python,3 don use regular expression parse xmlhtml use proper parser like beautifulsoup lxml python,i data xml format example shown follow i want extract data text tag here xml data text the yearold virgin american buddy comedy film middleaged man journey finally sex hthe ploth andy stitzer steve carell eponymous yearold virgin hcasth hsoundtrackh hexternal linksh text i need the yearold virgin american buddy comedy film middleaged man journey finally sex is possible thanks,1 whenever find looking xml data thinking regular expressions stop ask considering real xml parser the structure xml makes perfectly suited proper parser maddeningly frustrating regular expressions if must use regular expressions following until document changes import p recompiletexth psearchxmltextgroup spoiler regular expressions might appropriate oneoff problem needs quick dirty solution or might appropriate know input data fairly static tolerate overhead parser,i data xml format example shown follow i want extract data text tag here xml data text the yearold virgin american buddy comedy film middleaged man journey finally sex hthe ploth andy stitzer steve carell eponymous yearold virgin hcasth hsoundtrackh hexternal linksh text i need the yearold virgin american buddy comedy film middleaged man journey finally sex is possible thanks,1 cast buffer pointer byte array get value also bit system need make sure set return type malloc cvoidp default int return value lose bits you also need careful case embedded nuls data convert pointer ccharp convert string especially true data nulterminated malloc ctypesdllmsvcrtmalloc mallocrestype ctypescvoidp pbuf mallocnbufsize convert void pointer byte array pointer convert string this works even embedded nuls string data ctypescastpbuf ctypespointerctypescubyte nbufsize bytedata joinmapchr datacontents openfilename mode wb f fwritebytedata,i following code import ctypes pbuf ctypescdllmsvcrtmallocnbufsize wrote something buffer how i save content buffer file using python as may already know going work giving typeerror argument must string readonly buffer int f openoutdatawb fwritepbuf,1 use xml parser parse xml using lxml import lxmletree et content text the yearold virgin american buddy comedy film middleaged man journey finally sex hthe ploth andy stitzer steve carell eponymous yearold virgin hcasth hsoundtrackh hexternal linksh text textetfromstringcontent printtexttext yields the yearold virgin american buddy comedy film middleaged man journey finally sex,i data xml format example shown follow i want extract data text tag here xml data text the yearold virgin american buddy comedy film middleaged man journey finally sex hthe ploth andy stitzer steve carell eponymous yearold virgin hcasth hsoundtrackh hexternal linksh text i need the yearold virgin american buddy comedy film middleaged man journey finally sex is possible thanks,2 here could using elementtree in import xmletreeelementtree et in etparse fxml in print tgetroottextstrip the yearold virgin american buddy comedy film middleaged man journey finally sex,i data xml format example shown follow i want extract data text tag here xml data text the yearold virgin american buddy comedy film middleaged man journey finally sex hthe ploth andy stitzer steve carell eponymous yearold virgin hcasth hsoundtrackh hexternal linksh text i need the yearold virgin american buddy comedy film middleaged man journey finally sex is possible thanks,1 maybe would better buffer allocated ctypescreatestringbuffer instead malloc in case access data via bufraw if need access malloc ed data ctypesstringataddress size mybe combined cast ctypescvoidp ctypesccharp depending else memory contained terminated string data known length,i following code import ctypes pbuf ctypescdllmsvcrtmallocnbufsize wrote something buffer how i save content buffer file using python as may already know going work giving typeerror argument must string readonly buffer int f openoutdatawb fwritepbuf,2 here example using xmletreeelementtree import xmletreeelementtree et data text the yearold virgin american buddy comedy film middleaged man journey finally sex hthe ploth andy stitzer steve carell eponymous yearold virgin hcasth hsoundtrackh hexternal linksh text xml etxmldata xmltext n the yearold virgin american buddy comedyn film middleaged man journey finally sexnn xmltextstripreplace n the yearold virgin american buddy comedy film middleaged man journey finally sex and go,i data xml format example shown follow i want extract data text tag here xml data text the yearold virgin american buddy comedy film middleaged man journey finally sex hthe ploth andy stitzer steve carell eponymous yearold virgin hcasth hsoundtrackh hexternal linksh text i need the yearold virgin american buddy comedy film middleaged man journey finally sex is possible thanks,1 the getpass module written python you could easily modify in fact modified version getpasswingetpass could paste code import sys def wingetpassprompt password streamnone prompt password echo using windows getch import msvcrt c prompt msvcrtputchc pw c msvcrtgetch c r c n break c raise keyboardinterrupt c b pw pw msvcrtputch b else pw pw c msvcrtputch msvcrtputch r msvcrtputch n return pw you might want reconsider however the linux way better even knowing number characters password significant hint someone wants crack,i writing console program python windows the user need login use program input password i like echoed i get user input i found standard library module called getpass echo anything inputlinux like thanks,3 you need use equations combination the things unknown equations lagrange multipliers lambdas everything else depends empirical data available thus numbers given set values lambdas calculate gjr jacobian jjirs in turn know residuals jacobian use newton method given equation find roots system equations ie values lambda gjr thus use initial guess values lambdas calculate terms use terms update guess there conceptual challenge working equation plug values adding lot numbers care warranted equation little tricky written clearly since paper describes system equations generally expect solve linear equation j dlambda g dlambda vector changes guess g vector values function j matrix jacobian values the notation paper pretty muddled obscuring simple expression you get clearer form introducing unified index replace pair indices authors mention change discussion method giving formula calculating combined index second paragraph page overall procedure becomes using unified index choose lambdas act initial guess maybe zeros random numbers evaluate ga jab solve system linear equations get updates guess if updates small compared guess stop otherwise determine new guess go back step this looks quite feasible using numpy the paper talked using parallel computing strategy ten years ago seems like much smaller problem today,struggling days thingbut avail i good difficult math let alone kind level difficulty i trying implement maximum entropy application lottery python graduation assignment altough focus project implement number data mining techinques decision treesapriorikmeans something alreadey finished could pass opportunity something advancedbut guess advanced so question solve non linear equation following paper reference httpeprintsecssotonacukpaperpdf method based following paper reference httpwwwstanfordeducoverpaperspaperpdf help theoritical othwerwise deeply appreciated thanks,2 a nice profiling module lineprofiler called using script kernprofpy it downloaded my understanding cprofile gives information total time spent function so individual lines code timed this issue scientific computing since often one single line take lot time also i remember cprofile catch time i spending say numpydot,project euler coding contests often maximum time run people boast fast particular solution runs with python sometimes approaches somewhat kludgey ie adding timing code main what good way profile long python program takes run,3 in fedora python already installed just run command line python yourprogrampy,how i run simple python program fedora i much new fedora know exactly start fedora do need install software fedora make python programs work please tell step step i familiar idle fedora,1 put usrbinenv python top file then command line chmod ux yourpythonfilepy i use indicate shell prompt type you run file yourpythonfilepy you also python yourpythonfilepy need usr chmod stuff first approach natural way things unix,how i run simple python program fedora i much new fedora know exactly start fedora do need install software fedora make python programs work please tell step step i familiar idle fedora,3 unfortunately google app engine allow write files needed sqlite until recently support sql preferring homegrown solution see cap theorem this motivated creation projects like djangononrel version django require relational database recently opened beta service proposes mysql database but beware fundamentally less reliable probably going expensive edit as nick johnson observed new service google cloud sql fundamentally less scalable fundamentally less reliable,i created simple bookmarking app using django uses sqlite database backend can i upload appengine use what djangononrel,3 ospopen unnecessary every one tasks use shutil urllib pdb cytochromec giw title lc title lc title cwd ospathabspathosgetcwd pdb pdbs â â pdb cytochromec â â â â shutilmkdirospathjoincwd pdb â â lenpdb urlliburlopen httpwwwpdborgpdbfilesspdb pdbread â â â â openospathjoincwd cytochromec spdb pdb wwrites,i using code create folder download assocated pdbs protein the problem i pdbs downloaded wrong location they downloaded loaction python script cytochromec folder pdb cytochromec giw title lc title lc title pdb pdbs strpdb cytochromec ospopen mkdir cytochromec ospopen cd cytochromec lenpdb ospopen wget httpwwwpdborgpdbfilesspdb strpdb,2 use method gtkmainlevel get current nesting level main loop the nesting level increased calling gtkmain function reduced calling gtkmainquit function,is way i tell gtk automatically call gtkmainquit last open window application closeddestroyed if direct feature offering functionality i could think following in window destroy method get list open windows process empty quit is way get list the obvious solution would keep manually track open windows i would want avoid possible,1 i wrote simple module available httppypipythonorgpypicolorconsole it works windows mac os x linux it uses ansi linux mac native calls console functions windows you colors cursor positioning keyboard input it replacement curses useful need use simple scripts ascii games,how i output colored text terminal python what best unicode symbol represent solid block,1 from the zen python explicit better implicit in opinion first example explicit it takes two values processes wellunderstood ways although feels little strange new python programmers behaves like expect listextend accepts lists treats strings like list chars your proposal alters semantics listextend equivalent listappend dealing strings that would real surprise someone wants function treat strings lists chars would call like testxlist test you asking please,i run several times i dealing lot methods accept list strings several times i accidentally passed single string gets broken apart list character used desired behavior def testab x xextenda xextendb return x x what i want happen testx test e i resort strange syntax testx list i would like work implicitly testx list test testx one two three one two three i really feel like pythonic way something involving duck typing i see i know i could use isinstance check string i feel like better way edit i using python,1 i success using socketio asynchronous web stuff comet for django particular i personal experience i found nice article combining gevent socketio django some resources socketio gevent found couple blog articles well slideshare presentation,my possibilities limited i nice host use normal server plan which means normal server port i tried read websockets andor comet mostly seem require second server running another port is way get stable cometlike behaviour scales nicely my solution script sends get request every seconds good way make web chat and i afraid might kill server dozen people online so i get reliable cometlike behaviour,2 there appear numpy equivalent matlab eigsabk finding k largest eigenvectors if interested enthought compiled table showing differences matlab numpy that helpful answering questions like one httpwwwscipyorgnumpyformatlabusers one thought x matrices i think eigsab would help anyway the effort involved computing first eigenpair leaving matrix transformed second emerges directly there benefit x larger,i wondering python package numpy otherwise function computes first eigenvalue eigenvector small matrix say x i could use linalg package numpy follows import numpy np def whatever a npasmatrixnprand evals evecs nplinalgeiga assume eigenvalues ordered large small eigenvectors ordered accordingly return evals evecs but takes really long time i suspect numpy computes eigenvectors sort iterative process so i wondering much faster algorithm returns first largest eigenvalue eigenvector since i need first for x matrices course i write function computes eigenvalue eigenvector analytically problems floating point computations example i divide big number small number i get infinity nan does anyone know anything please help thank advance,1 what want wsgi environ specifically environ remoteaddr however proxy involved remoteaddr address proxy client address included likely httpxforwardedfor here function want cases credit sã¦var def getclientaddressenviron try return environ httpxforwardedfor split strip except keyerror return environ remoteaddr you easily see included wsgi environ writing simple wsgi app pointing browser example eventlet import wsgi import eventlet pprint import pformat def showenvenv startresponse startresponse ok contenttype textplain return srn pformatenv wsgiservereventletlisten showenv and combining two eventlet import wsgi import eventlet pprint import pformat def getclientaddressenviron try return environ httpxforwardedfor split strip except keyerror return environ remoteaddr def showenvenv startresponse startresponse ok contenttype textplain return srnrnclient address srn pformatenv getclientaddressenv wsgiservereventletlisten showenv,i currently writing basic dispatch model server based python eventlet library httpeventletnetdoc having looked wsgi docs eventlet httpeventletnetdocmoduleswsgihtml i see eventletwsgiserver function logs xforwardedfor header addition client ip address however way obtain attach filelike object default sysstderr server pipe object i would like able obtain client ip within application ie function startresponse environ parameters indeed environ key would perfect is way obtain ip address simply ie environ dictionary similar without resort redirecting log object somehow,3 i understand days hours minutes tddays tdseconds tdseconds days hours minutes tddays tdseconds tdseconds you get minutes seconds minute float,i got timedelta i want days hours minutes either tuple dictionary i fussed i must done dozen times dozen languages years python usually simple answer everything i thought i ask busting nauseatingly simple yet verbose mathematics mr fooz raises good point i dealing listings bit like ebay listings one duration i trying find time left whenadded duration am i right saying account dst if simplest way addsubtract hour,2 there several different ways depending whether want reuse images tours agencies whether makes sense one image class two without knowing use case i might like class gallerymodelsmodel represents set images maybe title fields class imagemodelsmodel represents one image field names usually lowercase clarity image modelsimagefielduploadtogallery gallery modelsforeignkeygallery relatedname images might want fields eg title alttext etc class tourmodelsmodel gallery modelsonetoonefieldgallery class agencymodelsmodel gallery modelsonetoonefieldgallery this sets intermediary model called gallery tour agency refer if wanted allow one gallery per tour agency wanted reuse galleries different objects could use foreignkey instead onetoonefield if wanted share images galleries could use manytomanyfield instead foreignkey image class,i models named tour agency tour agency n images i implement i define model like class gallerymodelsmodel imagemodelsimagefielduploadtogallery add field tour agency modelslike gallerymodelsforeignkeygallery if i thiswhen adding tour agency list images gallery i wanna add n images item i,2 use multiprocessing start if need multiple cpu look celery,what would interprocess communication ipc frameworktechnique following requirements transfer native python objects two python processes efficient time cpu ram efficiency irrelevant crossplatform winlinux nice works pypy update processes host use versions python modules update processes run independently user one spawns others,3 the module sub function designed kind search replace search pattern distinguishes things rest unstructured text construct appropriate substitution string import i thingslug thingfoo would like thingfoo resubr ww r hrefa i hrefthingslugthingsluga hrefthingfoothingfooa would like hrefthingfoothingfooa this reliable less errorprone make pattern things distinctive i thingslug thingfoo would like thingfoo resubr ww r hrefa i hrefthingslugthingsluga hrefthingfoothingfooa would like hrefthingfoothingfooa,i working django project model list things throughout site i may unstructured text entered models on display page i would like parse unstructured text reference thingslug include link thinggetabsoluteurl i would assume app would need consist custom templatetag parses objecttext uses something like regular expression parser match thingslug terms dictionary things take example i thinga thingb would like thingc would modified i hrefthingsathingaa hrefthingsbthingba would like hrefthingscthingca if django app already great otherwise advice best accomplish appreciated i suggestions jquery well even though i familiar,1 native objects get shared processes due reference counting instead pickle share using unix domain sockets mmap zeromq intermediary sqlite designed concurrent accesses,what would interprocess communication ipc frameworktechnique following requirements transfer native python objects two python processes efficient time cpu ram efficiency irrelevant crossplatform winlinux nice works pypy update processes host use versions python modules update processes run independently user one spawns others,3 parallel python might worth look works windows os x linux i seem recall i used ultrasparc solaris machine back i know works pypy seem work psyco,what would interprocess communication ipc frameworktechnique following requirements transfer native python objects two python processes efficient time cpu ram efficiency irrelevant crossplatform winlinux nice works pypy update processes host use versions python modules update processes run independently user one spawns others,2 for one could create custom subclass gobject provides custom signals the following example slightly adapted version one given linked article import pygtk pygtkrequire import gobject class cargobjectgobject gsignals enginestarted gobjectsignalrunlast gobjecttypenone enginestopped gobjectsignalrunlast gobjecttypenone def initself gobjectgobjectinitself selfstate def startself selfstate selfstate selfemit enginestarted def stopself selfstate selfstate selfemit enginestopped gobjecttyperegistercar def killswitchc def callbackunused ignored cstop return callback def onstartunused ignored print started def onstopunused ignored print stopped somecar car somecarconnect enginestarted onstart somecarconnect enginestarted killswitchsomecar somecarconnect enginestopped onstop somecarstart another approach would take advantage one many eventsignalling packages already pypi example zope event louie pydispatcher darts events trellis,i building pygtk application several widgets changed need notify widgets change i would like avoid code like def onentrycolorupdatedself widget selfpainttoolspanelcurrentcolorpaneupdatecolor selfmainwindowstatusbarupdatecolor selfcurrenttoolgetbrushupdatecolor and something like instead def onentrycolorupdatedself widget selfupdatenotify colorchanged the status bar current color pane current tool would subscribe notification event act accordingly from i tell gobject signaling mechanism allows register callback particular widget object wants receive notification aware widget does gtk provide system i build developers shotwell photo organization application gnome build signaling mechanism i understand design doc correctly searching so turn definitive answers edit clarification i think gobject signaling i need part i need with gobject i need explicitly connect object another object like emitterconnect customevent receivereventhandler so application i would class colorpanegtksomething def initself application init stuff goes applicationcolorpalletteconnect colorchanged selfupdatecolor def updatecolorself widget show new color pass class statusbargtksomething def initself application init stuff goes applicationcolorpalletteconnect colorchanged selfupdatecolor def updatecolorself widget show new color name pass class brushgtksomething def initself application init stuff goes applicationcolorpalletteconnect colorchanged selfupdatecolor def updatecolorself widget draw new color pass in words i pass application object object knows colorpallete objects application connect colorpallette signals this kind coupling i want avoid,1 following python code works reliable x the input data type str note server receives data loop read data large data sizes chunked also attached java code snippet read chunked data def postself url data selfcurl pycurlcurl selfresponseheaders stringiostringio selfresponsebody iobytesio selfcurlsetoptpycurlwritefunction selfresponsebodywrite selfcurlsetoptpycurlheaderfunction selfresponseheaderswrite selfcurlsetoptpycurlfollowlocation selfcurlsetoptpycurlmaxredirs selfcurlsetoptpycurltimeout selfcurlsetoptpycurlencodingdeflate gzip selfcurlsetoptpycurlurl url selfcurlsetoptpycurlverbose selfcurlsetoptpycurlpost selfcurlsetoptpycurlpostfieldsdata selfcurlsetoptpycurlhttpheader contenttype octatestream selfcurlsetoptpycurlpostfieldsize lendata selfcurlperform return url selfcurlgetinfopycurlresponsecodeselfresponseheadersgetvalue selfresponsebodygetvalue java code servlet engine int postsize integerparseintreqgetheadercontentlength results new bytepostsize int read whileread postsize int n reqgetinputstreamreadresults n break read n,i seen receipes uploading files via multipartformdata pycurl both methods seem require file disk can recipes modified supply binary data memory instead disk i guess i could use xmlrpc server instead i wanted get around encode decode binary data send raw do pycurl mutlipartformdata work raw data,1 it close open file descriptors ones filespreserve attribute you could probably coerce work figuring fd waker open sockets reactor passing filespreserve bother just use twistd twisted daemonize better yet use twistd n let process get monitored system tool bother daemonization,if use pep reference implementation httppypipythonorgpypipythondaemon looks like impossible twisted working since daemonising all possible file handlers explicitly closed includes pipes when twisted tries call ospipe write gets bad file descriptor as i see daemonising suited networking pep and probably reason twisted exist edit i point question why pep effectively makes impossible create network application rather how twisted breaks rules order work,1 gobjects widgets for example application class gobject defines signals widgets connect also i think understood shotwell design document correctly it looks like signalling system gobject signalling system particular guarantees order signals handled as say design document things possible plain gobject vala makes easier code way,i building pygtk application several widgets changed need notify widgets change i would like avoid code like def onentrycolorupdatedself widget selfpainttoolspanelcurrentcolorpaneupdatecolor selfmainwindowstatusbarupdatecolor selfcurrenttoolgetbrushupdatecolor and something like instead def onentrycolorupdatedself widget selfupdatenotify colorchanged the status bar current color pane current tool would subscribe notification event act accordingly from i tell gobject signaling mechanism allows register callback particular widget object wants receive notification aware widget does gtk provide system i build developers shotwell photo organization application gnome build signaling mechanism i understand design doc correctly searching so turn definitive answers edit clarification i think gobject signaling i need part i need with gobject i need explicitly connect object another object like emitterconnect customevent receivereventhandler so application i would class colorpanegtksomething def initself application init stuff goes applicationcolorpalletteconnect colorchanged selfupdatecolor def updatecolorself widget show new color pass class statusbargtksomething def initself application init stuff goes applicationcolorpalletteconnect colorchanged selfupdatecolor def updatecolorself widget show new color name pass class brushgtksomething def initself application init stuff goes applicationcolorpalletteconnect colorchanged selfupdatecolor def updatecolorself widget draw new color pass in words i pass application object object knows colorpallete objects application connect colorpallette signals this kind coupling i want avoid,1 it sounds like want modeless dialog in code posted change fileexplor class qdialog class fileexplorqtguiqdialog then add signal handler main fileexplorer class def handleshowdialogself hasattrself dialog selfdialog fileexplorself selfdialogshow and finally connect button handler showbuttonclickedconnectselfhandleshowdialog,i new pyqt using pyqt have two independent widgets first showfullscreen second show i want hiding second hide show clicking button first tried something googled nothing full code pyqt import qtcore qtgui class fileexplorerqtguiqwidget def initself parentnone superfileexplorer selfinitparent namelabel qtguiqlabelname selfnameline qtguiqlineedit addresslabel qtguiqlabeladdress selfaddresstext qtguiqtextedit showbutton qtguiqpushbutton show widget self showbuttonclickedconnectfileexplorshow mainlayout qtguiqgridlayout mainlayoutaddwidgetnamelabel mainlayoutaddwidgetselfnameline mainlayoutaddwidgetaddresslabel qtcoreqtaligntop mainlayoutaddwidgetselfaddresstext mainlayoutaddwidgetshowbutton selfsetlayoutmainlayout selfsetgeometry selfsizehint selfsetwindowtitlefile explorer class fileexplorqtguiqwidget def initself parentnone superfileexplor selfinitparent namelabel qtguiqlabelname selfnameline qtguiqlineedit addresslabel qtguiqlabeladdress selfaddresstext qtguiqtextedit quitbutton qtguiqpushbutton quit self quitbuttonclickedconnectselfhide mainlayout qtguiqgridlayout mainlayoutaddwidgetnamelabel mainlayoutaddwidgetselfnameline mainlayoutaddwidgetaddresslabel qtcoreqtaligntop mainlayoutaddwidgetselfaddresstext mainlayoutaddwidgetquitbutton selfsetlayoutmainlayout selfsetgeometry selfsizehint selfsetwindowtitlefile explorer name main import sys app qtguiqapplicationsysargv fileexplorer fileexplorer fileexplorershowfullscreen fileexplorershow fileexplor fileexplor fileexplorshow sysexitappexec logic want make end first widget main block fullscreen widgets show clicking buttons first,1 namepmatchnamegroup you changing name that probably makes false namejobname state c which makes statement execute deljobidsappendj i suggest taking look name namepmatchnamegroup statement,is way regular expression match inside block would interfere code inside else block in following code i test strings inputed jobname appended deljobids array only appended j jobs name jobsj jobname precompilewwd name name namepmatchnamegroup else namejobname state c print ok deljobidsappendj pass namejobname state c deljobidsappendj namenone if i comment line namepmatchnamegroup one case get appended get appended i also append job uncommmenting code else block string passes conditon getting appended the difference strings colon dashes one string neither i tested regex multiple times the string without dashes colons go else clause use default name defined top loop,1 the match interfere elseclause the likely cause namejob condition failing one test cases a judicious use printstatements likely show string skipped or use pdb,is way regular expression match inside block would interfere code inside else block in following code i test strings inputed jobname appended deljobids array only appended j jobs name jobsj jobname precompilewwd name name namepmatchnamegroup else namejobname state c print ok deljobidsappendj pass namejobname state c deljobidsappendj namenone if i comment line namepmatchnamegroup one case get appended get appended i also append job uncommmenting code else block string passes conditon getting appended the difference strings colon dashes one string neither i tested regex multiple times the string without dashes colons go else clause use default name defined top loop,1 simple just cut files py extension paste place different os path one files causing error run idle,idle subprocess make connection either idle start subprocess personal firewall software blocking connection don think askedhow come comes occasionally running simple programsi go task manager amp stop pythonw processes get work it seems happen randomnly different bits codehere one i moment f open moneytxt currentmoney floatfreadline printcurrentmoney end howmuch floatinput how much put take currentmoney howmuch printnow fclose f open moneytxt w fwritestrnow fclose sometimes works sometimes,1 if new depend self use classmethod class parentobject classmethod def newclsargskwargs return clsargskwargs class childparent pass pparent ppnew assert isinstancepparent cchild ccnew assert isinstancecchild or new depend self use typeself determine self class class parentobject def newselfargskwargs use self way perhaps change args andor kwargs return typeselfargskwargs,i function superclass returns new version i subclass super inherits particular function would rather return new version subclass how i code function call parent returns version parent called child returns new version child,3 hm may easy way def aargs x args iter diri xlisti else xappendi return x,i run several times i dealing lot methods accept list strings several times i accidentally passed single string gets broken apart list character used desired behavior def testab x xextenda xextendb return x x what i want happen testx test e i resort strange syntax testx list i would like work implicitly testx list test testx one two three one two three i really feel like pythonic way something involving duck typing i see i know i could use isinstance check string i feel like better way edit i using python,1 try using tuple var var var instead list var var convert lists tuples sending printing tuplevar,i excel sheet bunch info regarding stops delivery truck makes throughout day i successfully extract information i need xlrd this code i using book xlrdopenworkbookr cxytestxls sheet booksheetbyindex odlist range cid sheetrowivalue company id tid sheetrowivalue truck id xycoord sheetrowvaluesistartcolx endcolx long lat xycoordreverse reversed latlong correct format odlistappendcidtidxycoord printing odlist give output fields companyidtruckid latlong i get i used list indices grab coordinates query gmaps result gmapsdirectionsodlistodlist time result directions duration seconds dist result directions distance meters unfortunately gmaps understand gmaps understand any ideas get query send instead,1 supervisord upstart,if use pep reference implementation httppypipythonorgpypipythondaemon looks like impossible twisted working since daemonising all possible file handlers explicitly closed includes pipes when twisted tries call ospipe write gets bad file descriptor as i see daemonising suited networking pep and probably reason twisted exist edit i point question why pep effectively makes impossible create network application rather how twisted breaks rules order work,1 import numpy np import matplotlibpyplot plt n xnplinspace n ynpcumsumnprandomrandomn linepltplotxy pathlinepath these original xy data points printpathvertices here linearly interpolate find additional points you increase argument pathinterpolated find interpolated points original points pathpathinterpolated printpathvertices,i trying get rasterized line data pylab plot function my code like fitfunc lambda p x p p sin pi x dataheadsize p errfunc lambda p x fitfuncp x data npgenfromtxtdatafilename dtypenone delimiter namestrue xaxisseries linspace dataheadmax dataheadsize p initial guess parameters p success optimizeleastsqerrfunc p argsxaxisseries datahead time linspacexaxisseriesmin xaxisseriesmax plotinfo plottime fitfuncp time r i want get x line data plotinfo when i use typeplotinfo plotinfo list using print plotinfo dlist object,1 feel free use daemon httpwwwjejikcomarticlesasimpleunixlinuxdaemoninpython how mix twisted see httpmichaelxiiiblogspotcomtwistedhtml warning russian text ahead python code rather demonstrating,if use pep reference implementation httppypipythonorgpypipythondaemon looks like impossible twisted working since daemonising all possible file handlers explicitly closed includes pipes when twisted tries call ospipe write gets bad file descriptor as i see daemonising suited networking pep and probably reason twisted exist edit i point question why pep effectively makes impossible create network application rather how twisted breaks rules order work,1 this kind cheating i know getting etclocaltime work like following import os joinosreadlink etclocaltime split australiasydney hope helps edit i liked ah idea case etclocaltime symlink translating python usrbinenv python hashlib import sha import os def getcurrentolsonname tzfile open etclocaltime tzfiledigest shatzfilereadhexdigest tzfileclose root dirs filenames oswalkusrsharezoneinfo filename filenames fullname ospathjoinroot filename f openfullname digest shafreadhexdigest digest tzfiledigest return joinfullnamesplit fclose return none name main print getcurrentolsonname,how i get olson timezone name australiasydney corresponding value given c localtime call this value overridden via tz symlinking etclocaltime setting timezone variable timerelated system configuration files,3 read document httpdocsceleryprojectorgenlatestinternalsappoverviewhtml the app instance celery library subclass app override almost part corner celery behaves,can somebody please explain celery application object noted purposes used,2 j jobs name jobsj jobname this part make sense if jobs iterable first time loop j set jobs next time set jobs etc so using j index jobs crazy talk you saying give next element iterable jobs use element index jobs,is way regular expression match inside block would interfere code inside else block in following code i test strings inputed jobname appended deljobids array only appended j jobs name jobsj jobname precompilewwd name name namepmatchnamegroup else namejobname state c print ok deljobidsappendj pass namejobname state c deljobidsappendj namenone if i comment line namepmatchnamegroup one case get appended get appended i also append job uncommmenting code else block string passes conditon getting appended the difference strings colon dashes one string neither i tested regex multiple times the string without dashes colons go else clause use default name defined top loop,1 it little easierfaster convert lists set worry sorting filename setnewlist setoldlist print new file filename also instead saving list file raw text could use shelve module make persistent store conveniently accessible like regular python dict otherwise code virtues simple straightforward here worked example ftplib import ftp import shelve olddir shelveopen filelistshl create persistent dictionary ftp ftp ftpfreebsdorg ftplogin result ftpdirresultappend newdir setresult print new files center line sortedsetnewdir setolddir print line olddirline print done center olddirclose,my main goal check ftp server anytime new file hits generate txt file new files copied if new files returns nothing here i far i started copying files server oldlisttxt connecting ftp site comparing data newlisttxt oldlisttxt differences i want temporary ftp file changestxt each time i connect i change newlisttxt make oldlisttxt i compare next time i connect is better way my lists seem never change data time sorry confusing thanks import os filename oldlisttxt testing newlisttxt tempfilename temporary ftp file changestxt old openfilename r oldlist oldreadlines oldlistsort ftplib import ftp ftp ftpftpsite username password ftpsetpasvfalse newlist ftpdirnewlistappend newlistsort ftpclose bob opentesting w nl newlist bobwritenl n hello opentempfilename w c newlist c oldlist hellowritec n bobclose oldclose helloclose osremoveoldlisttxt osrenamenewlisttxt oldlisttxt,1 congratulations discovered motivating use case python doubleunderscore name mangling for details workedout example see httpdocspythonorgtutorialclasseshtmlprivatevariables httpdocspythonorgreferenceexpressionshtmlatomidentifiers here use example base class definition class classaobject def initself printinitializing a hoping function called class printfnx def fnxself x return x fnx fnx def printfnxself x printclassaselffnxx inherits classa class classbclassa def initself printinitizlizing b def fnxself x return x def printfnxself x printclassb selffnxx classaprintfnxselfx bx classb bxprintfnx the use case described way implementing openclosed principle the art subclassing found httpwwwyoutubecomwatchvyrboywkgoampnoredirect,i would like method base class call another method class instead overriding method inherited class i would like following code print class b class a can done base class definition class classaobject def initself printinitializing a hoping function called class printfnx def fnxself x return x def printfnxself x printclassaselffnxx inherits classa class classbclassa def initself printinitizlizing b def fnxself x return x def printfnxself x printclassb selffnxx classaprintfnxselfx bx classb bxprintfnx,3 i exact issue osx standard perl macports perl it seems socketgethostname working mac least running reply identical running hostname terminal work if i localip socketgethostbynamelocaliplocal i get ip address problem so either osx quirk setup rather strange i go latter zeroconfpy fails machine problem something i sure author would caught,i using pythonbrew install python snow leopard it failed readline error socket error i installed readline source made installer happy next attempt socket error remains testsocket test testsocket failed traceback recent call last file usersgfergusonpythonpythonbrewbuildpythonlibtesttestsocketpy line testsockname myipaddr socketgethostbynamesocketgethostname gaierror errno nodename servname provided known digging around system python shows import socket myipaddr socketgethostbynamesocketgethostname traceback recent call last file line socketgaierror errno nodename servname provided known socketgethostname swsmajhami socketgethostbyname swsmajhami traceback recent call last file line socketgaierror errno nodename servname provided known socketgethostbyname googlecom i triangulated problem ruby irb ipsocketgetaddresssocketgethostname socketerror getaddrinfo nodename servname provided known so i sure bug resolver understanding hostname something weird machine configuration something weird network dns lookup whatever installer happy i think benign failure installer though i feel safe force test succeed i sure tell pythonbrew ignore test value specifically pass testsocket i also seeing following statuses figured significant yet tests skipped testal testbsddb testbsddb testcd testcl testcodecmapscn testcodecmapshk testcodecmapsjp testcodecmapskr testcodecmapstw testcurses testdl testepoll testgdbm testgl testimageop testimgfile testlargefile testlinuxaudiodev testnormalization testossaudiodev testpep testpykwarn testsmtpnet testsocketserver teststartfile testsunaudiodev testtimeout testurllibnet testurllibnet testwinreg testwinsound testzipfile skip unexpected darwin testdl anyone experience getting python installed pythonbrew snow leopard update i tried socketgethostbynamesocketgethostname command python installed macbook pro snow leopard successfully reported ip back appears problem system config work i going ask so sibling apple site see anyone knows might,1 import os pathcwindowssystemloopymusicwav fopenpathr read byterate field file see microsoft riff wave file format httpsccrmastanfordeducoursesprojectswaveformat byterate located first th byte fseek afread convert string integerlongint value little endian proper conversion required byterate range byteratebyterate ordaipowi get file size bytes filesizeospathgetsizepath duration data milliseconds given msfilesizebyterate print file duration miliseconds ms print file duration hmsms ms ms ms ms print actual sound data bytes filesize fclose,i looking way find duration audio file wav python so far look python wave library mutagen pymedia pymad able get duration wav file pymad gave duration consistent thanks advance,3 you make ignore function shutilcopytree fullpath target ignorelambda directory contents common directory fullpathtoadir else or want able call copytree relative path import ospath def ignorepathpath def ignorefdirectory contents return f f contents osabspathospathjoindirectory f path return ignoref shutilcopytree path target ignoreignorepath fullpathtoadircommon from docs if ignore given must callable receive arguments directory visited copytree list contents returned oslistdir since copytree called recursively ignore callable called directory copied the callable must return sequence directory file names relative current directory ie subset items second argument names ignored copy process ignorepatterns used create callable ignores names based globstyle patterns,is way i filter directory using absolute path shutilcopytreedirectory targetdir ignore shutilignorepatternsfullpathtoadircommon this seem work trying filter common directory located adir if i shutilcopytreedirectory targetdir ignore shutilignorepatternscommon it works every directory called common filtered tree i want any suggestions thanks,3 the api shutilignorepatterns support absolute paths trivially easy roll variant as starting point look source code ignorepatterns def ignorepatternspatterns function used copytree ignore parameter patterns sequence globstyle patterns used exclude files def ignorepatternspath names ignorednames pattern patterns ignorednamesextendfnmatchfilternames pattern return setignorednames return ignorepatterns you see returns function accepts path list names returns set names ignore to support use case create similar function uses takes advantage path argument pass function ignore parameter call copytree alternatively use shutil asis the source code short sweet hard cut paste customize,is way i filter directory using absolute path shutilcopytreedirectory targetdir ignore shutilignorepatternsfullpathtoadircommon this seem work trying filter common directory located adir if i shutilcopytreedirectory targetdir ignore shutilignorepatternscommon it works every directory called common filtered tree i want any suggestions thanks,2 the return statement makes sense inside functions def foo true return false,when running following code python mac mac os x true return false i get following error syntaxerror return outside function i carefully checked errant tabs andor spaces i confirm code fails error i use recommended spaces indentation this behavior also happens return placed inside control statements eg etc any help would appreciated thanks,3 you want make ignore function checks current directory processed returns list containing common dir fullpathtoadir def ignorefullpathcommondir files dir fullpathtoadir return common return shutilcopytreedirectory targetdir ignoreignorefullpathcommon,is way i filter directory using absolute path shutilcopytreedirectory targetdir ignore shutilignorepatternsfullpathtoadircommon this seem work trying filter common directory located adir if i shutilcopytreedirectory targetdir ignore shutilignorepatternscommon it works every directory called common filtered tree i want any suggestions thanks,1 you odd things let go name jobsj jobname it seems perhaps jobs container dictionaries key jobname key value list tuple i think might mean name j jobname if jobs list strings job names need name j skip use j want refer precompilewwd you compiling regex every time go loop exactly time use exactly do compilation loop begins you need else clause and want else python use elif your regex could simplified using raw string eliminate double escapes precompilerwwd your whole regex may unnecessary if i think want appears first colon one unless really mean group i think which means could skip regex since matching anyhow use something like name namesplit,is way regular expression match inside block would interfere code inside else block in following code i test strings inputed jobname appended deljobids array only appended j jobs name jobsj jobname precompilewwd name name namepmatchnamegroup else namejobname state c print ok deljobidsappendj pass namejobname state c deljobidsappendj namenone if i comment line namepmatchnamegroup one case get appended get appended i also append job uncommmenting code else block string passes conditon getting appended the difference strings colon dashes one string neither i tested regex multiple times the string without dashes colons go else clause use default name defined top loop,1 try setting button style toolbar actions added selftbnavigatesettoolbuttonstyleqtcoreqttoolbuttontextundericon selfactionbackseticontextback,i learning pyqt playing examples in case i playing webbrowser example located pythonlibsitepackagespyqtexamplesactiveqtwebbrowser the demo something really odd add one line set icon text property qaction here code sample change i tried selfactionback qtguiqactionmainwindow selfactionbackseticonqtguiqiconiconsimagexpm selfactionbacksetobjectnameactionback added line selfactionbackseticontextback one time i tried entire toolbar went blank i reproduce i effect one line change what i trying figure qaction toolbar text button beside image done like is way make toolbar text plus icon,3 to break loop use break instead return or put loop control construct function functions return values,when running following code python mac mac os x true return false i get following error syntaxerror return outside function i carefully checked errant tabs andor spaces i confirm code fails error i use recommended spaces indentation this behavior also happens return placed inside control statements eg etc any help would appreciated thanks,3 this prints enodev no device import errno os def errortexterrnumber return errnoerrorcodeerrnumber osstrerrorerrnumber print errortexterrnoenodev,i using ctypes module ptrace system calls linux actually works pretty well but i get error i wanna provide useful information therefore i geterrno function call returns value errno i found function something else interprets errno value gives associated error message am i missing something is ctypes based solution here setup import logging ctypes import geterrno cdll ctypesutil import findlibrary errno load c lib libc cdllloadlibraryfindlibraryc useerrnotrue example returncode libcptraceptraceattach pid none none returncode errno geterrno errormsg wanna provide information error loggererrorerrormsg,1 if ok installing additional libs like xuggler use shorter way loads external file sure also generate soundpackets run it fragment tutorials site httpwwwxugglecomxugglerdownloadsfinaljsp imediareader reader toolfactorymakereaderyourmp imediaviewer viewer toolfactorymakeviewer readeraddlistenerviewer readerreadpacket null,just wondering library java like module pyaudiere python simply allows create tones play like sample python code device audiereopendevice tone devicecreatetone create hz tone toneplay tonestop this simply assigns variable default sound device makes tone device plays stops are libraries like simple use i appreciate feedback thanks d,1 python actually robust you b,lets say lists lol gg rofl b kek muh bobo lol lol kek bobo bobo gg how check first element found first element b,1 if need know string b pass however problem return true lol b lol c pass lol b xxlolxx c pass so care words vs simple presence long delimiters consistent bsplit pass if need know word position idx bsplitindexa note throws valueerror list if need know position string idx bfinda returns found if want know element corresponding element b ignores extra entries either list zipa b check simple membership isplit zipa b check whole words,lets say lists lol gg rofl b kek muh bobo lol lol kek bobo bobo gg how check first element found first element b,1 just b return true false maybe want check seti j b j j b j python,lets say lists lol gg rofl b kek muh bobo lol lol kek bobo bobo gg how check first element found first element b,2 you use python c code,i need pick numbers text files i pick lines i need grep know extract numbers lines a colleague showed bash perl cat resultstxt perl pe sddn however i usually code python perl so question could i used python way ie could i piped something bash python gotten result straight stdout makes sense or perl convenient case,1 yes use python command line python c stuff run stuff python code example python c import sys print syspath there direct equivalent p option perl automatic inputoutput linebyline processing mostly python use concept whatnot perl python input output done manually via rawinput input print print for particular example cat resultstxt python c import sys print joinresubr ddn r line line sysstdin obviously somewhat unwieldy it probably better write script actual python,i need pick numbers text files i pick lines i need grep know extract numbers lines a colleague showed bash perl cat resultstxt perl pe sddn however i usually code python perl so question could i used python way ie could i piped something bash python gotten result straight stdout makes sense or perl convenient case,3 not possible planned way without lot work if bold adventurous read wikipedia article meta circular evaluation python pretty good inspection reflection compilerevaluater objects may able cobble something together along lines metacircular implementations suited extending language written they also useful writing tools tightly integrated programming language sophisticated debuggers a language designed metacircular implementation mind often suited building languages general even ones completely different host language httpenwikipediaorgwikimetacircularevaluator i believe pypy something similarily might want look httppypyorg,is possible make userdefined python function act like statement in words i like able say myfunc rather myfunc get called anyway way say print would i already hear composing responses horrible thing i stupid asking i want i really something else instead please take word something i need debug problem i going checked used like air traffic control system,1 i know existing plugin everything mentioned certainly sounds doable one way another you use tracadmin cli command get list wiki pages dump contents particular wiki page plain text file stdout using write script reads wiki pages parses content links generates graph pages link this pinpoint orphans pages linked pages link source files pages link external resources running external links something like wget help identify broken links to access lastedited dates want query trac database the query need depend particular database type using for playing database relatively safe easy manner i find wikitablemacro tracsql plugins quite useful the hardest feature question implement would one regarding page views i think trac keeps track page views probably parse web server log sort information,hi guys is way improve trac wiki quality using plugin deals artifacts like obsolete pages pages refer code exist anymore pages unlinked pages low updaterate i think might several heuristics could used prevent wikirot number recent edits number recent views wether page links source file wether wiki page last update source files links wether entire directories wiki usededitedignored last n days etc etc etc if nothing else metrics alone would useful page directory administrative standpoint,1 you theory python anywhere near much regex magic perl resulting command much unwieldy especially use regular expressions without importing probably need sys sysstdin the python equivalent colleague perl oneliner approximately import sys line sysstdin print resubr ddn r line,i need pick numbers text files i pick lines i need grep know extract numbers lines a colleague showed bash perl cat resultstxt perl pe sddn however i usually code python perl so question could i used python way ie could i piped something bash python gotten result straight stdout makes sense or perl convenient case,1 you problem solved several ways i think consider using regular expression perl example directly python regular expressions module an example would import filecontent open somefiletxt read print refindall dd filecontent i would prefer using instead n line endings line endings different operational systems file encodings if want call bash commands inside python could use import os ossystemmycommand where command bash command i use time operations better perform bash python finally want extract numbers grep use option prints matched part,i need pick numbers text files i pick lines i need grep know extract numbers lines a colleague showed bash perl cat resultstxt perl pe sddn however i usually code python perl so question could i used python way ie could i piped something bash python gotten result straight stdout makes sense or perl convenient case,1 taking literally mean stub loaded straight import make unloadable untrusted code import sys sysmodules os none sysmodules system none of course module system might meant sys case trouble if trying keep untrusted code able bad things take look httpwikipythonorgmoinsandboxedpython realise something immediately feasible,in python script i want prevent certain stdlib modules os sys imported how would i accomplish,3 another way get number occurrences item dictionary dicti acounti,given item i count occurrences list python,3 don import more generally execute untrusted code inside module eval looks spiffy almost certainly friend if intent sandboxing external code look sandboxedpython article python wiki until read understood everything please try,in python script i want prevent certain stdlib modules os sys imported how would i accomplish,1 you less gave generic answer tagging sandbox need kind sandbox things come mind using jpython jruby run jvm within jvm create sandbox using policy file code jvm thing allow for c code difficult the brute force answer could run c code virtual machine networking capabilities i really elegant answer right one,suppose i script written python ruby program written c how i ensure script access network capabilities,3 i found subclass pickler wrap picklersave method try except block import pickle class mypickler picklepickler def saveself obj try picklepicklersaveself obj except exception e import pdbpdbsettrace then call like import stringio output stringiostringio mypickleroutputdumpthingee,when pickle object attributes cannot pickled fail generic error message like picklingerror can pickle type instancemethod attribute lookup builtininstancemethod failed is way tell attribute caused exception i using python even though i understand principle root cause problem eg example instance method still hard exactly pinpoint in case i already defined custom getstate method forgot critical attribute this happened complicated structure nested objects took identify bad attribute as requested one simple example pickle intentionally fails import cpickle pickle import new class testobject pass def testfuncself pass test test pickledumpstest print instancemethod testtestmeth newinstancemethodtestfunc test pickledumpstest this output instancemethod traceback recent call last file homewilbertdevelopworkspaceplaygroundsrcmiscpicklefailpy line module pickledumpstest file homewilbertlibpythoncopyregpy line reduceex raise typeerror pickle objects basename typeerror pickle instancemethod objects unfortunately hint attribute testmeth causes problem,2 variations question asked the short answer return break code executed binding i gave much longer answer python gui events order,i using tkinter text box python using script entrytype box enter pressed copies contents different text box deletes entry one i bound necessary event text box enter key pressed the problem i whenever i hit enter key seems execute event widgets default binding adding newline i sure way either delete newline added simply get rid widgets default binding thanks lot,1 i tell gae particular i tell biting bullet nothing using virtualenv virtualenvwrapper make python development smoother simpler easier around the head low benefits many switch now,i currently developing python project growing i may implement webapp gae future as project growing i pruning potentially reusable code separate packages amp modules present pythonpath do advice structure project reusable packages fit nicely gae project future looking recommendations gae project structure posts seem fairly flat best way go what rd party packagesmodules is best bite bullet use virtualenv beginning thanks much prembo,1 you certainly add weights edges networkx in fact set arbitrary data edges since basically dict in import networkx nx in g nxgraph in gaddedge weight typegreen in g out type green weight in gweight out furthermore change parameters edges nodes added in gweight in del gtype in gcolor green in g out color green weight and course calculate path according weights attribute specified weight parameter in gaddedge weight in gaddedge weight in gedges out in nxshortestpathg source target weightweight out for case deciding edge weights might tricky bear mind weighted shortest path calculated usually djikstra algorithm favors smaller weights it also requires positive weights one possible solution would assigning weight maxkikj edge ij ki kj degree nodes j the correct way compute shortest paths transition probabilities transform edge weights represent surprisal negative log probability this results weights positive given shortest path interpreted minimizing surprisal and since dijkstra algorithm sums weights log space means really multiplying probabilities to recover joint probability observing given shortest path take exponential negative surprisal,i using networkxlibrary python deal graphs i basically nodes various edges want see path would look like used nodes connected i use command see number connections lengedgescurrentnode i get number edges i sure apply list path for example i add number attribute i think attributes taken consideration finding path i adding edges connected i cannot add weights edges the problem higher score i want path followed edges i think follows lowest weighted edge i wondering approach people take find paths based certain characteristics node if someone knows networkx great i think networkx many features i get theory general approach i sure i find way python update sorry i might explaining wrong i understand i add attributes nodes i sure make path decisions based attributes so case based certain conditions i adding edges nodes each group nodes represents different daydaydata daydata daydata i connecting nodes day nodes day certain rules matched once i edges connected i want ones considered heavily choosing path so i added attribute weight node current day basically total number edges connecting node my problem weight attribute used path decision making attribute i created labeled myselfi could create label named abc hello world would apply attribute node how i get weight considered creating paththe edges already created i think i go back recreate,2 unless using sandboxed version python using pypy example reliable way switchoff network access within script of course could run vm network access shut,suppose i script written python ruby program written c how i ensure script access network capabilities,1 if use subprocess module best bet recode awk script python to end fileinput module great transition tool awklike feel,i trying run awk script using python i process data is way get awk script run python class without using system class invoke shell process the framework i run python scripts allow use subprocess call i stuck either figuring way convert awk script python possible running awk script python any suggestions my awk script basically read text file isolate blocks proteins contains specific chemical compound output generated framework i add example looks like isolate printing different file buildprotein compounda compoundb begin fusion calculate lots text multiple lines lines final result h value co value compound value other compounds x value y value zvalue another similar block so example i build protein i need see compounds i chcooh final result line i take whole block starting command buildprotein beginning next block save file move next see compound i looking forif i skip next end file file multiple occurrence compound i search sometimes contiguous times alternate blocks compound any help welcome banging head weeks finding site i decided ask help thanks advance kindness,2 python module help bothered regular expressions need quick field seperation use built str split find functions,i trying run awk script using python i process data is way get awk script run python class without using system class invoke shell process the framework i run python scripts allow use subprocess call i stuck either figuring way convert awk script python possible running awk script python any suggestions my awk script basically read text file isolate blocks proteins contains specific chemical compound output generated framework i add example looks like isolate printing different file buildprotein compounda compoundb begin fusion calculate lots text multiple lines lines final result h value co value compound value other compounds x value y value zvalue another similar block so example i build protein i need see compounds i chcooh final result line i take whole block starting command buildprotein beginning next block save file move next see compound i looking forif i skip next end file file multiple occurrence compound i search sometimes contiguous times alternate blocks compound any help welcome banging head weeks finding site i decided ask help thanks advance kindness,1 int give integer value ie trunc able specify decimals guess import math def truncinvalue digits return intinvaluemathpowdigitsmathpowdigits,i want remove digits float fixed number digits dot like i need output string another function print also i want ignore lost digits round,1 well oauth access token grants access blogs oauth give permission access blog methods could post,so code uses xauth authentication call tumblr api methods import urllib import urlparse import oauth oauth consumerkey consumersecret consumer oauthconsumerconsumerkey consumersecret client oauthclientconsumer resp content clientrequest httpswwwtumblrcomoauthaccesstoken post urlliburlencode xauthmode clientauth xauthusername yandexru xauthpassword token dicturlparseparseqslcontent print token token oauthtokentoken oauthtoken token oauthtokensecret client oauthclientconsumer token response data clientrequest httpapitumblrcomvbloggoodtumblrcomfollowers method get print data it works perfect user methods tumblr api require oauth authentication but fails try call blog method oauth authentication followers example metastatusmsgnot authorizedresponse except one thing if use blog name basehostname parameter works without errors weird how possible is something wrong code,1 both execnet pyro mention pypy cpython communication other packages python wiki parallel processing page probably suitable,what would interprocess communication ipc frameworktechnique following requirements transfer native python objects two python processes efficient time cpu ram efficiency irrelevant crossplatform winlinux nice works pypy update processes host use versions python modules update processes run independently user one spawns others,3 something like import operator makebinary lambda opfn lambda selfother binaryopself asmagicnumberother opfn makerbinary lambda opfn lambda selfother binaryopasmagicnumberother self opfn class magicnumberobject add makebinaryoperatoradd sub makebinaryoperatorsub mul makebinaryoperatormul div makebinaryoperatordiv radd makerbinaryoperatoradd rsub makerbinaryoperatorsub rmul makerbinaryoperatormul rdiv makerbinaryoperatordiv def negself return unaryopself lambda x x property def valueself return selfeval class constantmagicnumber def initself value selfvalue value def evalself return selfvalue class parameterconstant def initself superparameter selfinit def setvalueself v selfvalue v value propertyfsetsetvalue fgetlambda self selfvalue class binaryopmagicnumber def initself op op operation selfop op selfop op selfopn operation def evalself return selfopnselfopeval selfopeval class unaryopmagicnumber def initself op operation selfop op selfoperation operation def evalself return selfopnselfopeval asmagicnumber lambda x x isinstancex magicnumber else constantx and action x parameter xx x x xvalue print yvalue prints xvalue print yvalue prints compute series xy values function print xvalue yvalue xvalue range prints,i wondering exists python module would allow something like x magicnumber xvalue x print xvalue print so magicnumber would implement special operator methods would return instances magicnumber keeping track operations performed is class edit clarification i want use module remember lot parameters arbitrary calculation user wishes perform so user set parameters use produce result then decides like alter parameter change reflected result immediately so simplified usage session one parameter instance would look like p myparams pdistance i use getattr setattr pspeed getattr returns magicnumber instances time pdistance pspeed edit clarification okay i i done start i provide context you engineer produce latex document detailing workings properties prototype gadget it task repeatedly different prototypes you write small latex python interface for prototype create python module generates requisite document in type latex code calculating variables needed calculations context after notice two problems the number variables parameters makes locals mess variable names hard remember you group categories keep track you sometimes need redo calculation spread last couple chapters dozen lines one parameters changed you find way avoid code duplication out problem comes original question,3 you use strsplit method mystring abcde mylist mystringsplit print mylist a b c d e if want convert tuple print tuplemylist a b c d e if looking append list try mylistappend f print mylist a b c d e f,given string sequence several values separated commma mstr abcde how i convert string list mlist a b c d e,3 somestring abcde newtuple tuplesomestringsplit newtuple a b c d e,given string sequence several values separated commma mstr abcde how i convert string list mlist a b c d e,2 you could change lines like billy studenttool hammer tommy studenttool hammer that produce distinct instance tool class instance student class trouble posted example code called tool use words,as example couple dummy objects used together fwiw using python class studentobject def initself tool selftool tool def drawself selftoolbroken true print i used tool sweet else print my tool broken wah class toolobject def initself name selfname name selfbroken false def breakself print the busted selfname selfbroken true hammer toolhammer billy studenthammer tommy studenthammer that probably enough code see i going if i call hammerbreak i calling instance object billy hammer broken tommy really hammer now obviously program limited billy tommy instances students fix would obvious instantiate hammers but clearly i asking simple heh i would like know possible create objects show unique instances every time called edit the kind answers i getting lead believe i gaping hole understanding instantiation if i something like class fooobject pass class moofoo pass class guyobject def initself thing selfthing thing bill guymoo steve guymoo each time i use moo separate instance reference object if separate whole question withdrawn ahve make way mind getting blown,1 just call tool hammer every time want create new tool h tool hammer h tool hammer billy studenth tommy studenth,as example couple dummy objects used together fwiw using python class studentobject def initself tool selftool tool def drawself selftoolbroken true print i used tool sweet else print my tool broken wah class toolobject def initself name selfname name selfbroken false def breakself print the busted selfname selfbroken true hammer toolhammer billy studenthammer tommy studenthammer that probably enough code see i going if i call hammerbreak i calling instance object billy hammer broken tommy really hammer now obviously program limited billy tommy instances students fix would obvious instantiate hammers but clearly i asking simple heh i would like know possible create objects show unique instances every time called edit the kind answers i getting lead believe i gaping hole understanding instantiation if i something like class fooobject pass class moofoo pass class guyobject def initself thing selfthing thing bill guymoo steve guymoo each time i use moo separate instance reference object if separate whole question withdrawn ahve make way mind getting blown,1 you create new instances tool student class studentobject def initself tool selftool tool def drawself selftoolbroken true print i used tool sweet else print my tool broken wah class toolobject def initself name selfname name selfbroken false def breakself print the busted selfname selfbroken true instead instance make callable returns new one def hammer return tool hammer pass new object instead type billy studenthammer tommy studenthammer,as example couple dummy objects used together fwiw using python class studentobject def initself tool selftool tool def drawself selftoolbroken true print i used tool sweet else print my tool broken wah class toolobject def initself name selfname name selfbroken false def breakself print the busted selfname selfbroken true hammer toolhammer billy studenthammer tommy studenthammer that probably enough code see i going if i call hammerbreak i calling instance object billy hammer broken tommy really hammer now obviously program limited billy tommy instances students fix would obvious instantiate hammers but clearly i asking simple heh i would like know possible create objects show unique instances every time called edit the kind answers i getting lead believe i gaping hole understanding instantiation if i something like class fooobject pass class moofoo pass class guyobject def initself thing selfthing thing bill guymoo steve guymoo each time i use moo separate instance reference object if separate whole question withdrawn ahve make way mind getting blown,2 i try brief well i always try brief level success pretty much randomrandint never so yeah lol you even failed brief announcing try brief first need clear called means presumably want new hammer every time selftool object happens you want new instance every time example access tool attribute always get new presumably unbroken hammer every time check selftoolbroken a couple approaches one give tool copy method produces new object equal original object different instance for example class tool def initself kind selfkind kind selfbroken false def copyself result toolselfkind resultbroken selfbroken return result then student init say selftool toolcopy option two use factory function def makehammer return toolhammer class student def initself factory selftool factory billy studentmakehammer i think way python write line selftool object object automagically make copy i think want one thing i like python wysiwyg if want magic use c i think makes code hard understand tell line code even tell anything special note get even fancier factory object for example class realisticfactory def initself kind failurerate selfkind kind selffailurerate failurerate def makeself result toolselfkind randomrandom selffailurerate resultbroken true selffailurerate selffailurerate return result factory realisticfactoryhammer billy studentfactorymake tommy studentfactorymake tommy tool slightly likely broken,as example couple dummy objects used together fwiw using python class studentobject def initself tool selftool tool def drawself selftoolbroken true print i used tool sweet else print my tool broken wah class toolobject def initself name selfname name selfbroken false def breakself print the busted selfname selfbroken true hammer toolhammer billy studenthammer tommy studenthammer that probably enough code see i going if i call hammerbreak i calling instance object billy hammer broken tommy really hammer now obviously program limited billy tommy instances students fix would obvious instantiate hammers but clearly i asking simple heh i would like know possible create objects show unique instances every time called edit the kind answers i getting lead believe i gaping hole understanding instantiation if i something like class fooobject pass class moofoo pass class guyobject def initself thing selfthing thing bill guymoo steve guymoo each time i use moo separate instance reference object if separate whole question withdrawn ahve make way mind getting blown,1 go used compile nacl nacl moving target support removed go it probably resurrected point ifwhen nacl settles,would possible write native client application python go could run browser,3 try adding following class def reduceself return state information pickling return selfclass intselfhashcode strselffilepointer,i using yaml sqlalchemy i defined object i able use yaml print fine however i try use yaml object returned sqlalchemy query failing error pickle int objects i printed instance returned sqlalchemy showing correct type i let code talking class hashpointerbase tablename hashpointers id columninteger primarykeytrue hashcode columnvarbinary uniquetrue filepointer columntext def initself hashcode filepointer selfhashcode hashcode selffilepointer filepointer def reprself return hashpointer selfhashcode selffilepointer sqlalchemy import createengine sqlalchemyorm import sessionmaker engine createenginemysqluserpasslocalhostdb echotrue session sessionmakerbindengine session session fhash hashpointerx ctesttxt prints fine printyamldumpfhash instance sessionqueryhashpointerall prints fine as repr print instance throws error can t pickle int objects printyamldumpinstance,1 strip whitespace line see nonempty thus truthy if nonempty otherwise empty print horizontal line although i must say characters somewhat odd termwidth contextlibclosingfileinputinput myfile inplacetrue f line f linestrip sysstdoutwrite l formatlline else sysstdoutwrite n rjusttermwidth,i copying answer like line fileinputinput myfile inplacetrue sysstdoutwrite l formatlline add four underlines beginning line this turns myfile checklist but code prints underlines blank lines i want change blank lines full length lines how i so original lines like abc def ghi checklist look like abc def ghi thanks,1 searchterms b c user search query split list strings you accumulate keys order appearance buildup key frequencies one pass take advantage sort stability make sort decreasing frequency order appearance keysinorderofappearance keyfrequency defaultdictint item searchterms subquery someentityallkeysonlytrue subqueryfilter searchindex item searchindex stringlistproperty filters subqueryorder datecreated returneditem subquery key strreturneditem key keyfrequency keyorderofappearanceappendkey keyfrequencykey keys keysinorderofappearance order appearance kept secondary sort keyssortkeykeyfrequencygetitem reversetrue descending freq primary sort result someentitygetorderedkeylist,in lieu fulltext search gae i using solution return resultset sorted first keyword relevance secondly date though second sorting could anything really it feels bit bulky i concerned performance scale i looking optimization suggestions different approach altogether the secondary sorting important use case since given search likely multple results relevance measured number keyword matches preserving original query ordering adds lot complexity right any ideas step get list keys match search term resultskeylist searchterms b c user search query split list strings query search term add results list yields list keys frequency occurance indicating relevance item searchterms subquery someentityallkeysonlytrue subqueryfilter searchindex item searchindex stringlistproperty filters subqueryorder datecreated returneditem subquery resultskeylistappendstrreturneditem step group list frequency maintaining original order return dictionary keys frequency occurrence groupedresults defaultdictint key resultskeylist groupedresultskey sortedresults known set creates empty list match frequency rangelensearchterms sortedresultsappend using original results ordering construct array results grouped ordered descending frequency key resultskeylist key known continue frequency groupedresultskey sortedresultslensearchterms frequencyappendkey knownaddkey combine single list orderedkeylist l sortedresults orderedkeylistextendl del orderedkeylistoffset del orderedkeylistlimit result someentitygetorderedkeylist,1 q boundedqueue list they equal unless override eq repr used equality testing,in code i defined class repr method the representation class list def reprself selffront selftail q selfqueueselffrontselftail elif selffront selftail q selfqueueselffront qextendselfqueueselftail return qrepr i written following unittest test method def testenqueueself q boundedqueue qenqueue selfassertequalq however i end assertion error traceback recent call last file testinternmatchqueuepy line testenqueue selfassertequalq assertionerror i sure problem human eyes i tried several variations repr method returned errors well return reprq return strq,2 as recursive states repr used detect whether two values equal you several options define eq python calls check equality i recommend i really see boundedqueue equal list define items method returns list then check equality list add way build boundedqueue list then write eq check equality two boundedqueues,in code i defined class repr method the representation class list def reprself selffront selftail q selfqueueselffrontselftail elif selffront selftail q selfqueueselffront qextendselfqueueselftail return qrepr i written following unittest test method def testenqueueself q boundedqueue qenqueue selfassertequalq however i end assertion error traceback recent call last file testinternmatchqueuepy line testenqueue selfassertequalq assertionerror i sure problem human eyes i tried several variations repr method returned errors well return reprq return strq,1 i suggest try xulrunner instead python project xulrunner toolkit created mozilla used firefox thunderbird create gui it based xul xmllike language javascript extensive support dominteractions like loading pages tweaking csshtml onthefly but insist python pyqt pretty nice web widget uses webkit render html css,i idea create parental supervision web browser the way works i create desktop application pythonpreferably using wxpython wxpythons webkit thats widget display html amp css http requests website go proxy server so someone wants access website httpgooglecom type url python browser request goes script server httpmywebservercomcgibinbrowserrequestpyurlhttpgooglecom the python script checks url list invalid urls passes script downloadsaccesses webpage amp sends back html amp relevant external css javascript files my question what python gui libraries simple easy use widgets display html and display css i finding html widgets cant display css especially wxpython plus widgets dont allow html html body tag elements do know best widget either wxpython python based gui show html amp css,1 checkout webkit pyqt pyside pygtk httpwwwpysideorgdocspysidepysideqtwebkitindexhtml httparstechnicacomopensourcenewscreatingrichinternetapplicationsonlinuxwithwebkitars httpwwwyoutubecomwatchveeerwjbcfk,i idea create parental supervision web browser the way works i create desktop application pythonpreferably using wxpython wxpythons webkit thats widget display html amp css http requests website go proxy server so someone wants access website httpgooglecom type url python browser request goes script server httpmywebservercomcgibinbrowserrequestpyurlhttpgooglecom the python script checks url list invalid urls passes script downloadsaccesses webpage amp sends back html amp relevant external css javascript files my question what python gui libraries simple easy use widgets display html and display css i finding html widgets cant display css especially wxpython plus widgets dont allow html html body tag elements do know best widget either wxpython python based gui show html amp css,1 you use lc single level b x x,i trying copy nested list know without using deepcopy function i used ba ba but turn shallow copy any hintswithout using deepcopy function the simpler code better,2 in main python documentation note bottom simplehttpserver documentation other modules pdb timeit similar notes,i found following code i enter command line python simplehttpserver where i find documentation modules i,2 my entry simulate copydeepcopy def deepcopyobj isinstanceobj dict return deepcopykey deepcopyvalue key value objitems hasattrobj iter return typeobjdeepcopyitem item obj return obj the strategy iterate across element passedin object recursively descending elements also iterable making new objects type i make claim whatsoever comprehensive without fault pass object references get started truly the point demonstrate cover every possible eventuality the source copydeepcopy lines long handle everything,i trying copy nested list know without using deepcopy function i used ba ba but turn shallow copy any hintswithout using deepcopy function the simpler code better,3 django macport work pydjango pydjango it python version using causes problem check see using python comes mac python installed via macport try python python python terminal on mac osx default python version the macport version you replace usrbinpython macport version using ln,i installed django via macports i wasted lot time making work it still work i would like completely uninstall django macports install easy install django i would like keep macports uninstall i read should useful how i achieve thank attention,1 the overall command line feature documented you use modules as noted individual standard lib modules best consult source code,i found following code i enter command line python simplehttpserver where i find documentation modules i,1 no even fpconst generates unpacking ieee bit sequences,are constants infinity python the way i found parse values string inf floatinf ninf floatinf,2 you use inf e ninf e,are constants infinity python the way i found parse values string inf floatinf ninf floatinf,2 i days ago fairly hard create geography rather geometry point access meter unit i small extra query extrawhere stintersects thegeom geometrystbufferstgeographyfromtext f yourpoint point yourdistance meters yourmoduleobjectfiltersomethingextrawhereextrawhereyourpoint yourdistance notice geography part buffer part,i using geodjango postgis then i trouble query postgres db table get data within distance meters updates i using geodjango i found something url httpsdocsdjangoprojectcomendevrefcontribgisgeoquerysetsstdfieldlookupdistancelte zipcodeobjectsfilter polydistancelte geom d but know prepare parameter variables polydistancelte function geom variable create d function yes parameter name d function,1 this tool allows render response using jinga templates read usage cherrypyexpose cherrypytoolsjinjafilename indexhtml def controllerkwargs return this dict template context,i tool right httptoolscherrypyorgwikijinja i,1 in modwsgi configuration set processes see httpcodegooglecompmodwsgiwikiconfigurationdirectiveswsgidaemonprocess details,i writing wsgi app using modwsgi i want ability many concurrent connections modwsgi spins new process request making impossible use threadingcondition notifying change one thread another thread i understand different ways provide real time messaging different running processes rpc amqp dbus jabber i looking specifically something close oneliners threadingwait threadingnotifyall when i using modwsgi running multiple threads essentially i working obviously two functions run different threads def putvalue user given new value update db notify waiting threads myconditionacquire myconditionnotifyall myconditionrelease def getvalue user requested receive new value point return value soon notified changed myconditionacquire myconditionwait myconditionrelease return val db once i looking something close oneliners threadingwait threadingnotifyall i mind setting configuration even something running background i fair amount code relies ability stop wait middle request notified may continue,1 if wanted longest line file like question title says one shockingly simple modern python maxopen testtxt keylen,i file follows format line string line line another string line short line i trying write python code get line x label string longest string length can help fix code please here i far f open testtxt r print f readnull topreadlinelength topreadlinenull line f checkifreadlinefind line checkifread print read label found means read line currentreadline else we sequence line currentread currentlengthlenline print currentlength print topreadlinelength inttopreadlinelength intcurrentlength print topreadline topreadlinecurrentreadnow topreadline label line string topreadlinelengthintcurrentlength print topreadline go next line print done print longest line print topreadline,3 to fetch label longest line build mapping labels linelengths in sample dataset looks like labels startwith line corresponding line immediately follows labellinelength line open testtxt linestartswith line label line else labellinelengthlabel lenline lastline line print maxlabellinelengthitems keylambda kv kv,i file follows format line string line line another string line short line i trying write python code get line x label string longest string length can help fix code please here i far f open testtxt r print f readnull topreadlinelength topreadlinenull line f checkifreadlinefind line checkifread print read label found means read line currentreadline else we sequence line currentread currentlengthlenline print currentlength print topreadlinelength inttopreadlinelength intcurrentlength print topreadline topreadlinecurrentreadnow topreadline label line string topreadlinelengthintcurrentlength print topreadline go next line print done print longest line print topreadline,3 you trying open string f try file openf r,i using following code open file based path set user getting errors any suggestions f rawinputn hello user n n please type path file press enter file open f r it says f undefined thing exists even though i defining using r read file,1 you f quotes myfile openf r f means string consisting letter f code looking file called f finding instead use f means value variable f also call variable store file file this easily done try avoid there already builtin class called file best practice hide builtin classes functions names this code see expect file represent file class variable one way see term use use help function helpfile help class file module builtin class fileobject filename mode buffering file object open file the mode r w reading default writing appending the file created exist and indendation significant python i recommend getting indentation exactly right posting code,i using following code open file based path set user getting errors any suggestions f rawinputn hello user n n please type path file press enter file open f r it says f undefined thing exists even though i defining using r read file,3 don put f quotes f variable holding string open using string value f file openf r,i using following code open file based path set user getting errors any suggestions f rawinputn hello user n n please type path file press enter file open f r it says f undefined thing exists even though i defining using r read file,1 i something like label none maxlen maxstr maxlabel none open ftxt f line f line linerstrip linestartswith line label line elif lenline maxlen maxlen lenline maxstr line maxlabel label print maxlabel maxstr it little bit generic problem statement allows multiple lines text per label,i file follows format line string line line another string line short line i trying write python code get line x label string longest string length can help fix code please here i far f open testtxt r print f readnull topreadlinelength topreadlinenull line f checkifreadlinefind line checkifread print read label found means read line currentreadline else we sequence line currentread currentlengthlenline print currentlength print topreadlinelength inttopreadlinelength intcurrentlength print topreadline topreadlinecurrentreadnow topreadline label line string topreadlinelengthintcurrentlength print topreadline go next line print done print longest line print topreadline,1 that easy achieve data open testtxt readlines maxlinepos dataindexmaxdata keylen prevline datamaxlinepos print prevline,i file follows format line string line line another string line short line i trying write python code get line x label string longest string length can help fix code please here i far f open testtxt r print f readnull topreadlinelength topreadlinenull line f checkifreadlinefind line checkifread print read label found means read line currentreadline else we sequence line currentread currentlengthlenline print currentlength print topreadlinelength inttopreadlinelength intcurrentlength print topreadline topreadlinecurrentreadnow topreadline label line string topreadlinelengthintcurrentlength print topreadline go next line print done print longest line print topreadline,2 when browsers read directly file looking http headers when python script answering browser http request different browser expects first lines http headers interprets would expect,this seem like stupid question i contenttypetexthtml html headtitlehellotitlehead body hhello worldh body html file called testtxt open browser html python script usrbinpython print contenttypetexthtmlrnrn print html print head print titlehello word first cgi programtitle print head print body print hhello word this first cgi programh print body print html everything works fine i see difference printing contenttypetexthtml top information browser requested,2 the sqlite module standard library would job nicely the photos small bits per color plane easily stored blob entries database stored single file,i storeretrieve large number images use program each image small icon x one associated string path icon related since small i thinking library allows store single file i would need store image path string i know pickle possible choice i also heard much complicated libraries hdf thanks help alessandro,2 may you change conn smtpsmtpserver port also respective email server,i following code successfully sent email using gmail address but tried use email account gmail one domain email it gaves socket error do need change something def sendemailusername password subject content toemail fromemail print sending email toemail smtpserver smtpgmailcom sender fromemail destination toemail username username password password textsubtype plain try content content subject subject msg mimetextcontent textsubtype msg subject subject msg from sender conn smtpsmtpserver connehlo connstarttls connehlo connloginusername password try connsendmailsender destination msgasstring print email sent successfully finally connclose except exception exc raise exc the email using domainssmoothpluscom i also tried updating smtpserver smtpgmailcom smtpserver smtpoutsecureservernet smptp domain also work please help,2 i elaborate raymond answer grouper available standard lib answer would quite close oneliner unluckily grouper defined itertools examples i think prefer version since functional i test performance least i opening file seeking twice i keeping whole contents memory itertools import iziplongest def groupern iterable fillvaluenone grouper abcdefg x abc def gxx args iteriterable n return iziplongestfillvaluefillvalue args max grouper opentesttxt keylambda xlenx,i file follows format line string line line another string line short line i trying write python code get line x label string longest string length can help fix code please here i far f open testtxt r print f readnull topreadlinelength topreadlinenull line f checkifreadlinefind line checkifread print read label found means read line currentreadline else we sequence line currentread currentlengthlenline print currentlength print topreadlinelength inttopreadlinelength intcurrentlength print topreadline topreadlinecurrentreadnow topreadline label line string topreadlinelengthintcurrentlength print topreadline go next line print done print longest line print topreadline,1 both ways equivalent although homework task seems require create d array first reshape d afterwards v nprandomrandint num numpy allocates single memory block num integers fills random values drawn uniformly interval returns array interprets d array ccontiguous d array num rows columns v nprandomrandint num z npreshapev num this thing explicitly v still d array z view v interpreting data d array this means changing value v also change z since arrays point memory z npreshapev num the make sense array dimensions cannot negative numpy support one dimension take special value means infer dimension automatically size array it seems also accepts negative numbers purpose undocumented feature that means might well bug removed future versions either reshape explicitly num use num let numpy autodiscover please also note assignment says four rows n columns whereas arrays num rows columns for example d array reshaped,the homework task sounds something like generate random vector n uniform integer numbers ranging reshape vector array four rows n columns representing outcome n throws four dice i come following solution import numpy np num v nprandomrandintnum so far good i noticed generated array x n shape point creation reshaped i considered following well v nprandomrandintnum z npreshapevnum is difference two terms v built from couple print statements seem terms shape i could make sense documentation,1 you need define uploadto function it accepts instance argument but forget creating instance pk yet save first save image,i converting legacy site originally written rails default images saved using format pkextension file always overwritten new file uploaded i like continue format django version i originally thought extending filesystemstorage would te way go i know way pass current model object anyone suggestion django way accomplish if i need write class extends imagefield manage just wondering something simple i missing edit what i did based on answer from surfeurx drtyrsa tempimage none def imagepathself uploadedfilename prefix designs extension ospathsplitextuploadedfilename selfpk none return prefix strselfpk extension else tmpname struuiduuid selftempimage prefix tmpname extension return selftempimage imageupload modelsimagefielduploadtoimagepath nulltrue blanktrue def saveself selfupdatedat datetimenow isnew selfpk none superdesign selfsave isnew selftempimage none osrenamemediaroot selftempimage mediaroot selfimagepathselftempimage selftempimage none the real problem i i want overwrite image this provide right file name looks like i going extend imagefield get overwrite found little guy httpdjangosnippetsorgsnippets,2 an http response consists headers body separate first rnrn received by time web server sends ordinary file already sent headers separator when script run however headers sent automatically so first case webserver guessed contenttype extension sent appropriate headers sending contents file in second script sent overriding header contenttype it webserver handles terms inserting standard http headers edit apache use modmine etcmimetypes map file extensions contenttypes it probably defaults textplain anything extension understands the browser probably works extension contenttype use plain files assumed contain data headers generated web server whereas cgi scripts expectedallowed generate headers,this seem like stupid question i contenttypetexthtml html headtitlehellotitlehead body hhello worldh body html file called testtxt open browser html python script usrbinpython print contenttypetexthtmlrnrn print html print head print titlehello word first cgi programtitle print head print body print hhello word this first cgi programh print body print html everything works fine i see difference printing contenttypetexthtml top information browser requested,2 what definig base class mixin using inheritance class curuseronlydetailviewdetailview def getobjectself args kwargs obj supercuruseronlydetailview selfgetobjectargs kwargs objuser selfrequestuser raise permissiondenied else return obj class cardetailcuruseronlydetailview contextobjectname car templatename myappcardetailshtml model modelscar another view dry violation class bikedetailcuruseronlydetailview contextobjectname bike templatename myappbikedetailshtml model modelsbike,this model class carmodelsmodel user modelsforeignkeyuser relatedname cars name modelscharfieldmaxlength url pattern goes something like urlr carppkd loginrequiredcardetailsasview name cardetails and view class cardetaildetailview contextobjectname car templatename myappcardetailshtml model modelscar def getobjectself args kwargs car supercardetail selfgetobjectargs kwargs caruser selfrequestuser raise permissiondenied else return car this works fine every class i override getobject prevent user mess someone else objects this includes editing deleting every model i serious violation dry principle is better way something like loginrequired decorator maybe edit solution moreorless simple drtyrsa proposed answer one little difference i created base class curuseronly inherits object instead detailview i wanted use class deleteview updateview cardetail inherits curuseronly detailview cardelete inherits curuseronly deleteview funny thing i tried work i forgot python mro detailview first inheritance list curuseronly in end curuseronly class class curuseronlyobject def getobjectself args kwargs obj supercuruseronly selfgetobjectargs kwargs userattribute getattrself userattribute user user obj part userattributesplit user getattruser part none user selfrequestuser raise permissiondenied else return obj and i model direct contact user i need add userattribute field for example i model tyre foreignkey car deleteview would look like class tyredeletecuruseronly deleteview model modelstyre userattribute caruser,2 i think java slow nature this question may relevant java calculate sha hash large file efficiently,i found calculating sha java slow for example slower python i wrote two simple benchmarks calculate sha gb zeroes in cases result correct python time ms java time ms slower the result similar every time important difference how make calculation java faster benchmarks java import javasecuritymessagedigest import javasecuritynosuchalgorithmexception public class benchmarksha public static void mainstring args throws nosuchalgorithmexception int size byte bytes new bytesize messagedigest md messagedigestgetinstancesha long starttime systemnanotime int mdupdatebytes size long endtime systemnanotime systemoutprintlnstringformatx new javamathbiginteger mddigest systemoutprintlnstringformatd ms endtime starttime python usrbinenv python import hashlib import time size bytes bytearraysize md hashlibsha starttime timetime range mdupdatebytes endtime timetime print snd ms mdhexdigest endtime starttime results java benchmarksha bcdfeaefeffcebafccfddcfea ms python benchmarkshapy bcdfeaefeffcebafccfddcfea ms versions java python java version java version javatm se runtime environment build b java hotspottm bit server vm build b mixed mode python version python,1 have tried feeding data incrementally you use messagedigestupdate bytes get final digest messagedigestdigest allocating gb array memory fairly chunky operation you may find smaller incremental updates faster end,i found calculating sha java slow for example slower python i wrote two simple benchmarks calculate sha gb zeroes in cases result correct python time ms java time ms slower the result similar every time important difference how make calculation java faster benchmarks java import javasecuritymessagedigest import javasecuritynosuchalgorithmexception public class benchmarksha public static void mainstring args throws nosuchalgorithmexception int size byte bytes new bytesize messagedigest md messagedigestgetinstancesha long starttime systemnanotime int mdupdatebytes size long endtime systemnanotime systemoutprintlnstringformatx new javamathbiginteger mddigest systemoutprintlnstringformatd ms endtime starttime python usrbinenv python import hashlib import time size bytes bytearraysize md hashlibsha starttime timetime range mdupdatebytes endtime timetime print snd ms mdhexdigest endtime starttime results java benchmarksha bcdfeaefeffcebafccfddcfea ms python benchmarkshapy bcdfeaefeffcebafccfddcfea ms versions java python java version java version javatm se runtime environment build b java hotspottm bit server vm build b mixed mode python version python,2 when use smtpserver smtpgmailcom try port number may work,i following code successfully sent email using gmail address but tried use email account gmail one domain email it gaves socket error do need change something def sendemailusername password subject content toemail fromemail print sending email toemail smtpserver smtpgmailcom sender fromemail destination toemail username username password password textsubtype plain try content content subject subject msg mimetextcontent textsubtype msg subject subject msg from sender conn smtpsmtpserver connehlo connstarttls connehlo connloginusername password try connsendmailsender destination msgasstring print email sent successfully finally connclose except exception exc raise exc the email using domainssmoothpluscom i also tried updating smtpserver smtpgmailcom smtpserver smtpoutsecureservernet smptp domain also work please help,2 well unless compare two command line programs best test primarily numbers polluted vast differences overhead associated program vm start times vary memory allocation speeds vary to clean bit simply take two time samples actual md calculation within code this actually measure performance hashing operation,i found calculating sha java slow for example slower python i wrote two simple benchmarks calculate sha gb zeroes in cases result correct python time ms java time ms slower the result similar every time important difference how make calculation java faster benchmarks java import javasecuritymessagedigest import javasecuritynosuchalgorithmexception public class benchmarksha public static void mainstring args throws nosuchalgorithmexception int size byte bytes new bytesize messagedigest md messagedigestgetinstancesha long starttime systemnanotime int mdupdatebytes size long endtime systemnanotime systemoutprintlnstringformatx new javamathbiginteger mddigest systemoutprintlnstringformatd ms endtime starttime python usrbinenv python import hashlib import time size bytes bytearraysize md hashlibsha starttime timetime range mdupdatebytes endtime timetime print snd ms mdhexdigest endtime starttime results java benchmarksha bcdfeaefeffcebafccfddcfea ms python benchmarkshapy bcdfeaefeffcebafccfddcfea ms versions java python java version java version javatm se runtime environment build b java hotspottm bit server vm build b mixed mode python version python,2 you simplest way list list list,i trying append new float element list within another list example list listappend and i get following print list when i like get how i thanks advance,2 here one it works answers would fail eg input file like line abc line defg line hij but rely format file said open testtxt f spam freadlines labels spam lines spam dictziplabels lines longestlineslabel maxd keylambda x lendx print longest line print longestlineslabel dlongestlineslabel,i file follows format line string line line another string line short line i trying write python code get line x label string longest string length can help fix code please here i far f open testtxt r print f readnull topreadlinelength topreadlinenull line f checkifreadlinefind line checkifread print read label found means read line currentreadline else we sequence line currentread currentlengthlenline print currentlength print topreadlinelength inttopreadlinelength intcurrentlength print topreadline topreadlinecurrentreadnow topreadline label line string topreadlinelengthintcurrentlength print topreadline go next line print done print longest line print topreadline,1 you need define uploadto function,i creating site users upload images i need make sure filename unique name prevent files overwriting i generate unique name but i change filename saving file i see ways change folder saved quite i class savedphotosmodelsmodel name modelscharfieldmaxlength photo modelsimagefielduploadto imagesthings blanktrue nulltrue in code i newname getuniquename p savedphotosname newname photo requestfiles psave what i need actual name saved file newname,3 jsonitemexporter fairly simple class jsonitemexporterjsonlinesitemexporter def initself file kwargs selfconfigurekwargs selffile file selfencoder jsonjsonencoderkwargs selffirstitem true def startexportingself selffilewrite def finishexportingself selffilewrite def exportitemself item selffirstitem selffirstitem false else selffilewrite n itemdict dictselfgetserializedfieldsitem selffilewriteselfencoderencodeitemdict so two conclusions file created pipeline active hooks spideropened spiderclosed events processitem never called maybe item scraped item passed pipeline also think bug code def spideropenedself spider file open sitemsjson spidername wb selffilesspider file selfexporter jsonitemexporterfile selfexporterstartexporting selfexporter jsonitemexporterfile mean one exporter active time once spider opened create exporter while spider active another one open selfexporter overwritten new exporter,so i spent quite bit time going scrapy documentation tutorials i since plugging away basic crawler however i able get output json file i feel like i missing something obvious i able turn anything looking number examples trying several different things to thorough i include relevant code what i trying get specific items associated prices the prices change fairly often items change much lower frequency here itemspy class cartitemsitem url field name field price field and spider scrapyselector import htmlxpathselector scrapycontribspiders import crawlspider rule scrapyitem import item field exampleitems import cartitems class domainspidercrawlspider name examplecom alloweddomains examplecom starturls httpwwwexamplecompathtodesiredpage def parseself response hxs htmlxpathselectorresponse cart cartitems cart url hxsselect titletext extract cart name hxsselect tdtext extract cart price hxsselect tdtext extract return cart if example i run hxsselect tdtext extract scrapy shell url httpwwwexamplecompathtodesiredpage i get following response u text field i trying download edit okay i wrote pipeline follows one i found wiki i somehow missed section i digging last days altered use json instead xml scrapyxlibpydispatch import dispatcher scrapy import signals scrapycontribexporter import jsonitemexporter class jsonexportpipelineobject def initself dispatcherconnectselfspideropened signalsspideropened dispatcherconnectselfspiderclosed signalsspiderclosed selffiles def spideropenedself spider file open sitemsjson spidername wb selffilesspider file selfexporter jsonitemexporterfile selfexporterstartexporting def spiderclosedself spider selfexporterfinishexporting file selffilespopspider fileclose def processitemself item spider selfexporterexportitemitem return item this output file examplecomitemsjson contains so i something still right is issue spider pipeline done correctly clearly i missing something someone could nudge right direction link examples might help would appreciated,1 random sample set list numpy array nsample fast clear want anything like import random setsize samplesize max bigset set randomsample xrangemax setsize initial subset max def calc aset return set x x aset code sample calc new subset bigset add iter range asample randomsample bigset samplesize newset calc asample new subset max bigset newset you could use numpy arrays bitarray instead set i expect time calc dominate what setsize samplesize roughly,i need sample uniformly random number set fixed size calculation put new number back set the number samples needed large i tried store numbers list use randomchoice pick element remove append new element but way slow i thinking store numbers numpy array sample list indices index perform calculation are faster way process,1 i think tool pyscxml needs closer look this project uses wc definition state chart xml scxml state machine notation control abstraction scxml provides generic statemachine based execution environment based ccxml harel state tables currently scxml working draft chances quite high getting wc recommendation soon it th draft another interesting point highlight apache commons project aimed creating maintaining java scxml engine capable executing state machine defined using scxml document abstracting environment interfaces and certain tools supporting technology emerge future scxml leaving draftstatus,coming ruby world beautiful state machine frameworks like one recently baked rails i shocked find obvious candidate similar beauty python i like avoid rolling objectoriented state machine designs usually require sling bunch python every time add state i often case what framework state machines i using python code i like elegant code performance considerations,1 use numpy this lets use arrays add like vectors x numpyarange numpyarange total x with modified question add call sum well total numpysumxy,i use lot n dimensional arrays gets pain write indented code i know codes replaced list comprehensions inline statements for example x x print x xy replaced print x x x x but could i change action instead print something else like total xy so i want something like totalxy x x however work is smart way rather x x totalxy,3 as alternative writing loops n levels deep could use itertoolsproduct in import itertools in x itproduct x print x xy this extends naturally n dimensions,i use lot n dimensional arrays gets pain write indented code i know codes replaced list comprehensions inline statements for example x x print x xy replaced print x x x x but could i change action instead print something else like total xy so i want something like totalxy x x however work is smart way rather x x totalxy,3 tcp packets automatically chunked os application give hints flush apart application read write stream the oss two communicating peers automatically configure maximum packet sizes based mtu links path mtu discovery make sure block icmp packets get work since extremely unlikely wrong mtu problem mtu less often set anyway rediagnose problem example packet tracer wireshark,i implementing clientserver solution based twisted server side eg android phone client side because andoird emulator takes tcp packets larger b less i need able chunk packets server side without flushing socket transportwrite twisted buffers outgoing data chunking would useless without somekind manual automatic flushing maxpacketsize function how i twisted i familiar reactordoselect function since i using epoll reactor scalability performance reasons i cannot use doselect is possible change maxpacketvalue certain connections within twisted hoping someone show light,1 you use uploadto like def imagepathinstance filename return instanceid ospathsplitextfilename class brandmodelsmodel logo modelsimagefielduploadtoimagepath nulltrue blanktrue,i converting legacy site originally written rails default images saved using format pkextension file always overwritten new file uploaded i like continue format django version i originally thought extending filesystemstorage would te way go i know way pass current model object anyone suggestion django way accomplish if i need write class extends imagefield manage just wondering something simple i missing edit what i did based on answer from surfeurx drtyrsa tempimage none def imagepathself uploadedfilename prefix designs extension ospathsplitextuploadedfilename selfpk none return prefix strselfpk extension else tmpname struuiduuid selftempimage prefix tmpname extension return selftempimage imageupload modelsimagefielduploadtoimagepath nulltrue blanktrue def saveself selfupdatedat datetimenow isnew selfpk none superdesign selfsave isnew selftempimage none osrenamemediaroot selftempimage mediaroot selfimagepathselftempimage selftempimage none the real problem i i want overwrite image this provide right file name looks like i going extend imagefield get overwrite found little guy httpdjangosnippetsorgsnippets,2 in end i created python cbindings swig directly code i wanted test it turned several hundred times faster starting subprocesses,basic setup i using python script automatic testing programming project i working in test i run executable lots different options compare result previous runs the testing takes quite lot time since i roughly k different tests run at moment i split script two parts testmodule grabs tests jobqueue places results resultqueue mainmodule creates jobqueue checks results this allows play around using several testprocessesthreads far given improvement testing speed i running dualcore computer i would expect testprocesses work better quadcore in test module i create command string i execute using subprocesspopencmd shelltrue stdoutsubprocesspipe i read results pipe place resultqueue question is efficient way running lots lots command strings multicore system every popen i creates new process seems like might create quite bit overhead i really think better way i currently using python case matters edit os linux the subprocesses i spawn commandline cexecutables arguments,1 django handle unique filename correctly the duplicate file name renamed automatically if want set filename manually define uploadto function drtyrsa said this question may help,i creating site users upload images i need make sure filename unique name prevent files overwriting i generate unique name but i change filename saving file i see ways change folder saved quite i class savedphotosmodelsmodel name modelscharfieldmaxlength photo modelsimagefielduploadto imagesthings blanktrue nulltrue in code i newname getuniquename p savedphotosname newname photo requestfiles psave what i need actual name saved file newname,1 my master thesis student implemented app engine the project open source use however like i hope get idea might adapt needs,i currently developing python project growing i may implement webapp gae future as project growing i pruning potentially reusable code separate packages amp modules present pythonpath do advice structure project reusable packages fit nicely gae project future looking recommendations gae project structure posts seem fairly flat best way go what rd party packagesmodules is best bite bullet use virtualenv beginning thanks much prembo,1 see pythondocx official documentation available this worked well,is possible read write word files python without using com object i know i f open cfiledoc w fwritetext fclose word read html file native doc file,3 you foo import mydocstring foodoc yet simpler import mydocstring adoc,is way getting doc string python file i name file for instance i python file named apy i know doc string mandated know internal structure ie classes main etc i hope i forgetting something pretty obvious if i know main function i way using import filename apy foo importfilename filedescription inspectgetdocfoomain i way filenamedoc work,2 read documention command rawinput see get input user,below i script i done trying complete assignment i what script suppose ask user inputs return greater inputs this i havent figured completely yet the point assignment see happens i instead entering numbers enter two words hej h㥠what i need advice enable script accept user inputs return greater two def maximumx maxnra maxnrb lenx xi maxnra maxnra xi else print i fã¶rsta ordet ã¤r maximum maxnra leny yi maxnrb maxnrb yi else print i andra ordet ã¤r maximum maxnrb maximumhej h㥠edit i tried working another way way solving print first x input print second input def printmaxx x printx maximum elif b printx equal else printy maximum right im missing something cause returning anything i enter values,1 first need profile code understand exactly bottleneck also generic recommendation consider psyco although times psyco help once find bottleneck cython may useful need sure declare variables cython source,i currently requirement make comparison strings containing mac addresses eg aabbcc using python at present i preconfigured set containing mac address script iterates set comparing new mac address list this works great set grows script massively slows with notice massive difference does anybody advice speeding process is storing set best way compare better store csv db example sample code def detectp stamgmtstypes phaslayerdot ptype psubtype stamgmtstypes paddr observedclients this set locationmutex detection paddr strdatetimenow print typepaddr print detection lastlocation observedclientsappendpaddr,1 if want simple way get user input terminal window look rawinput function,below i script i done trying complete assignment i what script suppose ask user inputs return greater inputs this i havent figured completely yet the point assignment see happens i instead entering numbers enter two words hej h㥠what i need advice enable script accept user inputs return greater two def maximumx maxnra maxnrb lenx xi maxnra maxnra xi else print i fã¶rsta ordet ã¤r maximum maxnra leny yi maxnrb maxnrb yi else print i andra ordet ã¤r maximum maxnrb maximumhej h㥠edit i tried working another way way solving print first x input print second input def printmaxx x printx maximum elif b printx equal else printy maximum right im missing something cause returning anything i enter values,1 sum works total sumxy x x,i use lot n dimensional arrays gets pain write indented code i know codes replaced list comprehensions inline statements for example x x print x xy replaced print x x x x but could i change action instead print something else like total xy so i want something like totalxy x x however work is smart way rather x x totalxy,3 for sparse arrays use dict sparsearray sparsearray sparsearray print sparsearray show content sparse array print sparsearraykeys get used indices,i like arrays start say index go i interested creating memory space best proceed my d code follows arr row range col range arr arr traceback recent call last file stdin line indexerror list index range arr how selectively use specific range ie last index runs inclusive this maybe obvious way thanks suggestion dicts i avoiding i know much code i converting c i think dictionaries might saviour is way i asking arrays,1 you simply emulate list class offsetlistobject def initself offset selfoffset offset selflst def lenself return lenselflst def getitemself key return selflstkey selfoffset def setitemself key val selflstkey selfoffset val def delitemself key del selflstkey selfoffset def iterself return iterselflst def containsself item return item selflst all methods go backing list def getattrself return getattrselflst test like ol offsetlist olappend assert ol assert lenol,i like arrays start say index go i interested creating memory space best proceed my d code follows arr row range col range arr arr traceback recent call last file stdin line indexerror list index range arr how selectively use specific range ie last index runs inclusive this maybe obvious way thanks suggestion dicts i avoiding i know much code i converting c i think dictionaries might saviour is way i asking arrays,1 you cannot remove file handle file path since multiple paths refer file files like sockets even paths therefore import os f open tmptesttxt w osunlinkfname you still use f visible people handle close finished however better way solve problem use tempfile module deletes file automatically write devnull need file handle care content written,let say i open file previously exist writing f open tmptesttxt w once line executed file tmptesttxt created what cleanest way remove delete file file object f path,3 you get file name name member delete usual in f open tmptesttxt w in fname out tmptesttxt,let say i open file previously exist writing f open tmptesttxt w once line executed file tmptesttxt created what cleanest way remove delete file file object f path,2 import sourcestr you are probably familiar wildcard resubrar rbb sourcestr flagsreignorecase you barbe probably familibarb wildcbarbd,the goal prefix suffix occurrences substring caseinsensitive source string i basically need figure get sourcestr targetstr sourcestr you are probably familiar wildcard targetstr you barbe probably familibarb wildcbarbd in example i finding occurrences ar case insensitive replacing occurrence ie ar ar ar respectively prefix band suffix b,2 something like import arre recompilear rei print arresubrbb you are probably familiar wildcard perhaps,the goal prefix suffix occurrences substring caseinsensitive source string i basically need figure get sourcestr targetstr sourcestr you are probably familiar wildcard targetstr you barbe probably familibarb wildcbarbd in example i finding occurrences ar case insensitive replacing occurrence ie ar ar ar respectively prefix band suffix b,2 full answer f open tmptesttxt w fclose osremovefname you close file deleting documentation says throws exception windows file opened check f case handle it file delete directly,let say i open file previously exist writing f open tmptesttxt w once line executed file tmptesttxt created what cleanest way remove delete file file object f path,1 you probably need urlencode password you see error like password happens contain here local example actual values redacted opener urllibfancyurlopener instance xbfeac openeropen httpadminsomepassexamplecom addinfourl l whose fp socketfileobject object xbec openeropen httpadminsomepassaexamplecom invalidurl nonnumeric port somepass encode password openeropen httpadminsomepassfaexamplecom you use urllibquote somepassa safe encoding,following code theurl httpsssmembersdyndnsorgnicupdatehostnamesampmyipsampwildcardnochgampmxnochgampbackmxnochg username password hostname theip conn urlopentheurl send request url printconnread read response connclose close connection get following error file cpythonlibhttpclientpy line sethostport raise invalidurlnonnumeric port hosti any ideas,2 the year days long reshape have look scikitstimeseries import scikitstimeseries ts startdate tsdate h enddate tsdate h arrd d array time x y dates tsdatearraystartdatestartdate enddateenddate freq h tstimeseriesarrd datesdates make sure arrdshape lendates now access data daymonthyear objects tnplogicalandtday tmonth example dayofyear xrange year nprandomrandint tnplogicalandtdayofyear dayofyear tyear year returns x y array data day play attributes make work leap years,i d time x y numpy array containing hourly time series years say i would like create sampled time series containing instance calendar day randomly taken available records possibilities per day follows jan jan jan means i need take values values etc i working version works follows reshape input array add year dimension time year x y create values array randomly generated integers use nprepeat array integers extract relevant values example sampledvalues variablenparangenumberofdays valuesperdays sampledyearsrepeatvaluesperdays this seems work i wondering bestfastest approach solve problem speed important i loop adn would benefit testing many cases possible am i right thanks edit i forgot mention i filtered input dataset remove th feb leap years basically aim operation find days sample matches well long term time series terms mean etc if sampled time series passes quality test i want export start,2 if wanted go python route i look sqlalchemy list supported databases csv module python standard library personally i probably use elixir top sqlalchemy i find bit easier work simpler things i might also look numpy loadtxt i could got convenient features standard csv module like reading select columns example numpy might overkill application though,what best combination tools import daily data feed csv format mssql server table environment acceptable tools windows xp ruby python ms sql server remote server importing process done windows client machine,1 your selectexpression actually python expression selecttrue rolestablecisadmin rolestablecid else false rolestablecid personstablecroleid sqlalchemyselect see selecttrue someexpressionobject since column object rolestablecisadmin evaluate true boolean context i know top head sqlalchemy interpret surely work intended you rewrite expression correspond plain sql using sqlalchemysqlexpressioncase instead else columnproperty selectcaserolestablecisadmin rolestablecid else rolestablecid personstablecroleid in case however might much simpler solution person role seem n relation one person exactly one role i assume ormrelationship personrole get person role why add plain python property class person property def administratorself return selfrole selfroleisadmin selfroleid,i mapper table i want define columnproperty select true false whether entity propertie mapper person personstable properties administrator columnproperty select true rolestablecisadmin rolestablecid else false rolestablecid personstablecroleid label administrator is something i i interested part true rolestablecisadmin rolestablecid else false lets set value column based condition,2 you loop rows transposing calling iteritems date row dftiteritems logic i certain efficiency case to get best possible performance iterative algorithm might want explore writing cython could something like def myalgondarrayobject dates ndarrayfloatt open ndarrayfloatt low ndarrayfloatt high ndarrayfloatt close ndarrayfloatt volume cdef pyssizet n floatt foo n lendates n foo closei openi extremely fast i would recommend writing algorithm pure python first make sure works see fast fast enough convert things cython like minimal work get something fast handcoded cc,i want perform complex operations financial data dataframes sequential manner for example i using following msft csv file taken yahoo finance dateopenhighlowclosevolumeadj close i following usrbinenv python pandas import df readcsv tablecsv row enumeratedfvalues date dfindexi open high low close adjclose row perform analysis openclose based date etc is efficient way given focus speed pandas i would assume must special function iterate values manner one also retrieves index possibly generator memory efficient dfiteritems unfortunately iterates column column,3 doing job thoroughly going hard the problem recognizing function defined many possible layouts hard recognize possibilities for example int x return int yint z return z most ad hoc systems detect even detect handle x but lousy code layout probably indulge code layouts how start functions static void functionint arg static void functionint arg static void functionint arg static void function int arg static void function int arg etc depending notations used need write multiple different regular expressions note apply heuristics start line marks start function structureunion definition data initialization use end line containing function gets rather tricky you may need tokenize input keep track whether inside function definition although example used keywords functions using userdefined types xyz pqrabc def then course might old code written without prototypes xyz pqrdef abc def all get involved preprocessor stuff really confuse things define begin define end xyz pqrabc def begin end the original bourne shell source reputedly written using macros akin so normally develop ad hoc system recognizing functions laid style used project one hopes project systematic enough limited variety choices old code maintained many years many people likely special cases place,in regex script eg one written python i add printftracing calledn prettyfunction entry function definitions eg int functionnamecouldbeany uint ui insert entry printftracing calledn prettyfunction one file xxxc c files c directory workspacetestsrc please note functions defined file may share prefix always comment finstrumentfunctions work gcc else i provide cygprofilefuncenterexit functions find way print name binary address i wonder efficient way regex,1 depends program must if prints whether got url sysargvstartswith http might if must actually use url something useful urllib import urlopen try f urlopensysargv except valueerror invalid url f opensysargv,what standard practice python i commandline application taking one argument url web page path html file somewhere disk one sufficient code http sysargv print url else print path file,3 network method i would first get network cards installed everything if want something plugin go look card compatible ne that card work box windows problem in particular find com etherlink ii cb cheap online it excellent card the google shopping results list several from enable windows fileprint sharing service tcpip good go after done remotely manage upgrade machines saving lot headache later serialport method deanna suggestion using serial port network device transferring files normally work well however bit setup involved hassle never done there several software options i recommend laplink it fairly painless you could even go allout pickup multiport serial interface fairly cheap days manage computers centrally rs robust go long distance proper cabling networking ethernet way go though if possible choose option,i vb application running number old windows machines sometimes application upgraded the way accomplish today use hyperterminal send file null modem cable replacing machines option point i want write application take care transferring updating app null modem without rewriting vb app this means i free use anything i see fit what alternatives these ones i think i like know i wrong proscons also i prefer avoid cc possible python pyexe another vb app cc edit some clarifications reading comments i want make process easy possible today remove dismantle computer connect keyboard fire hyperterminal get going that i want something automatic i open suggestion existing solutions given specific needs i think there ethernet computers either solution needs able run rs and replacing machines option point just trust,1 the gae python sdk creates virtual environment running local environment virtualenv help much there frameworks like webpy djangononrel works well gae porting code least take inspiration folder structure,i currently developing python project growing i may implement webapp gae future as project growing i pruning potentially reusable code separate packages amp modules present pythonpath do advice structure project reusable packages fit nicely gae project future looking recommendations gae project structure posts seem fairly flat best way go what rd party packagesmodules is best bite bullet use virtualenv beginning thanks much prembo,1 you use bulk insert bcp utility,what best combination tools import daily data feed csv format mssql server table environment acceptable tools windows xp ruby python ms sql server remote server importing process done windows client machine,1 note i expert crypto either that said i took quick look pycrypto code github mailing list one things gives confidence good expert contributions code base the developers acknowledge insecurities work correct if specific use case need implemented securely look code ask list since seem leverage cc libraries work many cases check reputation base libraries directly,i planning using pycrypto project i want know whether pycrypto safe reliable enough use how i ensure pycrypto encrypting data correctly according various encryption algorithms rsa aes,2 while i experience djangoshibboleth i plain shibboleth if apache modshibboleth configured properly integrating web app relatively trivial check djangoshibboleth module see contain much code in particular modshibboleth already running use thirdparty saml library those bring lot unnecessary complexity,i investigating options using shibboleth django deployment from i found things look somewhat sparse can anyone comment following is anyone using djangoshibboleth module see httpcodearcsorgaugitoriousdjangodjangoshibbolethtrees if experiences module saml implementations django eg djangosamlsp python general eg pysaml appear somewhat experimental include little documentation does anyone know stable saml solutions djangopython thanks advance help,1 why use dictget dictpop default parameter,i got project i frequently something dict somevar dictsomething del dictsomething else errorhandlerorotherstuff however i idea use try somevar dictpopsomething except keyerror errorhandlerorotherstuff my question general fast try except constructs handle exceptions is ok use lot still faster stuff manually also sometimes i situation i convert value integer try somevar intdictpopsomething except keyerror errorhandlerorotherstuffno key except valueerror errorhandlerorotherstuffbad value key now solution exceptions seems quite nice since i checks one step also i removed original keyvalue pair dict part problem so i tell least looks like elegant solution however i sure faster disadvantages i worry,2 which construct makes code easier understand maintain pick one if resulting code slow go back consider whether different error handling strategy efficient,i got project i frequently something dict somevar dictsomething del dictsomething else errorhandlerorotherstuff however i idea use try somevar dictpopsomething except keyerror errorhandlerorotherstuff my question general fast try except constructs handle exceptions is ok use lot still faster stuff manually also sometimes i situation i convert value integer try somevar intdictpopsomething except keyerror errorhandlerorotherstuffno key except valueerror errorhandlerorotherstuffbad value key now solution exceptions seems quite nice since i checks one step also i removed original keyvalue pair dict part problem so i tell least looks like elegant solution however i sure faster disadvantages i worry,3 kv diteritems dk joinv,i dict like dict variable number list items always dict item how i merge thanks,1 case need concat string but want merge collection try b aextendb print,i dict like dict variable number list items always dict item how i merge thanks,1 larsmans might work check whether user actually specified argument import urllib import sys try arg sysargv except indexerror print usage sysargv fileurl sysexit try site urlliburlopenarg except valueerror file openarg,what standard practice python i commandline application taking one argument url web page path html file somewhere disk one sufficient code http sysargv print url else print path file,1 i working fine snow lepoard i upgraded lion i symlink gcc gcc running sudo env archflagsarch arch x easyinstall lxml looking gcc instead gcc,i tried run problems bunch times past does anyone recipe installing lxml os x without macports fink definitely works preferably complete steps downloading building dependencies,1 exceptions particularly slow obviously lot going exception handling simple unless literally million times per second speed difference negligible your example trivial reason worry speed begin microoptimizations like cost time thinking could ever save using the code given absolutely fine exceptions,i got project i frequently something dict somevar dictsomething del dictsomething else errorhandlerorotherstuff however i idea use try somevar dictpopsomething except keyerror errorhandlerorotherstuff my question general fast try except constructs handle exceptions is ok use lot still faster stuff manually also sometimes i situation i convert value integer try somevar intdictpopsomething except keyerror errorhandlerorotherstuffno key except valueerror errorhandlerorotherstuffbad value key now solution exceptions seems quite nice since i checks one step also i removed original keyvalue pair dict part problem so i tell least looks like elegant solution however i sure faster disadvantages i worry,2 you manually force refresh windowrefreshing events loop use updateidletasks methods toplevel tk refresh things properly see httpwwwpythonwarecomlibrarytkinterintroductionxeventprocessinghtm talks little,i tkinter window one button one text label when button pushed script downloads file using ftp i want label show current download progress the code download root window progress monitor work the label however starts update download finished point updates how i make code button starts run concurrently window mainloop communicate tkinter import time import sleep ftplib import ftp import os try root tk class processor def initself selfamounttransfered selfdownloadsize def windowselfmaster selfcontent framemaster selfcontentgridcolumn row selfcontentmastertitle parcel processor selfdownlbllabelselfcontenttext downloading gridcolumnrow selfdownvarstringvar selfdownvarset selfdownpctlabelselfcontenttextvariableselfdownvargridcolumnrow selfstartbuttonselfcontent text start commandselfparceldownloadergridcolumn row def handledownloadselfblock selfparcelzipwriteblock selfdownvarsetstrselfamounttransfered lenblockselfdownloadsize selfamounttransfered selfamounttransfered lenblock def parceldownloaderself oschdirrcgis projectsparcel downloads ftpftpftpsite user pass ftpdatelist filename ftpnlst filename pa ftpdatelistappendfilename parcels szip maxftpdatelist selfdownloadsizeftpsizeparcels try selfparcelzip openparcelszip wb ftpretrbinary retr parcels selfhandledownload selfparcelzipclose except exception e print e selfparcelzipclose finally ftpquit selfamounttransfered processorprocessor processorwindowroot rootmainloop except exception e print e sleep,2 you set either pythonpath set point additional directories private libraries if pyhonhome set python defaults using directory pythonexe found dir path,i going writing setup doc developers work python project i reading pythonpath environment variable i looking current development system think i things set wrong causing ide intellij behave incorrectly looking python libraries i looked documentation i still unsure actually pythonpath environment variable i pythonhome pointed cpython my current pythonpath set pythonhome should i also add directories syspath update based information pythonpath need set unless nonstandard libraries want python able find default for instance i install wxpython installer add libraries pythonpath i set pythonhome root python installation i add system path environment variable i run python,3 i created new django app i wanted it called djangofriendlytagloader available pypi httppypipythonorgpypidjangofriendlytagloader hackable httpsbitbucketorgjaapdjangofriendlytagloader it provides template tags friendlyload ifhastag ifnothastag friendlyload almost django builtin loader swallows invalidtemplatelibrary carries next library load ifhastag ifnothastag check template parser certain given tag either renders ignores bit template,i working django app provides templates optional functionality certain apps available it possible load unavailable template tag library using standard load django tag trying results templatesyntaxerror has anyone come solution problem ie conditional tag lib loader i something like loadifavailable apptags ifloaded apptags endif,1 for installations set variables since needed python run python knows find standard library the reason set pythonpath maintain directories custom python libraries want install global default location ie sitepackages directory make sure read httpdocspythonorgusingcmdlinehtmlenvironmentvariables,i going writing setup doc developers work python project i reading pythonpath environment variable i looking current development system think i things set wrong causing ide intellij behave incorrectly looking python libraries i looked documentation i still unsure actually pythonpath environment variable i pythonhome pointed cpython my current pythonpath set pythonhome should i also add directories syspath update based information pythonpath need set unless nonstandard libraries want python able find default for instance i install wxpython installer add libraries pythonpath i set pythonhome root python installation i add system path environment variable i run python,3 use sympy library you create matrix then calculate determinant and solve equation omega,as simple example let say matrix m omega omega need solve values omega satisfy condition det m how python,2 use underlying shell expand globs pid subprocesspopencatfilename shelltrue alternatively use globglob expand arguments running command import glob pid subprocesspopencat globglobfilename,how i invoke shell command python includes regexp ie cat filename i wrote pid subprocesspopencat filename i getting error cat filename file directory i like force shell treat regexp string is way implement,3 first regular expression shell expansion glob seem want execute which means invoke binsh execute cat the following trick pid subprocesspopenbinsh c cat filename now binsh actually perform asterisk expansion get desired result or use globbing library globbing expansions ie work shell pid subprocesspopencat globglobfilename globglob returns array files match globbing,how i invoke shell command python includes regexp ie cat filename i wrote pid subprocesspopencat filename i getting error cat filename file directory i like force shell treat regexp string is way implement,2 are receiving processing packet need suppress icmp portunreachable if maybe add entry iptables output chain drop,we occasionally debug glitchy cisco routers handle tcp selective acknowledgment sack options correctly this causes tcp sessions die routed iptables port redirection rule to help diagnosis i constructing pythonbased utility construct sequence packets reproduce error implementation uses raw sockets perform trick i got icmp ping working nicely i run snag udp implementation i construct send receive packet without problem issue i seeing linux like udp packets sent back remote system always sends icmp destination unreachable packet even though python script able receive process packet without apparent problems my question is possible subsume linux udp stack bypass icmp error messages working raw sockets thanks,1 you need make sure call oswalk unicode string silently change nonascii letters ascii change observed so file filesindirdirectoryu openfile r f print f def filesindirdirectory masku root dir files oswalkdirectory file globglobospathjoinroot mask yield file see also similar question,i unicode expert i read similar posts without conclusive solution i need snippet read files greek characters my files names like î™ïƒî¿î¶ïî³î¹î¿ î î»î·ïï‰î¼ïŽî½ î‘ïî³î¿ï ïƒï„î¿ï‚ xls i generator function yields filenames codingutf import os import glob def filesindirdirectory mask root dir files oswalkdirectory file globglobospathjoinroot mask yield file calling file filesindirdirectoryr openfile r f print f gives ioerror errno invalid mode r filename xb st xls how create valid file object using sort filenames,3 i would recommend using shibboleth native sp apache modshib it well tested large user base stable i took quick look djangoshibboleth module seems depends modshib saml in respect module simple probably works well i seen complete mostly complete python saml implementations none active project the xml security crypto requirements pain python likely contributes lack libraries edit i recant part the pysaml library development activity looks fairly complete cursory glance it uses xmlsec binary directly signatures encryption therefore rely outdated bindings this likely best bet using saml directly python moment,i investigating options using shibboleth django deployment from i found things look somewhat sparse can anyone comment following is anyone using djangoshibboleth module see httpcodearcsorgaugitoriousdjangodjangoshibbolethtrees if experiences module saml implementations django eg djangosamlsp python general eg pysaml appear somewhat experimental include little documentation does anyone know stable saml solutions djangopython thanks advance help,3 i found dirty solution i call rootupdate every subprocesscall to make sure buttons pressed processing seems problem rootupdate according quick google search i disable subprocesses started like tkinter import import subprocess filelist file file file file file def button bprocessconfigurestatedisabled go bprocessconfigurestatenormal def go filename filelist labelconfiguretextprocessing filename rootupdate proc subprocesscallcdtnastatrunexe filename print process terminated return code strproc labelconfiguretextall done root tk bprocess buttonroot textgo commandbutton bprocesspacksidetop label labelroot text press button start labelpacksidetop rootmainloop,i programmed gui calls cmd file several times different parameters class app def processself filename oslistdirpath subprocesscall scriptcmd filename selfoutput processed filename def outputself line selftextareaconfigstate normal selftextareatagconfiggreen backgroundgreen foregroundblack selftextareainsertend line green selftextareayviewend selftextareaconfigstate disabled selftextareaupdateidletasks root tk app app appbuildguiroot apppackguiroot rootmainloop process called pressing button i also tried subprocesspopen old osspawnv it always the gui reacting processing files only files processed gui updated processed xyz messages shouldn updateidletasks update gui every subprocess call thank edit i narrowed problem simple code tkinter import import subprocess filelist file file file file file def go labeltextset los filename filelist labeltextset processing filename labelupdateidletasks proc subprocesscallctestprocessexe filename labeltextset done root tk buttonroot textgo commandgopacksidetop labeltext stringvar labeltextset press button start label labelroot textvariablelabeltext labelpacksidetop rootmainloop now depends processexe script works properly if i write simple c program busylooping eg source code processexe int whileie gui updated every file when i call original exefile i wanted use displays processing file switches processing file freezes program termination done i dont really understand whats obviously something process called does anyone idea,1 you could use ospathjoinzippedfilesdir folder getfolderdirectories function import zipfile import os import sys zippedfilesdir zdevsomefiles def getfoldernames pathlist foldername oslistdirzippedfilesdir pathlistappendfoldername return pathlist def getfolderdirectoriesfolderlist folder folderlist pathname ospathabspathospathjoinzippedfilesdir folder printpathname def main getfolderdirectoriesgetfoldernames or pathlistappendospathjoinzippedfilesdir foldername getfoldernames import zipfile import os import sys zippedfilesdir zdevsomefiles def getfoldernames pathlist foldername oslistdirzippedfilesdir pathlistappendospathjoinzippedfilesdir foldername return pathlist def getfolderdirectoriesfolderlist folder folderlist pathname ospathabspathfolder printpathname def main getfolderdirectoriesgetfoldernames,i following code trying get full file path including folder import zipfile import os import sys zippedfilesdir zdevsomefiles def getfoldernames pathlist foldername oslistdirzippedfilesdir pathlistappendfoldername return pathlist def getfolderdirectoriesfolderlist folder folderlist pathname ospathabspathfolder printpathname def main getfolderdirectoriesgetfoldernames zdevnewfolderzip my problem i somefilesnewfolderzip returned directory any ideas thanks,1 you looking numpywhere print numpywherenumpyarange b b b b b b b b numpy even generalization maps etc values instead mapping true false numpychoose,does numpy ternary operator for instance r vectorized ifelse function ifelse ab b b b b b b b b is anything equivalent numpy,3 chown correct solution in code pass abspath string newfolderzip but abspath know came figure must current working directory get rzdevnewfolderzip you need use ospathjoin combine filename path find,i following code trying get full file path including folder import zipfile import os import sys zippedfilesdir zdevsomefiles def getfoldernames pathlist foldername oslistdirzippedfilesdir pathlistappendfoldername return pathlist def getfolderdirectoriesfolderlist folder folderlist pathname ospathabspathfolder printpathname def main getfolderdirectoriesgetfoldernames zdevnewfolderzip my problem i somefilesnewfolderzip returned directory any ideas thanks,1 python docs timedeltatotalseconds return total number seconds contained duration equivalent tdmicroseconds tdseconds tddays computed true division enabled note large time intervals greater years platforms method lose microsecond accuracy this functionality new version,apologies simple question i new python i searched around nothing seems working i bunch datetime objects i want calculate number seconds since fixed time past one example since january import datetime datetimedatetime this seems differentiating dates different days ttoordinal any help much appreciated,3 to get unix time seconds since january import datetime time datetimedatetime timemktimettimetuple,apologies simple question i new python i searched around nothing seems working i bunch datetime objects i want calculate number seconds since fixed time past one example since january import datetime datetimedatetime this seems differentiating dates different days ttoordinal any help much appreciated,3 this done setting layoutmanager null highly discouraged precisely annihilates goal layouts able goodlooking frames regardless look feel screen resolution etc you better learn use layout managers good way design gui,i trying convert python code java i need gui similar python i use widgetnameplacexy place objects anywhere i want window i want able specify object placed window i tried gridlayout gridbaglayout boxlayout flowlayout none allowing secify x coordinates place objectstext fields labels buttons ever i want i need able specify object goes screen using x coordinates anyone ideas,2 an answer question use enumerate instead incrementing counter for example showgraph method def showgraphself row selfmatrix print row simplified def showgraphself row enumerateselfmatrix print row,here code class incidencematrix def initself vertexnumber selfmatrix k range vertexnumber selfmatrix print selfmatrix def showgraphself row selfmatrix print row def isedgeself v v row selfmatrix v r row v r row print r r x rangelenr rx rx rx rx return true return false def addedgeself v v row selfmatrix v rowappend elif v rowappend else rowappend def removeedgeself v v row selfmatrix v r row v r row x rangelenr rx rx rx rx col x rx rx row selfmatrix v row r v row r row selfmatrix rowcol x rowremove x def removevertexself id pass name main grafim incidencematrix verticesnumber grafimaddedge grafimaddedge grafimaddedge grafimaddedge print grafimisedge grafimshowgraph print grafimremoveedge grafimshowgraph this incidence matrix i questions how remove vertex method how make code python style see question i use increment methods perhaps something else write edit i saw delete vertex i remove columns wher vertex but whole time waiting advice code quality,1 for special date january multiple options for starting date need get difference two dates seconds subtracting two dates gives timedelta object python totalseconds function tdatetimedatetimetotalseconds the starting date usually specified utc proper results datetime feed formula utc well if datetime utc already need convert use attach tzinfo class proper offset as noted comments tzinfo attached datetime need one starting date well subtraction fail example i would add tzinfopytzutc using python tzinfotimezoneutc using python,apologies simple question i new python i searched around nothing seems working i bunch datetime objects i want calculate number seconds since fixed time past one example since january import datetime datetimedatetime this seems differentiating dates different days ttoordinal any help much appreciated,3 while certified standard must use soap suds best choice suds slow large wsdls something working in meantime expect wsdl change often two options buy lot speed downloading wsdl localhost using caching downloading wsdl with large wsdls part problem first must download wsdl every time add overhead suds take time download parse entire wsdl startup make sure changed if download local system pass client constructor using file scheme url since suds uses urllib http transport perfectly legit now providing hostname wsdl url also pass location argument specifying actual url soap application here example sudsclient import client the service url soapurl httpmyappexamplenotrealpathtosoap the wsdl url wont use illustrating example this would file download system save wsdlfile wsdlurl httpmyappexamplenotrealpathtosoapwsdl the full path downloaded wsdl file local system wsdlfile pathtomyappwsdl wsdlurl file wsdlfile override original wsdlurl client clienturlwsdlurl locationsoapurl if interested i used approach work open sourced code caching wsdl the option use suds excellent caching feature you must explicitly create cache object pass constructor using cache argument otherwise defaults objectcache duration day you might also consider using approaches,i currently looking implementing client use existing extensive soap management api i looked different soap implementations like pysimplesoap suds while first problems parsing wsdl much recursions suds worked fine slow i really like module however seem several issues suds like high memory consumption wsdl parsing speed missing support wsdl attributes eg choice attribute while lot people actively committing bug reports patches release suds since also wiki roadmap look bit neglected for looks like suds longer maintained so questions does make sense base larger project suds soap client is suds fork already implements patches available ticketing system what alternatives available lower memory footprint easy use handle complex large wsdl files update november more two years passed turns original suds project really dead there releases since due fact lot people started forking suds distributions like debian deploying patched versions original suds package fix issues i recommend jurko actively maintained fork i used successfully it supports python addresses lot suds known problems release notes bug tracker available bitbucket package also available pypi installed using pip,3 i something similiar left main question revolves around i looked htmlparser bs i unsure something like ifposttext gold echo gold seems like bs deals lot tagsi suppose since facebook posts use variety tags would go search text return post,currently game different groups play prize gold every hour sometimes gold sometimes it posted facebook every hour gold group gold group times post due gold prize hour i want write small script check site hourly grab result gold group display back i wanting write python i learning would best language use and would i go all i really find information extracting links i want extract links text thanks help i appreciate,1 tcp streamoriented protocol packetoriented protocol when call transportwrite data gets appended tcp stream may sent number packets might broken glued together next previous call write this fairly frequently asked question twisted everyone asks asks slightly differently you want use protocol construction kit like amp basically linereceiver delimit messages within protocol rather relying upon random nature packet boundaries,i implementing clientserver solution based twisted server side eg android phone client side because andoird emulator takes tcp packets larger b less i need able chunk packets server side without flushing socket transportwrite twisted buffers outgoing data chunking would useless without somekind manual automatic flushing maxpacketsize function how i twisted i familiar reactordoselect function since i using epoll reactor scalability performance reasons i cannot use doselect is possible change maxpacketvalue certain connections within twisted hoping someone show light,1 the csvreader open file takes file object a better solution would import csv lines open outputtxt r f line freadlines linesappendline open correctedcsv w correct writer csvwritercorrect dialect excel open inputcsv r mycsv reader csvreadermycsv row reader row lines writerwriterowrow,i text file list strings i want search csv file rows begin strings put new csv file in instance text file called outputtxt original csv inputcsv new csv file correctedcsv the code import csv file open outputtxt line filereadline writer csvwriteropen correctedcsv wb dialect excel row csvreader inputcsv rowstartswithline writerwriterowrow writerclose line break pass the error traceback recent call last file cpythonsample programcsvparserpy line module writerwriterowrow typeerror str support buffer interface new error traceback recent call last file cpythonsample programcsvparserpy line module row reader csverror line contains null byte problem csv file saved tabs instead commas new issue following traceback recent call last file cpythonsample programcsvparserpy line module row lines indexerror list index range the csv file entries data make difference,1 if look documentation reader initialized spamreader csvreaderopen eggscsv r notice open eggscsv rb you passing file handle line str treated file handle throwing error replace line csvreaderopen inputcsv r newline,i text file list strings i want search csv file rows begin strings put new csv file in instance text file called outputtxt original csv inputcsv new csv file correctedcsv the code import csv file open outputtxt line filereadline writer csvwriteropen correctedcsv wb dialect excel row csvreader inputcsv rowstartswithline writerwriterowrow writerclose line break pass the error traceback recent call last file cpythonsample programcsvparserpy line module writerwriterowrow typeerror str support buffer interface new error traceback recent call last file cpythonsample programcsvparserpy line module row reader csverror line contains null byte problem csv file saved tabs instead commas new issue following traceback recent call last file cpythonsample programcsvparserpy line module row lines indexerror list index range the csv file entries data make difference,3 fwiw use cherrypy web server built webpy behind nginx serve html oystercom nginx splits traffic across web servers running python processes easily handle requests per second however use content delivery network cdn static resources like images css,i currently developing ios application needs backend pull data i implemented backend using python webpy pymongo i deployed everything ec instance assigned elastic ip instance ios devices call access backend launch application ssh nohup python mainpy amp everything works fine couple dozen users day potential grow data transferred rarely kilobytes i wondering proper way things for instance webpy website explain ways use webpy apache lightppd etc special cases i deploying backend using one full featured servers,1 i personally like loop keyvalue pair like def testkw k v kwitems k something v etc,what preferred way processing configuration parameters for example testthis could processed def testkw kwpop kwpop def testkw kw kw else kw kw else is better pythonic way,1 export archflags arch arch x run export command root trying pip easyinstall,after running sudo easyinstall lxml i get following error srclxmllxmletreec fatal error error writing broken pipe compilation terminated this looks like ccompiler problem gcc version yields i really know simply put i want install lxml osx,2 how badlinksplugin this plugin logs bad local links found wiki content it quite new one deals dangling links bad links i see source code this least one building block solution request visitcountermacro macro displays many times wiki page displayed this rather old one you get statistic per page administrative view missing could built rather easily ie like custom pageindex,hi guys is way improve trac wiki quality using plugin deals artifacts like obsolete pages pages refer code exist anymore pages unlinked pages low updaterate i think might several heuristics could used prevent wikirot number recent edits number recent views wether page links source file wether wiki page last update source files links wether entire directories wiki usededitedignored last n days etc etc etc if nothing else metrics alone would useful page directory administrative standpoint,1 the conversion sets great list elements converted sets otherwise need something like mark byers solution if large lists compare might want pay memory allocation overhead simplify line lremovem l l,i two lists l l i need items l l l l i want get new values l l l can i without iteration,1 you remove items list iterate either iterate copy list card selfthegamegamedeckdeck copies list or create new list items want keep reassign gamedeck selfthegamegamedeck gamedeckdeck card card gamedeckdeck castle cardsymbols,the strange thing i using python built iteration oo i class called card card among things name list symbols string here piece code prints debugging purposes this prints names cards deck iteration printstrcardname card selfthegamegamedeckdeck card selfthegamegamedeckdeck castle cardsymbols selfthegamegamedeckdeckremovecard printcardname removed else printcardname removed this prints names cards deck iteration printstrcardname card selfthegamegamedeckdeck and strangely enough output stdout writing tools the wheel sailing pottery oars mysticism me talworking masonry domestication code laws clothing city state archery agriculture writing removed the wheel removed sailing removed oars removed mysticism removed metalworking removed masonry removed domestication removed code laws removed city states removed archery removed agriculture removed tools the wheel pottery oars mysticism metalworking masonry domestication clothing city states archery as clearly see names first list specifically tools pottery clothing that nothing print second part output indeed left list three btw castle symbols removed can someone see i missing,3 if possible parameters defaults fixed pythonic way write def testthis if parameter list dynamic approach kwdspop nice advantage letting verify arguments used detecting misspelled parameter names example it instructive look fragment code generated collectionsnamedtuple point x verbosetrue notice final check make sure arguments consumed kwds def replaceself kwds return new point object replacing specified fields new values result selfmakemapkwdspop x self kwds raise valueerror got unexpected field names r kwdskeys return result,what preferred way processing configuration parameters for example testthis could processed def testkw kwpop kwpop def testkw kw kw else kw kw else is better pythonic way,2 try quoting command sent ssh subprocesspopen ssh rootip cd optmsyspebinperlscriptpl filecsv otherwise telling local shell,i trying execute following code working p subprocesspopenssh rootip cd optmsyspebinperlscriptpl filecsv shelltruestdoutsubprocesspipe stderrsubprocessstdout or p subprocesspopenssh rootip optmsyspebinperlscriptpl filecsv shelltruestdoutsubprocesspipe stderrsubprocessstdout the problem first seem chain together commands ssh the nd call file directly arg find file im directory i hoping use cwd parameter popen fails i ssh server,2 here nice trick i implemented exactly put debug settings class invalidstringstr def modself djangotemplatebase import templatesyntaxerror raise templatesyntaxerror undefined variable unknown value templatestringifinvalid invalidstrings this cause templatesyntaxerror raised parses sees unknown invalid value i tested little undefined variable names works great i tested function return values etc things could get complicated,inside django template one call object method like myobjectmymethod the problem get exceptionbug def mymethodself hidden rendering template empty string output instead errors appears as i want debug wrong def mymethodself i would like turn something like global django flag receive exception settingspy i already debug true templatedebug true i receive many kind template exceptions none i trig object method what i,3 source httpcodeactivestatecomrecipeswatchingadirectorytreeonunix the watchdirectories function takes list paths callable object repeatedly traverses directory trees rooted paths watching files get deleted modification time changed the callable object passed two lists containing files changed files removed future import nestedscopes import os time def watchdirectories paths func delay pathsstr funccallable delayfloat continuously monitors paths subdirectories changes if files directories modified callable func called list modified paths files directories func return boolean value rescanning returns true directory tree rescanned without calling func found changes this func write changes tree prevent immediately called basic principle allfiles dictionary mapping paths modification times we repeatedly crawl directory tree rooted path stat file comparing modification time allfiles def f unused dirname files traversal function directories filename files path ospathjoindirname filename try osstatpath except oserror if file deleted ospathwalk scanning directory get oserror just ignore report deletion next pass main loop continue mtime remainingfilesgetpath mtime none record file seen del remainingfilespath file mtime changed since last looked tstmtime mtime changedlistappendpath else no recorded modification time must brand new file changedlistappendpath record current mtime file allfilespath tstmtime main loop rescan false true changedlist remainingfiles allfilescopy allfiles path paths ospathwalkpath f none removedlist remainingfileskeys rescan rescan false elif changedlist removedlist rescan funcchangedlist removedlist timesleepdelay name main def f changedfiles removedfiles print changedfiles print removed removedfiles watchdirectories f this recipe useful like way send jobs daemon want use ipc mechanism sockets pipes instead daemon sit watch submission directory jobs submitted dropping file directory submission directory locking taken account the watchdirectories function really need locking misses modification one pass notice next pass however jobs written directly watched directory callable object might start running job file halfwritten to solve use lockfile callable must acquire lock runs submitters must acquire lock wish add new job a simpler approach rely rename system call atomic write job temporary directory watched file complete use osrename move submission directory,ex i need catch remove add files events directory linux os i found libs like inotify python wrappers i want use clear python code i watch oslistdirpath output every sec ways accomplish task,1 parsestr expecting headers well body try instead emailmimetext import mimetext msg mimetext htmlheadmeta httpequivcontenttype contenttexthtml charsetutfheadbodyttpre body prettbodyhtml html,the function giving trouble reason but i cant find bug the problem function parsestr i put argument literal string like hello world sends email string but surprise i put variable body also string email empty body i using python selfparser emailparserparser object thanks def sendmailself subject body print sending mailsubject smtplibsmtp sconnectmyserver myport sloginmyusermypasswd sstarttls sehloorheloifneeded msg selfparserparsestrbody print msgasstring msgfrom selfme msgto selfyou msgsubject subject msgorigdate emailutilsformatdate msgdate emailutilsformatdate logdebugsending email ssendmailselfme selfyou msgasstring here function calling sendmail it trivial def checkerrordirectoryself directory send email file errordirectory ifnot ospathexistsdirectory logwarningnotifyerrorfiles the directory existdirectory else filesize body directory sn directory problem false fn oslistdirdirectory fnc ospathjoindirectory fn filesize ospathgetsizefnc iffilesize body size sn fn filesize problem true ifproblem subject possible error directory selfsendmailsubject body,1 the error message says pyqt installer cannot find qmake executable running two commands solve pathpathqtsdksimulatorqtgccbin export path afterwards resume installation,i try install pyqt develop python apps using qt i downloaded sip pyqt httpwwwriverbankcomputingcouk compiled packages but i encountered problem compiling pyqt i ran python configurepy terminal i got error make sure working qt v qmake path use q argument explicitly specify working qt v qmake i looked qt settings saw path qmake defined homeuserqtsdksimulatorqtgccbinqmake where else path set and configure qt write code directly qt creator execute like c file example i installed qt nokia website installed homeuserqtsdk folder thanks,1 here requested removevertex method asked also code tightenedup bit enumerate zip class incidencematrix def initself vertexnumber selfmatrix k rangevertexnumber def showgraphself row enumerateselfmatrix print row def isedgeself v v return anyx x zipselfmatrixv selfmatrixv def addedgeself v v row enumerateselfmatrix rowappendintvi vi def removeedgeself v v numedges lenselfmatrix j rangenumedges selfmatrixvj selfmatrixvj row selfmatrix del rowj return raise exception edged found v v def removevertexself v targetrow selfmatrixpopv fetch delete target vertex col selector reversedlistenumeratetargetrow selector find columns edge target row row selfmatrix del rowcol remove column edge gone name main grafim incidencematrix verticesnumber grafimaddedge grafimaddedge grafimaddedge grafimaddedge print grafimisedge pair print grafimisedgepair grafimshowgraph print grafimremoveedge grafimshowgraph print grafimremovevertex grafimshowgraph note abandon onebased indexing favor python zerobased indexing simplify code bit removing enumerate removing indexed lookups also might want consider different representation using dict that suitable sparse structures simplifyspeedup code somewhat,here code class incidencematrix def initself vertexnumber selfmatrix k range vertexnumber selfmatrix print selfmatrix def showgraphself row selfmatrix print row def isedgeself v v row selfmatrix v r row v r row print r r x rangelenr rx rx rx rx return true return false def addedgeself v v row selfmatrix v rowappend elif v rowappend else rowappend def removeedgeself v v row selfmatrix v r row v r row x rangelenr rx rx rx rx col x rx rx row selfmatrix v row r v row r row selfmatrix rowcol x rowremove x def removevertexself id pass name main grafim incidencematrix verticesnumber grafimaddedge grafimaddedge grafimaddedge grafimaddedge print grafimisedge grafimshowgraph print grafimremoveedge grafimshowgraph this incidence matrix i questions how remove vertex method how make code python style see question i use increment methods perhaps something else write edit i saw delete vertex i remove columns wher vertex but whole time waiting advice code quality,1 subprocess best tool use case all process monitoring options wait terminate example apply local process ssh session happening remote script perl script example i use fabric handle running remote scripts it easier use attempting string together commands subprocess,i trying execute following code working p subprocesspopenssh rootip cd optmsyspebinperlscriptpl filecsv shelltruestdoutsubprocesspipe stderrsubprocessstdout or p subprocesspopenssh rootip optmsyspebinperlscriptpl filecsv shelltruestdoutsubprocesspipe stderrsubprocessstdout the problem first seem chain together commands ssh the nd call file directly arg find file im directory i hoping use cwd parameter popen fails i ssh server,1 it comes two lines shutilmove copytreesrc realdst symlinkstrue rmtreesrc src old realdst newold the copytree command copies old subdirectory newold that goes fine although may intended rmtree removes old directory that problem since new dangling symlink,a script i wrote meant move individual day directories old location new location structure like oldyyyymmdd newyyyymmdd another task unrelated moving data i created softlink new location like first mistake i made new old my script essential used function call oslistdirold shutilmoveospathjoinold ospathjoinnew after running script empty i occur work unarchived databig problem my question shutilmove give error day directory i moving already existed each day inside directory softlink new old doesn shutilmove call check src dst calling shutilcopy from docs the destination directory must already exist uses rename and makes difference old new locations glusterfs shutilmove documentation shutilcopy documentation thanks clarity provide editupdate i submitted question pythonlist asking behavior existed asked changed list archive they suggested i file bug report while tests submit bug i found fixed python you see differences source move function declaration python python this still moverename magically delete entire directory,1 getbyid change still key whether id name keyid,how define what used instead getbykeyname select key keyname,1 i end finding way using hook i able using extensionswrapcommand modifying options i included source resulting extension upon detecting lack case commit message version prompts user either enter one ignore warning abort commit if user responds prompt specifying case number appended existing commit message if user responds x commit aborted changes remain outstanding if user response hitting enter commit proceeds original caseless commit message i also added nofb option skips prompt user purposefully making commit case number here extension fogbugzreminder reminds user include fogbugz case reference commit message none specified mercurial import commands extensions import recase recompiler casesd reignorecase recasenum recompiler reignorecase def commitoriginalcommit ui repo opts haschange false changetype repostatus lenchangetype haschange true haschange uiconfig ui commitsubrepos defaulttrue ctx repo subpath sortedctxsubstate subrepo ctxsubsubpath subrepodirty haschange true haschange optsnofb recasesearchoptsmessage casenumresponse uiprompt please specify case number x abort hit enter ignore casenum recasenumsearchcasenumresponse casenum optsmessage case casenumgroup print continuing updated commit message optsmessage elif casenumresponse x uiwarn user abortedn return false return originalcommitui repo opts def uisetupui entry extensionswrapcommandcommandstable commit commit entryappend nofb none suppress fogbugzreminder warning case number present commit message to use extension copy source file named fogbugzreminderpy then mercurialini file hgrc whatever preference add following line extensions section fogbugzreminderpath fogbugzreminderpy file,i trying modify mercurial extension prompt user add fogbugz case number commit message ideally i like user type number prompted automatically appended commit message here i got far def pretxncommitui repo kwargs tip repochangectxrepochangelogtip recasesearchtipdescription lentipparents casenumresponse uiprompt please specify case number x abort hit enter ignore casenum recasenumsearchcasenumresponse casenum work tipdescriptiontipdescription case casenumgroup return true elif casenumresponse x uiwarn user abortedn return true return true return false what i able find way edit commit message tipdescription appears readonly i seen anything documentation examples would let modify the references i seen editing commit messages patches mq extension seem like help any ideas i could set commit message,3 mcrypto supplies fedorasetupsh script handle problems fedorarlcentos releases pip course know anything after pip install fails leaves downloaded stuff venvbuildmcrypto directory cd pathtoyourvenvvenvbuildmcrypto chmod ux fedorasetupsh fedorasetupsh build fedorasetupsh install this worked install process,i trying install python mcrypto package virtualenv x rhel machine this process invokes swig fails following error virtualenv q nositepackages venv pip install e venv mcrypto downloadingunpacking mcrypto downloading mcryptotargz kb kb downloaded running setuppy egginfo package mcrypto installing collected packages mcrypto running setuppy install mcrypto building mcryptomcrypto extension swigging swigmcryptoi swigmcryptowrapc swig python iusrincludepython iusrinclude includeall swigmcryptowrapc swigmcryptoi usrincludeopensslopensslconfh error cpp error this openssldevel package work architecture use cpperraswarn option continue swig processing error command swig failed exit status complete output command homelorinvenvbinpython c import setuptoolsfile homelorinvenvbuildmcryptosetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record tmppipbfinturecordinstallrecordtxt installheaders homelorinvenvincludesitepython i got openssl installed via rpm packages redhat the part usrincludeopensslopensslconfh causes error looks like definedi include opensslconfih elif definedia include opensslconfiah elif definedpowerpc include opensslconfppch elif definedpowerpc include opensslconfppch elif definedsx include opensslconfsxh elif defineds include opensslconfsh elif definedsparc ampamp definedarch include opensslconfsparch elif definedsparc include opensslconfsparch elif definedx include opensslconfxh else error this openssldevel package work architecture endif gcc right variable defined echo gcc e dm grep x define x define x but apparenty swig since line failing swig python iusrincludepython iusrinclude includeall swigmcryptowrapc swigmcryptoi is way fix changing something system configuration mcrypto gets installed virtualenv part larger script i control avoiding mucking around mcrypto files would good thing,3 it possible helper function better fits module level rather class if agree case staticmethod decorator use functions inside class simply put static method behaves object instantiations class it rely instance data for reason staticmethod decorator renders behavior function take implicit first argument typically self stated documentation,in python methods class need helper function helper function use anything class i put helper function inside outside class i tried putting inside pylint complaining function could put outside also good books talking kind stuff python thanks help jack karl the class software upgrader helper function creates new folder folder exist yet the class module pretty much code class other classes may added later thanks jack,3 make q homeuserqtsdksimulatorqtgccbinqmake does work i sure error came ran make i assume if add q homeuserqtsdksimulatorqtgccbinqmake proper command,i try install pyqt develop python apps using qt i downloaded sip pyqt httpwwwriverbankcomputingcouk compiled packages but i encountered problem compiling pyqt i ran python configurepy terminal i got error make sure working qt v qmake path use q argument explicitly specify working qt v qmake i looked qt settings saw path qmake defined homeuserqtsdksimulatorqtgccbinqmake where else path set and configure qt write code directly qt creator execute like c file example i installed qt nokia website installed homeuserqtsdk folder thanks,1 these kind performance questions easily answered using timeit module setup k b lbyl k pass else pass eapf try dk except keyerror pass timeit import timer print mintimerlbyl setuprepeat print mintimereapf setuprepeat the results show ifelse approach tryexcept approach the latter times slower former that said generally use whatever expresses clearest code sidenote two approaches give different answers subclasses dict define missing return value,i got project i frequently something dict somevar dictsomething del dictsomething else errorhandlerorotherstuff however i idea use try somevar dictpopsomething except keyerror errorhandlerorotherstuff my question general fast try except constructs handle exceptions is ok use lot still faster stuff manually also sometimes i situation i convert value integer try somevar intdictpopsomething except keyerror errorhandlerorotherstuffno key except valueerror errorhandlerorotherstuffbad value key now solution exceptions seems quite nice since i checks one step also i removed original keyvalue pair dict part problem so i tell least looks like elegant solution however i sure faster disadvantages i worry,2 there swing tutorial gives concise example positioning widgets absolutely,i trying convert python code java i need gui similar python i use widgetnameplacexy place objects anywhere i want window i want able specify object placed window i tried gridlayout gridbaglayout boxlayout flowlayout none allowing secify x coordinates place objectstext fields labels buttons ever i want i need able specify object goes screen using x coordinates anyone ideas,1 solved problem comtypes generated large module file taking much time parse pyexe comtypesgenfcbcfbbaabdceb the workaround patch pyexe source code ver pointed erez bibi post httpgroupsgooglecomgroupwxpythonusersbrowsethreadthreaddebabccdce setup file options pyexe packages wxlibpubsub includes comtypesgenfcbcfbbaabdceb skipscan comtypesgenfcbcfbbaabdceb everything seems working great,i python program wxpython comtypes dependencies win xp sp machine i using pyexe produce windows distributables following setup setup options pyexe packages wxlibpubsub windows script entrypy datafilesbitmaps resourcesiconsappbigpng resourcesiconsappmediumpng resourcesiconsappsmallpng resourcesiconsappsmallnewpng resourcesiconsappsmallbadpng resourcesiconscrosshoverpng resourcesiconscrosspng resourcesiconsdeletepng resourcesiconsrefreshpng i also using iehtmlwindow control what happening whenever i issue command python console pyexe runs second following output running pyexe searching required modules appears hang indefinitely i press ctrz i tracked problem import wxlibiewin import iehtmlwindow seems causing problem any suggestions,1 no worries the warning something standard library already fixed python you safely ignore the setspy part standard library line warning sets module deprecated favor set builtin method disappear python,i ran python code got error message cpythonlibsetspy deprecationwarning functions overriding warningsshowwarning must support line argument stacklevel i sure warning i ignore serious any input appreciated thanks,1 define helper function pass object method arguments function via poolmap the helper function would look something like def helperargs return argsargs and would use like pool pool results poolmaphelper objmethod arg arg note helper function must directly importable containing module,i list objects i want call foo function passing argument bar i want parallelize operation right i looking using poolmap multiprocessing package i sure use map run object method though how i or better way parallel,1 when deciding put helper functions question i ask is class if help places goes module level indeed class goes class either staticmethod needs class data job classmethod uses class instance data job another python code checker pyflakes,in python methods class need helper function helper function use anything class i put helper function inside outside class i tried putting inside pylint complaining function could put outside also good books talking kind stuff python thanks help jack karl the class software upgrader helper function creates new folder folder exist yet the class module pretty much code class other classes may added later thanks jack,3 this happen check code bad imports like numpy import,when i call randomsamplearrlength error returns randomsample takes positional argument given after googling i found i calling numpy random sample function i want call sample function random module i tried importing numpy different name fix problem i need numpy rest program though any thoughts thanks,3 def toseofriendlys maxlen join dashes eliminate punction clip maxlen lowercase toseofriendlythe quick brown fox jumped thequickbrow joinssplit join words dashes u joinc c cisalnum c remove punctation return umaxlenrstrip lower clip maxlen name main import doctest print doctesttestmod,basically question python gae c requirements separate word dash remove punctuation taking account words separated spaces function takes max length gets tokens max length example toseofriendlyhello world hello world returns helloworld all words converted lower case,3 be sure keep imports distinct import numpyrandom import random python random,when i call randomsamplearrlength error returns randomsample takes positional argument given after googling i found i calling numpy random sample function i want call sample function random module i tried importing numpy different name fix problem i need numpy rest program though any thoughts thanks,3 you everything want reading file first performing changes lines finally writing back if file fit memory read file batches create temporal file you modify file situ,i want open file add underline character beginning line find blank lines replace newline character blank lines underline characters add new lines underline characters i found many similar questions stackoverflow i could combine operations without getting errors see previous question is simple beginners way accomplish i start i mind writing file need open two files thanks,1 sounds like something like import random numpy import random getting clobbered numpy import if want keep import need rename random import random rnd whatever name like numpy import alternatively probably better import numpy module instead yanking module namespace import random import numpy np leave numpy whatever name like,when i call randomsamplearrlength error returns randomsample takes positional argument given after googling i found i calling numpy random sample function i want call sample function random module i tried importing numpy different name fix problem i need numpy rest program though any thoughts thanks,3 maybe forgot make file executable try command prompt chmod x scriptpy i prefer start python scripts mac lines assuming course saving file utf encoding usrbinenv python codingutf also make sure python command available path if everything set correctly necessary type python first run script directly typing scriptpy directory located one final thing running piece code executing script command line opposed simply loading definitions file write end name main code want call,i downloaded python mac os environment i new programming trying run first standalone py file i keep getting error message saying directory file the name file scriptpy i saved usersbillpdocuments when i open terminal run file i type python scriptpy i also tried adding line beginning script usrlocalbinpython as well one usrbinenv python yet i keep getting error message any help would greatly appreciated,2 you going pick use two files never store line memory time build new file memory read original overwrite original new a file flexible memory structure you replace characters newline underscores work like if sure new file going manageable size mind writing original without new file myself i would always allow user opt output file what something goes wrong disk space super cheap,i want open file add underline character beginning line find blank lines replace newline character blank lines underline characters add new lines underline characters i found many similar questions stackoverflow i could combine operations without getting errors see previous question is simple beginners way accomplish i start i mind writing file need open two files thanks,2 in python withvalgrind compiletime flag allows python interpreter detect runs valgrind disables pymalloc this allow accurately monitor memory allocations otherwise pymalloc allocates memory big chunks,i python extensions implemented c classes i c target run valgrind i want use valgrind memory check can i use valgrind python,3 make sure right working directory opening terminal type cd usersbillpdocuments use tab autocomplete python scriptpy this way launching python executable passing path file first argument the shebang line mentioned allows launch script directly like scriptpy need mark file executable chmod x scriptpy provide path interpreter python shebang usrbinenv python references default python installation the stands current directory by default type scriptpy shell thing type commands terminal would look executable file special folders listed path env variable scriptpy usually would see bash scriptpy command found python hand path work,i downloaded python mac os environment i new programming trying run first standalone py file i keep getting error message saying directory file the name file scriptpy i saved usersbillpdocuments when i open terminal run file i type python scriptpy i also tried adding line beginning script usrlocalbinpython as well one usrbinenv python yet i keep getting error message any help would greatly appreciated,3 opencv python interface could look if characters change much could try use matchtemplate function here official tutorial tutorial written using c interface able get good idea use function python,i currently building basically amounts cross search engine gallery web comics focused citing sources giving authors credit i trying figure way search image find characters within for example assuming i red character green character saved red man green man i determine image contains one this need recognition anything added feature i like create i sure start i done lot googling image recognition found much helpful for worth i prefer using python,1 i found tutorial pyqt explaining add slots qtvery informative,i pyqt v installedwhen i draw layouts i want view code comes error unable launch uic snapshot i compile ui files manually cmdline but i dont know put code slotmethods signals where i set settings finding uic compile ui my installation pyuic where i define slotsmethods functoins signatures receiver objectsender i see edit signalsslots edit menu shows standard signalsslotsdoesn options define,2 i ran issue decided use subcommands subcommands might overkill find program using positional arguments many instances i subcommands might good solution for given example i use something like following parser argparseargumentparserdescriptionfoo bar baz subparsers parseraddsubparsersdescription available subcommands parsermain subparsersaddparser maincommandname parsermainaddargument arg help arg positional argument parsermainaddargument arg help arg positional argument parserlist subparsersaddparser list help subcommand prints stuff options args parserparseargs i left details might want include like setdefaultsfunclist mentioned argparse documentation,i trying make argparse ignore fact two normally required positional arguments evaluated optional argument l specified basically i trying replicate behavior help specify h missing required arguments ignored example code parser argparseargumentparserdescriptionfoo bar baz parseraddargument arg help arg positional argument parseraddargument arg help arg positional argument parseraddargument l list dest list help optional argument prints stuff options args parserparseargs optionslist print i list stuff and course i run i get error arguments i tried different things like nargs get anything working this question quite similar answered any help appreciated thanks,3 you might want look binascii module specifically hexlify unhexlify functions,i want store hashes binary bytes but type api web service i would want pass around strings hashlibhexdigest give string hashlibdigest give binary but example i read binary version disk would i convert string and i read string web service would i convert binary,2 in x use strdecode hex strencode hex convert raw bytes hex string in x need use binascii module,i want store hashes binary bytes but type api web service i would want pass around strings hashlibhexdigest give string hashlibdigest give binary but example i read binary version disk would i convert string and i read string web service would i convert binary,2 you could start string version pass around display import hashlib stringversion hashlibmdb hello world hexdigest convert binary write disk saveasbinary stringversionencode utf printsaveasbinary b ebbbbeeeedcbbbfacdc when reading back disk convert back string backtostring saveasbinarydecode utf printbacktostring ebbbbeeeedcbbbfacdc,i want store hashes binary bytes but type api web service i would want pass around strings hashlibhexdigest give string hashlibdigest give binary but example i read binary version disk would i convert string and i read string web service would i convert binary,2 start turning text list lists that take care parsing part lol listcsvreaderopen texttxt rb delimiter the rest done indexed lookups dict key lol cell a value lol cell d dkey value add entry dictionary,i currently csv file opened excel total columns only columns a c significance data remaining columns irrelevant starting line working multiples ie lines etc i looking create dictionary python information fields the data column a key digit integer data column c respective value key i tried highlight formatting best a b c d cdcdcdcd vddbddb ddefeef fefefefe jones smith as per i looking extract value a ddefeef key dictionary fefefefe respective data add another entry dictionary jumping line key smith respective value any suggestions the source file txt file entries tabdelimited thanks clarification just clarify far i tried import csv mydict f openmyfile rt reader csvreaderf row reader print row the simply prints content though row time i try row reader returned error i researched go work neither import csv itertools import islice entries csvreaderopenmyfile rb mydict key value xrange mydict i integers representing columns range isliceentries entry range mydictentries entries integers representing columns,3 if file large may want load entirely memory this approach avoids of course making dict could still take ram guaranteed smaller original file mydict line enumeratefile continue k v linesplitt mydictk v edit not sure i got extend i meant update,i currently csv file opened excel total columns only columns a c significance data remaining columns irrelevant starting line working multiples ie lines etc i looking create dictionary python information fields the data column a key digit integer data column c respective value key i tried highlight formatting best a b c d cdcdcdcd vddbddb ddefeef fefefefe jones smith as per i looking extract value a ddefeef key dictionary fefefefe respective data add another entry dictionary jumping line key smith respective value any suggestions the source file txt file entries tabdelimited thanks clarification just clarify far i tried import csv mydict f openmyfile rt reader csvreaderf row reader print row the simply prints content though row time i try row reader returned error i researched go work neither import csv itertools import islice entries csvreaderopenmyfile rb mydict key value xrange mydict i integers representing columns range isliceentries entry range mydictentries entries integers representing columns,1 i think need cut line loop lines infilereadline that reading first line nothing go file linebyline,i text file contains x ycoordinates center circle followed radius fill color circle the text file reference goldenrod coral tomato maroon burlywood sienna chartreuse olivedrab peachpuff thistle mediumpurple cornsilk linen honeydew dodgerblue the entire program i figured works fine except one part i use loop take information file split necessary draw circles graphwin the problem data circles text file loop reading circles completely skipping first line the code def mycircles path c extension txt center radius color lines fname inputplease enter name file data stored the path c extension txt needed testdatacircles infile openpath fname extension r win graphwinwsutc cptsq winsetcoords lines infilereadline lines infilereadlines center radius color linessplit centerx centery centersplit centerx centery evalcenterx evalcentery ccenter pointcenterx centery mycircle circleccenter evalradius mycirclesetfillcolor mycircledrawwin infileclose printplease click anywhere inside graphics window close wingetmouse winclose how i get not skip first line text file i searched problem internet generally i getting people asking skip lines opposite i need,3 if interested i done tutorial series part i part ii talking tfidf using scikitslearn sklearn python module,i need compare documents stored db come similarity score the method i need use simple implementing vanilla version ngrams possible define many grams use along simple implementation tfidf cosine similarity is program or i start writing scratch,3 the gil ordinary mutex the cost locking unlocking uncontested mutex extremely low much cost changing global variable however lock unlock contested mutex often cost mutex become significant so usually good idea pybeginallowthreads pyendallowthreads what happening unlocking mutex try lock immediately afterwards if break two large chunks code gives another thread chance run but problems threading granularity keep lock so good idea context verylongcomputationrequiresgil pybeginallowthreads pyendallowthreads verylongcomputationalsorequiresgil it really impossible make educated guess without knowing context often still difficult without running tests,let suppose i c extension function something completely independent python interpreter is reason release gil for example reason write code like apart issues like readability avoiding microoptimization things important really relevant question pybeginallowthreads pyendallowthreads clearly trivial code performance probably matter much but performance reason release gil or gil released cpuintensive code,3 there several problems code posted firstly importing pyside pyqt good idea secondly qwebviewlinkclicked signal protected method override thirdly passing string qwebviewload passing qtcorequrl however aside problems also need set linkdelegationpolicy web page order override link handling here edited version code fix problems pyside import qtcore qtgui qtwebkit class browserwindowqtwebkitqwebview def initself parentnone superbrowserwindow selfinit selflinkclickedconnectselfhandlelinkclicked def handlelinkclickedself url printurltostring name main import sys app qtguiqapplicationsysargv view browserwindow viewloadqtcorequrlhttpgooglecom viewpagesetlinkdelegationpolicy qtwebkitqwebpagedelegatealllinks viewshow sysexitappexec,this pythonpyside i trying create parental webbrowser overloading pysideqtwebkitqwebview widget then whenever someone clicks link widget i check see going invalid website proceed yes i redirect generic page so i subclassed pysideqtwebkitqwebview i receiving notification link clicked i overridden linkclicked function function never runs link clicked what i wrong why cant function runreact hyperlink click event do i need override webpage object amp class react link clicks import pysideqtwebkit import sys pyqt import qtgui class browserwindow pysideqtwebkitqwebview class variables def init self parent constructor superbrowserwindow selfinit pysideqtwebkitqwebviewnone def linkclickedself arg post printlink clicked text ok qtguiqinputdialoggettextself input dialog enter name selfloadhttpyahoocom def main app qtguiqapplicationsysargv view browserwindownone pysideqtwebkitqwebviewnone viewloadhttpgooglecom viewshow sysexitappexec name main main,2 duplicate handling gui different threads how keep track thread progress python without freezing pyqt gui etc your dostuff function needs start computing thread return multithreading name given running multiple activities single process definition something going background running separate thread but need split functions different classes use threads sure computing functions anything gui main thread call functions used computing thread edit here silly example running threads single class nothing language threading library requires different class thread the examples probably use separate class processing illustrate good modular programming tkinter import import threading class myapp def initself root selfroot root selftimerevt threadingevent cf frameroot borderwidth reliefraised cfpack buttoncf textrun commandselfrunpackfillx buttoncf textpause commandselfpausepackfillx buttoncf textkill commandselfkillpackfillx def processstuffself processing threads selfgo printspam selftimerevtwait selftimerevtclear def runself start another thread selfgo threadingthreadtargetselfprocessstuff nameprocstart selfrootafter selftick def pauseself selfgo def killself wake threads die selfgo selftimerevtset def tickself selfgo selftimerevtset unblock processing threads selfrootafter selftick def main root tk roottitleprocessingthread app myapproot rootmainloop main,i relatively large application written python using pyqt gui frontend the entire application one class one file here example code class applicationqmainwindow def initself superetc selfconnectselfmainbtn signalclicked selfdostuff def dostuffself checking parameters else dosomeotherlongstuff def dosomeotherlongstuffself lines code stuff however problem i click mainbtn everything goes fine except gui kind freezes i anything else function performed web scraper takes quite bit time when function dosomeotherlongstuff ends everything goes back normal this really irritating is way somehow background dosomeotherstuff process i looked qthreads seems however would require rewrite basically code put half program different class therefore change variable names getting variable gui class putting working class,1 correct django apps running side side it possible the best applications running different virtual environments virtual environments python version modwsgi compiled,app a written python django runs apache server via modwsgi app b written python i want run sidebyside server i want update app a use change app b use the question can i run two django apps two separate python runtimes sidebyside one apache server if i i set this confuses hell wsgi documentation offers python “home” setting document says modwsgi compiled specific version python note version python baseline environment created must version python modwsgi compiled it possible mix environments based different majorminor versions python does mean i django apps running side side,2 that operatingsystem level protection if module get around problems windows sucks i think lot write different directory,i making file injection program via ftp user runs program ftp downloads another program distant folder runs program when i try make zip file system fold python yells says you cant do that is module i use get around thanks code lzipfile opencprogram fileszipfilename w,1 the string first case exactly saw printed salt mdsalthexdigest cedfbaddb notice i escaped backslashes keep digits interpreted octal byte values the string first case exactly saw printed salt mdsalthexdigest cedfbaddb notice i escaped backslashes keep digits interpreted octal byte values edit assuming want create byte string octal values list data you convert integer join characters different got ipython the first value digits instead should treated followed ascii treated the following latter salt joinchrintd data print reprsalt print mdsalthexdigest output xxxbfxecgxfh xtxxcd ddbdbeccbedcc,i trying extract string file using python mding string using something like mderpy salt extractsaltfilefoo print salt salt md import md print hash mdsalthexdigest python mder salt hash cedfbaddb but using ipython like in salt in salt out xxxbfxecgxfh xtxxcd in print salt ���g�ht�� in md import md in mdsalthexdigest out ebaeaffffb any clues md different scenarios ipython i typed variable name appeared different format original string print output third format hint in import sys in sysgetdefaultencoding out ascii,2 first foremost look csv docs once understand basics take look code this get started right path import csv original file southparkcsv ru reader csvreaderoriginal row reader print row columns names wear print row print print first column character names print row you want import csv module work csv filetype open file universal newline mode read csvreader then use loop begin iterating rows depending want the first print row print single line single character data ie everything name clothing type like stan marsh dob october th dude aww star quarterback wendy red gloves kyle broflovski dob may th kick baby you jewish canadian ushanka eric theodore cartman dob july respect my authroitah mooom bigboned political ly incorrect knitcap kenny mccormick dob march dod every week mmff mmff mmmfff mysterion orange parka leopold butters stotch dobyounger others the th friend professor chaos stu tter innocent nerdy finally second statement print row provide character names you change number able grab data necessary remember csv file everything starts case go a b c etc to see outputs clearly probably best comment one print statements get clearer picture grabbing stan marsh kyle broflovski eric theodore cartman kenny mccormick leopold butters stotch note i threw print would able see different outputs hope helps get start edit to answer second question the easiest way although probably best way grab single character info would something like import csv original file southparkcsv ru reader csvreaderoriginal stan readernext kyle readernext eric readernext kenny readernext butters readernext print eric outputs eric theodore cartman dob july respect my authroitah mooom bigboned politically incorrect knitcap take note csv modified order characters moved ex butters moved top output info another character,basically problem i csv excel file info southpark characters i i html template i take data rows stored lists character using html template given implement data create seperate html pages characters last names here image csv file iimgurcomrcipwpng this i far askfile rawinputwhat filename southpark filename openaskfile ru row filename print row filenameclose the prints info idle shell five rows i find way separate row and column store list i know it pretty rudimentary code i know i trying figure way store rows columns first i use function def first assign data html template create html file datatemplateand i far noob i tried searching net i understand stuff i allowed use downloadable modules i use things built python like import csv whatnot really supposed written couple functions list strings loops once i figure separate rows columns store i work implementing html template creating file i trying hw done i pretty much suck programming help appreciated btw i using python want dl csv file click update okay thanks lot that helped understand row printing info read program now since i use functions program somehow i thinking each row prints separate values print row function prints one character corresponding values i need what i want print data like print row would i store characters separate list basically print row prints characters corresponding attributes i split variables store list when i print row prints names print row prints dob i thinking creating def function takes print row splits variables loop another def function takes variableslists data combines html template end i figure create html files python sorry i sound confusing trying make sense this code right gives error many values unpack i trying fiddle around try different things see work based i wanted i probably delete code find way rewrite list type functions like append strip etc i familiar import csv original file southparkcsv ru reader csvreaderoriginal list data name dob descript phrase personality character apparel count def southparkinfo row reader count count row name print row name ex stan marsh print elif count row dob print row dob print elif count row descript print row descriptive saying ex respect my authoritah print elif count row phrase print row catch phrase ex mooom print elif count row personality print row personality ex jewish print elif count row character print row characteristic ex politically incorrect print elif count row apparel print row apparel ex red gloves return readerclose,3 i believe depends lock set transaction httpwwwsqliteorglockingvhtmlsharedlock httpwwwsqliteorglangtransactionhtml sqlite exclusive transactions lock read write immediate deferred transactions still allow readers so really depends transactions used chromium,i like open chromium site data configchromiumdefault pythonsqlite gets locked whenever chromium running understandable since transactions may made is way open readonly mode ensuring i corrupt integrity db chromium using,3 chromium holding database lock long periods time yuck that really good idea still fault… you could try copying database file eg system utility cp using snapshot reading purposes sqlite keeps committed state single file per database yes chance seeing partial transaction definitely lock problems unix sqlite definitely use mandatory locks this might well work windows due different locking scheme,i like open chromium site data configchromiumdefault pythonsqlite gets locked whenever chromium running understandable since transactions may made is way open readonly mode ensuring i corrupt integrity db chromium using,1 consider idiom instead def run print run def walk print walk def talk print talk switch run run walk walk talk talk switch run run i think little readable direction heading edit and works well switchrunwalk switch run switchmax walk you even use idiom switch default type structure defaultvalue try switch except keyerror switchdefaultvalue or less readable terse switchswitchgetdefaultvalue walk edit same idiom extended comment def gett return def gett return switchgettgettrun switch function run xd readability matters,i situation i six possible situations relate four different results instead using extended ifelse statement i wondering would pythonic use dictionary call functions i would call inside ifelse replacement switch statement like one might use c php my switch statement depends two values i using build tuple i turn use key dictionary function switch i getting values tuple two functions database calls i example one zero functions this code pattern i thinking using i stumbled playing around python shell def one simulated database value return def zero return def run shows correct function ran print run return def walk print walk return def main switchdictionary these values i want use decide functions use switchdictionary run switchdictionary walk these tuples i build database zerotuple zero zero onetuple one one these actually run functions in practice i simply one tuple dependent database information run function i defined switchdictionaryzerotuple switchdictionaryonetuple i actual code written i would post i would like know method considered python best practice i still python learner university method bad habit i would like kick i get real world note result executing code expected simply run walk edit for interested relevant code turned it used google app engine application you find code considerably tidier rough example pattern it works much better prior convoluted ifelse tree def getassignedagentself tpaypal paypalorder parent class function tagents switch these different methods actions take switch tpaypalassignnoagent switch tpaypalusebackupagents switch tpaypalusebackupagents switch tpaypalusefullagents switch tpaypalusefullandbackupagents switch tpaypalusefullandbackupagents switch tpaypalusefullagents switch tpaypalusefullagents switch tpaypalusefullagents i interested number i consider switch dictionary options available the state current status customer agent system tcurrentstate tpaypalgetnumberofavailableagents tpaypalgetnumberofbackupagents tagents switchtcurrentstate,3 it reasonably common python practice dispatch functions based dictionary sequence lookup given use indices lookup list lists would also work switchlist run none none walk switchlistzerotuple what considered pythonic maximizes clarity meeting operational requirements in example lookup tuple appear intrinsic meaning operational intent lost magic constant try make sure business logic get lost dispatch mechanism using meaningful names constants would likely help,i situation i six possible situations relate four different results instead using extended ifelse statement i wondering would pythonic use dictionary call functions i would call inside ifelse replacement switch statement like one might use c php my switch statement depends two values i using build tuple i turn use key dictionary function switch i getting values tuple two functions database calls i example one zero functions this code pattern i thinking using i stumbled playing around python shell def one simulated database value return def zero return def run shows correct function ran print run return def walk print walk return def main switchdictionary these values i want use decide functions use switchdictionary run switchdictionary walk these tuples i build database zerotuple zero zero onetuple one one these actually run functions in practice i simply one tuple dependent database information run function i defined switchdictionaryzerotuple switchdictionaryonetuple i actual code written i would post i would like know method considered python best practice i still python learner university method bad habit i would like kick i get real world note result executing code expected simply run walk edit for interested relevant code turned it used google app engine application you find code considerably tidier rough example pattern it works much better prior convoluted ifelse tree def getassignedagentself tpaypal paypalorder parent class function tagents switch these different methods actions take switch tpaypalassignnoagent switch tpaypalusebackupagents switch tpaypalusebackupagents switch tpaypalusefullagents switch tpaypalusefullandbackupagents switch tpaypalusefullandbackupagents switch tpaypalusefullagents switch tpaypalusefullagents switch tpaypalusefullagents i interested number i consider switch dictionary options available the state current status customer agent system tcurrentstate tpaypalgetnumberofavailableagents tpaypalgetnumberofbackupagents tagents switchtcurrentstate,1 buy nexuss buy tags then take look code tags application comes android play modify write tags application learn ndef craft messagesrecords learn use transceive function direct communication tags this open world aka writeprotect tags write protectable android etc all done two weeks the android nfcrfid subsystem easy use most hard stuff hidden afterwards write little application show advertising agencies android apps get high payed job nfc experience highly sought moment,i heard google nexus s rfid capabilities i like start learning rfid programmatically things where i start good tutorials code examples i hardware android i suppose doesn android could python java libraries well preference android i see future i want get,1 have considered building restful api backend maybe djangopiston could help sure runs gae box there also python library google channel api client side apparently somebody reverseengineered protocol httpsbitbucketorglohregaechanneloverview,the server well client side program written python can someone tell use python client side communicate google app server written python google app engine already provides channel api server side requires javascript client side will embedding javascript python help any alternatives using python google app engine v,2 simon sapin answered quite active flask mailing list why wsgi you get python interpreter somewhere then need call application somehow data webkit like url requested get response wsgi calling convention python functions callable objects if wsgi complex you’d like use test client httpflaskpocooorgdocsapiflaskflasktestclient httpwerkzeugpocooorgdocstestwerkzeugtestclient httpwerkzeugpocooorgdocstestwerkzeugtestenvironbuilder that’s i frozenflask it simulates http requests flask app wsgi level write responses static files the test client easier way make wsgi calls httpsgithubcomsimonsapinfrozenflaskblobmasterflaskextfrozeninitpyl wsgi really flask’s entry point other you’re interested flask inner workings start looking httpsgithubcommitsuhikoflaskblobmasterflaskapppyl,i want build hybrid application web technologies embedded desktop app i start web version embed using webkit i want embedded version service requests tcp port with webkit qtgtk i intercept url requests act what i missing way invoke flask urltocallable dispatcher without going tcp wsgi any ideas better analyzing call stack debugger,1 you confusing attribute lookup getattr you resolve strings attributes typing datasinglearg would python know whether use variable value attribute name singlearg data datasinglearg not set attribute string way you setting attribute called singlearg model field going saved to set attribute via string need use setattr singlearg data data dataobjectsgetid setattrdata singlearg datasave your last example expected dataentry singlearg attribute you need calling getattrdataentry singlearg want string attribute referenced variable singlearg,i model form class datamodelsmodel someid modelsintegerfieldprimarykeytrue data modelsintegerfield data modelsintegerfield data modelscharfieldmaxlength i reading data various files using header information identify columns said files saved each column name database unique i use point appropriate table well there cases given row database already contain columns data i need add data columns i running python code within django shell however i specify pk someid existing element save data one column data columns row overwritten none for example code reads dataargs dataargs someid dataargs data dataentry datadataargs dataentrysave data data entry already populated save would read none because i running script column names read strings header i able figure update data form examples documentation like dataentry dataobjectsgetsomeid dataentrydata dataentrysave while works command line python code data read string file header edit apologies lack clarity i trying spare gory detail when i say correct code work script i access name column data file header looks like someiddatadatadata i parse data file using numpygenfromtxt provides access names data columns form dataarraydtypenames someid data data data so assuming first entry data already exists i try save column data singlearg dataarraydtypenames dataentry dataobjectsgetsomeid dataentrysinglearg dataentrysave value end saved data column first entry the value i get still none in loop i performing operation save i print singlearg would show data example variable containing value i trying assign dataentrysinglearg example dataentrysinglearg read example look correct for reason however value get saved database if code correct perhaps problem lie elsewhere further edit as i thought problem seems singlearg registering data used dataentrysinglearg after save i requery database try print saved dataentry dataobjectsgetsomeid singlearg dataarraydtypenames print dataentrysinglearg i get error attributeerror data object attribute singlearg so might script entire string dataentrysinglearg value object dataentrydata actually accessed maybe so question i save data one column preserving existing data columns row,1 operator calls getitem class a def getitemself index return index a printa prints you implement returning proxy object represents row also responds getitem or accept tuple index use aij syntax,i want define class represent matrix class matrix def initself mat selfmat mat selfdim lenmat classmethod def withdimmatrix dimension mat dimension rangedimension return matrixmat mat list lists represent matrix a b c i write following a matrix b c i also started define operators like def addself n selfdim result selfwithdimn rangen j rangen resultmatij selfmatij othermatij return result now i want access element j matrix a i amatij the question i define operator order aij like i defined add,3 make sure include icom eggs list either add buildout section buildout eggs icom sqlalchemy flask scss icom section icom recipe zcrecipeegg eggs icom buildouteggs,buildoutcfg buildout parts icom develop unzip true includesitepackages false eggs sqlalchemy flask scss icom recipe zcrecipeegg eggs buildouteggs interpreter python scripts createdb scss createdb scripts setuppy setuptools import setup findpackages setup name icom version url httpdomaincom license bsd description author lzyy authoremail someonesomecom packages findpackages src packagedir src installrequires setuptools flask sqlalchemy scss flaskactions zipsafe false entrypoints consolescripts createdb modelstablescreatedb note flaskactions buildoutcfg run binbuildout vv got messages installing zcbuildout setuptools we best distribution satisfies zcbuildout picked zcbuildout we develop egg setuptools cdevr develop usershealdreamdropboxprojecticom usershealdreamdropboxprojecticom varfoldersdnnfjhttjsbfgnttmpfwbbk develop mxn usershealdreamdropboxprojecticomdevelopeggstmpfcxyfbuild running develop running egginfo writing requirements srcicomegginforequirestxt writing srcicomegginfopkginfo writing toplevel names srcicomegginfotopleveltxt writing dependencylinks srcicomegginfodependencylinkstxt writing entry points srcicomegginfoentrypointstxt reading manifest file srcicomegginfosourcestxt writing manifest file srcicomegginfosourcestxt running buildext creating usershealdreamdropboxprojecticomdevelopeggstmpfcxyfbuildicomegglink link src installed usershealdreamdropboxprojecticomsrc createdbpy bin dir install flaskactions either,2 i found solution pyqt installed correctly qt however pyqt installed macport installation python system pythoninstallation to change installation start executing python i selected python using macports sudo port select python python,i downloaded qt httpqtnokiacomdownloads installed using macports i tried install pyqt binding python installed default macos x snow leopard using two lines sudo port install pypyqt sudo port install pypyqt obviously didnt work if i try importing qtmodules interactive pythonshell i get following error import pyqtqtcore traceback recent call last file stdin line module importerror no module named pyqtqtcore what i wrong how i get python qt pyqt running,1 are specific problem way django explains httpsdocsdjangoprojectcomendevtopicshttpfileuploads first need assign enctypemultipartformdata inside form tag if must manually instead leveraging power django forms framework need manually assign file field data model def myviewrequest image requestfiles imagename tour tour tourname requestpostget name tourcapacity requestpostget capacity tourimagesaveimagename image toursave i recommend checking django modelforms view template combo much error checking redisplaying written one minute class myformformsmodelform class meta model tour def myviewself requestmethod post form myformrequestpost requestfiles formisvalid formsave else form myform return renderrequest mytemplatehtml form form form method post enctypemultipartformdata csrftoken formasp input typesubmit form,i form template like form action methodget stylefontfamily tahoma fontsize px table stylewidth tr td name td td input idname namename typetext td tr tr td labelcapacity labelampnbsptd td input idcapacity namecapacity typetext td tr tr td labelpicturelabel td td input typefile nameimagename ida div td tr tr td ampnbsp td td input idadd typebutton valuesave td tr table form i wanna get fields image save model class tourmodelsmodel namemodelscharfieldmaxlength capacitymodelssmallintegerfield imagemodelsimagefielduploadtogallery i save image template via view,1 solved least worked around by using thread ssh m option i could one master ssh connection open commands open ssh subprocess connects master connection thereby alleviating need open one connection,i trying make small module opens ssh connection allows send commands ssh return output command hereby one ssh connection multiple commands cause autoblocks i aware paramiko i cannot use i use python constraints the module i wrote httpkbickerwebcernchkbickersshpy in principle works however using cat read text file program hangs i determined reading new line pty hangs i assume kind buffer problem i idea solve i would also grateful advice code thank advance help,1 i think need numpy def getroundedthresholdva minclip return roundfloata minclip minclip single number want vectorize function need replace round npround floata nparraya dtypefloat,i would like know i round number numpy upper lower threshold function predefined step size hopefully stated clearer way i number step size equal i need round closest either case i came function work i wonder better succint way thanks advance paolo def getroundedthresholdva minclip import numpy np import math digits intmathlogminclip b nprounda digits b roundedup c b minclip uplow nparraybc else roundeddown c b minclip uplow nparraycb absdelta npabsa uplow return uplowabsdeltaargmin getroundedthresholdv,3 look state machine compilers like ragel they generate compilable code based state machine specification,i need define binary protocol use c python written application my question right tool job i need implement protocol parsing building code c python i heard google protocol buffers c implementation mature enough protocol is better substitute,1 your problem control codes proper utf ascii esc friends proper xml characters even inside cdata section the valid xml characters xml values less u u tab ua newline amd ud carriage return if want record things involving codes escape ub escape way there option,i writing python program logs terminal interaction similar script program i like store log xml format the problem terminal interaction includes vt escape codes python complain i write data file utf encoded eg pid fd ptyfork pid osexecvpbashbashl else lots ttyrelated stuff see httpgroupsgooglecomgroupcomplangpythonmsgdebcfccc fout codecsopensessionxml encodingutf modew foutwrite xml version encodingutfn foutwritesessionn r w e selectselect fd f r ffd foutwriteentrycdata buf osreadfd foutwritebuf foutwriteentryn else foutwritesession foutclose this script works sense writes file disk resulting file proper utf causes xml parsers like etree barf escape codes one way deal filter escape codes first but possible something like escape codes maintained resulting file parsed xml tools like etree,1 it working intended world programming languages work subclass overrides all methods parent class however really really want call afoo might able like i cannot guarantee and case must principles good programming class aobject def fooself afooself,this code throws exception attributeerror wtf afoo calling bfoo call afoo how i force call afoo method call inside afoo call a class aobject def fooself print selffoo def fooself return foo class ba def fooself raise attributeerror wtf def fooself raise attributeerror wtf def fooself superb selffoo myb b mybfoo,3 to local python deployments sitepackages create isolated python environments tool called virtualenv httppypipythonorgpypivirtualenv it answers questions overrides default python interpreter activation can sitepackages folder root access needed,i work grid i need install python packages i trying install pythonsetup tools though grid python installed run python setuppy install gives permission denied usrlocallibpythonsitepackagestesteasyinstallwritetest hence i went installed python home directory userpathdesktoppython now someone tell following change python path desktoppython ie i run python must run usrlocalbinpython instead must run python installed homedesktoppython directory how install setup tools home python directory,1 what want proxy model acts bridge qsqlmodel view for need subclass qabstractproxymodel you consistent way finding parentchild relationships proxy model mapping source model might require keeping tally proxy model when subclassing qabstractproxymodel need redefine minimum methods rowcount columncount parent index data maptosource mapfromsource also keep mind qabstractproxymodel autopropagate signals so order view aware changes source model like insert delete update need pass proxy model course updating mappings proxy model it require work end flexible structure and eliminate stuff need synchronizing database custom qabstractitemmodel edit a custom proxy model groups items flat model according given column import sys collections import namedtuple import random pyqt import qtcore qtgui groupitem namedtuplegroupitemnamechildrenindex rowitem namedtuplerowitemgroupindexrandom class grouperproxymodelqtguiqabstractproxymodel def initself parentnone supergrouperproxymodel selfinitparent selfrootitem qtcoreqmodelindex selfgroups list groupitems selfgroupmap map group names group indexes selfgroupindexes list groupindexes locating group row selfsourcerows map source rows group index selfgroupcolumn grouping column def setsourcemodelself source groupcolumn supergrouperproxymodel selfsetsourcemodelsource connect signals selfsourcemodelcolumnsabouttobeinsertedconnectselfcolumnsabouttobeinsertedemit selfsourcemodelcolumnsinsertedconnectselfcolumnsinsertedemit selfsourcemodelcolumnsabouttoberemovedconnectselfcolumnsabouttoberemovedemit selfsourcemodelcolumnsremovedconnectselfcolumnsremovedemit selfsourcemodelrowsinsertedconnectselfrowsinserted selfsourcemodelrowsremovedconnectselfrowsremoved selfsourcemodeldatachangedconnectselfdatachanged set grouping selfgroupbygroupcolumn def rowcountself parent parent selfrootitem root level return lenselfgroups elif parentinternalpointer selfrootitem children level return lenselfgroupsparentrowchildren else return def columncountself parent selfsourcemodel return selfsourcemodelcolumncountqtcoreqmodelindex else return def indexself row column parent parent selfrootitem group return selfcreateindexrowcolumnselfrootitem elif parentinternalpointer selfrootitem return selfcreateindexrowcolumnselfgroupsparentrowindex else return qtcoreqmodelindex def parentself index parent indexinternalpointer parent selfrootitem return selfrootitem else parentrow selfgetgrouprowparent return selfcreateindexparentrowselfrootitem def dataself index role role qtcoreqtdisplayrole parent indexinternalpointer parent selfrootitem return selfgroupsindexrowname else parentrow selfgetgrouprowparent sourcerow selfsourcerowsindexselfgroupsparentrowchildrenindexrow sourceindex selfcreateindexsourcerow indexcolumn return selfsourcemodeldatasourceindex role return none def flagsself index return qtcoreqtitemisenabled qtcoreqtitemisselectable def headerdataself section orientation role return selfsourcemodelheaderdatasection orientation role def maptosourceself index indexisvalid return qtcoreqmodelindex parent indexinternalpointer parentisvalid return qtcoreqmodelindex elif parent selfrootitem return qtcoreqmodelindex else rowitem selfgroupsparentrowchildrenindexrow sourcerow selfsourcerowsindexrowitem return selfcreateindexsourcerow indexcolumn qtcoreqmodelindex def mapfromsourceself index rowitem selfsourcerowsindexrow grouprow selfgetgrouprowrowitemgroupindex itemrow selfgroupsgrouprowchildrenindexrowitem return selfcreateindexitemrowindexcolumnselfgroupindexesgrouprow def cleargroupsself selfgroupmap selfgroups selfsourcerows def groupbyselfcolumn selfbeginresetmodel selfcleargroups selfgroupcolumn column sourcemodel selfsourcemodel row rangesourcemodelrowcountqtcoreqmodelindex groupname sourcemodeldataselfcreateindexrowcolumn qtcoreqtdisplayrole groupindex selfgetgroupindexgroupname rowitem rowitemgroupindexrandomrandom selfgroupsgroupindexrowchildrenappendrowitem selfsourcerowsappendrowitem selfendresetmodel def getgroupindexself groupname return index group denoted name group given name create return groupname selfgroupmap return selfgroupmapgroupname else grouprow lenselfgroupmap groupindex selfcreateindexgrouprowselfrootitem selfgroupmapgroupname groupindex selfgroupsappendgroupitemgroupnamegroupindex selfgroupindexesappendgroupindex selflayoutchangedemit return groupindex def getgrouprowself groupindex ix enumerateselfgroupindexes idgroupindexidx return return def rowsinsertedself parent start end row rangestart end groupname selfsourcemodeldataselfcreateindexrowselfgroupcolumn qtcoreqtdisplayrole groupindex selfgetgroupindexgroupname selfgetgrouprowgroupindex groupitem selfgroupsselfgetgrouprowgroupindex rowitem rowitemgroupindexrandomrandom groupitemchildrenappendrowitem selfsourcerowsinsertrow rowitem selflayoutchangedemit def rowsremovedself parent start end row rangestart end rowitem selfsourcerowsstart groupindex rowitemgroupindex groupitem selfgroupsselfgetgrouprowgroupindex childrenrow groupitemchildrenindexrowitem groupitemchildrenpopchildrenrow selfsourcerowspopstart lengroupitemchildren remove group grouprow selfgetgrouprowgroupindex groupname selfgroupsgrouprowname selfgroupspopgrouprow selfgroupindexespopgrouprow del selfgroupmapgroupname selflayoutchangedemit def datachangedself topleft bottomright toprow topleftrow bottomrow bottomrightrow sourcemodel selfsourcemodel loop changed data row rangetoprowbottomrow oldgroupindex selfsourcerowsrowgroupindex oldgroupitem selfgroupsselfgetgrouprowoldgroupindex newgroupname sourcemodeldataselfcreateindexrowselfgroupcolumnqtcoreqtdisplayrole newgroupname oldgroupitemname move new group newgroupindex selfgetgroupindexnewgroupname newgroupitem selfgroupsselfgetgrouprownewgroupindex rowitem selfsourcerowsrow newgroupitemchildrenappendrowitem delete old group oldgroupitemchildrenremoverowitem lenoldgroupitemchildren remove group grouprow selfgetgrouprowoldgroupitemindex groupname oldgroupitemname selfgroupspopgrouprow selfgroupindexespopgrouprow del selfgroupmapgroupname selflayoutchangedemit,i want produce simple enough application uses qtreeview widget show hierarchical data sqlite flat table use qdatawidgetmapper populate lineedit fields allow user edit turn updates table simple amp basic i working basis following process would best way connect dbase query data create populate custom qabstractitemmodel data manipulating dict create nodes parents children dynamically dict entry node generated associated parent use qdatawidgetmapper populate widgets user edits data qabstractitemmodel qaim updated then run update insert whatever query using new values qaim model refresh qaim associated widgets i realise i using qtableview qlistview i would need custom model could write straight back database the process i outlined seems mean keep two sets data going ie sqlite table custom qaim ensure kept date this seems bit cumbersome i sure must better way qtreeview taking data straight sqlite table obvious need manipulation convert flat data hierarchical data i wondering course whether i completely misunderstood relationship qabstractitemmodel qsqlmodels i overcomplicating ignorance thanks,1 revised based new info if able produce text tags need find pattern first paragraph fit cases based example data stuff text tags firstparagraph researchrnrndataredotall print firstparagraphgroup,i trying extract first paragraph but i found luck can one help text httpdpastecom my text dynamic thanks update i reading xml file using etree module in xml tag called texttext the data texttext i want print following data text tags is possible thanks zamindar teజమీందార్ telugu languagetelugu thriller film directed v madhusudhan rao produced tammareddy krishna murthy ravindra art picturesthis variety role akkineni nageswara rao popular soft romantic roleshe plays role tough cid officer wellthe movie good songsthis movie considerable resemblance cary grant english movie charade filmcharade,1 in code def fooself superb selffoo self instance b when method derived a called instance b start looking namespace b method found eg overridden b implementation a used always self referring b at point self instance a,this code throws exception attributeerror wtf afoo calling bfoo call afoo how i force call afoo method call inside afoo call a class aobject def fooself print selffoo def fooself return foo class ba def fooself raise attributeerror wtf def fooself raise attributeerror wtf def fooself superb selffoo myb b mybfoo,1 vehiclesobjectsall give empty list correct behavior if want raise exception test empty list raise vehicledoesnotexists i understand want,my code like def getallvehiclesself try vehobj vehiclesobjectsall except vehicledoesnotexists e loggerdebugexception getallvehicles e return vehobj and test case def testgetallvehiclesself vehiclesobjectsalldelete instance vehicles selfassertraisesvehicledoesnotexists instancegetallvehicles exception never raised i require vehiclesobjectsall raise exception code coverage asking execute except block,3 you probably want findall pattern recompiler n nn remultiline patternfindalldata tim answer gives background,the following content source file number name jan mayen country norway lat long it seems like major mistake expression misunderstanding rematch i need get properties last one pattern recompiler n nn print patternmatchtextgroups standard deviations n standard deviations any ideas edit oh differently formatted content following therefore i want use refindall michael,2 text number name jan mayen country norway lat long dictresplit w line line textsplit n line country norway lat long name jan mayen number long,the following content source file number name jan mayen country norway lat long it seems like major mistake expression misunderstanding rematch i need get properties last one pattern recompiler n nn print patternmatchtextgroups standard deviations n standard deviations any ideas edit oh differently formatted content following therefore i want use refindall michael,1 the problem repeating capturing group pattern recompiler this means every match previous match overwritten this expected behaviour regex engines like net allow later access individual captures repeated group so fact need use refindall correct parameters e g nonrepeating group avoiding matches want since explained sets following content apart stuff actually want i elaborate much,the following content source file number name jan mayen country norway lat long it seems like major mistake expression misunderstanding rematch i need get properties last one pattern recompiler n nn print patternmatchtextgroups standard deviations n standard deviations any ideas edit oh differently formatted content following therefore i want use refindall michael,3 in class a instead calling self methods need call a methods pass self manually this normal way things really good reason like class aobject def fooself print afooself def fooself return foo class ba def fooself raise attributeerror wtf def fooself raise attributeerror wtf def fooself superb selffoo myb b mybfoo,this code throws exception attributeerror wtf afoo calling bfoo call afoo how i force call afoo method call inside afoo call a class aobject def fooself print selffoo def fooself return foo class ba def fooself raise attributeerror wtf def fooself raise attributeerror wtf def fooself superb selffoo myb b mybfoo,3 my guess first file zfnamelist contain anything skip line words loop file newfilewrite n it difficult tell without seeing files looping perhaps add debug statements print files names info eg size,i stuck code printing blank line writing text file what i reading two files zipped folder writing text new text file i getting expected results file except fact blank line first line file def test zipfileiszipfiler cuserstestdesktopzipfilezip zf zipfilezipfiler cuserstestdesktopzipfilezip filename zfnamelist zfopenfilename r f words iotextiowrapperf newfile ioopenr cuserstestdesktopnewfiletxt line words newfilewriteline newfilewrite n else pass zfclose wordsclose fclose newfileclose output newfile blank line first this test line this test line this test line test test any ideas thanks,2 if build regex dot matches newline tested ruby i guess work python it quite answer niall byrne nnn please see effect rubular,i trying extract first paragraph but i found luck can one help text httpdpastecom my text dynamic thanks update i reading xml file using etree module in xml tag called texttext the data texttext i want print following data text tags is possible thanks zamindar teజమీందార్ telugu languagetelugu thriller film directed v madhusudhan rao produced tammareddy krishna murthy ravindra art picturesthis variety role akkineni nageswara rao popular soft romantic roleshe plays role tough cid officer wellthe movie good songsthis movie considerable resemblance cary grant english movie charade filmcharade,1 it seem really want rematch your regex almost right grouping much how xyz termabc foo foo termabc foo refindallr term n joins abc abc,i trying write regular expression python match either quoted string spaces unquoted string without spaces for example given string termfoo result would foo given string termfoo bar result would foo bar so far i come following regular expression r recompiler term term the problem match come either group group i something like rmatchsearchstring term mgroup mgroup is way i one step,1 if path exist ospathexists call returns false rather throwing exception so first part code work intended use instead ospathexistsecontact osmkdirecontact,import os try ospathexistsecontact check dir exist except osmkdirecontact create def addnamecellemail add contact conpath econtact conpath conpathb conpathstrip conpath name txt conpath conpathconpathbconpath file openconpath w filewrite name name n write file filewrite cell cell n filewrite email email n fileclose def getname get contact conpath econtact conpath conpathb conpathstrip conpath name txt conpath conpath conpathb conpath try ospathexistsconpath check exist file openconpath r getfile filereadlines printgetfile except printnot found! def deletename delete contact conpath econtact conpath conpathb conpathstrip conpath name txt conpath conpath conpathb conpath try ospathexistsconpath osremoveconpath printnamehas deleted! except printnot found! when i type add jack dsgmailcom i got traceback recent call last file pyshell line module add jack dsgmailcom file elabtpy line add file openconpath w ioerror errno no file directory econtactjacktxt i tried econtact stil work and i ran successfully first time but i newbie forgive code sucks thank,2 rather trying process page use firebug figure names form fields use httplib whatever send request necessary fields settings if sent using ajax able determine values sent server firebug well,i trying interact html website uses heavily obfuscated javascript hide regular html elements what i want fill form read returned results proving harder expected when i read page using firebug gave source code deobfuscated i use i want accomplish the firebug output showed regular elements website tags like hidden original source i written rest application python using mechanize interact web services i rather use existing python module possible the problem read source code way mechanize understand also generate response web server interpret could i use regular mechanize controls even though html code obfuscated in beginning project i used pywebkitgtk instead mechanize ditched really implemented well python most functions missing would sensible method perhaps start webkitbrowser i read html use mechanize any help would greatly appreciated i really bind thanks edit i tried dumping html fetched mechanize opening pywebkitgtk using loadhtmlstring evaluating html way unfortunately since document i trying parse loads resources dynamically scripts stops waiting resources loaded note i use webkit load document since i use mechanize cookiejar function allow log first i also tried dumping html webkit reason dumped obfuscated javascript displaying website perfectly fine if webkit could dump deobfuscated javascript way firebug i could work form request according clean code,1 from link posted scripts run interactively terminal background via locale this already disadvantage release apps android market easily this however ostensibly avoided build script pygame subset android i sure the python interpreter however need installed device bloat app size quite bit the speed execution python android device course slower java python magically accelerate runs phone the difference great situations though,this link says indeed possible write code python use app development android platform i would like know catch using python java is compromise made speed execution size,2 and spent hours trying find answer posting question i find solution minutes posting turns gtk need call glibthreadsinit code works initial girepository import glib glibthreadsinit call gtkmain working version code looks like girepository import gtkgdk glib import threading import time class appgtkwindow def initself superapp selfinit selfconnectdestroy selfondestroy selflayout gtkvbox selfprogress gtkprogressbar selflayoutpackstartselfprogress false false selfsetsizerequest selfgobutton gtkbuttonstart selfgobuttonconnectclicked selfdowork selflayoutpackstartselfgobutton false false selfaddselflayout selfshowall def ondestroywidget event gtkmainquit def doworkself widget def workerthread sofar sofar timesleep printwork far sofar gdkthreadsenter try sofar selfprogresssetfractionsofar finally gdkthreadsleave sofar threadingthreadtargetworkerthreadstart name main app app glibthreadsinit gdkthreadsinit gdkthreadsenter gtkmain gdkthreadsleave,i trying sort problem hours scouring web reading documentation helped i trying perform long running task separate thread display progress progress bar ui the new thread started given time main loop quits i called gdkthreadsinit gtkmain i surrounded ui calls gdkthreadsenter gdkthreadsleave the following code reproduces problem clicking start button effect window closed main loop quits i see second thread work ie i see print statements half second apart class appgtkwindow def initself superapp selfinit selfconnectdestroy selfondestroy selflayout gtkvbox selfprogress gtkprogressbar selflayoutpackstartselfprogress false false selfsetsizerequest selfgobutton gtkbuttonstart selfgobuttonconnectclicked selfdoworksubclass selflayoutpackstartselfgobutton false false selfaddselflayout selfshowall def ondestroywidget event gtkmainquit def doworkself widget def workerthread sofar sofar timesleep printwork far sofar gdkthreadsenter try sofar selfprogresssetfractionsofar finally gdkthreadsleave sofar threadingthreadtargetworkerthreadstart name main app app gdkthreadsinit gdkthreadsenter gtkmain gdkthreadsleave could related fact i using gtk,2 decimaldecimal allows use specific precision decimaldecimal decimal,i string x and i want convert digits however i used int float others i get want keep zeroes please help i want x result,3 the object returned pyevalevalcode transformed python string using pyobjectrepr pyobjectstr the resultant python string turned regular c string pystringasstring,i trying emulate codeinteractiveinterpreter embedded python c api i using pyevalevalcode evaluate user input i trying evaluate user input interpreter return output string like interpreter would however pyevalevalcode returns multitude datatypes wrapped pyobject is way i trying constraints it needs done using embedding api cannot done using pyrunrunsimplestring laying codeinteractiveinterpreter,2 one way read esri shape file using ogr library httpwwwgdalorgogr use geos geometry library httptracosgeoorggeos pointinpolygon test this requires cc programming there also python interface geos httpsgilliesnetblogpythongeosmodule i never used maybe want another solution use httpgeotoolsorg library that java i also java software download httpwwwmapyrusorg plus jtsjar httpwwwvividsolutionscomproductsasp you need text command file insidemapyrus containing following lines check point lays inside first polygon esri shape file dataset shapefile usstatesshp fetch print containsgeometry and run java cp mapyrusjarjtsjar orgmapyrusmapyrus insidemapyrus it print point inside otherwise you might also get good answers post question httpgisstackexchangecom,whats way check geopoint within area given shapefile i maneged load shapefile python get,1 citing jpype documentation python threads for part python threads based os level threads ie posix threads work without problem the thing remember call jpypeattachthreadtojvm thread body make jvm usable thread for threads start call isthreadattachedtojvm check hth,i tested simple hello world line test jpype jpypejavalangsystemoutprintlnhello world it works great inside context main python program however inside context running thread i get following response a fatal error detected java runtime environment sigsegv xb pcxfaeb pid tid jre version b java vm java hotspottm bit server vm b mixed mode linuxamd compressed oops problematic frame c jpypesox jpjavaenvfindclasschar constx failed write core dump core dumps disabled to enable core dumping try ulimit c unlimited starting java an error report file information saved homeimediantsvmsrcservernlphserrpidlog if would like submit bug report please visit httpbugreportsuncombugreportcrashjsp aborted,3 try removing celeryalwayseager true you explicitly asking celery execute tasks synchronously it always wait result this setting useful writing unit tests etc read httpaskgithubcomceleryconfigurationhtml,i trying run tasks background users browse site whenever i call function using celery seems executed synchronously instead asynchronously eg i call functiondelay entire site hangs functiondelay returns other methods calling functions similar manner applyasync subtasks exhibit problem i guessing something either django celery misconfigured i know celery configuration settingspy import djcelery djcelerysetuploader celeryresultbackend amqp celerybeatscheduler djceleryschedulersdatabasescheduler brokerhost localhost brokerport brokeruser test brokerpassword test brokervhost testhost testrunner djcelerycontribtestrunnerruntests celeryimports myapptasks brokerbackend memory celeryalwayseager true trying start celery daemon managepy celeryd i get following output warningmainprocess celeryimaclocal v configuration broker memorytestlocalhosttesthost loader djceleryloadersdjangoloader logfile stderrwarning concurrency events off beat off queues celery exchangecelery direct bindingcelery warningmainprocess celeryimaclocal started,3 avoid grouping instead use lookaheadlookbehind assertions eliminate parts needed termfoo termfoo bar termbar foo termfoo term refindallr term term gives foo foo bar bar,i trying write regular expression python match either quoted string spaces unquoted string without spaces for example given string termfoo result would foo given string termfoo bar result would foo bar so far i come following regular expression r recompiler term term the problem match come either group group i something like rmatchsearchstring term mgroup mgroup is way i one step,2 too much work singledigitsum intinputvalue note fail numbers less,i trying get user input birth date add individual ints numbers also sum digits greater equal loop repeats process runs value here code far sumyear sumyear num strsumyear sumyear intnum printsumyear this works however i think would better done loop and way i use something like sumyear would great note i think i use sum function thanks guys help i issue though i sure code evaluated i provide month day true yearinputplease enter year born monthinputplease enter month born dayinputplease enter day born ifintmonth intday break elifintmonth intday break elifintmonth intday break else printplease enter valid input,1 once approach list possible alternatives pick one minimum cost functools import wraps def cacheorigfunc wrapsorigfunc def wrapperargs args return dargs result origfuncargs dargs result return result return wrapper cache def alternativest given tuple word lengths maximum line length return list possible line groupings showing total length line alternatives return alts x enumeratet x break tail ti tail altsappends break subalt alternativestail altsappends subalt return alts def costt evaluate cost lines given line lengths cost sample text cost sample text return summ x x def textwraps given string result list strings optimal line wrapping print textwrap this sample text this sample text words ssplit tuplemaplen words lengths minalternativest keycost result worditer iterwords length lengths line length word nextworditer lineappendword lenword resultappend joinline return result name main import doctest print doctesttestmod the code spedup limiting number alternatives searches perhaps limited three longest alternatives line,first background i started algorithmswhich i feel i lack logic reasoning power excel ati trying print this sample text various lines max chars line first line spaces left end cost costthe spaces left end line cubed cost sample cost text cost total cost now optimized cost cost sample cost text cost total cost so clearly cannot use greedy approach instead use dynamic programming problem i cannot figure sub structure reused i really stuck figuring i link cost condition printing python i index word i get length word sort stuck i next when print happens entire string gets printed one line this i got far i apologize really silly question i stuck really need help thanks this i tried implementing code although i tried running tests code test written friend i dont think i getting right any help suggestion appreciated printtestpy import os import sys glob import glob todo replace solution printing import printneatly log open outputlog w this tests code text maxline source glob txt opensource f fulltext fread words fulltextsplit cost text printneatlywords maxline double check cost lines textsplit n truecost line text truecost maxline lenline print output cost print log print log source print log print log text print log print log cost cost print log true cost truecost print log logclose print log open outputlog f print fread printingpy def printneatlywordlist max strings this sample string splitting string taking words wordliststringssplit cost dynprint printlinewordlist lenwordlist max dyn dynprint print dyn return cost dynprint def costlines max return summaxlenx x lines def printlinewordlist count max results results count range lenwordlist best wordlistcount bestcost costbest max mycount count line wordlistmycount lenline max attempt attemptcost resultsmycount attempt attempt line attemptcost costlinemax attemptcost bestcost best attempt bestcost attemptcost mycount mycount line wordlistmycount line else break results best bestcost print best print bestcost return bestcost best printneatly the text files need tested give output two cost need i getting one point i going wrong cost true cost,1 if best way arrange one word two words etc lines going change based lines come later it change based words come later words small enough join others line but take words isolation try arrange lines set solutions always optimal there may equivalent answers example given criteria cats hats char lines two solutions both best always decide either one stick without sacrificing correctness this always best this note saying always best line what saying one word single best way arrange one line this arranged this this the latter however best so whenever two words consider ignore this entirely never superior this arranged this this this we already know this superior this see previous bullet point turns this best so ignore this this sample arranged this sample see bullet even look this sample see bullet this sample i know python hacked together so forgive unpythonic whatever p def costlines limit figures cost current arrangement words lines return sumlimitlenx x lines def lineifywords limit splits words lines limit chars find optimal solution assuming words limit chars long results count range lenwords best wordscount start assuming one word per line bestcost costbest limit mycount count line wordsmycount start one word lenline limit figure optimal cost assuming words another line attempt attemptcost resultsmycount attempt attempt line attemptcost costlinelimit print attempt attemptcost bestcost best attempt bestcost attemptcost steal another word one done mycount mycount line wordsmycount line else break optimal result count words save posterity results best bestcost return resultslenwords def wrapphrase limit helper functionso caller pass array words need know words phrasesplit return lineifywords limit i originally recursive solution turns python places limits recursion make unsuitable decent size text realworld length limit come play you backtrack way beginning anyway anything gets memoized like words ended hitting recursion limits this could extended starting enough words fill last line still limit max multiple original limit i found using hack build results til recursion limit longer issue if though perhaps indication recursion issue,first background i started algorithmswhich i feel i lack logic reasoning power excel ati trying print this sample text various lines max chars line first line spaces left end cost costthe spaces left end line cubed cost sample cost text cost total cost now optimized cost cost sample cost text cost total cost so clearly cannot use greedy approach instead use dynamic programming problem i cannot figure sub structure reused i really stuck figuring i link cost condition printing python i index word i get length word sort stuck i next when print happens entire string gets printed one line this i got far i apologize really silly question i stuck really need help thanks this i tried implementing code although i tried running tests code test written friend i dont think i getting right any help suggestion appreciated printtestpy import os import sys glob import glob todo replace solution printing import printneatly log open outputlog w this tests code text maxline source glob txt opensource f fulltext fread words fulltextsplit cost text printneatlywords maxline double check cost lines textsplit n truecost line text truecost maxline lenline print output cost print log print log source print log print log text print log print log cost cost print log true cost truecost print log logclose print log open outputlog f print fread printingpy def printneatlywordlist max strings this sample string splitting string taking words wordliststringssplit cost dynprint printlinewordlist lenwordlist max dyn dynprint print dyn return cost dynprint def costlines max return summaxlenx x lines def printlinewordlist count max results results count range lenwordlist best wordlistcount bestcost costbest max mycount count line wordlistmycount lenline max attempt attemptcost resultsmycount attempt attempt line attemptcost costlinemax attemptcost bestcost best attempt bestcost attemptcost mycount mycount line wordlistmycount line else break results best bestcost print best print bestcost return bestcost best printneatly the text files need tested give output two cost need i getting one point i going wrong cost true cost,1 ignacio vazquezabrams answer provides formula but none code loop without using sumyear could look like sumyear sumyear summapint strsumyear if allowed use sum homework sumyear strsumyear intd sumyear for second question assuming python true try year intinputplease enter year born month intinputplease enter month born day intinputplease enter day born birthday datetimedateyear month day except valueerror e printerror e else break if allowed use tryexcept year getintplease enter year born datetimeminyear datetimemaxyear month getintplease enter month born day getintplease enter day born numberofdaysinmonthyear month birthday datetimedateyear month day where getint def getintprompt minvalue maxvalue get integer user true inputprompt sstripisdigit v ints minvalue v maxvalue return v printerror input integer range minvalue maxvalue and numberofdaysinmonth number days month disregarding leap years ndays ndays lenndays odd months ndays lenndays even months ndays february ndays august fill months def numberofdaysinmonthyear month return ndaysmonth month isleapyear,i trying get user input birth date add individual ints numbers also sum digits greater equal loop repeats process runs value here code far sumyear sumyear num strsumyear sumyear intnum printsumyear this works however i think would better done loop and way i use something like sumyear would great note i think i use sum function thanks guys help i issue though i sure code evaluated i provide month day true yearinputplease enter year born monthinputplease enter month born dayinputplease enter day born ifintmonth intday break elifintmonth intday break elifintmonth intday break else printplease enter valid input,1 you probably want avoid using id field names it could confused data key id coding httpcodegooglecomappenginedocspythondatastorekeyclasshtml userid good choice your iphone guy wanting use ints concerning you really want depend use sequential int values ids beside tricky get correct clustered environments introduce security issues ids become easily guessable,hiya i asked question earlier regarding using keys answered perfectly however i wondering creating using keys models way go i told iphone app guy need ints store database i got python code working keys may back track i keen hear opinion whole creating key names vs auto generating ids iphone app use without big changes here models class userdbmodel id dbstringproperty name dbstringproperty image dbblobpropertydefaultnone class bookdbmodel image dbblobproperty dateadded dbdatetimepropertyautonowaddtrue isactive dbbooleanpropertydefaulttrue class bookuserdbmodel book dbreferencepropertybook user dbreferencepropertyuser isactive dbbooleanpropertydefaulttrue and i dealing using keys every time user signs bookuser record created exist already i need send data iphone ids store database the looks pretty solid handsup thinks i tell iphone developer suck or solved better way get users details userid user usergetbykeynameuserid userkey userkeyname get latest active book book bookallfilter isactive trueget bookkey bookkeyname get latest book user bookuserkeyname ss strbookkey struserkey bookuser bookusergetorinsertbookuserkeyname bookusercard card bookuseruser user bookuserput,1 i see problem using indexes sumx x x combinationsargs if really want avoid sumxy xy combinationsargs but honest i would prefer commented version it clear readable explicit and really gain much writing three variables is function i use acts like sum multiplication builtin no but get functionality rather simply following in in operator import mul in reducemula out,let say i class rectangleobject def initself length width height selfl length selfw width selfh height selfh selfa selfl selfw else itertools import combinations args selfl selfw selfh selfa sumxy xy combinationsargs thanks so original code selfl selfw selfl selfh selfw selfh selfv selfl selfw selfh what everyone take line selfa sumxy xy combinationsargs i heard explicit list index references avoided is function i use acts like sum multiplication thanks help everyone,2 if supply optional second argument strsplit control many splits performed testposition def givemes words lista ssplit resultlistaitem item words return result rec lorem ipsum dolor sit amet consectetur adipiscing elit in vitae neque nec magna tristique ornare cras faucibus risus eu odio pharetra interdum nunc dui mi rhoncus ut aliquet printgivemerec testposition yields nunc dui mi rhoncus ut aliquet rec lorem ipsum dolor sit amet consectetur adipiscing elit in vitae neque nec magna tristique ornare cras faucibus risus eu odio pharetra interdum nunc dui mi printgivemerec testposition yields nunc dui mi,python x i series lines i reading rearranging making line list nested inside another list i got following testposition def givemes words lista ssplit return listaitem item words rec testline testlistappendgivemerec testposition in words rec passed lorem ipsum dolor sit amet consectetur adipiscing elit in vitae neque nec magna tristique ornare cras faucibus risus eu odio pharetra interdum nunc dui mi rhoncus ut aliquet list line would rearranging list would get appended another list nested lists interdum dolar lorem ipsum risus eu amet consectetur elit in nec nunc dui mi rhoncus ut aliquet which fantastically well however i like take last group together like interdum dolar lorem ipsum risus eu amet consectetur elit in nec nunc dui mi rhoncus ut aliquet and line passed elements say groups whatever beyond nd element text line line ie example elements one lorem ipsum dolor sit amet consectetur adipiscing elit in vitae neque nec magna tristique ornare cras faucibus risus eu odio pharetra interdum nunc dui mi resulting list would interdum dolar lorem ipsum risus eu amet consectetur elit in nec nunc dui mi hope clear ideas thank,2 easyguienterbox argument message argdefaulttext what want import easygui result easyguienterboxmsg enter name title name query default ian ozsvald the signature enterbox function found httpeasyguisourceforgenetdownloadversionpydoceasyguihtmlenterbox alternate link httpwwwfergorgeasyguieasyguihtmlenterbox,the following code gives error import easygui result easyguienterboxmessageenter name titlename query argdefaulttextian ozsvald this error traceback recent call last file volumeschrome usbstoragetkinker guieasygui inputboxpy line result easyguienterboxmessageenter name titlename query argdefaulttextian ozsvald typeerror enterbox got unexpected keyword argument message i running python os x snow leopard,1 you missing c option configures cmd run command exit subprocesscheckoutput cmd c ftype http,how i find program associated given file type using python windows for example given http i like python determine default browser i cmd prompt running ftype http windows gives full path browser i tried subprocesscall httpwwwgooglecom results windowserror error the system cannot find file specified subprocesscheckcall cmd ftype http launches cmd window anything else,1 irc bot twisted demonstrates bot respond several commands you define several command methods call privmsg method getattrself command commandname none retrieves appropriate method call,i recently found oyoyo python irc framework looks decent newbie perspective i chosen build irc bot twisted seems bit daunting i looked example i sure i would implement commands would i lot statements privmsg function and would trigger statements while i complete noob i still newbie please judge stupid question,1 if really want perform calculations take precision account easiest way probably use uncertainties module here example import uncertainties x uncertaintiesufloat x print x the uncertainties module transparently handles uncertainties precision whatever complexity mathematical expressions involved the decimal module hand handle uncertainties instead sets number digits decimal point trust digits given decimal module thus decimaldecimal decimal whereas â± â± â± uncertaintiesufloat thus decimal module gives even though precision â± times larger so want numbers fixed number digits decimal point like accounting applications decimal module good instead need perform calculations uncertainties uncertainties module appropriate disclaimer i author uncertainties module,i string x and i want convert digits however i used int float others i get want keep zeroes please help i want x result,1 note i worked python looking link focus method optional parameter item highlight node if look selectmode option amp set browse,i ttktreeview widget rows data how i set focus select highlight specified item treefocusset nothing treeselectionset complains item found although widget plainly populated zero items trying item better edit select item find id use treeselectionsetid neither treefocusid treefocussetid appears anything,1 next time please show code fails i going guess something like x x print the problem iterate get keys values what want key value oitems v value print v items returns list keys values tuples iterate,i simple structure i going nuts trying isolate number lists eg i kind loop i get typeerror int object iterable what i need thanks btw python,2 one solution might using dictionary vars dict openfiletxt f line f eqindex linefind varname lineeqindexstrip number floatlineeqindex strip varsvarname number printvars and filetxt b c variable so want see variable value printvarsvariable,i text file xyztxt variables i want use variables i know read know use call i need for example if text file x i would like able call variable use said print x would give text file x z later it data,1 the comment style code sample incorrect python uses comments after fixing running snippet pyflakes i see errors programpy service imported unused programpy defer imported unused programpy undefined name succeed programpy local variable assigned never used programpy undefined name application it seems likely undefined name line cause nameerror encountered nameerror python signals sort bug x traceback recent call last file stdin line module nameerror name defined,i trying validate transaction receipt inapp purchase apple store server twisted server i sent skpaymenttransaction transactiontransactionreceipt app server but sending json object apple server i keep getting unhandled error deferred agentrequest i suspect i listening port response apple store i want app communicate twisted server port also here code twistedapplication import internet service twistedinternet import protocol reactor zopeinterface import implements twistedwebiweb import ibodyproducer twistedinternet import defer twistedwebclient import agent twistedwebhttpheaders import headers import json import base class stringproducerobject implementsibodyproducer def initself body selfbody body selflength lenbody def startproducingself consumer consumerwriteselfbody return succeednone def pauseproducingself pass def stopproducingself pass def printresponseresponse print response testing see i def httprequesturl values headers method post agent agentreactor agentrequestmethod url headersheaders stringproducervalues daddcallbackprintresponse class storeserverprotocolprotocol def datareceivedself data receiptbase basestandardbencodedata jsonreceipt jsondumps receiptdata receiptbase print jsonreceipt verified data correct httprequest httpsbuyitunesapplecomverifyreceipt jsonreceipt contenttype applicationxwwwformurlencoded factory protocolfactory factoryprotocol storeserver tcpserver internettcpserver factory tcpserversetserviceparentapplication how i fix error do i create another service listening port if might i service connecting app communicate service connecting https,1 you could call packforget hide widgets later pack show tkinter singledthreaded mainloop runs main event loop therefore call mainloop twice dev mkee import tkinter tk import sys class shuffleobject def initselfmasternone selfmastermaster selftexttktextmaster def hideself selftextpackforget def showself selftextpacksidetkleft padx pady class buttonsobject def initselfmasternone selfmastermaster selfred tkbuttonselfmaster textred bgred fgwhite selfgreen tkbuttonselfmaster textgreen bggreen fgblack selfblue tkbuttonselfmaster textblue bgblue fgwhite def hideself selfredpackforget selfgreenpackforget selfbluepackforget def showself selfredpacksidetkleftexpandtkyesfilltkboth selfgreenpacksidetkleftexpandtkyesfilltkboth selfbluepacksidetkleftexpandtkyesfilltkboth class mainappobject def initselfmasternone selfmastermaster appselfapptktk apptitlemkee tools appgeometry x selfshuffleshufflemaster selfbuttonsbuttonsmaster selfcurrentnone menubartkmenuapp programmenutkmenumenubar programmenuaddcommandlabel shuffle commandlambda selfshowselfshuffle programmenuaddcommandlabel buttons commandlambda selfshowselfbuttons programmenuaddcommandlabel quit commandsysexit menubaraddcascadelabel programs menuprogrammenu appconfigmenumenubar def showselfobj selfcurrent obj try selfcurrenthide except attributeerror pass selfcurrentobj objshow def main mmainapp mappmainloop name main main,i trying make first gui program the problem i figure make main menu would switch one programs clicking button dev mkee tkinter import import tkmessagebox main stuff app tk apptitlemkee tools appgeometry x modules class programs def shuffle app tk apptitleshuffle appgeometry x appmainloop end modules labeltext stringvar labeltextset label labelapp textvariablelabeltext height labelpack button buttonapp text shuffle width commandprogramsshuffle buttonpackside right padxpady appmainloop i know i wrong i idea so gave try could please help,1 it looks like numpy underwent reorganisation recent years httpwwwscipyorgnumpyexamplelistwithdocfft fft numpyfft realfft seems renamed rfft numpy import signal array numpyfft import f fftsignal print f j j j j j j j j f rfftsignal print f j j j j j,i ancient code years old i used access realfft method fft import realfftdata fftlength i guess fft module came numpy now years later i installed numpy pip install numpy and i see docs httpwwwscipyorgnumpyfunctionsbycategory functions fft fftfreq fftshift ifft it strange numpy docs realfft httpnumpysourceforgenetnumdochtmlnumdochtmpgfid,2 that indeed css you getting document like style wrapper primarynav marginoverflowhidden ascbbtnredbackgroundpositionright px ascbbtnblackbackgroundpositionright px ghsearchwidthpxheightpxlineheightpxbackgroundposition px ascbbtnred span spanbackgroundcolorfbackgroundposition px style div pthis bit htmlp div you need remove style tags parsing text,i using lxml convert html txt i almost get i wanted parsing converting parts cleanup tabs spaces empty lines functions ready program running however i tried code hundred htmls different sites i noticed exceptions ie lines like wrapper primarynav marginoverflowhidden ascbbtnredbackgroundpositionright px ascbbtnblackbackgroundpositionright px ghsearchwidthpxheightpxlineheightpxbackgroundposition px ascbbtnred span spanbackgroundcolorfbackgroundposition px i assume css web programming things but i totally unfamiliar questions what lines and suggestions get ride lines edit here i parts question reference anyone drops post future new python lot things improved works ok function htmltxt using lxml author httpgroupsgooglecomgroupcnbbscomplangpythonbrowsethreadthreadaecece def htmltexthtml tree lxmletreefromstringhtml lxmletreehtmlparser isinstancehtml basestring else html skiptag script iframe style node treexpathskiptag nodegetparentremovenode return lxmletreetounicodetree method text return lxmletreetostringtree encodingunicode method text function cleanup text clearnup tabs spaces empty lines remove short lines def textcleanuptext temp list process textlist textsplitlines strip meaningless spaces tabs sstrip set length limit slen textlistappends cleaned oslinesepjointextlist get rid empty lines cleaned oslinesepjoins cleanedsplitlines return cleaned,1 findall len seems like one solution,im trying make regular expression python allows find word within string n times for example wanted find expression could match word cat exactly two times how would it accept the blue cat talks red cat tree because cat exactly two times but accept the cat big because cat and accept either dog yellow for similar reasons thanks lot edit hey guys sorry complicating problem much forgot mention one thing if wanted find cat exactly two times the catcat runs would also match,1 don use regular expressions words textsplit print wordscount cat as vincent points assumes words seperated whitespace words refindallbw is probably better options although whether neccesary depends details provided post edit if even care word boundaries even less reason using regular expression print textcountcat,im trying make regular expression python allows find word within string n times for example wanted find expression could match word cat exactly two times how would it accept the blue cat talks red cat tree because cat exactly two times but accept the cat big because cat and accept either dog yellow for similar reasons thanks lot edit hey guys sorry complicating problem much forgot mention one thing if wanted find cat exactly two times the catcat runs would also match,2 how rematchr bcatb the blue cat talks red cat tree the means “repeat times” use repetitions the b word boundary case cat blue cat talks would match verification and match string you might want go documentation,im trying make regular expression python allows find word within string n times for example wanted find expression could match word cat exactly two times how would it accept the blue cat talks red cat tree because cat exactly two times but accept the cat big because cat and accept either dog yellow for similar reasons thanks lot edit hey guys sorry complicating problem much forgot mention one thing if wanted find cat exactly two times the catcat runs would also match,1 socket package might disabled gae sandbox have tried using request object determine httpdocsweboborgenlatestreferencehtmlid might reliable way,i like get hostname google app engine running devappserverpy gae making request external server server needs know send response unfortunately canonical python way seem work import socket socketgethostbynamesocketgethostname the socket library work gae also osenviron httphost osenviron servername are localhost how could one get ip external server would connect gae thanks reading,2 the forloop iterates keys use lookup corresponding sequences key seq okey print key print seq print,i simple structure i going nuts trying isolate number lists eg i kind loop i get typeerror int object iterable what i need thanks btw python,1 attempt import set flag fails then use flag determine whether offer graphic output try import tkinter guiinstalled true except importerror guiinstalled false result somecalc guiinstalled displaywithguiresult else displayastextresult,i developing python model support graphing correct modules installed i would like source code possible ie graphing model load graphing would ignored menu logic how i accomplish,3 yes you wrap import statement try except block it commonly used backwardscompatability cruft for instance importing fallback module desired module that way rest code oblivious module actually use,i developing python model support graphing correct modules installed i would like source code possible ie graphing model load graphing would ignored menu logic how i accomplish,1 if value equal zero either positive negative take absolute value x float x absx,i parsing xml file coordinates python write transformed output file the problem coordinates i problems parsing another system i would need instead how could i achieve thing this i far node nodes nodename nodeattrib name nodeparts nodenamesplit nodename nodeparts nodename scene fwritenodeparts position nodefind position fwrite f floatpositionattrib x fwrite f floatpositionattrib fwrite fn floatpositionattrib z,2 a couple quick notes quickly skimming code in getscore could add else clause handle ties happen check explicitly playgame move import random top file imports generally always found top file also need reimport every time want random number not sure typo cause play seems always hold integer play true play false inside playgame if want make play contain either true false need using single equals sign eg play true but seem make sense comparing play computer integers also trying accomplish score variable getscore method ah made getscore method return something know match would helpful you access computerwins playerwins inside getscore method defined inside main a simple way return int getscore rather cstyle way handling returning something like pseudo code def getscore score computer wins score elif player wins score return score winner getscore winner print tie game elif winner print player else print computer,i trying write python program i hard time getting score i written value returning function every time i run program seems skip step retrieves score unless i include else statement automatcially jump else statement i attach full code thank much help i greatful this also first time posting forum i apologize i screw something constants rock paper scissors define main function def main set control loop keepgoing y set counter zero computerwins playerwins tiescore call display message displaymessage keepgoing keepgoing y playgame prompt user keep going keepgoing input would like play y yes print the computer computerwins times print the player playerwins times print there tiescore tie scores def playgame get random input computer getrandom get players input play getplay validate input play play play play true else play false print error invalid entry play input please enter rock paper scissors play computer print tie score please try tiescore else getscorecomputer play print the computer chose computer print the player chose play define display message def displaymessage print welcome rock paper scissors game chance see print outsmart this game man vs computer print the program select random integer ask integer print rock paper scissors the program tell print game print good luck print print def getrandom import random generate random int computer randomrandint return computer def getplay prompt user enter integer play input select rock paper scissors return play def getscorecomputer play computer play score player wins print paper covers rock player wins player wins playerwins elif computer play score computer wins print scissors cut paper computer wins computer wins computerwins elif computer play score computer wins print paper covers rock computer wins computer wins computerwins elif computer play score player wins print scissors cut paper player wins player wins playerwins elif computer play score player wins print rock smashes scissors player wins player wins playerwins elif computer play score computer wins print scissors cut paper computer wins computer wins computerwins call main function main,1 there much wrong hard know start get discouraged first looks like mostly use input vs rawinput parens print statements using python already going limit amount help get most people still using python but way the main remaining issues addressing question first using strings player input eg numbers computer choice eg so need compare in words instead computer play you would need say computer play second trying reference one function variables another one work if want computerwins etc variables global need initialize global scope eg right constants declared get main then function uses must say eg global computerwins indicate global local once get issues addressed work bit better still need lot cleanup keep working keep soon natural,i trying write python program i hard time getting score i written value returning function every time i run program seems skip step retrieves score unless i include else statement automatcially jump else statement i attach full code thank much help i greatful this also first time posting forum i apologize i screw something constants rock paper scissors define main function def main set control loop keepgoing y set counter zero computerwins playerwins tiescore call display message displaymessage keepgoing keepgoing y playgame prompt user keep going keepgoing input would like play y yes print the computer computerwins times print the player playerwins times print there tiescore tie scores def playgame get random input computer getrandom get players input play getplay validate input play play play play true else play false print error invalid entry play input please enter rock paper scissors play computer print tie score please try tiescore else getscorecomputer play print the computer chose computer print the player chose play define display message def displaymessage print welcome rock paper scissors game chance see print outsmart this game man vs computer print the program select random integer ask integer print rock paper scissors the program tell print game print good luck print print def getrandom import random generate random int computer randomrandint return computer def getplay prompt user enter integer play input select rock paper scissors return play def getscorecomputer play computer play score player wins print paper covers rock player wins player wins playerwins elif computer play score computer wins print scissors cut paper computer wins computer wins computerwins elif computer play score computer wins print paper covers rock computer wins computer wins computerwins elif computer play score player wins print scissors cut paper player wins player wins playerwins elif computer play score player wins print rock smashes scissors player wins player wins playerwins elif computer play score computer wins print scissors cut paper computer wins computer wins computerwins call main function main,3 your original idea work instead call functions add return values rather trying add def addfuncsfgx fx gx this f g actually lambdatypes operator calls allowing operator add return values when use operator directly operator know add two lambdatypes edit to add little reason def addfunctionsf g def getf return f def getg return g return getf getg work trying add together two function objects however example def addfunctionsf g return f will work simply return another function object called argument value statement addfuncsaddsquare,lets say two defined function objects add lambda x x square lambda x xx i want function calls adds result two functions what i thought would work def addfuncsfg fg addfuncsaddsquare which i thought would give answer but gave error typeerror unsupported operand types function function so i tried def addfunctionsf g def getf return f def getg return g return getf getg but still avail however i def addfunctionsf g return f pops seems evaluate function return but i figure get evaluate functions first operate any help would greatly appreciated edit got def addfunctionsf g return lambda x fx gx,1 def addfuncsfg return lambda x fx gx addfuncsaddsquare python support adding functions together attempts tried instead need create new function lambda calls original functions,lets say two defined function objects add lambda x x square lambda x xx i want function calls adds result two functions what i thought would work def addfuncsfg fg addfuncsaddsquare which i thought would give answer but gave error typeerror unsupported operand types function function so i tried def addfunctionsf g def getf return f def getg return g return getf getg but still avail however i def addfunctionsf g return f pops seems evaluate function return but i figure get evaluate functions first operate any help would greatly appreciated edit got def addfunctionsf g return lambda x fx gx,2 i answered question separately fun little working rock paper scissors game look this one python x probably work python might helpful somebody future searching rock paper scissors demo python x dan kamins import random rock paper scissors names rock rock paper paper scissors scissors whatbeatswhat rock scissors paper rock scissors paper winactions rock crushes paper smothers scissors cuts scoreplayer scorecomputer scoreties def main intro mainloop pass summary def intro print welcome rock paper scissors def mainloop player getplayerinput computer randomrandint checkresultplayer computer return askplayagain def checkresultplayer computer global scoreplayer scorecomputer scoreties player computer print tie computer also chose formatnamescomputer scoreties else whatbeatswhatplayer computer print your massive computer format namesplayer winactionsplayer namescomputer scoreplayer else print the computer pathetic format namescomputer winactionscomputer namesplayer scorecomputer def askplayagain rawinputenter y play return y def getplayerinput true print player rawinputenter rock paper scissors try player intplayer player return player except valueerror pass print please enter number def summary global scoreplayer scorecomputer scoreties print thanks playing print player scoreplayer print computer scorecomputer print ties scoreties name main main,i trying write python program i hard time getting score i written value returning function every time i run program seems skip step retrieves score unless i include else statement automatcially jump else statement i attach full code thank much help i greatful this also first time posting forum i apologize i screw something constants rock paper scissors define main function def main set control loop keepgoing y set counter zero computerwins playerwins tiescore call display message displaymessage keepgoing keepgoing y playgame prompt user keep going keepgoing input would like play y yes print the computer computerwins times print the player playerwins times print there tiescore tie scores def playgame get random input computer getrandom get players input play getplay validate input play play play play true else play false print error invalid entry play input please enter rock paper scissors play computer print tie score please try tiescore else getscorecomputer play print the computer chose computer print the player chose play define display message def displaymessage print welcome rock paper scissors game chance see print outsmart this game man vs computer print the program select random integer ask integer print rock paper scissors the program tell print game print good luck print print def getrandom import random generate random int computer randomrandint return computer def getplay prompt user enter integer play input select rock paper scissors return play def getscorecomputer play computer play score player wins print paper covers rock player wins player wins playerwins elif computer play score computer wins print scissors cut paper computer wins computer wins computerwins elif computer play score computer wins print paper covers rock computer wins computer wins computerwins elif computer play score player wins print scissors cut paper player wins player wins playerwins elif computer play score player wins print rock smashes scissors player wins player wins playerwins elif computer play score computer wins print scissors cut paper computer wins computer wins computerwins call main function main,2 if rd party project using setuptools distribute python setuppy develop instead install this create appropriate symlinks sitepackages dir,i often find wanting use rd party python module project i know i also need make changes rd party module i want push upstream what best practice file layoutinstallation achieve most python modules laid root dir containing setuppy compileinstall module the problem every time i make changes module source i need rerun full install step order use changes project for large modules like scipy take time alternatively i hack installed version python module i manually move changes back source version module order generate patches etc i know virtualenv pythonpath ways installing module different location so far i manually created symlinks messy,3 for input files could use fileinput module it follows common convention input files files given filename reads stdin otherwise reads files given commandline there need f file options if program always requires input file option output used specify output file name various programs optparse usrbinenv python import fileinput import sys optparse import optionparser parser optionparser parseraddoption output help specifies output file the default stdout options files parserparseargs optionsoutput optionsoutput sysstdout openoptionsoutput w line fileinputinputfiles processline argparse argparse module allows specify explicitly files arguments usrbinenv python import fileinput import sys argparse import argumentparser parser argumentparser parseraddargument files nargs help specify input files group parseraddmutuallyexclusivegroup groupaddargument output help specify output file the default stdout groupaddargument inplace action storetrue help modify files inplace args parserparseargs argsoutput argsoutput sysstdout openargsoutput w line fileinputinputargsfiles inplaceargsinplace processline note i added inplace option second example python utilargparsepy help usage utilargparsepy h output files files positional arguments files specify input files optional arguments h help show help message exit output output output specify output file the default stdout inplace modify files inplace,i got dozen programs accept input via stdin option i like implement features similar way output the optparse code looks like parseraddoption f file default help specifies input file the default stdin parseraddoption output default help specifies output file the default stdout the rest applicable code looks like optsfilename infile sysstdin else infile openoptsfilename r optsoutput outfile sysstdout else outfile openoptsoutput w this code works fine i like simplicity i able find reference anyone using default value output indicate stdout is good consistent solution i overlooking something better expected,3 this capturing groups designed compiledregex recompile value matches compiledregexmatchsampletext capturedgroup matchesgroup grab contents first group the inside old groups parentheses means group noncapturing group accessible group result i converted keep output simpler leave capturing groups prefer use matchesgroup instead since first quote would first captured group,is simple method pull content regex assume i following sample text some text some more text valuessss some more text my regex compiledregex recompile value this obviously return entire some more text valuessss however i want ssss returned since i looking i obviously define parser function i feel python provides simple pythonic way task,1 i experienced strings version i bit encoding option es would work utf text it must cast wide net looking text delimited nonprintable characters value i expect lot noise a test random executable showed es bit result times bigger es bit,i noticed gnubinutilsstrings printout utf content file possible program print utf strings arguments appropriate working python environment using subprocess would like work output gnubinutilsstrings subprocesspopen call would generate pipe,2 you need abs testvalues testvalues x x else x testvalues x x testvalues x x testvalues,i parsing xml file coordinates python write transformed output file the problem coordinates i problems parsing another system i would need instead how could i achieve thing this i far node nodes nodename nodeattrib name nodeparts nodenamesplit nodename nodeparts nodename scene fwritenodeparts position nodefind position fwrite f floatpositionattrib x fwrite f floatpositionattrib fwrite fn floatpositionattrib z,1 user kaizerse onto something far original question goes i took step terms simplicity requires single decorator class classpropertyproperty def getself cls owner return classmethodselffgetgetnone owner usage class stats currentinstance none classproperty def singletoncls clscurrentinstance none clscurrentinstance stats return clscurrentinstance as noted way creating singleton good design pattern must done metaclass factory much better way i excited prospect class property though,i want statssingletontwittercount i thought i could class stats singletonobject none property staticmethod def singleton statssingletonobject return statssingletonobject statssingletonobject stats return statssingleton but throws exception statssingletona b traceback recent call last file stdin line module typeerror property object readonly attributes assign,3 i realize old question i started working tkinter yesterday develop hebrew application python righttoleft bidi available part framework bit googling research i managed convincingly fake keybindings forcibly repositioning cursor my entry widget keeps justification left hebrew text roughly position english box approach could easily modified rightjustified box or rightjustification might make simpler nonetheless i essentially manually enforcing cursor position using callbacks character codes index constants also must account arrow keys mine behave moving direction point i always hated rtl usually reverses arrows this easily changed though prefer otherwise backspace del also cause manual repositioning of course keeping track cursor manually update tracking variable event user repositions using mouse below code exception use global intended remove mite complexity explanation here necessary bindings we going make modifications key press release completed mouse click entrywidgetbindkeypress rtlpress entrywidgetbindkeyrelease rtlrelease entrywidgetbindbuttonrelease rtlmouse next three callback functions cursor tracking relocating with following functions keep mind want cursor move right increase index response right arrow press del essentially compensating movement explicit conditions since indexing cursor position ltr holding current position append text tantamount moving right on key release arrow key invoked update tracking variable reflect new cursor position if key pressed snap cursor back prior keypress prevent moving right cause next letter appended left side previous letter def rtlreleaseevent global hebcursorpos eventkeycode eventkeycode hebcursorposeventwidgetindexinsert else eventwidgeticursorhebcursorpos printstreventkeycode strhebcursorpos on keypress must compensate natural ltr behavior backspace del def rtlpressevent global hebcursorpos in ltr text entry backspace naturally removes character left cursor eventkeycode length leneventwidgetget in rtl right edge beginning string backspace nothing if right edge string insert meaningless character deleted appears user done nothing hebcursorposlength eventwidgetinserthebcursorpos in order cause backspace delete character right rather left cursor user perspective step cursor forward one this cause backspace delete character left new cursor position character right cursor user perspective if right end line insert space delete milliseconds later we need update cursor position tracking variable character deleted back index started counting index ltr perspective eventwidgeticursorhebcursorpos else del it deletes character right cursor want delete character right eventkeycode if left edge string insert meaningless character del delete user perspective nothing hebcursorpos eventwidgetinserthebcursorpos otherwise stepping cursor one left deletes character new right deleting character user thinks left because deleting character left cursor user perspective fewer characters left cursor operation complete as cursor positioning tracked ltr index must update tracking variable else hebcursorpos now snap cursor position tracking variable either preventing drifting right due overlapping keypresses repositioning maintain correct index del eventwidgeticursorhebcursorpos simply put user repositions cursor mouse track def rtlmouseevent global hebcursorpos hebcursorposeventwidgetindexinsert hope helps since accomplished forced cursor motion slight visual cursor jitter typing text ordering appears correct cursor seems always indicate correct position user midkeypress i making claims code perfection though,is possible use tkinter render user interfaces rtl languages arabic hebrew i tried googling tkinter rtl search results disappointing the tk wiki indicates bidi support time is anyone developing tkinter applications arabic hebrew locales,2 homework hint look python source code bisect module that shows find indexes make insertions sorted list,i assignment i supposed find word line add word list then also another list corresponding list word list tell amount times word appear text i finished part however i cannot find way compare new found word word list find index insert list alphabetical order i know i supposed write function find index list insert item lists i allowed use sort operator i little trouble can anyone help writing one function using conditions operators if i clear please let know,1 djangoshortcuts import getobjector get room instance id raise page found room getobjectorroompk id add squawk manytomany relation roomsquawksaddsquawkobject httpsdocsdjangoprojectcomendevrefmodelsrelations,i like insert individual squawks room object i insert database how i i tried roomsquawksquawk object appear work class squawkmodelsmodel username modelsforeignkeyuser message modelscharfieldmaxlength time modelsdatetimefieldautonowaddtrue def unicodeself return strselfusername selfmessage class roommodelsmodel title modelscharfieldmaxlength created modelsdatetimefieldautonowaddtrue users modelsmanytomanyfielduser squawks modelsmanytomanyfieldsquawk def unicodeself return selftitle,1 the start method qthread accept arguments however inherited qthread free customize so implement want pass arguments constructor worker here code sample slightly modified show action class workerqthread def initself docreatedatatrue parentnone super etc selfdocreatedata createdata def runself selfcreatedata selfcreatedata else selfuploaddata depends,i multithreaded application written python one thread takes care gui worker thread however worker thread two main functions say two main jobs i need tell run function job exactly so i mind create run function worker thread take one parameter save self the parameter either create upload without ado somewhatcode i far guipy class guiqmainwindow def initself parentnone super etc selfworker workerworker def createself selfworkerstart def uploadself selfworkerstart workerpy class workerqthread def initself parentnone super etc def runself selfcreatedata or selfuploaddata depends so question i tell workerstart function i want perform i realize one could directly use workerrun method i told rapid gui development pyqt never call workerrun directly always use workerstart,3 that would bad use many forms i suggest using pylons wtform to cope wtform create separate class example layout handle fields form uniform standard adopted site this good make processing forms separate class redo forms need change layout base class,is using formbuild pylons pretty customized needs actually easier manually creating form html,1 alternatively req urllibrequesthttpexamplecom data contenttype applicationoctetstream urlliburlopenreq that also shows specify contenttype data,i already binary data read file most examples i see online link directly file upload whole file i looking upload binary data i already another source via http post python,2 there introduction regular expressions python httpdocspythonorghowtoregexhtmlregexhowto import pat recompiler cm print patsearch filenamec group print patsearch filenamem group,string example filenamec filenamem target find exactly c using regular expression since confusing issue i would get good tutorial regular expression someone knows ron,1 import string filenamec find refindallcm string find filternone find print find i prefer using findall i guessing may looking one example,string example filenamec filenamem target find exactly c using regular expression since confusing issue i would get good tutorial regular expression someone knows ron,1 update making regex match strictly per comments this regex work according requirements ddsdsd this matches,i tried make regex validate phone number format xxxxxxxxx xxxxxxxxx my regex dsdsds and matched way i reread syntax couple times get make right,1 this another option it looks exact formats mentioned dddddd,i tried make regex validate phone number format xxxxxxxxx xxxxxxxxx my regex dsdsds and matched way i reread syntax couple times get make right,1 remove leading second string ospathjoin cusersmarcindocumentsoneclickcos oneclickos cusersmarcindocumentsoneclickcosoneclickos this ospathjoin discards previous components meets absolute path oneclickos absolute path here excerpt doc ospathjoin join one path components intelligently if component absolute path previous components windows including previous drive letter one thrown away joining continues,consider following djangoconf import settings import os settingsvirtualenv cusersmarcindocumentsoneclickcos settingsextrabase oneclickcos ospathjoinsettingsvirtualenvsettingsextrabase oneclickcos as imagine i neither expect want concatenation cusersmarcindocumentsoneclickcos oneclickcos oneclickcos oddly enough reversing path components shows python ignoring first path component ospathjoinsettingsextrabasesettingsvirtualenv cusersmarcindocumentsoneclickcos while works something like expected ospathjoin foobar settingsvirtualenv barfoo cusersmarcindocumentsoneclickcosbarfoo i course running windows windows native python why happening i,2 that pretty much ospathjoin defined quoting docs if component absolute path previous components windows including previous drive letter one thrown away and i say usually good thing avoids creating invalid paths if want avoid behavior feed absolute paths yes starting slash qualifies absolute path a quick dirty solution removing leading slash settingsextrabaselstrip want programmatically,consider following djangoconf import settings import os settingsvirtualenv cusersmarcindocumentsoneclickcos settingsextrabase oneclickcos ospathjoinsettingsvirtualenvsettingsextrabase oneclickcos as imagine i neither expect want concatenation cusersmarcindocumentsoneclickcos oneclickcos oneclickcos oddly enough reversing path components shows python ignoring first path component ospathjoinsettingsextrabasesettingsvirtualenv cusersmarcindocumentsoneclickcos while works something like expected ospathjoin foobar settingsvirtualenv barfoo cusersmarcindocumentsoneclickcosbarfoo i course running windows windows native python why happening i,2 all nonvimscript interfaces cursed way communicate vim unless want editget contents buffer available using buffer object execute vimcommandstring python eval vimevalstring python requiring serializing arguments if want start visual mode use vimcommandnormal v vimevalfeedkeys v but want example return value caller function use import json some code puts result variable r this work r contains nonunicode strings write serializer case as far i know also fail characters string represented using surrogate pairs vimcommandlet replyjsondumpsr now caller function variable lreply defined,i attempting write python script automate vim python vim interface give enough power everything i need i want communicate vim script tty able issue visual mode instructions etc as far vim concerned script human running xterm whatever can done without building terminal emulator python,1 you declared class variable instance variable class variables shared among instances class this means update one historicaldata object update instance variables local instance class these typically initialised init special method called instance created as probably initialise datapoints like get results desire class historicaldataobject def initself selfdatapoints,in python i instantiate class twice store different variables why second object contain copy first object i know copy i change values one object change example i following class class historicaldata datapoints i instantiate class fill datapoints values hd historicaldata hddatapointschannel hddatapointschannel hddatapointschannel i instantiate class fill values hd historicaldata hddatapointschannel when i print values hddatapoints hddatapoints i get following channel channel channel channel channel channel the dictionary copy first second object value channel changed second first i thought instantiate class values defaulted defined class am i missing something,3 you look template inheritance basically allows base template header footer define instance content block you templates extend base template filling empty blocks defined base template using rendertostring proper way django,i developing website django want keep common template header footer the contents header footer vary respect user logged so way could use headerrendertoresponse headerhtml footerrendertoresponse footerhtml contentrendertoresponse contenthtml return headercontentfooter,1 harsh concatenating httpresponse objects way django i believe reasonable approach recommends using templates including inheritance please take look block include extend template tags in case way implement template inheritance looks like basehtml div header code div block content divdefault contentdiv endblock content div footer code div mytemplatehtml extend basehtml block content divmy new contentdiv endblock content,i developing website django want keep common template header footer the contents header footer vary respect user logged so way could use headerrendertoresponse headerhtml footerrendertoresponse footerhtml contentrendertoresponse contenthtml return headercontentfooter,2 you use eevin answer however situation create two handlers it much simpler class onehandler def getself first url class twohandler def postself second url handlers rurlonehandler get allowed rurltwohandler post allowed anyone posting first url getting second would get method supported error,i trying implement sort api tornado i question possible route two urls one handler separating method class handler def getself first url def postself secornd url handlers rurlhandler get allowed rurlhandler post allowed so someone trying send post first url see error message,3 from i reading ptvs wpf support use ironpython here page may helpful httpwikipythonorgmoinguiprogramming personally i use qt pyqt pyside use qtdesigner make forms,i recently installed ptvs i come c i used visual studio i though ptvs gui creation support like windows forms c i pretty disappointed i need program several windows applications i like python is plugin add functionality ptvs plan program near future to widen question does exist real windows application ide python easy gui designer like visual studio before blaming know i already tried boa dabo spe python eclipse netbeans plugins without success i want project version is something solid i find thanks,3 you add import clr clraddreference ironpythonwpf and make sure put ironpythonwpfdll ironpython install directory directory main script i still getting exception related sta threads question edit look sta error,i want compile ironpython wpf based app exe file i looked net solutions found so compiling ironpython wpf project exe i found modified pycpy file better original i pass names files project pyc command line when i run i get dll executable i also included dll files mentioned discussion like ironpythondll there one problem i following top main file code import wpf systemwindows import messagebox application window the app runs fine vs executable seems able find dll named wpf window i file called ironpythonwpfdll i included folder seem work what dll i missing or way i solve problem,2 i always thought develop good ide good forms editor willing use ironpython net,i recently installed ptvs i come c i used visual studio i though ptvs gui creation support like windows forms c i pretty disappointed i need program several windows applications i like python is plugin add functionality ptvs plan program near future to widen question does exist real windows application ide python easy gui designer like visual studio before blaming know i already tried boa dabo spe python eclipse netbeans plugins without success i want project version is something solid i find thanks,1 take look pinax httppinaxprojectcom they lot reusable apps one provide mechanism inviting friends openid based sites ie facebook,super easy django app lets people click facebook invite and import friends,1 dd always also match dd since optional maybe see matches so backtrack much constraints allow,i learning regular expression i would like check mechanisms python using i regex refindallurdd first i thought result going when i run i got numbers including decimal clear process used here understanding python starts first expression find ok greedy search much possible comma next expects optional dot ok next expects one digits but next char comma accepted python back drop fullfils first next expects optional dot next expects one digits matches that fullfils whole regex will python memorize offset start that python start using whole regex string that whole regex used thre times the first time finds the second time finds third time find,2 from documentation findall emphasis mine return nonoverlapping matches pattern string list strings it seems would describe behaviour seeing to get nonoverlapping matches start next match end previous one,i learning regular expression i would like check mechanisms python using i regex refindallurdd first i thought result going when i run i got numbers including decimal clear process used here understanding python starts first expression find ok greedy search much possible comma next expects optional dot ok next expects one digits but next char comma accepted python back drop fullfils first next expects optional dot next expects one digits matches that fullfils whole regex will python memorize offset start that python start using whole regex string that whole regex used thre times the first time finds the second time finds third time find,1 to make label update set textvariableselfglobvar selfglobvar tkstringvar the label text updated calling selfglobvarset change commandselfcalc commandselfcalc without parentheses with parentheses selfcalc called time selfbuttn defined and command gets set return value selfcalc none nothing happens button pressed command equals none without parentheses command set function object selfcalc function called correctly whenever button pressed try avoid using global variables it help shuffle selfcontained easily reusable importable import tkinter tk import sys random class shuffleobject def initselfmasternone selfmastermaster selftexttklabelmaster texttype something selfboxtkentrymaster selfbuttn tkbuttonmaster textdone width commandselfcalc selfglobvar tkstringvar selfglobvarset selfresult tklabelselfmaster textvariableselfglobvar def hideself selftextpackforget selfboxpackforget selfbuttnpackforget selfresultpackforget def showself selftextpackpadx pady selfboxfocusset selfboxpacksidetktop padx pady selfbuttnpacksidetktop padx pady selfresultpacksidetktop padx pady def calcself word selfboxget lenword randomrandrange lenword selfglobvarsetwordi word wordi wordi class mainappobject def initselfmasternone selfmastermaster appselfapptktk apptitlemkee tools appgeometry x menubartkmenuapp selfshuffleshufflemaster selfcurrentselfshuffle programmenutkmenumenubar programmenuaddcommandlabel shuffle commandselfshowshuffle menubaraddcascadelabel programs menuprogrammenu appconfigmenumenubar def showshuffleself selfcurrenthide selfcurrentselfshuffle selfshuffleshow def showbuttonsself selfcurrenthide selfcurrentselfbuttons selfbuttonsshow def main mmainapp mappmainloop name main main,i problems global variables dev mkee import tkinter tk import sys random globvar class shuffleobject def initselfmasternone selfmastermaster selftexttklabelmaster texttype something selfboxtkentrymaster selfbuttn tkbuttonmaster textdone width commandselfcalc selfresult tklabelselfmaster textglobvar def hideself selftextpackforget selfboxpackforget selfbuttnpackforget selfresultpackforget def showself selftextpackpadx pady selfboxfocusset selfboxpacksidetktop padx pady selfbuttnpacksidetktop padx pady selfresultpacksidetktop padx pady def calcself word selfboxget lenword randomrandrange lenword global globvar globvar wordi word wordi wordi class mainappobject def initselfmasternone selfmastermaster appselfapptktk apptitlemkee tools appgeometry x menubartkmenuapp selfshuffleshufflemaster selfcurrentselfshuffle programmenutkmenumenubar programmenuaddcommandlabel shuffle commandselfshowshuffle menubaraddcascadelabel programs menuprogrammenu appconfigmenumenubar def showshuffleself selfcurrenthide selfcurrentselfshuffle selfshuffleshow def showbuttonsself selfcurrenthide selfcurrentselfbuttons selfbuttonsshow def main mmainapp mappmainloop name main main i get problem i click button selfbuttn tkbuttonmaster textdone width commandselfcalc i want make selfresult tklabelselfmaster textglobvar show globvar taken calc instead shows globvar set class globvar what i wrong,2 your question transformed two questions a compare output two runs specific case b definition iteration order set maybe distinguish post b new question appropriate i answer a imho using sorted list case clean solution you decide whether care iteration order use appropriate structure either want compare two sets see equal content irrespective order then simple operator sets seems appropriate see python sets python sets or want check whether elements inserted order but seems reasonable order insertion somehow matters users library case using set type probably inappropriate begin put another way unclear mean exactly comparing output two runs want in cases i doubt sorted list appropriate,why iteration order python set contents vary run run options making consistent run run i understand iteration order python set arbitrary if i put b c set iterate may come back order what i observed order remains within run program that program iterates set twice row i get order times however i run program twice row order changes run run unfortunately breaks one automated tests simply compares output two runs program i care actual order i would like consistent run run the best solution i come copy set list apply arbitrary sort list iterate list instead set is simpler solution note i found similar questions stackoverlow none address specific issue getting results run run,1 import lxmletree et import matplotlibpyplot plt text table row xx tt row row xx tt row table def convertttext abmapfloattsplit return ab docetfromstringtext xfloatx x docxpath xtext tconverttt docxpath ttext pltplotxt pltshow the code assumes means something like minutes seconds it converts float using convertt a closing table added make xml valid,filexml contains following data structure table row xx tt row row xx tt row table i hundred xt pairs i need plot x vs i would thankful help solve problem python matplotlib,1 you implemented naive matrix multiplication algorithm scipyweave compiles fast machine code however nonobvious cpu cache efficient algorithms matrix multiplication usually split matrix blocks deal additional speed gained cpuspecific optimizations numpy default uses optimized blas library operation one installed these libraries likely fast compared anything code without amount research,i python novice trying learn bit fantastic programming language i tried using scipyweaveinline speed computation just learn bit i tried implement matrix multiplication using scipyweaveinline i included error handling trying better understand the code follows import scipyweave def cmatmulab r numpyzerosashapebshape m rshape n rshape k ashape code int im int j jn j int k kk k rij aik bkj scipyweaveinlinecode r a b m n k typeconvertersscipyweaveconvertersblitz compiler gcc return r when i compare numpydot i experience weaveinline version takes roughly x time numpydot i know numpy fast applied the difference even seen large matrices size x i checked numpydot scipyweaveinline appear use one core computing numpydot delivers gflops compared theoretical gflops laptop double precision in single precision i measure double performance expected but scipyweaveinline way behind times performance scipyweaveinline is difference expected or i wrong,3 the common way achieve kind behaviour using requests dialog easy client side javascript implementation you read official facebook docs httpdevelopersfacebookcomdocsreferencedialogsrequests if want call callback js function dialog completes handling user input record user send back via ajax app,i need create input looks uses autosuggest lookup friends list send facebook id djangopython script i completes without hitch eg httpfcllyitemsjfinmatcscreenshotatpmpng but facebook id array side is possible loop though list invite users use facebook app thanks advance,1 try keys key key key words u word word word vals wordssplit dictzipkeys vals and want retrieve keyvalue pairs string like one example joinsortedk v kv ditems,i sure extremely easy combination questions so i find right answer i unicode string uword word word it always format i want parse dictionary always keys keyword keyword keyword how i,1 inequality filters list properties really work as know inequality filters run separate less value greater value queries hood concatenate results list properties multiple values multiple hits index filter one item always match another consider keeping two lists besides sent list keep notsent list query,i little application i passing messages users my model message like class messagedbmodel dbuserproperty senttousers dblistpropertydbkey i send message users online i detect user online i send message already sent i messagesenttousersappenduser chatpresenceavailable handler to indicate message already sent user my question i filter messages already sent user according section inequality filter queries translates two queries greater lesser results combined which needless say work case list keys basically membersnotsentmessage messageallfilter senttousers availableuserfetch work is way find values listproperty i go item find messages sent or another design system like circumvents gae datastore limitation one case,1 you need call pagesource property see selenium import webdriver browser webdriverfirefox browsergetrawinputenter url htmlsource browserpagesource whatever htmlsource something else something else,how i get html source variable using selenium module python i wanted something like selenium import webdriver browser webdriverfirefox browsergetrawinputenter url whatever htmlsource do something else do something else how i i know access html source,3 as charles said control codes may included xml file however live requiring xml use they included raw characters character references eg amp write character references cdata section interpreted ampersandhash would lose cdata wrapper manually escape amp characters entityreference equivalents note anyway cdata sections absolve responsibility text escaping fail text inside included sequence since always escaping anyway makes cdata sections pretty useless time xml lenient control codes everything supports still include nul character amp in general good idea include control characters xml you could use adhoc encoding scheme fit binary base popular humanreadable alternatives might include using random characters private use area substitutes ever application handling files encoding elements eg esc color,i writing python program logs terminal interaction similar script program i like store log xml format the problem terminal interaction includes vt escape codes python complain i write data file utf encoded eg pid fd ptyfork pid osexecvpbashbashl else lots ttyrelated stuff see httpgroupsgooglecomgroupcomplangpythonmsgdebcfccc fout codecsopensessionxml encodingutf modew foutwrite xml version encodingutfn foutwritesessionn r w e selectselect fd f r ffd foutwriteentrycdata buf osreadfd foutwritebuf foutwriteentryn else foutwritesession foutclose this script works sense writes file disk resulting file proper utf causes xml parsers like etree barf escape codes one way deal filter escape codes first but possible something like escape codes maintained resulting file parsed xml tools like etree,1 use gevent eventlet get concurrent network io,i writing script python scrape pages web server put file i using mechanizebrowser module particular task however i found creating one single instance mechanizebrowser rather slow is way i could relatively painlessly use multihreadingmultiprocessing ie issue several get requests,1 sqlite rock solid choice if need keyvalue store shelve module offers easytouse dictionary like api,i developing card catalog type application python trying decide store data not web app i expect large app massive amount data one alternative pickled dictionary for example id author title id author title reality would bit complex this virtue simplicity i could search items iterating entries another alternative sqlite database this seems suited task including persistence good facilities adding editing searching main downside i familiar sql databases otoh looks like good opportunity learn would use sqlite something else any considerations making choice any suggestions learning sqlite beyond questions python database sql programming start comprehensive beginners tutorial python sqlite,1 to drill submodules use inspect pyclbr modules those support tools used pydoc help sphinx good luck tooltip maker,is hopefully easy way list python standard library modules class submodules i read question working lists available modules tweaked avoid i know include submodules like example lists module urllib without submodule classes urllibcontenttooshorterror urllibmain urllibsplituser urllibfancyurlopener urllibnoheaders urllibsplitvalue urllibmaxftpcache urllibos urllibssl urlliburlopener urllibpathnameurl urllibstring urllibaddbase urllibproxybypass urllibsys urllibaddclosehook urllibproxybypassenvironment urllibtest urllibaddinfo urllibquote urllibtest urllibaddinfourl urllibquoteplus urllibthishost urllibalwayssafe urllibreporthook urllibtime urllibbasejoin urllibsocket urllibtobytes urllibc urllibsplitattr urllibunquote urllibftpcache urllibsplithost urllibunquoteplus urllibftperrors urllibsplitnport urllibunwrap urllibftpwrapper urllibsplitpasswd urlliburlpathname urllibgetproxies urllibsplitport urlliburlcleanup urllibgetproxiesenvironment urllibsplitquery urlliburlencode urllibi urllibsplittag urlliburlopen urlliblocalhost urllibsplittype urlliburlretrieve so way,1 is better framework using wsgi look pyramid previously named pylons see mentioned it sounds like better case vs django,i crazy green wsgi google app engine gae how i set content type json this i far class instructionswebapprequesthandler def getself response responsemessage this instruction object selfresponseoutwritejsondumpsresponse application webappwsgiapplication instructions instructions debugtrue def main runwsgiappapplication name main main additionally i building restful services nothing complicated i using restlets i developing java is better framework using wsgi the reason i using wsgi used app engine tutorial thanks,1 it unclear threading involved process restarter does work true proc subprocesspopencusersboappdataroamingminecrafminecraftserverexe procwait print minecraftserver process terminated restarting suggestions start lines code works add features use threading instead thread name variable popen similarity name function subprocess add logging print statements tell script monitor process creation task manager,windows bit python i run minecraft server sometimes program stoped different reasons i would like new instance start happens the following code works notepadexe keeps spawning new minecraftservers even tho previous one didnt stop why and i i new python import queue thread subprocess time results queuequeue def processwaiterpopen description que try popenwait finally queput description popenreturncode processcount true proc subprocesspopen cusersboappdataroamingminecrafminecraftserverexe threadstartnewthreadprocesswaiter proc finished results processcount timesleep processcount description rc resultsget print job description ended rc rc processcount,2 there facility built structunpack possible define function import struct def unpackfmt astr return structunpackfmt astr optional single fmt replaced appropriate number given length astr httpstackoverflowcoma try return structunpackfmt astr except structerror flen structcalcsizefmtreplace alen lenastr idx fmtfind beforechar fmtidx n alenflenstructcalcsizebeforechar fmt joinfmtidx strn beforechar fmtidx return structunpackfmt astr printunpack b abc,in php unpack flag means repeat format end input for example prints str abc b unpackc str printrb is something like python of course i str abc print structunpackb lenstr str i wondering better way,2 originally array four arrays the following line extracts four array variables abcdxxxx if need native python objects instead numpy arrays use list comprehension objs,i x input dtype object following structure xn elements elementm elements element to mimic input numpy import xarrayarrayarrayarrayarraydtypeobject x array dtypeobject i passing x argument python c extension pyarrayobject static pyobject samppyobject self pyobject args pyarrayobject arraypp int nj pyargparsetupleargs oamppyarraytype amparray return null narraynd ifn arraydescrtypenumpyarrayobject pyerrsetstringpyexcvalueerror array must onedimensional object type return null jarraydimensions now i stuck i sure split objects please kindly anyone give pointers,1 maybe bit crude answer question i would like share i could find far this version color two subplots axes ax ax ax ax two different colors it much shorter lines i stated question it inspired joe kington answer twinx kills tick label color import matplotlibpyplot plt import numpy np generate data num x nplinspace num yellowdata greendata bluedata nprandomrandomnum greendata nplinspace yellowdatasize bluedata nplinspace yellowdatasize fig pltfigure pltsubplot upper plot ax figaddsubplot axfillbetweenx yellowdata color yellow ax axtwinx axplotx greendata green pltsetppltgca xticklabels pltsubplot lower plot ax figaddsubplot axfillbetweenx yellowdata color yellow ax axtwinx axplotx bluedata blue start coloring ax color zipax ax ax ax green green blue blue ticks axxaxisgetticklines axyaxisgetticklines tickssetcolorcolor pos top bottom right left axspinespossetedgecolorcolor end coloring pltshow i marked accepted since compact solution i could find far still i open maybe elegant ways solve,this kind followup question post coloring axes ticks labels discussed i hope alright open new extended question changing color complete frame ticks axes around doubleplot via addsubplot axes ax ax results lot code this snippet changes color frame upper plot axspines bottom setcolor green axspines top setcolor green axspines left setcolor green axspines right setcolor green axxaxisgetticklines tsetcolor green axyaxisgetticklines tsetcolor green axxaxisgetticklines tsetcolor green axyaxisgetticklines tsetcolor green so changing frame color two plots two yaxes i would need lines code this looks like other methods i dug far matplotlibrc discussed changes globally locally i want plots different colors please discussions many colors plots matplotlibrc axes edgecolor green dig spines axis change also discussed really elegant i think child axgetchildren isinstancechild matplotlibspinesspine childsetcolor dddddd is elegant way condensing block something pythonic i using python matplotlib ubuntu,2 there nothing wrong current approach timediff written future accesses reads it effect module wide constant you run problems shared global state multiple threads accessing object least one threads writing that happening nothing concerned,i trying increment timestamps form hhmmss text file number seconds specified commandline parameter program here simplified version effort far import datetime import datetime timedelta timediff timedeltaseconds def replacetimematchobj matchobjgroup none return datetimestrptimematchobjgroup hms timediffstrftimehms print resub dddddd replacetime this works fine result running i want however i heard i use global variables less possible so i wondering simple way pass timediff argument replacetime instead using global variable i tried obvious failed def replacetimematchobj timediff matchobjgroup none return datetimestrptimematchobjgroup hms timediffstrftimehms timediff timedeltaseconds print resub dddddd replacetimematchobj timediff error nameerror name matchobj defined i pass matchobj directly i looked standard page standard howto find information i need how i avoid using global variable can i somehow pass extra argument replacetime function thanks advance,1 you wrap function closure like def incrementbytimediff def replacetimematchobj matchobjgroup none return datetimestrptimematchobjgroup hms timediffstrftimehms return replacetime timediff timedeltaseconds print resub dddddd incrementbytimediff or use partial stdlib like functools import partial def replacetimetimediff matchobj matchobjgroup none return datetimestrptimematchobjgroup hms timediffstrftimehms timediff timedeltaseconds print resub dddddd partialreplacetime timediff,i trying increment timestamps form hhmmss text file number seconds specified commandline parameter program here simplified version effort far import datetime import datetime timedelta timediff timedeltaseconds def replacetimematchobj matchobjgroup none return datetimestrptimematchobjgroup hms timediffstrftimehms print resub dddddd replacetime this works fine result running i want however i heard i use global variables less possible so i wondering simple way pass timediff argument replacetime instead using global variable i tried obvious failed def replacetimematchobj timediff matchobjgroup none return datetimestrptimematchobjgroup hms timediffstrftimehms timediff timedeltaseconds print resub dddddd replacetimematchobj timediff error nameerror name matchobj defined i pass matchobj directly i looked standard page standard howto find information i need how i avoid using global variable can i somehow pass extra argument replacetime function thanks advance,3 you use base encoding instead quoted printable use babase abbase quoted printable much bigger binary data like pictures in encoding binary non alphanumeric character code changed hex it used texts consist mainly alphanumeric like email subjects base much better mainly binary data it takes bites first byte last bits st byte bites nd byte etc it recognized padding end encoded text sometimes character used as example i took jpeg bytes in qp b base bytes size qp dependent data type text letters change size base origsize,i want convert binary file jpg mp etc websafe text back binary data i researched modules i think i really close i keep getting data corruption after looking documentation binascii i came binascii import rawbytes open testjpg rb read text baqprawbytesquotetabstrueheaderfalse bytesback abqptextheaderfalse f open convertedjpg wb fwritebytesback fclose when i try open convertedjpg i get data corruption i also tried using babase long blocks binary data i took block converted string concatenated together converted back abbase got corruption can anyone help i super knowledgeable intricacies bytes file formats i using python windows makes difference rn stuff,1 checkfornewfiles return statement therefore implicitely returns none therefore newfilescheckfornewfilesrootdir sets newfiles none cannot iterate none return read files checkfornewfiles def checkfornewfilespathrootdir newfiles oslistdirpath file newfiles print new file found file return newfiles,just wrote first python program i get zip files attachment mail saved local folder the program checks new file one extracts zip file based filename extracts different folder when run code get following error traceback recent call last file czipzipautopy line file newfiles typeerror nonetype object iterable can anyone please tell going wrong thanks lot time navin here code import zipfile import os rootdir czipzipped destinationpath czipextracted destinationpath czipextracted def checkfornewfilespathrootdir newfiles file oslistdirpath print new file found file def processfilefile sourcezip zipfilezipfilefile r filename sourcezipnamelist filenamestartswithxx filenameendswithcsv sourcezipextractfilename destinationpath elif filenamestartswithyy filenameendswithcsv sourcezipextractfilename destinationpath sourcezipclose namemain true newfilescheckfornewfilesrootdir file newfiles fails print unzipping files file processfilerootdirfile,3 your documentation reference python there good reason using python you using what exactly using suggestion change bytes rawbytes avoid confusion bytes builtin check rawbytes bytesback test script test work quotedprintable inefficient binary data use base instead update base encoding produces output bytes every input bytes your base code work byte chunks integral multiple chunk padded multiple then join chunks attempt decode guaranteed work your chunking loop would much better written outputstring join babaserawbytesii xrange xrangelenrawbytes in case chunking rather slow pointless babaserawbytes,i want convert binary file jpg mp etc websafe text back binary data i researched modules i think i really close i keep getting data corruption after looking documentation binascii i came binascii import rawbytes open testjpg rb read text baqprawbytesquotetabstrueheaderfalse bytesback abqptextheaderfalse f open convertedjpg wb fwritebytesback fclose when i try open convertedjpg i get data corruption i also tried using babase long blocks binary data i took block converted string concatenated together converted back abbase got corruption can anyone help i super knowledgeable intricacies bytes file formats i using python windows makes difference rn stuff,1 here answer next questions true code loop forever function checkfornewfiles check new files checks files you need either move incoming file archive directory processed use kind timestamp mechanism,just wrote first python program i get zip files attachment mail saved local folder the program checks new file one extracts zip file based filename extracts different folder when run code get following error traceback recent call last file czipzipautopy line file newfiles typeerror nonetype object iterable can anyone please tell going wrong thanks lot time navin here code import zipfile import os rootdir czipzipped destinationpath czipextracted destinationpath czipextracted def checkfornewfilespathrootdir newfiles file oslistdirpath print new file found file def processfilefile sourcezip zipfilezipfilefile r filename sourcezipnamelist filenamestartswithxx filenameendswithcsv sourcezipextractfilename destinationpath elif filenamestartswithyy filenameendswithcsv sourcezipextractfilename destinationpath sourcezipclose namemain true newfilescheckfornewfilesrootdir file newfiles fails print unzipping files file processfilerootdirfile,1 expression z always yields expression z always yields z it kind dsl making queries containers simple boolean expression find called result if want say z string need varfind varfind z and second one z string varfind varfind z,imagine i type following code interpreter var zuuzuu suppose type varfind interpreter returns understand substring found please help understand varfind z case returns varfind z case returns according logic head interpreter return case substrings and z not located string while case returned since z substring thanks,3 this find method fact support supports querying string so really going well turns operators performed strings z z z so basically searching z normal,imagine i type following code interpreter var zuuzuu suppose type varfind interpreter returns understand substring found please help understand varfind z case returns varfind z case returns according logic head interpreter return case substrings and z not located string while case returned since z substring thanks,1 oursql compatible python may bind sql alchemy it written python neither mypysql,i trying find mysql driver written python i may bind sql alchemy so compatiable dbapi the driver connect mysql db one but i cannot bind sql alchemy so drivers i use,1 if want hide private methods private variables pass option noprivate epydoc note epydoc method variable private name starts underscore name end underscore include name special dictionary alternatively use undocumented tag force epydoc completely ignore certain methods variables for instance i assume restructured text kind formatting class myclass some neat description undocumented x def yself pass def xself pass def zself pass result documentation contain unless used noprivate option z there nothing x even private whether private methods visible final documentation matter taste to documentation read people interest internal implementation private methods best hidden completely,i methods class meant used methods class i prefixed names can i hide functions epydoc is good idea should i use double underscore to honest i get difference reading places should naming convention used moduleclass instance functions or also variables,2 if using python python x use dictionary comprehension this equivalent eloka answer used list comprehension produces slightly readable code namemap oldcol newcol oldcol newcol oldcol newcol row rows each row dict form oldcol oldcol row namemapname val name val rowiteritems,i working program among things reads csv file gets stored array dicts form coldataacoldataacoldatabcoldatab for row part processing i need remap keys user entered values provided another dict used parameters api call the mapping array form badnamegoodname badnamegoodname so i like get badnamedata badnamedata goodnamedata goodnamedata i like use something like zip although zip yields badnamebadname seems like obvious solution alluding edit if data mapping b dictzipbaitervalues i get close work cases fields known order i think,2 func defined apy import oldobj aobj aobj mockobj afunc aobj oldobj,consider i following code python module apy def func obj obj some code uses obj is way monkey patch obj without making function argument reason in context code argument however context testing system simulations using code patch reasonable also various scenarios i may need patch different local objects placing arguments would tedious,1 if sure data correct need error handling job lines open testtxt r readlines print maxlenlinesi linesi xrange lenlines strip,i file follows format line string line line another string line short line i trying write python code get line x label string longest string length can help fix code please here i far f open testtxt r print f readnull topreadlinelength topreadlinenull line f checkifreadlinefind line checkifread print read label found means read line currentreadline else we sequence line currentread currentlengthlenline print currentlength print topreadlinelength inttopreadlinelength intcurrentlength print topreadline topreadlinecurrentreadnow topreadline label line string topreadlinelengthintcurrentlength print topreadline go next line print done print longest line print topreadline,1 if mean importing name simply leave numpy import cos arccos sin arcsin tan arctan beyond use globals get symbol table current module meglobals trigfunctions cos arccos sin arcsin tan arctan method trigfunctions memethod numpydictmethod you also use sysmodulesname reference current module,rather defining numpy import cos cos numpy import arccos arccos i something like trigfunctions cos arccos sin arcsin tan arctan method trigfunctions setattrheremethodgetattrnumpymethod where here either global space possibly local function environment this would make easier define general functions based cos arccos without specifying namespace loading appropriate function desired module eg math numpy available i realize lead errors applied generally small instances would useful,3 it sounds like want positional argument instead mutually exclusive options you use choices restrict possible acceptable options parser argumentparser parseraddargument action choices start stop restart this produces usage line looks like usage foopy h startstoprestart,python argparse accepts optional arguments prefixed mutually exclusive groups parser argparseargumentparserprog mydaemon action parseraddmutuallyexclusivegrouprequiredtrue actionaddargument start action storetrue help starts progs daemon actionaddargument stop action storetrue help stops progs daemon actionaddargument restart action storetrue help restarts progs daemon mydaemon h usage mydaemon h start stop restart optional arguments h help show help message exit start starts mydaemon daemon stop stops mydaemon daemon restart restarts mydaemon daemon is way make argparse arguments behaves like traditional unix daemon control start stop restart start stop restart,3 the memory belonging numpy array must contiguous if allocated arrays separately randomly scattered memory way represent view numpy array if know beforehand many arrays need instead start one big array allocate beforehand small arrays view big array eg obtained slicing,in numpy i concatenate two arrays endtoend npappend npconcatenate x nparray y nparray z npappendx y axis z array but make copies input arrays z z array x array is way concatenate two arrays view ie without copying would require npndarray subclass,3 your code looks quite complicated try usrbinenv python binascii import rawbytes open jpg rb read strone babaserawbytes strlist babaserawbytessplitn bytesbackall abbase joinstrlist print bytesbackall rawbytes true bytesbackall abbasestrone print bytesbackall rawbytes true lines tagged represent alternatives seems straightforward make one string process convert back,i want convert binary file jpg mp etc websafe text back binary data i researched modules i think i really close i keep getting data corruption after looking documentation binascii i came binascii import rawbytes open testjpg rb read text baqprawbytesquotetabstrueheaderfalse bytesback abqptextheaderfalse f open convertedjpg wb fwritebytesback fclose when i try open convertedjpg i get data corruption i also tried using babase long blocks binary data i took block converted string concatenated together converted back abbase got corruption can anyone help i super knowledgeable intricacies bytes file formats i using python windows makes difference rn stuff,1 depending size file possibly something like files file file myvar tm machinelist myvar myvar subprocesscheckoutputssh user tm bincat files file file etc space delimited assuming unix boxes bincat one shot machine this assuming simply loading entire content one variable variations ssh simpler diagnose at least thought update use something like myvar myvarpopenssh user tm stdoutpipecommunicate hope helps,python x cannot install nonstock modules question assuming use subprocesspopen say machines files needed read variable would prefer scp machine file scp commands total reading file scp variable discarding file or ssh machine file reading file memory ssh commands total unless way grab desired files one shot per machine files named yyyymmddhhblah range would given reading memory i cannot think,1 use font module render fonts screen from userguide white message message font pygamefontfontnone text fontrendermessage white screenblittext xpositionyposition,so far snake game score printed python shell how printed games window instead so game score window thanks eric running screenfill wormmove wormdraw fooddraw wormcrashed exit elif wormx wormx w running false elif wormy wormy h running false elif wormposition foodposition score wormeat print score score food foodscreen elif foodcheckwormx wormy score wormeat print score score food foodscreen elif running false exit event pygameeventget eventtype pygamequit running false elif eventtype pygamekeydown wormeventevent pygamedisplayflip clocktick edit running screenfill wormmove wormdraw fooddraw pygamefontinit pygamefontgetfonts wormcrashed exit elif wormx wormx w running false elif wormy wormy h running false elif foodcheckwormx wormy score wormeat food foodscreen message score score font pygamefontfontnone text fontrendermessage white screenblittext elif running false exit event pygameeventget eventtype pygamequit running false elif eventtype pygamekeydown wormeventevent why isnt score apearing im getting errors,1 the brute force way compare requestpath variable static view root la requestpathstartswith static the method i like best use apps add property request object called db lazily evaluated upon access so may add request anything accessed import types def getdbconnectionrequest hasattrrequest db requestdb myconnecttodb requestaddfinishedcallbackclosedbconnection return requestdb def newrequestsubscriberevent request eventrequest requestdb typesmethodtypegetdbconnection request later code access requestdb get connection unfortunately possible add property object runtime afaik set requestdb gives want you get behavior without using subscriber cookbook entry subclass request add lazy property via pyramid reify decorator,i newrequest event handler subscriber pyramid looks like subscribernewrequest def newrequestsubscriberevent request eventrequest print opening db conn open db requestdb myconnecttodb requestaddfinishedcallbackclosedbconnection however i observed connection db opened even request goes static asset obviously unnecessary is way newrequest handler check request bound static asset i tried comparing viewname static view name apparently viewname attribute available early stage processing request if anyone interesting ideas please let know,2 modwsgi keeps loaded python process memory speed requests that absolutely normal,it seems logical processes die memory cleared python scripts run http response sent however it seems i four processes running one using mb memory it seems like way much i is garbage collector settings i need configure something,1 you need parse settings ini file pylons used automatically hardcoding load testini the two options load ini settings via settings pastedeployappconfig testini loading actual wsgi app like wanted use via webtest app pyramidpastergetapp testini would parse ini file return actual wsgi app unfortunately route give access ini file directly automatically passes settings app startup function mainglobalconf settings you may also find pyramid docs functional tests useful,i running unit tests using nose i ini files productionini developmentini localini finally i testini file looks like appmain use configlocalini add additional test specific configuration options necessary sqlalchemyurl sqliteherestestsdb in test class i want setup database i would app server code something like engine enginefromconfigsettings initializesqlengine dbfixture sqlalchemyfixture envmodel engineengine stylenameddatastyle how nose pass settings test code i reading following link guidance i able connect dots httpfarmdevcomprojectsfixtureusingfixturewithpylonshtml thanks much,3 not sure fits use pgu fit pygame lets use render loop tie,i want create d game python heavy user interface windows buttons text input etc so far i using pygame simple games the game d mud standard rendering loop draw stuff screen i need user interface interact game entities like sales blacksmith etc i looking something like mix pygame wxpythonpyqtpygtk which libraries i use,1 it possible inherit ini files inheritance works sectionbysection basis so explicitly tell testini inherit servermain section the docs via pastedeploy package although entirely obvious i never actually seen inheritance chain server section may possible usually see done app sections i surprised duplicate section files as side note logging configuration ini file inheritable actually controlled pastedeploy duplicate file,is setup like possible productionini file appmain use eggmyproject various settings servermain developmentini file appmain use configproductioninimain override production settings then i try starting development server get no section main prefixed server found config developmentini i like chain config files together like productionini developmentini localini testini it seems like possible i gotten magic right yet,2 your code syntactically invalid current stage digit count else count missing colons digit count else count pass better skip whole else tree apart works although catch errors occur first second input say you yet solved subassignment afterwards program multiply number digit the python tutorial helpful finding multiply numbers,this currently i i stuck find many times digit number using loop if anyone basic ideas i new python i knowledgeable language assignment start print instructions print this program take number digit enter it find number times digit number afterwards program multiply number digit get user number number rawinputenter number use loop make sure number valid number print you entered invalid number number rawinputenter another number get digit digit rawinputenter digit use loop make sure digit valid intdigit print you entered invalid digit digit rawinputenter digit set count count show user number digit print your number number and digit digit use loop determine many times digit number number digit count else count print count,1 as i wrote comment already function recursive one recursion means function calls complete purpose this call indirect meaning function uses helper function call first function but code cover cases a recursive function always certain architecture first thing called test primitive case one primitive case among options reached returns if compute whatever needed pass results untill primitive case reached nested function calls finish one one wellknown usage recursion quicksort algorithm def quicksortalist lenalist return alist primitive case list size one ordered pivotelement alistpop compute lists next recursive call left element element alist element pivotelementleft smaller pivotelemet right element element alist element pivotelementleft greater pivotelemet call function recursively return quicksortleft pivotelement quicksortright so stop must return primitive case this vital recursion you cannot break somehow,i trying halt loop values xy z returned value keep increasing simply halts elif condition first def maxpalindromethelist students need put logic maxcomplist thelist maxcomplistreverse control lenthelist exit maxpalindrome true rangecontrol maxcomplist thelist x lenthelist return x break elif maxcomplisticontrol thelisticontrol successlist thelisticontrol z w lenthelist z return z w how i accomplish,1 you keep user inputs strings iterate characters string like number digit you might want consider putting method instead inline count number digit count print matched,this currently i i stuck find many times digit number using loop if anyone basic ideas i new python i knowledgeable language assignment start print instructions print this program take number digit enter it find number times digit number afterwards program multiply number digit get user number number rawinputenter number use loop make sure number valid number print you entered invalid number number rawinputenter another number get digit digit rawinputenter digit use loop make sure digit valid intdigit print you entered invalid digit digit rawinputenter digit set count count show user number digit print your number number and digit digit use loop determine many times digit number number digit count else count print count,1 you could use localsget p i strongly recommend structure code need refer variables might might the instance i use pattern javascript fake namespaces global objects i want depend script files included right order since python proper module system i imagine would necessary,in javascript i assign value like var p obviously p defined resort is elegant version operation python try except combo try p except,1 the easiest way communicate threads queue module have gui thread put okay value worker blocking get receive okay signal,i multithreaded application written python one thread takes care gui worker thread at one point however worker thread midst processing data emits signal qstring connects displayimage function gui thread the displayimage function requires user input line text my question i make worker thread wait data processing displayimage function returns value user presses ok button guipy class guiqmainwindow def initself parentnone super etc selfworker workerworker def displayimageself image wait user input workerpy class workerqthread def initself parentnone super etc def runself selfemitsignalimagefoundqstring image wait selfinputtedusertext inputtedusertext i need figure,1 people sometime use python oroperator purpose def fpnone p the relies unique python aspect oroperator return value makes expression true rather returning true false another option affords flexibility use conditional expression def fpnone p p none else if want check see variable already defined tryexcept cleanest approach try p except nameerror pass that said would atypical python may hint something wrong program design it better simply initialize variable placeholder value none in regard python style somewhat different javascript,in javascript i assign value like var p obviously p defined resort is elegant version operation python try except combo try p except,2 you could ensure p initialized sentinel value usually none test presence p none p p none else this necessary python way define variables without assigning first in javascript variable declared eg var p assigned evaluate special value undefined so javascript sentinel value implicitly created whilst python must always explicitly created,in javascript i assign value like var p obviously p defined resort is elegant version operation python try except combo try p except,1 as inerdia ignacio vazquezabrams pointed variables always initialized access if variable always get value initialize none use following code similar javascript p note use valid values p always evaluate true boolean context according python boolean rules,in javascript i assign value like var p obviously p defined resort is elegant version operation python try except combo try p except,1 count,this currently i i stuck find many times digit number using loop if anyone basic ideas i new python i knowledgeable language assignment start print instructions print this program take number digit enter it find number times digit number afterwards program multiply number digit get user number number rawinputenter number use loop make sure number valid number print you entered invalid number number rawinputenter another number get digit digit rawinputenter digit use loop make sure digit valid intdigit print you entered invalid digit digit rawinputenter digit set count count show user number digit print your number number and digit digit use loop determine many times digit number number digit count else count print count,2 use list comprehension get new elements optionally sliceassign replace existing elements list newalist listreversedx x alist alist listreversedx x alist,i trouble wrapping head around dealing lists within lists python i rather new programming now would i access nested list position manipulate position nested list values example change order maintaining position nested list main list for example i wanted go alist newalist i get access list i experiencing block i would change position values nested lists thanks help,3 blist l alist lreverse blistappendl,i trouble wrapping head around dealing lists within lists python i rather new programming now would i access nested list position manipulate position nested list values example change order maintaining position nested list main list for example i wanted go alist newalist i get access list i experiencing block i would change position values nested lists thanks help,1 the question initial assertions misleading assuming windowp property p variable effect result referenceerror javascript runtime var p python works manner example use tryexcept superfluous javascript slightly different var hoisted top function also means var work javascript equivalent var however general variable must existence used thus python pointed equivalent javascript differences var lack thereof aside please note python slightly different notion falsey values javascript happy coding,in javascript i assign value like var p obviously p defined resort is elegant version operation python try except combo try p except,1 import os import tempfile by default mkstemp creates file name begins tmp lowercase tmphandle tmppath tempfilemkstemp ospathexiststmppathupper case insensitive else case sensitive,is simple way check python file system case insensitive i thinking particular file systems like hfs osx ntfs windows access file foo foo foo even though file case preserved,3 whoops first last return ispalindromethesublisttest else return false,whenever i try run code def ispalindrome thesublist thesublisttest thesublist lenthesublisttest return true elif lenthesublisttest x thesublisttest thesublisttest x return true else return falsefirst thesublisttestpop elif lenthesublisttest first thesublisttestpop last thesublisttestpop first last ispalindromethesublisttest else return false candidateps range range range range range range range range p candidateps print p ispalindrome p runs correctly first two values p ouputs none following three values any help greatly appreciated thanks advance,2 you forgot return change lines first last ispalindromethesublisttest first last return ispalindromethesublisttest code work expected,whenever i try run code def ispalindrome thesublist thesublisttest thesublist lenthesublisttest return true elif lenthesublisttest x thesublisttest thesublisttest x return true else return falsefirst thesublisttestpop elif lenthesublisttest first thesublisttestpop last thesublisttestpop first last ispalindromethesublisttest else return false candidateps range range range range range range range range p candidateps print p ispalindrome p runs correctly first two values p ouputs none following three values any help greatly appreciated thanks advance,1 the cleanest solution add django extensions virttsmetscalvindocumentspriverugbyclubproposalkitu yolk l django active pygments active python active development usrlibpythonlibdynload djangoextensions active pip active setuptools c active wsgiref active development usrlibpython yolk active the list possible commands extended among things runscript command,i like run script populate database i like access django database api the problem i know i would need import gain access how achieved,1 the reason reverse bucketlist method actually returns generator rather actual list this much efficient also allows boto handle paging results behind scenes if really want reverse could collect elements list reverse objs obj obj selfbucketlistprefix objsreverse lot objects bucket inefficient,does anyone know get reversed bucket list bucketlist selfbucketlistprefix bucketlistreverse work thanks ron,2 slice using newlist oldlisti,so i want export data one list another i mess still untouched copy original data i know list splicing i export data first list index value determined function previously defined how would i choose data thanks advance,2 httpcodegooglecomplibrpg maybe need,i want create d game python heavy user interface windows buttons text input etc so far i using pygame simple games the game d mud standard rendering loop draw stuff screen i need user interface interact game entities like sales blacksmith etc i looking something like mix pygame wxpythonpyqtpygtk which libraries i use,1 i changed create methods missing parenthesis without new instances object created also i changed classdict call create methods instead i defer instantiation moment classdict accessed classdictindex the modified code looks like class foo id def initself selfattr class bar id def initself selfattr def createfoo return foo def createbar return bar classdict createfoocreatebar classindex data read file classlist output list containing newly instanciated bar foo index classindex c classdictindex classlistappendc classe classlist print strclasseattr print n classlistattr classe classlist print strclasseattr,i trying store file encode id class read file call class files data stored like idclassarguments read file look list file right class invoque pass arguments something like class foo id def initself selfattr def strself return strselfattr class bar id def initself selfattr def strself return strselfattr def createfoo return foo def createbar return bar classdict createfoocreatebar classindex data read file classlist output list containing newly instanciated bar foo index classindex c classdictindex classlistappendc code append classlist example foo one class i modify attribute modified whole list example classe classlist print classe print n classlistattr classe classlist print classe output,1 tkinter one choice it canvas widget easy use draw objects lines circles etc well embed images tiles example and course comes standard collection widgets buttons comboboxes listboxes menus etc either embedded canvas used traditional sense,i want create d game python heavy user interface windows buttons text input etc so far i using pygame simple games the game d mud standard rendering loop draw stuff screen i need user interface interact game entities like sales blacksmith etc i looking something like mix pygame wxpythonpyqtpygtk which libraries i use,1 you could reverse item like alist alistreverse alistreverse alistreverse alist but general better use loop since alist could lots items alist item alist itemreverse alist both methods modify alist place unmodified version destroyed heres could create new list leave alist unchanged alist newalist item alist newalistappendlistreverseditem newalist another way reverse list use extended slice trick the means step list steps ie backwards newalist item alist newalistappenditem newalist instead explicitly making empty list appending usual write loop like list comprehension newalist item item alist newalist,i trouble wrapping head around dealing lists within lists python i rather new programming now would i access nested list position manipulate position nested list values example change order maintaining position nested list main list for example i wanted go alist newalist i get access list i experiencing block i would change position values nested lists thanks help,2 set indexfalse properties need indexed ie properties use query this cuts number index writes takes save entity see httpcodegooglecomappenginedocspythondatastorequerieshtmlintroductiontoindexes explanation,version class actionlogdbmodel action dbstringproperty timeslice dbintegerproperty tracecode dbstringproperty profile log belong who facebookid dbstringproperty user facebook id ip dbstringproperty user ip address when time dbdatetimepropertyautonowaddtrue time event what url dbstringproperty imgurl secret dbstringproperty secret imgurl instance tag dbstringproperty tag referurl dbstringproperty tag link where weburl dbstringproperty user refer url domain dbstringproperty refer url domain bsp dbstringproperty refer url bsp execute log actionlogactionaction tracecodetracecode facebookidfacebookid ipip timeslicetimeslice urlurl secretsecret tagtag referurlreferurl weburlweburl domaindomain bspbsp dbputlog version class actionlogdbmodel tracecode dbstringproperty url dbstringproperty secret dbstringproperty use dict like text property store implicit properties desp mydictproperty time dbdatetimepropertyautonowaddtrue time event execute log actionlog secret secret url url tracecode tracecode desp action action facebookid facebookid ip ip tag tag referurl referurl weburl weburl dbputlog these two versions code basically task however version code use ms perform simple put operation yellow red light cpu time google app engine in contract version code use ms both test hrd datastore on ms datastore version code use ms version code use ms i image version slower compare version since use key index however hard believe difference huge it also surprising google app engine cannot handle easy task does mean cannot expect gae perform insert data properties i misunderstand anything thx,1 too much work def getsumoflastdigitsnumlist return sumx x numlist,i want function take last digit number list sum together so forexample function would return def getsumoflastdigitsnumlist x sumintnum num numlist print x getsumoflastdigits here receive instead expected def getsumoflastdigitsnumlist x sumintnum num numlist print x getsumoflastdigits,2 x sumnum num numlist,i want function take last digit number list sum together so forexample function would return def getsumoflastdigitsnumlist x sumintnum num numlist print x getsumoflastdigits here receive instead expected def getsumoflastdigitsnumlist x sumintnum num numlist print x getsumoflastdigits,1 you index number number sequence digits internally represented base you obtain last digit number using mathematical manipulation instead take remainder dividing we operator also don print value function return let calling code decide value calculation output separate tasks kept separate avoid indicating data types variable names yes even python it good idea build assumptions actually necessary you could use kind sequence example the simplest way indicate one number use plural numbers that also means use full word people think num short there need assign result expression temporary variable going use right away the name x tell us anything cut get considered ugly prefix function names pythonistas it already obvious function calculates returns value use nountype names functions verbtype names functions primarily intended manipulate existing data thus def sumoflastdigitsnumbers return sumnumber number numbers,i want function take last digit number list sum together so forexample function would return def getsumoflastdigitsnumlist x sumintnum num numlist print x getsumoflastdigits here receive instead expected def getsumoflastdigitsnumlist x sumintnum num numlist print x getsumoflastdigits,1 you filling surface given color drawing shape color of course visible way get solidcoloured surface rectangular,i know correct website guys helpful i wanted get advice problem i python pygame i making simple game recently begun learning python loving far moment i sprite constructor i using this constructor manage objects i want draw either ellipse rectangle based argument passed my code class blockpygamespritesprite variables speed indestructible true constructor def initself color width height name shapetype pygamespritespriteinitself selfimage pygamesurfacewidthheight selfimagefillcolor choose draw shapetype ellipse pygamedrawellipseselfimagecolorwidthheight elif shapetype rect pygamedrawrectselfimagecolorwidthheight elif shapetype printshape type name defined pygamedrawrectselfimagecolorwidthheight init rect class sprites selfrect selfimagegetrect the coding i using drawing square add white star list rangerandomrandrange whitestar blockwhite white star rect whitestarrectx randomrandrangesize whitestarrecty randomrandrangesize whitestarspeed blocklistaddwhitestar allspriteslistaddwhitestar this works wonderfully it draws perfect little white square but work create planet planet blockgreen planet ellipse planetrectx randomrandrangesize planetrecty planetspeed blocklistaddplanet allspriteslistaddplanet the planet spawns correctly square why happening and i fix should i use bitmap correct or coding wrong just clarify i know fact selfrect selfimagegetrect work draw ellipse coding works not code i using works proves selfrect selfimagegetrect cause call parent class sprite constructor pygamespritespriteinitself create image block fill color this could also image loaded disk selfimage pygamesurfacewidth height selfimagefillwhite selfimagesetcolorkeywhite pygamedrawellipseselfimagecolorwidthheight fetch rectangle object dimensions image image update position object setting values rectx recty selfrect selfimagegetrect thankyou help,1 first line the correct translation length randomrandint int length rand now let dissect dense second line piece piece xxss x means substitute format string given arguments like sprintf in case means concatenating bytes x x two strings x follow x packb length uses structpack in case means convert integer value length one byte representing value it almost equivalent using chr joinz means take element list z must string concatenate nothing for example joinabc abc z randomchoicestringprintable rangelength returns generator object you think list whose elements computed demand in case generates length elements element one character randomly chosen string stringprintable all second line yields string starts wxth x x followed charlength followed length random characters uniformly chosen set chars stringprintable,i trying convert python code c but life i figure line the rest program seems simple selfpayload xxss packb length joinrandomchoicestringprintable rangelength if anybody could give rough idea much appreciated,3 in block constructor call selfimagefillcolor that fill sprite entire image color get rectangle the example code calls selfimagesetcolorkeywhite fill gets drawn background fill transparent that probably fastest solution,i know correct website guys helpful i wanted get advice problem i python pygame i making simple game recently begun learning python loving far moment i sprite constructor i using this constructor manage objects i want draw either ellipse rectangle based argument passed my code class blockpygamespritesprite variables speed indestructible true constructor def initself color width height name shapetype pygamespritespriteinitself selfimage pygamesurfacewidthheight selfimagefillcolor choose draw shapetype ellipse pygamedrawellipseselfimagecolorwidthheight elif shapetype rect pygamedrawrectselfimagecolorwidthheight elif shapetype printshape type name defined pygamedrawrectselfimagecolorwidthheight init rect class sprites selfrect selfimagegetrect the coding i using drawing square add white star list rangerandomrandrange whitestar blockwhite white star rect whitestarrectx randomrandrangesize whitestarrecty randomrandrangesize whitestarspeed blocklistaddwhitestar allspriteslistaddwhitestar this works wonderfully it draws perfect little white square but work create planet planet blockgreen planet ellipse planetrectx randomrandrangesize planetrecty planetspeed blocklistaddplanet allspriteslistaddplanet the planet spawns correctly square why happening and i fix should i use bitmap correct or coding wrong just clarify i know fact selfrect selfimagegetrect work draw ellipse coding works not code i using works proves selfrect selfimagegetrect cause call parent class sprite constructor pygamespritespriteinitself create image block fill color this could also image loaded disk selfimage pygamesurfacewidth height selfimagefillwhite selfimagesetcolorkeywhite pygamedrawellipseselfimagecolorwidthheight fetch rectangle object dimensions image image update position object setting values rectx recty selfrect selfimagegetrect thankyou help,1 it background black transparent if set image background white get visible edges either transparent solid white works simple tests try values transblack shows example visible edges solidblack shows shape black background transwhite solidwhite im imagenewrgba solidwhite,imagine simple script pil import image aggdraw import draw brush im imagenewrgba draw drawim brush brushyellow drawpolygon none brush drawflush imsavepng and result sorry big size clearly and problem can see nonyellow nonwhite edges this alphachannel something when i trying pil draw object looks clearly good antialiased but aggdraw draw object looks antialiased ugly dirty edges i need exactly polygons nonstandard side angles simple box i want please help good optimistic answer solve problem,1 from description i deduced teacher wants implement selection sort algorithm you may want look in algorithm swap least number current position initially current position beginning list shifts swap values,my teacher wants algorithm sort ascending order using minimum number list putting beginning i read file numbers far i def findminls n range n n length lsilsm return def sortlistlsn n return findminlsn lsinsertm lsremovem sortlistls n i tried several techniques get work i trying put minimum number beginning minus list function would count length i know i sorting maximum i would put n i put minimum,1 class bikeobject def initself color selfbikecolor color mybike bikeblue is enough in python init really constructor initializer it takes already constructed object initializes example setting bikecolor attribute python also something closer constructor semantically new method you read online good so discussion i suspect really need point,i need return instance bike constructor for example class bikeobject def initselfcolor selfbikecolor color return self it return instance class right mybike bikeblue when i i get following error typeerror init return none bike if case could i return instance suppose return none,2 in response edit you blitting text screen take particular elif branch ie worm gets food on next frame clear screen food score get drawn you blit score screen every frame instead,so far snake game score printed python shell how printed games window instead so game score window thanks eric running screenfill wormmove wormdraw fooddraw wormcrashed exit elif wormx wormx w running false elif wormy wormy h running false elif wormposition foodposition score wormeat print score score food foodscreen elif foodcheckwormx wormy score wormeat print score score food foodscreen elif running false exit event pygameeventget eventtype pygamequit running false elif eventtype pygamekeydown wormeventevent pygamedisplayflip clocktick edit running screenfill wormmove wormdraw fooddraw pygamefontinit pygamefontgetfonts wormcrashed exit elif wormx wormx w running false elif wormy wormy h running false elif foodcheckwormx wormy score wormeat food foodscreen message score score font pygamefontfontnone text fontrendermessage white screenblittext elif running false exit event pygameeventget eventtype pygamequit running false elif eventtype pygamekeydown wormeventevent why isnt score apearing im getting errors,1 just posted part series implementing autocomplete gae serverside service python continuation using yui autocomplete plugin in particular using autocomplete tags similar so yui autocomplete plugin offers option querydelimiter lets define separator selecting string match thus set space plugin matches every new word typed textbox yuiuse autocomplete function y yone body addclass yuiskinsam autocomplete search input field yone searchfield plugypluginautocomplete querydelimiter source rpcxhractionackeywordsampargquery the action ackeywords defined gae looks list tags begin typed string,i want build auto complete feature tags field like so app engine idea i go process server side algo what logic autocomplete app engine implementation what datastore schema,1 well kind bizarre thing you explained want know importing module i actually help solve problem you also explained want know importing module def whoimportsstudiedmodule loadedmodule sysmodulesvalues moduleattribute dirloadedmodule getattrloadedmodule moduleattribute studiedmodule yield loadedmodule this give iterator modules use module toplevel object it find modules cmn import list change time import os whoimportsos print mname site main posixpath genericpath posixpath linecache,how i find file importing particular file python consider following example apy import cmn bpy import cmn cmnpy here i want know file apy bpy importing one is possible all files apy bpy cmnpy directory why i want in cc include feature what want illuminate cc code acpp define somestuff include cmnh bcpp define somestuff include cmnh cmnh here i define functionsclasses use symbol define acpp bcpp code refer somestuff in cc use method reuse sourecode now return python code when apy import cmnpy hope run cmnpy cmnpy refer symbol defined apy when bpy import cmnpy hope run cmnpy cmnpy refer symbol defined bpy,1 you need install import hook tracks imports see pep httpdocspythonorgdevpyklibraryimportlibhtml however comments point probably better way structure code,how i find file importing particular file python consider following example apy import cmn bpy import cmn cmnpy here i want know file apy bpy importing one is possible all files apy bpy cmnpy directory why i want in cc include feature what want illuminate cc code acpp define somestuff include cmnh bcpp define somestuff include cmnh cmnh here i define functionsclasses use symbol define acpp bcpp code refer somestuff in cc use method reuse sourecode now return python code when apy import cmnpy hope run cmnpy cmnpy refer symbol defined apy when bpy import cmnpy hope run cmnpy cmnpy refer symbol defined bpy,1 your script works perhaps bothering meanings encode decode switched that inputting encode invokes decoder inputting decode invokes encoder and see comments please use translate,i making program takes sentence garbles run degarbler theres probably better way i would appreciate everyone would show fix i wrong def sencoder sentence sentence sentencereplace ah sentence sentencereplace sj sentence sentencereplace dk sentence sentencereplace fl sentence sentencereplace bg sentence sentencereplace zt sentence sentencereplace qy sentence sentencereplace wu sentence sentencereplace ei sentence sentencereplace ro sentence sentencereplace xp sentence sentencereplace cb sentence sentencereplace vn sentence sentencereplace mm print sentence def decoder sentence sentence sentencereplace ha sentence sentencereplace js sentence sentencereplace kd sentence sentencereplace lf sentence sentencereplace gb sentence sentencereplace tz sentence sentencereplace yq sentence sentencereplace uw sentence sentencereplace ie sentence sentencereplace sentence sentencereplace px sentence sentencereplace bc sentence sentencereplace nv sentence sentencereplace mm print sentence sentence choice rawinput do want decode encode lower sentence quit sentence rawinputenter code choice encode decodersentence elif choice decode sencodersentence else print please make valid decision help,1 i making program takes sentence garbles run degarbler note work kind input sentence encode ah hh decode hh aa if two alphabets overlap need change algorithm keep partiallyencoded data separate input string from example obvious problem i thought i better point,i making program takes sentence garbles run degarbler theres probably better way i would appreciate everyone would show fix i wrong def sencoder sentence sentence sentencereplace ah sentence sentencereplace sj sentence sentencereplace dk sentence sentencereplace fl sentence sentencereplace bg sentence sentencereplace zt sentence sentencereplace qy sentence sentencereplace wu sentence sentencereplace ei sentence sentencereplace ro sentence sentencereplace xp sentence sentencereplace cb sentence sentencereplace vn sentence sentencereplace mm print sentence def decoder sentence sentence sentencereplace ha sentence sentencereplace js sentence sentencereplace kd sentence sentencereplace lf sentence sentencereplace gb sentence sentencereplace tz sentence sentencereplace yq sentence sentencereplace uw sentence sentencereplace ie sentence sentencereplace sentence sentencereplace px sentence sentencereplace bc sentence sentencereplace nv sentence sentencereplace mm print sentence sentence choice rawinput do want decode encode lower sentence quit sentence rawinputenter code choice encode decodersentence elif choice decode sencodersentence else print please make valid decision help,1 here hint use translate method instead import string stringmaketransabcdef bcdefa abracadabratranslatet bcrbdbebcrb stringmaketransbcdefa abcdef bcrbdbebcrbtranslatet abracadabra,i making program takes sentence garbles run degarbler theres probably better way i would appreciate everyone would show fix i wrong def sencoder sentence sentence sentencereplace ah sentence sentencereplace sj sentence sentencereplace dk sentence sentencereplace fl sentence sentencereplace bg sentence sentencereplace zt sentence sentencereplace qy sentence sentencereplace wu sentence sentencereplace ei sentence sentencereplace ro sentence sentencereplace xp sentence sentencereplace cb sentence sentencereplace vn sentence sentencereplace mm print sentence def decoder sentence sentence sentencereplace ha sentence sentencereplace js sentence sentencereplace kd sentence sentencereplace lf sentence sentencereplace gb sentence sentencereplace tz sentence sentencereplace yq sentence sentencereplace uw sentence sentencereplace ie sentence sentencereplace sentence sentencereplace px sentence sentencereplace bc sentence sentencereplace nv sentence sentencereplace mm print sentence sentence choice rawinput do want decode encode lower sentence quit sentence rawinputenter code choice encode decodersentence elif choice decode sencodersentence else print please make valid decision help,3 java c require base class constructor called memory layout if class baseclass member field create new class subclass adds member field instance subclass contains space field field you need constructor baseclass fill field unless require inheriting classes repeat baseclass initialization constructors and field private inheriting classes initialise field python java c all instances userdefined classes shape they basically dictionaries attributes inserted before initialisation done instances userdefined classes almost exactly places store attributes storing yet so makes perfect sense python subclass call base class constructor it could add attributes wanted there space reserved given number fields class hierarchy difference attribute added code baseclass method attribute added code subclass method if common subclass actually want baseclass invariants set goes customisation yes call baseclassinit use super complicated problems sometimes but and different arguments hell wanted could call baseclassinit another method entirely init maybe bizarre lazy initialization thing going python achieves flexibility keeping things simple you initialise objects writing init method sets attributes self that it behaves exactly like method exactly method there strange unintuitive rules things done first things automatically happen things the purpose needs serve hook execute object initialisation set initial attribute values if want something else explicitly write code,why python designers decide subclasses init methods automatically call init methods superclasses languages is pythonic recommended idiom really like following class superclassobject def initself print do something class subclasssuperclass def initself supersubclass selfinit print do something else,3 i think would possible a channel current data subscribe channel start receiving messages pushed clients channel hence blocking api also look redis commands documentation pubsub would make clear,i want use redis pubsub transmit messages want blocked using listen like code import redis rc redisredis ps rcpubsub pssubscribe foo bar rcpublish foo hello world item pslisten item type message print item channel print item data the last section block i want check given channel data i accomplish is check like method,3 the namedtuple code collections module example cmnpy import sys print i imported sysgetframefglobalsget name one limitation approach outermost module always named main if case name outermost module determined sysargv a second limitation code using sysgetframe module scope executed first import cmnpy you need call function sort imports want monitor imports module,how i find file importing particular file python consider following example apy import cmn bpy import cmn cmnpy here i want know file apy bpy importing one is possible all files apy bpy cmnpy directory why i want in cc include feature what want illuminate cc code acpp define somestuff include cmnh bcpp define somestuff include cmnh cmnh here i define functionsclasses use symbol define acpp bcpp code refer somestuff in cc use method reuse sourecode now return python code when apy import cmnpy hope run cmnpy cmnpy refer symbol defined apy when bpy import cmnpy hope run cmnpy cmnpy refer symbol defined bpy,3 the term searching slugify,basically question python gae c requirements separate word dash remove punctuation taking account words separated spaces function takes max length gets tokens max length example toseofriendlyhello world hello world returns helloworld all words converted lower case,1 as alternative probably tested version i suggesting use minimal modified slugify code django import unicodedata import def slugifyvalue normalizes string converts lowercase removes nonalpha characters converts spaces hyphens value unicodedatanormalize nfkd valueencode ascii ignore decode ascii value resub ws valuestriplower return resub value see httpsgithubcomdjangodjangoblobmasterdjangoutilstextpyl,basically question python gae c requirements separate word dash remove punctuation taking account words separated spaces function takes max length gets tokens max length example toseofriendlyhello world hello world returns helloworld all words converted lower case,1 the easiest way break logic functions you execute logic global module scope first place use name main wrapper construct you could define function addoptionsparser module must define options call root level calling parseargs import optparse import submodule def addoptionsparser parseraddoption def main parser optparseoptionparser addoptionsparser submoduleaddoptionsparser opts args parserparseargs main main main,i following example setup mainscriptpy module initpy submodulepy contents mainscript import optparse import module parser optparseoptionparser group optparseoptiongroupsubmodules options groupaddoptionmainscriptbar destbar actionstoretrue parseraddoptiongroupgroup optsargs parserparseargs optsbar print bar contents submodulepy import optparse parser optparseoptionparser group optparseoptiongroupparser submodules options groupaddoptionmodulesubmodulefoo destfoo actionstoretrue parseraddoptiongroupgroup optsargs parserparseargs optsfoo print foo since mainscript imports submodule parseargs submodule called is anyway combine instances optionparser raise error option conflicts,1 why integrate existing script parser eg integrating lua c,i looking complete tutorial learning resource i learn implement script parser c my intention implement system within game engine promote creation user generated content edit this learning exercise anything else,1 in general best postgis function query stdwithin returns true geometries within specified distance one another eg customers live within meters shop select customers from customers shops where stdwithincustomersthegeog shopsthegeog and shopid stdwithin use spatial index created therefore outperform stdistance in django seems corresponding filter called dwithin returns models distance geometry field lookup geometry within given distance one another zipcodeobjectsfilterpolydwithingeom dm backend sql equivalent postgis stdwithinpoly geom dm returns distance object length meters geom geometry want calculate distances zipcode objects dwithin function used poly geometry attribute zipcode objects z zipcodecode poly polygon,i using geodjango postgis then i trouble query postgres db table get data within distance meters updates i using geodjango i found something url httpsdocsdjangoprojectcomendevrefcontribgisgeoquerysetsstdfieldlookupdistancelte zipcodeobjectsfilter polydistancelte geom d but know prepare parameter variables polydistancelte function geom variable create d function yes parameter name d function,3 return exits current function method pass null operation allows execution continue next statement,i seen code pinax django apps instead pass empty return statement used what difference would effect example django code i running the code signal method automatically saves hashtags taggit tag objects tweet object i saw question whether return statement php makes difference interpreted bytecode i sure relevant python import tagregex recompiler ptagw def gettaggedsender instance kwargs automatically add tags tweet object instance return pass better worse post instance tagslist smartunicodetlower listsettagregexfindallpostcontent tagslist posttagsaddtagslist postsave else return pass better worse postsaveconnectgettagged sendertweet,3 instance return pass better worse pass would continue execution method a return would terminate execution method regarding following lines want put return else return pass better worse make difference even removing whole two lines change anything but anyway imagine would elaborate method it better choose right flow beginning,i seen code pinax django apps instead pass empty return statement used what difference would effect example django code i running the code signal method automatically saves hashtags taggit tag objects tweet object i saw question whether return statement php makes difference interpreted bytecode i sure relevant python import tagregex recompiler ptagw def gettaggedsender instance kwargs automatically add tags tweet object instance return pass better worse post instance tagslist smartunicodetlower listsettagregexfindallpostcontent tagslist posttagsaddtagslist postsave else return pass better worse postsaveconnectgettagged sendertweet,1 instance return pass better worse worse it changes logic pass actually means do nothing if would replace return pass control flow would continue changing semantic code the purpose pass create empty blocks possible otherwise python indentation scheme for example empty function c looks like void foo in python would syntax error def foo this pass comes handy def foo pass,i seen code pinax django apps instead pass empty return statement used what difference would effect example django code i running the code signal method automatically saves hashtags taggit tag objects tweet object i saw question whether return statement php makes difference interpreted bytecode i sure relevant python import tagregex recompiler ptagw def gettaggedsender instance kwargs automatically add tags tweet object instance return pass better worse post instance tagslist smartunicodetlower listsettagregexfindallpostcontent tagslist posttagsaddtagslist postsave else return pass better worse postsaveconnectgettagged sendertweet,3 in one line someboolvalue num but don’t this style normally expected people prefer longer form clarity consistency someboolvalue num equally camel caps avoided so rather use someboolvalue note inline expression somevalue predicate without else part exist would return value predicate false however expressions must clearly defined return value cases this different usage say ruby perl,i following code num someboolvalue true i need set value num someboolvalue true nothing otherwise so code num someboolvalue else num is someway i could avoid else num part make look cleaner an equivalent someboolvalue num i tried replacing else pass like num someboolvalue else pass all i got syntax error nor i could omit else num part thanks,3 no i guess hoping something like num someboolvalue would work i think best way statement written someboolvalue num,i following code num someboolvalue true i need set value num someboolvalue true nothing otherwise so code num someboolvalue else num is someway i could avoid else num part make look cleaner an equivalent someboolvalue num i tried replacing else pass like num someboolvalue else pass all i got syntax error nor i could omit else num part thanks,2 this comment answer fit comment instance return pass better worse as explained accepted answer pass would incorrect else return pass better worse here since end function pass would thing nothing even better would leave else clause entirely since nothing it true explicit better implicit zen rarely applies explicitly nothing clear happens else case anyone actually even wonders first place it also clear rename instance post within function could change parameter name sender argument supposed oh actually need convert set list iterate list comprehension,i seen code pinax django apps instead pass empty return statement used what difference would effect example django code i running the code signal method automatically saves hashtags taggit tag objects tweet object i saw question whether return statement php makes difference interpreted bytecode i sure relevant python import tagregex recompiler ptagw def gettaggedsender instance kwargs automatically add tags tweet object instance return pass better worse post instance tagslist smartunicodetlower listsettagregexfindallpostcontent tagslist posttagsaddtagslist postsave else return pass better worse postsaveconnectgettagged sendertweet,1 use num someboolvalue else num,i following code num someboolvalue true i need set value num someboolvalue true nothing otherwise so code num someboolvalue else num is someway i could avoid else num part make look cleaner an equivalent someboolvalue num i tried replacing else pass like num someboolvalue else pass all i got syntax error nor i could omit else num part thanks,3 that python bug special characters instead recompilerw try recompilerazaz it works however make regular expression this bug seems fixed,i get error message i use expression resubrsws i checked regex regexr returns expected but i try python i get error message raise error v invalid expression sreconstantserror nothing repeat can someone please explain,3 i think possible python since actually trying probably gets expanded something like num someboolvalue else num if exclude else num receive syntax error since i quite sure assignment must actually return something as others already mentioned could bad probably end confusing reading piece code next time someboolvalue num i big fan num someboolvalue num exact reason i actually think twice line the best way actually achieve want original version someboolvalue num the reason best verison obvious want confuse whoever else going come contact code later also side note num someboolvalue valid ruby code ruby works bit differently,i following code num someboolvalue true i need set value num someboolvalue true nothing otherwise so code num someboolvalue else num is someway i could avoid else num part make look cleaner an equivalent someboolvalue num i tried replacing else pass like num someboolvalue else pass all i got syntax error nor i could omit else num part thanks,3 have look micro webdevelopment framework flask from docs flask import flask app flaskname approute def helloworld return hello world name main apprun just save hellopy something similar run python interpreter easyinstall flask python hellopy running http,i considering several options user interface application i want application multiplatform windows linux osx one options i considered develop web application run local server still access administrator privileges required simply web interface program i want develop python convenience reasons does using pylons job recommended best way run setup,1 you compare datetime timedelta a timedelta represents duration datetime represents specific point time the difference two datetime timedelta datetimes comparable timedelta you options subtract another datetime one given compare resulting timedelta timedelta also given convert timedelta datetime adding subtracting another datetime compare resulting datetime datetime given,i python beginner i need see date x days how i python i tested something like datetimedate datetimetimedelta i got error typeerror compare datetimedate datetimetimedelta any clue achieve best regards,3 client requestpost something,first bit introduction i send post url either ip mac hostname now depending key querydict want certain calls ie output print requestpost querydict u ip u u message u test u client u auabrthin i want write something like requestpost client requestpost dosomething however requestpost client obviously value client i check requestpost key,3 comparing apples oranges always hard you trying compare january fixed point time hours duration there sense if asking datetime fall nth day month myimportantdate datetimenow myimportantdateday n pass important things,i python beginner i need see date x days how i python i tested something like datetimedate datetimetimedelta i got error typeerror compare datetimedate datetimetimedelta any clue achieve best regards,1 i assume actually need final return value i assume indicates number removed elements obviously always last pass the simpleisbetterthancomplex way reductionpassdataset pass the showingoff obviouslynotserious way itertools import listtakewhilelambda x x starmapreductionpass repeatdataset,so i function reduces dataset returns number elements removed i stop applying number items reduced function operation zero currently i got numremoved reductionpassdataset numremoved numremoved reductionpassdataset two variable assignments kind get is elegant way write,2 you get iterator iterlambda reductionpassdataset every step calls given function stops retrieved with iterator numremoved dowhatever,so i function reduces dataset returns number elements removed i stop applying number items reduced function operation zero currently i got numremoved reductionpassdataset numremoved numremoved reductionpassdataset two variable assignments kind get is elegant way write,1 first i would use figure object work makes easier construct plot liking to construct graph following fig pltfigure figsubplotsadjustbottom remark ax figaddsubplot axbararangelengrosses grosses axticklabelformatstyle plain remark axsetxticksarangelengenres axsetxticklabelsgenres rotation savefig barchartpng dpi along following remarks this adjusts size image case enlarges bottom able fit labels in cases roughly know data going put suffice if using matplotlib version higher could use tightlayout function automatically the alternative calculate needed size based bounding boxes axes labels shown need renderer able determine sizes labels by specifying label format using either sci plain change rendering values when using plain render value see docs function info note also use setyticklabels function text argument control formatting course function also available x axis,i couple problems bar chart i trying create python my code chart looks like import matplotlib matplotlibuse agg pylab import import calendar def webshowimg savefigimgdpi print contenttype texthtmln print img width height src img genres n c sortedlist genresappendsortedlistn n grosses c sortedlist grossesappendsortedlista clf bararangelengrossesgrosses xticks arangelengenresgenres rotation webshowbarchartpng my chart looks like basically main problem values decimals scientific notation i want present millions possible also i sure make genres cut bottom thank help,2 many web pages encoded incorrectly for parsing html try beautifulsoup handle many types incorrect html found wild beautiful soup python htmlxml parser designed quick turnaround projects like screenscraping three features make powerful beautiful soup choke give bad markup it yields parse tree makes approximately much sense original document this usually good enough collect data need run away beautiful soup provides simple methods pythonic idioms navigating searching modifying parse tree toolkit dissecting document extracting need you create custom parser application beautiful soup automatically converts incoming documents unicode outgoing documents utf you think encodings unless document specify encoding beautiful soup autodetect one then specify original encoding emphasis mine,i trying check certain word page many sites the script runs fine say sites stops unicodedecodeerror utf codec decode byte x position invalid start byte i search stackoverflow found many issues i seem understand went wrong case i would like either solve error skip site pls advice i i new code taken day write by way site script halted httpwwwhomesteadcom filetocheck openbloglistforcommentingr resultfile openfinalfilew countofsites filetocheckreadlines sitename countofsitesstrip htmlfile urlliburlopensitename page htmlfilereaddecode utf match researchenter name page match print match found sitename resultfilewritesitenamen else print sorry find pattern sitename print finished operations as per mark comments i changed code implement beautifulsoup htmlfile urlliburlopenhttpwwwhomesteadcom page beautifulsoup joinhtmlfile print pageprettify i getting error page beautifulsoup joinhtmlfile typeerror module object callable i trying quick start example httpwwwcrummycomsoftwarebeautifulsoupdocumentationhtmlquickstart if i copy paste code works fine i finally got work thank help here final code import urllib import beautifulsoup import beautifulsoup filetocheck openlistfiler resultfile openfinalfilew error errors countofsites filetocheckreadlines sitename countofsitesstrip htmlfile urlliburlopensitename page beautifulsoup joinhtmlfile pagetwo strpage match researchenter yourname pagetwo match print match found sitename resultfilewritesitenamen else print sorry find pattern sitename print finished operations,3 yes jython faq distribution basically need lib directory inside jython jar you add modules long jython compatible ie native part,is possible create jython standalone jar including jython packages pynum pythonexcel,1 the site httpwwwhomesteadcom claim sending utf response actually claims iso meta httpequivcontenttype contenttexthtml charsetiso you must use correct encoding page actually received guess randomly,i trying check certain word page many sites the script runs fine say sites stops unicodedecodeerror utf codec decode byte x position invalid start byte i search stackoverflow found many issues i seem understand went wrong case i would like either solve error skip site pls advice i i new code taken day write by way site script halted httpwwwhomesteadcom filetocheck openbloglistforcommentingr resultfile openfinalfilew countofsites filetocheckreadlines sitename countofsitesstrip htmlfile urlliburlopensitename page htmlfilereaddecode utf match researchenter name page match print match found sitename resultfilewritesitenamen else print sorry find pattern sitename print finished operations as per mark comments i changed code implement beautifulsoup htmlfile urlliburlopenhttpwwwhomesteadcom page beautifulsoup joinhtmlfile print pageprettify i getting error page beautifulsoup joinhtmlfile typeerror module object callable i trying quick start example httpwwwcrummycomsoftwarebeautifulsoupdocumentationhtmlquickstart if i copy paste code works fine i finally got work thank help here final code import urllib import beautifulsoup import beautifulsoup filetocheck openlistfiler resultfile openfinalfilew error errors countofsites filetocheckreadlines sitename countofsitesstrip htmlfile urlliburlopensitename page beautifulsoup joinhtmlfile pagetwo strpage match researchenter yourname pagetwo match print match found sitename resultfilewritesitenamen else print sorry find pattern sitename print finished operations,1 i guess nothing wrong base encoding it seems like embedded correct xml document probably error send data maybe check piece code,i read file stream zip file following code file opensourceurl rb data fileread fileclose bytearr basebencodedata now i trying call webservice accepts basebinary format data byte array written java if i send bytearr webservice i get client error fault envclient caught exception handling request unexpected element type expectedhttpwwwworgxmlschemabasebinary actualhttpwwwworgxmlschemastring please suggest base module working typebytearr still string with thanks sandhya,1 onedate datetimedate datetimetimedeltadays datetimedatetimenow the first date second datetime so want compare dates day month year convert second date onedate nowdate returns true,i need convert result timestamp print datetimedate datetimetimedeltadays i need compare value timestamp datetimedatetimenow how i achieve,1 first ask question like helpful add information failing eg copy error your query fails mixing operators document overrides you use set operator userid text fields well although userid part update irrelevant example so convert pymongo query dbtestupdateuserid settextlorem ipsum updatednew date inccount true false i removed userid update necessary if document exists value already if exist upsert copy query part update new document,i trying run following query data userid text lorem ipsum inc count set updated datetimenow selfdbcollection collection update userid data upserttrue two queries cause fail is possible within one statement,3 i need convert result timestamp import time mydate datetimedate datetimetimedeltadays timemktimemydatetimetuple i need compare value timestamp datetimedatetime datetimetimedeltadays b datetimedatetimenow b b b,i need convert result timestamp print datetimedate datetimetimedeltadays i need compare value timestamp datetimedatetimenow how i achieve,3 datetimedatetimenow return instance datetimedatetime date method returning instance datetimedate you compare result datetimedate datetimetimedeltadays,i need convert result timestamp print datetimedate datetimetimedeltadays i need compare value timestamp datetimedatetimenow how i achieve,1 the byte x presumably position either singlebyte encoding character last byte multiplebyte encoding making start character x binary byte matching pattern xxxxxx x xbf second subsequent byte utf encoding hence stream either utf else corrupted examining uri link find header contenttype texthtml since encoding stated use default http iso aka latin examining content find line meta httpequivcontenttype contenttexthtml charsetiso which fallback mechanism people reason unable set http headings correctly this time explicitly told character encoding iso as reason expect reading utf work for extra fun though consider iso x encodes u control character start of guarded area find iso correct either it seems people creating page made similar error from context would seem actually used windows encoding x encodes u endash looks like – so parse particular page want decode windows more generally want examine headers picking character encodings would perhaps incorrect case perhaps iso codecs actually windows correct often you still need something catch failures like reading fallback the decode method takes second parameter called errors the default strict also ignore replace xmlcharrefreplace appropriate backslashreplace appropriate register fallback handler codecsregistererror,i trying check certain word page many sites the script runs fine say sites stops unicodedecodeerror utf codec decode byte x position invalid start byte i search stackoverflow found many issues i seem understand went wrong case i would like either solve error skip site pls advice i i new code taken day write by way site script halted httpwwwhomesteadcom filetocheck openbloglistforcommentingr resultfile openfinalfilew countofsites filetocheckreadlines sitename countofsitesstrip htmlfile urlliburlopensitename page htmlfilereaddecode utf match researchenter name page match print match found sitename resultfilewritesitenamen else print sorry find pattern sitename print finished operations as per mark comments i changed code implement beautifulsoup htmlfile urlliburlopenhttpwwwhomesteadcom page beautifulsoup joinhtmlfile print pageprettify i getting error page beautifulsoup joinhtmlfile typeerror module object callable i trying quick start example httpwwwcrummycomsoftwarebeautifulsoupdocumentationhtmlquickstart if i copy paste code works fine i finally got work thank help here final code import urllib import beautifulsoup import beautifulsoup filetocheck openlistfiler resultfile openfinalfilew error errors countofsites filetocheckreadlines sitename countofsitesstrip htmlfile urlliburlopensitename page beautifulsoup joinhtmlfile pagetwo strpage match researchenter yourname pagetwo match print match found sitename resultfilewritesitenamen else print sorry find pattern sitename print finished operations,3 when installed python likely zlibdevel installed python feature built i recommend install readlinedevel sqlitedevel zlibdevel openssldevel compiling python after installing newly compiled python fetch setuptools source package install python setuppy install,install mysqldb module python centos server versions python default one installed want install mysqldb module version python installed line python setuppy install says traceback recent call last file setuppy line module setuptools import setup extension importerror no module named setuptools went installing setup tools using command setuptoolscpyegg installed python installed rpm execute command says traceback recent call last file string line module zipimportzipimporterror decompress data zlib available locate command find package rpm installed zlib usrsharedoczlib usrsharedoczlibreadme varcacheyumbasepackageszlibdevelelxrpm one please help i exactly want install mysqldb module python installed usrlocalbin directory help idea highly appreciated,3 there problem importing module two different modules python maybe particular design makes problem something python imposes anyhow could probably solve problem moving common stuff amodel bmodel module ie modelcommon importing amodel bmodel,how people get around issue a controller say controllerpy imports two models say amodelpy bmodelpy appmodel import amodel appmodel import bmodel now let say amodel wants use function bmodel let say wants get something bmodel id record query amodel i amodel appmodel import bmodel now since controller already imported bmodelpy amodelpy attempting break application can someone tell best way around maybe use proxy or library loader,3 i would take pyqt qgraphicsview qgraphicsscene sadly isnâ´t clanlib python binding like perl ruby that would probably ideal choice,i want create d game python heavy user interface windows buttons text input etc so far i using pygame simple games the game d mud standard rendering loop draw stuff screen i need user interface interact game entities like sales blacksmith etc i looking something like mix pygame wxpythonpyqtpygtk which libraries i use,3 i problem python script hung shell script i running remote ssh client wget command mb file i found adding timeout wget command fixed problem originally i wget httpblahfilezip wget q t httpblahfilezip works like charm hope helps,hi i problems executing command performs wget mb file ubuntu server shorter commands work fine except the class contains i use paramiko different tries overcoming problem see different run exec methods in case execcmd execution hangs line selfinbufferreadnbytes selftimeout recv method channelpy module paramiko the wget command works perfectly shell using normal ssh utility mac management ssh connections import logging import os import paramiko import socket import time import stringio class sshclient def initself selfsshclient paramikosshclient selfsshclientloadsystemhostkeys selfsshclientsetmissinghostkeypolicyparamikoautoaddpolicy selftimeout selfwait def connectself hostname user pkey retry selftimeout selfhostname hostname logginginfoconnecting tos users keys hostname user pkey retry try selfsshclientconnecthostname usernameuser keyfilenameospathexpanduserpkey timeoutselftimeout return except socketerror valuemessage value value loggingwarning ssh connection refused retry seconds timesleepselfwait retry selfwait else raise except paramikobadhostkeyexception loggingwarnings entry sshknownhosts match selfserverhostname loggingwarning edit file remove entry try retry except eoferror loggingwarning unexpected error ssh connection retry seconds timesleepselfwait retry selfwait loggingerror could establish ssh connection def existsself path status selfrun echo false path statusstartswith false return return def shellself start interactive shell session remote host channel selfsshclientinvokeshell interactiveshellchannel def runself command execute command remote host return tuple containing integer status string containing output command logginginfo runnings command selfhostname logfp stringiostringio status try selfsshclientexeccommandcommand except paramikosshexception loggingerrorerror executing command command status logfpwritetread logfpwritetread tclose tclose tclose logginginfo output logfpgetvalue return status logfpgetvalue def runptyself command execute command remote host pseudoterminal returns string containing output command logginginfo runnings command selfhostname channel selfsshclientgettransportopensession channelgetpty status try channelexeccommandcommand except loggingerrorerror executing command command status return status channelrecv def closeself transport selfsshclientgettransport transportclose def runremoteself cmd checkexitstatustrue verbosetrue usesudofalse logginginfo runnings cmd selfhostname ssh selfsshclient chan sshgettransportopensession stdin chanmakefile wb stdout chanmakefile rb stderr chanmakefilestderr rb processedcmd cmd usesudo processedcmd sudo s bash c cmdreplace chanexeccommandprocessedcmd result stdout stderr exitstatus chanrecvexitstatus result exitstatus exitstatus def printoutput line stdout result stdout appendline logginginfoline line stderr result stderr appendline logginginfoline verbose print processedcmd printoutput return exitstatusresult def execcmdself cmd import select ssh selfsshclient channel sshgettransportopensession end cmdepilogqwkjidksjkdskhjdksjkdsl cmd echo end logginginfo runnings cmd selfhostname channelexeccommandcmd buf end buf rl wl xl selectselectchannel lenrl must stdout buf channelrecv logginginfobuf buf return,1 maybe put spaces instead tabs line oposite happends sometimes,i models class tourmodelsmodel namemodelscharfieldmaxlength countmodelssmallintegerfield priceunitcodemodelsforeignkeypriceunit pricemodelscharfieldmaxlength descriptionmodelstextfield actiondatemodelsdatetimefieldautonowtrueeditablefalse actionusercodemodelsforeignkeyusereditablefalse statustypecodemodelsforeignkeystatustype class imagesmodelsmodel image modelsimagefielduploadtogallery tourmodelsforeignkeytour i wanna design form add tour set images tour form formmodel class tourformmodelform class meta model tour i viewspy def myviewrequestkey galleryformset inlineformsetfactorytourimages requestmethod post form tourformrequestpost requestfiles formisvalid tourformsave formsetgalleryformsetrequestpost requestfilesinstancetour formsetisvalid formsetsave else form tourform formsetgalleryformset return rendertoresponse airagencyaddtourhtml form form formset formset template form method post enctypemultipartformdata dirrtl csrftoken formasp formsetmanagementform form formset form endfor input typesubmit form error unexpected indent viewspy line line ifformisvalid course i changed code alotbut every time error line code line changing every time wrong thanks advance,2 very likely indentation differs line probably invisible differences leading whitespace example you many lines block start tab displayed editor spaces one lines line contains space tab leading whitespace displayed editor spaces you see difference yet line start different python problem advice remove leading space line autoindent editor get consistent results or remove leading whitespace line use start rest block to verify case open file vim type set list characters now tab displayed i space displayed single space character,i models class tourmodelsmodel namemodelscharfieldmaxlength countmodelssmallintegerfield priceunitcodemodelsforeignkeypriceunit pricemodelscharfieldmaxlength descriptionmodelstextfield actiondatemodelsdatetimefieldautonowtrueeditablefalse actionusercodemodelsforeignkeyusereditablefalse statustypecodemodelsforeignkeystatustype class imagesmodelsmodel image modelsimagefielduploadtogallery tourmodelsforeignkeytour i wanna design form add tour set images tour form formmodel class tourformmodelform class meta model tour i viewspy def myviewrequestkey galleryformset inlineformsetfactorytourimages requestmethod post form tourformrequestpost requestfiles formisvalid tourformsave formsetgalleryformsetrequestpost requestfilesinstancetour formsetisvalid formsetsave else form tourform formsetgalleryformset return rendertoresponse airagencyaddtourhtml form form formset formset template form method post enctypemultipartformdata dirrtl csrftoken formasp formsetmanagementform form formset form endfor input typesubmit form error unexpected indent viewspy line line ifformisvalid course i changed code alotbut every time error line code line changing every time wrong thanks advance,2 python line formisvalid,i models class tourmodelsmodel namemodelscharfieldmaxlength countmodelssmallintegerfield priceunitcodemodelsforeignkeypriceunit pricemodelscharfieldmaxlength descriptionmodelstextfield actiondatemodelsdatetimefieldautonowtrueeditablefalse actionusercodemodelsforeignkeyusereditablefalse statustypecodemodelsforeignkeystatustype class imagesmodelsmodel image modelsimagefielduploadtogallery tourmodelsforeignkeytour i wanna design form add tour set images tour form formmodel class tourformmodelform class meta model tour i viewspy def myviewrequestkey galleryformset inlineformsetfactorytourimages requestmethod post form tourformrequestpost requestfiles formisvalid tourformsave formsetgalleryformsetrequestpost requestfilesinstancetour formsetisvalid formsetsave else form tourform formsetgalleryformset return rendertoresponse airagencyaddtourhtml form form formset formset template form method post enctypemultipartformdata dirrtl csrftoken formasp formsetmanagementform form formset form endfor input typesubmit form error unexpected indent viewspy line line ifformisvalid course i changed code alotbut every time error line code line changing every time wrong thanks advance,1 it fine long cicrcular references ie main modelamodel modelbmodel modelbmodel is ok but add import amodel bmodelpy things would get complicated would way order loading way module prerequisites would satisfied python handles situation less nicely one would expect instead reporting circular imports raises exception undefined symbol one modules,how people get around issue a controller say controllerpy imports two models say amodelpy bmodelpy appmodel import amodel appmodel import bmodel now let say amodel wants use function bmodel let say wants get something bmodel id record query amodel i amodel appmodel import bmodel now since controller already imported bmodelpy amodelpy attempting break application can someone tell best way around maybe use proxy or library loader,2 from appscript documentation names match python keywords names reserved appscript underscore appended as next reserved keyword fix running app vlc next,i want make python script control vlc vlc controlled applescript using pyappscript i run applescript code python using applescript i playpause vlc tell application vlc play this equals following pyappscript app vlc play i also able skip next track app vlc next but i get following python error traceback recent call last file vlclibpy line module app vlc next typeerror next takes exactly arguments given does anyone know i get error the code equal following applescript works perfectly tell application vlc next,1 you disable warning adding comment python file warning raised pylint disablemsgw if want add comment python file see question how i disable pylint warning global solution,i using djangojenkins plugin django project seems installed pylint i run pylint byt running python managepy pylint it works fine i would like disable messages eg w i seem pass parameter pylint using managepy could anyone tell i quiet w messages thanks,2 as start connect remote site using tcp use code import socket struct def connecttohosthost port timeout try socksocketsocket timevalstructpacki timeout socksetsockoptsocketsolsocket socketsorcvtimeo timeval socksetsockoptsocketsolsocket socketsosndtimeo timeval sockconnecthost port return sock except return none you open socket connected remote server you would create listen socket wait one connection as soon connection multiplex data streams using select i time right code sketch might look like you would need proper error handling maybe nice error messages function noone comes complete solution i may make effort complete code,i trying write python process listens port client connects starts thread following connects remote service httpmagicfm passes data received connected client happens windows media player the story i want listen radio work i cannot i another countryavailable nationally i cannot change proxy settings computer but i server i would like use proxy thanks advance here i far usrbinenv python import socket urllib tcpip tcpport buffersize kbs socketsocketsocketafinet socketsockstream sbindtcpip tcpport slisten conn addr saccept print connection address addr req urlliburlopen httpmagicfm chunk reqreadbuffersize chunk break connsendchunk connclose fails traceback recent call last file magicfmproxypy line connsendchunk socketerror broken pipe,1 first python need semicolon end line then want supply one argument ie pid subprocesspopenmv globglobospathbasenamefilename folder otherwise specifying result globglob second argument bufsize subprocesspopen also note calling mv unnecessary python already functionality move files implemented shutilmove f globglobospathbasenamefilename shutilmovef folder,why getting error buffsize musth integer afer line pid subprocesspopenmvglobglobospathbasenamefilename folder it simply mv command blog shell expansion i want sth like mv filename folder,2 you getting loop use q start xrange allfilesshape q data allfilesstartstartq,ok so i array data shape called allfiles i need go array columns time extract subarray manipulation the problem address array using code seem recognize variables b code moment shown q npshapeallfiles rangea b q data allfilesab when replace variables number ie data allfiles it seems work so question way pass variables array index if better way create subarray using variables i tried find problem stack overflow luck sure first person trouble cheers guys morgan,1 you seem need osx app work infoplist file contains uservisible name application put this defaults python title see program menu this blog post outlines steps need take osx developer library docs property list need fill,i writing gui application using python qt when i launch application mac first menu item mac menu bar top screen python i would prefer application name name application how i get program name the following demo program creates window two menus python foo i like makes difference users whether i wrote app python cobol instead i want menus myapp foo usrbinpython this example demonstrates unwanted python application menu name mac makes difference whether use pyside pyqt pysideqtgui import pyqtqtgui import import sys app qapplicationsysargv mac menubar application menu always python i want desiredapptitle instead setapplicationname affect mac menu bar appsetapplicationnamedesiredapptitle win qmainwindow need none parent menubar mac get custom menus mbar qmenubar add custom menu menubar foomenu qmenumbar foomenusettitlefoo mbaraddactionfoomenumenuaction winsetmenubarmbar winshow sysexitappexec how i change application menu name mac edit i would prefer continue use system python whatever python user path possible,3 check python documentation httpdocspythonorgreferencedatamodelhtmlemulatingcontainertypes,i looking sample minimal example class mimics immutable sequence python class mysequence mysequence lena pass what methods must implemented,2 the decorator executed it takes callable object returns callable object the object returns used place in words b called point defined it prints b returns unchanged since returns unchanged b plays role whatsoever subsequent calls therefore following comment quite correct print b in fact prints the b see printed b def if change code like rerun sequence events become clearer def bfnc print b return fnc b def print name main print main finally achieve effect looking decorator would need return different callable object def bfnc def decorated print b return fnc return decorated b def print name main print main here pretty clear calling fnc,imagine def bfnc print b return fnc b def print name main print b so i using b gets turned ba right then i say this turns ba and goes print b return fnc wherewho exactly calling fnc i feeling i asking stupid question i want understand,3 it documented wtforms documentation selectfield quoted convenience select fields keep choices property sequence value label pairs i sure formparentchoices syntax code looks like formparentchoices parent name parent name parent name parent name,i testing python framework flask flaskmongoalchemy mongodb course as i building multiple documents test app i like get forms validated us wtforms can anyone share example create object references selectfield class parentdbdocument title dbstringfield description dbstringfield class objectdbdocument parent dbdocumentfieldparent title dbstringfield approute objectnew methods get post def newobject form objectformobjobject formparentchoices p parentqueryall correct syntax i like understand tid ttitle work formvalidateonsubmit formsave return redirecturlfor return class objectformwtfform parent wtfselectfieldu parent i need add anything special any suggestion would great or link online example thanks,1 below ants solution rewritten event system sqlalchemy sqlalchemyextdeclarative import declarativebase sqlalchemyorm import columnproperty sqlalchemy import event def checkstringlengthcls key inst prop instprop only interested simple columns relations isinstanceprop columnproperty lenpropcolumns col propcolumns string column length install length validator isinstancecoltype string coltypelength maxlength coltypelength def setinstance value oldvalue initiator lenvaluemaxlength raise valueerrorlength exceeds allowed lenvalue maxlength eventlisteninst set set base declarativebase eventlistenbase attributeinstrument checkstringlength,i using sqlalchemy maximum column length recipe previous question sqlalchemy maximum column length since i upgraded sqlalchemy lengthvalidator cannot installed using following expression instimplextensionsinsert lengthvalidatorcoltypelength the extension attribute defined sqlachemy is way change recipe work thanks honzas,3 if want able iterate sequence need implement iter method returning iterable the easiest way create generator using yield statement class mysequenceobject def iterself yield yield yield x mysequence print x prints however enable things like mysequence for need implement getitem method probably implement len well class mysequenceobject def lenself return def getitemself key key return elif key return elif key return else raise indexerror new mysequence rangelens print si prints x print x prints notice i omitted iter as long getitem raises indexerror try get value outofbounds python use iteration i could still include iter i wanted clearer wanted nonstandard iteration behaviour,i looking sample minimal example class mimics immutable sequence python class mysequence mysequence lena pass what methods must implemented,3 rules flask unique if define absolute url function default clash something stop since perspective wrong there one reason would want one url absolute endpoint backwards compatibility rule existed past since wz flask explicitly specify alias route approute approute indexhtml aliastrue def index return in case user requests indexhtml flask automatically issue permanently redirect that mean function could bound one url though case would need change endpoint approute def index appaddurlrule indexhtml viewfuncindex endpoint altindex or alternatively approute approute indexhtml endpoint altindex def index in case define view second time different name however something generally want avoid view function would check requestendpoint see called instead better something like approute def index return indexaltfalse approute indexhtml def altindex return indexalttrue def indexalt in cases url generation urlfor index urlfor altindex you also routing system level approute defaults alt false approute indexhtml defaults alt true def indexalt in case url generation urlfor index alttrue urlfor index altfalse,so i method accessible multiple routes approutecanonicalpath approutealternatepath def foo return hi now i call urlforfoo know i get first route,3 who calling fnc basically behind last line code so going decorators meant change behavior functions so decorate something new function created based decorator returns this means decorator runs defined here example demonstrates print def b def bfnc print b return fnc print def b def print name main print main print b this print def b def b main as see decorator b called main executed it returns function instance assigned alias used like function instance this call operator last line code,imagine def bfnc print b return fnc b def print name main print b so i using b gets turned ba right then i say this turns ba and goes print b return fnc wherewho exactly calling fnc i feeling i asking stupid question i want understand,1 here problem openfile csvdictreaderopentravel generatorsappendopenfile travelgenerators generators massagegenerators generators your travelgenerators massagegenerators lists using open file iterate get data problem file iterated csvdictreader massagegenerators exhausted get data try read travelgenerators try instead generatorsappendtravel filename travelgenerators generators massagegenerators generators loops filename massagegenerators dictionary csvdictreaderopenfilename also first loop gathering filenames aware loop saving last filename matches if intention make clear adding break line travel filename,i using loop add dictionary list dictionaries i calling datafile using datafileappend it works fine but later i try add dictionaries datafile another loop i use datafileappend work it add dictionaries datafile does anyone know i wrong i get error it produces file dictionaries massagegenerators it take anything travelgenerators i even tried commenting first loop one massagegenerators case add travelgenerators dictionaries it like i use append twice any help would much appreciated please i sorry elegant i learning coding stuff thanks import csv import copy import os import sys generators list filename oslistdirosgetcwd root ext ospathsplitextfilename rootstartswith travel allowance auto look ext csv travel filename openfile csvdictreaderopentravel generatorsappendopenfile travelgenerators generators massagegenerators generators datafile result stored list dicts travelremap finaltravelall amount massageremap massagebik amount generator massagegenerators dictionary generator dictionary paymenttypecode massagebik dictionary comment massage bik dictionary isgross false dictionary paymenttodate dictionary paid manually false oldkey newkey massageremapiteritems oldkey dictionary continue dictionary amount dictionary massagebik del dictionary massagebik dictionary amount dictionary amount datafileappenddictionary generator travelgenerators dictionary generator dictionary paymenttypecode transportationallowance dictionary comment annual travel allowance paid monthly installments dictionary isgross true dictionary paymenttodate dictionary paid manually false oldkey newkey travelremapiteritems oldkey dictionary continue dictionary amount dictionary finaltravelall del dictionary finaltravelall dictionary amount not applicable dictionary amount dictionary amount dictionary amount na datafileappenddictionary keys empid common name paymenttypecode currency amount effectivedate comment paymentfromdate paymenttodate isgross hiddenuntil paid manually paymentdate bulkupload open emea bulk uploadcsv wb dictwriter csvdictwriterbulkupload keys restval extrasaction ignore dictwriterwriterwriterowkeys dictwriterwriterowsdatafile print everything saved look emea bulk uploadcsv,1 if code pure python using cpython threading likely speed code due global interpreter lock what probably looking multiprocessing module specifically poolmap method since using mulitprocessing means using separate processes instead separate threads things like locking become much less issue that said vectorising code using numpy writing inner loop efficient compiled language like c cython likely give much speedup parallelising four cores,i monte carlo simulator calculation function calls many millions times loop in order speed i would like split multiple parallel thread calls simulator ie if i want run total million times split maybe runs going parallel with thread using variable names i handle clashes do i create seperate versions simulator differently named variables i started write version using python threading module certain still issues variables any suggestions thanks time kyle,1 dlls windows creatures the way able use dll using windows build python you able run windows python ubuntu windows installed inside virtual machine you also might able run using wine an alternative course ask api provider linux version api,i using python ubuntu intalled server i need integrate api applicaion case needed use dll given api provider their example code api integration written visual basic i made search google found examples using ctypes try using cdll pydll caused following error oserror homesomedll invalid elf header one possibility using ironpython much information ironpython sure handle needs completely is available module let use dll python aynthing missing exixting ones it hard upgrade python version,1 if named tuples results tage mylist tpersonid otherwise use indexes results mylist or use tuple unpacking per nate answer note give meaningful name every item unpack you personid age unpack six item tuple,i list tuples every tuple elements corresponding database columns i like make query select attribute mylist attribute something eg personage select age mylist personid is possible query list tuples way thank,3 one solution would list comprehension pattern matching inside tuple mylist age agepersonid mylist personid another way would using map filter map lambda age age filter lambda personid personid mylist,i list tuples every tuple elements corresponding database columns i like make query select attribute mylist attribute something eg personage select age mylist personid is possible query list tuples way thank,3 you use sqlalchemyormvalidates decorator validates name def validatenameself key name assert lenname return name,i using sqlalchemy maximum column length recipe previous question sqlalchemy maximum column length since i upgraded sqlalchemy lengthvalidator cannot installed using following expression instimplextensionsinsert lengthvalidatorcoltypelength the extension attribute defined sqlachemy is way change recipe work thanks honzas,1 yes use filter know position tuple desired column resides if case id first element tuple filter list like filterlambda mylist this return list corresponding tuples if want age pick element want instead filter could also use list comprehension pick element first go you could even unpack right away one result age mylist but i would strongly recommend use dictionaries named tuples purpose,i list tuples every tuple elements corresponding database columns i like make query select attribute mylist attribute something eg personage select age mylist personid is possible query list tuples way thank,2 if free willing change definition error might want consider using variance instead maxminmin you compute variance incrementally true using method deleting values stream variance depend values but with enough values first matter great deal variance variance average variancen become small enough values cluster around fixed value so choose halt variancen epsilon,i creating iterative algorithm monte carlo method the algorithm returns value every iteration creating stream values i need analyze values stop algorithm say returned values withing epsilon i decided implement calculation max min values last values calculate error using formula maxminmin compare epsilon errorepsilon and condition reached stop iterations return result the first harebrained idea use list append new values calculating max min values last values appending then i decided use keeping last values so i remembered deque it good idea since complexity adding deleting ends deque object o but solve problem needing go last values iteration calculate min max then i remembered heapq module it keeps data way efficiently return smallest one every moment but i need smallest largest ones furthermore i need preserve order elements i keep last returned elements algorithm i see i achieve heapq having thoughts mind i decided ask how i solve task efficiently,3 no even could replace class attribute attempt confusing likely break subtle ways if need create validating list need create new object use instead old one,i existing list instance live code references throughout when list reference passed certain function i need ensure items list valid point onwards validate list items attach validation future changes creating new class overrides setitem friends whilst deriving list provides validation required propertylist shown the trouble parts code pointing old list reference part library i cannot really ask developers account breaks backwards compatibility would chew code way unnoticeable first is anyway i change class list item live references list call modified setitem etc methods class propertylistlist def initself validator args kwargs selfvalidator validator superpropertylist selfinitargs kwargs def setitemself key value value selfvalidatorvalue superpropertylist selfsetitemkey value def appendself value value selfvalidatorvalue superpropertylist selfappendvalue def extendself mapselfvalidator superpropertylist selfextendother def insertself index value value selfvalidatorvalue superpropertylist selfinsertindex value,1 i afraid i position provide nice python answer i give outline data structure need use keep items fifo queue keep pointers largest smallest items queue if one leaves queue search queue new largestsmallest amortized cost dependent data if new largestsmallest value enters queue update pointer o assuming data converging work well,i creating iterative algorithm monte carlo method the algorithm returns value every iteration creating stream values i need analyze values stop algorithm say returned values withing epsilon i decided implement calculation max min values last values calculate error using formula maxminmin compare epsilon errorepsilon and condition reached stop iterations return result the first harebrained idea use list append new values calculating max min values last values appending then i decided use keeping last values so i remembered deque it good idea since complexity adding deleting ends deque object o but solve problem needing go last values iteration calculate min max then i remembered heapq module it keeps data way efficiently return smallest one every moment but i need smallest largest ones furthermore i need preserve order elements i keep last returned elements algorithm i see i achieve heapq having thoughts mind i decided ask how i solve task efficiently,2 create subclass deque minvalue maxvalue properties when adding removing entries compare current min maxvalues need rescan deque minmax value removing current min max and adding compare new value current min max update accordingly this optimize scanning deque minmax values,i creating iterative algorithm monte carlo method the algorithm returns value every iteration creating stream values i need analyze values stop algorithm say returned values withing epsilon i decided implement calculation max min values last values calculate error using formula maxminmin compare epsilon errorepsilon and condition reached stop iterations return result the first harebrained idea use list append new values calculating max min values last values appending then i decided use keeping last values so i remembered deque it good idea since complexity adding deleting ends deque object o but solve problem needing go last values iteration calculate min max then i remembered heapq module it keeps data way efficiently return smallest one every moment but i need smallest largest ones furthermore i need preserve order elements i keep last returned elements algorithm i see i achieve heapq having thoughts mind i decided ask how i solve task efficiently,1 how numpy just compare speed import numpy np range b nparange maxa us bmax us write array infinitely b npempty npnan loop bi value the values older iterations get overwritten you get minimummaximum npnanminb npnanmaxb the idea behind nan initialize array nan overwrite one another the nanmin nanmax methods ignore nan,i creating iterative algorithm monte carlo method the algorithm returns value every iteration creating stream values i need analyze values stop algorithm say returned values withing epsilon i decided implement calculation max min values last values calculate error using formula maxminmin compare epsilon errorepsilon and condition reached stop iterations return result the first harebrained idea use list append new values calculating max min values last values appending then i decided use keeping last values so i remembered deque it good idea since complexity adding deleting ends deque object o but solve problem needing go last values iteration calculate min max then i remembered heapq module it keeps data way efficiently return smallest one every moment but i need smallest largest ones furthermore i need preserve order elements i keep last returned elements algorithm i see i achieve heapq having thoughts mind i decided ask how i solve task efficiently,2 you could use python subprocess module subprocess import popen pipe p popen svn log v stoponcopy httpsubversionrepositorycomsvnrepositoryname stdoutpipe stdout stderr pcommunicate this way run svn command want examine stdout perhaps stderr get command result you could use example regex parse retrieved data popen svn log shelltrue stdoutpipecommunicate research rnrprevdsspauthorwssptimestamps timestamp wed okt rev author someuser,i need find first committer branch without checkout entire branches from command line easy svn log v stoponcopy httpsubversionrepositorycomsvnrepositoryname i need python script idea i i checked python subversion bindings i cannot understand even seemed done any help appreciated,2 as refinement unutbu excellent idea could consider using exponentiallyweighted moving variance it computed o time per observation requires o space advantage automatically reducing observation weight observation gets older the following paper relevant formulae link see equations therein finally might want work standard deviation instead variance it simply square root variance advantage units original data this make easier formulate meaningful stopping criterion,i creating iterative algorithm monte carlo method the algorithm returns value every iteration creating stream values i need analyze values stop algorithm say returned values withing epsilon i decided implement calculation max min values last values calculate error using formula maxminmin compare epsilon errorepsilon and condition reached stop iterations return result the first harebrained idea use list append new values calculating max min values last values appending then i decided use keeping last values so i remembered deque it good idea since complexity adding deleting ends deque object o but solve problem needing go last values iteration calculate min max then i remembered heapq module it keeps data way efficiently return smallest one every moment but i need smallest largest ones furthermore i need preserve order elements i keep last returned elements algorithm i see i achieve heapq having thoughts mind i decided ask how i solve task efficiently,3 you could use two fibonacci heaps adding values o deleting ologn in question already suggest heapq module i sure kind heap provides normal one also work smoothly the problem extract minimum one heap maximum solved keeping two heaps since i know heapq module either might able provide comparison function use value instead value key second heap,i creating iterative algorithm monte carlo method the algorithm returns value every iteration creating stream values i need analyze values stop algorithm say returned values withing epsilon i decided implement calculation max min values last values calculate error using formula maxminmin compare epsilon errorepsilon and condition reached stop iterations return result the first harebrained idea use list append new values calculating max min values last values appending then i decided use keeping last values so i remembered deque it good idea since complexity adding deleting ends deque object o but solve problem needing go last values iteration calculate min max then i remembered heapq module it keeps data way efficiently return smallest one every moment but i need smallest largest ones furthermore i need preserve order elements i keep last returned elements algorithm i see i achieve heapq having thoughts mind i decided ask how i solve task efficiently,1 is trying class adbmodel b dbreferencepropertyb class bdbmodel dbreferencepropertya if easy fix probably turn one weak reference class adbmodel b dbreferenceproperty class bdbmodel dbreferencepropertya this crappy solution question i sure better way,how people get around issue a controller say controllerpy imports two models say amodelpy bmodelpy appmodel import amodel appmodel import bmodel now let say amodel wants use function bmodel let say wants get something bmodel id record query amodel i amodel appmodel import bmodel now since controller already imported bmodelpy amodelpy attempting break application can someone tell best way around maybe use proxy or library loader,1 personally i used vpython create simple d graphics animations it easy learn library freely available httpvpythonorg since coordinates already fairly easy incorporate drawing blender bit complicated also incorporates python scripting want spend time learn lastly referencing youtube comments use video cite email get permission if making money presentation odds going fine using videos,i giving presentation fractal antennas take look previous threads november i wanted incorporate animation make presentation easier visualize content i referring most animations would relatively short probably minute long there animations would fantastic fractal mountains the animation continues add new iterations depict complex features mountain range fractal koch curve the animation begins initiator triangle adds new iterations either i slowly bring new fractal next iteration i use model users see iterations branching outward i would prefer latter technique show fractal increase iteration keeping constant length vindicate fractal shrinking size show fractal increase iteration keeping constant size vindicate fractal increasing total perimeter length cell phone animation show cell phone multiple antennas popping simple sketches lines the trouble i never done any animation in programs i already generate coordinates fractals use what best way render animations shortest time possible the presentation almost weeks away blender might option i idea go there great animations nova video might give idea i thanks austin,1 sorry looks like understand question correctly beginning correcting answer responses depth key meta you check take appropriate action class myspiderbasespider def makerequestsfromurlself url return requesturl dontfiltertrue meta starturl url def parseself response responsemeta starturl responsemeta depth something exceeding limit start url else find links yield requests passing start url yield requestotherurl meta starturl responsemeta starturl httpdocscrapyorgentopicsspidershtmlscrapyspiderbasespidermakerequestsfromurl,i trying get scrapy change maximum depth setting different url starturls variable spider if i understand correctly documentation way depthlimit setting global entire framework notion requests originated initial one is way circumvent is possible multiple instances spider initialized starting url different depth limits,1 in call print end main refer variable named value defined main hence error perhaps meant retain value returned call subtract value subtractdummy print the value value i must admit finding code little difficult follow least error message posted quite match code posted i think basic misunderstanding concerns functions return values when call function returns value must assign value something calling scope namespace so wrote subtractdummy value returned assign anything value forgotten instead assign something order use value subtractdummy,def subtractnum string strnum string b string c string large maxa b c small minabc summation inta intb intc mid summation intlarge intsmall mid strmid ascend large mid small descend small mid large print the digits ascending order ascend print the digits descending order descend value intdescend intascend return value def main dummy input type three digit integer pleasen lendummy print error main elif dummyisdigit print error main lendummy dummyisdigit subtractdummy print the value digits descending order minus digits ascending order value main when i input number like i get type three digit integer please the digits ascending order the digits descending order traceback recent call last file usersphilvollmandocumentsnyufreshman fall semesterintro computer programmingassignmentshomeworkpartapy line module main file usersphilvollmandocumentsnyufreshman fall semesterintro computer programmingassignmentshomeworkpartapy line main print the value digits descending order minus digits ascending order value nameerror global name value defined i sure i getting first function runs statements true returned value returned within statement,2 you already proper joã£o methinks the difference joxcxao print joxcxao former calls repr object latter calls str probably unicode case it string represented some examples might make clear print joxcxao decode utf joã£o joxcxao decode utf u joxeo print repr joxcxao decode utf u joxeo notice second third result identical the original ldapusername currently ascii string you see python prompt displaying acsii object shows ascii string unicode objects shown u unicode string key leading u so ldapusername reads joxcxao ascii string following applies joxcxao decode utf u joxeo print joxcxao decode utf to unicode joã£o u joã£o encode utf back ascii joxcxao summed need determine type string use type unsure based decode unicode encode ascii,edit the following print shows intended value sysstdoutencoding sysstdinencoding utf why variable value different print value i need get raw value variable username joxcxao usernamedecode utf encode latin joxeo print usernamedecode utf encode latin joã£o original question i issue querying bd decoding values python i confirmed db nlslang using select propertyvalue databaseproperties propertyname nlscharacterset alutf stores characters beyond uffff four bytes exactly unicode defines utf oracle’s “utf” stores characters sequence two utf surrogate characters encoded using utf six bytes per character osenvironnlslang alutf conndata str sss dbusr dbpwd dbsid sql select username apexusers userid userid cursorexecutesql ldapusername cursorfetchone print ldapusername joxcxao i tried return ldapusernamedecode utf u joxeo unicodeldapusername utf u joxeo u joã£o encode utf joxcxao get queries result back proper joã£o,1 just define columns mixin class sqlalchemyextdeclarative import declarativebase base declarativebase class mymixinobject id columninteger primarykeytrue data columnstring class mymodelmymixin base tablename models class mymodelmymixin base tablename models,i using flask sqlalchemy extension i need define several model classes create tables mysql database the tables differ name field namesdatatypes identical how i define classes tables i thinking inheritance i quite sure exactly would i,3 future import printfunction print lambda x sysstdoutwritesn x is nice cheap dirty hack,i seen similar post however refers python i hoping easier way from reading thread seems best way replace print statements sysstdoutwrites n i hoping nicer way allowed still use print,3 actually quite clearly written docs fabriccontextmanagerspath alters path variable fabriccontextmanagerscd used change remote directory so case def srefresh cd memyproject run python managepy collectstatic trick,i begining use fabric django production server here fabfilepy fabricapi import envhosts memyservernet def srefresh path memyproject run python managepy collectstatic sudo apachectl restart and output fab srefresh memyservernet executing task srefresh memyservernet run python managepy collectstatic memyservernet python open file managepy errno no file directory what i wrong sure i using context manager well,1 you use popular pyglet game library along wxpython cross platform gui library an example httppygletgooglecodecomsvntrunkexperimentalwxtestpy additionally want use pure pyglet use kytten pure python gui library built top pyglet,i want create d game python heavy user interface windows buttons text input etc so far i using pygame simple games the game d mud standard rendering loop draw stuff screen i need user interface interact game entities like sales blacksmith etc i looking something like mix pygame wxpythonpyqtpygtk which libraries i use,3 the easiest would use matplotlibmplotd the principle d animation described httpwwwscipyorgcookbookmatplotlibanimations using d methods described httpmatplotlibsourceforgenetmpltoolkitsmplotdtutorialhtml i teach computer methods physics one activities create koch snowflake using python matplotlib i also group students create d fractals project using python chaco interactivity using matplotlib instead pretty straightforward you also try mayavi another d plotting library python if want create movie need save frame graphics file convert files movie using convert imagemagick mencoder ffmpeg software i probably provide pseudocodesample code i sleepy moment pm i,i giving presentation fractal antennas take look previous threads november i wanted incorporate animation make presentation easier visualize content i referring most animations would relatively short probably minute long there animations would fantastic fractal mountains the animation continues add new iterations depict complex features mountain range fractal koch curve the animation begins initiator triangle adds new iterations either i slowly bring new fractal next iteration i use model users see iterations branching outward i would prefer latter technique show fractal increase iteration keeping constant length vindicate fractal shrinking size show fractal increase iteration keeping constant size vindicate fractal increasing total perimeter length cell phone animation show cell phone multiple antennas popping simple sketches lines the trouble i never done any animation in programs i already generate coordinates fractals use what best way render animations shortest time possible the presentation almost weeks away blender might option i idea go there great animations nova video might give idea i thanks austin,1 you use built set class setabcdefg b setkrtol c sethflsfjg aintersectionb simply amp b pass,for example abcdefg b krtol intersection c hflsfjg c intersaction what easiest way check need true false result,2 def hasintersectiona b return setaisdisjointb,for example abcdefg b krtol intersection c hflsfjg c intersaction what easiest way check need true false result,3 checkout httpgeospatialpythoncompointinpolygonhtml httpgeospatialpythoncompointinpolygononlinehtml,whats way check geopoint within area given shapefile i maneged load shapefile python get,1 this pythonspecific issue appears every language uses binary floating point pretty much every mainstream language from floatingpoint guide because internally computers use format binary floatingpoint cannot accurately represent number like when code compiled interpreted “” already rounded nearest number format results small rounding error even calculation happens some values exactly represented binary fraction output formatting routines often display shortest number closer actual value floatingpoint number masks rounding errors,i came across strange behavior python dictionaries the code i newitem val print newitem val print newitem and result val why it happens numbers others for example becomes becomes becomes becomes,3 this problem related floating point representations binary others pointed but i thought might want something would help solve implied problem python it unrelated dictionaries i i would remove tag if use fixedprecision decimal number purposes i would recommend check python decimal module from page emphaisis mine decimal “is based floatingpoint model designed people mind necessarily paramount guiding principle – computers must provide arithmetic works way arithmetic people learn school ” – excerpt decimal arithmetic specification decimal numbers represented exactly in contrast numbers like exact representations binary floating point end users typically would expect display binary floating point the exactness carries arithmetic in decimal floating point exactly equal zero in binary floating point result e while near zero differences prevent reliable equality testing differences accumulate for reason decimal preferred accounting applications strict equality invariants,i came across strange behavior python dictionaries the code i newitem val print newitem val print newitem and result val why it happens numbers others for example becomes becomes becomes becomes,1 ok i figure class browserqtwebkitqwebpage def initself superqtwebkitqwebpage selfinit def useragentforurlself url return mozilla x linux x rv gecko firefox example thanks httpwwwriverbankcomputingcompipermailpyqtmayhtml httppastebincommb,i trying set header useragent little webkitbrowser i get that piece code selfweb qtwebkitqwebviewself selfrequest qnetworkrequest selfrequestseturlurl selfrequestsetrawheaderuseragent qtcoreqbytearray testuseragent selfrequestsetrawheaderacceptlanguage qtcoreqbytearray en selfwebloadselfrequest in example acceptlanguage set correctly useragent always default value tell please how i set useragent thanks help,1 it nice python module docstring explaining module provides examples use classes this different comments often see beginning file giving copyright license information imo go docstring even argue disappear altogether see eg httphackerbosscomgetridoftemplates as far i know pylint separate code various place docstrings occur disable c the problem disable module scope disabled everywhere module ie get c line missing function class method docstring which arguably nice may want add issue pylint tracker so i suggest adding small missing docstring saying something like high level support soon enough finding useful things put providing examples use various classes functions module necessarily belong individual docstrings classes functions interact something like quick start guide,pylint throws errors files missing docstrings i try add docstrings class method function seems pylint also checks files docstring beginning can disable somehow i would like notified docstring missing inside class function method mandatory file docstring is term legal jargon often found beginning proprietary source file any examples i know whether okay post trivial question separately,3 just recently it actually fairly easy first add new model code specify parameter manytomanyfield yet create auto schemamigration create new table python managepy schemamigration auto yourapp second create datamigration python managepy datamigration yourapp nameofmigration in forwards migration b ormbobjectsall basall ormcobjectscreateaa bb in backwards migration c ormcobjectsall cbasadda finally add parameter manytomanyfield generate another auto schemamigration python managepy schemamigration auto yourapp,i want change manytomany field django app i following models class a class b modelsmanytomanyfielda i want class a class c modelsforeignkeya b modelsforeignkeyb extradata modelsbooleanfielddefaultfalse class b modelsmanytomanyfielda throughc i using south db migrations unfortunately case south propse delete existing appba table recreate new appc is way say south recreate mm table,1 it matter files go they readableexecutable user web server running i know mean djangowsgi sounds like backup file created editor need yes httpdconf configuration file apache some distributions eg debian ubuntu split separate files site server runs if administrator one edit files know already yes need django thirdparty packages,i new web development so gentle and thanks advance i developing windows env deploying linux server w python installed running apache virtual host i using modwsgi i plan serve media files virtual host i django site i ready deploy i stuck every site i go seems outdatedincompleteovermyhead httpsdocsdjangoprojectcomenhowtodeploymentmodwsgi httpwwwdjangobookcomenchapter links newbness the top link seems i need yet i still confused things what file structure look like server i cannot changeedit server files i rely dba i djangowsgi djangowsgi go where i put project relation wsgi files the httpdconf file something server i create another do i need put django way shape form server if and packages like registration defaults again sorry newbness i banging head weeks any helplinks greatly appreciated unless link djangodocs i read thosea lot thanks,2 they quite pythonic to address second question second function file indeed closed automatically that part protocol used statement ironically file guaranteed closed first example second ultimately i would choose use statement according pep expr var block is translated mgr expr exit typemgrexit not calling yet value typemgrentermgr exc true try try var value only var present block except the exceptional case handled exc false exitmgr sysexcinfo raise the exception swallowed exit returns true finally the normal nonlocalgoto cases handled exc exitmgr none none none as see get lot protection case file guaranteed closed matter happens intervening code this also really helps readability imagine put huge block code every time wanted open file,i trying write function gets path returns file content no error handling needed i came following def readallpath f openpath fread fclose return def readallpath openpath f return fread my questions one considered pythonic second function file closed automatically means better way maybe builtin function,3 ddmmyyyy hhmm timestamp without time zone import time datestring ttupletimestrptimedatestring dmy hm timestamptimemktimettuple hhmmss time without time zone can clarify kind object time,i strings represent date ddmmyyyy hhmm i need convert timestamp without time zone starttimeendtiime hhmmss i need convert time without time zone i need order add sql query looks like sql insert into mytable date starttime endtime values params timestamp starttime endtime selfcursorexecutesql params,1 i say second one yes file closed think statement like try f openfilepath code finally fclose about third question way involve opening file a third way without explicitly closing file openfilepathread the file closed file object garbage collected imho explicit better implicit,i trying write function gets path returns file content no error handling needed i came following def readallpath f openpath fread fclose return def readallpath openpath f return fread my questions one considered pythonic second function file closed automatically means better way maybe builtin function,2 in short i used lettuce question applies equally bdd frameworks cucumber this approach considered bad practice since integration tests slower run work maintain unit tests also big advantage gherkin syntax readable nontechnical stakeholders focus business rules whereas unit tests generally deal detailed implementation specifics classfunction level particular interest businessfocused stakeholders there sometimes overlap unit tests integrationacceptance tests general aim find appropriate balance,i like lettuce feel testing could i replace tests doctestsunit tests project lettuce features,3 ordereddict standard python syntax however ordered set keyvalue pairs standard python syntax simply key name value key name value key name value to explicitly get ordereddict ordereddict key name value key name value key name value another alternative sort dictnameitems need sorteddictnameitems,i want use py file like config file so using notation i create dictionary using strings keys definition order lost standard python dictionary my question possible override notation i get ordereddict instead dict i hoping simply overriding dict constructor ordereddict dict ordereddict would work eg dict ordereddict dictname b key value a key value c key value print dictnameitems output b key value a key value c key value,3 i would try following way add c model add extra data fields yet just set fk linked models schema effectively identical default mm table except table name run schemamigration auto app to effectively delete existing table create new one without moving data delete generated migration code forwards backwards methods add forwards dbrenametable yourappnamemmtablename yourappnamec backwards dbrenametable yourappnamec yourappnamemmtablename leave frozen models dict now extend c model generate new schemamigration,i want change manytomany field django app i following models class a class b modelsmanytomanyfielda i want class a class c modelsforeignkeya b modelsforeignkeyb extradata modelsbooleanfielddefaultfalse class b modelsmanytomanyfielda throughc i using south db migrations unfortunately case south propse delete existing appba table recreate new appc is way say south recreate mm table,3 probably easiest way use scipyinterpolateinterpd construct interpolation function assuming data array data x numpyarangedatashape numpyarangedatashape f scipyinterpolateinterpdx data extract values line r c r c numpoints xvalues numpylinspacec c numpoints yvalues numpylinspacer r numpoints zvalues fxvalues yvalues,i numpy array contains image data i would like plot profile transect drawn across image the simplest case profile running parallel edge image image array imdat profile selected point rc simply imdatr horizontal imdatc vertical now i want take input two points rc rc lying inside imdat i would like plot profile values along line connecting two points what best way get values numpy array along line more generally along pathpolygon i used slicing indexing i seem arrive elegant solution consecutive slice elements row column thanks help,3 once realize longest common substring problem describing easy find want eg wikibooks def longestcommonsubstrings s m lens xrangelens longest xlongest x xrangelens xrangelens sx sy mxy mxy mxylongest longest mxy xlongest x else mxy return sxlongestlongest xlongest,i would like python function given list mystrings abcde abcdf abcef abcnn returns string abc ie longest piece contained elements list i solution loops slices mystring compares rest breaks loop whenever first unmatching substring found however i suspect must efficient elegant pythonic way could someone point properly,1 the way described want biggest substring starting point ospathcommonprefix abcde abcdf abcef abcnn abc,i would like python function given list mystrings abcde abcdf abcef abcnn returns string abc ie longest piece contained elements list i solution loops slices mystring compares rest breaks loop whenever first unmatching substring found however i suspect must efficient elegant pythonic way could someone point properly,3 i guess maybe problem lives client side i know connections client tries establish maybe clash expected really transmitted you get connection client probably sends request data if match data send stream urlliburlopen answer match client cancels connection letting broken socket i see two solutions either try send answer line httpxx ok headers back client well somewhere reqheaders or urlliburlopen open regular socket connection but probably tamper headers request host header probably replaced,i trying write python process listens port client connects starts thread following connects remote service httpmagicfm passes data received connected client happens windows media player the story i want listen radio work i cannot i another countryavailable nationally i cannot change proxy settings computer but i server i would like use proxy thanks advance here i far usrbinenv python import socket urllib tcpip tcpport buffersize kbs socketsocketsocketafinet socketsockstream sbindtcpip tcpport slisten conn addr saccept print connection address addr req urlliburlopen httpmagicfm chunk reqreadbuffersize chunk break connsendchunk connclose fails traceback recent call last file magicfmproxypy line connsendchunk socketerror broken pipe,1 what asking impossible config file json syntax sufficient something similar json module import json collections jsonjsondecoderobjectpairshook collectionsordereddict ddecode ab ordereddictu u b,i want use py file like config file so using notation i create dictionary using strings keys definition order lost standard python dictionary my question possible override notation i get ordereddict instead dict i hoping simply overriding dict constructor ordereddict dict ordereddict would work eg dict ordereddict dictname b key value a key value c key value print dictnameitems output b key value a key value c key value,3 class myclass print static block executed static block executed obj myclass see information static variablesfunctions python static class variables python,i relatively new python i would like run block code class like static block java eg class abc execute class is options available python in java write like this executed class time class loaded not every object creation public class staticexample static systemoutprintlnthis first static block thanks,3 to put code directly class definition parallel function definitions class all code directly class gets executed upon creation type class namespace example class test def testfself print testy v test vtestf just fill last bit information method function def also executed like get executed define function global namespace called it happens executing def obviously visible results python objectorientedness quite clever takes bit get head around keep fun language,i relatively new python i would like run block code class like static block java eg class abc execute class is options available python in java write like this executed class time class loaded not every object creation public class staticexample static systemoutprintlnthis first static block thanks,3 i found kernel answer question because i want award bounty someone i op please anyone take kernel elaborate complete answer i get application menu myapp follows ln systemlibraryframeworkspythonframeworkversionsresourcespythonappcontentsmacospython myapp myapp myapppy there two elements required get work the symbolic link must named myapp whatever want appear application menu the symbolic link must point python executable inside system python app bundle it work link usrbinpython example there must clever way create app bundle shell script exploits mechanism robust way,i writing gui application using python qt when i launch application mac first menu item mac menu bar top screen python i would prefer application name name application how i get program name the following demo program creates window two menus python foo i like makes difference users whether i wrote app python cobol instead i want menus myapp foo usrbinpython this example demonstrates unwanted python application menu name mac makes difference whether use pyside pyqt pysideqtgui import pyqtqtgui import import sys app qapplicationsysargv mac menubar application menu always python i want desiredapptitle instead setapplicationname affect mac menu bar appsetapplicationnamedesiredapptitle win qmainwindow need none parent menubar mac get custom menus mbar qmenubar add custom menu menubar foomenu qmenumbar foomenusettitlefoo mbaraddactionfoomenumenuaction winsetmenubarmbar winshow sysexitappexec how i change application menu name mac edit i would prefer continue use system python whatever python user path possible,2 latin aka iso snare delusion decoding random binary gibberish latin works latin codec maps bytes unicode codepoint in case given information french winedtorg hello hello win windows file likely encoded cp guff open frdic rb read z guffdecode latin sum ordc c z count c control characters aliens setc c z ordc aliens setu xc unicodedata import name nameu xc traceback recent call last file stdin line module valueerror name name xc decode cp latin small ligature oe qed update you asked files website the first thing would site recommends read txt file associated dictionary for example large russian dictionary txt file says the dictionary assumes standard windows russian codepage failing try appropriate list cp eastern european latinbased scripts eg polish czech serbian latin script cp cyrillicbased scripts eg russian ukrainian serbian cyrillic script cp western european latinbased scripts eg german french cp greek cp turkish cp hebrew cp arabic cp estonian latvian lithuanian cp vietnamese,i french dictionary file i got winedtorg zip file i like read file memory i i get error unicodedecodeerror ascii codec decode byte xe position ordinal range i also tried using codecs module encoding utf work either codecsopenselftemplatefolderpath selftestlanguage txt rb encoding utf fp wordlist line fp wordlistappendlinestrip selfwordsselftestlanguage wordlist how i read file i also need read dictionary files website how i go,2 you could use one collectionsdefaultdict use update merge rows csv import collections amap collectionsdefaultdictdict row csvdictreadercsv amaprow id row row csvdictreadercsv amaprow id updaterow,i want merge two csv files i read python using following code csvdictreadercsv b csvdictreadercsv amap bmap row amaprow id row row b bmaprow id row now i two dictionaries whose keys id field two csvs what i want take everything amap add values corresponding key values bmap for example amap key dictionary looks like name somename type sometype and i bmap location somelocation and i want location somelocation name somename type sometype is specific function i create new dictionary something similar update appending values instead updating,1 to literally get asking fiddle syntax tree file i think advisable i resist temptation try so go first create module function myexecfile works like builtin execfile except occurrences dictionary displays eg replaced explicit calls dict constructor eg dict of course could directly replace calls collectionsordereddict want intrusive here code import ast class dictdisplaytransformerastnodetransformer def visitdictself node selfgenericvisitnode listnode astlist astcopylocationasttuplelistx astload x x zipnodekeys nodevalues astload namenode astnamedict astload newnode astcallastcopylocationnamenode node astcopylocationlistnode node none none return astcopylocationnewnode node def myexecfilefilename globalsnone localsnone globals none globals locals none locals globals node astparseopenfilenameread transformed dictdisplaytransformervisitnode exec compiletransformed filename exec globals locals with modification place modify behaviour dictionary displays overwriting dict here example testpy collections import ordereddict print dict ordereddict print now run file using myexecfiletestpy yielding output ordereddict note simplicity code touch dictionary comprehensions transformed generator expressions passed dict constructor you need add visitdictcomp method dictdisplaytransformer class given example code straightforward again i recommend kind messing around language semantics did look configparser module,i want use py file like config file so using notation i create dictionary using strings keys definition order lost standard python dictionary my question possible override notation i get ordereddict instead dict i hoping simply overriding dict constructor ordereddict dict ordereddict would work eg dict ordereddict dictname b key value a key value c key value print dictnameitems output b key value a key value c key value,3 adding following pylintrc file master add file directory black list it base name path you may set option multiple times ignoretestspy urlspy migrations,i using south migration django project when i run pylint project i get bunch errors migration files how i exclude migration files pylint i windows system i use filename exclusions pylint options i tried resort adding pylint disablemsgcatwcrefi top migration files it seems kludgy seems last resort documented directive work i get error e unrecognized file option disablemsgcat any help thanks,3 here slightly modified answer henrik multiple nodes ie getelementsbytagname returns one instance images xmlgetelementsbytagnameimageurl images print jointnodevalue ichildnodes tnodetype ttextnode,i creating gui frontend eve online api python i successfully pulled xml data server i trying grab value node called name xmldomminidom import parse dom parsecevexml name domgetelementsbytagname name print name this seems find node output dom element name xed how could i get print value node,1 what expecting the print method outputs specified text stdout case django view served webserver stdout response client console running dev server perhaps log file production server the fact getting errors far strange with view like django blowing saying response returned,def searchrequest print here work in django view method like when call url associated view dont get error but print here doenst work returns nothing also post method like thisi request via jquery how ever index view method returns web page main page i solve problem url conf like urlr include mapsworldurls worldurls urlr index name worldindex urlr save save name worldsave urlr search search name worldsearch call url going directly urlr index name worldindex every time index page returning than removed first url ok ä°t working,1 read row create list dicts keys want id r id name r name r mydictreader,if i using csvdictreader read csv would i go ignore certain columns csv for example idnameaddressnumbercreated somenamesomeaddresssomenumber and i want get id name using reader discarding ignoring rest i tried using fieldnames still reads sets none i noticed csvdictwriter ignore function seems dictreader was hoping elegant way versus reading writing columns i want another csv reading csv using dictreader processing thanks guys,2 ptournaments tournamentobjectsfilterteamplayerp there implicit lookup created every reverse foreign key mm field it either lowercased model class relatedname argument specified so essentially filter says get tournaments related teams related player p,i two levels many many associations django a player belong one many teams and team play one many tournaments given player want know tournaments played following simplified model class tournamentmodelsmodel name modelscharfieldmaxlength blanktrue nulltrue class teammodelsmodel teamname modelscharfieldmaxlength blanktrue nulltrue tournamentsplayed modelsmanytomanyfieldtournament class playermodelsmodel playername modelscharfieldmaxlength blanktrue nulltrue belongstoteam modelsmanytomanyfieldteam in views tried following pl playerobjectsgetplayername andrew flintoff ts plbelongstoteam gives one team team want know tournaments played qslist ts teamqs teamobjectsgetteamname tourn teamqstournamentsplayedall qslistappendtourn context pass queryset list qslist is bettersimpler way,2 sven answer easy way rather inefficient large arrays if dealing relatively small array notice difference wanting profile large eg mb may want try couple approaches you need work pixel coordinates though extra layer complexity there two memoryefficient ways use scipyndimagemapcoordinates need bilinear cubic interpolation want nearest neighbor sampling use indexing directly as example first import numpy np import scipyndimage import matplotlibpyplot plt generate data x npmgrid z npsqrtx npsinx extract line make line num points x these pixel coordinates x num x nplinspacex x num nplinspacey num extract values along line using cubic interpolation zi scipyndimagemapcoordinatesz npvstackxy plot fig axes pltsubplotsnrows axesimshowz axesplotx x ro axesaxis image axesplotzi pltshow the equivalent using nearestneighbor interpolation would look something like import numpy np import matplotlibpyplot plt generate data x npmgrid z npsqrtx npsinx extract line make line num points x these pixel coordinates x num x nplinspacex x num nplinspacey num extract values along line zi zxastypenpint yastypenpint plot fig axes pltsubplotsnrows axesimshowz axesplotx x ro axesaxis image axesplotzi pltshow however using nearestneighbor probably would want samples pixel probably something like instead import numpy np import matplotlibpyplot plt generate data x npmgrid z npsqrtx npsinx extract line make line num points x these pixel coordinates x length intnphypotxx yy x nplinspacex x length nplinspacey length extract values along line zi zxastypenpint yastypenpint plot fig axes pltsubplotsnrows axesimshowz axesplotx x ro axesaxis image axesplotzi pltshow,i numpy array contains image data i would like plot profile transect drawn across image the simplest case profile running parallel edge image image array imdat profile selected point rc simply imdatr horizontal imdatc vertical now i want take input two points rc rc lying inside imdat i would like plot profile values along line connecting two points what best way get values numpy array along line more generally along pathpolygon i used slicing indexing i seem arrive elegant solution consecutive slice elements row column thanks help,3 this simple generator def dictfilterit keys yield dictk dk k keys use like dreader id name bob otherstuff xy id name jen otherstuff xx dictfilterdreader id name print gives id name bob id name jen,if i using csvdictreader read csv would i go ignore certain columns csv for example idnameaddressnumbercreated somenamesomeaddresssomenumber and i want get id name using reader discarding ignoring rest i tried using fieldnames still reads sets none i noticed csvdictwriter ignore function seems dictreader was hoping elegant way versus reading writing columns i want another csv reading csv using dictreader processing thanks guys,2 i issue months ago from tk docs you assign list tags item using tags item configuration option creating item later tag configuration options specified apply items tag basically apply one tag oddnumbered rows different tag evennumbered rows configure tags when create items inside treeview add tags treeinsert end text text tags oddrow this code creates element tree tags argument assigns tag oddrow element once created elements oddrow evenrow tags color tags treetagconfigure oddrow background orange treetagconfigure evenrow background purple,how i set style treeview widgets alternate rows different background colors example rows white backgrounds rows light bluegrey backgrounds i also like set gridlines,3 my take i propose lazy singlepass partition function preserves relative order output subsequences requirements i assume requirements maintain elements relative order hence sets dictionaries evaluate condition every element hence using filter groupby allow lazy consumption either sequence afford precomute naã¯ve implementation likely acceptable split library my partition function introduced similar functions made small library pythonsplit it installable normally via pypi pip install user split to split list base condition use partition function split import partition files filejpg l jpg fileavi l avi imagetypes jpg jpeg gif bmp png images partitionlambda f f imagetypes files listimages filejpg l jpg listother fileavi l avi partition function explained internally need build two subsequences consuming one output sequence force one computed and need keep state user requests store processed yet requested elements to keep state i use two doubleended queues deques collections import deque splitseq class takes care housekeeping class splitseq def initself condition sequence selfcond condition selfgoods deque selfbads deque selfseq itersequence magic happens getnext method it almost like next iterators allows specify kind element want time behind scene discard rejected elements instead puts one two queues def getnextself getgoodtrue getgood cond selfgoods selfbads selfcond else cond selfbads selfgoods lambda x selfcondx return thesepopleft else exit stopiteration n selfseqnext condn return n else thoseappendn the end user supposed use partition function it takes condition function sequence like map filter returns two generators the first generator builds subsequence elements condition holds second one builds complementary subsequence iterators generators allow lazy splitting even long infinite sequences def partitioncondition sequence cond condition condition else bool evaluate bool condition none ss splitseqcond sequence def goods yield ssgetnextgetgoodtrue def bads yield ssgetnextgetgoodfalse return goods bads i chose test function first argument facilitate partial application future similar map filter test function first argument,what best way aesthetically performance perspective split list items multiple lists based conditional the equivalent good x x mylist x goodvals bad x x mylist x goodvals elegant way update actual use case better explain i trying files looks like filejpg l jpg fileavi l avi imagetypes jpg jpeg gif bmp png images f f files flower imagetypes anims f f files flower imagetypes,3 if forking process every page request going kill performance consider python process run daemon communicate using sort queuing ipc forking process expensive operation avoided perrequest basis suggestions interprocess communication gearman zeromq among others,ok i ask when i use shellexec exec commands execute python code php page loads x slower so even localhost empty pages exec system functions load around seconds normal circumstances time around seconds i feel comfortable python trying achieve task html parser extracts info according needs find recursive words index etc etc however slowness functions make think rewrite class php isn efficient way execute python php i prefer writing classes rather rd party parser since satisfy needs,1 the problem named module codepy code built python module werkzeug uses to fix problem rename codepy something else make sure delete codepyc file,using flask werkzeug attempting run code apprundebugtrue i get described error there errors using apprun the error traceback recent call last file codepy line module apprundebugtrue file snipenvlibpythonsitepackagesflaskpyeggflaskapppy line run runsimplehost port self options file snipenvlibpythonsitepackageswerkzeugpyeggwerkzeugservingpy line runsimple werkzeugdebug import debuggedapplication file snipenvlibpythonsitepackageswerkzeugpyeggwerkzeugdebuginitpy line module werkzeugdebugtbtools import getcurrenttraceback renderconsolehtml file snipenvlibpythonsitepackageswerkzeugpyeggwerkzeugdebugtbtoolspy line module werkzeugdebugconsole import console file snipenvlibpythonsitepackageswerkzeugpyeggwerkzeugdebugconsolepy line module class interactiveconsolecodeinteractiveinterpreter attributeerror module object attribute interactiveinterpreter the code codepy flask import flask app flaskname approute news def news pass name main apprundebugtrue steps taken recreate error cd project directory envbinactivate activates virtuanlenv environment see packages python codepy contents envlibpythonsitepackages versions various library used via virtualenv flaskpyegg jinjapyegg pippyegg setuptoolscpyegg werkzeugpyegg things i tried solve problem far helped unfortunately extensive googlingso searching heavy simplification code deleting created virtualenv libraries reinstallation via easyinstall the strange thing last night code worked fine this morning without changing anything i aware code failed properly run thanks much help,3 check surf features part opencv the idea algorithm finding interest points two images you also algorithm computing descriptor image patch around interest point typically descriptor captures distribution edge orientations patch then try find point correspondences e interest point image a try find corresponding interest point image b this accomplished comparing descriptors looking closest matches then set correspondences related geometric transformation detection of course high level explanation the devil details read papers start distinctive image features scaleinvariant keypoints david lowe read papers surf also consider moving question signal image processing stack exchange,i sample image contains object earrings following image httpimgurcomlujz i large candidate set images i need determine one likely contains object eg httpimgurcomybwgc so i need produce score image highest score corresponds image likely contains target object now case i following conditionsconstraints work witharound i obtain multiple sample images different angles the sample images likely different resolutions angles distances candidate images there lot candidate images must reasonably fast i willing sacrifice precision speed means search top instead top fine done manually i manipulate sample images manually outlining object i wish detect candidate images cannot manipulated manually many i real background opencv computer vision i starting scratch my initial thought start drawing rough outline around object sample image then i could identify corners object corners candidate image i could profile pixels around corner see look similar rank sum maximum similarity scores every corner i also sure quantify similar pixels i guess euclidean distance rgb values the problem kind ignores center object in examples corners earrings near gold frame would consider red green blue stones inside earring i suppose i could improve looking pairs corners determining similarity sampling points along line so i questions a does line thinking make sense general something i missing b which specific algorithms opencv i investigate using i aware multiple corner detection algorithms i need one differences optimizing margins i fine fastest c any example code using algorithms would helpful aid understanding my options languages either python c,2 you forgetting pack frame contains listbox fwiw overloading name listbox makes code confusing def listboxlistbox selflistbox framelistbox and also calllistbox listbox class add confusion,so i trying open file pressing button displaying contents listbox this i far i getting listbox display let alone get info listbox usrbinperl w import time tkinter import import tkfiledialog def listboxlistbox def openfile file tkfiledialogaskopenfilename openfile openfile line openfile listboxinsertend line openfile class app def initself parent frame frameparenttitlebuttons framepack rootpackpropagate selfexit buttonframe textquit fgred commandframequit selfexitpacksideleft selfopen buttonframe textopen commandselfcalllistbox selfopenpacksideleft framelistbox frame scrollme scrollbarframelistbox selflistbox listboxframelistbox yscrollcommand scrollmeset scrollmeconfigcommand selflistboxyview scrollmepackside right fill y selflistboxpack selflistboxinsertend code def calllistboxself listboxselflistbox root tk app approot rootmainloop suggestions thanks,1 the xerox library supports linux mac os x windows note bad idea perform action short minute intervals makes modern processors wake regularily you may want use respective operating system apis register callback clipboard changes,i trying create script python collect data put clipboard user preferably save list text file stringarrayvariable work later this work linux versions i would assume ubuntu mac os versions windows versions i sure bit bit systems different ways accessing data clipboard i guess would safe make work bit versions people running bit versions fall back onto bit version os the tricky part apart work mentioned os i would like script run long user stop runs data copied clipboard user copied list text file stringarrayvariable of course time limit user input data clipboard i thinking loop scanning clipboard every second every milliseconds check content changed copy otherwise copy is unified way module different os would better write separate scripts task various os the thing part bigger project i would like make work linux mac windows three options covered use python code used across mentioned os rest scriptproject would ideal am i asking much general script concerning work linux mac windows,2 you could use gui toolkit qt get portable clipboard api that said might little overkill use whole gui toolkit unless course also going use make gui that said clipboard apis dealing plain text reasonably simple make abstraction for instance os x use pyobjc installed along os x get plaintext contents clipboard appkit import nspasteboard launchservices import pb nspasteboardgeneralpasteboard text pbstringfortypekuttypeutfplaintext cpu architectures a bit native app bit os accessing clipboard bit one if need support architectures os writing driver windows okay ship bit binary linux likely versions os x reasonably safe ship bit version macs since mid bit cpus os support since leopard a python script linux probably executed python installation distribution package manager whose bitness match system necessarily need worry,i trying create script python collect data put clipboard user preferably save list text file stringarrayvariable work later this work linux versions i would assume ubuntu mac os versions windows versions i sure bit bit systems different ways accessing data clipboard i guess would safe make work bit versions people running bit versions fall back onto bit version os the tricky part apart work mentioned os i would like script run long user stop runs data copied clipboard user copied list text file stringarrayvariable of course time limit user input data clipboard i thinking loop scanning clipboard every second every milliseconds check content changed copy otherwise copy is unified way module different os would better write separate scripts task various os the thing part bigger project i would like make work linux mac windows three options covered use python code used across mentioned os rest scriptproject would ideal am i asking much general script concerning work linux mac windows,1 it looks like interested objectrowlevel security features allow owners accounts view data i would refer previous so answer topic well tutorial i working auth url dispatch built around answer specifically might want look objectsecurity demo linked github project well docs explaining resource trees part rendered html site pyramid authorization stored items httpsgithubcommmerickelpyramidauthdemo httpmichaelmerickelorgprojectspyramidauthdemo if questions understanding resources i happy elaborate,i really little idea acl work i know pretty cool could save lots time pain but currently bit lost all example pyramid use traversal i exclusively use url dispatch i sure understand i build ressource tree structure here sample code class questionfactoryobject def initself request selfacl default selfuid authenticateduseridrequest selfqid requestmatchdictget id selfqid selfquestion requestdbquestionsfindone id objectidselfqid strselfquestionget owner selfuid selfaclappendallow userid view the thing works but i define new factory every type ressource i certain i supposed know ressource i trying access trough url dispatch factory i see something like accountsaccount owners viewable anyone messagesmessage owners configsconfig admin pagespage admins viewable anyone that said i structure root account message config page each factory special acl the thing accounts main page it id anything also accountsnew also special case it id view create new item i using restful style getputdeletepost requirement i sure i supposed match url ressource right acl automatically if i define root special factory like problems edit i got work exception things i finally think i understand purpose traverse for example url commentsfedanew commentscommentnew we could node ressource tree even nodes the rootfactory get inspected first according traversal it get comments attribute rootfactory comment comment factory new commentfactory object i use factory dict example michael it looks pretty much like class ressourcefactoryobject def initself parent name selfacl selfname name selfparent parent selfuid parentuid selflocale parentlocale selfdb parentdb selfreq parentreq this base ressource object on every steps copies information parent new child i could certainly bubble attribute context parent parent uid great the reason i using dict attribute i add make works comments for reasons create commentfactory return need key so root factory pretty much look like class rootfactoryobject def initself request selfacl default selfreq request selfdb requestdb selfuid authenticateduseridrequest selflocale requestparamsget locale en def getitemself key key questions return questionfactoryself questions elif key pages return pagefactoryself pages elif key configs return configfactoryself configs elif key accounts return accountfactoryself accounts return self item found rootfactory return return new factory since i base code michael code second parameter factory constructor i certain keep questionfactory well aware handle questions need name factory it already know name class questionfactoryressourcefactory def initself parent name ressourcefactoryinitself parent name selfaclappendallow gadmin view selfaclappendallow gadmin edit selfaclappendallow gadmin create selfaclappendallow gadmin delete selfaclappendallow everyone create def getitemself key key read return self selfqid key selfquestion selfdbquestionsfindone id objectidselfqid strselfquestionget owner selfuid loginfo allowd user selfuid selfaclappendallow selfuid view selfaclappendallow selfuid edit selfaclappendallow selfuid delete return self so almost logic go in init i set acl work questions getitem work questionsid since i return getitem past ressourcefactory point unless i return new factory special case the reason context object database object my context handles multiple things like user id locale acl done i fresh context object ready use it removes logic views i could probably set events query locale uid really fits if i need anything new i edit rootfactory ressourcefactory copy child factory that way something change accross views redundancy,3 you simply use definition binomial coefficients math import factorial tri factorialn factorialk factorialn k k rangen n rangeheight,just sake exercise i trying find way express pascal triangle python list comprehension iterative way i representing pascal triangle python tri as i iteratively i need somehow access previously calculated lines triangle i trying without declaring local variable so far i tri linesappend linesijlinesij j xrange else linesi lines enumerateheight any ideas edit as pointed brc really bad example andor use list comprehensions,3 use callback def handleresultrpc url code goes def createcallbackrpc url return lambda handleresultrpc url rpcs url urls rpc urlfetchcreaterpcdeadline rpccallback createcallbackrpc url urlfetchmakefetchcallrpc url rpcsappendrpc rpcs rpc apiproxystubmapuserrpcwaitanyrpcs rpcsremoverpc,rpcs url urls rpc urlfetchcreaterpcdeadline urlfetchmakefetchcallrpc url rpcsappendrpc lenrpcs rpc apiproxystubmapuserrpcwaitanyrpcs res rpcgetresult resstatuscode something result rpcsremoverpc how determine url received response,1 you stuffed indentation line possibly misuse tabs source file as displayed so never incremented loop never exited,i ran program linux python ran fine returning decimal values i run python windows work gives blank space memory error i figure whyi need run windows program calculate stock equity roe thanks the csv file needed run program import csv csvname rawinputenter csv name sbuxfile csvreaderopencsvname delimiter quotechar list data row row row row avgequity roe roe range count grab data numerical values csv row sbuxfile count count row row elif count row row elif count row row elif count row row perform calculations average equity roe avgequityappendroundfloatrowa roeappendfloatrowa floatrowa roeappendfloatrowa floatrowa floatrowa floatrowa floatrowa floatrowa else avgequityappendroundfloatrowa floatrowa roeappendfloatrowa floatrowa roeappendfloatrowa floatrowa floatrowa floatrowa floatrowa floatrowa floatrowa print naverage equity stravgequity n print roe method strroe n print roe method strroe,1 as explicitly iterative approaches wanted i would use iterator def bincoeffnumnone math import factorial num none iterlambda true false waiting godot else xrangenum yield factorialn factorialk factorialn k k rangen with generator build list bc listbincoeff get certain maximum bc bincoeff lenbc break print bc,just sake exercise i trying find way express pascal triangle python list comprehension iterative way i representing pascal triangle python tri as i iteratively i need somehow access previously calculated lines triangle i trying without declaring local variable so far i tri linesappend linesijlinesij j xrange else linesi lines enumerateheight any ideas edit as pointed brc really bad example andor use list comprehensions,1 obeying slightly insane restrictions imposed upon simplifications i think incorporated dsetdefaultj sumdlendmaxi range j j enumerate at least shorter version gets rid conditional expressions of course still insane,just sake exercise i trying find way express pascal triangle python list comprehension iterative way i representing pascal triangle python tri as i iteratively i need somehow access previously calculated lines triangle i trying without declaring local variable so far i tri linesappend linesijlinesij j xrange else linesi lines enumerateheight any ideas edit as pointed brc really bad example andor use list comprehensions,1 operator import itemgetter cols name id tuple keys want keep valuesforitemgettercols dictreaderinput print dictzipcols valuesford dict zipping cols values,if i using csvdictreader read csv would i go ignore certain columns csv for example idnameaddressnumbercreated somenamesomeaddresssomenumber and i want get id name using reader discarding ignoring rest i tried using fieldnames still reads sets none i noticed csvdictwriter ignore function seems dictreader was hoping elegant way versus reading writing columns i want another csv reading csv using dictreader processing thanks guys,1 you able get behaviour strsplit if live rather complex parsing like ignoring double quotes preceded back slash shlexsplit might looking shlexsplitmystr a b c de fe gh i jk l o p q r,when using python string function split anybody nifty trick treat items surrounded doublequotes nonsplitting word say i want split white space i mystr a btc de fettgh i jk l to p q r mystrsplit a b c de fe gh i jk l o p q r i like treat anything within doublequotes single word even white spaces embedded would like end a b c de fe gh i jk l o p q r or least i strip doublequotes a b c de fe gh i jk l o p q r any nonregex suggestions,3 splitdata itempartition if splitdata pieces want splitdata splitdata otherwise splitdata whole string splitdata splitdata empty strings,when i try print spliteddata i getting error message indexerror list index range on hand spliteddata working fine i want insert data mysql spliteddata mysql columns spliteddata mysql column values i want spliteddata empty insert empty string mysql but i getting indexerror list index range how avoid error please help thank here code which working fine i get error message spliteddata empty def cleandata data datareplace data datareplace data datareplace data datareplace data datareplace data datareplace data datareplacebr return data xmlfindall httpwwwmediawikiorgxmlexporttext researchr msinfobox film ttext k mgroup kencode utf cleandata cleank clean function used replace garbase data text filterdata cleandatasplitlinestrue splited data lines filterdatapop indexitem enumeratefilterdata spliteddata itemsplit print spliteddataspliteddata spliteddata used mysql column spliteddata used mysql values spliteddata data u music u jatin sharman u cinematography u n u released u film datedfy,1 here idea needs fleshing maybe work it uses wsgirefhandlersbasehandler wsgiref part standard library from wsgiref docs you consult docstrings source code additional information attempting create customized basehandler subclass code modpython handler modules btw here i would start modpython import apache wsgirefhandlers import basehandler class mywsgihandlerbasehandler def initself apachereq basehandlerinitself selfapachereq apachereq def writeself data selfapachereqwritedata override required methods basehandler see httpdocspythonorglibrarywsgirefhtmlwsgirefhandlersbasehandler wsgiapp createyourwsgiapp def handlerreq wsgihandler mywsgihandlerreq wsgihandlerrunwsgiapp return apacheok idea pretty hackish you could handler code also use werkzeug wsgi testing module pass request wsgi app get werkzeug response back write response apache something like modpython import apache werkzeugtest import client werkzeugwrappers import baseresponse wsgiapp createyourwsgiapp def handlerreq c clientwsgiapp baseresponse resp cgetsomehowgettheurlfromreq cpost post request reqwriterespdata find way write headers well return apacheok,i wrote wsgi application i need deploy server however i given server already modpython installed i allowed remove modpython since modpython applications running already one option i considered installing modwsgi alongside modpython however i went sources found bad idea apparently modwsgi modpython mix well another option i considered installing modfastcgi deploying using fastcgi i would love hear someone better idea break current modpython applications running server,1 also go read httpcodegooglecompmodwsgiwikiintegrationwithdjango watch httpcodegooglecompmodwsgiwikiwheretogethelptmconferencepresentations the latter includes django examples talks bit locations permissions etc the first even linked document django documentation,i new web development so gentle and thanks advance i developing windows env deploying linux server w python installed running apache virtual host i using modwsgi i plan serve media files virtual host i django site i ready deploy i stuck every site i go seems outdatedincompleteovermyhead httpsdocsdjangoprojectcomenhowtodeploymentmodwsgi httpwwwdjangobookcomenchapter links newbness the top link seems i need yet i still confused things what file structure look like server i cannot changeedit server files i rely dba i djangowsgi djangowsgi go where i put project relation wsgi files the httpdconf file something server i create another do i need put django way shape form server if and packages like registration defaults again sorry newbness i banging head weeks any helplinks greatly appreciated unless link djangodocs i read thosea lot thanks,2 tabs rule same argument nested loops want bring outer loop back level tip if want convert old spaceriddled python code tabs use tabout utility available executable httpwwwtextpadcomaddons,i always used tabs indentation i python programming but i came across question so someone pointed python programmers use spaces instead tabs minimize editortoeditor mistakes how make difference are reasons one would use spaces instead tabs python or simply true should i switch editor insert spaces instead tabs right away keep going like i used,3 you use modpython modwsgi together long python version modpython linked static python library run ldd command modpythonso file ldd modpythonso find links libpythonxyso build modwsgi use python version ensuring similarly linked libpythonxyso update version x modwsgi explicitly refuses start modpython also loaded in order modpython modwsgi used together certain features modwsgi crippled as modpython old meaningfully updated various problems used anything new longer trying support used together,i wrote wsgi application i need deploy server however i given server already modpython installed i allowed remove modpython since modpython applications running already one option i considered installing modwsgi alongside modpython however i went sources found bad idea apparently modwsgi modpython mix well another option i considered installing modfastcgi deploying using fastcgi i would love hear someone better idea break current modpython applications running server,1 rob without regexes regexp solution simple mystr a btc de fettgh i jk l to p q r print refindallr w mystr a b c de fe gh i jk l o p q r,when using python string function split anybody nifty trick treat items surrounded doublequotes nonsplitting word say i want split white space i mystr a btc de fettgh i jk l to p q r mystrsplit a b c de fe gh i jk l o p q r i like treat anything within doublequotes single word even white spaces embedded would like end a b c de fe gh i jk l o p q r or least i strip doublequotes a b c de fe gh i jk l o p q r any nonregex suggestions,1 sqlalchemy import sqlalchemyorm import sqlalchemyextdeclarative import declarativebase import random base declarativebase class customerbase tablename customer id columninteger primarykeytrue name columnunicode orders relationshiporder backrefcustomer class orderbase tablename order id columninteger primarykeytrue customerid columninteger foreignkey customerid amount columninteger e createenginesqlite echotrue basemetadatacreatealle session sessione sessionaddall customernamecd orders orderamountrandomrandint j xrangerandomrandint xrange amountsum funcsumorderamountlabel totalamount amount sessionqueryordercustomerid amountsum groupbyordercustomerid orderbyamountsumdesc limit subquery b sessionquerycustomer amountctotalamount joinamount amountccustomeridcustomerid print aname b guidelines pattern httpwwwsqlalchemyorgdocsormtutorialhtmlusingsubqueries overall start sql first,i seem find good documentation i list users order amounts i want display users top order amount totals i trouble creating query sufficiently extracts data sqlalchemy is better way approach customers amount dbsessionqueryordercustomer funcsumorderamountlabel totalamount groupbyordercustomer orderbyfuncdesctotalamount limit b zipcustomers amount print aname stramount,2 i found way i sure best one anyway i mixed information mako recipe simpleform documentation pylons pylonsformencodestate inside pylonsdecorators i came following i subscribe newrequest event like configaddsubscribermyprojectsubscribersaddlocalizer pyramideventsnewrequest define addlocalizer pyramid import formencode import api formencodeapi def addlocalizerevent request eventrequest localizer ingetlocalizerrequest hasattrlocalizer oldtranslate localizeroldtranslate localizertranslate backup default method requestlocalizer localizer requesttranslate lambda x localizertranslateintranslationstringx set formencode language request formencodeapisetstdtranslationlanguagesit this depend user selection whatever def multiplegettextvalue try default translation first localizeroldtranslateintranslationstringvalue value it looks like translation failed let try formencode formencodeapistdtransvalue return localizertranslate multiplegettext,i know i run following code python shell import formencode ne formencodevalidatorsnotempty formencodeapisetstdtranslationlanguagesit try netopython except formencodeapiinvalid e print stre get printed inserire un valore now i get result im pyramid app using pyramidsimpleform formencode,2 this matplotlibpyplotscatter as quick example import matplotlibpyplot plt import numpy np generate data nplinspace nppi x npsint npcost pltscattertxcy pltshow,i variables xy change time i want plot x vs color ticks based value eg highest values tick color dark green lowest value dark red intermediate values color scaled green red can done matplotlib python,3 if mind using java apache james imap provides rfc compliant data access layer imap it fully optimized performance yet appears tested working condition otherwise they also provide full imap server everything apache license able use modify way feel like,i need write imap wrapper around messaging system with complexity imap protocol rather use existing library heavy lifting are imap servers libraries frameworks available php python alternatively imap server would allow write driver use custom messaging system backend,1 you probably better using advanced gui toolkit tk standard library available everywhere as really simple example import tkinter root tkintertk rootwithdraw hide main window optional textinclipboard rootclipboardget print textinclipboard,i trying create script python collect data put clipboard user preferably save list text file stringarrayvariable work later this work linux versions i would assume ubuntu mac os versions windows versions i sure bit bit systems different ways accessing data clipboard i guess would safe make work bit versions people running bit versions fall back onto bit version os the tricky part apart work mentioned os i would like script run long user stop runs data copied clipboard user copied list text file stringarrayvariable of course time limit user input data clipboard i thinking loop scanning clipboard every second every milliseconds check content changed copy otherwise copy is unified way module different os would better write separate scripts task various os the thing part bigger project i would like make work linux mac windows three options covered use python code used across mentioned os rest scriptproject would ideal am i asking much general script concerning work linux mac windows,2 try building c extensions inplace source directory setuppy buildext running selftestpy testsrunpy,i pil installed required libraries i think during installation shows tkinter support available jpeg support available zlib pngzip support available freetype support available littlecms support available however i run selftestpy i get pil core support installed tkinter support installed jpeg support ok zlib pngzip support ok freetype support installed littlecms support installed ie detecting pil core freetype littlecms i installed following packages centos using python libjpeg libjpegdevel zlib zlibdevel freetype freetypedevel lcms lcmsdevel pil installed pip install pil however selftest run source code offical pil website any ideas,3 why reactorrun called example tac files tac files meant loaded twistd commandline tool runs reactor running reactor something done whatever bit code serving mainpoint program most twisted code effectively plugin kind meant operate context larger system in particular case tac files never meant run standalone python programs job produce application object attached bunch service objects get started reactor runs it important tac file much work example service implementations question may need separate code needs run privileged unprivileged exacting process work performed tac may haphazardly executed wrong user how i use deferred inside twisted application without calling reactorrun deferred simply mechanism managing chains callbacks you need call reactorrun indeed even reactor use for example twistedinternetdefer import deferred deferred def helloresult print fired result return result daddcallbackhello deferred print deferred dcallback fired print deferred current result that said many apis return deferred need reactor work order eventually call callback for example twistedinternettask import deferlater twistedinternet import reactor deferlaterreactor lambda addcallbackhello deferred sitting around forever waiting fire unless somebody runs reactor nothing print happens but reactor already running example running interactive example python twistedconchstdio rather python would see deferred get called back second later interactive prompt already running reactor what differences twisted scripts vs applications these really formally separated terms any python script potentially import code twisted use way wants hard say particular property applies scripts except computer programs if twisted application mean tac file plugin difference kind code separated part builds service code top level tac file plugin part actually work privilegedstartservice startservice stopservice implementations services said toplevel code sets also code runs context ie driven twistd need run reactor since one set run twistd such code must also therefore careful avoid importing twistedinternetreactor twistd provides ability use different reactors select poll epoll kqueue etc importing reactor twistd chance set break feature,i feel like i understanding things writing twisted applications tac files using deferred objects py scripts easy calling reactorrun end i seen reactorrun used twisted application sample code can someone explain reactorrun called twisted applications erroneous conclusion i use deferred objects inside twisted application perhaps without calling reactorrun general differences writing twisted scripts vs applications,3 your code properly displays legend matplotlib mac os x provided matplotlib put interactive mode beginning pltion the code ends pltshow instance upgrading matplotlib might also help a last possible solution would indeed plot line separately label pltplotsingle line data label construction etc plot legend pltlegendloc best,i nightmare time trying label data pyplot i currently plotting data like pltplotdata data array column total costs columns sub costs i would like add legend label data lists appropriately i seem get legend work though pltlegend column column etc loc things like work if i plot column individually stops working correctly reason i look forward thank advice edit rangedays dataappendtotalcosti cost returns retval construction gas wage pltylabel cost us dollars plttitle economic cost time pltplotdata pltlegend total construction gas wage loc legend blank edit instead code different locations program i reorganized centralized everything with changes legend started working everything seems resolved i idea issue though pltplotdata pltlegend total cost construction cost gas cost wage cost loc pltgridfalse pltxlabel time days pltylabel cost us dollars plttitle economic cost time print close graph continue using model pltshow,1 with patch works like charm fieldpy fieldpy import sys import xmlrpclib copy import deepcopy cgi import escape cstringio import stringio filename getattrvalue filename valuegetid mimetype getattrvalue contenttype mimetype value valuedata elif isinstancevalue xmlrpclibbinary value valuedata elif isinstancevalue fileupload shasattrvalue filename filename valuefilename elif isinstancevalue filetype shasattrvalue name,based answer bad interaction zope xmlrpc at image mutator i expect able following plone proxy xmlrpclibserverproxy httpadminadminlocalhostplonescreenshotpng verbosetrue wrappeddata xmlrpclibbinaryopenfilenameread proxysetimagewrappeddata instead i get traceback archetypes value file string xmlrpclibbinarynstringvaluenmembernstructvaluenfaultnmethodresponsen i suspect i done something make at unhappy i sure the traceback comes line archetypes fieldpy see httpsgistgithubcom anyone know going also full code example httpsgithubcomaclarklifeplonexmlrpc,1 from lxml documentation lxml parse local file http url ftp url i see https sentence anywhere i assume supported an easy workaround would retrieve file using library support https urllib pass retrieved document string lxml,i using lxml parse html files given urls for example link httpsabccomdef htmltree lxmlhtmlparselink my code working well cases ones http however i found every https url lxml simply gets ioerror does anyone know reason and possibly correct problem btw i want stick lxml switch beautifulsoup given i already got quick finished programme,3 i know happening i get errors https probably supported you easily work around urllib though lxml import html urllib import urlopen htmlparseurlopen httpsduckduckgocom,i using lxml parse html files given urls for example link httpsabccomdef htmltree lxmlhtmlparselink my code working well cases ones http however i found every https url lxml simply gets ioerror does anyone know reason and possibly correct problem btw i want stick lxml switch beautifulsoup given i already got quick finished programme,3 import operator ops operatoror operatorand print opsoptrue false,python eval quite slow i need evaluate simple boolean expression logical operators like true false i thousands line data eval huge bottleneck terms performance it really slow any alternative approaches i tried creating dict possible expression combinations expected output really ugly i following code moment eval true operator false,3 one way done using list comprehension xletter x widelist letter x b c e f,i would like reshape following list widelist b c e f long format longlist b c e f how achieved efficiently python,1 try nested list comprehension widelist b c e f longlist k v k sublist widelist v sublist longlist b c e f note last group changed match pattern first two groups instead f use f instead otherwise need special case logic groups follow pattern,i would like reshape following list widelist b c e f long format longlist b c e f how achieved efficiently python,3 the common source errors one indentation change previous method generally lines actual error reported the common source problem copypasting something nets either tabbedspaced indented moreless your editor warn stuff like for example komodo ide provides arrows indicate indentation level so load fancy editor use spot problem there so post python ides,i models class tourmodelsmodel namemodelscharfieldmaxlength countmodelssmallintegerfield priceunitcodemodelsforeignkeypriceunit pricemodelscharfieldmaxlength descriptionmodelstextfield actiondatemodelsdatetimefieldautonowtrueeditablefalse actionusercodemodelsforeignkeyusereditablefalse statustypecodemodelsforeignkeystatustype class imagesmodelsmodel image modelsimagefielduploadtogallery tourmodelsforeignkeytour i wanna design form add tour set images tour form formmodel class tourformmodelform class meta model tour i viewspy def myviewrequestkey galleryformset inlineformsetfactorytourimages requestmethod post form tourformrequestpost requestfiles formisvalid tourformsave formsetgalleryformsetrequestpost requestfilesinstancetour formsetisvalid formsetsave else form tourform formsetgalleryformset return rendertoresponse airagencyaddtourhtml form form formset formset template form method post enctypemultipartformdata dirrtl csrftoken formasp formsetmanagementform form formset form endfor input typesubmit form error unexpected indent viewspy line line ifformisvalid course i changed code alotbut every time error line code line changing every time wrong thanks advance,1 the posted solutions build new smaller dicts larger fully populated dicts returned dictreader something like necessary dictreader api intentionally designed skip fields here excerpt source unlike basic reader prefer return blanks typically wind dict full none values row row selfreadernext dictzipselffieldnames row you see every fieldname gets assigned dictionary without filtering fwiw hard make variant dictreader desired behavior model existing csv source,if i using csvdictreader read csv would i go ignore certain columns csv for example idnameaddressnumbercreated somenamesomeaddresssomenumber and i want get id name using reader discarding ignoring rest i tried using fieldnames still reads sets none i noticed csvdictwriter ignore function seems dictreader was hoping elegant way versus reading writing columns i want another csv reading csv using dictreader processing thanks guys,1 my guess would easiest javascript widgetit easier wedge admin tons examples work daring venture slightly question though i say i pretty nervous trying write regexes parse humangenerated responses complexity particularly mode submission text messages smartphone text my guess typos ruin day though obviously i know kind data collecting,i building django app let researchers send text messages study participants parse responses while parsing say yn numbers going pretty easy need send messages need complex responses which i think means regular expressions all easy enough thing i want however let researchers test regex see various responses so i text box regex text box test response button see happens if i building app would easy way within confines django admin app,1 i suppose multiplefilehandlerapproach may slower performed write file system every close operation if writing small chunks time slower may writing less bytes sector size letting lower levels os file system block device handle buffering writing ensuring waste lots writes smaller sector size,in python process opening file handler slow compared actual write time one large file one file handler import marshal bigdatastructure j range range f open bigfile w marshaldumpbigdatastructure f fclose multiple smaller files multiple file handlers row enumeratebigdatastructure f openstri w marshaldumprow f fclose,1 it clear catplusplus solution evaluate boolean expression here example pyparsing wiki examples page boolean expression parserevaluator here test cases script p true q false r true test p q p notp q q p r q p r p q r p q r false test res boolexprparsestringt print n res boolres n,python eval quite slow i need evaluate simple boolean expression logical operators like true false i thousands line data eval huge bottleneck terms performance it really slow any alternative approaches i tried creating dict possible expression combinations expected output really ugly i following code moment eval true operator false,1 if i read question correctly confused event handling callback functions need something dupchk value returned dialog box yet defined user clicks apath what i think missing place store file directory chosen filechooser selfapath need spawn filechooser dialog box button clicked but apath button know path yet give callback function works path you could give callback function opens dialog box filechooser calls dupchk function result filechooser available mechanism another button embedded window alwaysopen text field suitable typing relabel apath button check a duplicates the filechooser callback stores selfapath button callback calls dupchkselfapath update learning gui programming ooprogramming might significant hurdle class hierarchies gui widgets perfectly suited objectoriented design project seems like approachable size start good job object oriented programming simply way bundle custommade types actions types you create window object store attributes related window methods work specific window object or create widget object provides data common graphical widgets x position y position width height whether widget grow shrink x y dimensions visible invisible etc operations common widgets setting x y position width height grow shrink controls visible invisible etc then every new graphical element inherits widget base functionality provide new data operations specific new type widget made to keep individual graphical controls simple gui programming toolkits provide events every graphical element generator consume you provide callbacks functions called events occur most gui programming environments work differently usual programming difference sometimes called inversion control in essence gui toolkit sets everything calls functions provide your main case init function sets widgets callbacks starts event loop waits events calls callback functions the callback mechanisms let reuse widget classes different tasks different places depending upon callbacks install a button might quit application another button might launch missiles start web browser unlike java python everything needs done inside class if top level program deserve class put class you might want put class anyway easier embed future programs program needs solve small task likely embedded need overly complicate programming task with mind i written small particularly pretty little demonstration tool shows display two filechooserbuttons connect fileset signal get filename filepicker question store results filepicker variable choosing i think last portion trouble c connect callbacks like char filea fileb hyptotheticalwidget widget newhypotheticalwidgetfoo hyptheticalconnectwidget ampcallback ampfilea ampfilea ampfileb would suffice select pointer wanted updated python makes little tricky way add amp pass pointer what pass array modify array callback the little demo i wrote uses pass reference trick make easy use callback function write two different variables depending upon widget connected usrbinpython import gtk def pickfilewidget filename filename widgetgetfilename print filename updateentryboxes def updateentryboxes easettextfilea ebsettextfileb fileanone selected filebnone selected win gtkwindowgtkwindowtoplevel box gtkhbox ba gtkfilechooserbuttonfile a baconnectfileset pickfile filea bb gtkfilechooserbuttonfile b bbconnectfileset pickfile fileb ea gtkentry eb gtkentry boxaddba boxaddea boxaddbb boxaddeb updateentryboxes winaddbox winshowall gtkmain i hope helpful,as python first oo language i cannot understand i need run dialog put return variable passed another function how i get around variable variables case dgetpath def dgetpathself widget datanone print needs filled output dialog data def dupchkself widget datanone print i figure dgetpath easy data def initself selfmainwin gtkwindowgtkwindowtoplevel selfmainwinsetpositiongtkwinposcenter selfapath gtkbuttona path selfapathconnectclicked selfdgetpath apath selfaopath gtkbuttona path selfaopathconnectclicked selfdgetpath aopath selfdupchka gtkbuttondupe check a check a path duplicates selfdupchkaconnectclicked selfdupchk dupchka selfdupchkasettooltiptextcheck a path duplicates using md sum selfbpath gtkbuttonb path selfbpathconnectclicked selfdgetpath bpath selfbopath gtkbuttonb path selfbopathconnectclicked selfdgetpath bopath selfdupchkb gtkbuttondupe check b check b path duplicates selfdupchkbconnectclicked selfdupchk dupchkb selfdupchkasettooltiptextcheck b path duplicates using md sum,1 you mention running memory merge lot neurons at least experience several hundred neurons sufficient toy programs wrote cs courses you probably want creating separate files store separate neurons certainly files store neurons the io overhead directory lookups file open read close small amounts io drastically weigh loading saving nontrivial amounts neurons of course thinking neurons go quickly matter perhaps simplest implementation called but mine i look hard trying build good datastructures neurons perhaps neurons given level described integer select neuron type array integers doubles describe perneuron characteristics list level descriptions could easily written separate files single file whichever easier if neurons change types within level fully connected levels might find sparse matrix storage designs useful larger data structure describe neurons maybe real question i improve storage neurons update i think even neurons justifies making combined storage format i created tiny files dropped caches test coldstart reread one individually it took seconds read files it took seconds read single file containing data files if network starts cold year maybe matter much but network starts cold dozen times per day might grow resent simpler storage format,in python process opening file handler slow compared actual write time one large file one file handler import marshal bigdatastructure j range range f open bigfile w marshaldumpbigdatastructure f fclose multiple smaller files multiple file handlers row enumeratebigdatastructure f openstri w marshaldumprow f fclose,1 yield best used function returns sequence want iterate sequence need every value memory for example i python script parses large list csv files i want return line processed another function i want store megabytes data memory i yield line python data structure so function get lines file might look something like def getlinesfiles f files line f preprocess line yield line i use syntax lists access output function line getlinesfiles process line i save lot memory usage,i know yield works i know permutation think math simplicity but yield true force when i use a simple good example better,3 your trouble far i tell mainloop inside oninit function halting program flow i speak worked like honest able enter mainloop app oninit returned true the oninit could return false case app fully initialize common single instance apps lock file example a common approach pseudocode would look like app wxpysimpleapp f framenone some title for this frame fshow appmainloop down code follow it execute code top level windows closed prior app instance something else calls wxgetappexitmainloop,we using python wxpython v project and working fine now upgrading python wxpython our project compiled fine new version but project one stage code destroy current window create amp open new window and i noticed code creating new window execute while old version executing in following code it displaying message doread open window but display message doread while old python version displaying message read means executing code i found come line selfmainloop oninit function new project but coming thus executing next line old project here code close existing window selfdestroy print doread create new window app app print doread appframesavecontents class appwxapp application class def oninitself wxinitallimagehandlers resetoptions setoptions selfframe pdtpframe selfframesettitlestdgettitle selfframeshow selfsettopwindowselfframe selfmainloop return true def main start pdtp main window application app app name main main,1 another use network client use yield generator function roundrobin multiple sockets without complexity threads for example i hardware test client needed send rgb planes image firmware the data needed sent lockstep red green blue red green blue rather spawn three threads i generator read file encoded buffer each buffer yield buf end file function returned i endofiteration my client code looped three generator functions getting buffers endofiteration,i know yield works i know permutation think math simplicity but yield true force when i use a simple good example better,1 this remove returns none most builtin functions python mutate value return none therefore outer join trying join nothing together,i playing codingbatcom i found really easy problem solve i started trying play newbie code golf given nonempty string int n return new string char index n removed the value n valid index char original string ie n range lenstr inclusive missingchar kitten → ktten missingchar kitten → itten missingchar kitten → kittn das code def missingcharstr n return join joinstrsplitremovestrn oddly python interpret why,3 not direct answer question seems like hard way slice def missingchars n return sn sn,i playing codingbatcom i found really easy problem solve i started trying play newbie code golf given nonempty string int n return new string char index n removed the value n valid index char original string ie n range lenstr inclusive missingchar kitten → ktten missingchar kitten → itten missingchar kitten → kittn das code def missingcharstr n return join joinstrsplitremovestrn oddly python interpret why,3 simply put yield gives generator you use would normally use return function as really contrived example cut pasted prompt def getoddnumbersi return range def yieldoddnumbersi x range yield x foo getoddnumbers bar yieldoddnumbers foo bar generator object yieldoddnumbers xcf barnext barnext barnext as see first case foo holds entire list memory it big deal list elements want list million not huge memory eater also costs lot time build time function called in second case bar gives generator a generator iterablewhich means use loop etc value accessed all values also stored memory time generator object remembers looping last time called itthis way using iterable say count billion count billion store billion numbers count again pretty contrived example probably would use itertools really wanted count billion this simple use case generators as said used write efficient permutations using yield push things call stack instead using sort stack variable generators also used specialized tree traversal manner things further reading python wiki httpwikipythonorgmoingenerators pep generators httpwwwpythonorgdevpepspep,i know yield works i know permutation think math simplicity but yield true force when i use a simple good example better,3 just put various libraries packages root directory app the root directory automatically added app syspath if wish put lib directory root write module adds directory end syspath import import anything lib using virtualenv option i personally think gains much since run virtualenv production devappserver emulates production environment,i currently developing python project growing i may implement webapp gae future as project growing i pruning potentially reusable code separate packages amp modules present pythonpath do advice structure project reusable packages fit nicely gae project future looking recommendations gae project structure posts seem fairly flat best way go what rd party packagesmodules is best bite bullet use virtualenv beginning thanks much prembo,3 i know existing library atom rss feeds usually indicated link tag head section link relalternative typeapplicationrssxml hrefhttplinktofeed link relalternative typeapplicationatomxml hrefhttplinktofeed straightforward way would downloading parsing url html parser like lxmlhtml getting href attribute relevant link tags,i huge list urls task feed python script spit feed urls is api library code help,2 in step iterating query object this results one fetch rpc per objects returned inefficient timewise instead call fetchn query object n maximum number results return single rpc it also benefit limiting number results search right i search i app get stuck processing nearly every record step it also completely unnecessary convert keys strings add keys set fine for worth though i personally find searches particularly useless i realise rank items match terms first inevitably followed piles piles irrelevant results you could search simply one query equality filter search term,in lieu fulltext search gae i using solution return resultset sorted first keyword relevance secondly date though second sorting could anything really it feels bit bulky i concerned performance scale i looking optimization suggestions different approach altogether the secondary sorting important use case since given search likely multple results relevance measured number keyword matches preserving original query ordering adds lot complexity right any ideas step get list keys match search term resultskeylist searchterms b c user search query split list strings query search term add results list yields list keys frequency occurance indicating relevance item searchterms subquery someentityallkeysonlytrue subqueryfilter searchindex item searchindex stringlistproperty filters subqueryorder datecreated returneditem subquery resultskeylistappendstrreturneditem step group list frequency maintaining original order return dictionary keys frequency occurrence groupedresults defaultdictint key resultskeylist groupedresultskey sortedresults known set creates empty list match frequency rangelensearchterms sortedresultsappend using original results ordering construct array results grouped ordered descending frequency key resultskeylist key known continue frequency groupedresultskey sortedresultslensearchterms frequencyappendkey knownaddkey combine single list orderedkeylist l sortedresults orderedkeylistextendl del orderedkeylistoffset del orderedkeylistlimit result someentitygetorderedkeylist,1 depending wellformed information feeds eg are links form http do know href link tags are links feeds going feeds etc i recommend anything simple regex straightup parsing module extract links feeds as far parsing modules go i recommend beautiful soup though even best parser go faresp case i mentioned guarantee links data going links feeds additional crawling probing,i huge list urls task feed python script spit feed urls is api library code help,1 golfed version missingcharlambda snsnsn,i playing codingbatcom i found really easy problem solve i started trying play newbie code golf given nonempty string int n return new string char index n removed the value n valid index char original string ie n range lenstr inclusive missingchar kitten → ktten missingchar kitten → itten missingchar kitten → kittn das code def missingcharstr n return join joinstrsplitremovestrn oddly python interpret why,1 your first model indexed properties second one it surprising first takes time reduce setting properties unindexed dave suggests does mean cannot expect gae perform insert data properties i misunderstand anything app engine performs insert fine prepared spend time cost operations,version class actionlogdbmodel action dbstringproperty timeslice dbintegerproperty tracecode dbstringproperty profile log belong who facebookid dbstringproperty user facebook id ip dbstringproperty user ip address when time dbdatetimepropertyautonowaddtrue time event what url dbstringproperty imgurl secret dbstringproperty secret imgurl instance tag dbstringproperty tag referurl dbstringproperty tag link where weburl dbstringproperty user refer url domain dbstringproperty refer url domain bsp dbstringproperty refer url bsp execute log actionlogactionaction tracecodetracecode facebookidfacebookid ipip timeslicetimeslice urlurl secretsecret tagtag referurlreferurl weburlweburl domaindomain bspbsp dbputlog version class actionlogdbmodel tracecode dbstringproperty url dbstringproperty secret dbstringproperty use dict like text property store implicit properties desp mydictproperty time dbdatetimepropertyautonowaddtrue time event execute log actionlog secret secret url url tracecode tracecode desp action action facebookid facebookid ip ip tag tag referurl referurl weburl weburl dbputlog these two versions code basically task however version code use ms perform simple put operation yellow red light cpu time google app engine in contract version code use ms both test hrd datastore on ms datastore version code use ms version code use ms i image version slower compare version since use key index however hard believe difference huge it also surprising google app engine cannot handle easy task does mean cannot expect gae perform insert data properties i misunderstand anything thx,1 it sounds like want cms rather reinventing wheel probably use existing one,what quick n easy way add edit function static html i could save html textproperty admin area edit entity variable contains html good solution recommend better solution i considering using tool appengineadmin model content admincontent change static html doctype html public wcdtd html transitionalen saved urlhttpwwwteknatorseeddaconsultmanagementserviceshtml htmlhead meta contenttexthtml charsetwindows httpequivcontenttype meta contentmicrosoft frontpage namegeneratorhead body bgcolorffffff text center p table border width tbody tr tdfont color size faceverdana arial helvetica sansserifbmanagement servicesbfont pfont size faceverdana arial helvetica sansserifbmanagementforhireb to editable page doctype html public wcdtd html transitionalen saved urlhttpwwwteknatorseeddaconsultmanagementserviceshtml htmlhead meta contenttexthtml charsetwindows httpequivcontenttype meta contentmicrosoft frontpage namegeneratorhead body is solution would support could make contructive criticism i might wrong since i might right save html textproperty i thinking simple models like class admincontentappengineadminmodeladmin model content listfields body editfields body class contentmodel body dbtextpropertyverbosename text then every page id dynamic content i finish case real quick solution dirty since variable mix markup actual content i try make real html editor instead thank suggestions,1 i think one approach might consider subclassing queryset basically allows query parent model return instances child models result queryset it would let queries like modelsserviceobjectsall return results like following sshserviceinstance telnetserviceinstance telnetserviceinstance for examples check links blog post linked httpjazstudiosblogspotcomdjangomodelinheritancewithhtml however use approach declare service model abstract example granted introducing extra join overall i found subclassing queryset work pretty well returning mixed set objects queryset anyway hope helps joe,i building personal project django train i love django i miss skills i basic requirements i know python i carefully read django book twice thrice my goal create simple monitoring service djangobased web interface allowing check status nodes servers each node multiple services the application checks availability service node my problem i idea represent different types services database i thought two solutions single service model servicetype field big mess fields i great experience database modeling looks bad multiple service models like solution i idea i reference different services field this short excerpt modelspy file i removed everything related problem djangodb import models create models class servicemodelsmodel port modelspositiveintegerfield class meta abstract true class sshserviceservice username modelscharfieldmaxlength pkey modelstextfield class telnetserviceservice username modelscharfieldmaxlength password modelscharfieldmaxlength class generictcpserviceservice pass class genericudpserviceservice pass class nodemodelsmodel name modelscharfieldmaxlength various fields services modelsmanytomanyfieldservice of course line manytomanyfield bogus i idea put place service i honestly searched solutions i heard generic relations triplejoin tables i nt really understand things moreover english native language coming database structure semantics knowledge understanding i read limited problem,3 for start use django multitable inheritance rather abstract model currently your code would become djangodb import models class servicemodelsmodel port modelspositiveintegerfield class sshserviceservice username modelscharfieldmaxlength pkey modelstextfield class telnetserviceservice username modelscharfieldmaxlength password modelscharfieldmaxlength class generictcpserviceservice pass class genericudpserviceservice pass class nodemodelsmodel name modelscharfieldmaxlength various fields services modelsmanytomanyfieldservice on database level create service table rows linked via one one relationships separate tables child service the difficulty approach something like following node nodeobjectsgetpknodeid service nodeservicesall do something service the service objects access loop parent type if know child type beforehand access child class following way djangocoreexceptions import objectdoesnotexist try telnetservice servicetelnetservice except attributeerror objectdoesnotexist you chose wrong child type telnetservice none if know child type beforehand gets bit trickier there hackymessy solutions including servicetype field parent model better way joe j mentioned use subclassing queryset the inheritancemanager class djangomodelutils probably easiest use read documentation really nice little bit code,i building personal project django train i love django i miss skills i basic requirements i know python i carefully read django book twice thrice my goal create simple monitoring service djangobased web interface allowing check status nodes servers each node multiple services the application checks availability service node my problem i idea represent different types services database i thought two solutions single service model servicetype field big mess fields i great experience database modeling looks bad multiple service models like solution i idea i reference different services field this short excerpt modelspy file i removed everything related problem djangodb import models create models class servicemodelsmodel port modelspositiveintegerfield class meta abstract true class sshserviceservice username modelscharfieldmaxlength pkey modelstextfield class telnetserviceservice username modelscharfieldmaxlength password modelscharfieldmaxlength class generictcpserviceservice pass class genericudpserviceservice pass class nodemodelsmodel name modelscharfieldmaxlength various fields services modelsmanytomanyfieldservice of course line manytomanyfield bogus i idea put place service i honestly searched solutions i heard generic relations triplejoin tables i nt really understand things moreover english native language coming database structure semantics knowledge understanding i read limited problem,3 one way scan db single pass building ten selecions here pseudo code query whole database records meeting user criteria buildup first ten encountered results list if additional records arise decide randomly whether include nth item included probability pn random n if included randomly choose previous selection swap randrange in python result n row enumeratecursorexecuteuserquery n resultappendrow elif random n randrange resulti row alternatively database nonqueryable huge high percentage records expected match user criteria could randomly select records entire db found ten unique records match criteria result set lenresult record randomchoiceentiredb record result matchesrecord usercriteria resultaddrecord the latter algorithm one two used python randomsample function if run queries though number matching records fit memory whole thing boils randomsamplelistcursorexecuteuserquery,i writing program select items randomly database criteria type based users choice so user chooses type program choose items type user chooses type program choose items type items type user chooses type program choose items type one types must extra item get items type gets extra question random so this done n number types user choose any suggestions way achieved by way i trying build random generator result random time ps i coding python language code fine ps i already able select items using sql where clause that real problem problem i gotten items selected types i select exactly items proportions ie types chosen items type exactly extra items two types,2 def debugval loggingdebug debug r val return val lengthofwire debugcoilvolume wirecrosssection don forget set logger appropriately,so i writing python scripts help simple calculations wireradius awg coilinnerradius coilouterradius coillength coilvolume coilouterradius coilinnerradius coillength print coilvolume strcoilvolume wirecrosssection wireradius print wirecrosssection strwirecrosssection lengthofwire coilvolume wirecrosssection print lengthofwire strlengthofwire now i want script print intermediate components i see going if i screw also let pinpoint line math wrong numbers become nonsensical however clearly dry since i writing variable name twice three times lengthofwire coilvolume wirecrosssection print lengthofwire strlengthofwire if i typing interactive shell would automatically spit values intermediate components back lengthofwire coilvolume wirecrosssection quite nice assignment statement preserved meaning i know exactly next value however problem putting interactive shell making changes rerunning whole script dozen calculations long tedious is way achieve functionality scripts run via python scriptpy,2 an improved version ignacio function import logging def debugval labelnone prints debug message consisting value optional label label none loggingdebug debug r val else loggingdebug debug r label val return val lengthofwire debugcoilvolume wirecrosssection labelwire length,so i writing python scripts help simple calculations wireradius awg coilinnerradius coilouterradius coillength coilvolume coilouterradius coilinnerradius coillength print coilvolume strcoilvolume wirecrosssection wireradius print wirecrosssection strwirecrosssection lengthofwire coilvolume wirecrosssection print lengthofwire strlengthofwire now i want script print intermediate components i see going if i screw also let pinpoint line math wrong numbers become nonsensical however clearly dry since i writing variable name twice three times lengthofwire coilvolume wirecrosssection print lengthofwire strlengthofwire if i typing interactive shell would automatically spit values intermediate components back lengthofwire coilvolume wirecrosssection quite nice assignment statement preserved meaning i know exactly next value however problem putting interactive shell making changes rerunning whole script dozen calculations long tedious is way achieve functionality scripts run via python scriptpy,1 basically need get form select item from items where type order by random limit see select random sqlite table this work postgresql this well let database work need figure pass types arguments dependent database library for multiple i probably run several queries dynamically generate one multiple unions you like select item from items where type type order by random limit union all select item from items where type type order by random limit which generated python like types type type type limit lentypes careful types set limit sql select item from items where type order by random limit limit unionedsql union all joinsql rangelentypes result cursorexecuteunionedsql types the syntax might wrong i used db api it give idea though you mentioned problem need select exactly items including extras proportion work exactly maybe would better hardcode limit select items trim list getting db,i writing program select items randomly database criteria type based users choice so user chooses type program choose items type user chooses type program choose items type items type user chooses type program choose items type one types must extra item get items type gets extra question random so this done n number types user choose any suggestions way achieved by way i trying build random generator result random time ps i coding python language code fine ps i already able select items using sql where clause that real problem problem i gotten items selected types i select exactly items proportions ie types chosen items type exactly extra items two types,1 there nbmyelement elements nbmyelement so last line really toxml if text nbmyelement use text node element subfirstchildnodevalue,i xml looks like nbmyelement param oxygen valuenbelement i using following python code sub domgetelementsbytagname nbmyelement ifsubgetattributenodeparamnodevalue oxygen value subgetelementsbytagname nbmyelement toxml but last line throwing index range execption how i get value enclosed tag also attributes,1 suggestion read header rows first make sure works proceeding none rest code needs indented consider writing separate function group traveltimes file list lists once working traveltimes reader grouper create new sta file print headers write timegroups build program stepbystep making sure expect step don try easily able track issue lies my quick edit script uses itertoolsgroupby grouper it little advanced grouping function stateful tracks state mutable list def makestationfilestraveltimes headerlines gives staxxtgrid files required locd open headerlines r f headers freadlines def stationcounterline cnt stateful station counter keeps count mutable list linestrip cnt return cnt opentraveltimes r timesfile station group groupbytimesfile stationcounter open stas station w outputfile header headers outputfilewrite sntn headerstrip line group linestartswith outputfilewrite line this code untested i sample data hopefully get gist,i got little script working nicely hope help find problem i two starting files traveltimes contains lines i need column file every row number the lines i need separated line starts whitespaces header lines contains three header lines outputfile i want get files stas what inside every file contain header lines i want append group lines contained traveltimes file one different group lines every file every group lines made rows column so far script creates files header lines mixes everything i mean writes something i want any idea def makestationfilestraveltimes headerlines gives staxxtgrid files required locd stacounter open headerlines r filein data fileinreadlines range open stas stacounter w outputfiles stacounter data values istrip outputfileswrite sntn values open traveltimes r timesfile collector line timesfile linestartswith break outputfileswrite line,1 i tried building dictionary using dictionary value template i get values dictionary why the values also keyvalue pairs listid dict listsummaryitems listid listid k v dictitems key k name total value v endfor endfor listid value listsummaryitems listid listid name valuename value valuevalue endfor,i processing queryset view get summary data need able iterate resultant dataset template i ok key single value building dictionary using items work key value pairs using idtotal listsummaryitems tr class cycle row row tdidtd tdtotaltd tr endfor the problem i i need key value i need multiple values i tried building dictionary using dictionary value template i get values dictionary what appropriate datastructure build make work i thought temporary model making custom template tag access sub dictionary values i think must better way process queryset data prior feeding view my view code listslistsobjectsfilteruseriduserid listsummary make dictionary wil iterate template the dictionary total spend deal list lists id listid name listdealname price listnormalprice quantity listquantity total price quantity try listitemlistsummaryid oldtotallistitem total listsummaryid name name total oldtotal total except listsummaryid name name total total context listsummary listsummary return rendertoresponselistshtml context any help would much appreciated many thanks advance rich,1 you wait browserdocument status interactive that wait js condition documentreadystate interactive,there long list images page there ajax load images button application bottom page activated automatically user scrolling page i want scroll page end selenium make sure button load images bottom page the script could elegant solution point browserexecutescript setintervalfunction windowscrollby invisibleshowmorecounter true browserfindelementbyidshowmoretext invisibleshowmorecounter invisibleshowmorecounter invisibleshowmorecounter break timesleep it scrolls page bottom check showmore element seconds sure cycle needed though so thing successfully scrolls page stuck browserfindelementbyidshowmore page fully loaded including images takes lot time so dom lot images take minutes load i sure page fully loaded looks likely goes first iteration cycle stay findelementbyid minutes go successfully finished the question possible command find method wait images finish downloading test take minutes pass setting browserimplicitlywait seem kind relevant seem help,1 first save image tempfile remove local file one tempfile import namedtemporaryfile shutil import copyfileobj os import remove tempfileobj namedtemporaryfilemode wb suffix jpg pilimage open tmpmyfilejpg rb copyfileobjpilimagetempfileobj pilimageclose remove tmpmyfilejpg tempfileobjseek second set temp file response per stackoverflow question flask import sendfile approute path def viewmethod response sendfiletempfileobj asattachmenttrue attachmentfilename myfilejpg return response,i using flask application i like send image dynamically generated pil client without saving disk any idea,3 consider using pdb monitor execution i doubt want logging statements workedout calculation doug hellmann nice workedout example using pdb,so i writing python scripts help simple calculations wireradius awg coilinnerradius coilouterradius coillength coilvolume coilouterradius coilinnerradius coillength print coilvolume strcoilvolume wirecrosssection wireradius print wirecrosssection strwirecrosssection lengthofwire coilvolume wirecrosssection print lengthofwire strlengthofwire now i want script print intermediate components i see going if i screw also let pinpoint line math wrong numbers become nonsensical however clearly dry since i writing variable name twice three times lengthofwire coilvolume wirecrosssection print lengthofwire strlengthofwire if i typing interactive shell would automatically spit values intermediate components back lengthofwire coilvolume wirecrosssection quite nice assignment statement preserved meaning i know exactly next value however problem putting interactive shell making changes rerunning whole script dozen calculations long tedious is way achieve functionality scripts run via python scriptpy,1 fortunately kind guys opencv check samples folder opencvsamplescppmatchingtomanyimagescpp compile give try wih default images the algorithm easily adapted make faster precise mainly object recognition algorithms split two parts keypoint detectionamp description adn object matching for many algorithmsvariants wich play directly opencv detectiondescription done siftsurforbgfttstarfast others for matching brute force hamming etc some methods specific given detection algorithm hints start crop original image interesting object covers much possible image area use training sift accurate laziest descriptor fast good combination precision accuracy gftt old quite unreliable orb newly added opencv promising speed accuracy the results depend pose object image if resized rotated squeezed partly covered etc try sift simple task ie appears almost sizerotationetc descriptors cope well orb may yet opencv release try download latest opencv trunk compile httpscoderosorgsvnopencvtrunk so find best combination trial error for details every implementation read original paperstutorials google scholar good start,i sample image contains object earrings following image httpimgurcomlujz i large candidate set images i need determine one likely contains object eg httpimgurcomybwgc so i need produce score image highest score corresponds image likely contains target object now case i following conditionsconstraints work witharound i obtain multiple sample images different angles the sample images likely different resolutions angles distances candidate images there lot candidate images must reasonably fast i willing sacrifice precision speed means search top instead top fine done manually i manipulate sample images manually outlining object i wish detect candidate images cannot manipulated manually many i real background opencv computer vision i starting scratch my initial thought start drawing rough outline around object sample image then i could identify corners object corners candidate image i could profile pixels around corner see look similar rank sum maximum similarity scores every corner i also sure quantify similar pixels i guess euclidean distance rgb values the problem kind ignores center object in examples corners earrings near gold frame would consider red green blue stones inside earring i suppose i could improve looking pairs corners determining similarity sampling points along line so i questions a does line thinking make sense general something i missing b which specific algorithms opencv i investigate using i aware multiple corner detection algorithms i need one differences optimizing margins i fine fastest c any example code using algorithms would helpful aid understanding my options languages either python c,2 your first line choices variable apostrophe end,the following code gives error token error eof multiline statement what error how i fix import easygui import time namegui easyguienterboxmsg enter name title name query default gian situationgui easyguienterboxmsg please enter situation title thought logsituation thoughtsgui easyguienterboxmsg please enter thoughts title thought logthoughts emotionsgui easyguienterboxmsg please enter emotions n sad mad hurt depressed anxious tense etc title thought logemotions behaviorgui easyguienterboxmsg please enter behavior title thought logbehavior thinkingtrapsgui easyguienterboxmsg please identify thinking traps n n fortunetelling this occurs predict things turn badly however cannot predict future magic ball n n mindreading this happens believe know others thinking assume thinking worst us however cannot mindread know others thinking n n labeling sometimes talk mean way use single negative word describe however kind thinking unfair complex summed single word n n filtering this happens take note bad things happen ignore good things n n overestimating this happens believe something unlikely occur actually happen n n catastrophizing this imagine worst possible thing happen unable cope n n overgeneralizing this use words like always never describe situations events this problematic way thinking take situation events account n n title thought logidentify your thinking traps baivar easyguichoicebox msg please identify thinking traps n n title thought logidentify your thinking traps choices fortunetelling this occurs predict things turn badly however cannot predict future magic ball n n mindreading this happens believe know others thinking assume thinking worst us however cannot mindread know others thinking n n labeling sometimes talk mean way use single negative word describe however kind thinking unfair complex summed single word n n filtering this happens take note bad things happen ignore good things n n overestimating this happens believe something unlikely occur actually happen n n catastrophizing this imagine worst possible thing happen unable cope n n overgeneralizing this use words like always never describe situations events this problematic way thinking take situation events account n n altbehaviorgui easyguienterboxmsg please enter alternative behavior title thought logalt behavior altthoughtsgui easyguienterboxmsg please enter alternative thoughts title thought logalt thoughts yeargui easyguienterboxmsg enter current year title current year default monthgui easyguienterboxmsg enter current month title current month daygui easyguienterboxmsg enter current day title current day timehourgui easyguienterboxmsg enter current hour title current hour timeminutegui easyguienterboxmsg please enter current minutes title current minute ampmgui easyguienterboxmsg please enter either pm title am or pm file open thought record txt filewritenamegui n filewritedaygui filewrite filewritemonthgui filewrite filewriteyeargui filewrite n filewrite your situation filewritesituationgui filewrite n filewrite your thoughts filewritethoughtsgui filewrite n filewrite your emotions filewriteemotionsgui filewrite n filewrite your behavior filewritebehaviorgui filewrite n filewrite thinking traps filewritethinkingtrapsgui filewrite n filewrite alternative bahvior filewritealtbehaviorgui filewrite n filewrite alternative thoughts filewritealtthoughtsgui filewrite n filewrite n fileclose this error showed i added following lines code baivar easyguichoicebox msg please identify thinking traps n n title thought logidentify your thinking traps choices fortunetelling this occurs predict things turn badly however cannot predict future magic ball n n mindreading this happens believe know others thinking assume thinking worst us however cannot mindread know others thinking n n labeling sometimes talk mean way use single negative word describe however kind thinking unfair complex summed single word n n filtering this happens take note bad things happen ignore good things n n overestimating this happens believe something unlikely occur actually happen n n catastrophizing this imagine worst possible thing happen unable cope n n overgeneralizing this use words like always never describe situations events this problematic way thinking take situation events account n n i running python mac os x,3 you missing closing quote fortunetelling line that easy find syntax highlighting becomes different,the following code gives error token error eof multiline statement what error how i fix import easygui import time namegui easyguienterboxmsg enter name title name query default gian situationgui easyguienterboxmsg please enter situation title thought logsituation thoughtsgui easyguienterboxmsg please enter thoughts title thought logthoughts emotionsgui easyguienterboxmsg please enter emotions n sad mad hurt depressed anxious tense etc title thought logemotions behaviorgui easyguienterboxmsg please enter behavior title thought logbehavior thinkingtrapsgui easyguienterboxmsg please identify thinking traps n n fortunetelling this occurs predict things turn badly however cannot predict future magic ball n n mindreading this happens believe know others thinking assume thinking worst us however cannot mindread know others thinking n n labeling sometimes talk mean way use single negative word describe however kind thinking unfair complex summed single word n n filtering this happens take note bad things happen ignore good things n n overestimating this happens believe something unlikely occur actually happen n n catastrophizing this imagine worst possible thing happen unable cope n n overgeneralizing this use words like always never describe situations events this problematic way thinking take situation events account n n title thought logidentify your thinking traps baivar easyguichoicebox msg please identify thinking traps n n title thought logidentify your thinking traps choices fortunetelling this occurs predict things turn badly however cannot predict future magic ball n n mindreading this happens believe know others thinking assume thinking worst us however cannot mindread know others thinking n n labeling sometimes talk mean way use single negative word describe however kind thinking unfair complex summed single word n n filtering this happens take note bad things happen ignore good things n n overestimating this happens believe something unlikely occur actually happen n n catastrophizing this imagine worst possible thing happen unable cope n n overgeneralizing this use words like always never describe situations events this problematic way thinking take situation events account n n altbehaviorgui easyguienterboxmsg please enter alternative behavior title thought logalt behavior altthoughtsgui easyguienterboxmsg please enter alternative thoughts title thought logalt thoughts yeargui easyguienterboxmsg enter current year title current year default monthgui easyguienterboxmsg enter current month title current month daygui easyguienterboxmsg enter current day title current day timehourgui easyguienterboxmsg enter current hour title current hour timeminutegui easyguienterboxmsg please enter current minutes title current minute ampmgui easyguienterboxmsg please enter either pm title am or pm file open thought record txt filewritenamegui n filewritedaygui filewrite filewritemonthgui filewrite filewriteyeargui filewrite n filewrite your situation filewritesituationgui filewrite n filewrite your thoughts filewritethoughtsgui filewrite n filewrite your emotions filewriteemotionsgui filewrite n filewrite your behavior filewritebehaviorgui filewrite n filewrite thinking traps filewritethinkingtrapsgui filewrite n filewrite alternative bahvior filewritealtbehaviorgui filewrite n filewrite alternative thoughts filewritealtthoughtsgui filewrite n filewrite n fileclose this error showed i added following lines code baivar easyguichoicebox msg please identify thinking traps n n title thought logidentify your thinking traps choices fortunetelling this occurs predict things turn badly however cannot predict future magic ball n n mindreading this happens believe know others thinking assume thinking worst us however cannot mindread know others thinking n n labeling sometimes talk mean way use single negative word describe however kind thinking unfair complex summed single word n n filtering this happens take note bad things happen ignore good things n n overestimating this happens believe something unlikely occur actually happen n n catastrophizing this imagine worst possible thing happen unable cope n n overgeneralizing this use words like always never describe situations events this problematic way thinking take situation events account n n i running python mac os x,1 this seems like version mismatch mysqlserver pythonmysqldb which version ubuntu using if recently shifted try using ubuntu the easiest way solve problem would update ubuntu atleast install matching versions mysqlserver pythonmysqldb i using ubuntu mysqlserver version ubuntu pythonmysqldb version build hope helps,i trying setup environment ubuntu making shift mswindows it course python i setup mysql mysqldb ubuntu software centre import dabo import mysqldb works ok no error but establishing connection says mismatch versions mysqldb amp mysql importerror mysqldb version gamma mysql version final how i solve complete traceback traceback recent call last file stdin line module file dabovmdhotelpy line module empconn dabodbdconnectionempci file dabodbdconnectionpy line init selfconnection selfopenconnectionkwargs file dabodbdconnectionpy line openconnection return selfconnectinfogetconnectionforcecreateselfforcecreate kwargs file dabodbdconnectinfopy line getconnection return selfbackendobjectgetconnectionself kwargs file dabodbdbmysqlpy line getconnection import mysqldb dbapi file mediapythpythonlibsitepackagesmysqldbinitpy line module versioninfo mysqlversioninfo importerror mysqldb version gamma mysql version final thanks advance vineet,1 i second waffle paradox recommending beautiful soup parsing html getting link relalternate tags feeds referenced the code i usually use beautifulsoup import beautifulsoup parser def detectfeedsinhtmlinputstream examines open text stream html referenced feeds this achieved detecting link tags reference feed html param inputstream arbitrary opened input stream funcread method type inputstream input stream eg open file url return list tuples url feedtype rtype listtuplestr str check really input stream hasattrinputstream read raise typeerroran opened input stream given instead typeinputstream result get textual data html input stream html parserinputstreamread find links alternate attribute feedurls htmlfindalllink relalternate extract url type feedlink feedurls url feedlinkgethref none valid url url resultappendurl return result,i huge list urls task feed python script spit feed urls is api library code help,2 xrange returns iterator this different range returns list both behave mostly fashion use like use range yes yes,i seen markov chain gibberish detector written response another question stackoverflow i would like convert php i looking someone i confused portions python code i knowledge i looked python docs confuses even what php equivalent yield def ngramn l return n grams l normalizing filtered normalizel start range lenfiltered n yield joinfilteredstartstart n what exactly xrange there pecl extension however i would prefer pure php implementation would possible counts xrangek xrangek row enumeratecounts floatsumrow j xrangelenrow rowj mathlogrowj what assert is equivalent throwing exception assert mingoodprobs maxbadprobs python pickle essentially serialize pickledump mat counts thresh thresh open gibmodelpki wb thanks help edit typos,1 change settings like emailhost smtpgmailcom emailhostuser user emailhostpassword yourpassword emailport emailusetls true then try python managepy shell djangocoremail import emailmessage email emailmessage mail test this test somemailsomethingcom emailsend this return status means worked,i trying get django work gmail smtp server send mails i always get traceback any help appreciated settingspy emailhost smtpgmailcom emailhostuser usergmailcom emailhostpassword yourpassword emailport emailusetls true python shell djangocoremail import emailmessage email emailmessage mail test this test somemailsomethingcom emailsend traceback recent call last file console line module file homefiodorovichenvsfdictlibpythonsitepackagesdjangocoremailmessagepy line send return selfgetconnectionfailsilentlysendmessagesself file homefiodorovichenvsfdictlibpythonsitepackagesdjangocoremailbackendssmtppy line sendmessages sent selfsendmessage file homefiodorovichenvsfdictlibpythonsitepackagesdjangocoremailbackendssmtppy line send emailmessagemessageasstring file usrlocallibpythonsmtplibpy line sendmail raise smtpsenderrefusedcode resp fromaddr smtpsenderrefused must issue starttls command first zsmanl webmasterlocalhost edit new errors made modification suggested unni the shell execute i getting error message emailhostuser someaccountgmailcom syntaxerror invalid syntax,3 what php equivalent yield there equivalent yield php yield used generator functions special class function returns result retains state for example def simplegeneratorstart end start end start yield start gen simplegenerator gen gen gen you something similar php like class simplegenerator private start private end function constructstart end thisstart start thisend end function call ifthisstart thisend thisstart return start gen simplegenerator gen gen what exactly xrange xrange behaves like range uses generator function this performance tweak working large lists memory tight what assert is equivalent throwing exception yes beware php assert really fun vector attacks software python pickle essentially serialize yes,i seen markov chain gibberish detector written response another question stackoverflow i would like convert php i looking someone i confused portions python code i knowledge i looked python docs confuses even what php equivalent yield def ngramn l return n grams l normalizing filtered normalizel start range lenfiltered n yield joinfilteredstartstart n what exactly xrange there pecl extension however i would prefer pure php implementation would possible counts xrangek xrangek row enumeratecounts floatsumrow j xrangelenrow rowj mathlogrowj what assert is equivalent throwing exception assert mingoodprobs maxbadprobs python pickle essentially serialize pickledump mat counts thresh thresh open gibmodelpki wb thanks help edit typos,2 this may suitable needs i found mysql connectorpython much much easier set mysqldb it implemented entirely python care c interface libraries this solution couple downsides it supposed slower and importantly case i know nothing dabo i idea possible sub different mysql interface,i trying setup environment ubuntu making shift mswindows it course python i setup mysql mysqldb ubuntu software centre import dabo import mysqldb works ok no error but establishing connection says mismatch versions mysqldb amp mysql importerror mysqldb version gamma mysql version final how i solve complete traceback traceback recent call last file stdin line module file dabovmdhotelpy line module empconn dabodbdconnectionempci file dabodbdconnectionpy line init selfconnection selfopenconnectionkwargs file dabodbdconnectionpy line openconnection return selfconnectinfogetconnectionforcecreateselfforcecreate kwargs file dabodbdconnectinfopy line getconnection return selfbackendobjectgetconnectionself kwargs file dabodbdbmysqlpy line getconnection import mysqldb dbapi file mediapythpythonlibsitepackagesmysqldbinitpy line module versioninfo mysqlversioninfo importerror mysqldb version gamma mysql version final thanks advance vineet,1 you may want take look tool developed python code devs automatically convert python code python code the tool first parses code tree spits fixed python code tree this may good place start official python tool endorsed core developers part recommended python migration path alternatively check codegenpy module generates python code back python ast see also so question may relevant i marking duplicate i sure scopes questions overlap,i want able perform code generation python given ast description i done static analysis c built ast visitors python i feel relatively comfortable manipulating syntax tree i never attempted code generation trying determine best practice generating python code specifically i love pointers automatic code generation typically done pointers libraries targetting python could make task simpler my end goal attempt something similar csmith tool make python code compliant pep,3 this python command search syspath django module question python djangobindjangoadmin,i added cpythonlibsitepackagesdjangobin path i started new cmd session windows i try python djangoadminpy says file djangoadminpy when i type path full path djangobin this driving nuts clearly working any suggestions,2 defaultdict requires callable argument provides defaultvalue invoked without arguments none callable what want defaultdictlambda none,i wish dictionary contains set state transitions i presumed i could using states defaultdictnone working i expected for example states defaultdictnone newstate statesstate dispatchtransition i would thought statesstate would return value none newstate bool i would gotten false newstate statesstate instead i get keyerror what wrong thanks barry,3 looks like missing colon printnone line,im issues get exercise names variables code functions work and honest dont quite understand either like i didnt fully understand couple previous ones yeah here code writed def printtwoargs arg arg args print arg r arg r arg arg def printtwoagainarg arg print arg r arg r arg arg def printonearg print arg r arg def printnone print i got nothing printtwozed shaw printtwoagainzed shaw printonefirst printnone line def printnone syntaxerror,2 in use case use defaultdict plain dict fine states newstate statesgetstate dispatchtransition the dictget method returns value given key default value key found the default value defaults none,i wish dictionary contains set state transitions i presumed i could using states defaultdictnone working i expected for example states defaultdictnone newstate statesstate dispatchtransition i would thought statesstate would return value none newstate bool i would gotten false newstate statesstate instead i get keyerror what wrong thanks barry,3 in exact example i guess would okay use defined constants would raise error constant found alas typo string would i guess least equal solution using object orientation btw cts always true since empty strings interpreted false,i read post recently someone mentioned need using enums python i interested whether true for example i use enum represent modem control signals class signals cts cts dsr dsr isn better i use signal signalscts signal cts i missing something,1 signalscts seem better cts but signals enum class specific fields the claim i heard need separate enum language construct things like done question perhaps cts dsr xxx yyy zzz range if signals module imported used similar fashion eg signal signalscts this used several modules standard library including os modules,i read post recently someone mentioned need using enums python i interested whether true for example i use enum represent modem control signals class signals cts cts dsr dsr isn better i use signal signalscts signal cts i missing something,3 first add userlink listdisplay then add modeladmin def userlinkself obj return hrefssa urlresolversreverse adminauthuserchange argsobjuserid objuser userlinkallowtags true userlinkshortdescription user untested,i inserted creatormethod model like def creatorself return selfuser then add line adminclass model listdisplay title createdat votes creator and good usernames displayed column want make links names forward edit userprofiles how thanks lot,2 something add proper path syspath variable i know blender specifically general could add follows syspathappendr mymodule relative path syspathappendr cpathtomymodule absolute path the one use depends conditions running script blender dedicated scripts folder could use first one if run example program files folder use absolute path,hi i trying use multiple python files blenderd script eg myscriptpy mymodulepy myscriptpy looks like import bpy import math addutils import addobjecthelper addobjectdata import mathutils line work import mymodule register def register pass def unregister printfinished name main register running script within blenderd i get error importerror no module named mymodule i setup blenderd script folder point folder containing script mymodulepy thanks help j,2 firstly might wise print configfile ospathexistsconfigfile reading sure file python find as actually accessing ospathsplitfile looks almost correct i sure works properly pyinstaller proper way packing files add spec file pyinstaller load compile time unpack meipass run time to get meipass dir packedmode use local directory unpacked development mode i use def resourcepathrelative return ospathjoin osenvironget meipass ospathabspath relative development resourcepathloggingconf homeshishsrcmyapploggingconf deployment resourcepathloggingconf tmpmeiloggingconf,edit i replaced file sysargv i need know location scriptexecutable this exactly case seems run fine least executable version now everything working fine onefile mode use accepted answer function access resource files edit shown accepted answer comments problem coming path resolution script i try use file get location script i access resource files this work packaged file return filename pythondll script quite always path file name so i find another trick make access resource files workaround moment move current directory executable path by way means configparser report problem accessing file section missing i update question way i resolved path resolution question i got problems pyinstaller first time i using sure i done something wrong so problem pyisntaller runs smoothly script i wrote generates stuff dist folder ok i want execute see went well i get cprogram filespyinstallerpyinstallerptooldistptoolptoolexe traceback recent call last file string line module file ptoolbuildpyiwinptooloutpyzpyzloggingconfig line f ileconfig file ptoolbuildpyiwinptooloutpyzpyzloggingconfig line createformatters file ptoolbuildpyiwinptooloutpyzpyzconfigparser line ge configparsernosectionerror no section formatters my first idea loggingconf file missing i added resource files ptoolspec file better python version winxp i using pyinstaller i need package files solaris workstation so anyone problem the topic related following question pyinstaller problem really close problem hopelessly got answer edit details logging removed really related problem,3 check documentation warning clearly written when writing crawl spider rules avoid using parse callback since crawl spider uses parse method implement logic so override parse method crawl spider longer work url verification,i trying make sgmllinkextractor work this signature sgmllinkextractorallow deny allowdomains denydomains restrictxpaths tags area attrs href canonicalizetrue uniquetrue processvaluenone i using allow so i enter rules rulesgmllinkextractorallowaadler callback parse so initial url httpwwwwhitecasecomjacevedo i entering allow aadler expect aadler get scanned well but instead spider scans initial url closes wcase info domain opened wcase debug crawled jacevedo referer none wcase info passed nuitemschoolu jd u columbia law school harlan fiske stone scholar parker school recognition achievement international foreign law u wcase info closing domain finished what i wrong is anyone used scrapy successfully help finish spider thank help i include code spider scrapycontribspiders import crawlspider rule scrapycontriblinkextractorssgml import sgmllinkextractor scrapyselector import htmlxpathselector scrapyitem import item nuitems import nuitem urls import u class nuspidercrawlspider domainname wcase starturls xxxxxxjacevedo rules rulesgmllinkextractorallowaadler callback parse def parseself response hxs htmlxpathselectorresponse item nuitem item school hxsselect tdclassmaincolumntda jdsd return item spider nuspider note so let post url substitute initial url necessary sorry,2 from pep style guide python code imports always put top file module comments docstrings module globals constants unless good reason violate follow,i web app python main file router the router reads path import module needed request call method directly in case modules needed app imported beginning file in first case routerpath args import module needed run in second case app would look like servicesa import servicesa import servicesa import servicesa import servicesa import servicesa import router function rooterpath args based path call fn aargs what better,1 use timesince template tag,i two dates want show message like n days left trial end n number days two given dates is better inside views quick way inside template,3 possible duplicate i actually use method lazerscience uses something like datetime import datetime timedelta django import template djangoutilstimesince import timesince register templatelibrary registerfilter def timeuntilvalue datetimenow try difference value except return value difference timedeltaminutes return return times ago time timesincevaluesplit,i two dates want show message like n days left trial end n number days two given dates is better inside views quick way inside template,1 not i know i something similar concept although lot simple php using phpqyery custom htmllike markup for instance simplified nonstandard html chunk bodynode lt ie script srchtmlshivgooglecodecomsvntrunkhtmljsscript endif div classholder article header classcolf component idlogocomponent component idaddresscomponent component idlanguagescomponent component idmainmenucomponent header section idbanner component idmaingallerycomponent component id sidemenu component section section classcol first idintrotitle h classunderlinedh section classcol first idintrocolsection section classcol last idintrocolsection section section classcol idlocationsection section classcol last idservicessection article div classcleardiv div component idfootercomponent bodynode using phpquery works serverside xml html dom nodes way similar jquery i map tags content coming db using id key well componentcomponent tags custom output functions so existence component idlogocomponent would cause call function called componentlogo using function replacecomponents pqinput pqdoc phpquerynewdocumentpqinput comps pq component foreach comps comp compfunc component pqcompattr id pqcompreplacewithcompfunccomp return pqdoc function componentlogocomp pqcomp phpquerynewdocumentfilegetcontents templatescomponentslogocomponenthtml pqcompfind attr href currentlanguage attr title website title pqcompfind img attr src gfxlogopng return pqcomp although based mvc pattern uses straight procedural programming far method allowed quick development small medium sized sites keeping things nicely dry,i came across interesting templating tool author calls hquery unobtrusive serverside scripting more information httpsgithubcomchoonkeathquery it built ruby ror platform i wanted know something similar available platforms php python java ps i know templating engines like smarty twig i looking something closer hquery,1 ttrtretreetre,is possible use only posix regular expressions guarantee word appear inside string i mean wanted words dont tree it tell i like turtles matches on hand match the man tree thanks,2 you calling function merely referencing function object try theworlddisplay,get class variables working properly class world def initself size selfsize size selfgrid rangesize selfgridappend j rangesize selfgridiappend def displayself row selfgrid print row theworld worldintrawinputinput world sizeinteger theworlddisplay the problem display function anything think referencing selfgrid properly somehow i input world size make difference any ideas thanks,3 this vba i call function using theworld worldintrawinputinput world sizeinteger theworlddisplay,get class variables working properly class world def initself size selfsize size selfgrid rangesize selfgridappend j rangesize selfgridiappend def displayself row selfgrid print row theworld worldintrawinputinput world sizeinteger theworlddisplay the problem display function anything think referencing selfgrid properly somehow i input world size make difference any ideas thanks,1 add braces call method theworlddisplay,get class variables working properly class world def initself size selfsize size selfgrid rangesize selfgridappend j rangesize selfgridiappend def displayself row selfgrid print row theworld worldintrawinputinput world sizeinteger theworlddisplay the problem display function anything think referencing selfgrid properly somehow i input world size make difference any ideas thanks,1 well actually called display function you say theworlddisplay function actually called,get class variables working properly class world def initself size selfsize size selfgrid rangesize selfgridappend j rangesize selfgridiappend def displayself row selfgrid print row theworld worldintrawinputinput world sizeinteger theworlddisplay the problem display function anything think referencing selfgrid properly somehow i input world size make difference any ideas thanks,2 looks like cpplintpy simply exiting nonzero return code might instance finds errors lint source files checking see documentation subprocesscheckoutput note command executed returns nonzero exit code subprocesscalledprocesserror raised you could work around watching calledprocesserror eg try output subprocesscheckoutputcmd except subprocesscalledprocesserror e ack cpplintpy failed report error user edit the syntaxerror seems key probably caused cpythonlib pythonpath either explicitly could happen current working directory the python interpreter since ish automatically runs import site started so case script goes execute cpythonpythonexe cusersmedocumentsdevcpplintpy python interpreter find cpythonlibsitepy first try load instead one presumably cpythonlibsitepy the issue python sitepy contains syntax incompatible python process launched subprocesscheckoutput failing syntaxerror even gets chance run cpplint propagates calledprocesserror solution make sure python gets bonafide python pythonpath likewise python in words make sure cpythonlib pythonpath search path running python interpreter one way case set explicit environment launching process eg pythonenv pythonpath pathtopythonstuff output subprocesscheckoutputcmd envpythonenv,i trying execute google cpplintpy group files collect results one log file however i managed beat subprocess module my current code import os subprocess rootdir cusersmedocumentsdev srcdir projectsrc openrootdirsrcdirlogtxt mode w encoding utf logfile subdir dirs files oswalkrootdirsrcdir file files fileendswithh fileendswithcpp filewithpathospathjoinsubdir file cmd cpythonpythonexe cusersmedocumentsdevcpplintpy filterwhitespacelegalbuildincludebuildheaderguard filewithpath output subprocesscheckoutputcmd logfilewriteoutputdecode ascii trying run code throws error file cpythonlibsitepy line filesysstderr syntaxerror invalid syntax traceback recent call last file cusersmedocumentsdevprojectsrcverifierpy line module output subprocesscheckoutputcmd file cpythonlibsubprocesspy line checkoutput raise calledprocesserrorretcode cmd outputoutput subprocesscalledprocesserror command cpythonpythonexe cusersmedocumentsdevcpplintpy filterwhitespacelegalbuildincludebuildheaderguard cusersmedocumentsdevprojectsrcaboutdialogcpp returned nonzero exit status if i substitute cmd something simpler like cmd cwinavrbinavrgccexe version then script works expected i also tried use single command string instead list strings cmd result when debugging code i copied listofstringsturnedintothecommandlinecommand debugger ran windows command line command ran expected the python interpreter running script python any tips greatly appreciated,3 with firebug expression tableid table tdtext gives textnode textcontentimportant text textnode textcontentimportant text textnode textcontentimportant text textnode textcontentimportant text textnode textcontentimportant text i included td filtering give nicer result since otherwise would get whitespace newlines tags but seems work what i noticed query divcontainsid randomid html snippet tag reads div idrandomdiv id div different i know scrapy i really say something issue well,i currently trying extract information badly formatted web page specifically page used id attribute multiple table elements the markup equivalent something like body div idrandomdiv psome contentp table idtable tr tdimportant text td tr table hsome heading betweenh table idtable tr tdimportant text td tdimportant text td tr table phow text herep table idtable tr tdimportant text td tdimportant text td tr table div body clearly incorrectly formatted html due multiple use id element i using xpath try extract text various table elements utilising language scrapy framework my call looks something like hxsselect divcontainsid randomdivtableidtabletext extract thus xpath expression divcontainsid randomidtableidtabletext this returns u important text ie contents first table matches id value table it seems come across element certain id ignores future occurrences markup can anyone confirm update thanks fast responses i tested code page hosted locally test format correct response returned ie u important text u important text u important text there therefore nothing wrong either xpath expression python calls i making i guess means problem webpage either screwing xpath html parser libxml does anyone advice i dig bit update i successfully isolated problem it actually underlying parsing library lxml provides python bindings libxml c library the problem parser unable deal vertical tabs i idea coded site i dealing full vertical tabs web browser seem able ignore running xpath queries firebug site question example successful further simplified example contain vertical tabs works fine for anyone comes across issue scrapy python generally following fix worked remove vertical tabs html responses def parseitemself response remove vertical tabs html response responsebody filterlambda c c v responsebody hxs htmlxpathselectorresponse items hxsselect divcontainsid randomdiv tableidtabletext extract,1 you never use two words token instead split two seperate tokens ensure language enforces one always followed eg implement declaratorwas token declaratora token,i writing compiler part lab excercise chosen python using ply i spent time trying work particular problem reached dead end lab helpers in language i write declarators specified two words for example x number x became equal int x x when parsing ply i put reserved word reserved declarator but i parse ply lexer treats separate tokens how i parse token type declarator without ply lexer splitting if unclear let know i try answer questions best i thanks pete,2 i would request run first pipe subprocesspopencmd optionsstdinsubprocesspipe stdoutsubprocesspipe stderrsubprocessstdout stdout stderr pipecommunicate you get know exactly error behind since calledprocesserror raised exit code nonzero,i trying execute google cpplintpy group files collect results one log file however i managed beat subprocess module my current code import os subprocess rootdir cusersmedocumentsdev srcdir projectsrc openrootdirsrcdirlogtxt mode w encoding utf logfile subdir dirs files oswalkrootdirsrcdir file files fileendswithh fileendswithcpp filewithpathospathjoinsubdir file cmd cpythonpythonexe cusersmedocumentsdevcpplintpy filterwhitespacelegalbuildincludebuildheaderguard filewithpath output subprocesscheckoutputcmd logfilewriteoutputdecode ascii trying run code throws error file cpythonlibsitepy line filesysstderr syntaxerror invalid syntax traceback recent call last file cusersmedocumentsdevprojectsrcverifierpy line module output subprocesscheckoutputcmd file cpythonlibsubprocesspy line checkoutput raise calledprocesserrorretcode cmd outputoutput subprocesscalledprocesserror command cpythonpythonexe cusersmedocumentsdevcpplintpy filterwhitespacelegalbuildincludebuildheaderguard cusersmedocumentsdevprojectsrcaboutdialogcpp returned nonzero exit status if i substitute cmd something simpler like cmd cwinavrbinavrgccexe version then script works expected i also tried use single command string instead list strings cmd result when debugging code i copied listofstringsturnedintothecommandlinecommand debugger ran windows command line command ran expected the python interpreter running script python any tips greatly appreciated,1 i found bug report python issue tracker it suggests python setuppy build b somedir install and works,this work python setuppy install buildbasefoo how i tell distutils take built files installation,2 polling not robustreliable you cannot determine data changed windows anyway without pasting buffer inspection this requires opening clipboard if loop going collide apps ie app user copying another item onto clipboard this explode cannot open clipboard memory error this approach work reliablyrobustly you need use proper clipboard monitoring apis various platforms,i trying create script python collect data put clipboard user preferably save list text file stringarrayvariable work later this work linux versions i would assume ubuntu mac os versions windows versions i sure bit bit systems different ways accessing data clipboard i guess would safe make work bit versions people running bit versions fall back onto bit version os the tricky part apart work mentioned os i would like script run long user stop runs data copied clipboard user copied list text file stringarrayvariable of course time limit user input data clipboard i thinking loop scanning clipboard every second every milliseconds check content changed copy otherwise copy is unified way module different os would better write separate scripts task various os the thing part bigger project i would like make work linux mac windows three options covered use python code used across mentioned os rest scriptproject would ideal am i asking much general script concerning work linux mac windows,1 this standard python idiom clearing list – assigning “entire list” slice blogposttags instead empty list may want assign new set tags directly blogposttags newtags sqlalchemy relations instrumented attributes meaning keep interface list set dict etc changes reflected database this means anything list possible relation sqla transparently listens changes updates database accordingly,i need remove object declarative orm manytomany relationship i supposed blogposttagsremovetag well what i supposed i need purge relations one typical situation i like set new list tags blogpost so i need remove existing relations blogpost tags set new relations create new tags exist of course could better way in case please let know,3 i also run error seems fixed true fig pyplotfigure ax figaddsubplot axplotxy axlegendlegendstrings loc best figsavefig himompng new bit pylabclosefig f figure running loop stably fluctuating memory consistant increase,i fairly simple plotting routine looks like future import division import datetime import matplotlib matplotlibuse agg matplotlibpyplot import figure plot show legend close savefig rcparams import numpy globalconstants import def plotcolumnscolumnnumbers showfigfalse filenameprefixnone savefigtrue savethumbtrue lineprops b r g c k b r g c k g b r g c k rcparams figurefigsize columnnumbers plott outi linepropsi legendstrings listnumpyzerosnumcomponents legendstringsglucose glucose legendstringscellulose cellulose legendstringsstarch starch legendstringsacetate acetate legendstringsbutyrate butyrate legendstringssuccinate succinate legendstringshydrogen hydrogen legendstringspropionate propionate legendstringsmethane methane legendstringsruminococcus ruminococcus legendstringsmethanobacterium methanobacterium legendstringsbacteroides bacteroides legendstringsselenomonas selenomonas legendstringsclostridium clostridium legendstrings legendstringsi columnnumbers legendlegendstrings loc best dt datetimedatetimenow dtasstring dtstrftime dmyhms filenameprefix none filenameprefix filenameprefix filenameprefix filenameprefix savefig savefigfilenameprefixdtasstring eps savethumb savefigfilenameprefixdtasstring png dpi showfig fshow close when i plot single iterations works fine however moment i put loop matplotlib throws hissy fit traceback recent call last file chmparamvariationhconcpy line module plotcolumnscolumnnumbers timevector showfigfalse filenameprefix c hmparamvariationhconc strhydrogenconc savefigfalse savethumbtrue file dphdprojectalexander paperpythonvplotcolumnspy line plo tcolumns savefigfilenameprefixdtasstring png dpi file cpythonlibsitepackagesmatplotlibpyplotpy line savefi g return figsavefigargs kwargs file cpythonlibsitepackagesmatplotlibfigurepy line savef ig selfcanvasprintfigureargs kwargs file cpythonlibsitepackagesmatplotlibbackendbasespy line n printfigure kwargs file cpythonlibsitepackagesmatplotlibbackendsbackendaggpy line printpng figurecanvasaggdrawself file cpythonlibsitepackagesmatplotlibbackendsbackendaggpy line draw selffiguredrawselfrenderer file cpythonlibsitepackagesmatplotlibartistpy line drawwr apper drawartist renderer kl file cpythonlibsitepackagesmatplotlibfigurepy line draw selfaxes adrawrenderer file cpythonlibsitepackagesmatplotlibartistpy line drawwr apper drawartist renderer kl file cpythonlibsitepackagesmatplotlibaxespy line draw adrawrenderer file cpythonlibsitepackagesmatplotlibartistpy line drawwr apper drawartist renderer kl file cpythonlibsitepackagesmatplotliblegendpy line draw bbox selflegendboxgetwindowextentrenderer file cpythonlibsitepackagesmatplotliboffsetboxpy line get windowextent px py selfgetoffsetw h xd yd file cpythonlibsitepackagesmatplotliboffsetboxpy line get offset return selfoffsetwidth height xdescent ydescent file cpythonlibsitepackagesmatplotliblegendpy line findof fset return findoffsetwidth height xdescent ydescent renderer file cpythonlibsitepackagesmatplotliblegendpy line findo ffsetbest ox oy selffindbestpositionwidth height renderer file cpythonlibsitepackagesmatplotliblegendpy line find bestposition verts bboxes lines selfautolegenddata file cpythonlibsitepackagesmatplotliblegendpy line auto legenddata tpath transtransformpathpath file cpythonlibsitepackagesmatplotlibtransformspy line ransformpath selfatransformpathpath file cpythonlibsitepackagesmatplotlibtransformspy line ransformpath return pathselftransformpathvertices pathcodes file cpythonlibsitepackagesmatplotlibtransformspy line ransform return affinetransformpoints mtx memoryerror could allocate memory path this happens iteration counting makes difference the code running windows xp bit python matplotlib numpy scipy edit the code updated reflect fact crash actually occurs call legend commenting call solves problem though obviously i would still like able put legend graphs,3 a answering question i finally accept one the problem solved time ago the important answer documentation each query run uri argument for example inserteventevent uri uri set manually google calendar settings automatically written post note calendareventquery takes username whole url the construction goes way user abcdgroupcalendargooglecom uri httpwwwgooglecomcalendarfeeds user privatefullnoattendees what useful run queries different uri adddelete events many different calendars one script hope someone finds helpful,i wonder possible create delete events google api secondary calendar i know well main calendar i ask change calendarservice read write calendar i tried loging secondary calendar email possible badauthentication error the url surely correct becouse read api waiting help,1 i answering question i finally close if anyone interested problem solved there bug sudssx reported as soap request edited one request i sent empty to correct i delete sx part change messageplugin if anyone interested write,i sending soap request update entity when i create instead update nearly thing everything works fine i tracked logging client transport finally gave clue it looks like debugsudsclientsending httpswebservicesautotasknetatservicesatwsasmx message xml version encodingutf soapenvenvelope xmlnsnshttpautotasknetatwsv xmlnsnshttpschemasxmlsoaporgsoapenvelope xmlnsxsihttpwwwworgxmlschemainstance xmlnssoapenvhttpschemasxmlsoaporgsoapenvelope soapenvheader nsbody nsupdate nsentities xmlnsxsdhttpwwwworgxmlschema nsentity xsitypensticket nsidnsid nsuserdefinedfields xsitypexsdstringnsuserdefinedfields nsaccountid xsitypexsdstringnsaccountid nsallocationcodeid xsitypexsdstringnsallocationcodeid nscompleteddate xsitypexsdstring nscompleteddate nscreatedate xsitypexsdstring nscreatedate nscreatorresourceid xsitypexsdstringnscreatorresourceid nsdescription xsitypexsdstringnsdescription nsduedatetime xsitypexsdstring nsduedatetime nsestimatedhours xsitypexsdstringnsestimatedhours nsissuetype xsitypexsdstringnsissuetype nslastactivitydate xsitypexsdstring nslastactivitydate nspriority xsitypexsdstringnspriority nsqueueid xsitypexsdstringnsqueueid nsstatus xsitypexsdstringnsstatus nssubissuetype xsitypexsdstringnssubissuetype nsticketnumber xsitypexsdstringnsticketnumber nstitle xsitypexsdstringfoonstitle nsfirstresponsedatetime xsitypexsdstring nsfirstresponsedatetime nsresolutionplandatetime xsitypexsdstring nsresolutionplandatetime nsresolveddatetime xsitypexsdstring nsresolveddatetime nsresolution xsitypexsdstringnsresolution nsentity nsentities nsupdate nsbody soapenvenvelope debugsudsclientheaders soapaction u httpautotasknetatwsvupdate contenttype textxml charsetutf debugsudstransporthttpsending urlhttpswebservicesautotasknetatservicesatwsasmx headers soapaction u httpautotasknetatwsvupdate soapaction u httpautotasknetatwsvupdate contenttype textxml charsetutf contenttype textxml charsetutf authorization basic yxvbhdglhqgfyyvzlmlddpdwykowfynvqady message xml version encodingutf soapenvenvelope xmlnsnshttpautotasknetatwsv xmlnsnshttpschemasxmlsoaporgsoapenvelope xmlnsxsihttpwwwworgxmlschemainstance xmlnssoapenvhttpschemasxmlsoaporgsoapenvelope soapenvheader nsbody nsupdate entities nsupdate nsbody soapenvenvelope and i get error object reference set instance object anyone idea happens soap request looses whole entity body proceed empty message is problem suds server code thanks little help understing happening,1 i wrote similar program help stack overflow guys string import punctuation operator import itemgetter n words wordsgen wordstrippunctuationlower line openpoiruntxt word linesplit word wordsgen wordsword wordsgetword topwords sortedwordsitems keyitemgetter reversetruen word frequency topwords print word frequency,i count word frequency text using python i thought keeping words dictionary count words now i sort words according occurrences can dictionary instead using new dictionary key count array words values,1 the value tourpk converted integer format specifier it needs string containing integer without sign ignores leading zeros numeric type like float class int method,urlspy r airagencypkeyazazedittourptouridd airagencyviewsedittour viewspy toursave angagentobjectsgetpkkey return httpresponseredirect airagencysedittouriedittourhtml agnwebsitetourpk note tour formafter saving form tour pk used pass edittourhtml redirecting edittourhtml error valueerror airagencymastaneaddtour invalid literal int base mastane request method post request url airagencymastaneaddtour django version exception type valueerror exception value invalid literal int base mastane exception location cpythonlibsitepackagesdjangodbmodelsfieldsinitpy getprepvalue line python executable cpythonpythonexe,2 if specify file get string image data eg in import networkx nx in gnxpathgraph in anxtoagraphg in alayoutprog dot in pngadrawformat png in png out xpngrnxanxx,i networkx digraph object i draw graph file using toagraph but i want draw graph memory something i save database table without necessarily writing file is way following code i use draw graph file import networkx nx g nxdigraph gaddnodesfrommynodes gaddaddedgesfrommyedges grphnxtoagraphg sgrphstring grphlayoutprog dot grphdraw testgraphgif thanks,1 add tree control sizer within panel similar parameters treesizer wxboxsizerwxvertical treesizeraddtree wxexpand panelsetsizertreesizer,i frame panel attached panel wxpanelself stylewxsimpleborder then i make tree control widget within panel tree wxtreectrlpanel style wxtrhasbuttons i add vertical sizer vboxwxboxsizerwxvertical vboxaddpanel wxexpand wxall i run treecontrol occupies corner panel expand size panelthe panel self part another sizer expands well according size framewhat i make treecontrol expand well,1 i found solution it due dns i put redirection wwwmydomaincom mydomaincom sometimes cookie set www sometimes server check good place find cookie send error,i using tornado twittermixin i use following basic code class oauthtwitterhandlerbasehandler tornadoauthtwittermixin tornadowebasynchronous def getself selfgetargumentoauthtoken none selfgetauthenticateduserselfasynccallbackselfonauth return selfauthorizeredirect def onauthself user user raise tornadowebhttperror twitter auth failed selfwriteuser selffinish for works well sometimes users application get error says missing oauth request token cookie i know comes browser twitter api callback configuration i looked tornado code i understand error appears,1 did mean lenlist what difference decremented length index last element by way say properly index last element in programming languages count except fortran matlab lua smalltalk example the elements indexes believe get used one you see trying operate list if searchin method try listindexlist i recommend one you sure list contains no duplicates,list i need check last index list like listlastindex i python,3 i guess want lastindex lenyourlist last index list would,list i need check last index list like listlastindex i python,2 you use list length the last index length list minus one lenlist,list i need check last index list like listlastindex i python,1 as agf said get around problem simply replacing line return httpresponseredirect airagencysedittoursedittourhtml agnwebsitestrtourpk assuming tourpk greater equal,urlspy r airagencypkeyazazedittourptouridd airagencyviewsedittour viewspy toursave angagentobjectsgetpkkey return httpresponseredirect airagencysedittouriedittourhtml agnwebsitetourpk note tour formafter saving form tour pk used pass edittourhtml redirecting edittourhtml error valueerror airagencymastaneaddtour invalid literal int base mastane request method post request url airagencymastaneaddtour django version exception type valueerror exception value invalid literal int base mastane exception location cpythonlibsitepackagesdjangodbmodelsfieldsinitpy getprepvalue line python executable cpythonpythonexe,1 nathan an easier option learning really many expenses i could also suggest take look heroku allows easily deploy applications minutes up recently supported ror brought support django python really well documented tutorials well i hope helps heroku django python tutorial,i new web development so gentle and thanks advance i developing windows env deploying linux server w python installed running apache virtual host i using modwsgi i plan serve media files virtual host i django site i ready deploy i stuck every site i go seems outdatedincompleteovermyhead httpsdocsdjangoprojectcomenhowtodeploymentmodwsgi httpwwwdjangobookcomenchapter links newbness the top link seems i need yet i still confused things what file structure look like server i cannot changeedit server files i rely dba i djangowsgi djangowsgi go where i put project relation wsgi files the httpdconf file something server i create another do i need put django way shape form server if and packages like registration defaults again sorry newbness i banging head weeks any helplinks greatly appreciated unless link djangodocs i read thosea lot thanks,1 lenlist definitely way go absolutely need list function returns last index could create class inherits list class mylistlist def lastindexself return lenself lmylist llastindex,list i need check last index list like listlastindex i python,3 doesn simply casting string work you keep storage asis format number liking presenting data strdecimal strdecimal strdecimal,i creating app basically stores shoe sizes along information i using django decimal field store sizes however decimal field stores sizes like question way make already exists field provided int stores value int provided decimal stores decimal,1 most depends use case i lot experience dealing various hdfbased methods traditional relational databases i comment much sqlite libraries python at least far hpy vs pytables offer seamless access via numpy arrays oriented towards different use cases if ndimensional data want quickly access arbitrary indexbased slice much simple use hpy if data tablelike want query pytables much better option hpy relatively vanilla wrapper around hdf libraries compared pytables this good thing going regularly accessing hdf file another language pytables adds extra metadata hpy lot use cases eg pytables going need spend time tweaking things pytables really nice features however data look much like table probably best option to give concrete example i work lot fairly large tens gb dimensional arrays data they homogenous arrays floats ints uints etc i usually want access small subset entire dataset hpy makes simple fairly good job autoguessing reasonable chunk size grabbing arbitrary chunk slice disk much much faster simple memmapped file emphasis arbitrary obviously want grab entire x slice cordered memmapped array impossible beat data x slice adjacent disk as counter example wife collects data wide array sensors sample minute second intervals several years she needs store run arbitrary querys relatively simple calculations data pytables makes use case easy fast still advantages traditional relational databases particularly terms disk usage speed large indexbased chunk data read memory,there seems many choices python interface sqlite sqlite atpy hdf hpy pytables i wonder anyone experience using together numpy arrays data tables structuredrecord arrays seamlessly integrate scientific modules numpy scipy data format sqlite hdf,3 there nothing like duplicate keys dictionary if columns name dictreader take last one overwriting previous ones for following csv file abcab dictreader return following dicts c b c b thus throwing previous values b columns away,i new python i currently stumped problem i list dictionaries generated csvdictreader i created list function follows def csvtodictlistfilename reader csvdictreaderopenfilename rb list row reader listappendrow return list readerfieldnames this worked great csv file i processing duplicate columns i end dictionary like column value column value unique columns values column value column value column valuen column valuen unique columns values column valuen column valuen my main question i remove duplicate columns dictionary list i thought iterating key removing column i detect duplicate key name something like def removecolumndictlist colname row dictlist del rowcolname but remove columns should i operating hashkeys dictionary any help appreciated edit the duplicates i seeing actually present readerfieldnames list so i assuming dictionaries contained columns well incorrect assumption,1 you pass extra arguments deferred callback deferredaddcallback call site simply passing arguments deferredaddcallback def functionselffilename def resultsresult name something rangeintnumbers name something value df functionwhichreturnsa defername dfaddcallbackresults name you also pass arguments keyword dfaddcallbackresults namename all arguments passed like addcallback adderrback passed callback function,i following python code using twisted api def functionselffilename def resultsresult something rangeintnumbers name something value df functionwhichreturnsa defername dfaddcallbackresults it uses twisted api what want achieve pass callbacked function results value name constructed every iteration without changing content functionswhichreturnsa defer function along deferred object course in every result functionswhichreturnsa deffer value name passed results something ie first iteration execution reach results function need function hold result deffered object along value name ithen defered object passed value name onso need every time result defer object called name variable alond name variable when try directly use value nameinside results holds always value last iteration rationale since functionwhichreturnsa defername returned,3 those good ideas implementation presenting cheese making interface user they care many holes cheese internals go making cheese the user code wants gouda parmesean right so cheeseuserpy cheeses import makegouda makeparmesean gouda makegouda paremesean makeparmesean and use methods actually implement functions cheesespy class cheeseobject def initself args kwargs args tuple anonymous arguments kwargs dictionary named arguments selfnumholes kwargsget numholes randomholes def makegouda return cheese def makeparemesean return cheesenumholes this good encapsulation technique i think pythonic to way things fits line duck typing you simply asking gouda object really care class,i find definitive answer afaik multiple init functions python class so good way solve problem suppose i class called cheese numberofholes property how i two ways creating cheeseobjects one takes number holes like parmesan cheesenumholes one takes arguments randomizes numberofholes property gouda cheese i think one way seems kinda clunky class cheese def initself numholes numholes randomize numberofholes else numberofholes numholes what say is better way,3 here similar question recipe listfield widget could get started djangononrel form field listfield,using djangoldapdb i trying manage user ssh keys stored ldap directory the main problem i listfield displayed modelform renders input repr list unicode string actual datatype returned listfieldtopython list what best way write custom widget would turn list set input boxes custom html the end goal something looks similar user could easily add new ssh keys remove existing ones the existing stuff like screenshot mango display ssh key fingerprint comment email instead raw key bonus points anyone figure way hook jquery make similar django admin inline pretty google django jquery admin click djangoadvent article i enough so points link how would implement something like,1 mxdatetimeisoparsedatetimeutc right thing applying specified timezone adjust time utc the resulting utc time timezone local time anymore the standard python library contain concrete timezone classes according documentation tzinfo abstract base clase meaning class instantiated directly you need derive concrete subclass least supply implementations standard tzinfo methods needed datetime methods use the datetime module supply concrete subclasses tzinfo i always surprised least include class utc generic implementation like dateutil tzoffset,is way i obtain datetime aware object string python using standard library modules i know i use dateutilparserparse unfortunately good enough reason add dependency project i already mxdatetime module dependency buuttttt dateutilparserparse t datetimedatetime tzinfotzoffsetnone mxdatetimeisoparsedatetimeutc t mxdatetimedatetime object ce parsedatetimeutc fails detect offset even though documentation says returns datetime instance utc reflecting given iso date a time part optional must delimited date space t timezones honored,1 the short answer there way adding custom attributes bound methods the long answer follows in python function objects method objects when define class def statement creates function object lives within class namespace class c def mself pass cm function xfae function objects special dict attribute hold userdefined attributes cmi cmdict method objects different beasts they tiny objects holding reference corresponding function object func one host object self cm bound method cm mainc object xd cmself mainc object x cmfunc function xfae cmfunc cm true method objects provide special getattr forwards attribute access function object cmi this also true dict property cmdict cma cmdict cmdict true setting attributes follows default rules though since dict way set arbitrary attributes this similar userdefined classes defining slots dict slot trying set nonexisting slot raises attributeerror see docs slots information class c slots b x c xa xb xc traceback recent call last file stdin line module attributeerror c object attribute c,in following setattr succeeds first invocation fails second attributeerror method object attribute why way setting attribute method exist one instance instance class class c def mself printtypecm setattrcm printtypeselfm setattrselfm python,3 this could looking lena lenb c bcopy clena else c acopy clenb b basically copy longer one add inplace shorter one,if i two numpy arrays different sizes i superimpose numpy b numpy what cleanest way add two vectors produce new vector this generic question for background i specifically applying green transform function need superimpose results time step evaulation unto responses previously accumulated,3 tbh shoe size field i probably use charfield choices attribute relatively small number valid shoe sizes way format want if part product model may contain things shoes charfield size useful also store values like m l xxl etc you need math shoe sizes point using decimalfield for reason really matter saved db display jsyk couple good alternative suggestions along lines comments,i creating app basically stores shoe sizes along information i using django decimal field store sizes however decimal field stores sizes like question way make already exists field provided int stores value int provided decimal stores decimal,2 how serialportscom com inport outport use inport outport reserved word python using variable name result syntaxerror edit here one possible implementation untested import serial contextlib import contextmanager contextmanager def serialportsargs ports serialserialarg arg args try yield ports finally port ports portclose serialports com com inp outp print inp inpisopen outp outpisopen print inp inpisopen outp outpisopen but i defer agf one his suggestion much better case,is following reasonable approach serialports serialports serialportcom serialportsaddin serialportcom serialportsaddout use serialports serialport implement context manager interface serialportsexit loops added serial ports calling exit serialport exit closes serial port is better way,1 if know b higher dimension aresizebshape c ab need,if i two numpy arrays different sizes i superimpose numpy b numpy what cleanest way add two vectors produce new vector this generic question for background i specifically applying green transform function need superimpose results time step evaulation unto responses previously accumulated,3 i written simple deployment guide django applications found it goes way project setup deployment i also references setup i honestly believe answers questions i would give look goodluck,i new web development so gentle and thanks advance i developing windows env deploying linux server w python installed running apache virtual host i using modwsgi i plan serve media files virtual host i django site i ready deploy i stuck every site i go seems outdatedincompleteovermyhead httpsdocsdjangoprojectcomenhowtodeploymentmodwsgi httpwwwdjangobookcomenchapter links newbness the top link seems i need yet i still confused things what file structure look like server i cannot changeedit server files i rely dba i djangowsgi djangowsgi go where i put project relation wsgi files the httpdconf file something server i create another do i need put django way shape form server if and packages like registration defaults again sorry newbness i banging head weeks any helplinks greatly appreciated unless link djangodocs i read thosea lot thanks,1 first need find indicies values second column a need match order v in case once use numpy fancy indexing rest so might something like import numpy np a nparangereshape v column atolist order columnindexitem item v print aorder if want avoid python lists entirely something like shown it hackish may better way though we abuse numpyunique what i depending particular implementation detail unique seems start end array could change time that makes ugly hack import numpy np a nparangereshape v nparray vals order npuniquenphstackav returninversetrue order ordervsize print aorder,i matrix a vector values v i would like reorder a nd column using values v the result a nd columns values order v how,3 if run code class aobject def enterself return self def exitself args print exit self class bobject def enterself return self def exitself args print exit self raise exception a b b pass see exit get called even one raises error either a b b a if call exit single collective exit first error second exit get called use nested context managers instead assuming small fixed number,is following reasonable approach serialports serialports serialportcom serialportsaddin serialportcom serialportsaddout use serialports serialport implement context manager interface serialportsexit loops added serial ports calling exit serialport exit closes serial port is better way,1 you typo angagentobjectsgetpkkey agnwebsite agf pointed comments appears value tourpk mastane instead integer,urlspy r airagencypkeyazazedittourptouridd airagencyviewsedittour viewspy toursave angagentobjectsgetpkkey return httpresponseredirect airagencysedittouriedittourhtml agnwebsitetourpk note tour formafter saving form tour pk used pass edittourhtml redirecting edittourhtml error valueerror airagencymastaneaddtour invalid literal int base mastane request method post request url airagencymastaneaddtour django version exception type valueerror exception value invalid literal int base mastane exception location cpythonlibsitepackagesdjangodbmodelsfieldsinitpy getprepvalue line python executable cpythonpythonexe,1 if using numpy probably use c python compiled extension i recommend saving image disk perhaps temporary file calling python subprocess if dealing binary data could even try memory mapping data java passing path subprocess alternatively depending circumstances could set simple data processing server python accepts requests returns processed data,in java application i need use specific image processing algorithm currently implemented python what would best approach knowing script uses numpy library i alreayd tried compile script java using jythonc compiler seems support dependencies native libraries like numpy i also tried use jepp i get importerror importing numpy any suggestion,1 self already available mycallback since created inside function access enclosing function variables including self these variables actually stored inner function called closure stick around even enclosing function returns here minimal example class cobject def fself def g print self return g c c g cf g mainc object xaedf,i want able call self inside callback function class myclass def mymethodself def mycallbackp print callback called i want something self callbackx ctypeswinfunctypectypescvoidp ctypescuint somedllsetcallbackcallbackxcbfilerefdone the dword parameter callback function used how i access self,2 the parsed data unicode byte string so try write data file tries decode unicode encoding utf since default codec ascii actually utf chokes first character byte value you decode utf returned data else use mecab method returns unicode data,i written gui allows japanese input go file parse writes text file that text file gets run mecab spaces put words after supposed written text file displayed another gui window the issue i want write parsed data text file it problem writing first time also prints parsed info idle problem well here parser error usrbinpython coding utf import sys import mecab import codecs readfrom openpholdertxtread mecab mecabtaggerowakati output mecabparsereadfrom print output text output writeto codecsopenpholdertxt w utf writetowritetext writetoclose traceback recent call last file cmecabspacespy line module writetowritetext file ccodecspy line write return selfwriterwritedata file ccodecspy line write data consumed selfencodeobject selferrors unicodedecodeerror ascii codec decode byte xe position ordinal range,2 is form actually working you need submit button change button type submit instead button other things check actually user database typing username password correctly casesensitively,viewspy def loginrequest username requestpost password requestpost useruserobjectsgetusernameexactrequestpost username passwordexactrequestpost password requestsession username userusername requestsession lastlogin userlastlogin return rendertoresponse airagencyloginhtml user user return rendertoresponse airagencyloginhtml template form action methodpost stylefontfamily tahoma fontsize px centerdiv dirrtl stylewidthpx height px div stylefloatright table stylewidth tr td username td td input idusername nameusername typetextampnbsp td tr tr td ampnbsplabelpassword labelampnbsptd td input idpassword namepassword typepassword ampnbsp td tr tr td input typesubmit valuelogin ampnbsp td td input idcheckbox typecheckbox ampnbsp remember metd tr table div divcenter form i enter right usernamepasswordbut return user meactually i check user returned templatebut never return anythin template course error wrong thanks advance help,1 it appear checking user returned to check user returned template put user somewhere template,viewspy def loginrequest username requestpost password requestpost useruserobjectsgetusernameexactrequestpost username passwordexactrequestpost password requestsession username userusername requestsession lastlogin userlastlogin return rendertoresponse airagencyloginhtml user user return rendertoresponse airagencyloginhtml template form action methodpost stylefontfamily tahoma fontsize px centerdiv dirrtl stylewidthpx height px div stylefloatright table stylewidth tr td username td td input idusername nameusername typetextampnbsp td tr tr td ampnbsplabelpassword labelampnbsptd td input idpassword namepassword typepassword ampnbsp td tr tr td input typesubmit valuelogin ampnbsp td td input idcheckbox typecheckbox ampnbsp remember metd tr table div divcenter form i enter right usernamepasswordbut return user meactually i check user returned templatebut never return anythin template course error wrong thanks advance help,1 do not use this you created user model appear storing passwords plain text this dangerous do django builtin user authentication framework fully documented properly hashes passwords security includes login forms use instead even need fields use builtin user model anyway create userprofile model includes extra fields,viewspy def loginrequest username requestpost password requestpost useruserobjectsgetusernameexactrequestpost username passwordexactrequestpost password requestsession username userusername requestsession lastlogin userlastlogin return rendertoresponse airagencyloginhtml user user return rendertoresponse airagencyloginhtml template form action methodpost stylefontfamily tahoma fontsize px centerdiv dirrtl stylewidthpx height px div stylefloatright table stylewidth tr td username td td input idusername nameusername typetextampnbsp td tr tr td ampnbsplabelpassword labelampnbsptd td input idpassword namepassword typepassword ampnbsp td tr tr td input typesubmit valuelogin ampnbsp td td input idcheckbox typecheckbox ampnbsp remember metd tr table div divcenter form i enter right usernamepasswordbut return user meactually i check user returned templatebut never return anythin template course error wrong thanks advance help,3 if communicating using web service preferrably stateless – always send context information service implementation needs request while technologies let implement stateful web services exist likely make things complicated less i clear description need connection object created step create different connection object steps – i implement,this solution question it long time since last c coding first time write web service previous question i need use dll ubuntu python final solution using web service propose my problem api used kind payment there three basic function dll used webservice first one used connection server second one asking available payments third one selecting one making payment since system using python i wish keep logic selects payment method python web service and problem i make connection webservice must create connection object following two steps using connection that may dispose connection object create new one next connection payment so python code something like use web service create connection get list available payments web service two functions used single function web service do calculation select proper payment python send payment method info web service all steps must done connection object first step as i said i much knowledge web services using python so i confused whether i may use connection object steps if i create connection object global web service connection step following function calls use object in oop way must i sure web services some code snippet namespace paymenttype public class x systemwebserviceswebservice connectionobj conn connresult result webmethod public void connecttoserverstring deviceid conn new connectionobj result baglanticonnectdeviceid webmethod public listint getcompanylist listint kurumlar new listint sonuccrcstatus baglanticompanylist null blah blah blah since conn global set function call connecttoserver use baglanti object functions update let try get clear when i connect remote server via function dll remote server accepts connection give somewhat unique id connection then i ask available payments customer server sends available ones transaction id belong transaction and final step i use transaction id i want payment problem transaction id usable within connection created so i must request transaction id confirm one i want connection but far i see best solution using single function call job web service since api provider considers removing connectiontransactionid lock might cause security vulnerabilities but hand i want handle web service one question on connection step creating connection using setget functions returning connection object pass back web service following step might work,1 a to control sysgetdefaultencoding output python c import sys printsysgetdefaultencoding ascii then echo import sys syssetdefaultencoding utfbe sitecustomizepy pythonpathpythonpath python c import sys printsysgetdefaultencoding utfbe you could put sitecustomizepy higher pythonpath also might like try reloadsyssetdefaultencoding eol b to control stdinencoding stdoutencoding want set pythonioencoding python c import sys printsysstdinencoding sysstdoutencoding ascii ascii then pythonioencodingutfbe python c import sys printsysstdinencoding sysstdoutencoding utfbe utfbe finally use a b,i many encode decode problems python i run applications console but eclipse pydev ide default character encoding set utf i fine i searched around setting default encoding people say python deletes syssetdefaultencoding function startup use so best solution,3 i tried file snpsnpsnp aaa aba bbb result in csvrec helixcsv out recarray a a a a b a b b b dtype snp s snp s snp s i matplotlib might try updating i access older matplotlib testing,i working ipython trying load csv file matplotlib import datamatplotlibmlabcsvrec helixcsv delimiter here error message ioerror traceback recent call last mnthgfsdocspythonipython console module usrlibpymodulespythonmatplotlibmlabpyc csvrecfname comments skiprows checkrows delimiter converterd names missing missingd usemrecords reset reader start fhseek reader csvreaderfh delimiterdelimiter processskiprowsreader ioerror errno illegal seek does someone already run error i tried reinstall everything i working python i matplotlib v numpy v ipython,1 if mean subtree rooted node networkxalgorithmstraversaldepthfirstsearch import dfstree subtreeat dfstreet edit seems reversed order nodes edges in directed tree paths proceed root leaf way around dfstreetreverse gives tree want change code,in networkx i tree digraph usrbinpython coding utf import networkx nx nxdigraph taddedge r taddedge r taddedge r taddedge taddedge taddedge print tedges if take node tree i get subtree edit i expected subtree,3 there way programmatically of course documented djangocontribauth import authenticate login user authenticateusername username password password user none loginrequest user,how i login user programmatically django i username password user is method let log,3 comma tuple packing operator x calls xgetitem def getitemself ij j ij return selfxi selfyj,assume i class x attributes j i want x x would set j i want subscripting work following way b x b at moment i trying def getitemself j return selfxi selfyj however keeps giving error getitem takes exactly arguments given i try print x instance,2 i changed path bashprofile include path desired version python follows vi bashprofile replace pathpathhomebin pathusrlocalpythonbinpathhomebin source bashprofile configure make it picks correct python version no need change wscript i centos python installed usrlocalpython using nodejs,i pretty new centos also nodejs i already got older version nodejs work virtual server now i trying install newer version i know centos needs python node needs newer i installed python using altinstall but even i set alias python points version running configure i still get error rootnodewscript error traceback recent call last file rootnodetoolswafadminutilspy line loadmodule execcompilecode filepath exec moduledict file rootnodewscript line pre nodeisrelease else syntaxerror invalid syntax that content configure binsh v like ccache z echo cc grep ccache echo error v like cache please set cc env var gcc echo bash export ccgcc exit fi curdirpwd possible relative path workingdirdirname cd workingdir abs path workingdirpwd cd curdir workingdirtoolswaflight jobs configure exit and top wscript following line usrbinenv python i also tried replacing something else though i think work using python alias any ideas i need get work thanks,1 a b c d e f h i j print maplist prints a b c d e f h i j,ok i got information form a b c d e f h i j i would like convert a b c d e f h i j what besteasiest way,2 data a b c d e f h i j listtup tup data a b c d e f h i j,ok i got information form a b c d e f h i j i would like convert a b c d e f h i j what besteasiest way,2 list comprehension tpl a b c d e f h i j lst listx x tpl,ok i got information form a b c d e f h i j i would like convert a b c d e f h i j what besteasiest way,3 if know structure two levels try x a b c d e f h i j listt x if might deeper nesting want recursion see fj answer,ok i got information form a b c d e f h i j i would like convert a b c d e f h i j what besteasiest way,1 on debian install vimgnome vimnox dont xserver system sudo aptget install vimnox these versions include python support vim,i installed vim debian system along vimrc downloaded internet it used work fine debian machine get error messages load vim editor here errors error detected processing hometejindervimplugingundovim line e sorry command available version python endpython line e not editor command def asciiedgesseen rev parents line e undefined variable rev e invalid expression rev seen line e return inside function line e return inside function line e return inside function line e return inside function line e missing line e missing line e missing line e missing line e missing line e return inside function line e missing endfor press enter type command continue if anyone could figure thats going please guide thanks lot here vimrc source httpsgithubcommitsuhikodotfilestreemastervim,3 here simple recursive solution number nested tuples tup a b c d e f h i j listify lambda x maplistify x isinstancex tuple else x listifytup a b c d e f h i j for python replace maplistify x listmaplistify x,ok i got information form a b c d e f h i j i would like convert a b c d e f h i j what besteasiest way,1 it looks like problem use shelltrue from python documentation popen on unix shelltrue if args string specifies command string execute shell this means string must formatted exactly would typed shell prompt this includes example quoting backslash escaping filenames spaces if args sequence first item specifies command string additional items treated additional arguments shell so looks like echo command test gets sent argument shell instead echo so changing subprocess call either subprocesscallecho test stdoutlogfile stderrsubprocessstdout shelltrue subprocesscallecho test stdoutlogfile stderrsubprocessstdout fixes problem least testing,i seeing odd behaviour i open file append mode windows using python i wondering whether behaviour fact incorrect i misunderstanding use following code logfile openlogfilepath returncode subprocesscallmake target stdoutlogfile stderrsubprocessstdout logfileclose the code lines properly append file in fact subsequent runs even modify file i tested using python shell well once file opened first time making multiple subprocess calls append properly file however file closed reopened never append anyone clues thanks to simply problem here another set steps fail logfileopentemptxt logfilewritethis is a test logfileclose logfileopentemptxt subprocesscallecho test stdoutlogfile stderrsubprocessstdout shelltrue logfileclose if open file temptxt i see test s a muther f test,1 i think way naively consumer level pika consumers default priority what i might solve problem would two queues suggested mailing list queue consumer in consumer callback consumer instead dealing message directly i would put priority queue call function reads highest priority message queue handles another question similar response,i looking implement priority queue rabbitmq the mailing list recommends use multiple queues queue representing different priority level my question poll multiple queues prioritized order using pika possibly python library,2 bsb x x data data mylist,ok i list a b c d e f g h i i want add html tags values inner lists how would i go ie bab bbb bcb bdb beb bfb bgb bhb bib,3 like def addhtmls return b b def addhtmlarraya return mapaddhtml mapaddhtmlarray yourlist,ok i list a b c d e f g h i i want add html tags values inner lists how would i go ie bab bbb bcb bdb beb bfb bgb bhb bib,1 l a b c d e f g h i b b subl subl l bab bbb bcb bdb beb bfb bgb bhb bib,ok i list a b c d e f g h i i want add html tags values inner lists how would i go ie bab bbb bcb bdb beb bfb bgb bhb bib,1 i think legal xml opening tag associated even somewhere else properly nested example the expression interpreted closing tag character,i number xml files i need parse i written code works ugly i like get advice people experienced xml i first i might using terms wrong context experience xml limited by element unless specified otherwise i mean something like root element element element element root anyway file consist number elements number child elements obviously what stumps relevant values need accessed four different ways node text tagvaluetag attribute tag attributevaluetag a value hidden inside tag true case tagbooleantruetag values inside tags name taga grandparent tags different names tag tag within element taga use instead i looking tag tag element tagtagavaluetagatag tagtagavaluetagatag element at moment i dictionary file key the values dictionaries keys attribute node text tag parent element example filexml attributes person id car color node text name address where person car tags id color attribute names this makes easy iterate elements inspect tag match dictionary elemtag dict filexml attributes extract value so i said code works i like solution also elements child elements example person might car tag missing altogether i need give assign values none right i get tags exist every element file turn set check difference set tags i actually extracted values element again code pretty ugly hopefully mess makes sense edit i used jf sebastian suggestion storing xpath value dictionary field name key xpath value,1 are sure using pyramid every thing posted pylons pyramid they different frameworks assuming using pylons urlfor deprecated you instead using url global variable imported pylons import url,i attempting use urlfor inside mako template pyramid using book example hurlforcontroller formtest action submit when i i get error attributeerror threadlocal object attribute mapper i installed routes put helperspy file import webhelpershtmltags tags routes import urlfor googling error i read urlfor deprecated pylons is true pyramid if i using,1 oswalk go files directory subdirectories recursively osrename rename the encoding files pays role i think you course detect extension use ospathsplitext something based long need rename files ie manipulate names contents hardly matter,i directory music album folders well individual songs level how i traverse files also encoded different formatsmp wav etc in addition way i rename format consistent liking using regular expressions thanks,3 first think convention use lowercase underscores attributes python classes next use useragencypositionsetall think returns queryset object instance class want think might need instance access attributes to get users agency useragencypostiionsetallagency this agency object connected particular user,i models class agencymodelsmodel locationmodelsforeignkeylocation namemodelscharfieldmaxlength websitemodelscharfieldmaxlength class agencypositionmodelsmodel agencymodelsforeignkeyagency usersmodelsmanytomanyfielduser phonenumbermodelscharfieldmaxlength emailmodelscharfieldmaxlength user login i wanna get agency user belonge i use get user position agnpositionuseragencypositionsetall every thing good til herenow wanna get agency agnposition i tryed many things like agnagencyobjectsgetpkagnpositionagencysetid agnagencyobjectfilterpkagnpositionagencyid agnagencyobjectfilterpkagnpositionagencyid errors like queryset object attribute agency i handle thanks advance help d,1 i use piece code program i wrote i use get recursive list image files call pattern something like recompiler bmpjpgpng reignorecase i think get idea def getfilesdirname suffixpatternnone dirnameospathnormpathdirname retdirs retfiles root dirs files oswalkdirname dirs retdirsappendospathjoinroot files suffixpattern none suffixpatternsearchi none retfilesappendroot return retdirs retfiles after list would easy apply renaming rule osrename friend see httpdocspythonorglibraryoshtml,i directory music album folders well individual songs level how i traverse files also encoded different formatsmp wav etc in addition way i rename format consistent liking using regular expressions thanks,1 you need ssl support ubuntu sudo aptget install libssldev centos yum install openssldevel open pythonpathmodulessetupdist uncomment ssl related content make sure ssl variable points ssl installation path recompile python configure enablessl amp make amp make install,i trouble installing cherrypy linux machines ubuntu centos i latest python pip version installed machines on ubuntu i using sudo pip install cherrypy on centos i installing source after install finished succeeded importing cherrypy module i get error import cherrypy traceback recent call last file stdin line module file usrlocallibpythonsitepackagescherrypyinitpy line module cherrypycpcompat import urljoin urljoin urlencode urlencode file usrlocallibpythonsitepackagescherrypycpcompatpy line module httpcookies import simplecookie cookieerror importerror no module named httpcookies i looked docs seems httpcookies python i missing anything machine i tried clean never python installed,1 using alrfflkafdfaeglkayeurfsbbvvcbf import rrecompileazazaz rfindalla ayeurfs,i lot scrambled letters in letters find pattern xxxxxxx which means three uppercase letters one lowercase another three uppercase i using python solve problem way easily also i would like print lowercase letters without uppercase ones how i,1 for particular reason datetimestrptime missing ironpython if stuck older version use timestrptime instead,i trying port program mine running cpython interpreter ironpython the latest part stumps i use datetime class datetime module here happens i try use strptime function â» datetime import datetime â» dt datetimestrptime dmy hm traceback recent call last file string line module attributeerror type object attribute strptime â» is something i need aware makes datetime specially different ironpython,1 for complex text loading look numpygenfromtxt it slower numpyloadtxt flexible in case i avoiding saving temporary file import numpy np import urllib url httpwwwcdcnoaagovcorrelationamonuslongdata data npgenfromtxturlliburlopenurl skipheader skipfooter,i trying generate array reading text file internet my target use python instead matlab replace step matlab url httpwwwcdcnoaagovcorrelationamonuslongdata urlwriteurl filetxt i using code urlliburlretrieve httpwwwcdcnoaagovcorrelationamonuslongdata usersepyfiletxt nploadtxt usersepyfiletxt skiprows dtypenone but fails text description end file do know exist way skip x lines end i use sort string manipulation readlines instead,3 i suggest use truncatewords template filter template example ul blogpost blogposts libblogposttitleb blogpostcontenttruncatewordsli endfor ul if blog content stored html use truncatewordshtml ensure open tags closed truncation point combine striptags remove html tags if want truncate characters words use slice blogpostcontentslice outputs first characters if content stored html combine striptags avoid open tags problems blogpostcontentstriptagsslice,i building blog application django i display blogs i want display small blog excerpt entry can anybody tell i one way would make extra field store fixed number words blog entry let say words but would storing redundant information database is better way,3 the logical control structure decides whether code executed consider this throw error in contrast following throw error matter function implemented def logicalora b return b logicalor,in python operatoror equivalent bitwise logical why operator logical,3 generally yes seem things correctly far i know the ringing due overly sharp high pass filter method using however might consider using numpyfftrfft real fft numpyfftirfft instead numpyfftfft numpyfftifft dealing purely real values it slightly faster,as part digital image processing class assigned inverse filter image restoration i using numpy the variable names try follow names digital image processing gonzalezwoods e a zoom original image gaussian kernel zztif size original image zoom gaussian smoothed image noise added f imtoolsloadimage sysargv model dtypefloat zz imtoolsloadimage zztif model dtypefloat f npfftfft f f npfftfftshift f normalize h zz calculate damaged image g h f inverse filter fhat g h cheat replace division zero nan zeroes npnantonumfhat fhat npfftifft npfftifftshifta imtoolssaveimage npabsfhat outtif imtools wrapper using pilnumpy loadstore images can post src zoom inverse filtered image am i calculating inverse filter correctly am i using numpy correctly is ringing final image expected i something wrong,2 the operators expressed functions shortcircuiting behavior false somefunction true somefunction cases somefunction never called a hypothetical ortrue somefunction hand would call somefunction function arguments always evaluated function called,in python operatoror equivalent bitwise logical why operator logical,3 python type checks go together learn live it job whoever uses code pass proper types document code expects check explicitly there collections lists tuples why would forbid say namedtuple python dynamic language fight writing type checks look eafp python glossary don try anticipate errors deal happen a reasonable thing might instead type checking converting list selfteams listtms listincompatible types cause exception raised line sure dealing list it prevent someone assigning nonstrings list course oh ever good reason need type check use isinstance function instead comparing type that also catch subclasses whatever required type and try use general base type the proper way test string unicode otherwise isinstancemyobject basestring and proper way check listlike collection – narrowminded “list tuple” – import collections isinstancemyobject collectionssequence but aside proper solution problem don type checking without good reason,i new python i would like help i created classes properties order keep passing meaningless arguments so example i class class matchobject teamsnonenone def setteamsselftms typetms typelist typetms typetuple raise exceptionteams must list length lentms raise exceptionteams must list length typetmstypestr typetmstypeunicode typetmstypestr typetmstypeunicode selfteamstms else raise exceptionboth teams must strings return teamspropertygetteamssetteams if i write matchmatch matchteams i get exception i matchteams raise exception passes number please keep mind class i wrote relative question assume code behaves i describe i guess everything passed reference python i careful assign meaningless data objects defeats purpose properties first place so way fix apart using lists i learn live,2 get instance instead query set using useragencypositionsetall if slice queryset get another queryset need instance agnposition useragencypositionsetall is typo agencyposition class is class agencypositionmodelsmodel agencymodelsforeignkeyagent or class agencypositionmodelsmodel agencymodelsforeignkeyagency update i think correct agnagencyobjectsgetpkagnpositionagencysetid agencyset relatedmanager object attribute id try agnposition useragencypositionsetall agn agencyobjectsgetpkagnpositionagencypk and please oh god please uppercase field names,i models class agencymodelsmodel locationmodelsforeignkeylocation namemodelscharfieldmaxlength websitemodelscharfieldmaxlength class agencypositionmodelsmodel agencymodelsforeignkeyagency usersmodelsmanytomanyfielduser phonenumbermodelscharfieldmaxlength emailmodelscharfieldmaxlength user login i wanna get agency user belonge i use get user position agnpositionuseragencypositionsetall every thing good til herenow wanna get agency agnposition i tryed many things like agnagencyobjectsgetpkagnpositionagencysetid agnagencyobjectfilterpkagnpositionagencyid agnagencyobjectfilterpkagnpositionagencyid errors like queryset object attribute agency i handle thanks advance help d,1 this error failing typecheck unless misrepresented code obviously edited posted run correctly happening matchteams calls getteams function setteams function to see try exercise class matchobject teamsnonenone def setteamsselftms print set selfteams tms def getteamsself print get return selfteams teamspropertygetteamssetteams when i try i get following match match matchteams get traceback recent call last file stdin line module typeerror tuple object support item assignment matchteams teamteam set matchteams get,i new python i would like help i created classes properties order keep passing meaningless arguments so example i class class matchobject teamsnonenone def setteamsselftms typetms typelist typetms typetuple raise exceptionteams must list length lentms raise exceptionteams must list length typetmstypestr typetmstypeunicode typetmstypestr typetmstypeunicode selfteamstms else raise exceptionboth teams must strings return teamspropertygetteamssetteams if i write matchmatch matchteams i get exception i matchteams raise exception passes number please keep mind class i wrote relative question assume code behaves i describe i guess everything passed reference python i careful assign meaningless data objects defeats purpose properties first place so way fix apart using lists i learn live,3 install pytz import pytz import time import locale import urllib yourolsontz none yourcountrycode localegetdefaultlocalesplit yourcountrycode urlliburlopen httpapihostipinfocountryphp read olsontz pytztimezoneolsontz olsontz pytzalltimezones olsontztzname timetzname strolsontz pytzcountrytimezonesyourcountrycode yourolsontz olsontz break print yourolsontz this code take bestguess crack olson timezone based timezone name according python time module country code according python locale module hostipinfo project references ip address geolocates accordingly for example simply matching timzone names could result americamoncton americamontreal americanewyork est gmt if country us however limit answer americanewyork however country canada script simply default topmost canadian result americamoncton if way refine please feel free leave suggestions comments,how i get olson timezone name australiasydney corresponding value given c localtime call this value overridden via tz symlinking etclocaltime setting timezone variable timerelated system configuration files,3 i guessing nul byte inputcsv you test open inputcsv read print null bytes input file else print reader csvreaderxreplace x mycsv may get around or may indicate utf something interesting csv file,i trying write program looks csv file inputcsv rewrites rows begin certain element correctedcsv listed text file outputtxt this program looks like right import csv lines open outputtxt r f line freadlines linesappendline open correctedcsv w correct writer csvwritercorrect dialect excel open inputcsv r mycsv reader csvreadermycsv row reader row lines writerwriterowrow unfortunately i keep getting error i clue traceback recent call last file cpythonsample programcsvparserpy line module row reader csverror line contains null byte credit people even get point solved input file csv hiding one extension,3 this tell line problem import csv lines open outputtxt r f line freadlines linesappendline open correctedcsv w correct writer csvwritercorrect dialect excel open inputcsv r mycsv reader csvreadermycsv try row enumeratereader row lines writerwriterowrow except csverror print csv choked line raise perhaps daniweb would helpful i getting error reading csv file runtime error line contains null byte any idea root cause error ok i got thought i post solution simply yet caused grief used file saved xls format instead csv didn catch file name csv extension type still xls,i trying write program looks csv file inputcsv rewrites rows begin certain element correctedcsv listed text file outputtxt this program looks like right import csv lines open outputtxt r f line freadlines linesappendline open correctedcsv w correct writer csvwritercorrect dialect excel open inputcsv r mycsv reader csvreadermycsv row reader row lines writerwriterowrow unfortunately i keep getting error i clue traceback recent call last file cpythonsample programcsvparserpy line module row reader csverror line contains null byte credit people even get point solved input file csv hiding one extension,1 the syntax slightly different display manytomany relations using inline class iteminlineadmintabularinline model categoryitemsthrough class categoryadminadminmodeladmin inlines iteminline exclude items see django admin docs working manytomany models details,in admin i want use inline elements i want category display items related but i get error exception adminstorecategory class storemodelsitem foreignkey class storemodelscategory it true ofcourse since i chose use category point items but i get admin list inline items given category how i get around error context class category itemsmodelsmanytomanyfielditemthrough categoryhasitem class categoryhasitemmodelsmodel category modelsforeignkeycategory dbcolumn category item modelsforeignkeyitem dbcolumn item class itemmodelsmodel id modelsautofieldprimarykeytrue this adminpy file class iteminlineadmintabularinline modelitem class categoryadminadminmodeladmin inlinesiteminline class itemadminadminmodeladmin pass adminsiteregistercategory categoryadmin adminsiteregisteritem itemadmin,1 this get forward this script prints links webpage using regular expression import urllib page urlliburlopenhttpsebsauvagenetindexhtmlread urls refindall href page url urls print url,i new python i questions def extractdownloadurlurl uresponse urlliburlopenurl open url contents uresponsereadlines readlines url file fo opentesthtmlw open testhtml line contents fowritelinewrite lines url file text file focloseclose text file cadena ossystem testhtml grep uploads grep zip cadenahtml f opencadenahtmlr text fread fclose match researchr href text match cadenamatchgroup texto cadena ossystem rm testhtml ossystem rm cadenahtml return texto this function download webpage take one url following conditions it works but i want apply efficient way saving web file i want make something similar grep without save read files it really slow and faster way copy url string please write code look url inside contents without saving contents file i know lot questions i would grateful answer,1 you looking natural language library for python natural language toolkit nltk for example could take look punktsentencetokenizer the punktsentencetokenizer divides text list sentences using unsupervised algorithm build model abbreviation words collocations words start sentences it must trained large collection plaintext taret language used the algorithm tokenizer described kiss amp strunk kiss tibor strunk jan unsupervised multilingual sentence boundary detection computational linguistics the nltk data package includes pretrained punkt tokenizer english,i curious library python or javascript tokenize sentences string sentences put new line sentence ie lorem ipsum dolor sit amet consectetur adipiscing elit vestibulum aliquet leo urna hendrerit placerat donec adipiscing dignissim adipiscing duis adipiscing mollis cursus etiam fringilla elit nec enim sagittis auctor nisi gravida nunc sollicitudin leo sit amet consequat pharetra mi orci vestibulum mi suscipit odio tellus tincidunt erat suspendisse consequat turpis morbi eget ante leo dignissim mi lorem ipsum dolor sit amet consectetur adipiscing elitn vestibulum aliquet leo urna hendrerit placeratn donec adipiscing dignissim adipiscing n duis adipiscing mollis cursus etiam fringilla elit nec enim sagittis auctor nisi gravida nunc sollicitudin leo sit amet consequat pharetra mi orci vestibulum mi suscipit odio tellus tincidunt erat n suspendisse consequat turpis n morbi eget ante leo dignissim mi,2 page never work leading makes relative website root rather current directory page work everything except without trailing slash somethingelse interpreted file rather current directory one solution would link somethingsomethingelsepage link change based user address,i know current user location it one following url httpmyappappspotcomsomethingsomethingelse httpmyappappspotcomsomethingsomethingelse httpmyappappspotcomsomethingsomethingelsepage httpmyappappspotcomsomethingsomethingelsepage actually addresses page i need display pages link page httpmyappappspotcomsomethingsomethingelsepage the question generate link i tried use relative links page page work properly i sure create absolute link selfrequestpath work properly also,1 to concatenate lists use sum values sum a b c d e f g h i to add html tags use list comprehension htmlvalues tr tr values,how i merge list lists a b c d e f g h i a b c d e f g h i even better i add value beginning end item merging lists like html tags ie end result would tratr trbtr trctr trdtr tretr trftr trgtr trhtr tritr,1 import itertools print trstr x x itertoolschainfromiterablel you use sum i think kinda ugly pass parameter as raymond points also expensive so use sum,how i merge list lists a b c d e f g h i a b c d e f g h i even better i add value beginning end item merging lists like html tags ie end result would tratr trbtr trctr trdtr tretr trftr trgtr trhtr tritr,1 one advantages property able data validation sometimes really important make sure get something specific in case need one two things store teams data structure modified tuple namedtuple data retrieved cannot changed get method return copy data modification mess original the first solution immutable types looks like class matchobject teamsnonenone def setteamsselftms sequence type long length two lentms raise typeerror teams must sequence length isinstancetms str unicode raise typeerror team names must str unicode r typetms isinstancetms str unicode raise typeerror team names must str unicode r typetms selfteams tupletms def getteamsself return selfteams teamspropertygetteamssetteams and try assign getting value happens traceback recent call last file testpy line module matchteams typeerror tuple object support item assignment the second solution returning copy instead original looks like class matchobject teamsnonenone def setteamsselftms sequence type long length two lentms raise typeerror teams must sequence length isinstancetms str unicode raise typeerror team names must str unicode r typetms isinstancetms str unicode raise typeerror team names must str unicode r typetms selfteams listtms def getteamsself return listselfteams teamspropertygetteamssetteams code action matchmatch matchteams us u matchteams print matchteams following results us u as see changes make back match object,i new python i would like help i created classes properties order keep passing meaningless arguments so example i class class matchobject teamsnonenone def setteamsselftms typetms typelist typetms typetuple raise exceptionteams must list length lentms raise exceptionteams must list length typetmstypestr typetmstypeunicode typetmstypestr typetmstypeunicode selfteamstms else raise exceptionboth teams must strings return teamspropertygetteamssetteams if i write matchmatch matchteams i get exception i matchteams raise exception passes number please keep mind class i wrote relative question assume code behaves i describe i guess everything passed reference python i careful assign meaningless data objects defeats purpose properties first place so way fix apart using lists i learn live,1 don use sum slow joining lists instead nested list comprehension work x a b c d e f g h i elem sublist x elem sublist a b c d e f g h i tr elem tr elem the advice use itertoolschain also good,how i merge list lists a b c d e f g h i a b c d e f g h i even better i add value beginning end item merging lists like html tags ie end result would tratr trbtr trctr trdtr tretr trftr trgtr trhtr tritr,3 the easygui tutorial section using multienterbox you put field names list fieldnames name query burns anxiety inventory query pass multienterbox along window title title message msg fieldvalues multenterboxmsgtitle fieldnames if still need values individual fields could unpack tuple include one variable name value fieldvalues namegui baigui bdcgui fieldvalues,how i make easygui multienterbox questions one window namegui easyguienterboxmsg enter name title name query default gian baigui easyguienterboxmsg enter bai title burns anxiety inventory query default gian bdcgui easyguienterboxmsg enter bdc title burns depression checklist query default gian yeargui easyguienterboxmsg enter current year title current year default monthgui easyguienterboxmsg enter current month title current month daygui easyguienterboxmsg enter current day title current day timehourgui easyguienterboxmsg enter current hour title current hour timeminutegui easyguienterboxmsg please enter current minutes title current minute ampmgui easyguienterboxmsg please enter either pm title am or pm i using python mac os x snow leopard,1 the length check shortest sensible filename single character followed py gives least characters the last checks seem trying ingore compiled files extensions pyc pyo totally unnecessary match condition f py for splitting filename root extension also consider using ospathsplitext root root ext mapospathsplitext oslistdirpath ext py,please meaning line return ffrindex f oslistdirpath f lenf f py f f c i found script link httpwwwuserscsumnedumeinblenderpluginspythonmiscscriptloadertheonescriptpy i know needed split file name extenstion py lenf f c mean,2 this line returns files directory least characters long end c end py it cuts remainer files blubberpy converted blubber i suggest following solution x x oslistdir xendswithpy,please meaning line return ffrindex f oslistdirpath f lenf f py f f c i found script link httpwwwuserscsumnedumeinblenderpluginspythonmiscscriptloadertheonescriptpy i know needed split file name extenstion py lenf f c mean,1 assuming rows equal length approach like data list mareader csvreaderopen testcsv rb delimiter quotechar rindex row enumeratemareader iindex item enumeraterow lendata iindex dataappend dataiindexappenditem,i looking flip rows columns d list running trouble python allow value assigned uninitialized cell i sure initialize grid since i know length ahead time the following data list mareader csvreaderopen testcsv rb delimiter quotechar rindex row enumeratemareader iindex item enumeraterow dataiindexrindex item fails indexerror list assignment index range error i could loop twice first time count columns rows initialize grid loop assign values seems awfully wasteful i pretty new python figure simple way i missing thanks help,1 i think mix tkinter cocoa toolkits interchangeably selfroot attribute class app inherits appkitnsapplication my guess tk call returns pointer passed cocoa frameworks points tk data structure understand also tkinter pyobjc need eventloop i sure even mix two though i never tried my recommendation would use one ui toolkit,the following simple code pyobjctools import apphelper import appkit import tkinter class appappkitnsapplication def finishlaunchingself selfroottkintertk appsharedapplication apphelperruneventloop yields following exception pythond app setup unrecognized selector sent instance xd what i wrong,1 to answer question getting url use urllib execute javascript code url browserexecutescriptreturn windowlocation,how i get html source variable using selenium module python i wanted something like selenium import webdriver browser webdriverfirefox browsergetrawinputenter url whatever htmlsource do something else do something else how i i know access html source,1 joekington numpy solution clever relies a sorted order here fix general case import numpy np nprandomseed n a nparangenreshape nprandomshufflea printa if a looks like v v acopy nprandomshufflev printv looks like use joe solution vals order npuniquenphstackav returninversetrue save order a v aorder ordervsize vorder ordervsize sort a forming anpargsortaorder reordering vorder print anpargsortaordervorder anpargsortaorder a sorted according second column note npunique always returns array sorted order the documentation guarantees returninversetrue returned indices indices unique array reconstructs original array that call npunique like uniqarr indices npuniquearr returninversetrue guaranteed uniquearrindices arr because rely relationship joe method depend mere implementation detail unique always behave way famous last words considering happened order output arguments returned npuniqued never mind,i matrix a vector values v i would like reorder a nd column using values v the result a nd columns values order v how,3 i suggest f f globiglobpy concise alternative given code,please meaning line return ffrindex f oslistdirpath f lenf f py f f c i found script link httpwwwuserscsumnedumeinblenderpluginspythonmiscscriptloadertheonescriptpy i know needed split file name extenstion py lenf f c mean,1 with exception multicast sockets connections you maintain list open sockets somewhere send message the port connect creating socket merely means client connected service here might add connection list broadcast of course i strongly recommend code handle dead andor closed connections remove list well i going general idea especially since i coded python years i based code snippet pywbsocket example code different note i considered thread safety either concern connections def websocketdoextrahandshakerequest connectionsappendrequest pass def websockettransferdatarequest true line msgutilreceivemessagerequest connection connections msgutilsendmessageconnection line line bye return,hello i trying use python pywebsocket html server use given example file echos back whatever received def websockettransferdatarequest count count line requestwsstreamreceivemessage print line requestwsstreamsendmessageline it works fine one webpage use two clients two webpages connection socket server ports script works what trying messages broadcasted socket server message echoed back listened cient webpages but unforutnally work i confused pages listening socket working is workaround modification need make socket server transfer message broadcast connected clients please help,2 this mareader csvreaderopen testcsv rb delimiter quotechar data zipmareader though zip gives list tuples if need list lists either data listx x zipmareader data maplist zipmareader,i looking flip rows columns d list running trouble python allow value assigned uninitialized cell i sure initialize grid since i know length ahead time the following data list mareader csvreaderopen testcsv rb delimiter quotechar rindex row enumeratemareader iindex item enumeraterow dataiindexrindex item fails indexerror list assignment index range error i could loop twice first time count columns rows initialize grid loop assign values seems awfully wasteful i pretty new python figure simple way i missing thanks help,1 here eafp counterpoint retracile lbyl approach data list mareader csvreaderopen testcsv rb delimiter quotechar rindex row enumeratemareader iindex item enumeraterow try dataiindexappenditem except indexerror dataappenditem,i looking flip rows columns d list running trouble python allow value assigned uninitialized cell i sure initialize grid since i know length ahead time the following data list mareader csvreaderopen testcsv rb delimiter quotechar rindex row enumeratemareader iindex item enumeraterow dataiindexrindex item fails indexerror list assignment index range error i could loop twice first time count columns rows initialize grid loop assign values seems awfully wasteful i pretty new python figure simple way i missing thanks help,2 sqlite stores unicode strings it likely url unicode need convert you store url blob binary instead make life complicated later,when i want insert string python code sqlite database i get error sqliteprogrammingerror you must use bit bytestrings unless use textfactory interpret bit bytestrings like textfactory str it highly recommended instead switch application unicode strings this insert statement curexecuteinsert links url title values url title locals the string came existence follows soup beautifulsouphtmlread fromencodingutf htmlclose soupfindall url href title irendercontents could advise insert string sqlite database edit i found url string ok inserting another table the type url string unicode the problem inserting title string the type title string str i tried title unicodeirendercontents ends error unicodedecodeerror ascii codec decode byte xc position ordinal range thank,2 change delimiter get list values csv reader,i csv file thru i want parse data lists so i using python csv module read basically following import csv fin csvreaderopenpath rb delimiter quotechar print fin gives following lets say following ele strfin ele elestripsplit print ele gives following ele gives output how i get rid in end i want get convert integer any clues happening thanks edit never mind resolved thanks first comment,1 you spawn bunch subprocesses inherit current value hits each subprocess get copy hits modifies exits dropping processlocal copy hits the intended use multiprocessingpoolmap use return value ignoring each process could return copy hits finally join copies,hello i trying define values dictionary parallel using multiprocessing when function f called outside pool dictionary value set correctly in pool call however fails what i wrong thanks multiprocessing import pool hits def fx hitsx x involve complex operation f print hits name main pool poolprocesses inputs b c result poolmapf inputs print hits,3 one problem multiple pretty names like australiasydney point time zone eg cst so need get possible names local time zone select name like eg australia time zones way time zone identifiers australialordhowe australiahobart australiacurrie australiamelbourne australiasydney australiabrokenhill australiabrisbane australialindeman australiaadelaide australiadarwin australiaperth australiaeucla check library wraps tzinfo handle time zone api eg python check pytz library httppytzsourceforgenet httppypipythonorgpypipytz python pytz import timezone import pytz in pytzcountrytimezones au out u australialordhowe u australiahobart u australiacurrie u australiamelbourne u australiasydney u australiabrokenhill u australiabrisbane u australialindeman u australiaadelaide u australiadarwin u australiaperth u australiaeucla api python seems pretty limited eg seem call like ruby alllinkedzonenames find synonym names given time zone,how i get olson timezone name australiasydney corresponding value given c localtime call this value overridden via tz symlinking etclocaltime setting timezone variable timerelated system configuration files,3 rows equal length data zipmareader if itertools import iziplongest listiziplongestf fillvalue see also matrix transpose python,i looking flip rows columns d list running trouble python allow value assigned uninitialized cell i sure initialize grid since i know length ahead time the following data list mareader csvreaderopen testcsv rb delimiter quotechar rindex row enumeratemareader iindex item enumeraterow dataiindexrindex item fails indexerror list assignment index range error i could loop twice first time count columns rows initialize grid loop assign values seems awfully wasteful i pretty new python figure simple way i missing thanks help,1 you appending five different lists result you appending list five times you fix appending copy list result ruudukkoappendrivi see working online ideone,size input kirjainmã¤ã¤r㤠kirjaimet abcdefghijklmnopqrstuvwxyz ruudukko rivi size rangesize produce n rows rangei row needs letters z rangeisizei riviz kirjaimetsizei print rivi ruudukkoappendrivi print ruudukko so code supposed produce number matrices format input output ddddddd dcccccd dcbbbcd dcbabcd output code input print rivi part e e e e e e e e e e d d d d d d d e e d c c c c c d e e d c b b b c d e e d c b a b c d e everythings ok far e d c b a b c d e e d c b a b c d e e d c b a b c d e e d c b a b c d e e d c b a b c d e the appended list ruudukko comes filled object appended last what hell going,1 listappend stores reference object appended so stored multiple references list rivi list ruudukko naturally since actually object change one changes everywhere referenced make fresh rivi list time loop this behavior strange normal expected covered decent python tutorial,size input kirjainmã¤ã¤r㤠kirjaimet abcdefghijklmnopqrstuvwxyz ruudukko rivi size rangesize produce n rows rangei row needs letters z rangeisizei riviz kirjaimetsizei print rivi ruudukkoappendrivi print ruudukko so code supposed produce number matrices format input output ddddddd dcccccd dcbbbcd dcbabcd output code input print rivi part e e e e e e e e e e d d d d d d d e e d c c c c c d e e d c b b b c d e e d c b a b c d e everythings ok far e d c b a b c d e e d c b a b c d e e d c b a b c d e e d c b a b c d e e d c b a b c d e the appended list ruudukko comes filled object appended last what hell going,1 if mind lack short circuiting behaviour mentioned others could try code alla b b anya b b they accept single collection list tuple even generator elements following also valid alla b c b c for details look documentation question httpdocspythonorgpyklibraryfunctionshtmlall,in python operatoror equivalent bitwise logical why operator logical,1 in brief intfinputstrip but set quotechar are sure instead with set get strings without quotes,i following piece code i reading csv parsing contents list import csv finput inputreaderopenpath rb delimiter quotechar print finput output now i want extract number first element print finput gives now i convert integer el intfinput i get error valueerror invalid literal int base why double quotes what clean way extract integer,3 use strip el intfinputstrip astrip intastrip the documentation strip follows return copy string leading trailing characters removed if chars omitted none whitespace characters removed if given none chars must string characters string stripped ends string method called,i following piece code i reading csv parsing contents list import csv finput inputreaderopenpath rb delimiter quotechar print finput output now i want extract number first element print finput gives now i convert integer el intfinput i get error valueerror invalid literal int base why double quotes what clean way extract integer,1 linestrip or want eat lines consisting spaces line n rn,trying figure write cycle check line empty the file many strings one blank line separate statements carriage return followed another carriage return think new statement asdasdasd asdasdasdasd new statement asdasdasdasd asdasdasdasd since using file input module way check line empty using code seems work thanks everyone line x line n print found end line xclose,3 if evaluating etclocaltime ok following trick might work translating python mdsum etclocaltime abcdefabcdefabcdefabcdefabcdefab etclocaltime find usrsharezoneinfo type f xargs mdsum grep abcdefabcdefabcdefabcdefabcdefab abcdefabcdefabcdefabcdefabcdefab usrsharezoneinfoeuropelondon abcdefabcdefabcdefabcdefabcdefab usrsharezoneinfoposixeuropelondon the duplicates could filtered using official region names europe america if still duplicates could take shortest name,how i get olson timezone name australiasydney corresponding value given c localtime call this value overridden via tz symlinking etclocaltime setting timezone variable timerelated system configuration files,3 if want ignore lines whitespace linestrip something the empty string false value or really want empty lines line n rn something,trying figure write cycle check line empty the file many strings one blank line separate statements carriage return followed another carriage return think new statement asdasdasd asdasdasdasd new statement asdasdasdasd asdasdasdasd since using file input module way check line empty using code seems work thanks everyone line x line n print found end line xclose,3 you open text files using ru newlines properly transformed see httpdocspythonorglibraryfunctionshtmlopen this way need check rn,trying figure write cycle check line empty the file many strings one blank line separate statements carriage return followed another carriage return think new statement asdasdasd asdasdasdasd new statement asdasdasdasd asdasdasdasd since using file input module way check line empty using code seems work thanks everyone line x line n print found end line xclose,1 though strictly necessary url could store unicode beautifulsoup works unicode beautifulsoup import beautifulsoup soup beautifulsoupa hrefascii fromencodingutf isinstancesoup hreftrue href unicode true soup beautifulsoupa hrefî±î²î³ fromencodingutf soup hreftrue href u ububub in cases url unicode you could call isinstance type find type url you could specify encodingnone get unicode irendercontentsencodingnone in general might helpful use dirobj helpobjmethod interactive python console see also printing document,when i want insert string python code sqlite database i get error sqliteprogrammingerror you must use bit bytestrings unless use textfactory interpret bit bytestrings like textfactory str it highly recommended instead switch application unicode strings this insert statement curexecuteinsert links url title values url title locals the string came existence follows soup beautifulsouphtmlread fromencodingutf htmlclose soupfindall url href title irendercontents could advise insert string sqlite database edit i found url string ok inserting another table the type url string unicode the problem inserting title string the type title string str i tried title unicodeirendercontents ends error unicodedecodeerror ascii codec decode byte xc position ordinal range thank,1 the default ctypes result type bit integer file handle pointer width ie bits you therefore losing half information file pointer before call fopen must state result type pointer libcfopenrestype ctypescvoidp fp libcfopen libcfclosefp,i want call msvcrt functions bit python using ctypes package i obviously wrong is right way obvious python default jun msc v bit amd win type help copyright credits license information import ctypes libc ctypescdllmsvcrt fp libcfopen texttxt wb seems work creates file libcfclosectypescvoidpfp traceback recent call last file stdin line module windowserror exception access violation reading xffffffffffb if code i want would opened closed text file without crashing,3 insufficiently tested use risk import numpy numpyrandomrandom abyaij ai aj abya anumpynewaxis anumpynewaxis taking upper triangular ignore cases j abya numpytriuabya argmax give first index highest value case print numpyargmaxabya axis lower memory version numpyrandomrandom numpyvectorize def valuesi try return ai ainonzero except indexerror return valid values found b valuesnumpyarange faster version npvectorize def valuesi try return nextidx idx value enumerateai value ai except stopiteration return valid values found return valuesnparangelena even faster version def futurea list tuples index a value a invariant indexes values sorted order known result idx xrangelena value aidx since known sorted binary search could applied i bothered anything lower current value cannot possibly used since value first index instead known xy xy known value known values known current value reverse sorted index value lowest index first resultappendknown else values exist high report resultappend add end list maintain invariant knownappend idx value let numpy worry reversing array return nparrayresult credit cyborg ideas used algorithm difference cyborg showed significant differences various algorithms depending data fed i gathered stats running algorithms see i could figure going random data average distance value target average length ascends list average length segment ascends list average length known list since lists really short ascents algorithm mostly decays linear search it clear ascents cannot used future still noticably better linear search oscillating average distance value target average length ascends list average length segment ascends list average length known list the oscillations tend put different pieces apart this naturally hampers linear search algorithm both smarter algorithms keep track additional data my algorithm decays considerably since scans data time the ascends algorithm touch less data better ascending average distance value target average length ascends list average length segment ascends list average length known list its clear algorithm issues track huge number ascending values the short distance value target explains good performance linear search ascends still working long segments better algorithms there reason algorithm linear search data it sorted need remove small values end list def futurea list tuples index a value a invariant indexes values sorted order known result idx xrangelena value aidx since known sorted binary search could applied i bothered anything lower current value cannot possibly used since value first index instead known known value knownpop known values known current value reverse sorted index value lowest index first resultappendknown else values exist high report resultappend add end list maintain invariant knownappend idx value let numpy worry reversing array return nparrayresult but occurs reuse previous calculated values b instead constructing new data structures if j ai aj bi bj def futurea b lena index xrangelena target index value aindex target atarget value target btarget bindex target return nparrayb my benchmark results random series future ascends future full list future vectorize future reuse oscillating series future ascends future full list future vectorize future reuse ascending trend series future ascends future full list future vectorize future reuse ascending sections cyborg interesting idea take advantage ascending segments i think test cases really exhibit behaviour i think sections long enough take advantage but i figure real data may well sections taking advantage would really helpful but i think work it takes on time prepare necessary data binary search that would fine binary search many times find value middle ascending section never revisit anything left as result even binary search spend on time processing data it could work less expensive build neccesary data scan ascending section later but scan pretty cheap hard pressed come way handling ascending sections less expensive,i time series a i want generate another time series b bi j j first index greater aj ai fast way numpy thanks edited preferably use on space,3 i would choose version one way functionality points stored point class ie grouping related functionality additionally point objects know best meaning inner workings data right place implement function an external function example c would friend smells like hack,i need deal two objects class way return third object class i trying determine whether better independent function receives two objects returns third method would take one object return third for simple example would collections import namedtuple class pointnamedtuple point x slots attached class def midpointself otherpoint mx selfx otherpointx selfy otherpointy return pointmx point b point print amidpointb pointx or collections import namedtuple class pointnamedtuple point x slots attached class takes two point objects def midpointp p mx px px py py return pointmx point b point print midpointa b pointx would one preferred this seems far less clear cut i expected i asked question in summary seems something like amidpointb preferred since seems give special place one point another really symmetric function returns completely new point instance but seems largely matter taste style something like freestanding module function function attached class meant called insance pointmidpointa b i think personally i stylistically lean towards freestanding module functions may depend circumstances in cases function definitely tightly bound class risk namespace pollution potential confusion making class function probably makes sense also couple people mentioned making function general perhaps implementing additional features class support in particular case dealing points midpoints probably overall best approach it supports polymorphism code reuse highly readable in lot cases though would work project inspired ask instance points midpoints seemed like concise understandable example illustrate question thank enlightening,1 the first approach reasonable conceptually different setunion setintersection any funcpoint point point clearly related point class question interfering unity cohesion class it would tougher choice different classes involved drawperpendicularline point line to resolve choice classes would pick one related logic for example strjoin needs string delimiter list strings it could standalone function old days string module could method lists works lists strings method strings the latter chosen joining strings lists this choice made eventhough led arguably awkward expression delimiterjointhingstojoin i disagree respondent recommended using classmethod those often used alternate constructor signatures transformations instances class for example datetimefromordinal classmethod constructing date something instance class case int this contrasts datetimereplace regular method making new datetime instance based existing instance this steer away using classmethod midpoint computation one thought keep midpoint point class makes possible create classes point api different internal representation ie polar coordinates may convenient types work cartesian coordinates if midpoint separate function start lose benefits encapsulation coherent interface,i need deal two objects class way return third object class i trying determine whether better independent function receives two objects returns third method would take one object return third for simple example would collections import namedtuple class pointnamedtuple point x slots attached class def midpointself otherpoint mx selfx otherpointx selfy otherpointy return pointmx point b point print amidpointb pointx or collections import namedtuple class pointnamedtuple point x slots attached class takes two point objects def midpointp p mx px px py py return pointmx point b point print midpointa b pointx would one preferred this seems far less clear cut i expected i asked question in summary seems something like amidpointb preferred since seems give special place one point another really symmetric function returns completely new point instance but seems largely matter taste style something like freestanding module function function attached class meant called insance pointmidpointa b i think personally i stylistically lean towards freestanding module functions may depend circumstances in cases function definitely tightly bound class risk namespace pollution potential confusion making class function probably makes sense also couple people mentioned making function general perhaps implementing additional features class support in particular case dealing points midpoints probably overall best approach it supports polymorphism code reuse highly readable in lot cases though would work project inspired ask instance points midpoints seemed like concise understandable example illustrate question thank enlightening,2 another option use classmethod it probably i would prefer case class point classmethod def midpointcls p p mx px px py py return clsmx print pointmidpointa b,i need deal two objects class way return third object class i trying determine whether better independent function receives two objects returns third method would take one object return third for simple example would collections import namedtuple class pointnamedtuple point x slots attached class def midpointself otherpoint mx selfx otherpointx selfy otherpointy return pointmx point b point print amidpointb pointx or collections import namedtuple class pointnamedtuple point x slots attached class takes two point objects def midpointp p mx px px py py return pointmx point b point print midpointa b pointx would one preferred this seems far less clear cut i expected i asked question in summary seems something like amidpointb preferred since seems give special place one point another really symmetric function returns completely new point instance but seems largely matter taste style something like freestanding module function function attached class meant called insance pointmidpointa b i think personally i stylistically lean towards freestanding module functions may depend circumstances in cases function definitely tightly bound class risk namespace pollution potential confusion making class function probably makes sense also couple people mentioned making function general perhaps implementing additional features class support in particular case dealing points midpoints probably overall best approach it supports polymorphism code reuse highly readable in lot cases though would work project inspired ask instance points midpoints seemed like concise understandable example illustrate question thank enlightening,1 in comment posted call function ispalindrome calling function number you need call string change call ispalindrome work,i trying write code detect list palindrome here i far thesublist rawinputinput list def ispalindrome thesublist return thesublist thesublist why tell int object subscriptable the way i get run putting top line commented part i want everything come ispalindrome thesublist any ideas thanks,1 do mean something like def ispalindromea return joinreverseda this strings ispalindrome otto true,i trying write code detect list palindrome here i far thesublist rawinputinput list def ispalindrome thesublist return thesublist thesublist why tell int object subscriptable the way i get run putting top line commented part i want everything come ispalindrome thesublist any ideas thanks,1 i would choose second option opinion clearer first you performing midpoint operation two points midpoint operation respect point similarly natural extension interface could define dot cross magnitude average median etc some functions operate pairs points others may operate lists making function makes consistent interfaces defining function also allows used pair objects present x interface making method requires least one two point lastly address location function i believe makes sense colocate package point class this places namespace clearly indicates relationship point opinion pythonic static class method update further reading pythonicness staticmethod vs packagemodule in thomas wouter answer question what difference staticmethod classmethod python mike steder answer init arguments python authors indicated package module related functions perhaps better solution thomas wouter say staticmethod basically useless python use module function instead staticmethod while mike steder comments if find creating objects consist nothing staticmethods pythonic thing would create new module related functions however codeape rightly points calling convention pointmidpointab colocate functionality type the bdfl also seems value staticmethod new method staticmethod my personal preference would use function reasons cited appears choice staticmethod standalone function largely eye beholder,i need deal two objects class way return third object class i trying determine whether better independent function receives two objects returns third method would take one object return third for simple example would collections import namedtuple class pointnamedtuple point x slots attached class def midpointself otherpoint mx selfx otherpointx selfy otherpointy return pointmx point b point print amidpointb pointx or collections import namedtuple class pointnamedtuple point x slots attached class takes two point objects def midpointp p mx px px py py return pointmx point b point print midpointa b pointx would one preferred this seems far less clear cut i expected i asked question in summary seems something like amidpointb preferred since seems give special place one point another really symmetric function returns completely new point instance but seems largely matter taste style something like freestanding module function function attached class meant called insance pointmidpointa b i think personally i stylistically lean towards freestanding module functions may depend circumstances in cases function definitely tightly bound class risk namespace pollution potential confusion making class function probably makes sense also couple people mentioned making function general perhaps implementing additional features class support in particular case dealing points midpoints probably overall best approach it supports polymorphism code reuse highly readable in lot cases though would work project inspired ask instance points midpoints seemed like concise understandable example illustrate question thank enlightening,1 tcl thing already for example write gui program creates separate window interactive prompt from reload code type new code etc you gui toolkit though much harder others it easy python though indentation thing imho makes interactive use challenging i reasonably certain dynamic languages without much trouble look way toolkit lets open one window reason one windows interactive prompt all need ability open window sort eval command runs code fed string,i would like build live coding framework i explain meant live coding framework i comparing live coding traditional coding generally put traditional programming write code sometimes compile launch executable open script sort interpreter if want modify application must repeat process a live coding framework enables code updated application running reloaded demand perhaps reloading happens time file containing code changed action changes code reflected application running there need close program recompile relaunch in case application windowed app updatedraw loop likely using opengl graphics audio library sound processing supercollider ideally networking lib of course i preferred languages though i certain would well suited kind architecture ideally i would use python lua ruby another higher level language however friend recently suggested clojure possibility i considering well i would like know languages would suitable kind framework generally language features would make framework possible,1 i pretty sure adding newlines c program cause readlines return,i simple c program i trying execute python script i new writing scripts i trouble reading output pipe from i seen seems like readline work without eof i want able read middle program script respond whats outputted instead reading output hangs python script usrbinenv python import subprocess def callrandomnumber print running random guesser rngsubprocesspopenrandomnumber stdinsubprocesspipe stdoutsubprocesspipe shelltrue rngstdinwritedn outputrngstdoutreadline outputrngstdoutreadline callrandomnumber c file generates random number one checks users guess guess correctly includeiostream includecstdlib using namespace std int main coutthis program generates random number asks user enter guesses succuessfully guess number it tells user many guesses took themendl srandtimenull int numrand int guesscount int guess coutplease enter number cinguess whileguessnum ifguessnumcoutthat guess high please guess elsecoutthat guess low please guess cinguess guesscount coutcongratulations you solved guesscount guessesendl return eventual goal script solve problem binary search i want able read line without end file,1 those users probably access rights opportunity object child object read access rights documentation details update you said trouble configuring new user as experiment try adding permissions existing user instead starting brand new user also check configured roles well permissions trips sometimes another update you said removing groups stopped warning it may removed access rules object if groups explicitly granted access something openerp everyone granted access if really want figure going i suggest read documentation i linked you also search error message source code see exactly complaining i find really helpful run openerp server debug mode step code i trying understand weird behaviour like you also try figure exactly change triggers error adding removing groups find single change makes problem happen,after creating opportunity i click save gives warning users operation prohibited access rules performed already deleted document operation read document type user modification what causing problem update i created new user admin type i added groups salesusersalesuser all leadssurveyusertoolsuser it gives warning creating opportunity i added following groups new user working fine employee partnermanager marketinguser accountingaccountant accountinginvoice accountingmanager administrationaccess rights human resourcemanager human resourceuser knowledgeuser marketingmanager projectmanager salesmanager toolsmanager trimaxadminmeeting trimax‌​salesexecutive trimaxvertical trimaxsaleshead trimaxsalesmanager useabilityan‌alyticaccounting useabilityextended view useabilitymulticompanies useabilityno one useabilityproduct uos view useabilityproduct variant warehousemanager warehouseuser toolsuser administrationconfiguration but already created user i remove groups give warning also shows warning the solution i mentioned new usersbut existing users still giving problem so i removed unwanted groups i needed users worked show warning was warning due access right overlap something else,1 in case use operator overloading collections import namedtuple class pointnamedtuple point x slots attached class def addself otherpoint mx selfx otherpointx selfy otherpointy return pointmx def divself scalar return pointselfxscalar selfyscalar point b point def midab general function return ab print midab i think decision mostly depends general abstract function if write function way works objects implement small set clean interfaces turn separate function the interfaces function depends specific makes sense put class instances class likely objects function work anyways,i need deal two objects class way return third object class i trying determine whether better independent function receives two objects returns third method would take one object return third for simple example would collections import namedtuple class pointnamedtuple point x slots attached class def midpointself otherpoint mx selfx otherpointx selfy otherpointy return pointmx point b point print amidpointb pointx or collections import namedtuple class pointnamedtuple point x slots attached class takes two point objects def midpointp p mx px px py py return pointmx point b point print midpointa b pointx would one preferred this seems far less clear cut i expected i asked question in summary seems something like amidpointb preferred since seems give special place one point another really symmetric function returns completely new point instance but seems largely matter taste style something like freestanding module function function attached class meant called insance pointmidpointa b i think personally i stylistically lean towards freestanding module functions may depend circumstances in cases function definitely tightly bound class risk namespace pollution potential confusion making class function probably makes sense also couple people mentioned making function general perhaps implementing additional features class support in particular case dealing points midpoints probably overall best approach it supports polymorphism code reuse highly readable in lot cases though would work project inspired ask instance points midpoints seemed like concise understandable example illustrate question thank enlightening,1 there must least one statement block a lone string literal considered valid statement even used docstring it cause memory leaks though since compiler omits actual code,all i run across weird surprise python today the following code works seems violate python syntax i know would work without pass statement code def test sample docstring range test print testing i like determine works leaves nasty bits memory runs it may cause memory issue i trying track,3 python syntax explained language reference the relevant parts function definitions funcdef def funcname parameterlist suite so syntax function stuff colon followed suite compound statements suite stmtlist newline newline indent statement dedent stmtlist simplestmt simplestmt so suite either stmtlist indented block containing least one statement and stmtlist bunch simplestmt chunks connected semicolons one line finally simple statements simplestmt expressionstmt assertstmt that shows simplestatement expression assert whatever else list you click links pages explore an expressionstmt expression evaluated like dir cat int which perfectly valid python program parse run even though nothing a function docstring also expression it string happens treated specially system the special treatment part syntax though it happens another phase long parser built abstract syntax tree i would look elsewhere memory issue,all i run across weird surprise python today the following code works seems violate python syntax i know would work without pass statement code def test sample docstring range test print testing i like determine works leaves nasty bits memory runs it may cause memory issue i trying track,1 getattrmodulea mod getattr builtin function takes object string returns attribute,short question is possible call module retrieved python dir function background i working building custom test runner would like able choose modules run based string filter see examples ideal usage moduleapy def notmykeydontdothis print i better def mykeydosomething print doing something def mykeydosomethingelse print doing something else modulebpy import modulea listfroma dirmodulea notmykeydontdothis mykeydosomething mykeydosomethingelse mod listfroma ifmodstartswith mykey run module moduleamod note work mod string output doing something doing something else,2 sure import modulea listfroma dirmodulea mod listfroma ifmodstartswith mykey f getattrmodulea mod f,short question is possible call module retrieved python dir function background i working building custom test runner would like able choose modules run based string filter see examples ideal usage moduleapy def notmykeydontdothis print i better def mykeydosomething print doing something def mykeydosomethingelse print doing something else modulebpy import modulea listfroma dirmodulea notmykeydontdothis mykeydosomething mykeydosomethingelse mod listfroma ifmodstartswith mykey run module moduleamod note work mod string output doing something doing something else,2 it repetitive sense repeated script might execute command line if put main code function like import module without executing this sometimes useful it also keeps things organized bit same far i tell python generally pretty good avoiding boilerplate it flexible enough situations write code produce boilerplate rather writing boilerplate code off topic question if write code check arguments ignored,google python tutorial describe boilerplate code unfortunate provide example usrbinpython import modules used sys standard one import sys gather code main function def main print hello sysargv command line args sysargv sysargv sysargv script name ignored standard boilerplate call main function begin program name main main now i heard boilerplate code described seemingly repetitive code shows order get result seems like ought much simpler example anyways python part considered boilerplate code example name main main now questions follows does boilerplate code python like example provided take definition definition i provided if is code even necessary it seems like code runs whether main method what makes using code better is even better why use code service provide does occur throughout python are examples boilerplate code oh topic question need import sys use command line arguments python how handle arguments,3 hadoop streaming uses stdinstdout passing keyvalue pairs mappers reducers log messages written specific log file check sample code python logging documentation details this query might also help,i see hadoop logs usrlocalhadooplogs path i see application level logs example mapperpy import logging def main logginginfostarting map task task print statement reducerpy import logging def main line sysstdin logginginforeceived input reducer line task print statement where i see logginginfo related log statements application i using python using hadoopstreaming thank,1 the thing that’s necessary make work form dynamic binding eg message passing erlang eval many languages if dynamic binding change target message without affecting message message without affecting target—provided target defined try send message message defined targets send send when changing target serve messages previous version new version place small locked update transition new version similarly changing message serve old version till new one available readily hotswappable code must still designed however—the application must modular enough replacing implementation component cause interruption come careful programming,i would like build live coding framework i explain meant live coding framework i comparing live coding traditional coding generally put traditional programming write code sometimes compile launch executable open script sort interpreter if want modify application must repeat process a live coding framework enables code updated application running reloaded demand perhaps reloading happens time file containing code changed action changes code reflected application running there need close program recompile relaunch in case application windowed app updatedraw loop likely using opengl graphics audio library sound processing supercollider ideally networking lib of course i preferred languages though i certain would well suited kind architecture ideally i would use python lua ruby another higher level language however friend recently suggested clojure possibility i considering well i would like know languages would suitable kind framework generally language features would make framework possible,2 the reason use main check module runs part code toplevel create things – constants functions classes – exports part executed script eg unit tests functionality the reason latter code wrapped function local variables main block would leak module scope now alternate design could file executed script would declare function named say main would mean adding new magic function name language name mechanism already and removed every module name module executed script special name module names assigned introducing two mechanisms thing get rid two lines boilerplate – usually two lines boilerplate per application – seem worth,google python tutorial describe boilerplate code unfortunate provide example usrbinpython import modules used sys standard one import sys gather code main function def main print hello sysargv command line args sysargv sysargv sysargv script name ignored standard boilerplate call main function begin program name main main now i heard boilerplate code described seemingly repetitive code shows order get result seems like ought much simpler example anyways python part considered boilerplate code example name main main now questions follows does boilerplate code python like example provided take definition definition i provided if is code even necessary it seems like code runs whether main method what makes using code better is even better why use code service provide does occur throughout python are examples boilerplate code oh topic question need import sys use command line arguments python how handle arguments,1 the default csvwriter setup handle properly here simple example import csv myparagraph long paragraph quotes stuff mycsv csvwriteropen foocsv wb mycsvwriterowmyparagraph word mycsvwriterow word word this yields following csv file long paragraph quotes stuff word wordword which load favorite csv opening tool problems two rows two columns,i completely new python struggling make simple thing work i reading bunch information web service parsing results i want write flatfile most items single line items one things i get back web service paragraph the paragraph contain newlines quotes random characters i going use csv module python unsure parameters i use escape string paragraph gets put onto single line i guaranteed characters properly escaped especially delimiter,1 main boilerplate common cannot simpler main called without boilerplate boilerplate allows module usage standalone script library programs it’s common doctest another one train become python guru…and good luck thesis,google python tutorial describe boilerplate code unfortunate provide example usrbinpython import modules used sys standard one import sys gather code main function def main print hello sysargv command line args sysargv sysargv sysargv script name ignored standard boilerplate call main function begin program name main main now i heard boilerplate code described seemingly repetitive code shows order get result seems like ought much simpler example anyways python part considered boilerplate code example name main main now questions follows does boilerplate code python like example provided take definition definition i provided if is code even necessary it seems like code runs whether main method what makes using code better is even better why use code service provide does occur throughout python are examples boilerplate code oh topic question need import sys use command line arguments python how handle arguments,1 it worked creating requesthandler def teardownself selfclientclose selfservershutdown selfserverserverclose it may bug socketserver shutdown call serverclose,how i write unit tests socketserver request handler i tried use following code encountered problem import socketserver unittest threading class testserversocketserverthreadingmixin socketservertcpserver allowreuseaddress true class myrequesthandlertestunittesttestcase def setupself selfserver testserverhost port myrequesthandler selfserverthread threadingthreadtargetselfserverserveforever selfclient socketcreateconnectionhost port selfserverthreadsetdaemontrue selfserverthreadstart def teardownself selfclientclose selfservershutdown if i try use multiple test functions like def testfooself selfclientsendb foon result selfclientrecv selfassertequalb foo result def testbarself selfclientsendb barn result selfclientrecv selfassertequalb bar result i get error socketerror errno address already use line selfserver even though i instructed test server allowreuseaddress edit removed one two errors i originally posted order simplify question,1 the reason name main block called boilerplate case replicates functionality automatic many languages in java c among many others run code look main method run even complain python runs whatever code file need tell run main method simple alternative would make running main method default functionality so name main common pattern could shorter there reason something different like name main print hello stack overflow range print exit this work fine although example little silly see put whatever like the python designers chose behavior automatically running main method may well exist presumably python scripting language write commands directly file run commands execute i personally prefer python way makes starting python easier beginners always nice language hello world one line,google python tutorial describe boilerplate code unfortunate provide example usrbinpython import modules used sys standard one import sys gather code main function def main print hello sysargv command line args sysargv sysargv sysargv script name ignored standard boilerplate call main function begin program name main main now i heard boilerplate code described seemingly repetitive code shows order get result seems like ought much simpler example anyways python part considered boilerplate code example name main main now questions follows does boilerplate code python like example provided take definition definition i provided if is code even necessary it seems like code runs whether main method what makes using code better is even better why use code service provide does occur throughout python are examples boilerplate code oh topic question need import sys use command line arguments python how handle arguments,2 your could reverse lookup names globals name def nameofvalue k v globalsitems v value return k raise keyerror find name value nameofname name if object assigned one name one name returned if want search broadly globals look dicts gcgetreferrersvalue capture matches def namesofvalue find names value result gcgetreferrersvalue isinstanced dict k v ditems v value resultappendk return result import math pie mathpi namesofpie pie pi pi pi,i programming python need access name i given object able pass string concatenated another string the reason i need program i using forces create global case dictionary i writing function work general several different objects similar sets properties eg object length signifying case neurons labelled properties abcd i want create dictionary filetree properties object object instances class therefore i need change first level keys name name name name def initneuroninput initialises neuron group arguements neuron neurongroup input neurongroup global dict dict x rangelenneuron neuronxl neuronxg neuronxronperiod neuronxroffperiod dictx tauon nonoff neuronxroff nonoff neuronxron nion onesleninputqon ni onesleninputqoffonesleninputqon pcurrent pprevious mytauon mynonoff mynoffon mynion myni mypon myron myroff mytheta myweights myrecordtimes dict x neurondictpopx work give name assigned object merely name object minimal case problem name def funcx creates string name print x funcname output name,3 use subprocess module this section shows replace ospopen calls,i want get stdout stderr command along return code can someone point python function already accomplishes i modified function i found site follows i able grab return code command in snippet sts always seems def getstatusoutputcmd return status output executing cmd shell import sys mswindows sysplatform win import os mswindows cmd cmd fifofeospopencmd textout foread texterr feread sts foclose sts none sts textout n textout textout return sts textout texterr,2 there tools packaging python program libraries executable run i keep list handy httpwwwfreehackersorgpackagingapythonprogram i sure least one tools handle wxpython i years ago sorry i remember one yes tkinter popularity waning years see question options higher level python gui toolkit eg pass dict treeviewgrid,i making programs solve show work math problems i would like add gui i think wxpython best if i use wxpython gui end user need wxpython computer order use program gui if would i use these apps used mostly windows i would also like work macs linux i sure python gui elements work android sla know would appreciated also i know tkinter bundled python dying technique i read thanks,1 the socket library cannot alone take look python twisted this help though i tried django yet,i trying write unit test webhooks callback django my application set i run bit code sends post request url choice functionality i trying test i like set socket listens request tells sent i imagine goes something like import socket def webhookstestself targeturl http socketsocketsocketafinet socketsockstream sbind localhost slisten saccept code triggers post request goes selfassertnotequalsrecvd none webhooks url receive anything as work program get hung saccept line never send request i completely new asynchronous programming could use advice from examining python docs i fairly sure socket module alone i need asynchronous magic,1 you could streamline input code using xpath expressions relative element instead complex datastructure eg cases tagtext tagattribute namedtboolean tagtagtext what output datastructure use depends like used code later you could start structure convenient current code and evolve general solution later better understand requirements i output csv element one row csv file i use defaultdict store elements store list i output csv you could use ordinary dict csvdictwriterfieldnamesxpathdictkeys element rowdict dictfromkeysxpathdictkeys key rowdictkey elementxpathxpathdictkey none dictwriterwriterowrowdict where xpathdict mapping field names corresponding xpath expressions for generality could store function objects felement csv field instead ofin addition xpath exprs,i number xml files i need parse i written code works ugly i like get advice people experienced xml i first i might using terms wrong context experience xml limited by element unless specified otherwise i mean something like root element element element element root anyway file consist number elements number child elements obviously what stumps relevant values need accessed four different ways node text tagvaluetag attribute tag attributevaluetag a value hidden inside tag true case tagbooleantruetag values inside tags name taga grandparent tags different names tag tag within element taga use instead i looking tag tag element tagtagavaluetagatag tagtagavaluetagatag element at moment i dictionary file key the values dictionaries keys attribute node text tag parent element example filexml attributes person id car color node text name address where person car tags id color attribute names this makes easy iterate elements inspect tag match dictionary elemtag dict filexml attributes extract value so i said code works i like solution also elements child elements example person might car tag missing altogether i need give assign values none right i get tags exist every element file turn set check difference set tags i actually extracted values element again code pretty ugly hopefully mess makes sense edit i used jf sebastian suggestion storing xpath value dictionary field name key xpath value,2 you use list comprehensions instead replace temporary lists forloops example match set xname x alist amp set xname x blist,if b lists objects name property eg a b b etc would i check equivalency i currently alist blist b b anamelist bnamelist alist anamelistappend iname blist bnamelistappend iname match setanamelist amp setbnamelist set but seems kind long unnecessary what better way,2 there many tools easily create simple restful http webservices my favorite itty itty import get runitty import glob gzip json os functools def jsonifyorigfunc functoolswrapsorigfunc def wrapperargs kwds result origfuncargs kwds return jsondumpsresult indent return wrapper get logs jsonify def listlogfilesrequest return globglob varlogmyservergz get logspnamew def showlogfilerequest name fullname ospathjoin varlogmyserver name gzipopenfullname rb f return fread runittyhost localhost port,is tools catches python logging socket http handlers reports serves http service i check logs http page thanks finally i found working server job loggingwebmonitor update i found sentry github it seems sophiscated productionready,1 comment answer follows i see behavior usrbinenv python import os import sys filename tmpa openfilename wb f fwriteb abca printopenfilename rb read bufsize table bytesmaketransb abcde b xyzzz mapping openfilename rb f range ospathgetsizefilename bufsize fseeki osseekset b freadbufsize result depend due b break fseeki osseekset fwritebtranslatetable fseek osseekend magic printopenfilename rb read output magic line buffering fflush fwrite b abca b xyzx output without magic line b abca b abzxxy answer if mapping could use bytestranslate usrbinenv python import io import os import sys filename tmpa data b abca openfilename wb f fwritedata assert data openfilename rb read printdatadata bufsize iodefaultbuffersize table bytesmaketransb abcde b xyzzz mapping openfilename rb f true b freadbufsize result depend bufsize due b break fseeklenb osseekcur fwritebtranslatetable fflush trdata datatranslatetable assert trdata openfilename rb read printtrdatatrdata it seems iobufferedrandom interlaced readseekwrite bug python without flush,i working function map bytes binary file another set bytes i reading writing file my problem every time end extra bytes unless move end file closing code openselfpath rb source lookat rangeselfsizeselfsize sourceseeklookatselfsize readbuffer arrayarray b readbufferfromfilesource selfsize newline arrayarray b mappingdictmat mat readbuffer sourceseeklookatselfsize newlinetofilesource sourceseek magic line solves stupid bug sourceclose i using array module read write data since got problem used read write i understand magic line solves problem since never used i appreciate insight get,2 recommend bootlepy nice framework cases here link project website httpbottlepyorgdocsdev,is tools catches python logging socket http handlers reports serves http service i check logs http page thanks finally i found working server job loggingwebmonitor update i found sentry github it seems sophiscated productionready,1 having experimented little i conjecture bug python in support conjecture i offer following code based jf sebastian import os import sys filename tmpa openfilename wb f fwriteb abca printopenfilename rb read bufsize openfilename rb f range ospathgetsizefilename bufsize fseeki osseekset b freadbufsize fseeki osseekset fwriteb fseek osseekend magic printopenfilename rb read when run using python works expect magic line makes difference when run using python inexplicably requires magic noop seek order make work expected at point i suggest demonstrating code core python developers get opinion whether indeed bug,i working function map bytes binary file another set bytes i reading writing file my problem every time end extra bytes unless move end file closing code openselfpath rb source lookat rangeselfsizeselfsize sourceseeklookatselfsize readbuffer arrayarray b readbufferfromfilesource selfsize newline arrayarray b mappingdictmat mat readbuffer sourceseeklookatselfsize newlinetofilesource sourceseek magic line solves stupid bug sourceclose i using array module read write data since got problem used read write i understand magic line solves problem since never used i appreciate insight get,1 my guess commas model definition you setting schemaid tuple model field id modelsautofield remove trailing comma good go class recordmodelsmodel id modelsautofieldprimarykeytrue blanktrue remove schemaid modelsintegerfield remove name modelscharfieldmaxlength remove desc modelstextfieldblanktrue class meta dbtable keeperrecord,i started learning django problem insertquery using orm db mysql my model class recordmodelsmodel id modelsautofieldprimarykeytrue blanktrue schemaid modelsintegerfield name modelscharfieldmaxlength desc modelstextfieldblanktrue class meta dbtable keeperrecord following code handle post query viewpy def addrecordrequest requestmethod post recordobjectscreate schemaid requestpostget schemaid name requestpostget name desc requestpostget desc recordsave return httpresponse but code raising error request method post request url httprecordsadd django version exception type typeerror exception value schemaid invalid keyword argument function exception location cprogram files xpythonlibsitepackagesdjangodbmodelsbasepy init line python executable cprogram files xpythonpythonexe python version python path dprojectspasskeeper dxcfxfxeexexfxexecxecxfbxcfxfxeexexfxexecxecxexfxeexexexedxexepycharmhelpers dprojectspasskeeper dprojects cwindowssystempythonzip cprogram files xpythondlls cprogram files xpythonlib cprogram files xpythonlibplatwin cprogram files xpythonliblibtk cprogram files xpython cprogram files xpythonlibsitepackages i install mysql driver python standard settings project removed csrf middlewareclasses djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware,3 the trailing commas model class definition giving problems removing solve problem a trailing comma creating tuple one element equivalent which tuple one element what happends case fields recognized django model fields since fields wrapped tuple see python documentation tuples information httpdocspythonorgtutorialdatastructureshtmltuplesandsequences,i started learning django problem insertquery using orm db mysql my model class recordmodelsmodel id modelsautofieldprimarykeytrue blanktrue schemaid modelsintegerfield name modelscharfieldmaxlength desc modelstextfieldblanktrue class meta dbtable keeperrecord following code handle post query viewpy def addrecordrequest requestmethod post recordobjectscreate schemaid requestpostget schemaid name requestpostget name desc requestpostget desc recordsave return httpresponse but code raising error request method post request url httprecordsadd django version exception type typeerror exception value schemaid invalid keyword argument function exception location cprogram files xpythonlibsitepackagesdjangodbmodelsbasepy init line python executable cprogram files xpythonpythonexe python version python path dprojectspasskeeper dxcfxfxeexexfxexecxecxfbxcfxfxeexexfxexecxecxexfxeexexexedxexepycharmhelpers dprojectspasskeeper dprojects cwindowssystempythonzip cprogram files xpythondlls cprogram files xpythonlib cprogram files xpythonlibplatwin cprogram files xpythonliblibtk cprogram files xpython cprogram files xpythonlibsitepackages i install mysql driver python standard settings project removed csrf middlewareclasses djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware,1 use traceback module import traceback def fdepth print depth tracebackprintstack depth fdepth f file stdin line module file stdin line f none file stdin line module file stdin line f file stdin line f none file stdin line module file stdin line f file stdin line f file stdin line f none so entry stack indicates code called f call indirectly recursive the tracebackextractstack method gives easy access data the lenl statement example simply counts number exact matches name function to make even prettier thanks agf idea could make decorator def norecursef def funcargs kwargs lenl l tracebackextractstack l ffuncname raise exception recursed return fargs kwargs return func norecurse def foodepth print depth foodepth foo traceback recent call last file stdin line module file stdin line func file stdin line foo file stdin line func exception recursed,let say i python function f fhelp fhelp designed call recursively f called recursively is way f determine called recursively,3 if software mostly complicated processing fairly simple ui tkinter probably fine,i making programs solve show work math problems i would like add gui i think wxpython best if i use wxpython gui end user need wxpython computer order use program gui if would i use these apps used mostly windows i would also like work macs linux i sure python gui elements work android sla know would appreciated also i know tkinter bundled python dying technique i read thanks,1 you use twisted you put simplexmlrpcserver asynchronous loop synchronous code expects block flowcontrol twisted even udp easy rather overriding method like writable datagramprotocol call methods like stopreading stopwriting startreading startwriting transport attribute you see methods,how i handle asyncoredispatchers simplexmlrpcserver events eventloop ps i already know might recommend twisted problem twisted little bit highlevel library needs in particular i udp flowcontrol overriding asyncoredispatcherwritable method depends timers not sure ifhow could doable twisted,1 import print resubr r abcdef,i following problem i would like write function python given string returns string every group two characters swapped for example given abcdef returns badcfe the length string would guaranteed even number can help python,1 to add another option abcdefghijkl joinc c c zips badcfehgjilk,i following problem i would like write function python given string returns string every group two characters swapped for example given abcdef returns badcfe the length string would guaranteed even number can help python,1 you could use flag set decorator def norecursefunc funccalled false def fargs kwargs funccalled print recursion funccalled false going continue execution raise exception funccalled true result funcargs kwargs funccalled false return result return f then norecurse def fsome arg dostuff f gets called running called true raise exeption,let say i python function f fhelp fhelp designed call recursively f called recursively is way f determine called recursively,1 itertools import chain iziplongest joinchainfromiterableiziplongests fillvalue you also use islice instead regular slices large strings want avoid copying works odd length strings even though requirement question,i following problem i would like write function python given string returns string every group two characters swapped for example given abcdef returns badcfe the length string would guaranteed even number can help python,1 you generally get mb space localstorage api if really d game soundmusic going get eaten really quickly assets big goodquality mp days you need super aggressive compressing assets likely come mechanism stream stuff local storage game runs i would ask need php game server database can game server speak directly database save work good luck project,i interested producing sort multiplayer rpg purely browser based game little plugin requirements having done quite bit research i arrived following plan i aware tech i referencing adopted across browsers specifically ie i willing accept moment also i aware mmo lofty goal strive case done lots smaller projects past similar direction i feel like i want give really good go finally so heres rough outline i love hear glaring problems anyone see arrangement client webgl javascript probably threejs use browser local storage hold game assets accepting deleting browser cache remove messaging encode messages client server using google protocol buffers convenience size reduction message delivery would via websocket game server running top gevent python looks good solution dealing many concurrents would built using sharded pattern based design db server mysql database php acting inbetween game server db details i intend game server update individual client roughly times per second use clientside prediction fill gaps clients may send key input messages server region fps i prefer go experience close realtime possible rather turnbased my main concern tcp based protocol websocket make whole thing impossible does solution seem realistic so many thanks,1 i assuming want take something like root element textattributesome texttextattribute attribute varblah boolattributebooleantrueboolattribute element element textattributesome texttextattribute attribute varblah boolattributebooleanfalseboolattribute element root and get something like textattributesome text attributeblah boolattributetrue textattributesome text attributeblah boolattributefalse to i something like untested helper function extract default xpath result empty def getfirstx defaultvalue iflenx return x return defaultvalue parse one element def processelement e retval retval textattribute getfirstexpathtextattributetext default text retval attribute getfirst expathattributevar default attribute retval boolattribute getfirst expathboolattributebooleantrue false return retval parse elements elements elementsxml xmlxpath rootelement e elementsxml elementspush processelemente,i number xml files i need parse i written code works ugly i like get advice people experienced xml i first i might using terms wrong context experience xml limited by element unless specified otherwise i mean something like root element element element element root anyway file consist number elements number child elements obviously what stumps relevant values need accessed four different ways node text tagvaluetag attribute tag attributevaluetag a value hidden inside tag true case tagbooleantruetag values inside tags name taga grandparent tags different names tag tag within element taga use instead i looking tag tag element tagtagavaluetagatag tagtagavaluetagatag element at moment i dictionary file key the values dictionaries keys attribute node text tag parent element example filexml attributes person id car color node text name address where person car tags id color attribute names this makes easy iterate elements inspect tag match dictionary elemtag dict filexml attributes extract value so i said code works i like solution also elements child elements example person might car tag missing altogether i need give assign values none right i get tags exist every element file turn set check difference set tags i actually extracted values element again code pretty ugly hopefully mess makes sense edit i used jf sebastian suggestion storing xpath value dictionary field name key xpath value,1 i recently set slightly different settingspy config move emailusetls true top emailhost add defaultfromemail usergmailcom serveremail usergmailcom,i trying get django work gmail smtp server send mails i always get traceback any help appreciated settingspy emailhost smtpgmailcom emailhostuser usergmailcom emailhostpassword yourpassword emailport emailusetls true python shell djangocoremail import emailmessage email emailmessage mail test this test somemailsomethingcom emailsend traceback recent call last file console line module file homefiodorovichenvsfdictlibpythonsitepackagesdjangocoremailmessagepy line send return selfgetconnectionfailsilentlysendmessagesself file homefiodorovichenvsfdictlibpythonsitepackagesdjangocoremailbackendssmtppy line sendmessages sent selfsendmessage file homefiodorovichenvsfdictlibpythonsitepackagesdjangocoremailbackendssmtppy line send emailmessagemessageasstring file usrlocallibpythonsmtplibpy line sendmail raise smtpsenderrefusedcode resp fromaddr smtpsenderrefused must issue starttls command first zsmanl webmasterlocalhost edit new errors made modification suggested unni the shell execute i getting error message emailhostuser someaccountgmailcom syntaxerror invalid syntax,3 list comprehension ideal name pluto,suppose list dictionaries like one name pippo age name pluto age what extract list dict namepluto to make things little bit harder consider i cannot import,3 name pluto,suppose list dictionaries like one name pippo age name pluto age what extract list dict namepluto to make things little bit harder consider i cannot import,1 age name pluto,suppose list dictionaries like one name pippo age name pluto age what extract list dict namepluto to make things little bit harder consider i cannot import,1 python pickle module used serialize objects if use protocol version data serialized binary format you use pickle like class websitesobject def init selfsitename selfrank import cpickle serialize object opendatadump wb output cpickledumpwebsites output cpicklehighestprotocol deserialize object opendatadump rb input obj cpickleloadinput protocol version auto detected pickle takes care nested objects cycles bad stuff like easily serialize quite complex structures note limitations notably pickle requires access definitions pickled objects,i want save classes file python i want something like i similar class python like c struct struct websites char sitename int rank i want write something like void writetobinaryfilewebsites pdata fstream binaryfilectestdatiosoutiosbinaryiosapp binaryfilewritereinterpretcastchar amppdatasizeofwebsites binaryfileclose could read simply void readfrombinaryfile websites pdata fstream binaryfilectestdatiosbinaryiosin binaryfilereadreinterpretcastchar amppdatasizeofwebsites binaryfileclose coutpdatasitenameendl coutrank pdatarankendl method python,3 apart list comprehension responses give also filter lambda filterlambda x xget name pluto,suppose list dictionaries like one name pippo age name pluto age what extract list dict namepluto to make things little bit harder consider i cannot import,3 it well good live coding dev box way directly interact deployed server takes lot closer real for need network aware repl clojure provides nicely form socket repl this allows remotely attach running version code deployed tomcat server instance you attach favorite swankenabled development tool hack away,i would like build live coding framework i explain meant live coding framework i comparing live coding traditional coding generally put traditional programming write code sometimes compile launch executable open script sort interpreter if want modify application must repeat process a live coding framework enables code updated application running reloaded demand perhaps reloading happens time file containing code changed action changes code reflected application running there need close program recompile relaunch in case application windowed app updatedraw loop likely using opengl graphics audio library sound processing supercollider ideally networking lib of course i preferred languages though i certain would well suited kind architecture ideally i would use python lua ruby another higher level language however friend recently suggested clojure possibility i considering well i would like know languages would suitable kind framework generally language features would make framework possible,1 take look tracebackprintexc rest traceback module import traceback try except print traceback tracebackprintexc print end traceback there examples towards end traceback documentation page,in python except block i want print error message i want program stop executing i understand i something like try except print errormessage in except part i looking put something like java printstacktrace,3 for straight proxying see httppythonpasteorgmodulesproxyhtml for higher level abstractions look messaging systems rabbitmq you might also interested task execution systems celery,i developing application apache wsgi the structure app like client web server dispatcherreceive http request server workerprocess request sinkresponse web server web server client basically processesdispatcher worker sink i stuck forwarding http requestresponse processes is way pythonlike requestdispatcher java servlet,1 you also use loggingexception logging module it print current exception stacktrace default logger message severity error link httpdocspythonorglibrarylogginghtmlloggingloggerexception,in python except block i want print error message i want program stop executing i understand i something like try except print errormessage in except part i looking put something like java printstacktrace,1 the efficient solution i think needs copy original array import numpy np nparray idx npargsorta so idx index sorted column c acopy rangelenidx ai cidxi that reasonably fast course wastes memory,say i numpy array i want sort bottom row array top row follow sorting i get i know sort like using sorted function requires input output lists any ideas thanks much,1 you use sitespecific configuration hook a path configuration file file whose name form namepth exists one four directories mentioned contents additional items one per line added syspath in case able achieve want simply dropping pth file containing path directory include roothome echo usrlocallibpythonsitepackages optpythonlibpythonsitepackagesusrlocalpth,is way tell python additional sitepackages locations without modifying existing scripts on centos server i python installation installed optpython sitepackages folder optpythonlibpythonsitepackages the reason i want disturb existing python install shipped distribution however third party python application also added sitepackages folder usrlocallibpythonsitepackages installed location this partly fault i tweak prefix application makefile installing however much i i know i import sys syspathinsert usrlocallibpythonsitepackages however would involve tracking every script adding ideal updates future to get around i created symbolic link optpythonlibpythonsitepackages location third party application ln sf usrlocallibpythonsitepackagestheapp optpythonlibpythonsitepackagestheapp this appears work fine i wondering better way,3 they definitely allowed error come custom tag properly defined located loaded make sure custom tags located apptemplatetags directory loaded properly usually using register decorator reference httpsdocsdjangoprojectcomendevhowtocustomtemplatetagsregisteringcustomfilters,i written custom template tags django the goal use one custom tag inside another is permitted the template custom outer tag looks like ul type types custominternaltag param endfor ul which rendering results invalid block tag custominternaltag expected empty endfor are nested custom tags allowed what would cause error,3 you could replace python executable wrapper script appends added installpath pythonpath but kludge but i try fix installation addon properly goes sitepackages dir,is way tell python additional sitepackages locations without modifying existing scripts on centos server i python installation installed optpython sitepackages folder optpythonlibpythonsitepackages the reason i want disturb existing python install shipped distribution however third party python application also added sitepackages folder usrlocallibpythonsitepackages installed location this partly fault i tweak prefix application makefile installing however much i i know i import sys syspathinsert usrlocallibpythonsitepackages however would involve tracking every script adding ideal updates future to get around i created symbolic link optpythonlibpythonsitepackages location third party application ln sf usrlocallibpythonsitepackagestheapp optpythonlibpythonsitepackagestheapp this appears work fine i wondering better way,1 as usual difference digest implementation welldocumented implemented correctly major libraries the difference represent resulting data mddigest returns byte binary data produced digest new stringmddigest tries interpret bytes text platform default encoding almost certainly want you probably want digest represented hex base encoding try make sure import javaxxmlbinddatatypeconverter string result datatypeconverterprinthexbinarymddigest alternatively need base use printbasebinary instead,an application need sha encryptionbut results different python java java correct because byte object python java byte used hash calculation how get correct results python,2 this qt issue lack understanding multiple inheritance works you absolutely use multiple inheritance tricky subject python in nutshell last example first init called changed class dqtguiqmainwindowa class da qtguiqmainwindow would see a constructor called qmainwindow one see following links reference super behavior multiple inheritance how pythons super work multiple inheritance httppythonhistoryblogspotcommethodresolutionorderhtml,for number reasons i contemplating redoing program i use work pyqt present pygtk after playing around getting feel appreciating philosophy gui building i running annoying bugs implementation limitations one inheritance usrbinenv python coding utf import sys pyqt import qtcore qtgui app qtguiqapplicationsysargv class aobject def initself print a init class ba def initself superbselfinit print b init class cqtguiqmainwindow def initself supercselfinit print c init class dqtguiqmainwindowa def initself print d init superdselfinit print nsingle class inheritance a print nsingle class inheritance b print nsingle class qt inheritance c print nsingle class qt inheritance one d if i run i get python testpy single class inheritance a init single class inheritance a init b init single class qt inheritance c init single class qt inheritance one d init i expecting python testpy single class inheritance a init single class inheritance a init b init single class qt inheritance c init single class qt inheritance one d init a init why cannot use super initialise inherited classes qt class involved i would rather todo qtguiqmainwindowinit ainit anyone know going,1 import something refers py file template handler application webappwsgiapplication somethingsomethingelse somethingsomethingelsehandler somethingsomethingelse somethingsomethingelsehandler somethingsomethingelse somethingpagehandler the pattern recognized close url if want url end without slash remove reg ex like somethingsomethingelse somethingpagehandler debugconfigdebug utilrunwsgiappapplication in somethingpy class pagehandler parse key id parsing manually render correct content,i know current user location it one following url httpmyappappspotcomsomethingsomethingelse httpmyappappspotcomsomethingsomethingelse httpmyappappspotcomsomethingsomethingelsepage httpmyappappspotcomsomethingsomethingelsepage actually addresses page i need display pages link page httpmyappappspotcomsomethingsomethingelsepage the question generate link i tried use relative links page page work properly i sure create absolute link selfrequestpath work properly also,1 import numpy np nparray idx npargsorta now use idx index array baidx,say i numpy array i want sort bottom row array top row follow sorting i get i know sort like using sorted function requires input output lists any ideas thanks much,3 by default already returning results order unless overrodemodified automatic id column may need fiddle mapper check ormmapper api specifically orderby setting this done somewhat metalevel schema,we migrating mysql postgresql one major features mysql relied fact objects came back order inserted in postgresql sort order guaranteed would like globally tell sqlalchemy entities order id we want avoid updating every single query if create subclass entity hook somewhere globally would best,1 if want industrial strength python web scraping check scrapy it uses twisted async comms blindingly fast being able spider pages persecond unrealistic expectation,i writing script python scrape pages web server put file i using mechanizebrowser module particular task however i found creating one single instance mechanizebrowser rather slow is way i could relatively painlessly use multihreadingmultiprocessing ie issue several get requests,1 i know currentthread returns probably use builtin id hash functions get safe value if lookup enough eg want iterate container weakrefweakkeydictionary,i debugging memory leaks django application could something curious djangocachepurge threading import currentthread urlstopurge def addpurgeurlurl urlstopurgesetdefaultcurrentthread setaddurl is construct prone memory leaks i suspect unless i familiar python magic there location dict cleaned,1 use groupby l itertools import groupby lcounti groupbyl,given list l todo get count element keep occurrence order eg i could tmpl ilcounti l tmps set cntlist x x tmpl x tmps tmpsaddx but better way i seen link sorts counts hence breaks order edit performance issue solution preferable something builtin,3 import itertools k lenlistg k g itertoolsgroupbyl this keeps order items also allows repeated items l k lenlistg k g itertoolsgroupbyl,given list l todo get count element keep occurrence order eg i could tmpl ilcounti l tmps set cntlist x x tmpl x tmps tmpsaddx but better way i seen link sorts counts hence breaks order edit performance issue solution preferable something builtin,3 if using python use counter collections exactly looking httpdocspythonorglibrarycollectionshtmlcollectionscounter,given list l todo get count element keep occurrence order eg i could tmpl ilcounti l tmps set cntlist x x tmpl x tmps tmpsaddx but better way i seen link sorts counts hence breaks order edit performance issue solution preferable something builtin,1 no works leave you consider something think upgrade new version python actually removes module deprecated means encouraged use new code mean need modify hence break existing code uses,i using djangoregistration v django everything works fine i wondering i getting warning message time i run server cpythonlibsitepackagesregistrationmodelspy deprecationwarning sha module deprec ated use hashlib module instead import sha could problem future can i avoid without changing djangoregistration original code edit this deprecation warning comes python,2 my two cents make test using debug option pyinstaller just update specfile exe exe pyz debugtrue note order avoid numerous message boxes may want set console output consoletrue maybe would return useful data please provide us output case according output get quite common problem pyinstaller resolves dependencies modules dependencies dependencies may forgotten in case tcl missing needed tkinter library take look python pyinstaller creating shortcuts windows according documentation elaborating makespecpy supported command line python makespecpy opts where allowed options k tk include tcltk deployment you may make try argument check impact spec file i bet addition modules taken account analysis exe function,i trying compile python code single exe manage correctly i tried pyinstaller spec file mode python analysisospathjoinhomepath supportmountzlibpy ospathjoinhomepath supportuseunicodepy programstoolboxpy pathex cusersronaldodesktoppythonpyinstaller pyz pyzapure exe exe pyz ascripts abinaries azipfiles adatas nameospathjoin dist programexe debugfalse stripfalse upxtrue consolefalse pyinstaller compiled fine created single exe file worked apparently users version python installed run doesn give error it simply launch i tried sending friends also tried virtual machine tried pyexe when comes compiling libraries next rest files works fine i tried compiling single file compiled exe file gave toolboxexe stopped working error here error report case might useful problem signature problem event name appcrash application name toolboxexe application version application timestamp fault module name stackhashae fault module version fault module timestamp exception code c exception offset bfcb os version locale id additional information ae additional information aedbadbae additional information ae additional information aedbadbae the setuppy file distutilscore import setup import pyexe sys os sysargvappend pyexe setup options pyexe bundlefiles windows script toolboxpy zipfile none singlepy file and singlepy import os sys ctypes ctypeswindllusermessageboxa curdir snexedir snsyswinver ospathabspathoscurdir ospathabspathospathdirnamesysargv syswinver message ospathbasenamesysexecutable x the program i wrote uses tkinter sys random winclipboardpywin modules what i wrong are better compilers update by joã«l tip i compiled debug console mode still work users python this error message cusersxxxxxdesktopprogramexe found embedded pkg cusersxxxxxdesktopprogramexe extracting binaries setting run child setting magic environment var creating child process waiting child process finish found embedded pkg cusersxxxxxdesktopprogramexe workpath cusersxxxxxappdatalocaltempmei manifestpath cusersxxxxxappdatalocaltempmeiprogramexemanifest activation context created activation context activated cusersxxxxxappdatalocaltempmeipythondll manipulating evironment pythonpathcusersxxxxxappdatalocaltempmeicusersxxxxxdesktop importing modules carchive extracted iu extracted struct extracted archive installing import hooks outpyzpyz i really hope serves help possible answer,1 you might consider webpy the framework easy set learn use provides easy way distribute app binary the user would simply unzip click run run standalone app browser user machine it even includes python interpreter user python installed helpful windows typically python installed the builtin rocket server adequate running locally people even use production you also use rocket frameworks if need help ask mailing list,i considering several options user interface application i want application multiplatform windows linux osx one options i considered develop web application run local server still access administrator privileges required simply web interface program i want develop python convenience reasons does using pylons job recommended best way run setup,1 create new issueticketbug project site report developers project activity project free fix code locally,i using djangoregistration v django everything works fine i wondering i getting warning message time i run server cpythonlibsitepackagesregistrationmodelspy deprecationwarning sha module deprec ated use hashlib module instead import sha could problem future can i avoid without changing djangoregistration original code edit this deprecation warning comes python,2 problem kept getting mail cron job throwing deprecation warning ran python script w ignoredeprecationwarning since script running virtualenv moving pyk live,i using djangoregistration v django everything works fine i wondering i getting warning message time i run server cpythonlibsitepackagesregistrationmodelspy deprecationwarning sha module deprec ated use hashlib module instead import sha could problem future can i avoid without changing djangoregistration original code edit this deprecation warning comes python,1 yes supposed work if b belong instance foo correct way class fooobject def initself selfa selfb the following makes b belong class instances share variables class fooobject b when mix two methods second example add anything useful causes confusion one caveat worth mentioning following first example foob changing foob adding brand new attribute foo shadows foob when neither barb foob change if subsequently del foob delete attribute foob refer foob,i python class class attribute set something none when creating new instance changes made attribute perpetuates instances here code make sense class fooobject b foo foo fooaappend item foob using fooa returns item foob returns one would expect when i create new instance call bar using bara returns item barb return however i initially set class attributes none set whatever init like class fooobject none b none def initself selfa selfb using bara returns barb returns fooa returns item foob returns is suppose work i apparently never ran issue years i programmed python would like clarification i also find anywhere documentation giving reference would wonderful possible,3 yes exactly expect when define variable class attributes attached class instance you might always notice assign attribute instance instance picks new value masking class attribute methods modify place like listappend give instance new attribute since modify existing object happens attribute class any time every instance class unique value attribute usually set init method sure different every instance class attribute sensible default value value immutable type cannot modified place int str set attributes class,i python class class attribute set something none when creating new instance changes made attribute perpetuates instances here code make sense class fooobject b foo foo fooaappend item foob using fooa returns item foob returns one would expect when i create new instance call bar using bara returns item barb return however i initially set class attributes none set whatever init like class fooobject none b none def initself selfa selfb using bara returns barb returns fooa returns item foob returns is suppose work i apparently never ran issue years i programmed python would like clarification i also find anywhere documentation giving reference would wonderful possible,1 how big input hadoop splits jobs input splits file small one split try larger file say around gb size see mappers get you also check make sure every tasktracker reporting properly jobtracker if tasktracker properly connected get tasks hadoop job listactivetrackers this command output hosts,i hadoop cluster three machines one machine acts master slave when i run wordcountexample run map tasks two machines worker worker but i run code runs one machine worker i make map tasks run machines input split locations defaultrackmaster defaultrackworker defaultrackworker fixed i added following configuration mapredsitexml fixed property namemapredmaptasksname valuevalue property,1 you try pyjasper httppypipythonorgpypipyjasper i experience module,is way run jasper report within python without using jasper server we jasper server running additional overhead using method extra layer complexity if eliminated great current solution,1 the answer really depends want achieve apis pretty different pyfacebook older legacy api pythonsdk new opengraph protocol i say longer supported thin wrapper facebook opengraph protocol supports new features facebook provide instantly wout needing dev work lib djangofacebook higher level pythonsdk helps add facebook connection features site also seems pave way creating apps live inside facebook rather helping sites live outside facebook get access facebook data never heard fandjango github seems moment comment if want add userlogin using facebook something like djangosocialauth might work well if want start exploring social graph pythonsdk way go i also check see functions want supported opengraph protocol improved last year odd thing frustratingly support whereas legacy api support the best documentation facebook check graphexplorer pretty fascinating,i decide write applications using facebook django even twisted matter i choose appropriate tools i see many apiwrappers writed python exists facebook official seems longer supported pythonsdk new actively developed seems new djangofacebook good old maintained pyfacebook simple wellmaintaned nondocumented fandjango primitive tools i saw similar questions i noticed facebook periodically introduces big changes api advices may already outdated may new libraries appeared also i like know significant differences libraries and course good documentation tutorials welcome,2 the reliable way utilize bonafide address verification service not standardize normalize address components according usps standards see publication also certain address real full disclosure i work smartystreets provides service here really simple python sample code shows use service via http get request httpsgithubcomsmartystreetsliveaddresssamplesblobmasterpythonstreetaddresspy,i django form one fields textinput street address i want normalize data for example normalize east th st e th street normalize amsterdam av amsterdam ave normalize amsterdam avenue amsterdam ave or something like i already using geopy geocoding perhaps might help also where i normalize in database model clean function form field,2 you could always take look twisted supposed make easy create irc bot httptwistedmatrixcomdocumentsapitwistedwordsprotocolsircirchtml,i made script python connect mysql database every xx second check new posts forum if new posts i would like user irc channel notified to i need hook script irc bot i searching around find irc bot supports plugins called commands eg google example i would like script running constantly new posts found bot print message does anyone know irc bot would allow,1 keyword arguments aa cannot take default value self keyword arguments evaluated method defined called typically one would achieve trying setting default aa none class foo def initself selfa def fooself aanone aa none aa selfa return la note also since keyword argument defaults evaluated definition execution invocations foo share default argument even called different instances foo this often trips new python programmers working methods def footooalist aappend return all calls footoo get list object new one call so calling footoo repeatedly result following footoo footoo footoo,class foo def initselfa selfaa def fooselfaaselfa return la classmethod def testcls dfoo dfoo the memberfunction foo cannot find selfa a is a globally set inside class,2 from documentation for plain long integer division result integer the result always rounded towards minus infinity the rounding towards inf explains behaviour seeing,i confused following integer math python since i understand i get defined in opinion how work,3 this works intxinty mathfloorfloatxfloaty,i confused following integer math python since i understand i get defined in opinion how work,2 so coutput attempting emit complete cookie response header you emptied header name result values separated rn do need use simplecookie you set cookies directly webob response object selfresponsesetcookie emailaddress selfrequestget emailaddress selfresponsesetcookie secretcode selfrequestget secretcode path,i using google app engine how i set either multiple cookies multivalue cookie single response right i using code url httplocalhostservershowcookieemailaddressmyemailgmailcomampsecretcode c cookiesimplecookie cemailaddress selfrequestget emailaddress csecretcode selfrequestget secretcode csecretcodepath headervalue coutputheader selfresponseheadersaddheadersetcookie headervalue work value headervalue emailaddressmyemailgmailcom secretcode path well formed header missing comma how i create well formed cookie values,1 expanding answers aix robert the best way think terms rounding towards minus infinity floating point result floor floor,i confused following integer math python since i understand i get defined in opinion how work,1 osstatfilename simply returns size bytes file named filename you read osstat documentation randomrandint generates random integer zero n n size file obtained via osstat the code seeks random position file the chances position middle line therefore code reads partial line discards it reads next line returns finally code bug random position lands last line file second readline nothing read edit also noted russell borogove comments method ensure lines chosen equal probability,i writing python hangman program i wanted able randomly generate word file works but i got one line code website helps i need i dont know thanks offset randomrandint osstatfilename fd filefilename rb fdseekoffset fdreadline return fdreadline,3 your data generated mu sigma you testing data normal distribution mean standard deviation the null hypothesis h distribution data sample equal standard normal distribution mean std deviation the small pvalue indicating test statistic large d would expected probability pvalue in words pvalue e highly unlikely h true that reasonable since means std deviations match compare result in import scipystats stats in statskstestnprandomnormal norm out to test data gaussian could shift rescale normal mean std deviation datanprandomnormalmusigma normeddatadatamusigma printstatskstestnormeddata norm warning many thanks user if know mu sigma estimating parameters makes pvalue invalid import numpy np import scipystats stats mu sigma numtests numrejects alpha xrangenumtests data nprandomnormalmu sigma normeddata data mu sigma okay rejects rejection level expected normeddata data datamean datastd not okay rejects rejection level expected d pval statskstestnormeddata norm pval alpha numrejects ratio floatnumrejects numtests print f rejects rejection level format numrejects numtests ratio alpha prints rejects rejection level expected shows statskstest may reject expected number null hypotheses sample normalized using sample mean standard deviation normeddata data datamean datastd not okay,i data set n numbers i want test normality i know scipystats kstest function examples use interpret results is anyone familiar give advice according documentation using kstest returns two numbers ks test statistic d pvalue if pvalue greater significance level say cannot reject hypothesis data come given distribution when i test run drawing samples normal distribution testing gaussianity import numpy np scipystats import kstest musigma kstestnprandomnormalmusigma norm i get following output e the pvalue less means reject hypothesis data normally distributed but samples drawn normal distribution can someone understand explain discrepancy does testing normality assume mu sigma if i test data gaussianly distributed different mu sigma,3 to expand upon aix answer random integer within range file go location fdseekoffset we use fdreadline drop line move next one then use fdreadline return entire current line note end last line file return empty string to demonstrate set offset osstatfilename use readline twice,i writing python hangman program i wanted able randomly generate word file works but i got one line code website helps i need i dont know thanks offset randomrandint osstatfilename fd filefilename rb fdseekoffset fdreadline return fdreadline,1 let see happens def expensiveoperationx print expensive operation x return x def mygenerator xrange yield expensiveoperationi mygen mygenerator tenthelement nextitertoolsislicemygen print tenthelement tenthelement prints expensive operation expensive operation expensive operation expensive operation expensive operation expensive operation expensive operation expensive operation expensive operation expensive operation expensive operation tenthelement best would decouple expensiveoperation mygenerator since code suggests expensiveoperation affect mystate def mygeneratorarg arg arg mystate dosomeworki arg yield mystate then apply expensiveoperation want,let say i generator i want pull th element ignore first the generator function i written looks something like def mygeneratorarg arg arg mystate dosomeworki arg yield expensiveoperationmystate now i use grab th index like mygen mygeneratorlist list tenthelement nextitertoolsislicemygen i wondering runs expensiveoperation ten times edit calls times next part i interested is way optimize away calls expensiveoperation since discarded edited clarity i think several solutions involve using generator function would give exactly i want syntax clean turning iterative function generator replacing return yield edit i necessarily trying solve specific problem much looking way inexpensively scroll generator in real case i currently working i actually know index i want i call mygenerator first time i may grab th index th nd i could probably figure way slice th first call i need scroll next time around,1 the generator isolated consumer know throw away so yes expensive operation every step i would move expensive operation outside generator def mygeneratorarg arg arg mystate dosomeworki arg yield mystate mygen mygeneratorlist list tenthelement expensiveoperationnextitertoolsislicemygen,let say i generator i want pull th element ignore first the generator function i written looks something like def mygeneratorarg arg arg mystate dosomeworki arg yield expensiveoperationmystate now i use grab th index like mygen mygeneratorlist list tenthelement nextitertoolsislicemygen i wondering runs expensiveoperation ten times edit calls times next part i interested is way optimize away calls expensiveoperation since discarded edited clarity i think several solutions involve using generator function would give exactly i want syntax clean turning iterative function generator replacing return yield edit i necessarily trying solve specific problem much looking way inexpensively scroll generator in real case i currently working i actually know index i want i call mygenerator first time i may grab th index th nd i could probably figure way slice th first call i need scroll next time around,3 i use long polling rather continous works ok in long polling mode dbchanges blocks least one change happened returns changes generator object here code i use handle changes settingsdb couchdb database object since true changes settingsdbchangessincesince since changeslastseq changeset changesresults try doc settingsdbchangesetid except couchdbhttpresourcenotfound continue else process doc as see infinite loop call changes iteration the call changes returns dictionary two elements sequence number recent update objects modified i loop result loading appropriate object processing for continuous feed instead true line use changes settingsdbchangesfeedcontinuous sincesince,i trying use couchdbpy create update databases i like implement notification changes preferably continuous mode running test code posted i see changes scheme works within python class somedocumentdocument def init self intfield integerfieldfor integer textfield textfield couch couchdbserver http databasename testnotifications databasename couch print deleting creating database databasename server del couchdatabasename db couchcreatedatabasename else print creating database databasename server db couchcreatedatabasename iii range doc somedocumentintfieldiiitextfield somestring striii docstoredb print docid docrev something dbchangesfeed continuous sinceheartbeat iii range doc somedocumentintfieldiiitextfield somestring striii docstoredb timesleep print something print dbchangessinceiii the value dbchangessinceiii returns information interest format i worked extract sequence revision numbers document information u lastseq u results u changes u rev u cedfceacadaaeade u id u dcbccbfdbbcfa u seq u changes u rev u bbeaefafdfacb u id u dcbccbfdbbcfd u seq meanwhile code i really interested using dbchangesfeed continuous sinceheartbeat returns generator object appear provide notifications come couchdb guide suggests has anyone used changes couchdbpython successfully,2 there way python know expensive operation skipped for example might side effects need happen so way fastforwarding generator one option def mygeneratorarg arg arg mystate dosomeworki arg yield functoolspartialexpensiveoperation mystate this return callable object instead actual value to get actual value call yielded value only expensive operations performed,let say i generator i want pull th element ignore first the generator function i written looks something like def mygeneratorarg arg arg mystate dosomeworki arg yield expensiveoperationmystate now i use grab th index like mygen mygeneratorlist list tenthelement nextitertoolsislicemygen i wondering runs expensiveoperation ten times edit calls times next part i interested is way optimize away calls expensiveoperation since discarded edited clarity i think several solutions involve using generator function would give exactly i want syntax clean turning iterative function generator replacing return yield edit i necessarily trying solve specific problem much looking way inexpensively scroll generator in real case i currently working i actually know index i want i call mygenerator first time i may grab th index th nd i could probably figure way slice th first call i need scroll next time around,2 the second one group objectid this expected behaviour the first one simply counting objectid row database,i confusion result queries fcount f favouriteobjectsannotatecount count objectid second one f count f favouriteobjectsvalues objectid annotatecountcount objectid according django docs first query work fine favourite object count objectid can anyone explain second query working first thanks,2 there nothing stopping providing responses standard json eg instances cors available browser jsonp cases it affect anything output i would say cors viable ie support i would also say nothing wrong jsonp technology utilized major players facebook api twitter api flickr api google various api in short said correct cors adopted widely enough time used,i writing rest service accessed web applications desktop clients mobile clients etc via rest interface the idea store objects like notes calendar events etc common hierarchy provide http methods creating updating deleting documents ideal scope rest interface my plan rest server somewhere web applications servers using data i need make crossdomain request special restrictions security reasons see eg article i also want realtime updating web stuff now i extensive research learning cors trying tornado jqueryajax i getting suspicion setup i aiming simply coming soon i tried firefox i already problems http authentication work jqueryajax even withcredentials set browsers support cors says wikipedia least one ff plugin requestpolicy makes cors work i understand corsajax possible solution seem exist many restrictions practical use what people kind thing think something i hope problems solved someone sometime future or soon crossdomain restajax approach what alternative would choose plans as i starting new project i would like clean without jsonp proxies workarounds way around i anyway thanks answers,1 yes seems surprising begining way python works said answers three years python without slashed you lucky lucky if i i check sensitive past code little animals be also careful function calls def funclist similar behavior surprising and possible plug pylint parse commit hooks or least run pylint sometime code instructive would probably told trick trick fact logic orthogonal python way,i python class class attribute set something none when creating new instance changes made attribute perpetuates instances here code make sense class fooobject b foo foo fooaappend item foob using fooa returns item foob returns one would expect when i create new instance call bar using bara returns item barb return however i initially set class attributes none set whatever init like class fooobject none b none def initself selfa selfb using bara returns barb returns fooa returns item foob returns is suppose work i apparently never ran issue years i programmed python would like clarification i also find anywhere documentation giving reference would wonderful possible,1 uploading multiple files blobstore sending mail attachments,hi i new please gentle i html web form i need allow multiple file upload using pythondjangoappengine the files stored within blobstore uploaded sent attachments within email sent via system could someone provide simple code example multiple upload sending email please even point right direction please the sending email easy uploading attaching i sure many thanks,1 if object valid called call method init use factory function you need silly singletons sure,what pythonic way deal module methods must called certain order as example i xml configuration must read anything else configuration affects behavior the parseconfig must called first config file provided calling supporting methods like querydata work parseconfig called i first implemented singleton ensure filename config passed time initialization noticing modules actually singletons longer class regular module what best way enforce parseconfig called first module edit worth noting function actually parseconfigconfigfile,3 you picking newlines depending os created file different new line characters the safest way rid arstrip that take care trailing whitespace you could also maplambda x xrstrip file also name variable file this python builtin function renamed script script imports finally might prefer handle files like openstudentnametxt r testfile item linerstrip line testfile print item no need close file statement controls scope closes,input john statement kicking studentnametxt john paul poop whats studentnametxt ba name input students name list fileopen studentnametxt r file listappenda ba next statement tripping name entered john instance name b printa fileclose,1 as cat plus plus said words wrap behaviourfunctions class put required setup init method you might complain functions seem like naturally belong together object hence bad oo design if case think classobject form namespacing it much cleaner flexible trying enforce function calling order somehow using singletons,what pythonic way deal module methods must called certain order as example i xml configuration must read anything else configuration affects behavior the parseconfig must called first config file provided calling supporting methods like querydata work parseconfig called i first implemented singleton ensure filename config passed time initialization noticing modules actually singletons longer class regular module what best way enforce parseconfig called first module edit worth noting function actually parseconfigconfigfile,1 you get gtkgdkwindow widgetwindow using gtkwidgetgetwindow use undocumented gtkgdkwindowensurenative eg mywidgetgetwindowensurenative works least pygtk i available hand,is equivalent gdkwindowensurenative pygtk i need unbreak drawing opengl widget gtk,2 the model i using subsequent functions available methods return value previous functions like class secondobject def twoself print two return third class thirdobject def threeself print three def one print one return second onetwothree properly designed style i admit terribly pythonic yet makes fluent libraries handle complex pipeline operations later steps library require results early calculations fresh input calling function an interesting result error handling what i found best way handling wellunderstood errors pipeline steps blank error class supposedly handle every function pipeline except initial one functions except possibly terminal ones return self class errorobject def twoself args print two done earlier errors return self def threeself args print three done earlier errors class secondobject def twoself arg arg print two return third else print two cannot done return error class thirdobject def threeself print three def onearg arg print one return second else print one cannot done return error onetwothree in example parser class would almost nothing configure function returned instance configuredparser class would thing properly configured parser could this gives access things multiple configurations handling failed attempts configuration,what pythonic way deal module methods must called certain order as example i xml configuration must read anything else configuration affects behavior the parseconfig must called first config file provided calling supporting methods like querydata work parseconfig called i first implemented singleton ensure filename config passed time initialization noticing modules actually singletons longer class regular module what best way enforce parseconfig called first module edit worth noting function actually parseconfigconfigfile,1 yes import gtk w gtkwindow wshowall gw wgetwindow gw gtkgdkwindow object xae gdkwindow xaea gwensurenative true gwhasnative true alternatively you may try setting environmental variable gdknativewindows,is equivalent gdkwindowensurenative pygtk i need unbreak drawing opengl widget gtk,1 if timing issue clear could decouple input reading processing sides code sticking queue middle processing another thread reads queue you could also make chunk size smaller less processing per loop,i trying process large gzip file pulled internet python using urllib zlib techniques two stackoverflow questions python decompressing gzip chunkbychunk stream large binary files urllib file this works great except chunk file read i need operations resultant string involve lot splitting iterating this takes time code goes next reqread returns nothing program ends read first chunk if i comment operations whole file read decompressed code zlibdecompressobjzlibmaxwbits chunk url httpfoobarfoogz req urlliburlopenurl true chunk reqreadchunk chunk print done break ddecompresschunk lots operations might take seconds any ideas edit this turned bug elsewhere program not urllibzlib handling thanks everyone helped i recommend pattern used code need handle large gzip files,1 class threeobject def getattrself name return lambda args kw,or least pretend anything three three threevalue threesqrt threeclose threesomerandomfunctionwithmadeupparametershello world mathpi true threestopsayingthreedamnit is possible implement class three python,1 class metathreetype def reprcls return def getattrclskey return three class threeobject metaclassmetathree def initselfargskwargs pass def callself return three def getattrselfkey return three def reprself return threethree printthreevalue printthreesomerandomfunc hello printthreesomerandomfunc printthreesomerandomfuncfoobar printthree,or least pretend anything three three threevalue threesqrt threeclose threesomerandomfunctionwithmadeupparametershello world mathpi true threestopsayingthreedamnit is possible implement class three python,1 i would recommend urllstrip remove dots url urlurl add slash,i strings starts dots i want delete which best way and next caracter add i new python i trying something like erase dots syntax error rematchr urlend url url xxx xxx xxx xxx ab ab ab ab ca ca this i trying thank guys,2 try badurl xxx url badurllstrip it remove dots slashes beggining strings add slash manually,i strings starts dots i want delete which best way and next caracter add i new python i trying something like erase dots syntax error rematchr urlend url url xxx xxx xxx xxx ab ab ab ab ca ca this i trying thank guys,3 to get rid dots mystr yourstring mystr mystrlstrip result yourstring regardless whether begins dots slashes replaced single slash,i strings starts dots i want delete which best way and next caracter add i new python i trying something like erase dots syntax error rematchr urlend url url xxx xxx xxx xxx ab ab ab ab ca ca this i trying thank guys,3 celery seems like good solution scheduling problem celery periodictasks run time resolution seconds you using appropriate tool crontab entry want you want use python datetimetimedelta object crontab scheduler celeryschedules minute resolution using timedelta configure periodictask interval provides strictly functionality case per second resolution eg celery docs celerytask import tasks periodictask datetime import timedelta class everythirtysecondstaskperiodictask runevery timedeltaseconds def runself kwargs logger selfgetloggerkwargs loggerinfoexecute every seconds httpaskgithubcomceleryreferencecelerytaskbasehtmlcelerytaskbaseperiodictask class datetimetimedeltadays seconds microseconds milliseconds minutes hours weeks the challenge describe frequency want task run rather clock time want run however i would suggest check advanced python scheduler httppackagespythonorgapscheduler it looks like advanced python scheduler could easily used launch normal ie non periodic celery tasks schedule choosing using scheduling functionality,edit i accepted bakennedy answer confirming original thoughts yes box a good combo seems celery apscheduler original question what best way schedule periodic task starting specific datetime i using cron considering i need schedule hundred remote rsyncs i compute remote vs local offset would need rsync path second logs generated host by understanding celerytaskschedules crontab class allows specifying hour minute day week the useful tip i found nosklo answer is best solution am i using wrong tool job,3 if starting integer first convert string address digits within integer conveniently myint mystr strmyint mystr address individual digits index square brackets starting zero mystr convert digits back integers need math intmystr and numerological summation list comprehensions convenient sum intx x mystr just keep mind considering individual digits working strings arithmetic working integers kind thing requires lot conversion back forth,i looking general way refer particular digits integer string i need able perform different operations alternating digits sum result returned values any help much appreciated oh i complete beginner idiotproof answers would appreciated i elaborate inbuilt function python could reduce integer list digits i looked avail i hoping someone would understand i asking sorry vague i know enough python yet provide indepth question,1 don you trying microoptimization need algorithmic optimization this i argued use exponentialtime solution based itertools better recursive solution,i wrote small module python get possibilities x products fit total cost the module runs fine slow it takes six hours calculate six products iterations product so i thinking rewriting script fortran see i milk better speed unfortunately i new fortran libraries is similar modulefunction python itertoolscombinationswithreplacementpool r fortran module accomplishes thing,1 has anyone considered using lstrip ok lstrip formally answer question asked since remove dots slashes whereas intermixtures dots slashes ignored multiple slashes preserved according literal reading post for go ewok solution,i strings starts dots i want delete which best way and next caracter add i new python i trying something like erase dots syntax error rematchr urlend url url xxx xxx xxx xxx ab ab ab ab ca ca this i trying thank guys,1 looking python regex howto,i trying parse results tshark capture here line i filtering internet protocol src dst i trying extract src dst here code strresearchsrcs reiremgroup strresearchdsts reiremgroup i keep getting match i run i use exact length ip address regular expression works ie strresearchsrcs reiremgroup works fine how i fix problem,2 i guessing problem due aliasing what x example if x values interpolating less closely spaced original points inherently lose frequency information this completely independent type interpolation it inherent downsampling nevermind bit aliasing it apply case though i still idea x example i realized evaluating points original input points using nonzero smoothing factor by definition smoothing fit data exactly try putting instead as quick example import matplotlibpyplot plt import numpy np scipy import interpolate x nplinspace nppi num interval pi steps a e amplitude sine function anpsinx fig axes pltsubplotsnrows ax title zipaxes with without yinterp interpolateunivariatesplinex ssx axplotx yinterp label interpolated axplotx bo label original axlegend axsettitletitle smoothing pltshow the reason clearly seeing effects smoothing low amplitude due way smoothing factor defined see documentation scipyinterpolateunivariatespline details even higher amplitude interpolated data match original data use smoothing for example change amplitude a code example still see effects smoothing,i need numerically calculate first second derivative function i attempted use splrep univariatespline create splines purpose interpolation function take derivatives however seems inherent problem spline representation functions magnitude order lower rapidly oscillating as example consider following code create spline representation sine function interval pi function oscillates three times import scipy scipy import interpolate import numpy numpy import linspace import math math import sin k linspace pi num interval pi steps a e amplitude sine function rangelenk yappendasinki tck interpolateunivariatesplinex wnone bboxnone none k mtckk below results m a e a e httpiimgurcomueixqpng amplitude httpiimgurcomzffkpng amplitude clearly interpolated function created splines totally incorrect the nd graph even oscillate correct frequency does anyone insight problem or know another way create splines within numpyscipy cheers rory,3 match refinditerrbddddddb subject this match ipv ip address actual ips captured group while regex may work dangerous valid match,i trying parse results tshark capture here line i filtering internet protocol src dst i trying extract src dst here code strresearchsrcs reiremgroup strresearchdsts reiremgroup i keep getting match i run i use exact length ip address regular expression works ie strresearchsrcs reiremgroup works fine how i fix problem,2 you override delete method model want httpsdocsdjangoprojectcomendevtopicsdbmodelsoverridingpredefinedmodelmethods class image code def deleteself args kwargs code remove file system goes superimage selfdeleteargs kwargs,i models class gallerymodelsmodel headimage modelsimagefielduploadtogallery class imagemodelsmodel image modelsimagefielduploadtogallery gallery modelsforeignkeygallery relatedname images class tourmodelsmodel namemodelscharfieldmaxlength countmodelssmallintegerfield priceunitmodelsforeignkeypriceunit pricemodelscharfieldmaxlength gallery modelsonetoonefieldgalleryeditablefalse u see tour gallery imagesi designed modelform let user add tourthis code viewspy def addtourrequestkey imageformset inlineformsetfactorygalleryimage candeletefalseextra requestmethod post gformgalleryformrequestpostrequestfiles gformisvalid gallerygformsavecommitfalse formsetimageformsetrequestpost requestfiles instancegallery formsetisvalid gallerysave formsetsave tform tourformrequestpost requestfiles tformisvalid tourtformsavecommitfalse touractionusercodeuserobjectsgetpk tourgallerygallery toursave return httpresponseredirectreverse airagencyviewsedittour argsagnwebsitetourpk airagencyedittouri tourpk else tform tourform gformgalleryform galleryinstancegallery formsetimageformsetinstancegalleryinstance return rendertoresponse airagencyaddtourhtml tform tform gform gform formset formset u see viewsafter adding touruser redirected edittour pagenow i wanna user edittour page delete tour images belong gallery deleted images deleteed storage addition deleting databasehow i handle,1 not nice text fasgafastfgws pattern rdddd patternre recompilepattern ipaddress patternrefindalltext,i trying parse results tshark capture here line i filtering internet protocol src dst i trying extract src dst here code strresearchsrcs reiremgroup strresearchdsts reiremgroup i keep getting match i run i use exact length ip address regular expression works ie strresearchsrcs reiremgroup works fine how i fix problem,1 you efficiently go via numpy array import numpy arr numpyarrayim return gtkgdkpixbufnewfromarrayarr gtkgdkcolorspacergb,i looking see another way convert pil image gtk pixbuf right i seems like inefficient coding practice i found hacked needs this i far def imagepixbufselfim file stringiostringio imsavefile ppm contents filegetvalue fileclose loader gtkgdkpixbufloaderpnm loaderwritecontents lencontents pixbuf loadergetpixbuf loaderclose return pixbuf is easier way conversion i missed,3 the array object getobj method associated returns ctypes array presents buffer interface i think following work multiprocessing import process array import scipy import numpy def fa name main create array n int unsharedarr scipyrandn array unsharedarr print originally first two elements arr sa create start finish child process p processtargetf argsa pstart pjoin print changed values print now first two elements arr sa b numpyfrombufferagetobj b print when run prints first element showing b two views memory in order make sure still multiprocessor safe i believe use acquire release methods exist array object built lock make sure safely accessed though i expert multiprocessor module,i would like use numpy array shared memory use multiprocessing module the difficulty using like numpy array ctypes array multiprocessing import process array import scipy def fa name main create array n int unsharedarr scipyrandn array unsharedarr print originally first two elements arr sarr create start finish child process p processtargetf argsa pstart pjoin print changed values print now first two elements arr sarr this produces output originally first two elements arr now first two elements arr the array accessed ctypes manner eg ai makes sense however numpy array i cannot perform operations asum i suppose solution would convert ctypes array numpy array however besides able make work i believe would shared anymore it seems would standard solution common problem,3 you call something like useradd p password password get result crypt function defined unistdh as found case python looks like import os import crypt password testpassword encpass cryptcryptpasswordsalt ossystemuseradd p encpass someuser,i want write gui aplication creating linux users pygtk in linux console problem commands useradd adduser i know via gui application i want create gui form entries first name second password third confirm password button add i know send variable password useradd adduser commands what option i use or another way,1 i using gedit basic version comes ubuntu i error this mainly caused mix spaces tabs a good way differentiate lines problem would go edit preferences editor check automatic indentation increase indentation big number fifth step able see lines code relly causing problem lines mix space tab make entire code convention tab space done manually line line hope helps,i figure wrong usrbinenv python bugspy future import division no module name main print bugspy meant module exit app import pygame sys random math pygameinit configuration vars conf startenergy foodenergy mateminenergy mateuseenergy lifespan class bugs def initself selflist selftimers names colors sexes selfsex male female selfcolor cbcb aaa bug info tracking selfbugid selfbuginfo maxgen maxspeed def newself xfalse yfalse sex speed generation genes sex sex sex else randomrandint speed speed speed else randomrandint create new bug object selfbugsappendbugobjsex speed generation bugid pygametimegetticks genes make sure timer selftimersspeed selftimersspeed pygametimesettimer speed speed update info tracking variables speed selfbuginfomaxspeed selfbuginfomaxspeed speed generation selfbuginfomaxgen selfbuginfomaxgen generation selfbugid def speedcountself speed list ispeed speed return class bugobj def initself sex speed generation bugid born genes global conf selfsex sex selfspeed speed selfgeneration generation selfid bugid selfborn born selfgenes genes selfdied selfenergy confstartenergy selftarget none def updateself global conf selfage conflifespan selfdie else f closestfood closestmate if potential mate selfenergy confmateminenergy selfrectcolliderectmrect selfmovetowardm selftarget mate strmrectcenter else bugsmateself selftarget mate reached elif f selfrectcolliderectfrect selfmovetowardf selftarget food strfrectcenter else selfeatf selftarget food reached else selftarget resting use energy selfenergy def closestfoodself pass def closestmateself pass def ageself selfdied return pygametimegetticks selfborn else return selfdied selfborn def dieself remove self list bugslistremoveself turn timer bugsspeedcountselfspeed bugstimersselfspeed pygametimetimers selfspeed bye del self class food def initself pass def updateself pass update loop ev pygameeventwait speed evtype speed bugslist ispeed speed iupdate print updating bug striid speed foodupdate i get following every time file bugspy line def newself xfalse yfalse sex speed generation genes indentation error unindent match outer indentation level,1 almost exactly yesterday using gdal ogr python binding it looked like import ogr load shape file layer drv ogrgetdriverbyname esri shapefile dsin drvopenshpregsatregetxwgsshp lyrin dsingetlayer field index want data extracted satreg looking idxreg lyringetlayerdefngetfieldindexsatreg def checklon lat create point geometry pt ogrgeometryogrwkbpoint ptsetpointd lon lat lyrinsetspatialfilterpt go polygons layer see one include point featin lyrin roughly subsets features instead go everything ply featingetgeometryref test plycontainspt todo need print lon lat featingetfieldasstringidxreg,whats way check geopoint within area given shapefile i maneged load shapefile python get,1 to add unutbu available anymore henry gomersall answers you could use sharedarrgetlock synchronize access needed sharedarr mparrayctypescdouble n def fi could anything numpy accepts index another numpy array sharedarrgetlock synchronize access arr npfrombuffersharedarrgetobj data copying arri arri example import ctypes import logging import multiprocessing mp contextlib import closing import numpy np info mpgetloggerinfo def main logger mplogtostderr loggersetlevellogginginfo create shared array n m sharedarr mparrayctypescdouble n arr tonumpyarraysharedarr fill random values arr nprandomuniformsizen arrorig arrcopy write arr different processes closingmppoolinitializerinit initargssharedarr p many processes access slice stopf n pmapasyncf slicestopfm many processes access different slices array assert m odd step n pmapasyncg slicei step rangestopf n step pjoin assert npallclosemtonumpyarraysharedarr arrorig def initsharedarr global sharedarr sharedarr sharedarr must inhereted passed argument def tonumpyarraymparr return npfrombuffermparrgetobj def fi synchronized sharedarrgetlock synchronize access gi def gi synchronization infostart arr tonumpyarraysharedarr arri arri infoend name main mpfreezesupport main if need synchronized access create locks mparray unnecessary you could use mpsharedctypesrawarray case,i would like use numpy array shared memory use multiprocessing module the difficulty using like numpy array ctypes array multiprocessing import process array import scipy def fa name main create array n int unsharedarr scipyrandn array unsharedarr print originally first two elements arr sarr create start finish child process p processtargetf argsa pstart pjoin print changed values print now first two elements arr sarr this produces output originally first two elements arr now first two elements arr the array accessed ctypes manner eg ai makes sense however numpy array i cannot perform operations asum i suppose solution would convert ctypes array numpy array however besides able make work i believe would shared anymore it seems would standard solution common problem,3 take look sphinxextgraphviz sources eg sphinx extension almost thing describe,i trying create restructuredtext directive takes content creates image based content using pil displays generated image document what i done far subclass image directive create file certain path say imagesdiagrampng pass imagesdiagrampng image directive the problem file gets saved images generated html document looks outputdirstaticimages my question i access value directory rest using store output i stash image right place,1 i guess packet always byte aligned may use field somehow eg class statusfieldflagsfield name bit status def initself name flagsfieldinitself name b c class totalstatuspacket name bit status fieldsdesc statusfieldaxis statusfieldaxis,i trying add new protocol scapy i running difficulties building packets store bitenumfield packets one byte length i wondering workaround make work without bundling packets full byte fields here example scapypacket import packet scapyfields import class statuspacket name bit status fieldsdesc bitenumfield disabled enabled bitenumfield b disabled active bitenumfield c disabled active bitenumfield disabled active added debug purposes def postbuildself pktpay print pkt pkt type typepkt return pktpay now i understand statusshow fails pkt bits long one dies i guess packet formed independently class totalstatuspacket name bit status fieldsdesc packetfield axis status status packetfield axis status status totalstatusshow gives lengthy traceback ends selfpostbuild unable cat pkt tuple rest payload empty string ie typeerror concatenate tuple str tuple is way avoid bundling bit fields full bytes,2 i sure question trying correctly define function pay attention indentation required python see examples function definitions convert string variable integer newvar intoldvar generally please pay attention types like dynamically typed languages strings dynamically converted numbers explicitly read value variable based name myvar varsget variablename variablename name variable optionally give context within brackets vars see helpvars details did solve problem edit based clarification this solve problem def istruemyvariable here variable named myvariable accessible if want something inplace passed variable i bad news strings integers immutable python thus able simply change probably return result function least two workarounds i recommend novice python edit proper code styling you probably read pep get familiar coding standard python scripts commonly used across python community follow point appreciate,i trying define function include variable n n string numbers eg definition function starts istruen however n going string istruen string defined i test function example string n i get syntax error i use istruen however and i wondering i would go testing function example string n my entire function define shown httpoitinypiccomiqojpg bear mind i absolute novice probably many mistakes i would appreciate help experts possible def isvalidn n number checked number inty a converts string list useable digits altern integer sets altern one set alternating digits double x x altern doubles element list altern sum sumdouble adds together doubled items list altern integer sets altern set alternating digits return sum sumalternsums set alternating digits sumtotal sum sum works total sum worked mod sumtotal works remainder sumtotal divided mod remainder zero sumtotal multiple print true sumtotal multiple therefore n credit card number else print false sumtotal not multiple therefore valid credit card number here actual question the algorithm verifying number follows starting penultimate digit working towards rst digit double alternating digit b sum doubled digits treating etc add result sum undoubled digits c if sum divisible number valid credit card number write test function isvalid takes argument credit card number string eg valid returns true false depending whether number valid credit card number,1 quotes used string literals enclose variable parameter name quotes indicate string the function definition would look like def istruen and body function use n reference value passed caller to call function specific value istrue side suggestion think explanatory names functions variables for instance seems like function might reasonably called isvalidcardnumber,i trying define function include variable n n string numbers eg definition function starts istruen however n going string istruen string defined i test function example string n i get syntax error i use istruen however and i wondering i would go testing function example string n my entire function define shown httpoitinypiccomiqojpg bear mind i absolute novice probably many mistakes i would appreciate help experts possible def isvalidn n number checked number inty a converts string list useable digits altern integer sets altern one set alternating digits double x x altern doubles element list altern sum sumdouble adds together doubled items list altern integer sets altern set alternating digits return sum sumalternsums set alternating digits sumtotal sum sum works total sum worked mod sumtotal works remainder sumtotal divided mod remainder zero sumtotal multiple print true sumtotal multiple therefore n credit card number else print false sumtotal not multiple therefore valid credit card number here actual question the algorithm verifying number follows starting penultimate digit working towards rst digit double alternating digit b sum doubled digits treating etc add result sum undoubled digits c if sum divisible number valid credit card number write test function isvalid takes argument credit card number string eg valid returns true false depending whether number valid credit card number,2 winston ewert future method on better previous proposals to prove on observe inner loop executed value btarget my old answer here benchmark three approaches ping pong winston ewert ascending list binary search future full list future winston ewert numpyvectorize future enhanced version winston ewert future each significantly faster others different conditions if series random full list future fastest if series oscillates ascending list future fastest if series tends ascend vectorize future fastest if data stock quotes i would go vectorize future stocks ascending trend simple performs reasonably conditions output random series future ascends future full list future vectorize oscillating series future ascends future full list future vectorize ascending trend series future ascends future full list future vectorize code import numpy np import time import timeit def futurea def reverseenuml index reversedxrangelenl yield lenlindex lindex def findnextx a ascends find index first future number greater x idx segment reverseenumascends joffasegmentsegmentsearchsortedxside right binary search joff segmentsegment jsegmentjoff ascendspop rangeidx delete previous segments segmentj cut beginning segment return j return b nparangelena note bi greater value future b put end ascends list pairs indexes ascending segments a maximum true xrangelena scan backwards printascends ai ai maximum ascendsappendii maximum false else ascends else ai ai bi findnextai a ascends maximum true return b def futurea list tuples index a value a invariant indexes values sorted order known result idx xrangelena value aidx since known sorted binary search could applied i bothered anything lower current value cannot possibly used since value first index instead known xy xy known value known values known current value reverse sorted index value lowest index first resultappendknown else values exist high report resultappend add end list maintain invariant knownappend idx value let numpy worry reversing array return nparrayresult def futurea npvectorize def valuesi idx v enumerateai loop faster genexp exception aiv return idxi return return valuesnparangelena name main print random series tsetup import future import numpy a numpyrandomrandome timeittimeit futurefuturea tsetup number print future ascends strt timeittimeit futurefuturea tsetup number print future full list strt timeittimeit futurefuturea tsetup number print future vectorize strt print oscillating series tsetup import future import numpy a numpyrandomrandintesizeee a acumsum timeittimeit futurefuturea tsetup number print future ascends strt timeittimeit futurefuturea tsetup number print future full list strt timeittimeit futurefuturea tsetup number print future vectorize strt print ascending trend series tsetup import future import numpy a numpyrandomrandintesizeee a acumsum timeittimeit futurefuturea tsetup number print future ascends strt timeittimeit futurefuturea tsetup number print future full list strt timeittimeit futurefuturea tsetup number print future vectorize strt,i time series a i want generate another time series b bi j j first index greater aj ai fast way numpy thanks edited preferably use on space,1 you using sage function declaration syntax fxy somethingorother right hand side putting sage expression python one this evaluated declared by i mean sage varx x sage booly x false sage dens x else sage dens sage densxy x else sage dens x if care values function take say plotting simply use python function if want differentiate etc harder go i afraid,in sagemath version i notebook varx densxy x else give errors however typing dens returns dens returns in fact i found way get answer what i wrong,2 you try list comprehension result yourlist yourlist yourlists anynodestartswith node yourlist or generator expression want results memory result yourlist yourlist yourlists anynodestartswith node yourlist see working online ideone,i bit confused approach problem i large number lists looking delete lists contents start specific digit for example say i looking keep lists least one node start following lists i delete second one keep first list case i know detect ones start i figure lists trait sure mark lists deletion what best approach i many lists like thisseveral million i trying find least expensive way i thinking creating list lists keep comparing original list delete ones lists i trying avoid many nested loops,2 start generating many identical tuples n need an bn now pick two tuples random make random change value one compensating change value keeping everything within given constraints put two tuples back now pick another random pair this times twiddle b values lather rinse repeat,i faced following programming problem i need generate n b tuples sum given a sum b given b tuple ratio b range cmin cmax a b within range i also trying make sure bias result introduced constraints b values moreorless uniformly distributed given range some clarifications metaconstraints a b cmin cmax given the ratio a b cmin cmax range this problem solution given constraints b noninteger i trying implement python ideas language english included much appreciated,1 i think simplest thing use favorite method throw n values sumin ai a set get right total there several so question though i never seen answer i really happy yet maybe i write paper something get n b throwing ci uniformly allowed range set final b get right total check final c i think must ok i proven yet note since hard constrains expect throw n random numbers method exactly assumption step n throws,i faced following programming problem i need generate n b tuples sum given a sum b given b tuple ratio b range cmin cmax a b within range i also trying make sure bias result introduced constraints b values moreorless uniformly distributed given range some clarifications metaconstraints a b cmin cmax given the ratio a b cmin cmax range this problem solution given constraints b noninteger i trying implement python ideas language english included much appreciated,1 from wikipedia article luhn algorithm def isluhnvalidcc num mapint strcc return sumnum sumdivmodd num,i trying define function include variable n n string numbers eg definition function starts istruen however n going string istruen string defined i test function example string n i get syntax error i use istruen however and i wondering i would go testing function example string n my entire function define shown httpoitinypiccomiqojpg bear mind i absolute novice probably many mistakes i would appreciate help experts possible def isvalidn n number checked number inty a converts string list useable digits altern integer sets altern one set alternating digits double x x altern doubles element list altern sum sumdouble adds together doubled items list altern integer sets altern set alternating digits return sum sumalternsums set alternating digits sumtotal sum sum works total sum worked mod sumtotal works remainder sumtotal divided mod remainder zero sumtotal multiple print true sumtotal multiple therefore n credit card number else print false sumtotal not multiple therefore valid credit card number here actual question the algorithm verifying number follows starting penultimate digit working towards rst digit double alternating digit b sum doubled digits treating etc add result sum undoubled digits c if sum divisible number valid credit card number write test function isvalid takes argument credit card number string eg valid returns true false depending whether number valid credit card number,1 windows dos batch language ill suited kind task while may possible resulting script certain cumbersome convoluted confusing python fine solution clear posting want use if concern installing python consider pyexe allows create standalone python executable,i really need help using batch file following i need read text file line line entry given csv file starts element found line text file write new csv file or words read following examplecsv page pageviews bounce rate categoryapples categorybrusselsprout categoryorange then read following text file line line exampletxt categoryapples categoryorange and create file newcsv page pageviews bounce rate categoryapples categoryorange so far i worked project batch file takes individual address list checks see certain header writes extension list unfortunately enough i also need regenerate tables original csv ones header i attempting via python proving cumbersome system boundaries made feasible write python anyway if like see code click questions profile concern piece what i left i ask clarity ideas strengths lie bat c option thank help this community exception proved excellent grounds learning valuable lessons pushing succeed this i headed python import csv lines open outputtxt r f line freadlines linesappendline open correctedcsv w correct writer csvwritercorrect dialect excel open inputcsv r mycsv reader csvreadermycsv row reader row lines writerwriterowrow,1 abspath based getcwd most likely current working directory simply expect you change code launches script change directories manually use chdir python,question pretty much title suggests research led try something like import os pathname ospathabspathsomerelativedirectory print pathname problem whenever something like simply returns whatever relative directory gave preceded python directory example cpythonsomerelativedirectory even existing directory computer understand python interpreter searches working directory default like search entire computer absolute path contains partial directory specify purpose create exe using pyexe search arbitrary directory computer method standard library available module would implement algorithm,2 this make sense invoice invoices invoicesdataclientid clientdataid i think must mean invoice invoices invoicedataclientid clientdataid if case solution quandary simply add assertions invoices object received callback eg invoicedataclientidshouldbe clientdataid invoice invoices whatever correct syntax assertions test—you used shouldbe example with extra assertion easier make function work properly generate fake data,i like test force design i comes collections i always run problems the code i want force following clientinvoices client callback invoices callback invoice invoice invoices invoicedataclientid clientdataid at first i wrote get randomid invoices subjectclientinvoices client invoices invoiceslengthshouldbe but since need make test pass least amount effort could make pass clientinvoices client callback invoices callback the code coffeescript examples python ruby javascript appreciated,1 you use sysexcepthook sysexcepthook catches exceptions uncaught code how handle choice for sending emails may interested python email module here examples you reconstruct traceback exception using python traceback module specifically formatexception import sys import traceback def excepthooktype value tb whatever exception information want exception tracebackformatexceptiontype value tb print joinexception sysexcepthook excepthook note i know anything twisted may twisted way pun intended however i would official way course,i initialize servers one twisted script so i want get unhadled exception inside mail is posible thank,1 from httpmatplotlibsourceforgenetexampleseventhandlingpickeventdemohtml matplotlibpyplot import figure show import numpy npy numpyrandom import rand picking scatter plot matplotlibcollectionsregularpolycollection x c rand def onpickevent ind eventind print onpick scatter ind npytakex ind npytakey ind fig figure ax figaddsubplot col axscatterx c pickertrue figsavefig pscolleps figcanvasmplconnect pickevent onpick show this recipe draws annotation picking data point httpscipycookbookreadthedocsioitemsmatplotlibinteractiveplottinghtml this recipe draws tooltip requires wxpython point line tooltips matplotlib,i using matplotlib make scatter plots each point scatter plot associated named object i would like able see name object i hover cursor point scatter plot associated object in particular would nice able quickly see names points outliers the closest thing i able find searching annotate command appears create fixed label plot unfortunately number points i scatter plot would unreadable i labeled point does anyone know way create labels appear cursor hovers vicinity point,3 assuming using stream tcp socket first rule stream sockets receive data groups sent if send three messages bytes may receive end one block bytes blocks one byte anything you must structure protocol receiver knows long message within stream either adding length field fixed length message formats must save unused portion recv crosses message boundary use next message the alternative streamtcp sockets datagramudp sockets these preserve message boundaries guarantee delivery ordering messages depending may acceptable probably,hello i written client server code write i noticed i bug i handling receiving command these commands server commands cmdmsg cmdmulti cmdip cmdaudio cmdaudiomulti cmdfile range i send command like selfclientchrcmdaudio data receive like msg connrecv msg cmd msg ordmsgmsg cmd cmdmsg something the first command seems work i call seems loop its really bizarre i post code needed but ideas handle commands sent server would great cheers,1 djangotemplateloader import gettemplatefromstring tpl templategettemplatefromstringmy name myname,i storing templates database i path provide templaterender method is exposed method accepts template string is workaround,2 if i remember right pyexe discontinued really safe use i use cxfreeze never failed working it might help also remember paths different frozen vs script typically need ospathdirnamesysexecutable frozen test using hasattrsys frozen vs typical ospathdirnamefile also make sure copying imageformats qt plugin directory it caused problems people the imageformats folder svg plugin resides well you also need copy pyqtqtxml pyqtqtsvg dll sso well required svg plugin my project buildbinarypy file cxfreeze autodetects plugin directory copies required stuff it may help take look,my pyqt application pyexe binary flashes briefly screen disappears i idea happened my application display svg images loading exe i dug around bit saw i modify setuppy include qtconf dlls then binary stopped loading qtconf included i played qtconf found exe load unless i delete qtconf i think malformed here qtconf paths plugins plugins i tried absolute paths forward slashes back slashes name i even copied entire pyqt folder file still luck if relevant setuppy import os sys glob distutilscore import setup pyexebuildexe import pyexe def finddatafilessourcetargetpatterns globhasmagicsource globhasmagictarget raise valueerrormagic allowed src target ret pattern patterns pattern ospathjoinsourcepattern filename globglobpattern ospathisfilefilename targetpath ospathjointargetospathrelpathfilenamesource path ospathdirnametargetpath retsetdefaultpathappendfilename return sortedretitems setup zipfile none datafiles finddatafiles bin pluginsiconengines qtconf windows script mainpy cmdclass pyexe pyexe options pyexe bundlefiles includes sip dllexcludes msvcpdll qsvgicondll,1 add numpy libraries syspath call import,i xd code references python script i trying implement certain functions make use numpy module however i able import builtin modules python i looking way import numpy module script without call interpreter ie testpy instead python testpy currently i get importerror no module named numpy my question is way import numpy module without call interpreter is way include numpy one builtin modules python,1 the example given works i wonder facing newline issue instead stripping one character line outputtxt try strip method that instead line use linestrip if still problems try opening inputcsv rb mode instead r and still problems start putting lot print statements telling us see,it works perfectly idea take list names text file new line create new csv file based whether line starts text name here i got far import csv lines open outputtxt r f line freadlines linesappendline open correctedcsv w correct writer csvwritercorrect dialect excel open inputcsv r mycsv reader csvreadermycsv row reader row lines writerwriterowrow the problem quits i checked data goes properly perfectly appends line data new csv file continue one i played around loops i got lot help so users build really know i need mess around if i vague needy please let know thank help received example outputtxt categoryapples categoryoranges categorybrusselsprouts categoryzuccini categorypassionfruit inputcsv categoryapples categoryoranges categorybrusselsprouts categoryzuccini categorypassionfruit correctedcsv categoryapples categoryoranges categorypassionfruit as see checks inputcsv values listed outputtxt create correctedcsv here example i getting instead correctedcsv categoryapples this issue resolved however new error i new issue i made counting program def filelenfname openfname f l enumeratef pass return x fileleninputtxt filelenoutputtxt z fileleninputcsv q filelencorrectedcsv print inputtxt x print outputtxt print inputcsv z print correctedcsv q user input and counting program results inputtxt outputtxt inputcsv correctedcsv what would account issue missing transfer outputtxt correctedcsv,1 i understand i run code correctedcsv contains first four lines five apples oranges brusselsprouts zucchini it would written last line passionfruit except read outputtext deleting last character leaving passionfrui match get rid line use strip linesappendlinestrip why expect correctedcsv contain apples oranges passionfruit,it works perfectly idea take list names text file new line create new csv file based whether line starts text name here i got far import csv lines open outputtxt r f line freadlines linesappendline open correctedcsv w correct writer csvwritercorrect dialect excel open inputcsv r mycsv reader csvreadermycsv row reader row lines writerwriterowrow the problem quits i checked data goes properly perfectly appends line data new csv file continue one i played around loops i got lot help so users build really know i need mess around if i vague needy please let know thank help received example outputtxt categoryapples categoryoranges categorybrusselsprouts categoryzuccini categorypassionfruit inputcsv categoryapples categoryoranges categorybrusselsprouts categoryzuccini categorypassionfruit correctedcsv categoryapples categoryoranges categorypassionfruit as see checks inputcsv values listed outputtxt create correctedcsv here example i getting instead correctedcsv categoryapples this issue resolved however new error i new issue i made counting program def filelenfname openfname f l enumeratef pass return x fileleninputtxt filelenoutputtxt z fileleninputcsv q filelencorrectedcsv print inputtxt x print outputtxt print inputcsv z print correctedcsv q user input and counting program results inputtxt outputtxt inputcsv correctedcsv what would account issue missing transfer outputtxt correctedcsv,1 find numpy installed system for usrlibpymodulespython import explicitly importing numpy import sys syspathappend usrlibpymodulespython need help finding correct path check contents syspath using python interpreter import sys print syspath,i xd code references python script i trying implement certain functions make use numpy module however i able import builtin modules python i looking way import numpy module script without call interpreter ie testpy instead python testpy currently i get importerror no module named numpy my question is way import numpy module without call interpreter is way include numpy one builtin modules python,2 i going guess line pointing different python interpreter one use normally make sure point one,i xd code references python script i trying implement certain functions make use numpy module however i able import builtin modules python i looking way import numpy module script without call interpreter ie testpy instead python testpy currently i get importerror no module named numpy my question is way import numpy module without call interpreter is way include numpy one builtin modules python,2 the case etreehtmlparser receives html creates full html dom tree so instead intended use etreetostringtree get doctype html public wcdtd html transitionalen httpwwwworgtrrechtmlloosedtd htmlbodydiv pspana hrefurlspanp h classheadera hrefurlotherah hrefurlotherabra classaaaaa hrefurlindicea p so correct xpath would htmlbodydivh,i trying parse html i problem little html code xml div pspana hrefurlaspanp h classheadera hrefurlotherah hrefurlotherabr classaaaaa hrefurlindicea pp div code import urllib lxml import etree import stringio resultadourlliburlopen trozohtml html resultadoread parser etreehtmlparser treeetreeparsestringiostringiohtmlparser xpath divh htmlfiltradotreexpathxpath print htmlfiltrado when i print code appears i suppose it list h classheadera hrefurlotherah if i would list i would execute etreetostringhtmlfiltrado see h classheadera hrefurlotherah so get code h classheadera hrefurlotherah or url part i want thank,2 after homework aka research trying directly convert java code reference posted question python sad experience trying pythonnumpy update humongous array pixel colors based positions rippling ripple effect sorry first language english thus parsing several xy positions pass effect calculations blitting onto displayed surface screen surfarray ensues i come conclusion backed commenters pygame simply powerful enough actually traverse entire array pixels apply results calculations onto every pixel screen minimum rate fps lessthanaverage experience quoting developer behind last light productions former project geometrian ian mallet pygame good pixel pushing nothing gpu the search turned search alkahest something would turn never truly found based idea rippling images time using transparency see several layers pygame surfaces i posted question pygame circular croppingmasks gamedev the chosen answer actually corroborates fact i already feared pygame would never macho enough job one day later i went back previous ideas development came across ogred it turns ogred samples opensource one examples d water model interacts moving object exactly thing i tried achieve d much professional manner since knowledge cc nil i decided ask customize ogred water demo glimpse start looking one answers pointed software touchscape sdk provided see answer ogred pretty much wrapped water ripple effect opengl may optionally use based hardware game engine python wrappers via pythonogre answer question can anyone provide suitable implementation effect using opencvopengl pygame basically yes check ogred water demo provided sdk plug python via pythonogre,i googled ready scripts opposed effect flash i checked algorithm the water effect explained also tested implementation perlin noise provides good simulation end waves flat surface i looking implementation found several flash effects based mouseoverhover actions this targetting interactive floor library i would enjoy moving away flash matter particularly avoid easy reverseengineering code yes i know could use readymade flash code i would use last resort has anyone seen suitable implementation effect pygame using opengl edit can anyone provide suitable implementation effect using opencvopengl pygame the culprit code interface pass list values sent external interpreter tracker tuio though via python i tried straight days pygame able generate anything fast sheer cc code used shaders opengl knowledge cc null so target least coming python code a good example different flash effect still good water simulation using java applet bounty showing answers enough detail since closest op incapable creating code wants lacks fundamental skills answer probably use several people,3 the xpath query example quite right to get list h tags within div tags use elements treexpath divh etreetostringelements which give h classheadera hrefurlotherahn to get list href attributes tags within h tags could use something like treexpath hahref which gives url,i trying parse html i problem little html code xml div pspana hrefurlaspanp h classheadera hrefurlotherah hrefurlotherabr classaaaaa hrefurlindicea pp div code import urllib lxml import etree import stringio resultadourlliburlopen trozohtml html resultadoread parser etreehtmlparser treeetreeparsestringiostringiohtmlparser xpath divh htmlfiltradotreexpathxpath print htmlfiltrado when i print code appears i suppose it list h classheadera hrefurlotherah if i would list i would execute etreetostringhtmlfiltrado see h classheadera hrefurlotherah so get code h classheadera hrefurlotherah or url part i want thank,2 you looking join import platform platformlinuxdistribution ubuntu natty joinplatformlinuxdistribution ubuntu natty,i want strip platformlinuxdistribution output tuple ubuntu oneiric i want show ubuntu oneriric group working,3 you set attribute variable value way eventojbectk hello setting attribute k hello model you simply assigning eventobjectk foo repeating k itemkeys setattreventobject k itemk print eventobjects k eventobjectk or case could pass keyvalue pairs model constructor eventobject eventitems,i webscraper delivers dictionary objects data entered django model i written simple script test loading data it operates iterating dictionary object delivering key value appropriate model field keys share names respective model fields while new model object accepts data retained iteration i figure in eventsmodels import event in eventobject event new model object hold item in item title hellooo description test eventid we want load item eventobject in k itemkeys eventobjectk itemk print eventobjects k eventobjectk eventobjecteventid eventobject received item data expected eventobjectdescription test eventobjecttitle hellooo in eventobject eventobject still empty out event in eventobjecttitle making sure out in k itemkeys eventobjectk itemk print eventobjects k eventobjectk eventobjectsave oh maybe need save eventobjecteventid integrityerror traceback recent call last homeanthonydropboxprojectsdjangolivingcitymapipython console module usrlocallibpythondistpackagesdjangodbmodelsbasepyc saveself forceinsert forceupdate using forceinsert forceupdate raise valueerrorcannot force insert updating model saving selfsavebaseusingusing forceinsertforceinsert forceupdateforceupdate savealtersdata true usrlocallibpythondistpackagesdjangodbmodelsbasepyc savebaseself raw cls origin forceinsert forceupdate using values create new record result managerinsertvalues returnidupdatepk usingusing else create new record defaults everything usrlocallibpythondistpackagesdjangodbmodelsmanagerpyc insertself values kwargs def insertself values kwargs return insertqueryselfmodel values kwargs def updateself values kwargs usrlocallibpythondistpackagesdjangodbmodelsquerypyc insertquerymodel values returnid rawvalues using part public api query sqlinsertquerymodel queryinsertvaluesvalues rawvalues return querygetcompilerusingusingexecutesqlreturnid usrlocallibpythondistpackagesdjangodbmodelssqlcompilerpyc executesqlself returnid def executesqlself returnidfalse selfreturnid returnid cursor supersqlinsertcompiler selfexecutesqlnone returnid cursor return usrlocallibpythondistpackagesdjangodbmodelssqlcompilerpyc executesqlself resulttype cursor selfconnectioncursor cursorexecutesql params resulttype usrlocallibpythondistpackagesdjangodbbackendsutilpyc executeself sql params start time try return selfcursorexecutesql params finally stop time usrlocallibpythondistpackagesdjangodbbackendspostgresqlpsycopgbasepyc executeself query args def executeself query argsnone try return selfcursorexecutequery args except databaseintegrityerror e raise utilsintegrityerror utilsintegrityerrortuplee sysexcinfo integrityerror null value column eventid violates notnull constraint and model case curious djangocontribgisdb import models class eventmodelsmodel title modelscharfieldmaxlength description modelstextfield eventid modelsintegerfieldmaxlength genre modelscharfieldmaxlength contact modelscharfieldmaxlength cost modelscharfieldmaxlength venue modelscharfieldmaxlength address modelscharfieldmaxlength neighborhood modelscharfieldmaxlength city modelscharfieldmaxlength date modelsdatetimefield this replaced new class time modelscharfieldmaxlength this obviously datetime probably exist class first requires input normalized via serious regex magic def unicodeself return selftitle,1 because str type type wich attribute dict from docs classes section a class namespace implemented dictionary object class attribute references translated lookups dictionary eg cx translated cdictx you also enforce something similar custom objects class xobject slots x aa afoo traceback recent call last file stdin line module attributeerror x object attribute foo in general setting modifying fields objects supposed the documentation specific data type reference fields available public modification for example readonlypoint object x coordinates set object construction class readonlypointobject slots x def initself x selfx x selfy def getxself return selfx def getyself return selfy x propertygetx propertygety p readonlypoint print px py px traceback recent call last file stdin line module attributeerror set attribute px print px py while x properties readonly accessing object internals allows alter object state the inhability add new field str object implementation detail specific python version using,usually set arbitrary attribute custom object instance aa afoo adict foo on hand binding string object astrbar afoo traceback recent call last file stdin line module attributeerror str object attribute foo adict traceback recent call last file stdin line module attributeerror str object attribute dict why,3 httpdocspythonorgreferencedatamodelhtml if class setattr delattr method called instead updating instance dictionary directly httpdocspythonorgreferencedatamodelhtmlobject setattr,usually set arbitrary attribute custom object instance aa afoo adict foo on hand binding string object astrbar afoo traceback recent call last file stdin line module attributeerror str object attribute foo adict traceback recent call last file stdin line module attributeerror str object attribute dict why,1 answering question anyone knows better feel free answer some seems quite fragile eg version numbers paths comment edit know better way finding files firstly i use code actually find root gtk runtime this specific install runtime though could probably improved number checks common locations gtk file inclusion import gtk the runtime dir directory module gtkruntimedir ospathjoin ospathsplitospathdirnamegtkfile runtime assert ospathexistsgtkruntimedir cannot find gtk runtime data what files include this depends much concern size b context application deployment by i mean deploying whole wide world anyone arbitrary locale setting internal corporate use need translated stock strings if want windows theming need include gtkthemedefault ospathjoinshare themes default gtkthemewindows ospathjoinshare themes mswindows gtkgtkrcdir ospathjoinetc gtk gtkgtkrc gtkrc gtkwimpdir ospathjoinlib gtk engines gtkwimpdll libwimpdll if want tango icons gtkicons ospathjoinshare icons there also localisation data i omit might want gtklocaledata ospathjoinshare locale piecing together firstly function walks filesystem tree given point produces output suitable datafiles option def generatedatafilesprefix tree filefilternone walk filesystem starting prefix tree producing list files suitable datafiles option setup the prefix omitted path given setup for example cpythonlibsitepackagesgtkruntimeetc want dist dir contain etc subdirectory invoke function generatedatafiles rcpythonlibsitepackagesgtkruntime retc if instead want contain runtimeetc use generatedatafiles rcpythonlibsitepackagesgtk rruntimeetc empty directories omitted filefilterroot fl optional function called containing directory filename file if returns false file omitted results datafiles root dirs files oswalkospathjoinprefix tree todir ospathrelpathroot prefix filefilter none fileiter fl fl files filefilterroot fl else fileiter files datafilesappendtodir ospathjoinroot fl fl fileiter nonempties fro fro datafiles fro return nonempties so call setup like setup other setup args datafiles use function generatedatafilesgtkruntimedir gtkthemedefault generatedatafilesgtkruntimedir gtkthemewindows generatedatafilesgtkruntimedir gtkicons include single files manually gtkgtkrcdir ospathjoingtkruntimedir gtkgtkrcdir gtkgtkrc gtkwimpdir ospathjoin gtkruntimedir gtkwimpdir gtkwimpdll,i using python pygtk allinone installer windows xp trying build singlefile executable via pyexe app my problem i run app script ie built exe file loose collection py files uses nativelooking windows theme i run built exe i see default gtk theme i know problem fixed copying bunch files dist directory created pyexe everything i read involves manually copying data whereas i want automatic part build process furthermore everything topic including faq date pygtk keeps files cpythonxlibsitepackagesgtkruntime copying lib etc directories fix problem my questions i like able programmatically find gtk runtime data setuppy rather hard coding paths how i what minimal resources i need include update i may almost answered trialanderror for wimp ie ms windows theme work i need files runtimelibgtkengineslibwimpdll runtimeetcgtkgtkrc runtimeshareicons runtimesharethemesmswindows without runtime prefix otherwise directory structure sitting directly dist directory produced pyexe but come given gtkgtkversion,3 saving array floats text file creates m text file when reload numpy goes file linebyline parsing text recreating objects i would expect memory usage spike time numpy know big resultant array needs gets end file i expect least m m temporary memory used here relevant bit numpy code libnpyiopy parse line including first line enumerateitertoolschainfirstline fh vals splitlineline lenvals continue usecols vals valsi usecols convert value according column store items convval conv val zipconverters vals then pack according dtype nesting items packitemsitems packing xappenditems a bit x nparrayx dtype this additional memory usage concern way python works python process appears using m memory internally maintains knowledge items longer used reuse memory for example rerun saveload procedure one program save load save load memory usage increase m,when i load array using numpyloadtxt seems take much memory eg numpyzerosinte causes increase mb memory using htop bytesmillion approx mb on hand i save load array numpysavetxt acsv b numpyloadtxt acsv memory usage increases mb again i observed htop this observed ipython shell also stepping code using pdb any idea going after reading jozzas answer i realized i know ahead time array size much memory efficient way things say mxn array b numpyzerosmn open acsv r f reader csvreaderf row enumeratereader bi numpyarrayrow,3 generally i suggest your productioncode really realize unittests exist one reason could code testing block makes tests pass accidentally since production runs code run bits could leave exposed failure production even tests pass however insist two potential ways i think done first could use module level testing var set test case true for example production code testing false this false overridden tests def foo testing print expensive stuff unittest code import production def testfoo productiontesting true productionfoo prints expensive stuff the second way use python builtin assert keyword when python run o interpreter strip ignore assert statements code allowing sprinkle expensive gems throughout know run executed optimized mode just sure run tests without o flag example production code def expensivechecks print expensive stuff return true def foo print normal speedy stuff assert expensivechecks foo output run python mycodepy normal speedy stuff expensive stuff output run python o mycodepy normal speedy stuff one word caution assert statements assert statement evaluate true value assertionerror raised,let say i following function def f testing run expensive sanity check code what correct way run testing code block running unittest edit is global variable i access find unittests,3 the method described post worked perfectly ubuntu httpdewbotposterouscominstallationofpythonandgoogleappengi,i trying use google appengine python skd ubuntu lucid i already compiled python but i execute devappserverpy command i get following error traceback recent call last file devappserverpy line module runfilefile globals file devappserverpy line runfile execfilescriptpath globals file homerohanworkspaceappengoogleappenginegoogleappenginetoolsdevappservermainpy line module googleappenginetools import appcfg file mediaultimatewebddjangoappenginegoogleappenginegoogleappenginetoolsappcfgpy line module googleappenginetools import appenginerpc file mediaultimatewebddjangoappenginegoogleappenginegoogleappenginetoolsappenginerpcpy line module import fancyurllib file mediaultimatewebddjangoappenginegoogleappenginelibfancyurllibfancyurllibinitpy line module class fancyhttpshandlerurllibhttpshandler attributeerror module object attribute httpshandler i checked urllib moduls python python difference models defination httpshandelr python so i guess sort error i tried run default python i get following error warning datastorefilestubpy could read datastore data tmpdevappserverdatastore traceback recent call last file devappserverpy line module runfilefile globals file devappserverpy line runfile execfilescriptpath globals file homerohanworkspaceappengoogleappenginegoogleappenginetoolsdevappservermainpy line module sysexitmainsysargv file homerohanworkspaceappengoogleappenginegoogleappenginetoolsdevappservermainpy line main staticcachingstaticcaching file homerohanworkspaceappengoogleappenginegoogleappenginetoolsdevappserverpy line createserver server httpserverwithschedulerserveaddress port handlerclass file homerohanworkspaceappengoogleappenginegoogleappenginetoolsdevappserverpy line init requesthandlerclass file usrlibpythonsocketserverpy line init selfserverbind file usrlibpythonbasehttpserverpy line serverbind socketservertcpserverserverbindself file usrlibpythonsocketserverpy line serverbind selfsocketbindselfserveraddress file string line bind socketerror errno address already use it works well windows even wine update problem python solved i configured apache server django deployment port time earlier but still error python isntallation,1 you use model meta property fill database table name djangodb import connection cursor connectioncursor cursorexecute truncate table formatmymodelmetadbtable note this work inherited models span multiple tables,to empty database table i use sql query truncate table books how i truncate table using django models orm i tried work bookobjectstruncate,3 my approach problem i wrap fortran code fpy explicitly declare relevant numpy arrays fortran order numpy happily work transparently even works well combining fortran c order arrays unfortunately seems numpy operations preserve fortran order therefore preallocate destination arrays passed mex fortran order example a npempty b npempty fill a b data want c npempty order f c npdota b note index essential c passed mex routine i sure much efficient solution a since assignment implicit copy however need reorder fortran arrays coming mex routine numpy deal quite transparently long knows order,i porting matlab code numpy this task includes stripping mex c code replacing equivalent calls numpy capi one problem mex code treats incoming data fortranordered matlab orders arrays numpy hand uses c ordering default short completely rewriting mex code c ordering i a reorder arrays go c code copy f reorder come copy c b figure get numpy emulate matlab everything fortran order getgo option a currently implemented works fine terribly inefficient anybody know make option b work,2 the usual technique use tryexcept exception highest level call main function this pretty much assures missed exception matches nonexiting exceptions casting broad net,i python script running background i want log exception output log file i know use logging module try catch log exception i missed way log exceptions,1 you bunch options you could go allout xml parser like lxml though seem want domainspecific solution i go multiline regex import rex recompiler fontfont resrem data font facearialhelvetica size jul font match rexmatchdata match text matchgroupsstrip now text turn date pretty easily datetime import datetime date datetimestrptimetext b,i string font facearialhelvetica size jul font outputs two lines must n i wish extract string fontfont tags in case jul might another date number the best way extract value font tags i thinking i could extract everything edit second question removed,2 or could simply use beautiful soup beautiful soup python htmlxml parser designed quick turnaround projects like screenscraping,i string font facearialhelvetica size jul font outputs two lines must n i wish extract string fontfont tags in case jul might another date number the best way extract value font tags i thinking i could extract everything edit second question removed,1 while may possible parse arbitrary html regular expressions often death trap there great tools parsing html including beautifulsoup python lib handle broken well good html fairly well beautifulsoup import beautifulsoup bshtml bs bshtml font facearialhelvetica size jul font bsfontcontentsstrip u jul then need parse date datetimestrptimebsfontcontentsstrip b datetimedatetime datetimedatetime,i string font facearialhelvetica size jul font outputs two lines must n i wish extract string fontfont tags in case jul might another date number the best way extract value font tags i thinking i could extract everything edit second question removed,3 the following works image f e ospathsplitextinfile print infile outfile f jpg infile outfile im imageopeninfile imconvert rgb saveoutfile jpeg,i prototyping image processor python using pil i would like images end jpg input file types include tiffgifpng transparency without i trying combine two scripts i found convert file types jpg removing transparency creating blank white image pasting original image white background my searches spammed people seeking generate preserve transparency rather opposite i currently working usrbinpython import os glob import image images globglobpngglobglobgif infile images f e ospathsplitextinfile outfile f jpg infile outfile try im imageopeninfile create new image solid color background imagenew rgba imsize paste image top background backgroundpasteim im i suspect problem line im backgroundconvert rgb convert p paletteimageadaptive imsaveoutfile except ioerror print cannot convert infile both scripts work isolation i combined i get valueerror bad transparency mask traceback recent call last file pilhellopy line module backgroundpasteim im file usrlibpythondistpackagespilimagepy line paste selfimpasteim box maskim valueerror bad transparency mask i suspect i save png without transparency i could open new file resave jpg delete png written disk i hoping elegant solution i found yet,2 make background rgb rgba and remove later conversion background rgb course since already mode this worked test image i created pil import image im imageopenrcjkpng bg imagenewrgb imsize bgpasteimim bgsavercjkjpg,i prototyping image processor python using pil i would like images end jpg input file types include tiffgifpng transparency without i trying combine two scripts i found convert file types jpg removing transparency creating blank white image pasting original image white background my searches spammed people seeking generate preserve transparency rather opposite i currently working usrbinpython import os glob import image images globglobpngglobglobgif infile images f e ospathsplitextinfile outfile f jpg infile outfile try im imageopeninfile create new image solid color background imagenew rgba imsize paste image top background backgroundpasteim im i suspect problem line im backgroundconvert rgb convert p paletteimageadaptive imsaveoutfile except ioerror print cannot convert infile both scripts work isolation i combined i get valueerror bad transparency mask traceback recent call last file pilhellopy line module backgroundpasteim im file usrlibpythondistpackagespilimagepy line paste selfimpasteim box maskim valueerror bad transparency mask i suspect i save png without transparency i could open new file resave jpg delete png written disk i hoping elegant solution i found yet,3 i write batch file need however i know csv file format i assumed several details these assumptions the csv file contains ascii text crlf separators each csv element separated comma and do not contain spaces limitation may solved the size input csv file kb required read contents batch variable the csv data comprised groups elements header elements category elements both categories csv file lines txt file placed ascii ascending order the categories txt file are included csv this batch file echo setlocal enabledelayedexpansion rem read csv data splitstore elements csv array set p csvdata examplecsv set e csvdata set a set csvie rem create newcsv file header echo csv csv csv newcsv rem process line text file set f l exampletxt call seekandwritecsv l goto eof seekandwritecsv rem seek matching csv category set a csvi goto seekandwritecsv rem write matching category newcsv file set a ji ki echo csvi csvj csvk newcsv that please try let know problem get edit i realized error newcsv categories placed separated lines to fix make changes change lines rem create newcsv file header echo csv csv csv newcsv ones rem create newcsv file header echo entertxt set p dummycsv csv csv entertxt newcsv change line echo csvi csvj csvk newcsv one set p dummy csvi csvj csvk entertxt newcsv also avoid errors special characters insert quotes line set csvie way set csvie,i really need help using batch file following i need read text file line line entry given csv file starts element found line text file write new csv file or words read following examplecsv page pageviews bounce rate categoryapples categorybrusselsprout categoryorange then read following text file line line exampletxt categoryapples categoryorange and create file newcsv page pageviews bounce rate categoryapples categoryorange so far i worked project batch file takes individual address list checks see certain header writes extension list unfortunately enough i also need regenerate tables original csv ones header i attempting via python proving cumbersome system boundaries made feasible write python anyway if like see code click questions profile concern piece what i left i ask clarity ideas strengths lie bat c option thank help this community exception proved excellent grounds learning valuable lessons pushing succeed this i headed python import csv lines open outputtxt r f line freadlines linesappendline open correctedcsv w correct writer csvwritercorrect dialect excel open inputcsv r mycsv reader csvreadermycsv row reader row lines writerwriterowrow,2 your labels document model mm field going end rendering multiselect rendered form showing labels available system assuming want viewspy def uploaddocumentrequest requestmethod post form documentformrequestpost requestfiles formisvalid labels requestpostgetlist labels newdocument formsave labelid labels going add currently defined labels label labelobjectsgetidintlabelid newdocumentlabelsaddlabel newdocumentsave return httpresponseredirectthanks else form documentform return rendertoresponse docformhtml form form contextinstancerequestcontextrequest i updated model label modelspy class labelmodelsmodel name modelscharfieldmaxlength uniquetrue slug modelsslugfieldmaxlength uniquetrue editablefalse def saveself args kwargs selfslug slugifyselfname superlabel selfsaveargs kwargs def unicodeself return selfname if thinking user also create labels fly need override labels field form something else like input field as example instructing users enter labels seperated commas updated viewspy like label labels labels entered user try lbl labelobjectsgetname label except labeldoesnotexist lbl none lbl lbl label lblname label lblsave newdoclabelsaddlbl newdocsave hope solves problem give something work,i set document objects label objects i want two objects linked it typical manytomany relationship i following code modelspy class documentmodelsmodel title modelscharfieldmaxlength uniquetrue titleslug modelsslugfieldmaxlength uniquetrue editablefalse labels modelsmanytomanyfield label def saveself args kwargs selftitleslug slugifyselftitle superdocument selfsaveargs kwargs class labelmodelsmodel name modelscharfieldmaxlength uniquetrue slug modelsslugfieldmaxlength uniquetrue editablefalse def saveself args kwargs selfslug slugifyselfname superdocument selfsaveargs kwargs viewspy class documentformmodelform class meta model document fields titlelabels def uploaddocumentrequest requestmethod post form documentformrequestpost requestfiles formisvalid newdocument formsave return httpresponseredirectthanks else form documentform return rendertoresponse uploadpagehtml form form contextinstancerequestcontextrequest when i upload document gets added database however labels created associated document do i need explicitly add something document save function make happen or somewhere viewspy file i imagine go something like check see label added already exists if create new label grab current documentid newexisting labelid add record documentlabels table automatically created manytomany relationship i feel like pretty standard functionality i assumed would built manytomany relationship django seem working far i trying avoid reinventing wheel somewhat new django thanks advance,1 modify code bit like def factorarg arg n x factors abso x x n x factorsappendn x else x return factors a intrawinputwhat a quadratic equation a b intrawinputwhat b quadratic equation b c intrawinputwhat c quadratic equation c br absb absa range b bpf range br br possible factors b abpf factora c possible factors a c acpf abpf acpfappendi acpfappendi cf common factors bpf j acpf j cfappendi print cf now try running you get result,ok i finally started math python far surprisingly hard i thought would bei know calculus trigonometry know basic algebra i trying create program scratch factors quadratic equations here i far sorry poorly written def factorarg arg n x factors abso x x n x factorsappendn x else x return factors a intrawinputwhat a quadratic equation a b intrawinputwhat b quadratic equation b c intrawinputwhat c quadratic equation c br absb absa range b bpf range br br possible factors b acpf factora c possible factors a c abpf acpfappendi cf common factors bpf j acpf j cfappendi print cf i ran script terminal asked a b c froze thirty seconds after unfroze i typed said killed does anyone know caused i appreciate answers advice,1 it looks like problem lines acpf factora c possible factors a c abpf acpfappendi try instead acpf factora c possible factors a c acpf loop copy acpf acpfappendi the notation used copy list that makes sure mutating list growing looping also little cleanup code factor def factorarg arg factors x range x n x factorsappendn return factors,ok i finally started math python far surprisingly hard i thought would bei know calculus trigonometry know basic algebra i trying create program scratch factors quadratic equations here i far sorry poorly written def factorarg arg n x factors abso x x n x factorsappendn x else x return factors a intrawinputwhat a quadratic equation a b intrawinputwhat b quadratic equation b c intrawinputwhat c quadratic equation c br absb absa range b bpf range br br possible factors b acpf factora c possible factors a c abpf acpfappendi cf common factors bpf j acpf j cfappendi print cf i ran script terminal asked a b c froze thirty seconds after unfroze i typed said killed does anyone know caused i appreciate answers advice,1 being future proof impossible software exist viewed vapourware use works today ignore may exist tomorrow,i want make app django pylons i came know django supporting python near future so i want know i update django python supported support python changes i need or things done people developing django i need changes and possible update django and django easily portable pylons if i update django python future sort changes required will rework except i think i rails choice please suggest thanks,1 how using free statistics provider like statcounter google analytics,i django application hosted server running apache ubuntu i deployed application using modwsgi is way find number visitors web site i realize query might little django server any help would appreciated,1 why use google analytics you easily monitor user behavior traffic source time spend page etc if really want django could write context processor record request would write user ip check user visited would incredibly imprecise since might different users sharing ip etc,i django application hosted server running apache ubuntu i deployed application using modwsgi is way find number visitors web site i realize query might little django server any help would appreciated,1 i person wrote blog post listed i copied code gist ran kubuntu installing pyrssgen produced code without problem take look testxml file look like xml version encodingutf rss version xmlnsmediahttpsearchyahoocommrss channel titleexample titletitle linkhttpexamplecomlink descriptionexample rss outputdescription pubdatethu oct gmtpubdate lastbuilddatethu oct gmtlastbuilddate generatorpyrssgengenerator docshttpblogslawharvardedutechrssdocs item titleitem titletitle linkhttpexamplecomlink mediathumbnail urlhttpexamplecomimagejpgmediathumbnail description cdatapbexamplebtextpbr pwhere going todayp description guidrandomguidxguid pubdatethu oct gmtpubdate item channel rss i try explain code works posterity sake much like viennamike said pyrssgen uses built sax library automatically escapes html there however ways get around in code fragment mentioned i overrode pyrssgen rssitem output description would actually output anything this behind inclusion nooutput class since description output add method attach output hence publishextensions code outputs mediathumbnail description tags i see somewhat confusing since need mediathumbnail class i gone ahead rewritten class media thumbnail class muck things this insecure proof concept your mileage may vary et cetra import pyrssgen import datetime class nooutput def initself pass def publishself handler pass class iphonersspyrssgenrssitem def initself kwargs pyrssgenrssiteminitself kwargs def publishself handler selfdonotautooutputdescription selfdescription selfdescription nooutput this disables pygenrss automatic output description would escaped pyrssgenrssitempublishself handler def publishextensionsself handler handleroutwrite cdatass description selfdonotautooutputdescription description how use rss pyrssgenrss title example title linkhttpexamplecom descriptionexample rss output lastbuilddatedatetimedatetimeutcnow pubdatedatetimedatetimeutcnow items iphonerss titleitem title descriptionpbexamplebtextpbr pwhere going todayp linkhttpexamplecom guidrandomguidx pubdatedatetimedatetimenow rssrssattrsxmlnsmedia httpsearchyahoocommrss rsswritexmlopentestxml w utf you mention want include image feed including html image description tag elsewhere if elsewhere provide sample rss feed i make appropriate changes situation,i using pyrssgen i would like publish raw html specifically couple images item feed however looking source seems constructor rssitem accept image html autoescaped clever way i get round i found post code example seem work i attached pyrssgen anyone better solution maybe i write rss feed thanks,1 check imgseek imgseek collection free open source visual similarity projects the query image looking expressed either rough sketch painted user another image supply image collection the searching algorithm makes use multiresolution wavelet decomposition query database images,i trying calculate similarity read levenshtein distance two images using python pil i plan us e pythonlevenshtein library fast comparison main question what good strategy comparing images my idea something like convert rgb transparent white maybe convert monochrome scale smaller one larger one size convert channel channel converted monochrome sequence item value color value pixel calculate levenshtein distance two sequences of course handle cases like mirrored images cropped images etc but basic comparison useful is better strategy documented somewhere edit aaron h right speed issue calculating levelshtein takes forever images bigger hundred hundred pixels however difference results downscaling x x less example might wise set maximum image size px edit thanks preludeandfugue question i looking by way levenshtein distance optimized seems giving really bad results perhaps lots redundant elements backgrounds got look algorithms eidt root mean square deviation peak signaltonoise ration seem another two options hard implement seemingly cpuexpensive however seems i going need kind context analysis recognizing shapes etc anyway thanks links also pointing direction towards numpyscipy,3 assuming state always fields url users cities good practice create class likewise city then end either mapstring state locations mapstring city cities state setstate locations state name field indexed setcity cities state name field you want get habit letting type system work much possible,i list us states along various properties within cities various properties needs created dynamically startup currently text file in python slightly broken syntax readability i would use dict matrix sounds terrible could represented something like locations alabama url wwwdomaincompagephp users cities city url wwwdomaincompagephp users city url wwwdomaincompagephp users i could use class course really necessary represent python small list dict would much useful i currently plans need extra functionality classes db there bit details course states maybe citiesregions per state relatively small in c i could achieve similar thing nested unorderedmap perhaps one thing i mix data types unordered map users would string instead int i unaware suitable built type i easily make using strings things however made come ask question creating header declaration i quickly realized looked really ugly hardly readable it going const created well fwiw else i create fly python even though i always follow i mostly looking best practice advice i represent data i getting grade otherwise publishing,3 use current stable version you find windows installer httppythonorgftppythonpythonmsi install python use python package index version lxml windows installer specifically python httppypipythonorgpackagesllxmllxmlwinpyexemddfbabbecefaebbc download run python installer download run lxml installer easy,i would like install python lxml windows there seems several versions available what best versionway install by best i mostly mean easiest points i compile anything,1 dictmapstrstrip asplit l create following dictionary probably want since dictionary repeated keys caption cinematography director sameer butt distributor editing image music robin ghosh name badmash gujjar producer released film date starring saimabrshaan actorshaanbr writer nasir adeeb if want remove br tags use dictmaplambda x xstripreplace br asplit l if need remove html tags complicated regular expression html parser needed,i list like name badmash gujjarn image n image n caption n director sameer buttn producer n writer nasir adeebn starring saimabrshaan actorshaanbr music robin ghoshn cinematography n editing n distributor n released film date i want remove repeated elements list i tried following code found luck listsetl also way remove html tag thanks,1 in recent pylint versions disablemsgcat unified disable options single disable option since pylint disableierfc may added top files want messages issued,i using south migration django project when i run pylint project i get bunch errors migration files how i exclude migration files pylint i windows system i use filename exclusions pylint options i tried resort adding pylint disablemsgcatwcrefi top migration files it seems kludgy seems last resort documented directive work i get error e unrecognized file option disablemsgcat any help thanks,1 you nose timed decorator i use testing functions timing example timed def test funcwithtimeouttimeout,i using python unittest i like write test ensures certain method completes certain time i usual calculation difference timestamp timestamp i started wondering commonly done tdd write tests fail method function efficient refactor make efficient python unittest slick way,1 you really set value saving model better override save method ot use presave signal,is way django custom property setter like class mymodelmodelsmodel myfield modelscharfieldlength myfieldsetter def setpasswordself value selfpassword encryptvalue,1 don install source install debian package instead aptitude install pythoncrypto and install python dev files need anyway follow advice aptitude install pythondev,i tried install pycrypto module downloading source code executing following command python setuppy install error came running install running build running buildpy running buildext warning gmp library found not building cryptopublickeyfastmath building cryptohashmd extension gcc pthread fnostrictaliasing fwrapv wall wstrictprototypes fpic stdc o fomitframepointer isrc iusrincludepython c srcmdc buildtemplinuxxsrcmdo srcmdc error pythonh no file directory srcmdc error expected asm attribute token in file included srcmdc srchashtemplatec error expected specifierqualifierlist pyobjecthead srchashtemplatec error expected asm attribute pytypeobject srchashtemplatec in function newalgobject srchashtemplatec warning implicit declaration function pyobjectnew srchashtemplatec error expected expression algobject srchashtemplatec warning assignment makes pointer integer without cast srchashtemplatec at top level srchashtemplatec error expected token srchashtemplatec error expected asm attribute token srchashtemplatec error expected asm attribute token srchashtemplatec error expected asm attribute token srchashtemplatec error expected asm attribute token srchashtemplatec error expected asm attribute algmethods srchashtemplatec error expected asm attribute token srchashtemplatec error expected asm attribute algtype srchashtemplatec error expected asm attribute token srchashtemplatec error array type incomplete element type srchashtemplatec error pycfunction undeclared function srchashtemplatec error expected algnew srchashtemplatec in function initmd srchashtemplatec error pyobject undeclared first use function srchashtemplatec error each undeclared identifier reported srchashtemplatec error function appears srchashtemplatec error undeclared first use function srchashtemplatec error algtype undeclared first use function srchashtemplatec error pytypetype undeclared first use function srchashtemplatec warning implicit declaration function pyinitmodule srchashtemplatec error undeclared first use function srchashtemplatec warning implicit declaration function pyintfromlong srchashtemplatec warning implicit declaration function pydictsetitemstring srchashtemplatec warning implicit declaration function pymodulegetdict srchashtemplatec warning implicit declaration function pydecref srchashtemplatec warning implicit declaration function pyerroccurred srchashtemplatec warning implicit declaration function pyfatalerror error command gcc failed exit status which means find pythonh i searched online error seems installing python header file problem solved debian lenny came anther error aptget install pythondev error reading package lists done building dependency tree reading state information done e couldn find package pythondev,3 dictenumerate vuqtx if want starting count good reason use dictenumerate vuqtx start,i list vuqtx v u q t x i want get array associative like index anyone tell please thanks,3 i think enumerate want data list vuqtx id id enumeratedata v u q t x dictid id enumeratedata v u q t x,i list vuqtx v u q t x i want get array associative like index anyone tell please thanks,1 there true code style rule every framework library software redefine style rule project in personal code i prefer use general code style rule case official python one specify documentation,i write code python using django framework now i read coding style advices encountered vague thing in djangoproject section httpsdocsdjangoprojectcomendevinternalscontributingwritingcodecodingstylepythonstyle says function comments say like does returns however httpwwwpythonorgdevpepspeponelinedocstrings says say like do return so option true,1 pep follows first person singular django documentation standard follows third person singular the former one standard,i write code python using django framework now i read coding style advices encountered vague thing in djangoproject section httpsdocsdjangoprojectcomendevinternalscontributingwritingcodecodingstylepythonstyle says function comments say like does returns however httpwwwpythonorgdevpepspeponelinedocstrings says say like do return so option true,1 i changed following code libmagickreadimagewand monalisajpg f libmagickreadimage fargtypes cvoidp ccharp fwand monalisajpg so works well,i using imagemagick library python ctypes i wrote following simple code crashes segmentation fault kerninvalidaddress mac ctypes import ctypesutil import findlibrary lib cdllfindlibrary magickwand libmagickwandgenesis wand libnewmagickwand libmagickreadimagewand monalisajpg libdestroymagickwandwand libmagickwandterminus it works well linux windows craches mac os x lion i built imagemagick various ways official binary package homebrew traditional configure ampamp make crashed every trial program received signal excbadaccess could access memory reason kerninvalidaddress address xa xad magickreadimage not magickreadimage function ismagickwand function also crashes i guess newmagickwand returns wrong pointer ctypes mac handles pointers incorrectly i’m sure what’s wrong situation,1 i think pass instance nad requestpost time try something like requestmethod post tform tourformrequestpost requestfiles else tform tourforminstancetour,i form class tourformmodelform class meta model tour i wanna design edit pageso send tourid page get tour touridnow i wanna fill form tour instance i gottonsome thing like viewspy tourtourobjectsgetpktourid tform tourformrequestpost requestfilesinstancetour help update models class gallerymodelsmodel headimage modelsimagefielduploadtogallery class imagemodelsmodel image modelsimagefielduploadtogallery gallery modelsforeignkeygallery relatedname images class tourmodelsmodel namemodelscharfieldmaxlength countmodelssmallintegerfield priceunitmodelsforeignkeypriceunit pricemodelscharfieldmaxlength descriptionmodelstextfield actiondatemodelsdatetimefieldautonowtrueeditablefalse actionusermodelsforeignkeyusereditablefalse statustypemodelsforeignkeystatustype gallery modelsonetoonefieldgalleryeditablefalse fields foreigkey like priceunit statustypedoesn fill form thanks advance,1 take look platformwinver also see how check os vista python,anyone know determine windows edition eg bit bit windows windows xp homeprofessional windows vista businessultimateetc windows home basichome premiumprofessionalultimateetc i wonder could retrieve info registry python api thanks,1 bottle uses httpdocspythonorglibrarycookiehtml implement cookie support this implementation requires expires parameter string wdy ddmonyy hhmmss gmt format passing datetime date objects fails silently i fix future versions bottle hi i author i suggest using maxage instead edit oh i noticed also documented incorrectly sorry edit fixed master,i site im working want store value cookie number user comes website want know number last visit i thinking persistant cookie stores current value user comes site session cookie session cookie grabs copy persistant cookie this way session cookie always value last visit ever seems persistant cookie isnt persisted even though set expiry date year python code persistentcookiekey category highestid sessioncookiekey session persistentcookiekey highestid persistentcookievalue requestgetcookiepersistentcookiekey persistentcookievalue none persistentcookievalue time restart browser comes sessioncookievalue requestgetcookiesessioncookiekey print persistentcookievalue persistentcookievalue print sessioncookievalue sessioncookievalue sessioncookievalue none print session cookie set setting persistentcookievalue sessioncookievalue persistentcookievalue responsesetcookiesessioncookiekey strpersistentcookievalue print setting persistent cookie value highestid expiredate datetoday timedeltadays responsesetcookiepersistentcookiekey strhighestid expiresexpiredate highestidlastvisit intsessioncookievalue,3 the link provided jeff indeed works though assumes default group users added i simply replaced groupgroupobjectsgetpk groupcreatedgroupobjectsgetorcreatenameeveryone if want tighter integration amp features also djangoauthldap gives control ldap usersgroup mapped onto django usersgroups for debugging ldap connection i found blog post useful particular command testing ldap connection ldaputils ldapsearch h ldapsldapxcompanygrouplocal d cnsomething ldapourandom groupdccompanygroupdclocal w psswrd v if using ssl also issue getting hold certificate play nice either extract server follow instructions generate,i working djangobased application corporate environment would like use existing active directory system authentication users get yet another loginpassword combo i would also like continue use django user authorization permission system manage user capabilities does anyone good example,2 we look tuples ai bi b bn distribution invariant permutation indices would call unbiased ratios ai bi uniformly distributed cmin cmax sumai a sumbi b if cmin cmax ill conditioned ie close another n large following works generate ai uniformly sum ai a draw n samples aai n distribution eg uniform divide sum multiply a ai a aai sumaai desired properties generate bi sum bi b method if exists ai bi interval cmin cmax throw away ai bi try beginning it scale well n set ai bi satisfying constraints gets narrow n increases reject candidates to honest i see simple solution if n gets large cmin cmax use sledgehammer eg mcmc generate samples distribution unless trick see if really want use mcmc algorithms note change cmin cmin b a likewise cmax assume a b the problem draw uniformly product two unit nsimplices uun vvn ui vi cmin cmax so use mcmc algorithm metropolishastings seems suited product two unit nsimplices density fu un v vn prod indicatoruivi cmin cmax definitely doable albeit involved,i faced following programming problem i need generate n b tuples sum given a sum b given b tuple ratio b range cmin cmax a b within range i also trying make sure bias result introduced constraints b values moreorless uniformly distributed given range some clarifications metaconstraints a b cmin cmax given the ratio a b cmin cmax range this problem solution given constraints b noninteger i trying implement python ideas language english included much appreciated,1 i think django facebook good choice but opinion biased i written startup fashiolistacom run production quite huge edge cases resolved django facebook also include openfacebook python api client open graph protocol it python client i know fully date actively maintained have look httpsgithubcomtschellenbachdjangofacebook ps just released new decorators make simple get started these decorators indeed new caused bugs past days the project already year old since open graph api released otherwise quite stable httpwwwmellowmorningcom,i decide write applications using facebook django even twisted matter i choose appropriate tools i see many apiwrappers writed python exists facebook official seems longer supported pythonsdk new actively developed seems new djangofacebook good old maintained pyfacebook simple wellmaintaned nondocumented fandjango primitive tools i saw similar questions i noticed facebook periodically introduces big changes api advices may already outdated may new libraries appeared also i like know significant differences libraries and course good documentation tutorials welcome,3 i recently posted sort tutorial get started bottlejinja google app engine my emphasis organize project files you may able get something use httpcodeaspoetrywordpresscomhowtobuildawebappusingbottlewithjinjaingoogleappengine,i looking microframeworks python come across two interesting options flask bottle similar features one thing i noticed example sites show application code located inside single python file obviously even moderately sized sites would become difficult manage quite quickly do either frameworks support broken among different files would accomplished i familiar django like little structured would rather use something lightweight still powerful,1 if ctypes work due vs bits hack def getwindowsname import subprocess subprocesspopen systeminfo stdoutsubprocesspipecommunicate try stro latin python except pass return researchos names ogroupstrip printgetwindowsname or read registry try import winreg except import winreg winreg winregopenkeywinreghkeylocalmachine rsoftwaremicrosoftwindows ntcurrentversion key printwinregqueryvalueexkey editionid or use wincomclient import getobject wim getobject winmgmts printocaption wimexecqueryselect winoperatingsystem,i writing function prints detailed windows version informations output may tuple like bit xp professional sp english it supporting windows xp and i stuck getting windows edition eg professional home basic etc platformwinver sysgetwindowsversion winapigetversionex almost hits looks like tell enough information then i saw getproductinfo looks like implemented pywin any hints,1 there maybe better ways without adding significant amount code try usersettablevariables int int float float string string variable usersettablevariables execif productvariablentselffields variable label productvariablentselffields variable value productvariablenelsentdel selffields variable but saves trouble writing code makes wee bit easier add user settable variabls but i recommend approach code become less readable implement using getattr variable usersettablevariables getattrproduct variable selffieldsvariablelabel getattrproduct variable else,i django app allows user create variables name class productmodelsmodel name modelscharfieldmaxlength uniquetrue intname modelscharfieldmaxlength blanktrue nulltrue intdefault modelsintegerfieldblanktrue nulltrue intname modelscharfieldmaxlength blanktrue nulltrue intdefault modelsintegerfieldblanktrue nulltrue floatname modelscharfieldmaxlength blanktrue nulltrue floatdefault modelsfloatfieldblanktrue nulltrue floatname modelscharfieldmaxlength blanktrue nulltrue floatdefault modelsfloatfieldblanktrue nulltrue stringname modelscharfieldmaxlength blanktrue nulltrue stringdefault modelscharfieldmaxlength blanktrue nulltrue stringname modelscharfieldmaxlength blanktrue nulltrue stringdefault modelscharfieldmaxlength blanktrue nulltrue and stored class itemdatamodelsmodel created modelsdatetimefielddefaultdatetimenow item modelsforeignkeyitem editablefalse intval modelsintegerfieldblanktrue nulltrue intval modelsintegerfieldblanktrue nulltrue floatval modelsdecimalfieldblanktrue nulltrue maxdigits decimalplaces floatval modelsdecimalfieldblanktrue nulltrue maxdigits decimalplaces stringval modelscharfieldmaxlength blanktrue nulltrue stringval modelscharfieldmaxlength blanktrue nulltrue and moment i present user form created fill i following lable fields names user given variables class itemdataformmodelform only renames fields based whether product name field def initselfproductargskwargs superitemdataform selfinitargs kwargs delete fields automatically filled saving del selffields created values set product productintname selffields intval label productintname selffields intval value productintdefault else del selffields intval productintname selffields intval label productintname selffields intval value productintdefault else del selffields intval productfloatname selffields floatval label productfloatname selffields floatval value productfloatdefault else del selffields floatval productfloatname selffields floatval label productfloatname selffields floatval value productfloatdefault else del selffields floatval productstringname selffields stringval label productstringname selffields stringval value productstringdefault else del selffields stringval productstringname selffields stringval label productstringname selffields stringval value productstringdefault else del selffields stringval is way i could bit pythonicaly like list settingspy loop usersettablevariables int int float float string string the applies way i make sure data entered unique saving def isuniqueselflatestsi selfcleaneddata intval latestsiintval selfcleaneddata intval latestsiintval selfcleaneddata floatval latestsifloatval selfcleaneddata floatval latestsifloatval selfcleaneddata stringval latestsistringval selfcleaneddata stringval latestsistringval return false else return true i ask i want add model i want editing functions,1 you could implement recursive function def combisls ls yield return name limit ls start combisls c range limit yield start name c,i really find i tried use itertools tried kind looping still achieve i want here need i list list car plane bike this list time different different items time i need get something like car plane bike car plane bike car plane bike car plane bike car plane bike car plane bike i really lost it obvious probably something simple i unable solve,1 you could use itertoolsproduct mylist car plane bike itertoolsproductname stri rangelength name length mylist x print x prints car plane bike car plane bike car plane bike car plane bike car plane bike car plane bike,i really find i tried use itertools tried kind looping still achieve i want here need i list list car plane bike this list time different different items time i need get something like car plane bike car plane bike car plane bike car plane bike car plane bike car plane bike i really lost it obvious probably something simple i unable solve,3 try l car plane bike o n l oappendeach nappendeach o strin item n strin strin item print strin since list contain five items utmost plausible solution,i really find i tried use itertools tried kind looping still achieve i want here need i list list car plane bike this list time different different items time i need get something like car plane bike car plane bike car plane bike car plane bike car plane bike car plane bike i really lost it obvious probably something simple i unable solve,1 there parentheses around first line allowed you used keyword syntax third argument use first two either log easyguimultenterboxmsg fill blanks title log fieldnamesfieldnames log easyguimultenterbox fill blanks log fieldnames would work it looks like useful try typing commands interpreter open terminal search terminal spotlight type lines one one look error get terminal type python yourscriptpy see error messages each problems helpful error message describing problem get used reading debug scripts,this best attempt multienterbox easygui python would someone please give working example import easgui fieldnames year month day time hour time minute am pm log easyguimultenterboxmsg fill blanks title log fieldnames i running python os x,1 don use exec getattr perfectly adequate much safer readable class itemdataformmodelform def initselfproductargskwargs superitemdataform selfinitargs kwargs del selffields created fields int int float float string string field fields val getattrproduct field name fval field val val selffieldsfvallabel val selffieldsfvalvalue getattrproduct field default else del selffieldsfval,i django app allows user create variables name class productmodelsmodel name modelscharfieldmaxlength uniquetrue intname modelscharfieldmaxlength blanktrue nulltrue intdefault modelsintegerfieldblanktrue nulltrue intname modelscharfieldmaxlength blanktrue nulltrue intdefault modelsintegerfieldblanktrue nulltrue floatname modelscharfieldmaxlength blanktrue nulltrue floatdefault modelsfloatfieldblanktrue nulltrue floatname modelscharfieldmaxlength blanktrue nulltrue floatdefault modelsfloatfieldblanktrue nulltrue stringname modelscharfieldmaxlength blanktrue nulltrue stringdefault modelscharfieldmaxlength blanktrue nulltrue stringname modelscharfieldmaxlength blanktrue nulltrue stringdefault modelscharfieldmaxlength blanktrue nulltrue and stored class itemdatamodelsmodel created modelsdatetimefielddefaultdatetimenow item modelsforeignkeyitem editablefalse intval modelsintegerfieldblanktrue nulltrue intval modelsintegerfieldblanktrue nulltrue floatval modelsdecimalfieldblanktrue nulltrue maxdigits decimalplaces floatval modelsdecimalfieldblanktrue nulltrue maxdigits decimalplaces stringval modelscharfieldmaxlength blanktrue nulltrue stringval modelscharfieldmaxlength blanktrue nulltrue and moment i present user form created fill i following lable fields names user given variables class itemdataformmodelform only renames fields based whether product name field def initselfproductargskwargs superitemdataform selfinitargs kwargs delete fields automatically filled saving del selffields created values set product productintname selffields intval label productintname selffields intval value productintdefault else del selffields intval productintname selffields intval label productintname selffields intval value productintdefault else del selffields intval productfloatname selffields floatval label productfloatname selffields floatval value productfloatdefault else del selffields floatval productfloatname selffields floatval label productfloatname selffields floatval value productfloatdefault else del selffields floatval productstringname selffields stringval label productstringname selffields stringval value productstringdefault else del selffields stringval productstringname selffields stringval label productstringname selffields stringval value productstringdefault else del selffields stringval is way i could bit pythonicaly like list settingspy loop usersettablevariables int int float float string string the applies way i make sure data entered unique saving def isuniqueselflatestsi selfcleaneddata intval latestsiintval selfcleaneddata intval latestsiintval selfcleaneddata floatval latestsifloatval selfcleaneddata floatval latestsifloatval selfcleaneddata stringval latestsistringval selfcleaneddata stringval latestsistringval return false else return true i ask i want add model i want editing functions,3 this addition alex answer i reading comment alex answer found important get management form basically metaform information many forms formset template submitted data treated formset rather pile forms documentation the two ways i know get template send formset addition whatever data structure made render management form myformsetmanagementform render management form view send item template of course use alex first method formset already available add management form directly,i list soccer matches i like display forms the list comes remote source matches a vs b c vs d e vs f matchformset formsetfactorymatchformextralenmatches formset matchformset on template side i would like display formset according title ie a vs b form formsetforms fieldset legendtitlelegend formteam formteam fieldset endfor now i get title contain right title current form or asked different way i iterate matches index iteration formsetforms thanks input,1 i always prefer second way the problem first pass object want write paramenter smatrix caller function know must passed empty list what happens caller passes dict list empty by way want matrix calculations take look numpy library offers many things standard python,i want write function create empty square matrix size nxn i ways write smatrix createemptysquarematrixsmatrix n smatrix emptysquarematrixn ofcourse two functions different bit function createemptysquarematrix like procedure manipulate smatrix function emptysquarematrix create amp return matrix which way pythonic amp clearer do suggestions naming style i sure emptysquarematrix amp createemptysquarematrix,2 from tkdocs tutorial trees seems create tag desired colors selected row then catch virtual events treeview assign tag row gets focus unassign tag row loses focus here specific paragraph documentation i used the treeview generate virtual events treeviewselect treeviewopen treeviewclose allow monitor changes widget made user you use selection method determine current selection selection also changed program along code tutorial treetagconfigure ttk background yellow treetagbind ttk itemclicked item clicked found via treefocus note i sure work i dig code see i,the selected row ttk treeview shows dark blue background text white if i set color row tag example selftreeitemitem tags oddrow configure tag color example selftreetagconfigure oddrow background lightgrey select oddrow background color change remains lightgrey text changes black white how i get selected row background dark blue whether row tagged color rows tagged display black white selected white dark blue i tried ttkstyleconfigure treeview selectbackground blue anything edit i suppose i select item i could retag oddrow go back unselected rather inelegant,1 you need open file using wb mode bgfile operation under unix python differentiate text binary files windows to support platform independence use wb mode write image binary format i know internals mechanize guess retrieve method well see abstracted library for details see section python docs,i following code selfbgbr mechanizebrowser selfbgbrretrieveselfbgimageurl imagejpg selfbgfile openimagejpg modew selfbgimage selfbgbropenselfbgimageurlread selfbgfilewriteselfbgimage selfbgfileclose the problem imagejpg one downloaded via read method corrupted this displayed later qt reports jpg corrupted error i try open file windows application image garbled it opens fine garbled via retrieve method everything works fine however image i downloading generated anew every time visit link good what even puzzling methods work fine linux however windows like i said first method gives corrupt image help,1 as per top answer safe multiple writers shelve my approach making shelves safer write wrapper takes care opening accessing shelve elements the wrapper code looks something like def openself modereadonly mode readwrite lockfilemode lockmode lockex shelvemode c else lockfilemode r lockmode locksh shelvemode r selflockfd openshelvefilelck lockfilemode fcntlflockselflockfdfileno lockmode locknb selfshelve shelveopenshelvefile flagshelvemode protocolpicklehighestprotocol def closeself selfshelveclose fcntlflockselflockfdfileno lockun lockfdclose,does python shelve module protection built make sure two processes writing file time,1 input equivalent evalrawinputprompt so script currently tries interpret input example case execute statement script for user input might i simply say input unless know always use rawinput function so solve replace input rawinput filename rawinputfilename,i trying write script asks input file runs command i run script askes filename i give file eg examplebam i get error nameerror name examplebam defined i tried many things i fix can someone tell wrong this comand subprocess import call filename input filename open filename r command samtools tview chickenchickbuildunmaskedfa callcommand shelltrue this short version command much stuff i also thinking input files time perhaps information helpful clarify intentions,2 module abc class abc instance instance named like class definitively required in case i give variable name describing instance avoid naming clash example class car pass audi car mycar car mybrotherscar car,first i fully aware pep sometimes clear name things let assume abc abbreviation module named abc class inside module named abc abc sure instance variable named abc abcpy constant foo class abcobject pass testpy import abc print abcconstant abc abcabc oops i use abc lose ability access abcfoo if constant inside abc module may want access using abcconstant outside also instance name clear if clean way solve kind problem is solution different instead acronym simple word note abc class acts time singleton reason i able find another name instance,1 here code works python probably x versions python without raising attributeerror instance attribute getresponse class timeouthttpconnectionhttplibhttpconnection def connectself httplibhttpconnectionconnectself selfsocksettimeoutselftimeout class timeouthttphttplibhttp connectionclass timeouthttpconnection def settimeoutself timeout selfconntimeout timeout class timeouttransportxmlrpclibtransport def initself timeoutsocketglobaldefaulttimeout args kwargs xmlrpclibtransportinitself args kwargs selftimeout timeout def makeconnectionself host selfconnection host selfconnection return selfconnection chost selfextraheaders x selfgethostinfohost selfconnection host httplibhttpconnectionchost return selfconnection transport timeouttransporttimeouttimeout xmlrpclibserverproxyinitself uri transporttransport allownonetrue,i using xmlrpclibserverproxy make rpc calls remote server if network connection server takes default seconds return socketgaierror program this annoying development without network connection remote server is way update timeout serverproxy object i see clear way get access socket update,1 you may use inotify detect filesystem activity see manual quoting manual indelete filedirectory deleted watched directory indeleteself watched filedirectory deleted not sure get deleted another idea chattr testpy see command tries unsuccessfully delete gives error message,see update end i using ubuntu linux python i wrote python script converts qt ui files py using pyuic then want compile obtained py file pyc delete py file for reason delete converted py file pyc version also deleted try command pyuic homevicuiformpy homevicformui output subprocesscheckoutputcommand shell true stderr subprocessstdout except subprocesscalledprocesserror e print failed eoutput else print converted source targetname convert py pyc delete source source homevicuiformpy target source c py pyc pycompilecompilesource target shutilcopytarget target uncommented pyc file remains osremovesource commented py pyc files remain otherwise deleted i know happening see comments code additional info i thought would hint find who deletes file maybe pyuic i possibility monitor process deletes file update i debugging step step after executing osremovesource files py source pyc deleted could python behavior,1 perhaps want something like dictasplit stringsplit n intv going work values right side cannot converted int,hello i text following format but i want convert dict i using code convert dict but working dict nintv nv asplit stringsplit please anybody help thanks name kurradu image imagesize producer p kiran writer starring varun sandeshneha sharma music achu cinematography sarvesh murari editing distributor released november studio country ind,1 a hours ago needed list need dict text name kurradu image imagesize producer p kiran writer starring varun sandeshneha sharma music achu cinematography sarvesh murari editing distributor released november studio country ind dictmapstrstrip linesplit line textsplitlines cinematography sarvesh murari country ind distributor editing image imagesize music achu name kurradu producer p kiran released november starring varun sandeshneha sharma studio writer,hello i text following format but i want convert dict i using code convert dict but working dict nintv nv asplit stringsplit please anybody help thanks name kurradu image imagesize producer p kiran writer starring varun sandeshneha sharma music achu cinematography sarvesh murari editing distributor released november studio country ind,1 osremove returns none never get append list,i building simple function works delete files but in end i want return list files effectively deleted this function def deletefilesfiles empty list removedfiles list file files delete file osremovefile removedfilesappendfile return removedfiles i run function print deletefileshomexyzxyzzip this effectively deletes xyzzip returns empty list what i wrong,2 osremove return value statement becomes effectively none removedfilesappendfile on hand throw exception remove file following work try osremovefile except oserror pass else removedfilesappendfile,i building simple function works delete files but in end i want return list files effectively deleted this function def deletefilesfiles empty list removedfiles list file files delete file osremovefile removedfilesappendfile return removedfiles i run function print deletefileshomexyzxyzzip this effectively deletes xyzzip returns empty list what i wrong,2 the problem osremove return anything you however try except filename filenames try try remove file osremovefilename except oserror pass file removed maybe exist writeprotected may report error else executes osremove successful removedfilesappendfilename,i building simple function works delete files but in end i want return list files effectively deleted this function def deletefilesfiles empty list removedfiles list file files delete file osremovefile removedfilesappendfile return removedfiles i run function print deletefileshomexyzxyzzip this effectively deletes xyzzip returns empty list what i wrong,2 i think easy way achieve using regular expressions it possible compile python modules walk ast find variable definitions see documentation httpdocspythonorglibraryfunctionshtmlcompile httpdocspythonorglibraryasthtmlmoduleast edit my current program using idea sven usrbinenv python import ast import sys example assignment b class mynodevisitorastnodevisitor visit nodes ast idea sven def visitnameself node isinstancenodectx aststore print assigning name line nodeid nodelineno def visitfunctiondefself node pass def visitclassdefself node pass def printassignmentsname read python file print list variable assignments read file fopenname ru datafreadlines fclose create ast tastparsejoindata filenamename mode exec find assignments mynodevisitorvisitt walk nodes node astwalkt isinstancenode astname isinstancenodectx aststore nodecoloffset print assigning name line nodeid nodelineno print assignments files name sysargv print name printassignmentsname print lenname,i looked back forward possible solution issue i guess googlefu poor today not mention knowledge regular expressions close zero i trying retrieve definition constants ie modulelevel global variables series python files using text processing basically i read whole text python file i apply regex text find wherewhat constants as example i python file something like constantone standard constantright rotation right constantleft rotation left and i found regex works ok extract variable names recompile w rem however badly fails declarations like name name none const const const range is way i modify regex handle cases my apologies basic question i really expert regex thank advance andrea,2 that osremove return anything your condition evaluates false try def deletefilesfiles empty list removedfiles list file files delete file try osremovefile removedfilesappendfile except oserror continue return removedfiles this work,i building simple function works delete files but in end i want return list files effectively deleted this function def deletefilesfiles empty list removedfiles list file files delete file osremovefile removedfilesappendfile return removedfiles i run function print deletefileshomexyzxyzzip this effectively deletes xyzzip returns empty list what i wrong,1 don use regular expressions use python parser instead it much simpler class targetextractorastnodevisitor def visitnameself node isinstancenodectx aststore print nodeid def visitfunctiondefself node pass def visitclassdefself node pass targetextractorvisitastparsea b c prints b c instead string also pass whole contents file astparse,i looked back forward possible solution issue i guess googlefu poor today not mention knowledge regular expressions close zero i trying retrieve definition constants ie modulelevel global variables series python files using text processing basically i read whole text python file i apply regex text find wherewhat constants as example i python file something like constantone standard constantright rotation right constantleft rotation left and i found regex works ok extract variable names recompile w rem however badly fails declarations like name name none const const const range is way i modify regex handle cases my apologies basic question i really expert regex thank advance andrea,2 this might solution lookin htmlparser import htmlparser class myparserhtmlparser def initselflink keyword htmlparserinitself selfhtml selflink link selfkeyword keyword def handledataself data text datastrip selfhtmlappendtextreplaceselfkeyword href selflink selfkeyword def handlestarttagself tag attrs selfhtmlappendtag def handleendtagself tag selfhtmlappendtag def newhtmlself return joinselfhtmlstrip parser myparserblahkeyword parserfeeddivptext keyword herepdiv parserclose print parsernewhtml this give following output divptext hrefblahkeyworda herepdiv the problem lxml approach seems occur keywords single nesting it seems work fine multiple nestings so i added condition catch exception lxmlhtml import fragmentsfromstring fromstring tostring import compile def markupawaresubpattern repl text exp compilepattern root fromstringtext els el el rootgetiterator eltext els el el els eltextstrip lenels el els text expsubrepl eltext parent elgetparent newel fromstringtext neweltag eltag k v elattribitems newelattribk v return tostringnewel el els text expsubrepl eltext text eltext continue parent elgetparent newel fromstringtext neweltag eltag k v elattribitems newelattribk v parentreplaceel newel return tostringroot print markupawaresub keyword ablaha ptext keyword herep not elegant seems work please check,i string represents html document i trying replace text document excluding markup attribute values ofcourse replacement html i thought would simple incredibly tedious want replace text markup for example replace somekeyword href linksomekeyworda lxmlhtml import fragmentsfromstring fromstring tostring import compile def markupawaresubpattern repl text exp compilepattern root fromstringtext els el el rootgetiterator eltext els el el els eltextstrip el els text expsubrepl eltext text eltext continue parent elgetparent newel fromstringtext neweltag eltag k v elattribitems newelattribk v parentreplaceel newel return tostringroot markupawaresub keyword ablaha divptext keyword herepdiv it works keyword exactly two nestings there better way googling many hours i find anything,2 how reading file binary dump need deal cases preexisting file name zfilenamelist fname ospathjoinzipdir ospathbasenamename fout openfname wb foutwritezfilereadname,i zip file path when i unzip file using python put target folder creates files path inside target folder target dunzipfiles zip file path file name nistestfilestntpng what happens dunzipfilesnistestfilestntpng is way hae unzip tntpng file dunzipfiles or i read list move file delete empty folders import os sys zipfile zippath rdzipfilestestzip zipdir rdunzipfiles zfile zipfilezipfilezippath r name zfilenamelist zfileextractname zipdir zfileclose so worked import os sys zipfile zippath rdzipfilestestzip zipdir rdunzipfiles zfile zipfilezipfilezippath r name zfilenamelist fname ospathjoinzipdir ospathbasenamename fout openfname wb foutwritezfilereadname foutclose thanks help,1 if use nose write test cases functions methods testcase derived class nose fiddle order uses order functions defined file in order assert methods handy without needing subclass testcase i usually use testing module numpy example numpytesting import def testaaa assertequal def testzzz assertequal def testbbb assertequal running nosetest vv gives testittestaaa ok testittestzzz ok testittestbbb ok ran tests ok note contend unit tests ordered true unit tests isolated run independently functions classes usually independent they rather build another simplerlowlevel functions complexhighlevel functions when start optimising lowlevel functions mess part i frequently probably need unit test anyway lot better diagnosing cause tests simple functions come first tests functions depend functions later if tests sorted alphabetically real cause usually gets drowned among one hundred failed assertions function test bug lowlevel function relies that i want unit tests sorted way i specified use state built early tests later tests helpful tool diagnosing problems,how i sure unittest methods order is alphabetical numeric prefixes proper way class testfootestcase def testself def testself class testfootestcase def testaself def testbself,3 you set sysctl w vmblockdump see every file system action dmesg high volume disable afterwards,see update end i using ubuntu linux python i wrote python script converts qt ui files py using pyuic then want compile obtained py file pyc delete py file for reason delete converted py file pyc version also deleted try command pyuic homevicuiformpy homevicformui output subprocesscheckoutputcommand shell true stderr subprocessstdout except subprocesscalledprocesserror e print failed eoutput else print converted source targetname convert py pyc delete source source homevicuiformpy target source c py pyc pycompilecompilesource target shutilcopytarget target uncommented pyc file remains osremovesource commented py pyc files remain otherwise deleted i know happening see comments code additional info i thought would hint find who deletes file maybe pyuic i possibility monitor process deletes file update i debugging step step after executing osremovesource files py source pyc deleted could python behavior,3 python builtin range function aware symbolic evaluation try using sympy sum function instead sympy import sum var solve x var x f lambda n sumn n n n varn fx x x x note lambda expression might unnecessary depending actually want achieve n varn solvesumn n n n i i you still ignore complex results,for example i like solve here i tried sympy import var solve x var x f lambda n sum n n rangen fx output traceback recent call last file stdin line module file stdin line lambda typeerror range integer end argument expected got add,3 looks like indexpsp file either future import top file likely imo file including indexpsp processing bunch work future import hit causing error,i receiving error trying use python server pages modpython apache file usrlibpythondistpackagesmodpythonimporterpy line handlerdispatch defaultdefaulthandler argreq silenthlistsilent file usrlibpythondistpackagesmodpythonimporterpy line processtarget result executetargetconfig req object arg file usrlibpythondistpackagesmodpythonimporterpy line executetarget result objectarg file usrlibpythondistpackagesmodpythonpsppy line handler p pspreq file usrlibpythondistpackagesmodpythonpsppy line init selfloadfromfile file usrlibpythondistpackagesmodpythonpsppy line loadfromfile code compilesource filename exec file varwwwinventoryindexpsp line future import printfunction syntaxerror future imports must occur beginning file,1 i pretty sure better rewriting swig interface include new function swig uses internal registration system classesfunctions compatible boostpythons system least box,i two classes first called radish second called radishcont all code written c need used python radish exposed python using swig radishcont instead exposed using boostpython i need add method class radishcont syntax radish getradish return ampradish where radish radish instance contained radishcont when i execute python code i receive exception typeerror no python class registered c class radish so question i make method work python without rewriting radishcont using swig,1 the error seems library loaded libmysqlclientdylib referenced make sure install mysqldb library see how install mysqldb package importerror no module named setuptools andor httpwwwmangoorangecominstallingpythonmysqldbonmacosx you also syntax error code records cursorfatchone records cursorfetchone,example import mysqldb conn mysqldbconnectpasswdpasswd dbmydb cursor conncursor cursorexecuteselect from table records cursorfatchone print records provides next error traceback recent call last file applicationseclipsepluginsorgpythonpydevdebugpysrcpydevdpy line debuggerrunsetup file none none file applicationseclipsepluginsorgpythonpydevdebugpysrcpydevdpy line run pydevimportsexecfilefile globals locals execute script file usersuserdocumentsdevelopworkspacemyprojectsrcmainpy line import mysqldb file buildbdistmacosxinteleggmysqldb init py line file buildbdistmacosxinteleggmysqlpy line file buildbdistmacosxinteleggmysqlpy line bootstrap importerror dlopenusersuserpythoneggsmysqlpythonpymacosxinteleggtmpmysqlso library loaded libmysqlclientdylib referenced usersuserpythoneggsmysqlpythonpymacosxinteleggtmpmysqlso reason image found where error,1 blocked gibbs sampling pretty simple converges right distribution along lines alexandre proposing for initialize a n b b n select ≠j uniformly random with probability update j uniform random values satisfying constraints the rest time b b j repeat step many times seems necessary application i idea convergence rate,i faced following programming problem i need generate n b tuples sum given a sum b given b tuple ratio b range cmin cmax a b within range i also trying make sure bias result introduced constraints b values moreorless uniformly distributed given range some clarifications metaconstraints a b cmin cmax given the ratio a b cmin cmax range this problem solution given constraints b noninteger i trying implement python ideas language english included much appreciated,1 take look messagepack,i need define binary protocol use c python written application my question right tool job i need implement protocol parsing building code c python i heard google protocol buffers c implementation mature enough protocol is better substitute,1 assuming using boostpython let give idea proceed cases rather letting boostpython automatically wrap function provide wrapping namespace void foomethodusingdate foo pointer const objectamp dateobject boostgregoriandate date convertfrompython dateobject pointermethodusingdate date void wrapfoo class foo foo def bar amp foobar def foobar amp foofoobar def methodusingdate amp foomethodusingdate of course need provide method converts boostpythonobject boostgregoriandate object you decide handle for instance could assume parameter sequence three integers could allow complex way passing parameters define new class wraps gregorian date method exposes directly python as first question using boostpython stdstring automatically converted tofrom python strings,i questions relating arguments python c mix i function c i calling python function takes dates strings is python str c class stdbasicstringcharstruct stdchartraitscharclass stdallocatorchar and secondly function needs date type class boostgregoriandate anyone know i give date python read correct signature help much appreciated i hope fairly simple problem i experienced different types signatures bode well current experimentation linking python c,1 each dialog open next dialog since dialogs tend block main loop shown modally you could use pubsub send message closing event last dialog previous dialog close thing dialog forth each dialog emits message parent close here pubsub tutorial httpwwwblogpythonlibraryorgwxpythonandpubsubasimpletutorial,how would able open lets say dialog boxes last one open close dialog boxes,1 no in order call python functions c c use python c api in case c string mean first converting python string using pystringfromstringandsize cppstringdata cppstringsize passing resulting pyobject and want call arbitrary function use pyimportimport load module pyobjectgetattrstring get function python functions attributes like everything else use pyobjectcallobject call converted arguments put tuple via functions python c api,i questions relating arguments python c mix i function c i calling python function takes dates strings is python str c class stdbasicstringcharstruct stdchartraitscharclass stdallocatorchar and secondly function needs date type class boostgregoriandate anyone know i give date python read correct signature help much appreciated i hope fairly simple problem i experienced different types signatures bode well current experimentation linking python c,1 not elegant solution i determined i version virtualenvwrapper installed virtualenvwrappersh libraryframeworkspythonframeworkversionsbinvirtualenvwrappersh cd libraryframeworkspythonframeworkversionslibpythonsitepackages ls virtualenvwrapper virtualenvwrapperpynspkgpth virtualenvwrapperpyegginfo,i know virtualenvwrappersh locate virtualenvwrapper bash script but i determine version virtualenvwrapper installed,1 i prefer writing small one liners replace i instead making generic complex code eg this replaces underscores hyphens nonhidden file current directory import os osrenamef freplace f oslistdir fstartswith,is easy way rename group files already contained directory using python example i directory full doc files i want rename consistent way xdoc newxdoc ydoc newydoc,3 what wrong method instancesetpassword mypw you use property define setters httpdocspythonorglibraryfunctionshtmlproperty pasted docs class cobject def initself selfx none property def xself i x property return selfx xsetter def xself value selfx value xdeleter def xself del selfx,is way django custom property setter like class mymodelmodelsmodel myfield modelscharfieldlength myfieldsetter def setpasswordself value selfpassword encryptvalue,1 how displayed differ os application ect for true string formatting i would recommend checking docs for example print formatindexcolcol will want assuming col never larger characters if always adjust value liking,i trying nicely format text data database send emails django i encountering problems strings line breaks in particularmy desired output tcontinue tend tend scontinue send here strings taken database tntcontinuentend tntend snscontinuensend this desired output like see columns excel what i want say strings contain line breaks simple formatting print strindex col col work please share approach many thanks,2 you use table display tabular data email body before loop print table row print table header print table for data row format like print trtdtdtdtdtdtdtr formatindex col col finally loop print table row print table footer print table,i trying nicely format text data database send emails django i encountering problems strings line breaks in particularmy desired output tcontinue tend tend scontinue send here strings taken database tntcontinuentend tntend snscontinuensend this desired output like see columns excel what i want say strings contain line breaks simple formatting print strindex col col work please share approach many thanks,1 looking source code find basememcachedcache property def cacheself implements transparent threadsafe access memcached client getattrself client none none selfclient selflibclientselfservers return selfclient so i would say work ccachecas try let know details httpscodedjangoprojectcomsvndjangotrunkdjangocorecachebackendsmemcachedpy,over django groups tom evans explains method compare set django shown you access memcached client via django though djangocore import cache ccachegetcache default helpcclientcas but somehow i couldn’t get work djangocore import cache ccachegetcache memcache helpcclientcas traceback recent call last file console line module attributeerror memcachedcache object attribute client how i get compare set django method shown i use django version,2 if subprocess really capable multicore operation matter spawn you generally request cores os automatically give whatever resources available i suspect answer lies commercial program question rather parent process python subprocess package,i code calls commercial program run subprocess using subprocess module the commercial program capable running parallel i noticed processor used subprocess running is simple way run serial python program requests resources example processors subprocess,1 the python logging module defines classes loggers emit log messages handlers put messages destination formatters format log messages filters filter log messages a logger handlers you add invoking addhandler method a handler filters formatters you similarly add invoking addfilter setformatter methods respectively it works like import logging make logger mainlogger logginggetloggermy logger mainloggersetlevellogginginfo make handlers consolehandler loggingstreamhandler default sysstderr filehandler loggingfilehandlermylogfiletxt set logging levels consolehandlersetlevelloggingwarning filehandlersetlevellogginginfo add handlers logger mainloggeraddhandlerconsolehandler mainloggeraddhandlerfilehandler now use object like mainloggerinfologged file mainloggerwarninglogged file console if run python machine type code interactive console see output the log file get crated current directory permissions create files i hope helps,i looking simple way extend logging functionality defined standard python library i want ability choose whether logs also printed screen example normally log warning would call loggingbasicconfiglevelloggingdebug format asctimes levelnames messages filename loglog filemode w loggingwarningwarning this sets configurations log puts warning log i would like something along lines call like loggingwarningwarning true true statement signifys log also printed stdout i seen examples implementations overriding logger class i new language really follow going implement idea any help would greatly appreciated,2 the expression r evaluates numpy array boolean values use statement you automatically reinterpreted numbers though def qxy r x return r,i function def qxy r x r return else return i want call using something like pylab import dl x y mgriddl dl gxy obviously gives error comparison can done without make cycle x y because i want call qxy two doubles cycle must reimplemented case edit adding question long comment answer may help others answer it appears pylabmgrid numpymgrid adjusted numpy code import numpy def qxy r x r return else return dl x y numpymgriddl dl qxy gives error r valueerror the truth value array one element ambiguous use aany aall,2 one way would use plttextxy text,i find right function add footnote plot the footnote i want something like explanation one item legend long put legend box so i like add ref number eg legend item add footnote bottom plot xaxis which function i use thanks,2 as far i know distutils crossplatform utility permanently changing environment variables so write platform specific code in windows environment variables stored registry this sample code read set keys i use standard librarie need install pywin achieve import winreg winreg import ctypes envhttpproxy u http class registryobject def initself keylocation keypath selfregkey winregopenkeykeylocation keypath winregkeyallaccess def setkeyself name value try regtype winregqueryvalueexselfregkey name except windowserror if value exists yet guess use string regtype regtype winregregsz winregsetvalueexselfregkey name regtype value def deletekeyself name try winregdeletevalueselfregkey name except windowserror ignores key value exists pass class environmentvariablesregistry configures httpproxy environment variable used pip proxy def initself superenvironmentvariables selfinitwinreghkeylocalmachine r systemcurrentcontrolsetcontrolsession managerenvironment def onself selfsetkey httpproxy envhttpproxy selfrefresh def offself selfdeletekey httpproxy selfrefresh def refreshself hwndbroadcast xffff wmsettingchange xa smtoabortifhung x result ctypesclong sendmessagetimeoutw ctypeswindllusersendmessagetimeoutw sendmessagetimeoutwhwndbroadcast wmsettingchange u environment smtoabortifhung ctypesbyrefresult this sample code get started implements settings deleting keys make sure always calls refresh method changing registry this tell windows something changed refresh registry settings here link full application i wrote proxy switcher windows httpsbitbucketorgcanassaswitchproxy,is possible modify path environment variable globally permanently platformindependent way using python distutils background i application plugin serna xml editor i going make installer probably using python distutils setuppy after installation setuppy needs modify path environment variable add installation directory value a possible solution achieve i want would copy executables usrlocalbin somewhere else ms windows obvious copy execs any ideas,1 j from docs statement execute oneline statement context current stack frame the exclamation point omitted unless first word statement resembles debugger command,using pdbsettrace i trying debug series expression j used indexing variable statements j allowed since j reserved symbol pdb how i get around,3 every time call paintgui creating brand new window that calling tk creating new widgets running new mainloop these things need happen take paintgui function this minimally modified version code want tkinter import class a def initself selfvar true obj a def meth objvar false paintgui def paintgui objvar false witemconfigrect fillred master tk w canvasmaster width height wpack wcreaterectangle fillblue tagsrect btn buttonmaster textcerrar mesacommandmeth btnpacksidebottom mainloop,i searched quite extensively found answer i tracked reduced problem example tkinter import class a def initself selfvar true obj a def meth objvar false paintgui def paintgui master tk w canvasmaster width height wpack wcreaterectangle fillblue tagsrect btn buttonmaster textcerrar mesacommandmeth btnpacksidebottom objvar false witemconfigrect fillred mainloop paintgui as see rectangle conditional itemconfig the line paintgui inside meth show code working objvar false turning red my problem original window one underneath still blue i could kill original window leave new one necessary so i question how i solve i tried updateidletaskes none seem work though i may using incorrectly what problem i thouth tkinter suposed loop when i change value var loop repaint screen evaluate objvar false true,3 you want check sort command you sort create timestamp stored epoch time hmset users firstname john lastname smith created ok hmset users firstname jane lastname forbes created ok sadd users true sadd users true sort users get usersfirstname userscreated johnjane sort users get usersfirstname userscreated desc janejohn you get multiple keys want sort probable command options study doc about keys think carefully possible key reuse delete count insert would reuse key i get keys relational database project,i getting started redis hit first stumbling block going nosql previously known sql server i understand principle everything key value based work ordering example using hash set hmset users firstname james lastname smith created datetimedatatimenow now i assume add second record would get length hash set case shall say returned value x add another row hmset usersx firstname john lastname smith created datetimedatatimenow how would get latest record date say get record hashset possibly proposing use hashset sorted sets appropriate using python important,1 your example script seems okay say runs fine using python what version python using it possible errors seeing may related bug if upgrading python python might help,i trying understand example here code import queue import threading import urllib import time beautifulsoup import beautifulsoup hosts httpyahoocom httpgooglecom httpamazoncom httpibmcom httpapplecom queue queuequeue outqueue queuequeue class threadurlthreadingthread threaded url grab def initself queue outqueue threadingthreadinitself selfqueue queue selfoutqueue outqueue def runself true grabs host queue host selfqueueget grabs urls hosts grabs chunk webpage url urlliburlopenhost chunk urlread place chunk queue selfoutqueueputchunk signals queue job done selfqueuetaskdone class dataminethreadthreadingthread threaded url grab def initself outqueue threadingthreadinitself selfoutqueue outqueue def runself true grabs host queue chunk selfoutqueueget parse chunk soup beautifulsoupchunk print soupfindall title signals queue job done selfoutqueuetaskdone start timetime def main spawn pool threads pass queue instance range threadurlqueue outqueue tsetdaemontrue tstart populate queue data host hosts queueputhost range dt dataminethreadoutqueue dtsetdaemontrue dtstart wait queue everything processed queuejoin outqueuejoin main print elapsed time timetime start sometimes i get error exception thread thread likely raised interpreter shutdown explain please caused update another author here full exception i see similar code exception thread thread likely raised interpreter shutdown traceback recent call last file usrlocallibpythonthreadingpy line bootstrapinner file usrlocallibpythonthreadingpy line run file minepy line run file usrlocallibpythonqueuepy line get file usrlocallibpythonthreadingpy line wait type exceptionstypeerror nonetype object callable,1 class mainclassircircclient othermodule import b c othermodulea b c methods mainclass anothermodule import everything anothermodule mainclass name conflicts last import wins this works import simply imports symbols namespace much care kind namespace module class function copacetic import of course functions othermodule must written accept self first argument since become instance methods mainclass instances you could maybe decorate using classmethod staticmethod i tried this nice pattern mixins necessarily want use multiple inheritance headaches cause,i making irc bot twisted i run problem i want import functions seperate file main class one inherits ircircclient used methods i thought two possible solutions seem bit newbish problems solution put functions class separate file import main file make main class inherit class the problem solution i end inheriting quite classes i modify main class time i make new module bot solution put functions separate file import main file assign imported functions variable this annoying i would set variable main class methods i want class import somewhere else example importthispy class def somemethodself print blah mainpy import importthis class mainclassircircclient thisisnowamethod importthisa as see methods pun intended require lot stupid work maintain is smarter way,1 in python actually use statement import future future import withstatement,i wrote code python server how rewrite next code run python gziphandler gzipopengzipfile try opentxtfile w line gziphandler outwriteline except pass right try run script i get error warning become reserved keyword python traceback recent call last file mainpy line extractor import extractor file dataclientscriptsextractorpy line openselflogfile w syntaxerror invalid syntax thanks ron,3 you change resolution way pylabsavefig newpng dpi,in python ubuntu linux i using pylab make plots when i call pylabsavefigfilename it saves figure current screen resolution the looks terrible i lots subplots i usually manually maximize window i call savefig examples without maximizing window with window maximized is way automatically maximize pylab window i saw someone posted solution windows using wingui i linux thanks,1 you could put code function make statements negative use return continue break statements that would avoid much indentation also statement right loop looks like needed since list empty loop gets skipped ie volumeatags volumeatag volumeatags,the code working i looking tips could written little properly especially use as tell i programmer nature sys admin little fiddling python thanks advice provide def findallwileylinks pagebase httponlinelibrarywileycom journallist httponlinelibrarywileycombrowsepublicationstypejournalampampstartampresultsperpage inputlist getinputlist inputlist alljournallistsoup beautifulsoupgetwebpagejournallist alljournallistsoup alljournallisttags alljournallistsoupfind ol attrs id publications eissn inputlist journalatag alljournallisttagsfind attrs href recompileeissnrstrip journalatag journalsoup beautifulsoupgetwebpagepagebase journalatagget href issues journalsoup allvolumetags journalsoupfind ol attrs class issuevolumes volumeatags allvolumetagsfindall volumeatag volumeatags volumesoup beautifulsoupgetwebpagepagebase volumeatagget href volumesoup allissuetags volumesoupfind li attrs id volumeatagget id issueatags allissuetagsfindall issueatag issueatags currentlinksavailiableappendpagebase issueatagget href n else appendlog eissn eissnrstrip found alljournallist page try openinputdirectory selectedpublisher currentlinksavailiabletxt w f fwritelinescurrentlinksavailiable except ioerror e appendlog findalllinks operation failed probably creating new link text file error estrerror,1 one thing jumps lot code form tags parenttagfindall tag tags tag tags something tag you guaranteed tags list tags line redundant if use empty list loop body loop executed as small point beginning file inputlist removed immediately overwrite function call it clear part larger script rather including body script block terminate inputlist empty inputlist sysexit rather inputlist process inputlist you need add import sys top script work,the code working i looking tips could written little properly especially use as tell i programmer nature sys admin little fiddling python thanks advice provide def findallwileylinks pagebase httponlinelibrarywileycom journallist httponlinelibrarywileycombrowsepublicationstypejournalampampstartampresultsperpage inputlist getinputlist inputlist alljournallistsoup beautifulsoupgetwebpagejournallist alljournallistsoup alljournallisttags alljournallistsoupfind ol attrs id publications eissn inputlist journalatag alljournallisttagsfind attrs href recompileeissnrstrip journalatag journalsoup beautifulsoupgetwebpagepagebase journalatagget href issues journalsoup allvolumetags journalsoupfind ol attrs class issuevolumes volumeatags allvolumetagsfindall volumeatag volumeatags volumesoup beautifulsoupgetwebpagepagebase volumeatagget href volumesoup allissuetags volumesoupfind li attrs id volumeatagget id issueatags allissuetagsfindall issueatag issueatags currentlinksavailiableappendpagebase issueatagget href n else appendlog eissn eissnrstrip found alljournallist page try openinputdirectory selectedpublisher currentlinksavailiabletxt w f fwritelinescurrentlinksavailiable except ioerror e appendlog findalllinks operation failed probably creating new link text file error estrerror,2 afaik easy way turning pdf tables something useful data analysis you use data science toolkit file text utility r interface via rdstk package parse resulting text be warned parsing often nontrivial edit there useful discussion converting pdfs xml discerningcom the short answer probably need buy commercial tool,i using xml package successfully extracting html tables want extend pdf from previous questions appear simple r solution wondered recent developments failing way python i complete novice obtain manipulate pdfs i could finish job r xml package,2 extracting text pdfs hard nearly always requires lots care i start command line tools pdftotext see spit the problem pdfs store text order use awkward font encodings things like use ligature characters joined ff ij see proper typesetting throw pdftotext installable linux system,i using xml package successfully extracting html tables want extend pdf from previous questions appear simple r solution wondered recent developments failing way python i complete novice obtain manipulate pdfs i could finish job r xml package,3 here python code tests implements algorithm running onlogn i found wikipedia talk page longest increasing subsequence import unittest def longestincreasingsubsequencex find return longest increasing subsequence s if multiple increasing subsequences exist one ends smallest value preferred multiple occurrences value end sequence earliest occurrence preferred n lenx x none x pad sequence starts x m nonen allocate arrays m p p nonen l rangen l xm xi j st xmj xi j else binary search largest j st xmj xi lo largest value known j hi l smallest value known j lo hi mid lo hi xmmid xi lo mid else hi mid j lo pi mj j l xi xmj mj l maxlj backtrack find optimal sequence reverse order output pos ml l outputappendxpos pos ppos l outputreverse return output try small lists check correct subsequences generated class listestunittesttestcase def testlisself selfassertequallongestincreasingsubsequence selfassertequallongestincreasingsubsequencerange selfassertequallongestincreasingsubsequencerangerange selfassertequallongestincreasingsubsequence unittestmain,given input sequence best way find longest necessarily continuous nondecreasing subsequence sequence nondecreasing subsequence longest nondeceasing subsequence unique i looking best algorithm if code python would nice anything alright,1 from documentation the recommended configuration sentry involves setting separate web server handle error logging this means number sentry clients simply pass information primary sentry server you also configure one client server residing machine,little confused sentry works send errors various servers central server,1 your problem redirect responses request try lib help handle redirect urls httppypipythonorgpypirequests httpwwwsearchsourceforgenetmechanize,if i use urllib open url using import urllib import urllib url httpwwwbbccouk useragent mozilla compatible msie windows nt values headers useragent useragent data urlliburlencodevalues req urllibrequesturl data headers response urlliburlopenreq thepage responseread it works fine but i want mobile version i set useragent useragent mozilla iphone u cpu iphone os like mac os x enus applewebkit khtml like gecko version mobileg safari which iphone comes back go test page read headers however i run code user agent set urllib freaks seems follow indefinite redirection loop occur i visit site iphone urllib comes back whole heap debug info showing following lots finally urllibhttperror http error the http server returned redirect error would lead infinite loop the last x error message moved permanently any ideas would gratefully received,1 following kirk peeling last minute let polymorphic key take care choosing right kind decryptor foo magicalencryptor foociphertext fooencryptdata key fookey bar keydecryptor data bardecryptciphertext it create appropriate decryptor pass or whatever protocol key creation decryptors private i might even rearrange things like key createmagicalkey foo keyencryptor ciphertext fooencryptdata bar keydecryptor data bardecryptciphertext and course simple step key createmagicalkey ciphertext keyencryptdata data keydecryptciphertext,i need write set wrappers python around symmetric ciphers aesdes etc various modes operation allow crypto agility specifically code calling wrappers needs need knowledge actually protecting data changed dynamically basically following hold whether methods object separate functions something else foo magicalencryptor foociphertext fooencryptdata key fookey bar magicalencryptor barkey key data bardecryptciphertext the problem depending mode used resulting ciphertext different it may modecbcivciphertext cbc modegcmivciphertextmac gcm mode this clearly violates liskov substitution principle makes argument decrypt covariant if caller holding instance generic magicalencryptor interface happens gcm mode cannot hand instance ecb mode what good pythonic solution or answer simply care for i specifically need ought work i interested solutions either also key must short representation bitstream probably bits max this meant used hybrid encryption schemes example one might send rsaencpublickeysymetrickeyasmessageaessymetrickeyasmessageactualmessage,1 your cbfunccbfunc parameter gets garbagecollected right setcallback function that object persist long callback called callback functions last paragraph assign variable keep around here working example dll typedef unsigned int dword typedef long long typedef int bool define true define false typedef void stdcall callbackdworddword callback gcallback dword gport dword guser bool declspecdllexport setcallback long nport callback callback dword nuser gcallback callback gport nport guser nuser return true void declspecdllexport fire ifgcallback gcallbackgportguser failing script ctypes import def cbfuncportuser print portuser x cdll x callback winfunctypenonecuintcuint cbfunc callbackcbfunc xsetcallbackcallbackcbfunc xfire passing script ctypes import def cbfuncportuser print portuser x cdll x callback winfunctypenonecuintcuint cbfunc callbackcbfunc xsetcallbackcbfunc xfire edit also since callback function returning function used decorator python callback eliminating problem callback going scope ctypes import callback winfunctypenonecuintcuint callback def cbfuncportuser print portuser x cdll x xsetcallbackcbfunc xfire,i define callback function python one called dll bool setcallback long nport void stdcall pfilerefdone dword nport dword nuser dword nuser i tried code seems work python python crashes i assume i something wrong import ctypes ctypeswintypes ctypeswintypes import dword def cbfuncport userdata print hurrah cbfunc ctypeswinfunctypenone dword dword mydllsetcallbackctypesclong cbfunccbfunc dword where mistake note the platform running bit windows python the dll loads successfully also functions inside work fine called python a full sample code reproduces available httpsgithubcomssbarneapyhikvision run videopy py py,2 i asked robin dunn maker wxpython looks like work however call panel setcursor does work i told here example try import wx class myformwxframe def initself wxframeinitself none wxidany tutorial add selfpanel looks correct platforms selfpanel wxpanelself wxidany btn wxbuttonselfpanel labelchange cursor btnbindwxevtbutton selfchangecursor sizer wxboxsizerwxhorizontal sizeraddbtn selfpanelsetsizersizer def changecursorself event mycursor wxstockcursorwxcursorwait selfpanelsetcursormycursor run program name main app wxpysimpleapp frame myformshow appmainloop,i building python program searches things remote website sometimes operation takes many seconds i believe user notice status bar message search operation progress therefore i would like change mouse cursor highlight program still waiting result this method i using def onbuttonsearchclick self event if text search text launch searchoperation searchedvalue selfmsearchtextgetvalue searchedvalue return clean eventual previous results selfenablebuttonsfalse selfcleansearchresults operationssearchoperationselfmframe searchedvalue i tried two different approaches last line wxbeginbusycursor selfmframesetcursorwxstockcursorwxcursorwait none working i using kde gnulinux this work gnome any hints thank,1 the ducktyping solution far pythonic however rather testing argument see whether id edge treat common case first work try way if use explicit typechecking sometimes way use isintance rather type work subclasses a variable wellnamed poorlynamed orthogonal whether using strong typing if variables reference edge id others reference edge instance distinguishing way seems smart even using duck typing i use something like edge edgeid rather hungarian though,so another question pythonic the application domain case network algorithms nodes edges dijkstra kind thing something i previously coded strongly typed languages certain everything meanwhile python i got class net single instance class represents network i class edge instantiated edge network each edge instance among things unique id sometimes i wish remove edge reference relevant edge instance other times i wish remove edge using id to honest i starting lose track variables edges ids i think i preferred c job p so i propose two solutions start using systems hungarian notation name variables better i know whether actual edge objects id edge i want implement strong typing make removeedge method net explicitly reject anything edge make wrapper function removeedgeid looks relevant edge id calls removeedge function likewise rejects anything id use duck typing have removeedge check whether argument id edge right thing whadday reckon,2 just add awesomo answer also add line bashprofile profile,whenever i use syspathappend new directory added however i close python list revert previous default values how i permanently add directory pythonpath,3 i would say mix it good practice names objects tell might looking part i would name edges edge edge ids edgeid i would probably use duck typing idea removeedge def removeedgeedge isinstanceedge int edge getedgefromidedge delete edge,so another question pythonic the application domain case network algorithms nodes edges dijkstra kind thing something i previously coded strongly typed languages certain everything meanwhile python i got class net single instance class represents network i class edge instantiated edge network each edge instance among things unique id sometimes i wish remove edge reference relevant edge instance other times i wish remove edge using id to honest i starting lose track variables edges ids i think i preferred c job p so i propose two solutions start using systems hungarian notation name variables better i know whether actual edge objects id edge i want implement strong typing make removeedge method net explicitly reject anything edge make wrapper function removeedgeid looks relevant edge id calls removeedge function likewise rejects anything id use duck typing have removeedge check whether argument id edge right thing whadday reckon,1 if want use use finally gziphandler gzipopengzipfile opentxtfile w try line gziphandler outwriteline finally outclose gziphandlerclose the cleanup code finally clause always excecuted whether exception raised,i wrote code python server how rewrite next code run python gziphandler gzipopengzipfile try opentxtfile w line gziphandler outwriteline except pass right try run script i get error warning become reserved keyword python traceback recent call last file mainpy line extractor import extractor file dataclientscriptsextractorpy line openselflogfile w syntaxerror invalid syntax thanks ron,2 if know remove edge id simply something like class net def removeedgeself edge try selfremoveedgebyidedgeid except attributeerror oups edge edge id selfremoveedgebyidedge id,so another question pythonic the application domain case network algorithms nodes edges dijkstra kind thing something i previously coded strongly typed languages certain everything meanwhile python i got class net single instance class represents network i class edge instantiated edge network each edge instance among things unique id sometimes i wish remove edge reference relevant edge instance other times i wish remove edge using id to honest i starting lose track variables edges ids i think i preferred c job p so i propose two solutions start using systems hungarian notation name variables better i know whether actual edge objects id edge i want implement strong typing make removeedge method net explicitly reject anything edge make wrapper function removeedgeid looks relevant edge id calls removeedge function likewise rejects anything id use duck typing have removeedge check whether argument id edge right thing whadday reckon,1 there bug filed launchpad httpsbugslaunchpadnetscreenletsbug notice activate signal available appindicator submenus,here minimal example appindicator usrbinpython import gobject import gtk import appindicator name main ind appindicatorindicatorexamplesimpleclient gtkexecute appindicatorcategoryapplicationstatus indsetstatus appindicatorstatusactive menu gtkmenu menuitems gtkmenuitem quit menuappendmenuitems menuitemsconnectactivate gtkmainquit menuitemsshow indsetmenumenu gtkmain unfortunately documentation incomplete what i looking way check appindicator menu opend user eg indicator icon clicked so signal emitted menu opened,1 why call lenvals your code work simply removing,i want insert dictionary data mysql key field i tried following code but wrong can one help i really appreciate thanks much spam etcetcegg cols dkeys vals dvalues stmt insert into table valuess joincols joinlenvals,1 innodb constraints foreign keys ensure breaking database model migration see httpdevmysqlcomdocrefmaneninnodbforeignkeyconstraintshtml myisam native support constraints although seems implement choose httpdevmysqlcomtechresourcesarticlesmysqlenforcingforeignkeyshtml because myisam checking fk relationships get error innodb however check seems problem migration,py managepy migrate turkey running migrations turkey migrating forwards initial turkeyinitial error found real run migration aborting since database support running schemaaltering statements transactions leave interim state migrations you might able recover drop table turkeydemorecs cascade the south developers regret happened would like gently persuade consider slightly easiertodealwith dbms note the error caused migration fail for reason i get i try but setups myisam why work innodb,2 output defaultdictlist item cat x x x data outputcatappenditem without defaultdict output item cat x x x data outputsetdefaultcat appenditem example output data somedate boy anotherdate boy moredate girl output item cat x x x data outputsetdefaultcat appenditem print output boy somedate anotherdate girl moredate,i data following form saved list id price date category now i basically want seperate items based category basically dictionary key category rest stuff id price data values i already created datastructure lets datastructre item four stated attributes id price date category so basically want dictionary following form itemitem item since many values single key hence know use defaultdict still i able get around thanks,2 i got problem recently syt right pylintepylint got several methods however call subprocess python launched in case getting quite slow building mcarans answer finding flag exit i following class writableobjectobject dummy output stream pylint def initself selfcontent def writeself st dummy write selfcontentappendst def readself dummy read return selfcontent def runpylintfilename run pylint given file pylint import lint pylintreporterstext import textreporter args rn rcfilercpylint put pylintoutput writableobject lintrunfilenameargs reportertextreporterpylintoutput exitfalse l pylintoutputread ever want l times faster case with i going whole project using full output check source file point errors rank files note,i like invoke pylint checker limited error signalling part part unit testing i checked pylint executable script got pylintlintrun helper class i got lost quite long init function ending call sysexit anybody ever tried managed dreamplan would name main import pylintlint pylintlintsomethingfile justerrorstrue continue unit testing hints copy init method skip sysexit i mean i need tests run pylint might well pyflakes software feel free suggest alternatives thanks,3 one way would dictionary value list items id price date key category something along lines following dictionary c category itm tupleitem def insertd c itm c dc itm else dcappenditm,i data following form saved list id price date category now i basically want seperate items based category basically dictionary key category rest stuff id price data values i already created datastructure lets datastructre item four stated attributes id price date category so basically want dictionary following form itemitem item since many values single key hence know use defaultdict still i able get around thanks,1 i problem configuring pil installing mac os lion this post the problem installing pil using virtualenv buildout shows directives install using link fixed version regards at,i installed pil easyinstall reason i run file uses i get importerror no module named pil does anyone know could i think also worth mentioning i installed webpy easyinstall working fine,1 i think want something like assuming current data stored list listdata dictdata defaultdictlist item listdata dictdataitemcategoryappenditem if item tuple instead object use item instead itemcategory,i data following form saved list id price date category now i basically want seperate items based category basically dictionary key category rest stuff id price data values i already created datastructure lets datastructre item four stated attributes id price date category so basically want dictionary following form itemitem item since many values single key hence know use defaultdict still i able get around thanks,2 sadly csv cannot handle unicode least python but work around issue wrapping dictreader generator open hrplanreviewcsv rb infile dr csvdictreaderinfile delimiter def unicodeddata row dr assuming infile encoding utf yield dictkey unicodevalue encoding utf key value rowiteritems todb iunknown county businessname address city zip phone email approvalstatus date date typeofconstruct typeofbiz unknown unknown unknown unknown unknown bizname address city zip country phone email phone unicodeddata,import csv sqlite conn sqliteconnectmycustomerssql curs conncursor try cursexecutecreate table unknown text county text businessname text address text city text zip integer phone integeremail text approvalstatus text date text date text typeofconstruct text typeofbiz text unknown text unknown text unknown text unknown text unknown textbizname textaddress text city textzip textcountry textphone textemail textphone text except sqliteoperationalerror print table already exist open hrplanreviewcsv rb infile dr csvdictreaderinfile delimiter todb iunknown county businessname address city zip phone email approvalstatus date date typeofconstruct typeofbiz unknown unknown unknown unknown unknown bizname address city zip country phone email phone dr cursexecutemanyinsert into unknown county businessname address cityzip phone email approvalstatus date datetypeofconstruct typeofbiz unknown unknown unknownunknown unknownbiznameaddress cityzipcountryphoneemailphone values todb todb returns list encoded utf sqllite database seem requesting formating unicode how convert todb list unicode running sql statement below error message get run code sqliteprogrammingerror you must use bit bytestrings unless use te xtfactory interpret bit bytestrings like textfactory str it highly recommended instead switch application unicode str ings edited based input answers the revised codebelow executes successfully insert values taken csv database import csv sqlite conn sqliteconnectmycustomerssql curs conncursor try cursexecute create table unknown text county text businessname text address text city text zip integer n phone integeremail text approvalstatus text date text date text typeofconstruct text typeofbiz text unknown text n unknown text unknown text unknown text unknown textbizname textaddress text city textzip textcountry textn phone textemail textphone text except sqliteoperationalerror print table already exist infile open hrplanreviewcsv rb dr csvdictreaderinfile delimiter keysunknown county businessname address city zip phone email approvalstatus date date typeofconstruct typeofbiz unknown unknown unknown unknown unknown bizname address city zip country phone email phone argstuplekeydecode utf key keys row dr sql insert into f values p format f joinkeys p join lenkeys cursexecutemanysql args,1 i thank answers i ended solving problem another way using google maps static api formulas convert coordinate space pixel space i get precise images stich nicely together for anyone interested code if helps someone please comment import image urllib stringio math import log exp tan atan pi ceil earthradius equatorcircumference pi earthradius initialresolution equatorcircumference originshift equatorcircumference def latlontopixelslat lon zoom mx lon originshift logtan lat pipi originshift res initialresolution zoom px mx originshift res py originshift res return px py def pixelstolatlonpx py zoom res initialresolution zoom mx px res originshift py res originshift lat originshift lat pi atanexplatpi pi lon mx originshift return lat lon neighbourhood lajeado brazil upperleft lowerright zoom careful get many images ullat ullon mapfloat upperleftsplit lrlat lrlon mapfloat lowerrightsplit set important parameters scale maxsize convert coordinates pixels ulx uly latlontopixelsullat ullon zoom lrx lry latlontopixelslrlat lrlon zoom calculate total pixel dimensions final image dx dy lrx ulx uly lry calculate rows columns cols rows intceildxmaxsize intceildymaxsize calculate pixel dimensions small image bottom largura intceildxcols altura intceildyrows alturaplus altura bottom final imagenewrgb intdx intdy x rangecols rangerows dxn largura x dyn altura latn lonn pixelstolatlonulx dxn uly dyn bottom zoom position joinstrlatn strlonn print x position urlparams urlliburlencode center position zoom strzoom size dxd largura alturaplus maptype satellite sensor false scale scale url httpmapsgooglecommapsapistaticmap urlparams furlliburlopenurl imimageopenstringiostringiofread finalpasteim intxlargura intyaltura finalshow,i noticed google maps page get embed link put inside iframe load map browser news the image size adjusted large i interested getting som big images single pngs more specifically i would like define rectangular area bounding box upperright lowerleft coordinates get corresponding image appropriate zoom factor but question how i use python get pixel content map image object my rationale browser get render image content python capable edit content html file shows sample map iframe width height frameborder scrollingyes marginheight marginwidth srchttpmapsgooglecombrmapshlptbrampampllampampspnampampzampampoutputembed edit i suggested ned batchelder read content urlliburlopen call using src address taken iframe the result lot javascript code i think google maps javascript api so question lingers could i useful stuff stuff python order get map image edit link appears contain pretty relevant info google maps tiles maps httpwwwcodeprojectcomkbscrapbookgooglemapaspx also httpeconymorgukgmaphowitworkshtm,3 you need create mask import numpy np arr npmaarraynpnan printnpmamaxarr nan since mask marr npmamaskedarraynpnan npisnanarr printnpmamaxmarr since mask tells mask ignore nan the max rest,i understand behavior numpymamax min mean etc import numpy np arr npmaarraynpnan npmamaxarr nan i thought supposed return value excluding nan the way i get real value npnanmaxnpasarrayarr is right i using numpymamax incorrectly,1 i think following want c conncursor cexecute select from pacientes row cfetchall nome row nome id row id cexecute select file from exames where idpaciente id exam c print exam file,i small database legacy almost defunct project this database patients table individual personal data unique id field exams table fields exam one fields patientid what i want given patient row pacientes table exams rows exames table whose patientid matches given patient i beginner sql question naive i apologize my working code following i using loop i would much rather sql query point using databases i think usrbinenv python coding utf import os sqlite conn sqliteconnect bddatadb connrowfactory sqliterow c conncursor cexecute select from exames exams cfetchall cexecute select from pacientes row c nome row nome id row id exam exams i would like replace loop exam idpaciente id sql query meaning print exam file an answer similar question seems i want i idea python sqlite module much less expression essential incidental syntax structure selecting rows table one field table select iprofimage from profileimages where catid select maxcatid imagescat,1 i believe issue accessing tuple within list need specify location list location tuple row cursorfetchall f row print row print row print row outputs,i grabbed bunch sql ids i need update python pyodbc import pyodbc cnxn pyodbcconnect dsnyesonepwdxxx cursor cnxncursor cursorexecuteselect id from onedbotwo where status ongoing and id i second bit code updates ids cursorexecuteupdate onedbotwo set status completed modified today where id the problem i view ids grabbed python earlier i get either row cursorfetchall f row print row row print row i need number i run second part script where id part i tried count lenrow count newrow rowcount print select id from onedbotwo where id strnewrow count count gave select id from onedbotwo where id select id from onedbotwo where id etc and i tried strrowlstrip i got how i strip characters id i reuse id thanks adrian,1 there couple different ways i think simplest use enhancedstatusbar widget httpwikiwxpythonorgenhancedstatusbar however thread also mentions way normal statusbar httpwxpythonusersnnabblecomaddaprogressbarinastatusbartdhtml as making frame size fixed try setting setsizehints size want,i using wxpython search files particular directory as searches files progress number files sent progress bar give little background what i want move progress bar bottom frame setstatustext usually show name but search commenced i would like nametext replaced progress bar currently i try change position progress bar visible right progress bar secondly i want lock gui current size window resized i looked examples every one started default size i want gui remain size i give way buttons displayed warrants here gui code looks like class myappwxapp def oninitself frame mainwindowst v frameshow selfsettopwindowframe return true class mainwindowwxframe def initself pos size title wxframeinitself none pos size title panel wxpanelself wxidany panelsetbackgroundcolour light grey toolbar selfcreatetoolbar toolbarrealize menufile wxmenu menufileappend ampabout menufileappendseparator menufileappend eampxit menubar wxmenubar menubarappendmenufile ampfile menu wxmenu menuappendwxnewid ampcopy copy status bar menuappendseparator menuappendwxnewid camput menuappendseparator menuappendwxnewid paste menuappendseparator menuappendwxnewid ampoptions display options menubarappendmenu ampedit selfsetmenubarmenubar selfcreatestatusbar selfsetstatustextwelcome sqastcan put connected logged selfbindwxevtmenu selfonabout id selfbindwxevtmenu selfonquit id x progress gauge selfgauge wxgaugepanel x pos size close button selfbutton wxbuttonpanel labelexit pos size selfbindwxevtbutton selfonquit selfbutton selfbindwxevtclose selfonclosewindow dispenser button selfbutton wxbuttonpanel labelserv pos size selfbindwxevtbutton selfonstartbutton selfbutton site server selfbutton wxbuttonpanel labelserv pos size selfbindwxevtbutton selfonsiteservbutton selfbutton local search selfbutton wxbuttonpanel labelabort pos size selfbindwxevtbutton selfonabortbutton selfbutton selfbuttondisable selfshouldabort false this worked count count afile filelist head filename ospathsplitafile afileendswithlog afileendswithtxt count selfprogressbarshow wxcallafterselfprogressbarsetvalue count this works fftpopenafile r line enumeratefreadlines result regexsearchline selfshouldabort return selfshouldabort break,2 very interesting question here approach create signaltestpy import os import signal pid osgetpid def donothingargs pass def foo print initializing oskillpid signalsigusr print variable value print all done signalsignalsignalsigusr donothing foo then run gdb gdb args python signaltestpy gnu gdb gdb red hat enterprise linux el copyright c free software foundation inc license gplv gnu gpl version later httpgnuorglicensesgplhtml this free software free change redistribute there no warranty extent permitted law type show copying show warranty details this gdb configured xredhatlinuxgnu for bug reporting instructions please see httpwwwgnuorgsoftwaregdbbugs reading symbols netgsvolsoftwaremodulesswpythonlinuxrhelxbinpythondone and run go reach call kill gdb run starting program netgsvolsoftwaremodulesswpythonlinuxrhelxbinpython signaltestpy warning loadable sections found added symbolfile systemsupplied dso xaaaaaaab thread debugging using libthreaddb enabled initializing program received signal sigusr user defined signal xdf kill liblibcso you look backtrace gdb backtrace xdf kill liblibcso xddd posixkill selfvalue optimized argsvalue optimized modulesposixmodulec xb callfunction fxaca throwflagvalue optimized pythoncevalc pyevalevalframeex fxaca throwflagvalue optimized pythoncevalc xccd callfunction fxac throwflagvalue optimized pythoncevalc pyevalevalframeex fxac throwflagvalue optimized pythoncevalc xdbb pyevalevalcodeex coxaaaaef globalsvalue optimized localsvalue optimized argsx argcount kwsx kwcount defsx defcount closurex pythoncevalc xd pyevalevalcode coxa globalsxa localsx pythoncevalc xbf runmod fpxad filenamexfffffffbb signaltestpy startvalue optimized globalsxe localsxe closeit flagsxfffffffaee pythonpythonrunc pyrunfileexflags fpxad filenamexfffffffbb signaltestpy startvalue optimized globalsxe localsxe closeit flagsxfffffffaee pythonpythonrunc xbfd pyrunsimplefileexflags fpvalue optimized filenamexfffffffbb signaltestpy closeit flagsxfffffffaee pythonpythonrunc xcc pymain argcvalue optimized argvvalue optimized modulesmainc xdd libcstartmain liblibcso xb start if continue rest program run normally gdb continue continuing variable value all done program exited normally you instead step appropriate frame reach statement interested you probably going want run debugging python make much sense,let say following megasimple python script print initializing print variable value print all done say i like debug script placing breakpoint line stepping script now i like use gdb i like debug python bindings may come part shared object library hence i ideally place breakpoint python code line step c part shared object note debuggingwithgdb pythoninfo wiki really explicitly state possible the problem gdb cannot really recognize breakpoints placed python script line gdb python gnu gdb gdb cvs reading symbols usrbinpythonno debugging symbols founddone gdb b testpy no symbol table loaded use file command make breakpoint pending future shared library load n breakpoint testpy pending gdb run testpy starting program usrbinpython testpy entire python script run within gdb breakpoint simply never reached so i want possible gdb alternatives would i something similar,3 your might want check text mining package tm i recall implemented called readers also one pdfs,i using xml package successfully extracting html tables want extend pdf from previous questions appear simple r solution wondered recent developments failing way python i complete novice obtain manipulate pdfs i could finish job r xml package,3 no difference i interested know documentation got impression the difference whether validation performed initial data trigger validation this allows example prefill certain fields leave others empty even though required if used bound data would get errors empty required fields even first viewing form would annoying user bound data course triggers validation also using modelform related instance updated bound data initial data,given example like class myformformsform name formscharfield i trying grasp difference following two snippets bound data style myform myform name requestuserfirstname initial data style myform myforminitial name requestuserfirstname the documentation seems suggest initial dynamic initial values yet able pass bound data constructor accomplishes exactly thing i used initial data past dynamic values i tempted use straightforward bound data style would like insights real difference two styles,3 here key part django docs bound unbound forms a form instance either bound set data unbound if it’s bound set data it’s capable validating data rendering form html data displayed html if it’s unbound cannot validation there’s data validate still render blank form html you really see difference example form gave form valid bound data style let extend form adding age field difference obvious class myformformsform name formscharfield age formsintegerfield bound form myform myform name requestuserfirstname this form invalid age specified when render form template see validation errors age field unbound form dynamic initial data myform myforminitial name requestuserfirstname this form unbound validation triggered errors displayed render template,given example like class myformformsform name formscharfield i trying grasp difference following two snippets bound data style myform myform name requestuserfirstname initial data style myform myforminitial name requestuserfirstname the documentation seems suggest initial dynamic initial values yet able pass bound data constructor accomplishes exactly thing i used initial data past dynamic values i tempted use straightforward bound data style would like insights real difference two styles,3 i could install modules eggs i used package manager install version pythondev sudo aptget install pythondev after i able run setuppy file included downloaded unpacked module without gcc errors i assume pythondev development package,i wrote function python then i wanted make module install ubuntu here i created setuppy along functionpy file built distribution file using python setuppy sdist then installed python setuppy install all going fine but later i wanted use module importing code i got import error importerror no module named ps i searched google find particular answer detailed answer much appreciated,1 there something else wrong proposed solution first replacement made resulting string could match characters could replaced for example solution would give desired result tried swap qq ff setting pairs qq ff ff qq you could try instead dictpairs import pattern recompile joinreescapek k patternsublambda kdkgroup frsfsdbbsdfvsdfvrtdsff,i many string pairs one large string content file i need replace every occurrence first member pair respective second one for instance pairs aa bb qq rt i need replace every occurrence aa bb qq rt the strings pairs unique order replacements matter final result my python code naive i apply stringreplace method succession pairs exhausted sfrsfsdaasdfvsdfvqqdsff pairs aa bb qq rt p pairs ssreplacep p frsfsdbbsdfvsdfvrtdsff i believe bad solution large strings can anyone suggest efficient one the question python thanks,2 if want add two classes i look add function allows normal addition call add b as question i exactly sure asking i wrote vector class like class vector def initself x z selfx x selfy selfz z def addself return vectorselfx otherx selfy othery selfz otherz,i guess would easy explain question examply suppose i want write vector class and class let say want define method add vectors something like class vector def addselfother code basically vector vec vecaddothervec addition like inherting classdatatype thanks,2 in python use duck typing ie worry type class vectorobject def initself x selfx x selfy def addself othervec return vectorselfx othervecx selfy othervecy if want make add modify vector object instead returning new one however makes class mutable therefore harder deal def addmutableself othervec selfx othervecx selfy othervecy,i guess would easy explain question examply suppose i want write vector class and class let say want define method add vectors something like class vector def addselfother code basically vector vec vecaddothervec addition like inherting classdatatype thanks,1 sure exactly said suppose wanting add change functionality list class vectorlist def addself v listextendself v use like v vector vadd print v,i guess would easy explain question examply suppose i want write vector class and class let say want define method add vectors something like class vector def addselfother code basically vector vec vecaddothervec addition like inherting classdatatype thanks,1 you posted far little context give decent answer i try anyway the filename trying create seems contain nonascii characters cannot automatically converted standard str python x if replace str unicode avoid need conversion alltogether if part code requires use str could try encode like newfilename unicodefilekeyencode ascii ignore note unconvertable characters omitted example,strfilekey filename newfilename strfilekey but i run code get unicodeencodeerror ascii codec encode characters position xy ordinal range i need parsing file name download server how i get filename,1 the keyword exec executes python code it start new processes try subprocess module instead lines subprocesscheckoutputlspcisplit n count sum vga line line lines,i trying run loop goes line output command for ex line exec lspci grep vga count count to try get amount video cards installed system but seem line syntax loop line do i import library exec or i using wrong or thanks,3 exec executes python code external command you looking subprocesspopen import subprocess p subprocesspopen lspci stdoutsubprocesspipe line pstdout vga line print linestrip pwait on box prints vga compatible controller nvidia corporation gf geforce gtx rev,i trying run loop goes line output command for ex line exec lspci grep vga count count to try get amount video cards installed system but seem line syntax loop line do i import library exec or i using wrong or thanks,3 you guaranteed ordering inner objects every time parse indexing safe bet reference index object name attribute set something instead nesting statements get away using list comprehension observe iterate response key get list lists dictionary inside data responseuidnamelacidnamesomethingcidnamesomethingelse lst lst dataget response name la uid name something cid name somethingelse cid if index first item list lst end list objects lst lst dataget response name la uid name something cid name somethingelse cid if add condition list comprehension match name attribute objects get list single item containing desired object lst lst dataget response lstget name something name something cid and indexing first item final list get desired object lst lst dataget response lstget name something name something cid so turn function move life def getobjbynamedata name objects lst lst dataget response lstget name name objects return objects return none print getobjbynamedata something name something cid print getobjbynamedata something name something and resilient return none response key found print getobjbynameerrorsomeerror something none,i following json string response name la uid cid name something cid name somethingelse one following errorsomeerror response name la uid cid name cid name somethingelse response name la uid so i sure childs elements will enough following verifications get something value jsonstrget response jsonstr jsonstrget response jsonstr name jsonstrget name jsonstr i need empty value save database can simplified,1 pysqlite provides special native hook print implement repr str i say bit missed chance least explains behavior observing see pysqlite source httpcodegooglecomppysqlitesourcebrowsesrcrowc and python docs httpdocspythonorgcapitypeobjhtmltpprint,i testing code interpreter i noticed unexpected behavior sqliterow class my understanding print obj always get result print strobj typing obj interpreter get result print reprobj however case sqliterow print row row object prints like tuple u string print strrow match output sqliterow object xaa row usually would repr object u string print reprrow reprrow something different well sqliterow object xaa i think sqliterow must subclass tuple i still understand exactly going behind scenes could cause behavior can anyone explain this tested python sure behavior python versions not sure whether matters rowfactory attribute connection set sqliterow,3 turned began work django console later i noticed i old code formspy class hardwaretypeformsmodelform class meta model hardwaretype thus work bad day naming classes etc,fragment modelspy class hardwaretypemodelsmodel type modelscharfieldblank false maxlength verbosenametype description modelstextfieldblank true verbosenamedescription slug modelsslugfieldunique true maxlength verbosename slug class softwaretypemodelsmodel type modelscharfieldblank false maxlength verbosenametype description modelstextfieldblank true verbosenamedescription slug modelsslugfieldunique true maxlength verbosename slug sw softwaretypeobjectsgetslug unix sw softwaretype unix hw hardwaretypeobjectsgetslug printer traceback recent call last file console line module attributeerror type object hardwaretype attribute objects i see happens anyone help edit sorry sent code problem solved another class i hardwaretype modelsmanytomanyfieldhardwaretype verbosenamehardware type change hardwaretype hwtype works fine i know cause problem,1 when i seen problem past usually someone set breakpoint line actually connected python statement run for example blank lines comment lines wrong part multiline statement,i quite new debugging directly pdb i issues debugging django application here i python pdb managepy runserver pdb b coreviewspy breakpoint usersraphaelcruzeirodocumentsprojectspdbtestcoreviewspy pdb c however execution passes directly breakpoint am i missing command the manual elaborate setting breakpoint anymore,1 given remarks comments i guess something like following looking import numpy np import matplotlibpyplot plt def plotexponentialdensitymu xmax fmt label x nparange xmax mu npexpxmu pltplotx fmt labellabel def sampleandplotn color first sample n valus samples npzeros n rangen samplesi nprandomexponential determine mean mu npmeansamples printn mu f n mu plot histogram samples n bins nphistogramsamples binsintnpsqrtn densitytrue pltstepbins n colorcolor labelsamples n n xmax maxbins plot density according estimated mean plotexponentialdensitymu xmax color labelestimated density n n return xmax sample values draw histogram density according estimated mean xmax sampleandplot r samples xmax sampleandplot b finally plot true density plotexponentialdensity maxxmax xmax k true density add legend pltlegend show plot pltshow i used samples since samples estimate already pretty good but still samples i somewhat surprised good estimate mean thus density given histogram without knowledge samples drawn exponential distribution i sure i would recognize exponential distribution,i drawing samples exponential distribution in first experiment i drawing samples second i drawing samples distribution numpyrandomexponential i would like visually compare difference maximum likelihood estimate two experiments since exponential distribution mle sample mean second experiment mle closer true density how i comparison python i know plot graphics matplotlib i know type graphic i use,2 have look struct module you need pack function edit the code import struct lssss string structpack i note shorter constant example print output l╙☻ð¦i structpack available python your number cannot packed bytes i shortened bit,i usually perform things like c i using python write quick script i run wall if i binary list whatever python stores result fread i access individual bytes buffer buffer etc i need change bytes hold new bit filesize read already filesize i need update in c i would get pointer location cast store integer python i suddenly realized i idea something like how i update bytes buffer specific location hold value integer python edit i going add i seem figure solutions though i see right track first i python upgrade big corporation servers apparently limits options sorry mentioning earlier i aware many less features secondly let make ultrasimple lets say i binary file named myfilebinary fivebyte contents c hex equates ascii representations letters l xs alone file if i f open myfilebinary rb contents fread contents sven marnach answer hold fivebyte immutable string using python facilities could i change s held contents arbitrary integer value ie give line code make byte indices contents contain bit integer myint value,2 the result fileread string python immutable depending context task trying accomplish different solutions problem one using array module read file directly array bit integers you modify array write back file openfilename f fseek size ftell fseek data arrayarrayi assert dataitemsize datafromfilef size data newvalue use datatofileg write data back new file g,i usually perform things like c i using python write quick script i run wall if i binary list whatever python stores result fread i access individual bytes buffer buffer etc i need change bytes hold new bit filesize read already filesize i need update in c i would get pointer location cast store integer python i suddenly realized i idea something like how i update bytes buffer specific location hold value integer python edit i going add i seem figure solutions though i see right track first i python upgrade big corporation servers apparently limits options sorry mentioning earlier i aware many less features secondly let make ultrasimple lets say i binary file named myfilebinary fivebyte contents c hex equates ascii representations letters l xs alone file if i f open myfilebinary rb contents fread contents sven marnach answer hold fivebyte immutable string using python facilities could i change s held contents arbitrary integer value ie give line code make byte indices contents contain bit integer myint value,1 listwhat need function structpackintofmt buffer offset v v it documented httpdocspythonorglibrarystructhtml near top example code import struct import ctypes datactypescreatestringbuffer structpackintoi data x print listdata similar posting python how pack different types data string buffer using structpackinto edit added python compatible example import struct fopen myfilebinary rb contentsfread datalistcontents datastructpacki x print data,i usually perform things like c i using python write quick script i run wall if i binary list whatever python stores result fread i access individual bytes buffer buffer etc i need change bytes hold new bit filesize read already filesize i need update in c i would get pointer location cast store integer python i suddenly realized i idea something like how i update bytes buffer specific location hold value integer python edit i going add i seem figure solutions though i see right track first i python upgrade big corporation servers apparently limits options sorry mentioning earlier i aware many less features secondly let make ultrasimple lets say i binary file named myfilebinary fivebyte contents c hex equates ascii representations letters l xs alone file if i f open myfilebinary rb contents fread contents sven marnach answer hold fivebyte immutable string using python facilities could i change s held contents arbitrary integer value ie give line code make byte indices contents contain bit integer myint value,3 you use key instead cmp it lot easier write key function done one line datelistsortkey lambda datetimestrptimes mdy you also need import datetime import datetime,i got following python code date comparison list sort function eg datelistsortcmpdcmp i wondering possibly remove cmpif testing make oneliner def dcmpa b amm add ayy intv v asplit bmm bdd byy intv v bsplit v cmpayy byy v return v v cmpamm bmm v return v return cmpadd bdd update let make clear i curious remove block code function v cmpayy byy v return v v cmpamm bmm v return v return cmpadd bdd,1 you could install numpy module often used scientific computing readdata numpyfromfilefileid dtypenumpyuint then access data desired location make changes,i usually perform things like c i using python write quick script i run wall if i binary list whatever python stores result fread i access individual bytes buffer buffer etc i need change bytes hold new bit filesize read already filesize i need update in c i would get pointer location cast store integer python i suddenly realized i idea something like how i update bytes buffer specific location hold value integer python edit i going add i seem figure solutions though i see right track first i python upgrade big corporation servers apparently limits options sorry mentioning earlier i aware many less features secondly let make ultrasimple lets say i binary file named myfilebinary fivebyte contents c hex equates ascii representations letters l xs alone file if i f open myfilebinary rb contents fread contents sven marnach answer hold fivebyte immutable string using python facilities could i change s held contents arbitrary integer value ie give line code make byte indices contents contain bit integer myint value,1 in context video class using nested function class videoobject def initself selfcbfilerefdone def openself filename winfunctypenone dword dword def cbfilerefdoneport userdata print file indexed filename selfcbfilerefdoneappendcbfilerefdone save reference selfhsdkplaymsetfilerefcallback clongselfport cbfilerefdone dword loggingerrorunable set callback indexing return false it somewhat ugly natural variant fails typeerror callback xxx work winfunctypenone dword dword def cbfilerefdoneself port userdata print file indexed to fix special function descriptor could created def methodprototype class methoddescriptorobject def initself func selffunc func selfboundfuncs hold references prevent gc def getself obj typenone assert obj none always require instance try return selfboundfuncsobjtype except keyerror ret selfboundfuncsobjtype prototype selffuncgetobj type return ret return methoddescriptor usage class videoobject methodwinfunctypenone dword dword def cbfilerefdoneself port userdata print file indexed def openself filename selfhsdkplaymsetfilerefcallback clongselfport selfcbfilerefdone dword additionally methoddescriptor saves references c functions prevent garbage collected,i define callback function python one called dll bool setcallback long nport void stdcall pfilerefdone dword nport dword nuser dword nuser i tried code seems work python python crashes i assume i something wrong import ctypes ctypeswintypes ctypeswintypes import dword def cbfuncport userdata print hurrah cbfunc ctypeswinfunctypenone dword dword mydllsetcallbackctypesclong cbfunccbfunc dword where mistake note the platform running bit windows python the dll loads successfully also functions inside work fine called python a full sample code reproduces available httpsgithubcomssbarneapyhikvision run videopy py py,2 you pass numpy array matrix argument initializing sparse matrix for csr matrix example following import numpy np scipy import sparse a nparray b npmatrix a array sa sparsecsrmatrixa here initialization sparse matrix sb sparsecsrmatrixb sa x sparse matrix type type numpyint stored elements compressed sparse row format print sa,for scipy sparse matrix one use todense toarray transform numpy matrix array what functions inverse i searched got idea keywords right hit,3 property setter defined readonly the reason might work using python defined oldstyle class remember always derive object python x class cobject property def dxself return selfdx def initself dx selfdx dx,i following code class c def initself dx selfdx dx def getdxself return selfdx dx propertygetdxnonenone c c print cdx cdx print cdx shows this work see however questions follows is possible restrict users cdx if intention make readonly attributes i know always way hack around i want prevent standard cdx val working,2 if possible change pickle protocol multiprocessing package uses define getstate setstate objects import pickle class fooobject slots def initself selfthis selfthat selfother def getstateself return dictname getattrself name name selfslots def setstateself state name value stateitems setattrself name value pickledumpsfoo protocol,i using python multiprocessing module place objects onto queue processed several workers my first issue getting bound instance methods pickle i working i running separate issue caused fact objects using slots when mp module goes pickle objects seems using older ascii pickle protocol handle slots the newer protocol handle i sure make mp module use protocol anyone experience,3 the error message strictly accurate misleading the reason formatters section missing logging module find file passed loggingconfigfileconfig try using absolute file path,trying use logging configuration file implement timedrotatinigfilehandler just take config file reason any suggestions appreciated xpy import logging import loggingconfig import logginghandlers loggingconfigfileconfigxini mylog logginggetlogger x mylogdebug starting xini loggers keysroot loggerroot levelnotset handlerstrfhand handlers keystrfhand handlertrfhand classhandlerstimedrotatingfilehandler whenm interval backupcount formattergeneric leveldebug args varlogxlog formatters keysgeneric formattergeneric classloggingformatter formatasctimes levelnames messages datefmt traceback recent call last file xpy line loggingconfigfileconfigxini file usrlibpythonloggingconfigpy line fileconfig flist cpgetformatters keys file usrlibpythonconfigparserpy line get raise nosectionerrorsection configparsernosectionerror no section formatters thanks,3 new relic package python including django modwsgi httpssupportnewreliccomhelpkbpython,i want able instrument python applications i know page generation time percentage time spent external requests mysql api calls number mysql queries mysql queries i want data production offline profiling time spent various places different load in php i xhprof instrumentationforphp in ruby railsnetjava i new relic is package recommended python django,1 found answer lot google search simple just stepsetfieldstactual actual result wohhooooo if code fails work try following optional set win com follows making late binding httporeillycomcatalogpythonwinchapterchhtml start pythonwin tools menu select item com makepy utility b using windows explorer locate client subdirectory ota com type library main wincom directory doubleclick file makepypy thank,i want try add step details expected actual status etc qc run testcase testset python script living outside quality center i come till code given i know add step expected step actual result if anyone knows please help please i want qtp solutions thanks code script name addtsrunpy cpythonpythonexe this script lives locally windows machine python win installed ie dependencies windows machine python pythonwin installed ie qc account connectivity qcserver import wincomclient os tdc wincomclientdispatchtdapioletdconnection tdcinitconnection httpqcserverqcbin tdclogin username password tdcconnect domainname project tsfolder tdctestsettreemanagernodebypath roottestmesubfolder tslist tsfolderfindtestsets testset tsobject tslistitem tsdir ospathdirname testset tsname ospathbasename testset tsfolder tdctestsettreemanagernodebypathtsdir tslist tsfolderfindtestsetstsname tsobject tslistitem tstestfact tsobjecttstestfactory testsettestslist tstestfactnewlist tsinstance testsettestslistitem newitem tsinstancerunfactoryadditemnone newitem run object newitemstatus no run newitemname run newitempost newitemcopydesignsteps copy design steps newitempost steps newitemstepfactorynewlist step steps stepstatus not completed steppost how i change actual result i access actual expected result change stepfield stactual my actual result this works vb python syntax error traceback file interactive input line syntaxerror assign function call hope helps guys if know answer set actual result please help let know thanks amit,1 it http post basic authentication basic authentication described official fetch internet resources using urllib howto so xml xml sending url url posting merchantcode password self explanatory following works import urllib passwordmgr urllibhttppasswordmgrwithdefaultrealm passwordmgraddpasswordnone url merchantcode password handler urllibhttpbasicauthhandlerpasswordmgr opener urllibbuildopenerhandler urllibinstallopeneropener request requesturl xml contenttype textxml response openeropenrequest xml something response responseclose,does anyone example code integrating rbs worldpay using python specifically posting xml order worldpay,1 you could feed iterator npgenfromtxt import numpy np import openfilename r f lines resubr line line f arr npgenfromtxtlines printarr yields thanks bitwise clueing answer,a coworker left data files i want analyze numpy each file matlab file say datam following formatting lot columns rows values typical explicit matrix creation syntax used matlab my question would practical way create numpy array files i could think brute force quick dirty solution would straightforward one i would much rather use like standard function numpy even another module edit i noticed files may contain nan values i probably adapt answers given use numpygenfromtxt instead numpyloadtxt i plan include final code soon i thanks help edit i ended following code i get everything using regex create numpy array using genfromtxt order handle nan a shorter solution could use fromstring method need stringio cannot handle nan data nan op usrbinenv python coding utf import numpy stringio open datam f research fread redotallgroup buf stringiostringios numpygenfromtxtbuf missingvalues nan fillingvaluesnumpynan,1 i also fan module quite time this one seems recent commits also true original form really i like best different versions i tried installable using pip install pathpy edit looks like python backported pypi standard lib path module called pathlib it nearly extensive path modules benefits lack clutter wellthoughtout path implementation retaining best base qualities quite path libraries particularly note cleanly handles differences different os paths windows posix seems like good clean tool worth look regardless whether every feature one could ever want nice python finally good standard path implementation,there good module pathpy written jason orendorff if i recall correctly discussion adding standard library faded away it looks multiple outgrowths original one i find far unipath looks like forked pathpy another one others according pypi anyone experience options is one better terms functionality maintenance criteria or i pick one random apologies whimsical title i first went which pathpy short so taste,3 using example html file script lxml import etree parser etreehtmlparserencoding utf tree etreeparse sourcehtml parser print treexpath ahref gives html html,suppose i doctype html public wcdtd html transitionalen html langja head meta httpequivcontenttype contenttexthtml charsetshiftjis meta namegenerator contentsnanail version titlewwwexampleorgtitle style typetextcss htitle fontsize pt fontfamily arial color ffffff style head body center table border cellspacing cellpadding aligncenter tr td width table aligncenter cellpadding cellspacing tr td height width aligncenter valignmiddle a hrefhtml targetblankimg srcthumbpng width height altthumbpng bordera td tr tr td height aligncenter valignmiddle font size colorffffffjpgfontbr font size colorffffff x ( kb)fontbr td tr table td td width table aligncenter cellpadding cellspacing tr td height width aligncenter valignmiddle a hrefhtml targetblankimg srcthumbpng width height altthumbpng bordera td tr tr td height aligncenter valignmiddle font size colorffffffjpgfontbr font size colorffffff x ( kb)fontbr td tr table td tr table center html and i want find urls page tree lxmlhtmlparse examplehtml links treexpath ahref yet i get first one html why i tried manually iterating tree using getroot seems first table first url visible i understand edit i tested example i posted actually worked testing seems i remove head works maybe something breaking parser i dunno i guess best way solve would search file remove anything head head since i parse due parse working expected so i added head example break,1 sure save time variable use variable substitutions timelocaltime dirname dirfmt csvafile ospathjoindirname csvafmt csvbfile ospathjoindirname csvbfmt logfile ospathjoindirname logfmt edited include creating complete path csv log files,i currently looking create directory linux using python v directory name date time ie my code import time import os dirfmt rootddd ddd dirname dirfmt timelocaltime osmkdirdirname this code works fine generates directory requested nonetheless i also like within directory create two csv files log file name now directory name dynamically generated i unsure move directory create files i like directory together three files name csv files prefixed letter so example given i like directory created called within two csv files called csv b csv log file called log my code file creations csvafmt addd dddcsv csvbfmt bddd dddcsv logfmt ddd dddlog csvafile csvafmt timelocaltime csvbfile csvbfmt timelocaltime logfile logfmt timelocaltime fcsva opencsvafile wb fcsvb opencsvbfile wb flog openlogfile wb any suggestions i second remains throughout i appreciate code would take split second run within time second may change i assume key lies within altering timelocaltime i remain unsure thanks,1 it may require useragent accepts header well try comparingcopying http headers sent browser using firebug livehttp headers firefox chrome dev tools compare hexed password confirm correct then add headers one time discovered issue,i following scenario i shoutcastish server serves radio station xml info i flash player client needs fetch flash player fetch things httpbasic auth using get so i building python cgi script handle authentication reserve information hope makes sense essentially script serves proxy real data creating http request fetching data serving requested here python usrbinpython import base cgitb sys urllib cgitbenable print contenttype textxml print username username password password url httpsvoscastcomadmincgimodeviewxml auth baseencodestring ss username password request urllibrequesturl requestaddheaderauthorization basic auth try handle urlliburlopenrequest except ioerror e print something failed sysexit print handleread pretty straightforward right unfortunately working if i visit website browser enter username password works i see xml tree instead i get following output stdout contenttype textxml icy resource not found icynoticebrshoutcast distributed network audio serverlinux vbr icynoticethe resource requested foundbr what i wrong given url username password browser everything works what i missed,1 requestget requestpost immutable querydict instances this means cannot change attributes directly copying querydict returns mutable querydict you call pop method copy without raising error requestget get requestgetcopy getpop key,looking dirrequestget i notice pop listed method i also believe popped attributes request past is accurate if would fail requestgetpop key,3 if really want full proxy object available quick dirty solution expense extra database call class myuseruser def prettyusernameself selffirstname return selffirstname return selfusername class meta proxy true def getmyuserself try return myuserobjectsgetpkselfpk except myuserdoesnotexist return none useraddtoclass getmyuser getmyuser so use view could say requestusergetmyuserprettyusername or template requestusergetmyuserprettyusername a nicer solution tied proxy model idea would following def prettyusernameself selffirstname return selffirstname return selfusername useraddtoclass prettyusername prettyusername this would allow following requestuserprettyusername or requestuserprettyusername,i like define proxy model django default user class something kind like class myuseruser def prettyusernameself selffirstname return selffirstname return selfusername class meta proxy true and i like able call prettyusername view code ideally even templates is simple way take instance standard user model typecast instance myuser even init magic would okay long i say myuser myuserrequestuser view code,1 just means name generated class irrelevant,i looking code uses typename namedtuple i wondering purpose example namedtuple nameofclass nameofclass why use string,1 b b copy copy original list the lists inside original list still referenced change shows lists you b l l new list consisting copies sublist copy import deepcopy b deepcopya,i list list b copy list b c a b c b b b b b if i look b i get following c b a b c b c b a b c why swap list b also affects original list thank,1 you need create manifestin file include simple instructions extra files want include see manifestin template example include docs dir files directly underneath include docs include files doc dir recursively recursiveinclude docs,i python project following structure clustering project name clustering package clusteringpy modules tests subpackage testclusteringpy files docs bin i would like include docs directory distribution i seem any pointers done would helpful thanks my current setuppy looks like distutilscore import setup setupname clustering version description desc author a authoremail mesomemailcom packages clustering clusteringtests requires numpy scipy scripts binpredict binverify i tried using packagedata option successful including docs directory distribution is conventional way including docs distribution,3 i used app called djangoschedule similar features if dig source see uses pythondateutil see rrules underneath it keeps list schedule rules event database you could use similar tactic when venueopenstatus queried see current datetime fits inside startend occurrence provided venue schedule rules if open,i need implement open filter website lists venues i know start my website implemented using python webpy mysql database i store opening hours every venue select venues open an example opening hours works pm weekdays pm weekend works round clock excluding opening hours may different every day week day one interval time i need hack exceptions specific holidays any tipssuggestions interface data schema query welcome upd i managed come solution ok dateutilrelativedelta import dateutilrrule import datetime import date import venue many rules hoursstart minutesstart hoursend timeend less timestart ends next day minutesend daysofweek th hoursdiff hoursend hoursstart minutesdiff minutesend minutesstart hoursdiff hoursdiff minutesdiff hoursdiff datetimestart datetoday relativedeltahourshoursstart minutesminutesstart days yesterday timestart datetimenow occurrence rruleweekly wkstmo byweekdaydaysofweek dtstartdatetimestartbeforenow true occurrence relativedeltahourshoursdiff minutesminutesdiff print is open now,1 here couple options although neither built the solution probably find acceptable this solution probably falls quick dirty category helps lead next solution remove values last line globally replace nothing get then use numpy loadtxt follows import numpy np a nploadtxt datam a array a solution might find acceptable in solution create method coerce input data form numpy loadtxt likes form actually import stringio import numpy np def convertmfname openfname r fin arrstr finread arrstr arrstrsplit remove content first arrstr arrstrrsplit remove content arrstr arrstrreplace n replace newline return stringiostringioarrstr now following nploadtxtconvertm datam array,a coworker left data files i want analyze numpy each file matlab file say datam following formatting lot columns rows values typical explicit matrix creation syntax used matlab my question would practical way create numpy array files i could think brute force quick dirty solution would straightforward one i would much rather use like standard function numpy even another module edit i noticed files may contain nan values i probably adapt answers given use numpygenfromtxt instead numpyloadtxt i plan include final code soon i thanks help edit i ended following code i get everything using regex create numpy array using genfromtxt order handle nan a shorter solution could use fromstring method need stringio cannot handle nan data nan op usrbinenv python coding utf import numpy stringio open datam f research fread redotallgroup buf stringiostringios numpygenfromtxtbuf missingvalues nan fillingvaluesnumpynan,1 there several sparse matrix classes scipy bsrmatrixarg shape dtype copy blocksize block sparse row matrix coomatrixarg shape dtype copy a sparse matrix coordinate format cscmatrixarg shape dtype copy compressed sparse column matrix csrmatrixarg shape dtype copy compressed sparse row matrix diamatrixarg shape dtype copy sparse matrix diagonal storage dokmatrixarg shape dtype copy dictionary of keys based sparse matrix lilmatrixarg shape dtype copy rowbased linked list sparse matrix any conversion import numpy np scipy import sparse anparray bsparsecsrmatrixa printb see httpdocsscipyorgdocscipyreferencesparsehtmlusageinformation,for scipy sparse matrix one use todense toarray transform numpy matrix array what functions inverse i searched got idea keywords right hit,3 structure code one function encapsulates entire process data retrieval url another encapsulates processing data import urllib httplib beautifulsoup import beautifulsoup def appendlogmessage print message def getwebpageaddress try useragent mozilla compatible msie windows nt headers useragent useragent request urllibrequestaddress none headers response urlliburlopenrequest timeout try return responseread finally responseclose except urllibhttperror e errordesc httplibresponsesgetecode appendlog http error strecode errordesc address except urlliburlerror e appendlog url error ereason address except exception e appendlog unknown error stre address def processwebpagedata data none print beautifulsoupdata else pass something else data getwebpage httpdoesnotexistblahcom processwebpagedata data getwebpage httpdocspythonorgcopyrighthtml processwebpagedata,currently error retrieving webpage soup populated page gets default return beautifulsoup i looking way check error getting webpage i skip chunk code like soup stuff i want terminate together appologies newbie inquiry def getwebpageaddress try useragent mozilla compatible msie windows nt headers useragent useragent req urllibrequestaddress none headers webhandle urlliburlopenreq except urllibhttperror e errordesc basehttpserverbasehttprequesthandlerresponsesecode appendlog http error strecode address return except urlliburlerror e appendlog url error ereason address return except appendlog unknown error address return return webhandle def test soup beautifulsoupgetwebpage httpdoesnotexistblahcom print soup soup stuff test,1 import os ossystemr rundllexe powrprofdllsetsuspendstate hibernate,i like write short python script puts computer sleep i ve already searched api result suspend delayed execution what function trick,1 it look like proper indention remember python whitespace important the problem section code probably start looking something like elif structitem v typestructitem tuple structitem lenstructitem structitem st jt enumeratestructitem structitem st appendstructtypemapstructitem j structitem st tuplestructitem st structitem lenstructitem st,very new far little help making it keeps giving syntax error line many errors im really sure person helped create gone leaving noob self try fix thisthere script middle decompiles direct files cant post but need figure whats wrong syntax error whats worng script oo compatible w python configuration section toptablefolder cgamestopkopscriptstable toptableversion toptableencoding gbk end config import struct types import class toptsv name filename list version frombinmap v def initself filename version filename selffilename toptablefolderselfclassname else selffilename filename version selfversion toptableversion else selfversion version selflist selffrombinmap v def unencryptself item load data file openselffilename bin rb data bytearrayfileread fileclose arraysize intliststructunpackfrom dataii rdata dataii data datailendata k l lendataarraysize encryption selfversion selfclassname magicsingleinfo selfclassname magicgroupinfo selfclassname resourceinfo selfclassname terraininfo newbytes bytesfromhex d f e ab e d e e cb dd d cb d cf whilekl item dataiiarraysize iarraysize selfversion selfclassname magicsingleinfo selfclassname magicgroupinfo selfclassname resourceinfo selfclassname terraininfo mc enumerateitem j lennewbytes itemm itemm newbytesj rdata rdata item k k file openselffilename unbin wb filewriterdata fileclose def loadbindataself array item addresses load structure calculate size structtypemap charc byteb ubyteb bool shorth ushorth inti uinti longl ulongl quadq uquadq floatf doubled strs colorb rcolorb structvars l stp f v lpad rpad sa sap ea eap st lm sm smb smea sv func initialize addresses structinitaddress structlimitaddress structmarkedaddresses structfuncindexes v enumeratelistzipselffrombinmap structitem structvarscopy structitemupdatev structitem smb structmarkedaddressesstructitem smb structinitaddress structitem lm structinitaddress structmarkedaddressesstructitem lm structitem sm structmarkedaddressesstructitem sm structinitaddress typestructitem func functiontype structfuncindexesappendi elif structitem v typestructitem tuple structitem lenstructitem structitem st jt enumeratestructitem structitem st appendstructtypemapstructitem j structitem st tuplestructitem st structitem lenstructitem st else structitem st structtypemapstructitem structitem color structitem rcolor structitem structitem sa structinitaddress structitem sap structitem sa structitem lpad structitem ea structitem sap typestructitem tuple jt enumeratestructitem structitem ea structitem ea structcalcsizestructitem st j structitem stp structitem l structitem stp else structitem ea structitem ea structcalcsizestructitem st structitem structitem stp structitem l structitem stp structitem smea structmarkedaddressesstructitem smea structitem ea structitem eap structitem ea structitem rpad structinitaddress structitem eap structinitaddress structlimitaddress structlimitaddress structinitaddress printstructitem selffrombinmapi selffrombinmapistructitem structsize structlimitaddress load data file openselffilename bin rb data bytearrayfileread fileclose k arraysize intliststructunpackfrom dataii arraysize structsize printselffilename bin actual array size strarraysize match structure size strstructsize raise size error data datailendata k l lendatastructsize encryption selfversion selfclassname magicsingleinfo selfclassname magicgroupinfo selfclassname resourceinfo selfclassname terraininfo newbytes bytesfromhex d f e ab e d e e cb dd d cb d cf whilekl item dataiistructsize istructsize selfversion selfclassname magicsingleinfo selfclassname magicgroupinfo selfclassname resourceinfo selfclassname terraininfo mc enumerateitem j lennewbytes itemm itemm newbytesj arrayappenditem k k associate data structure selflist selflistappendlistzipselffrombinmap yrawrow enumeratearray row xcellstruct enumeratelistzipselffrombinmap typecellstruct func functiontype cell cellappend rowappendselftransformtostrcellcellstruct else cell cellstruct v cellstruct sap j rangecellstruct l processeddataliststructunpackfrom strcellstruct lencellstruct st cellstruct stp joincellstruct st rawrowicellstruct stp x printcellstruct cellappendprocesseddata iicellstruct structcalcsizejoincellstruct st cellstruct stp sizeof cellstruct rcolor cellreverse else cellappendcellstruct v printcell x l x rowappendselftransformtostrcellcellstruct selflistappendrow xrow enumerateselflist x funcindex structfuncindexes selflistxfuncindex listzipselffrombinmapfuncindex func funcindex row deletions zstructitemname enumeratelistzipselffrombinmap structitemname del selflistxzdeletions deletions deletions return def iselfx iv enumerateselflist ifxv return break return def jselfx iv enumeratelistzipselffrombinmap ifxv return break return def remapselfv enumeratelistzipv selfjn selffrombinmapappendlistzipvilistzipvi else listzipvi del selffrombinmapselfjn else selffrombinmapselfjn listzipvilistzipvi def bintotsvself file openselffilename txt wt encodingtoptableencoding ia enumerateselflist alista deletions zitem enumeratea item del azdeletions deletions deletions filewrite joina else printa filewrite n joina fileclose return self def trimnullbytestrstring flag flag return string empty result string ibyte enumeratestring byte result stringi break flag amp string string result return result def transformtostrselfresulttslstpfveaeaplpadrpadsasapstsmlmsmbsmeasvfunc v return strv type j nv enumerateresult typet tuple type tj isinteger nottypefloat typedouble typestr typechar typebool isinteger f f kw enumeratev isinteger result flagx remove ff flagx cut file defect bytes flagx remove f amp x w f amp x w w w w w f amp x typebyte typeubyte w typeshort typeushort w typelong typeulong w typequad typeuquad w del resultjm mm else f amp x w resultj resultjm break resultjmstrresultjm mm typefloat f f resultjkstrroundfloatwf typestr f f w w resultjm else resultjm wdecode gbk ignore ox enumerateresultjm x resultjm resultjmo break resultjm resultjmstrip f amp resultjm result resultj resultj joinresultj isinteger resultj resultj jj typestr result joinresult f amp result result else result joinresult isinteger result result return result c toptablebins myc c try mycloadbindata except ioerror print mycfilename bin exist skipping mycbintotsv lines line error jt enumeratestructitem structitem st appendstructtypemapstructitem j structitem st tuplestructitem st structitem lenstructitem st else structitem st structtypemapstructitem structitem color structitem rcolor structitem structitem sa structinitaddress structitem sap structitem sa structitem lpad structitem ea structitem sap typestructitem tuple jt enumeratestructitem structitem ea structitem ea structcalcsizestructitem st j structitem stp structitem l structitem stp,1 struct used cstyle binary representations numbers if text representations instead pass int intx x split,suppose i file name numtxt i want read integers file i know structunpack might trick i cannot get right here i fp open numtxt rb print structunpack iii fpread right anyone help ps this i got file numtxt fp open numtxt wb fpwrite n fpclose,2 you use struct read numbers text file it reading data binary file first byte actually x rather byte order mark encoded value character you want threeints intx x numfilereadlinestripsplit if interested first three numbers allints intx x linesplit line numfile want list list int line,suppose i file name numtxt i want read integers file i know structunpack might trick i cannot get right here i fp open numtxt rb print structunpack iii fpread right anyone help ps this i got file numtxt fp open numtxt wb fpwrite n fpclose,3 putting aside questions style use classmethod staticmethod it passes class used class a classmethod def interfacebasedmethodcls print want delegate overriding method subclass classmethod def acls clsinterfacebasedmethod class ba classmethod def interfacebasedmethodcls print class b processes name main bb ba,in superclass python i call function overridden subclass class a staticmethod def interfacebasedmethod print want delegate overriding method subclass staticmethod def interfacebasedmethod i know causes error but i want call overridden method subclass class ba staticmethod def interfacebasedmethod print class b processes name main bb ba ideal output class b processes google search really return pages interfacebased programming python although common java etc thanks,1 your inheritance question answered but summary python provides function supertype instance documented super provides fairly clean way accessing superclass methods within subclass this page provides exhaustive study super use cases rundown class cb def methodself arg superc selfmethodarg which could generalized bit class cb def methodself arg superselfclass selfmethodarg,in superclass python i call function overridden subclass class a staticmethod def interfacebasedmethod print want delegate overriding method subclass staticmethod def interfacebasedmethod i know causes error but i want call overridden method subclass class ba staticmethod def interfacebasedmethod print class b processes name main bb ba ideal output class b processes google search really return pages interfacebased programming python although common java etc thanks,1 python ntfslink extension or want use pywin use previously stated method read use winfile import winioctlcon import fsctlgetreparsepoint islink readlink winfile seem attribute fileattributereparsepoint to make things easier reparsefolder fileattributedirectory fileattributereparsepoint for parsereparsebuffer function symboliclink symbolic mountpoint mountpoint generic generic def islinkfpath windows islink implementation getfileattributesfpath amp reparsefolder reparsefolder return true return false def parsereparsebufferoriginal reparsetypesymboliclink implementing python typedef struct reparsedatabuffer ulong reparsetag ushort reparsedatalength ushort reserved union struct ushort substitutenameoffset ushort substitutenamelength ushort printnameoffset ushort printnamelength ulong flags wchar pathbuffer symboliclinkreparsebuffer struct ushort substitutenameoffset ushort substitutenamelength ushort printnameoffset ushort printnamelength wchar pathbuffer mountpointreparsebuffer struct uchar databuffer genericreparsebuffer dummyunionname reparsedatabuffer preparsedatabuffer size data types szulong sizeofulong szushort sizeofushort our structure probably better way iterate dictionary particular order i hurry unfortunately i used pkeys buffer tag szulong datalength szushort reserved szushort symboliclink substitutenameoffset szushort substitutenamelength szushort printnameoffset szushort printnamelength szushort flags szulong buffer u pkeys substitutenameoffset substitutenamelength printnameoffset printnamelength flags mountpoint substitutenameoffset szushort substitutenamelength szushort printnameoffset szushort printnamelength szushort buffer u pkeys substitutenameoffset substitutenamelength printnameoffset printnamelength generic pkeys buffer header stuff buffer tag originalszulong buffer datalength originalszulongszushort buffer reserved originalszulongszushortszushort original original parsing k reparsetype c bufferk pkeys typebufferkc int sz bufferkc bytes originalsz bufferkc b bytes n ordb n bufferkc n original originalsz using offset length grabbed set buffer bufferk buffer original return buffer def readlinkfpath windows readlink implementation this return true file exist far i know islinkfpath return none open file correctly depending string type handle createfilewfpath genericread none openexisting fileflagopenreparsepoint typefpath unicode else createfilefpath genericread none openexisting fileflagopenreparsepoint maximumreparsedatabuffersize buffer deviceiocontrolhandle fsctlgetreparsepoint none above return ugly string byte array need parse but first close handle file locking anymore closehandlehandle minimum possible length assuming length target bigger lenbuffer return none parse return result result parsereparsebufferbuffer offset resultsymboliclink substitutenameoffset ending offset resultsymboliclink substitutenamelength rpath resultsymboliclink buffer offsetendingreplace x lenrpath rpath rpath rpath return rpath def realpathfpath os import path islinkfpath rpath readlinkfpath pathisabsrpath rpath pathabspathpathjoinpathdirnamefpath rpath fpath rpath return fpath def example os import system unlink system cmdexe c echo hello world testtxt system mklink testlinktxt testtxt print islink islink testlinktxt print readlink readlink testlinktxt print realpath realpath testlinktxt unlink testlinktxt unlink testtxt name main example adjust attributes createfile needs normal situation work feel free improve it also work folder junctions use mountpoint instead symboliclink you may way check sysgetwindowsversion put something releasing since form symbolic link supported vista,does anyone know way makeread symbolic links across versions win python ideally minimum amount platform specific code i need app cross platform,3 i cut losses start this solution attempt complicated kludgy there many readymade solutions area outstanding linux backup utilities fwbackups sounds good want take easy route rsyncssh hard core,i trying set remote backup server dar along lines i really like piping python possible i asked separate question using netcat subprocesspopencmd shelltrue i succeeded making differential backup examples dar site the two problems i know assign port numbers dynamically way if i execute server background fails why update this seem related netcat hangs even without netcat mix here code socket import socket afinet sockstream import os sys import socketserver import subprocess class darhandlersocketserverbaserequesthandler def handleself print entering handler data selfrequestrecvstrip print got data data xform cmd nc dl darslave archivesremotehost nc l printcmd cmd nc dl darxform k archivesdiffbackup printcmd proc subprocesspopencmd shelltrue proc subprocesspopencmd shelltrue print sending port number selfrequestsend print waiting result strprocwait print ncdarslavenc returned result result strprocwait print ncdarxform returned result else result bad request selfrequestsendresult print send result exiting handler myaddress localhost def server server socketservertcpservermyaddress darhandler print listening serverserveforever def client sock socketafinet sockstream print connecting sockconnect localhost print connected sending request socksend xform print waiting response port sockrecv print got port try osunlink toslave except pass osmkfifo toslave cmd nc w localhost toslave cmd nc w localhost dar b configtestdcf a toslave c nc w localhost port printcmd proc subprocesspopencmd shelltrue proc subprocesspopencmd shelltrue print waiting result procwait result procwait print ncfifo returned strresult print ncdarnc returned strresult result sockrecv print received result sockclose print socket closed exiting name main sysargvstartswith serv server else client here happens server python clientserverpy serve amp listening entering handler got xform nc dl darslave archivesremotehost nc l nc dl darxform k archivesdiffbackup sending port number waiting stopped python clientserverpy serve here happens client python clientserverpy client connecting connected sending request waiting response got nc w localhost dar b configtestdcf a toslave c nc w localhost waiting fatal error aborting operation corrupted data read pipe ncfifo returned ncdarnc returned the client also hangs i kill keyboard interrupt,1 same always factors set x range,i python newbie attempting write code sieve eratosthenes for i initialize list empty sets i tried factorsset produces shallow copy i want deep copy factorsi factorsj point different sets is simple syntax,3 factors set index xrange,i python newbie attempting write code sieve eratosthenes for i initialize list empty sets i tried factorsset produces shallow copy i want deep copy factorsi factorsj point different sets is simple syntax,3 i got frustrated troubles i made simple routines using poster python standard cookielib httplib it located httpsgithubcomgandrewstonemediawikipythonbot,i trying upload image random picture mediawiki site i keep getting error unrecognized value parameter action upload here i site url password changed python r feb gcc apple inc build darwin type help copyright credits license information import wikitools import poster wiki wikitoolswikiwikimywikiurlapiphp wikiloginusernameadmin passwordmypassword true screenshotpage wikitoolswikifilefilewikiwiki titlescreenshot screenshotpageuploadfileobjopenusersjeffpicturesmagensbayxjpg r ignorewarningstrue traceback recent call last file line file librarypythonsitepackageswikitoolswikifilepy line upload res reqquery file librarypythonsitepackageswikitoolsapipy line query raise apierrordata error code data error info wikitoolsapiapierror u unknownaction uunrecognized value parameter action upload from i could find google current mediawiki support uploading files but ridiculous must way right i married wikitools package—any way appreciated edit i set wgenableuploads true localsettingsphp i upload files manually python edit i think wikitools gets edit token automatically i attached upload method before api request calls selfgettoken edit take care i think i play around little though see manually adding fixes things def uploadself fileobjnone comment urlnone ignorewarningsfalse watchfalse upload file requires poster module fileobj a file object opened reading comment the log comment used inital page content file already exist wiki url a url upload file allowed wiki ignorewarnings ignore warnings duplicate files etc watch add page watchlist apicanupload fileobj raise uploaderrorthe poster module required file uploading fileobj url raise uploaderrormust give either file object url fileobj url raise uploaderrorcannot give file url params action upload comment comment filename selfunprefixedtitle token selfgettoken edit there specific upload token url params url url else params file fileobj ignorewarnings params ignorewarnings watch params watch req apiapirequestselfsite params writetrue multipartboolfileobj res reqquery upload res res upload result success selfwikitext selflinks selftemplates selfexists true return res also first question somebody let know post peoples code something thanks,1 program used display text terminal i believe generally comes windows installations python trying use display help text seems computer python interpreter able use here list common windows shell commands including,so i installed python interpreter wanted use helpsys feature get information sys module i got error idea went wrong cusersjakepython python default jun msc v bit amd win type help copyright credits license information import sys helpsys recognized internal external command operable program batch file is matter source code sys module computer something else entirely any help would greatly appreciated,2 python uses program show help text it saying find program it cwindowssystemmorecom you need cwindowssystem path environment variable,so i installed python interpreter wanted use helpsys feature get information sys module i got error idea went wrong cusersjakepython python default jun msc v bit amd win type help copyright credits license information import sys helpsys recognized internal external command operable program batch file is matter source code sys module computer something else entirely any help would greatly appreciated,2 the simplest clearest may conditional expression fields fieldfield obj else field,is way something like obj fields field else fields field field thanks advance,1 rvm similar virtualenv also checkout rbenv perhaps like virtualenv bundler packaging dependencies development deployment works like setuppy pip i used pip seems features rubygems bundler bundler gemfile similar pip requirement file bundler install dependencies development directory package deployment directory layouts tend look like lib classes modules etc bin executables things want path test unit tests jeweler good tool setting maintaining releasing gems edit here resources some links ruby layout directory layout pure ruby project ideal ruby project structure httpwwwrubyforumcomtopic some python what best project structure python application initialize project layout python here one making comparison tools httpnewsycombinatorcomitemid,i experience ruby it’s less python experience i packaged published several python packages there’s one ruby package i published i want learn rapidly ruby packaging ecosystem comparing python i believe there’s tool equivalent virtualenv ruby i don’t know yet what roles rvm bundler when i write python package i usually use setuppy develop command — resolves dependencies installed sitepackages what equivalent thing ruby what preferred way make directory layout structure ruby packages gem package naming rule is gem name case sensitive should contained ruby module name any points i missed,3 when import module twice runs module global namespace access interactive session global variables x that whole point modules this typically rectified passing variables functions rather operate global variables has nothing whatsoever sympy issue using regular ol python numbers whatever,i like define function module interactive also take symbolic variables let say function then i want work like function number function number x x function number the reason i want prompt user input i thinking functions many arguments i also thinking using equations like fxgyhz useful variables assigned instead fixed here i tried work the reason explained kendall answer i first made module twicepy def twice num input number return num then i ran import sympy x svar x import twice ttwice number x nameerror name x defined,1 this pretty much standard way factors set x xrange it better use xrange instead range xrange generator,i python newbie attempting write code sieve eratosthenes for i initialize list empty sets i tried factorsset produces shallow copy i want deep copy factorsi factorsj point different sets is simple syntax,1 you need create list first use append method add element end tree treeappendnodeinfo tree nodeinfo,i new python difficulty getting object stored access array list python i tried something like class nodeinfo def initself left value right selfl left selfr right selfv value tree nodeinfo treel treer treev when i try assign values try read variable i get following error tree nodeinfo nameerror name tree defined what i wrong different way assign read objects arrays lists python,3 works c py filetype file andor syntax file right location python vim manual help i also would try scr command this lists vim script loaded so start vim two different way vim yourc vim yourpy vim session type scr see syntax file c loaded like chain reaction doesnt work way python may give clue,i using mac osx lion terminalapp supports output echo amptco in vimrc i pathtovimvimrc syntax filetype plugin indent set nobackup when i vim blahpy colorscheme torte syntax colors loading for example python keyword proper colors they regular text color that works c files python i updated syntaxpythonvim still luck can someone tell thanks,3 you want sourcetosource program transformation tool such tool parses language internal data structure invariably ast allows modify ast regenerate source text modified ast without changing essentially anything source except ast changes made such program transformation tool parse text asts antiparse called prettyprint asts text if ironpython prettyprinter need if build one maybe lot effort observed easy one might think see answer compiling ast back source code if work dms software reengineering toolkit python front end might trick it properties,i working tools game i making the tools serve front end making editing game files easier several files python scripting files for instance i itemspy file contains following minimalized example itemmodule import import copy class scripteditemitem def initself name description itemtypes primarytype flags usability value throwpower iteminitself name description itemtypes primarytype flags usability value throwpower itemgetnextitemid def cloneself return copydeepcopyself itemlibraryadditemscripteditemabounding crystal a colourful crystal composed many smaller crystals it gives warm glow itemtypesynthesismaterial itemtypesynthesismaterial itemusageunusable as i mentioned i want provide front end editing file without requring editor know pythonedit file directly my editor needs able find list class types example scripted item find list created items case one abounding crystal i need find type casescripteditem parameter values allow editing parameters creationremoval items to i started writing parser looking class keyword recorded classes use construct objects this worked simple data i started using classes complex constructors lists maps etc became increasing difficult correctly parse after searching around i found ironpython made easy parse python files i went once i built abstract syntax tree i used pythonwalkers identify find information i need this works perfectly reading data i see easy way push updated data python file as far i tell way change values ast much less convert ast back script file if i wrong i love someone tell i could what i need search file i find correctly line try push data constructor ensuring correct ordering is obvious solution i seeing should i keeping working parser make support complex data types i really though i ironpython parser i think tricky push modified data back file any suggestions would appreciated,1 your call script incorrect range startpod endpod the rangeij functions returns following list j or differently put end point always removed try changing pod range line pod rangestartpod endpod,i writing script i extract command line arguments using getopt qualify values offered use values limits loop code fragment try startpod endpod topovalue mapint args except valueerror errormsg invalid strerrormsg errfunct noninteger values supplied args else errfuncterrormsg pod rangestartpod endpod print value pod pod switch range print value switch switch the problem i range function i think i passing integers map function converting list strings integers i tryexcept handler exits way error function i wrote reason working if i call script correct number inputs eg somescriptpy script returns nothing,1 please make sure paste selfcontained example yours obviously missing crucial part args set if i naively assume example give maps straight args add top args behaves like said output however probably want startpod endpod if instead i args i get output what args reaching code given command line print reprargs code right block output expect,i writing script i extract command line arguments using getopt qualify values offered use values limits loop code fragment try startpod endpod topovalue mapint args except valueerror errormsg invalid strerrormsg errfunct noninteger values supplied args else errfuncterrormsg pod rangestartpod endpod print value pod pod switch range print value switch switch the problem i range function i think i passing integers map function converting list strings integers i tryexcept handler exits way error function i wrote reason working if i call script correct number inputs eg somescriptpy script returns nothing,1 probably work way i recommend work exactly way want keeps things simple abstract it matter num simpy variable int float list numeric object twice apply you may use twice lib safely twicepy def twicenum return num console import sympy x svar x import twice ttwicex version user input here working solution you use mixing io functionality function which bad twicepy import sympy def fetchinput userinput rawinput number try return intuserinput except valueerror return svaruserinput def twice num fetchinput return num rawinput usually best prompting user input it returns string instead trying eval expression,i like define function module interactive also take symbolic variables let say function then i want work like function number function number x x function number the reason i want prompt user input i thinking functions many arguments i also thinking using equations like fxgyhz useful variables assigned instead fixed here i tried work the reason explained kendall answer i first made module twicepy def twice num input number return num then i ran import sympy x svar x import twice ttwice number x nameerror name x defined,1 we want platform independent startup script invoking jvm system properties dynamically generated classpath you could use platform independent script generate platform specific startup script either installation time invocation in latter case additionally need simple static platform specific script invokes platform independent startupscriptgenerating script generated script in cases start application calling static platform specific script can invoke subprocess way stdout file written even parent process terminates you could open fileredirect child process eg using shell popen joinargs logfile amp shell specific cmdline shelltrue windows see cmdlinelist understand going,let start i really trying we want platform independent startup script invoking jvm system properties dynamically generated classpath we picked jython particular need depend standalone jythonjar startup script we decided could write jython script uses subprocesspopen launch application jvm terminates one thing our application uses lot legacy debug code prints standard so startup script typically redirecting stdoutstderr log file i attempted reproduce jython script like subprocesspopenargsstdoutlogfilestderrlogfile after line launcher script hosting jvm jython terminates the problem nothing shows logfile if i instead subprocesspopenargsstdoutlogfilestderrlogfilewait get logs so parent process needs run parallel application process launched via subprocess i want avoid two running jvms can invoke subprocess way stdout file written even parent process terminates is better way launch application jvm jython is jython bad solution anyway,1 don know best way working fine class upload def initself selfurl qurlhttpwwwwebsitecomupphp selfmanager qtnetworkqnetworkaccessmanager def sendrequestself replayfile selfrequest qtnetworkqnetworkrequestselfurl selfrequestsetrawheaderhost strselfurlhost selfrequestsetrawheadercontenttype multipartformdata boundaryaabx fp qfilereplayfile fpopenqiodevicereadonly bytes qbytearray bytesappendaabxrn bytesappendcontentdisposition bytesappendformdata namereplay filename qbytearraystrqfileinforeplayfilefilename rn bytesappendcontenttype srnmimetypesguesstypestrreplayfile bytesappendrn bytesappendfpreadall fpclose bytesappendrn bytesappendaabx contentlength byteslength selfrequestsetrawheadercontentlength contentlength selfmanagerpostselfrequest bytes in php array replay array name testscreplay type none tmpname tmpphpktchh error size,i need use qnetworkaccessmanager upload multiple files apache server php i asking i new python ad qt pyside i would like know someone tutorial example code python demonstrating note if kind content available i try share tutorial,2 you correct connecttcp endpointconnect functionally part assuming telnetprotocol twistedconchtelnettelnetprotocol problem telnetprotocol really supposed connect directly tcp transport supposed connect twistedconchtelnettelnettransport that gibberish datareceived seeing actual telnet protocol bytes supposed parsed twistedconchtelnettelnettransport iprotocol order call methods like enablelocal enableremote telnettransport i would guess connecttcp based example probably instantiating telnettransport setting protocol attribute point telnetprotocol basically make sure factory object passing exactly protocol attribute clientfactory using connecttcp example in future also please include complete runnable code examples run see happens rather guessing,my goal create telnet clients endpoints per tcpclientendpoint implementation here im class telnetclient telnetprotocol factory factory factoryprotocol telnetclient point tcpclientendpoint reactor xxxx defer pointconnect factory deferaddcallback todo reactorrun the telnetclient class handles authentication logging firing commands etc i use approach i read output datareceived giberish the telnet client functions expected constructed factory reactorconnecttcp called factory what im wrong thanks edit connecting telnetclient factoryprotocol via telnetprotocol class telnetclient telnetprotocol factory factory factoryprotocol telnettransport telnetclient point tcpclientendpoint reactor xxxx defer pointconnect factory deferaddcallback todo reactorrun edit solved the final piece clientfactory class telnetclient telnetprotocol factory clientfactory factoryprotocol telnettransport telnetclient point tcpclientendpoint reactor xxxx defer pointconnect factory solving problem two fold since want telnet client need ensure protocol instance telnetprotocol the factory must clientfactory if look source twistedinternetendoints see factory pass endpoints wrapped wrappingfactory descended clientfactory if factory pass attributes clientfactory wrappedfactory cause attributeerrors attempts call methods clientfactory,1 the ctypes library offer anything nature statement need,is portable way load c standard library libcso libcdylib python ctypes should i use elif statements result platformsystem function,1 i like zzzeek recipe httptechspotzzzeekorgtheenumrecipe i changed two things i using python name enumsymbol also name database instead using value i think less confusing having separate value still useful eg creating popup menus ui the description considered longer version value used eg tooltips in original recipe order enumsymbols arbitrary iterate python also order database but often i want determinate order so i changed order alphabetic set attributes strings tuples order values declared explicitly set attributes enumsymbols using trick sqlalchemy orders columns declarativebase classes examples class employeetypedeclenum order alphabetic contractor parttime fulltime fulltime full time parttime part time contractor contractor class employeetypedeclenum order stated fulltime parttime contractor fulltime enumsymbolfull time parttime enumsymbolpart time contractor enumsymbolcontractor here modified recipe uses ordereddict class available python import sqlalchemytypes import schematype typedecorator enum sqlalchemyutil import setcreationorder ordereddict class enumsymbolobject define fixed symbol tied parent class def initself value descriptionnone selfvalue value selfdescription description setcreationorderself def bindself cls name bind symbol parent class selfcls cls selfname name setattrcls name self def reduceself allow unpickling return symbol linked declenum class return getattr selfcls selfname def iterself return iterselfvalue selfdescription def reprself return selfname class declenummetatype generate new declenum classes def initcls classname bases dict reg clsreg clsregcopy k sorteddict kstartswith continue v dictk isinstancev basestring v enumsymbolv elif isinstancev tuple lenv v enumsymbolv isinstancev enumsymbol vbindcls k regk v regsortkeylambda k regkcreationorder return typeinitcls classname bases dict def itercls return iterclsregvalues class declenumobject declarative enumeration attributes strings used values tuples used value description enumsymbols if strings tuples used order alphabetic otherwise order declaration metaclass declenummeta reg ordereddict classmethod def namescls return clsregkeys classmethod def dbtypecls return declenumtypecls class declenumtypeschematype typedecorator declenum augmented persist database def initself enum selfenum enum selfimpl enumenumnames namecks resub az lambda mgrouplower enumname def settableself table column selfimplsettabletable column def copyself return declenumtypeselfenum def processbindparamself value dialect isinstancevalue enumsymbol value valuename return value def processresultvalueself value dialect value none return getattrselfenum valuestrip,im reading sqlalchemy see code employeestable table employees metadata column employeeid integer primarykeytrue column name string column managerdata string column engineerinfo string column type string nullablefalse employeemapper mapperemployee employeestable polymorphiconemployeestablectype polymorphicidentity employee managermapper mappermanager inheritsemployeemapper polymorphicidentity manager engineermapper mapperengineer inheritsemployeemapper polymorphicidentity engineer make type int constants library make make type enum,3 i sure i understand question i guessing following code might help import def splitrawstrings return maplambda x resub r x resplit hello world string string string sting hello world string string string string hello world string string string string print splitrawstringa gives following output hello world string string string sting hello world string string string string hello world string string string string is need,i raw variable store rawvariable hello world string string string sting hello world string string string string hello world string string string string is possible i store word array front back double quotes delimiter i unable use delimiter example formattedarray helloworldstring string string sting helloworld string string string string helloworldstring string string string note there different spacing including n word i storing d array formattedarray,1 normally urlconf pass requestuser extracontext urlspy access request but passwordchange like builtin views uses requestcontext render template means user object automatically passed djangocontribauthcontextprocessorsauth unless removed contextprocessors list settingspy,i url handler changing passwords urlr passwordchange authviewspasswordchange templatename accountpasswordpasswordchangeformhtml name authpasswordchange all good template loaded password changing works expected however template needs access requestuser the request object passed default template builtin authviewspasswordchange view i know authviewspasswordchange view passed extra context pass along template i know url handler i know i could write another view wraps around authviewspasswordchange i curious shortcut way within url handler can show modify current url handler pass current request object extracontext authviewspasswordchange view,1 your items class attribute appears shared instances class tile def initself type selfitems selftype type,i class map simplified enums import import globals import tile class map tiles actual map d list tile objects x rangeglobalsmapwidth rangeglobalsmapheight selftilesxyadditemitemsfoliage and class tile class tile items def initself type selftype type def additemselfi selfitemsappendi my problem items array class tile seems shared within every instanciation class for example end for loops printlenselftilesxyitems return every tile why i lists size instead printing list size loop increases can someone explan happens thanks lot help,1 there several ways eg could use f open del f if python version supports also use statement openfiletxt r f line freadlines this automatically closes file edit i get i downvoted explaining create correct way deal files maybe without assigning variable preferable,how i close file python opening way line openfiletxt rreadlines,1 it seems need split string via delimeter get every substring since interesting ones interwined whitespace def splitquotedstringss splitviaquote ssplit return splitviaquote testing appears yield correct results hello world string string string sting hello world string string string string hello world string string string string splitquotedstringa hello world omitted string,i raw variable store rawvariable hello world string string string sting hello world string string string string hello world string string string string is possible i store word array front back double quotes delimiter i unable use delimiter example formattedarray helloworldstring string string sting helloworld string string string string helloworldstring string string string note there different spacing including n word i storing d array formattedarray,1 best use context manager this close file automatically end block rely implementation details garbarge collection openfiletxt r f line freadlines,how i close file python opening way line openfiletxt rreadlines,2 i right post the difference thread threadcreatefalse crucial i define new method one selfthread thread selfdiffthread threadcreatefalse connect different slots make work,i somewhat strange problem i coding multithreaded app using signals communicate qthread data gui class data without ado simplified code class guiuimainwindowmainwindow def initself parentnone super etc selfthread thread selfconnectselfthread signalchangestatusqstring selfsetstatus qtqueuedconnection def setstatusself status selfstatusbarsettextstatus class threadqthread def initself parentnone createtrue super etc selfcreate create def runself selfcreate createdata selfcreate uploaddata def createdataself selfemitsignalchangestatusqstring changing statusbar text rest code def uploaddataself selfemitsignalchangestatusqstring changing statusbar text pretty basic right however problem selfemit works createdata function uploaddata matter function i tried putting init well i tried putting print i got status status setstatus function again works createdata function uploaddata function the differences two functions relatively minor far i tell nothing interfering selfemit function fact cases selfemit lines away function definition this really puzzling any help thanks advance edit far i tell difference two functions run first one called create parameter true second one false,1 use enumerate looping this track current item index index index x enumeratedata x none,data cat dog none turtle none newdata item data item none newdataappenddataindexitem print newdata how i go getting store new data this i want thank,3 try in data cat dog none turtle none in ival enumeratedata val none out,data cat dog none turtle none newdata item data item none newdataappenddataindexitem print newdata how i go getting store new data this i want thank,1 idx item enumeratedata item none newdataappendidx better yet use list comprehension sven answer,data cat dog none turtle none newdata item data item none newdataappenddataindexitem print newdata how i go getting store new data this i want thank,1 dataindexitem returns position first occurance item list you could simply rangelendata datai none newdataappendi give required output or check sven answer,data cat dog none turtle none newdata item data item none newdataappenddataindexitem print newdata how i go getting store new data this i want thank,1 give redis try drivers two platforms interest availablepython redis via package index r rredis cran the genius redis magically recognize numpy data type allow insert extract multidimensional numpy arrays native redis datatypes rather genius remarkable ease create interface lines code there least several tutorials redis python one degizmo blog particularly good import numpy np create data a nprandomrandint reshape couple utility functions manipulate numpy arrays prior insertion redis db compact storage amp ii restore original numpy data types upon retrieval redis db fnx lambda v mapint listv fnx lambda v joinmapstr v start redis server eg bash prompt cd usrlocalbin default install directory nix redisserver starts redis server start redis client redis import redis r redisdb port host localhost r redis insert items using redis string datatype call set database r pass key item insert rset k a rowwise insertion d array redis iterate array c rangeashape rset kformatc fnxac insert rows use mset multi set pass keyvalue mapping x dictsublist sublist enumerateatolist rmsetx retrieve row pass key get rget k retrieve entire array redis kx rkeys returns keys redis database r key kx rgetkey retrieve original form a key kx aappendfnxrgetformatkey a nparraya a array,the common sqlite interface i seen python sqlite anything works well numpy arrays recarrays by i mean one recognizes data types require inserting row row extracts numpy recarray kind like r sql functions rdb sqldf libraries anyone familiar importexportappend whole tables subsets tables r data tables,3 you need explain somewhere raw data utf letters get stripped like utf letter want strip it would also help explained elementtreewrite tostring seem choke unicode means please edit question show full error message traceback why want used function bash unicode ascii is merely overcome problems it probable feeding str objects encoded utf elementtree don feed unicode objects works e etelement root etext u joinunichri xrangex x etext u uuuuuuuu if must ascii output communicating bitwide channel ettostringe rootampampampampampampampamproot utf works ettostringe utf xml version encoding utf nrootxdxxdxxdxxdxxdxxdxxdxxdxroot you use elementtreewrite method write file preference using tostring saves doublehandling,i giant mb xml elementtree i generated somewhere raw data utf letters get stripped elementtreewrite tostring seem choke unicode even though encoding utf option tostring the docs rather limited i even sure tostring utf friendly looking source so question i strip whole elementtree nonascii characters i write monster disk took hours generate i pickled i also used function called latintoascii data def latintoasciiunicrap this takes unicode string replaces latin characters something equivalent bit ascii anything converted deleted unicode hammer approach httpcodeactivestatecomrecipeslatintoasciitheunicodehammer xlatexc a xc a xc a xc a xc a xc a xc ae xc c xc e xc e xca e xcb e xcc i xcd i xce i xcf i xd th xd n xd o xd o xd o xd o xd o xd o xd u xda u xdb u xdc u xdd y xde th xdf ss xe xe xe xe xe xe xe ae xe c xe e xe e xea e xeb e xec xed xee xef xf th xf n xf xf xf xf xf xf xf u xfa u xfb u xfc u xfd xfe th xff xa xa cent xa pound xa currency xa yen xa xa section xa umlaut xa c xaa xab xac xad xae r xaf xb degrees xb xb xb xb xb micro xb paragraph xb xb cedilla xb xba xbb xbc xbd xbe xbf xd xf x r unicrap xlatehaskeyordi r xlateordi elif ordi x pass else r stri return r nuclear option function works strings i data element i seem strip stuff i missed,1 setup funkload proxy recorder login site using browser described funkload docs httpfunkloadnuxeoorgrecorderhtml then easily check exactly sending via post you might sending params think in following example i testing django login uses crsfmiddleware also redirectto param server knows redirect login successful the test really use form sends browser would send someone if want test real form functionality best way use something like selenium i add extract crsftoken manually changes every request assert check return login page besides test like recorder autogenerated def testlogintestself the description set configuration file serverurl selfserverurl begin test tmptmpmfaheyfunkloadwatchrequest selfgetserverurl descriptionget tmptmpmfaheyfunkloadwatchrequest reply selfgetserverurl companyconfigdashboard descriptionget companyconfigdashboard csrftoken extracttokenselfgetbody name csrfmiddlewaretoken value tmptmpmfaheyfunkloadwatchrequest selfpostserverurl accountsmanagerloginnextcompanyconfigdashboard params csrfmiddlewaretoken csrftoken redirectto companyconfigdashboard email user password descriptionpost accountsmanagerlogin selfassertlogin selfgetlasturl error login tmptmpmfaheyfunkloadwatchrequest selfgetserverurl accountsmanagerlogout descriptionget accountsmanagerlogout this works following form form methodpost action input type hidden name csrfmiddlewaretoken value bbdcedaceeebadcd input typehidden nameredirectto valuecompanyconfigdashboard ididredirectto input ididemail typetext classformtxt fomsize nameemail maxlength input ididpassword typepassword classformtxt fomsize namepassword button classformbtn typesubmitvalidatebutton,i trying test functionality webapplication using funkload the page testing login form give email pwd successful redirects index page successful throws error i code selfgetserverurl login descriptionget initdefaultlogin params email xxxxgmailcom password xxxxx formname login retselfpost slogin serverurl paramsparams descriptiontesting login functionality selflogdselfgetbody whether valid email idpwd wrong one test throws return code stays login page how i test posting forms using funkload btw i tested web page mechanize script i could login routed correct index page thank,1 can subdivide area squares side minimum allowed distance points pick random for example pointbounding squares numbered j b c e f g h j then make array square indices j example randomly shuffle ending say bcjedfghai take beginning many indices need points eg bcj then place points centers maybe topleft corners chosen squares e f g h,i trying generate set points fall within range fixed area my approach given import collections random import uniform x y points radius def incirclecx cy radius x distsquared cx x cy return distsquared radius current collectionsdefaultdictlambda threshold point range points cx uniform x cy uniform y cur current incirclecurrentcur currentcur radius cx cy cx uniform x cy uniform x threshold threshold e print cannot satisfy constraints sysexit threshold currentpoint cx cy print cx cy is good way terminate algorithm without making enter infinite loop i threshold check better ways,1 this article poisson disk sampling may interesting the author explains strategy selecting points close even provides sample code languages including python the problem strategy outlined noted want select lot points want points quite far apart performance become atrocious the poisson disk scheme better performance characteristics i believe,i trying generate set points fall within range fixed area my approach given import collections random import uniform x y points radius def incirclecx cy radius x distsquared cx x cy return distsquared radius current collectionsdefaultdictlambda threshold point range points cx uniform x cy uniform y cur current incirclecurrentcur currentcur radius cx cy cx uniform x cy uniform x threshold threshold e print cannot satisfy constraints sysexit threshold currentpoint cx cy print cx cy is good way terminate algorithm without making enter infinite loop i threshold check better ways,2 this class problem known circle packing the article mathworld indicates densest known packings unit square known problem transformed one scaling x the images article demonstrate two dense sphere packings square hexagonal as whether insert new circle voronoi diagram potential useful measure maximum remaining unsampled area other approximate methods assessing unoccupied area quad trees spatial hashing may also sufficient cases,i trying generate set points fall within range fixed area my approach given import collections random import uniform x y points radius def incirclecx cy radius x distsquared cx x cy return distsquared radius current collectionsdefaultdictlambda threshold point range points cx uniform x cy uniform y cur current incirclecurrentcur currentcur radius cx cy cx uniform x cy uniform x threshold threshold e print cannot satisfy constraints sysexit threshold currentpoint cx cy print cx cy is good way terminate algorithm without making enter infinite loop i threshold check better ways,1 since pyminuit uses introspection use introspection makechisquared could implemented like import inspect chisquaredtemplate def chisquaredparamss return fdatax paramss datay errors sum def makechisquaredf datax datay errors params joininspectgetargspecfargs exec chisquaredtemplate params params return chisquared example usage import numpy def fx return ax ax ax datax numpyarange errors numpyrandomrandn datay datax errors chisquared makechisquaredf datax datay errors print inspectgetargspecchisquaredargs printing,i data fitting using pyminuit python bindings minuit minimisation code httpcodegooglecomppyminuit the minimiser accepts function uses introspection extract parameters minimised in general i want minimise chi squared value dataset given particular function describe dataset my question is way define chi squared function given arbitrary function varying numbers parameters returns function gives chi squared value function contains parameters minimised function argument specification example scipy import import minuit generate data fit datax arange noise datay datax normal noise fit function eg cubic fitfunc lambda x ax ax ax minimisation function eg chi squared note parameters minimised definition eg datax minfunc lambda sum fitfuncdatax datay noise this i like write something like minfunc makechifitfunc i know datax datay defined outside function the rest minimisation routine completeness looks like initialise minimiser object initial values minuitminuitminfunc run minimiser mmigrad print minimised values example output print mvalues thanks help advance,1 from qt documentation qthreadterminate warning this function dangerous use discouraged the thread terminated point code path threads terminated modifying data there chance thread clean unlock held mutexes etc in short use function absolutely necessary it probably much better idea rethink threading strategy eg use qthreadquit signal thread quit cleanly rather trying get thread terminate way actually calling threadexit within thread depending implemented run if like share code thread run method might hint work,i tried using selfterminate qthread class also selfthreadterminate gui class i also tried putting selfwait cases however two scenarios happen the thread terminate gui freezes waiting thread finish once thread finished gui unfreezes everything back normal the thread indeed terminate time freezes entire application i also tried using selfthreadexit no joy to clarify i trying implement userabort button gui would terminate executing thread point time thanks advance edit here run method def runself selfcreate print calling create f selfemitsignaldisablecreatebool selfcreateselfpassword selfemail selfstop selfemitsignalfinishedbool selfcompleted def stopself tried following one one together i desperate selfterminate selfquit selfexit selfstopped true selfterminated true neither works and gui class method aborting thread def onabortclickedself selfthread threadmodulethread tried following also one one altogether selfthreadexit selfthreadwait selfthreadquit selfthreadterminate again none work,2 you could manage template inheritance blocks your basehtml defines block called login surrounds html login loginhtml overrides block empty version basehtml block login login form endblock block main endblock loginhtml extends basehtml block login endblock block main real login form endblock,in urlconf i urls neatly named i reverse lookups keep everything dry all templates extend universal template named basehtml in basehtml amongst lot html framework i display login form i also specific view uses django provided authviewslogin view displays custom template loginhtml this template like others extend basehtml template in cases like i would like basehtml template would display login form loginhtml template already displaying login form in order basehtml either needs know used extend loginhtml know named url resulted basehtml extended name myapplogin can suggest way i thinking writing view call authviewslogin extra context includes suppressheaderloginform var based var basehtml template could suppress login form however i trying see nicer way accomplish,2 i know nose use globs argument testmod testfile here simple module called foobarpy note i import os usrbinpython ospipe builtin function pipe you test module like console example python python default jun gcc linux type help copyright credits license information import doctest foobar doctesttestmodfoobar fail expected os imported file foobarpy line foobar failed example ospipe exception raised traceback recent call last file usrlibpythondoctestpy line run compileflags testglobs file doctest foobar line module ospipe nameerror name os defined items failures foobar test failed failures testresultsfailed attempted import os globs os os doctesttestmodfoobar globsglobs testresultsfailed attempted win your example say globs hp healp,in doctests module i would like reference module full namespace example hpmyfunc and i would like avoid cluttering doctests writing import healpy hp doctests i run doctesttestmod i know i use globs keyword provide i run nose i use setup function is another standard way could work,1 that mainclasstopickle classtopickleclasstopickle think like when pickled class instance classtopickle classtopicklepy script pickle module pickle reference class mean pickle module name class defined executed script classtopicklepy mean module set main mean pickle module pickle mainclasstopickle and tried load pickled instance fail find instance class mainclasstopickle one imported using classtopickle import classtopickle latest classtopickleclasstopickle a fix create another script handle dumping instead classtopicklepy eg import pickle classtopickle import classtopickle namemain p classtopickle pickledumpp open pickle w,i got error i use pickle unittest i wrote program files class pickled class use class unittest testing class real codes follows respectively classtopicklepy import pickle class classtopickleobject def initself x selfx x namemain p classtopickle pickledumpp open pickle w someclasspy classtopickle import classtopickle import pickle class someclassobject def initself selfpickle pickleloadopenpickle r selfx selfpicklex print selfx name main someclass someclasstestpy import unittest someclass import someclass classtopickle import classtopickle requiredline class someclasstestunittesttestcase def testaself sc someclass selfassertequalscx def main unittestmain name main main i ran program first make pickle file and i run program file alone ie enter python someclasspy works and i run program alone ie enter python someclasstestpy also works however i run program unittest eclipsepydev returns error message error testa someclasstestsomeclasstest traceback recent call last file hometmppickleproblemsomeclasstestpy line testa sc someclass file hometmppickleproblemsomeclasspy line init selfpickle pickleloadopenpickle r file usrlibpythonpicklepy line load return unpicklerfileload file usrlibpythonpicklepy line load dispatchkey file usrlibpythonpicklepy line loadglobal klass selffindclassmodule name file usrlibpythonpicklepy line findclass klass getattrmod name attributeerror module object attribute classtopickle ran test failed errors and also i commented line import classtopickle class line program commented requiredline it work return error message described e error testa main someclasstest traceback recent call last file someclasstestpy line testa sc someclass file hometmppickleproblemsomeclasspy line init selfpickle pickleloadopenpickle r file usrlibpythonpicklepy line load return unpicklerfileload file usrlibpythonpicklepy line load dispatchkey file usrlibpythonpicklepy line loadglobal klass selffindclassmodule name file usrlibpythonpicklepy line findclass klass getattrmod name attributeerror module object attribute classtopickle ran test failed errors i guess problem namespace python i know happened exactly i resolving how i run unittest eclipsepydev program correctly run program command line without line imports classtopickle please help,3 i suggest using bitmaps slingers birds ie s b s b s b b then input data written birddata the cost function written like def costshots hit units show shot zipbirddata shots units n birds enumerateshow shot amp units hit birds hit hit return units shot return penalty hit now easy find optimal shots calculating minimum cost function itertools import product shotsequences productrangelenbirddata print mincostshots shots shots shotsequences this prints means optimum units s s fire of course solution also possible s fires s cost however since algorithm using brute force running possible shot sequences fast feasible data sets small like example,let us call problem slingerbird problem actually slinger analogous server bird request i nervous breakdown thinking i changed hoping get different perspective there s stone throwers slingers b birds the slingers within range slinging kill birds within sight slinger consume one shot one time unit i trying figure optimal solution minimizes time number shots takes kill birds given particular arrival pattern birds let give example absolute numbers slingers birds time slinger s b b b b b b s b b b bb s b b b bbbb data looks like print s b b s s b s b b b s b s b b s b s bb s s s b b s b b b b there number solutions i could think sx tk implies slinger sx takes shot time k s s s cost shots time units s s cost shots time units s s cost shots time units s cost shot time units to appears solution optimal one of course i hand possibility i may missed something i cannot think scalable way also i worried corner cases decision one shooter might alter decision others i global view may matter what fast good way solving problem python i hard time coming good data structure leave alone algorithm i thinking using dynamic programming seems involve state space exploration bit confused proceed any suggestions,1 you seem mixing python bash scripting rawinput python everything else script bash rather trying rewrite whole thing python seems like use bash maybe read command instead rawinput,i want write script wich get files input run command i first want know many files dose user ask himher upload later i want run command so i used command cnt seq similar situation long time ago i use command i get syntex error comand readnumber rawinputhow many pares cnt seq intreadnumber parecnta rawinputfilename parecnta parecntb rawinputfilename parecntb cmd samtools merge parecntbam parecnta parecntb and error i get cnt seq intreadnumber syntaxerror invalid syntax i expext put readnumber ask upload input parea pareb parea pareb parea pareb run command,1 you need parse anything suds already just access attributes object printed,if i print answer request i get following reply returncode ok vouchercode vouchertype reloadable voucherstatus ok how i parse i found solution clientlastreceived i know problematic many requests time,2 you prefill file field but i think need use one since getting file url user local machine just use normal text field url get file serverside eg using urllib form submitted,i form subject body file fields page django site if subject andor body parameters exist get i prefill form server side i want file field exactly i want url parameter requestget take file url prefill file field i googled still idea implement whether pure javascript serverside help experience possible least hard browsers due input typefile nature is fact possible implement way,1 you probably want something like pairs intrawinputhow many pairs pairn xrange pairs file rawinputpairda pairn file rawinputpairdb pairn cmd samtools merge pairdbam pairn file file ossystemcmd run command,i want write script wich get files input run command i first want know many files dose user ask himher upload later i want run command so i used command cnt seq similar situation long time ago i use command i get syntex error comand readnumber rawinputhow many pares cnt seq intreadnumber parecnta rawinputfilename parecnta parecntb rawinputfilename parecntb cmd samtools merge parecntbam parecnta parecntb and error i get cnt seq intreadnumber syntaxerror invalid syntax i expext put readnumber ask upload input parea pareb parea pareb parea pareb run command,1 most sites something like implement second form attach file doing upload via ajax means need store file server amount time original form needs reference file know done then need know delete,i form subject body file fields page django site if subject andor body parameters exist get i prefill form server side i want file field exactly i want url parameter requestget take file url prefill file field i googled still idea implement whether pure javascript serverside help experience possible least hard browsers due input typefile nature is fact possible implement way,1 oops i think i may answered question another thread lead believe udp flow control support twisted little robust actually nevertheless get need done which method twisted call socket become writable unfortunately udp protocols twisted get monitored writability premise udp always fail never raise ewouldblock except actually sometimes bug twisted i rediscovered answering question this happens twisted sending udp faster local wire speed requires fast application slow network as workaround application simply catch ewouldblock for protocol type workaround might constitute serious problem case udp already prepared lose outgoing packets need inband control flow mechanism anyway helping us get bug review process always option if want get really fancy write alternative udpport implementing ifiledescriptor rather writing udp protocol override doread dowrite called underlying socket readable writable respectively this give perfect writelevel flow control probably necessary since udp drop packets sometimes networks without ability properly process icmp source quench messages dumb firewalls configured block icmp block dropped packets source flow control information i saying fix bug twisted real fact life udp world likely reason nobody bothered yet how i call startwriting method needs called particular timeintervals limit outgoing udp bandwidth particular datagramssecond amount due limitations described part answer udp transports useful startwriting method however startwriting stopwriting really right way timelimit outgoing udp bandwidth anyway simply call selftransportwrite appropriate times scheduling said calls via appropriate scheduling mechanism loopingcall example designed invoke udp sends rtp media streaming appropriate interval transmitting sound sample but also calculate delay use calllater directly in case likely need keep around kind queue mechanism event need retransmissions outgoing data queued transport udp pop if need inbound flowcontrol udp transports still support quite nicely stopreading startreading hope answer helpful sorry i previously mislead twisted capabilities area,i class inherits twistedinternetprotocoldatagramprotocol class in startprotocol implementation i call startwriting socket gets notified time i write without blocking two questions which method twisted call socket become writable how i call startwriting method needs called particular timeintervals limit outgoing udp bandwidth particular datagramssecond amount,1 use popencommunicate instead popenwait the python documentation wait states warning this deadlock child process generates enough output stdout stderr pipe blocks waiting os pipe buffer accept data use communicate avoid dar related executables get q running interactively when syncronizing multiple processes make sure call communicate weakest link first darslave darxform dar cat this done correctly question worth noting clean shared resources the client process holding open socket darxform still reading attempting sendrecv data initial socket dar friends finished without closing socket therefore cause deadlock here working example use shelltrue netcat an advantage i secondary ports assigned dynamically therefore could conceivably serve multiple backup clients simultaneously,i trying set remote backup server dar along lines i really like piping python possible i asked separate question using netcat subprocesspopencmd shelltrue i succeeded making differential backup examples dar site the two problems i know assign port numbers dynamically way if i execute server background fails why update this seem related netcat hangs even without netcat mix here code socket import socket afinet sockstream import os sys import socketserver import subprocess class darhandlersocketserverbaserequesthandler def handleself print entering handler data selfrequestrecvstrip print got data data xform cmd nc dl darslave archivesremotehost nc l printcmd cmd nc dl darxform k archivesdiffbackup printcmd proc subprocesspopencmd shelltrue proc subprocesspopencmd shelltrue print sending port number selfrequestsend print waiting result strprocwait print ncdarslavenc returned result result strprocwait print ncdarxform returned result else result bad request selfrequestsendresult print send result exiting handler myaddress localhost def server server socketservertcpservermyaddress darhandler print listening serverserveforever def client sock socketafinet sockstream print connecting sockconnect localhost print connected sending request socksend xform print waiting response port sockrecv print got port try osunlink toslave except pass osmkfifo toslave cmd nc w localhost toslave cmd nc w localhost dar b configtestdcf a toslave c nc w localhost port printcmd proc subprocesspopencmd shelltrue proc subprocesspopencmd shelltrue print waiting result procwait result procwait print ncfifo returned strresult print ncdarnc returned strresult result sockrecv print received result sockclose print socket closed exiting name main sysargvstartswith serv server else client here happens server python clientserverpy serve amp listening entering handler got xform nc dl darslave archivesremotehost nc l nc dl darxform k archivesdiffbackup sending port number waiting stopped python clientserverpy serve here happens client python clientserverpy client connecting connected sending request waiting response got nc w localhost dar b configtestdcf a toslave c nc w localhost waiting fatal error aborting operation corrupted data read pipe ncfifo returned ncdarnc returned the client also hangs i kill keyboard interrupt,1 to avoid injections use execute place variable pass value via list tuple second parameter execute here example documentation cdbcursor maxprice cexecuteselect spam eggs sausage from breakfast where price maxprice note using comma would direct string substitution escaped don cexecuteselect spam eggs sausage from breakfast where price maxprice in addition need quotes around position holder parameter string,what safest way run queries mysql i aware dangers involved mysql sql injection however i know i run queries prevent injection variables users webclients manipulate i used write escape function apparently notdone what i use i use query inserts safely mysql database python without risking mysql injection,3 try set options pyexe bundlefiles zipfile none setup section python make single exe file without dependencies example distutilscore import setup import pyexe setup console wattpy options pyexe bundlefiles zipfile none,writing installer using pyexe needs run admin permission perform various file operations modified sample code useraccesscontrols directory comes pyexe create setup file creatingrunning generated exe works fine run computer however try run exe computer python installed get error saying import modules shutil os case exist impression pyexe automatically wraps file dependencies exe guess case pyexe generate zip file called library contains python modules apparently used generated exe basically question get imports included exe generated pyexe perhaps modification need made setuppy file code follows distutilscore import setup import pyexe the targets build create target says nothing uac on python identical asinvoker however earlier force app compatibility mode manifest exist target dictscriptfindpathpy destbasefindpath uacinforequireadministrator console hack make windows copies w tail executable windows script findpathpy uacinfo requireadministrator setup version description pyexe useraccesscontrol name pyexe samples targets build windows windows console console,1 option valueidsss soption x x x zipnumlist numlist,so i following code optionlist option valueidsss soption x x x numlist numlist what i would like values x inserted first values inserted second value x inserted third value inserted fourth,1 do mean like in l in l b c in option valueid option formati j j zipl l out option valueida aoption option valueidb boption option valueidc coption,so i following code optionlist option valueidsss soption x x x numlist numlist what i would like values x inserted first values inserted second value x inserted third value inserted fourth,1 i problem trying bind unicode parameter hy freetdssql serverinvalid data type sqlbindparameter i solved upgrading freetds version i use pyodbc i apply patch make work unicode otherwise i getting memory corruption errors occasionally,i using ubuntu i installed following package versions unixodbc unixodbcdev build tdsodbc libsybdb freetdscommon freetdsdev i configured etcunixodbcini like freetds description tds driver sybasems sql driver usrlibodbclibtdsodbcso setup usrlibodbclibtdssso cptimeout cpreuse usagecount i configured etcfreetdsfreetdsconf like global tds version client charset utf i grabbed pyodbc revision efaeadbfbafeacfbf httpgithubcommkleehammerpyodbc installed using python setuppy install i windows machine microsoft sql server installed local network listening local ip address i empty database created name common i user sa password secret full priviledges i using following python code setup connection import pyodbc odbcstring serveruidsapwdsecretdatabasecommondriverfreetds con pyodbcconnects cur concursor curexecute create table testing id integer not null identity name nvarchar null primary key id concommit everything works point i used sqlserver enterprise manager server new table now i want insert data table cur concursor curexecute insert into testing name values u something that fails here error i get pyodbcerror hy hy freetdssql serverinvalid data type sqlbindparameter since client configured use utf i thought i could solve encoding data utf that works i get back strange data cur concursor curexecute delete from testing curexecute insert into testing name values u somã© string encode utf concommit fetching data back cur concursor curexecute select name from testing data curfetchone print typedata data that gives error data returned data sent i get type unicode somãƒâ© string that pyodbc accept unicode object directly returns unicode objects back and encoding mixed now question i want code insert unicode data nvarchar andor ntext field when i query back i want data i inserted back that configuring system differently using wrapper function able convert data correctly tofrom unicode inserting retrieving that asking much,1 i assuming know numbers give example starting algorithm get finishing etc i also assume two slingers fire though matter much at first choice assign value cell amountofbirdsincelltime this gives two cells values st st rest lower only time last cell counts score picking earliest one remove time next round making valuable time that first pick now remove birds killed first pick cells repeat value determining process remaining cells in example cell st give highest result repeating process get valuable cells earliest times one important bit example cover if first valuable pick next valuable pick might take account however since already confirmed take time account value i never written python i algorithm tag javaclike pseudo code highestcelltime whilebirdsremain bestcell forevery cell picked yet currentcellvalue amountofbirds ifcurrentcelltime highestcelltime currentcellvalue currentcellvalue currentcelltime ifcurrentcellvalue bestcellvalue bestcell thiscell else ifcurrentcellvalue bestcellvalue ampamp currentcelltime bestcelltime bestcell thiscell addcelltopicksbestcell removebirdsfromothercellsbestcellbirds unless i forgot something optimal combination cells picks collection i hope code makes sense python programmer if someone translate please and please remove bit text earlier mention javacpseudocode edit op first version end best cells i guessing must bug code nevertheless i posting import math cellsnotpicked range celltobird picks def getcellvaluecell return lencelltobirdcell def getcelltimecell return intmathfloorcell birdsremain whilebirdsremain bestcell thiscell cellsnotpicked currentcellvalue getcellvaluethiscell currentcelltime getcelltimethiscell highestcelltime getcelltimebestcell ifcurrentcelltime highestcelltime currentcellvalue currentcellvalue currentcelltime ifcurrentcellvalue getcellvaluebestcell bestcell thiscell elif currentcellvalue getcellvaluebestcell currentcelltime getcelltimebestcell bestcell thiscell picksappendbestcell cellsnotpickedremovebestcell birdstoremove celltobirdbestcell key celltobird bird birdstoremove try celltobirdkeyremovebird birdsremain except pass print picks,let us call problem slingerbird problem actually slinger analogous server bird request i nervous breakdown thinking i changed hoping get different perspective there s stone throwers slingers b birds the slingers within range slinging kill birds within sight slinger consume one shot one time unit i trying figure optimal solution minimizes time number shots takes kill birds given particular arrival pattern birds let give example absolute numbers slingers birds time slinger s b b b b b b s b b b bb s b b b bbbb data looks like print s b b s s b s b b b s b s b b s b s bb s s s b b s b b b b there number solutions i could think sx tk implies slinger sx takes shot time k s s s cost shots time units s s cost shots time units s s cost shots time units s cost shot time units to appears solution optimal one of course i hand possibility i may missed something i cannot think scalable way also i worried corner cases decision one shooter might alter decision others i global view may matter what fast good way solving problem python i hard time coming good data structure leave alone algorithm i thinking using dynamic programming seems involve state space exploration bit confused proceed any suggestions,1 what import numpy np abc rnprandomrandom w rabc v rac z npsumwvnpnewaxisaxis doesn use loops newer features reasonably fast comparing zloop jf sebastian post print npsumnpabszzloopwv gives e,hi im tying multiply tensor matrix following fashion dimensions w x b x c v x c i want z zidotwivi z dimension x b x c c x x b ive tried numpytensordot havent able can i want if i without loops basically equivalent def fwv z rangelenw zappenddotwivi return z thanks edit specifically achievable tensordot,1 a pygtk type used type pygtk property to known gobject type system type registered i think actually call function pygtk probably done automatically call gobjectinit sometimes pygtk docs succinct in case might want read c docs,in pygtk gobjecttyperegister the documentation merely says registers specified python class pygtk type well duh what registering class pygtk type,2 i would use python json encoder validate first json feeding xml parser try jsonloadsjsontotest except valueerror print invalid json,i working somewhat nonstandard soap webservice most calls webservice return standard soap xml would expect one call particular returns json string instead this fouls xml parser client side my question way designate return type particular webmethod suds try run xml parser i want raw json response,1 as expansion bruno answer mysql client library may support several different formats specifying named parameters from pep dbapi could write queries like qmark cursorexecuteselect spam from eggs where lumberjack lumberjack numeric cursorexecuteselect spam from eggs where lumberjack lumberjack named cursorexecuteselect spam from eggs where lumberjack jack jack lumberjack format cursorexecuteselect spam from eggs where lumberjack lumberjack pyformat cursorexecuteselect spam from eggs where lumberjack jacks jack lumberjack you see client library supports looking paramstyle modulelevel variable clientlibraryparamstyle pyformat any options do the right thing regards handling possibly insecure data as bruno pointed please ever try insert parameters the commonlyused client libraries much better processing data correctly mere mortals ever,what safest way run queries mysql i aware dangers involved mysql sql injection however i know i run queries prevent injection variables users webclients manipulate i used write escape function apparently notdone what i use i use query inserts safely mysql database python without risking mysql injection,3 it appears updatetype returns none could use anycellupdatetypenextcellscellindex cell cells unless problem normal loop stick it readable optimize prematurely you use map way avoid using python function lambda expression get speed advantage normal loop you use list comprehension needlessly accumulating list return values updatetype even though ignoring use instead,i looping array objects calling method like cell cells cellupdatetypenextcellscellindex is way equivalent map,3 use scrapy base work httpscrapyorg for uploading script performance output web interface i assume need write custom web front end stores information database explore one option pyramid httppypipythonorgpypipyramid for python cloud deployments see heroku httpwwwherokucom,i planning develop webcloud application using python following upload perlpython scraping scripts execute uploaded scripts run schedule run multiple instance script different input parameters measure scripts performance view scripts standard outputlog i got limitedno knowledge technologies satisfy requirement tips pointers ideas existing work libraries open source implementation etc appreciated thanks rajesh,1 see data go away hint commit needed,cexecutedelete from data where user and machine user machine i two variables sent get technically machineuser i split variable based plus respectively assigned variables machine user theoretically script work correct what i incorrectly it delete record i wish would,1 as first second questions dict list etc types already threadsafe you add thread safety however may find useful it decorator basically implements synchronized keyword java using function scope define critical section using similar approach possible author threadingcondition oriented decorator also import threading def tryfinallyfinallyf ureturns decorator adds tryfinally behavior given noargument call finally def decoratorcallable def executeargs kwargs try result callableargs kwargs finally finallyf return result return execute return decorator def usinglocklock ureturns decorator whose argument acquire given lock executing def decoratorfunction body tryfinallylockreleasefunction def executeargs kwargs lockacquire return bodyargs kwargs return execute return decorator def synchronizedfunction udecorator one thread enter decorated function time recursion ok return usinglockthreadingrlockfunction use like beware deadlocks overuse synchronized def fooargs print only one thread enter function time on third question python tutorial states search order inherited attributes depthfirst leftfirst so inherit myclass dict setitem method myclass used in older versions python section tutorial implied choice arbitrary nowadays appears quite deliberate i guessing freudian slip semicolon posted source new python experienced either java c if need keep mind attribute method resolution occurs run time python classes well instance firstclass objects inspectedexplored run time first instance attribute dictionary searched class attributes parent class search algorithm starts this done conceptually equivalent repeated hasattrclassorinstance attribute calls the confirms newstyle classes classes inherit object x language specification optional resolution occurs time attribute looked it done class subclass created instances created this done release class fooobject def bazself print original foobaz class barfoo pass def newprintself print new foobaz x foo bar foobaz newprint foo b bar maplambda k kbaz x b new foobaz new foobaz new foobaz new foobaz none none none none replacing method class foo changes behavior subclasses already defined instances already created,i two questions creating thread safe types python one related question multiple inheritance are problematic implications using following subclasses threaded application sort lazy threadsafe type i realize whomever sets values may altered threads bears responsibility ensure values thread safe well another question i exists prudent alternatives types within python typical installation example threading import lock future import withstatement class safedictdict def initselfargskwargs selfmylocklock supersafedict selfinitargs kwargs def setitemselfargskwargs selfmylock print debug overloaded setitem lock supersafedictselfsetitemargskwargs class safeobjectobject mylock lock temporary useless lock proper instance def initselfargskwargs selfmylocklock supersafeobject selfinitargs kwargs def setattrselfargskwargs selfmylock print debug overloaded setattr lock supersafeobjectselfsetattrargskwargs if types defined could considered reasonably safe negative implications would faced using multiple inheritance create type supported mixture modifications example inherit classes optimal order example class safedictsafeobjectdict def setitemselfargskwargs selfmylock print debug overloaded setitem lock supersafedictselfsetitemargskwargs edit just another example another type inheriting former types testing using ipython in class safedictsafeobjectsafedict pass in safedict debug overloaded setattr lock debug overloaded setattr lock in da debug overloaded setattr lock in b debug overloaded setitem lock in out b,1 don use slice rather simple index channel ndarr this actually behaves slicing indexing normal python lists using slice length one results sublist using simple indexing results element returned,i trying channel compare two numpy arrays generated opencv python bindings so i mask arrayimagechannel shape x i want compare channel rgb arrayimage shape xy having halfway wrapped head around numpy slicing i get closer i want channel ndarrii channel i want returns ndarray shape xy rather xy i need is elegant way single slicing operation failing simplest way,2 for closest thing starting java jar file app new feature python executable zip files directories python myappzip where myappzip zip containing mainpy file executed script file executed your package dependencies also included file mainpy mypackageinitpy mypackagesomeliblibfilepy you also execute egg incantation nice bourn shell derivatives linuxosxunix pythonpathmyappegg python myapp rem windows set pythonpathmyappegg python myapp this puts myappegg python path uses argument run module your myappegg likely look something like myappinitpy myappsomelibfilepy and python run initpy check file main app command line use egg files zip files might able add mainpy egg zip tool make executable python run like python myappegg instead incantation pythonpath environment variable set more information executable zip files including make directly executable shebang found michael foord blog post subject,i questions egg files python i much python code organized package i trying create egg files i following instructions common according seems i need setuppy file would please tell i need put setuppy file reside i suppose enough create setuppy start setuppy bdistegg getting egg file could please confirm is possible include pyc files egg file having egg file i start code without unpacking like java jar jar file,3 the value int float savetxt requires array you want create numpy array integration results save end using savetxt i think something like trick intarray applyalongaxistrapz data savetxt inttxt intarray keep mind along original example sum time fields rather integrating across time this yield valid results spacing along xaxis otherwise want something like data intarray applyalongaxistrapz data savetxt inttxt intarray assuming time fields numeric edit further explanation nd code section follows you using trapezoidal rule integrate variety values integration approximation technique works summing average successive yvalues curve multiplied change x two yvalues this amounts calculating area trapezoid connects two yvalues xaxis like it completely clear question seemed integrating values across time xaxis would represent time the xvalues need incorporated get correct area trapezoid area trapezoid x x final integration result sum areas the simplest way incorporate xaxis values pass trapz function x parameter see docstring in example i used data array x values suchly another caveat spacing x values x x constant save calculation pulling summation simply multiplying end this functionality available trapz function dx parameter so time measurements taken every seconds example could replace nd line nd example intarray applyalongaxistrapz data none hope helps,to this question pertains ms research i what i want seemingly simple i text file values time values i want integrate values times save value text file numpy import pylab import import os sys shutil import math load data data loadtxt whtxt open file save plots shutilrmtreewhfiles osmakedirswhfiles oschdirwhfiles range int trapzdataiaxis print int savetxt inttxt int when i run i get following error file integralpy line savetxt inttxt int file libraryframeworkspythonframeworkversionslibpythonsitepackagesnumpylibnpyiopy line savetxt ncol xshape indexerror tuple index range i trying solve problem days yet find solution i appreciate helpcomments give,1 getorcreate returns tuple consisting object created to get model use mymodel mymodelobjectsgetorcreatedatedate dayday timetime mymodel mymodelobjectsgetorcreatedatedate dayday timetime,having little django problem stuck my model class mymodelmodelsmodel user modelsmanytomanyfielduser my attempt create new user mymodel mymodelobjectsgetorcreatedatedate dayday timetime this one gives solid mymodel object play mymodeluseradduser user instance django user system when trying execute throws tuple object attribute user did accidentally turn tuple,3 since homework i refrain giving code outright you create dict works lookup table name key phone number value creating lookup table you easily convert parallel arrays dict using dict zip something along lines lookup dictzippeople phonenumbers to see works look example people john jacob bob phonenumbers zippeople phonenumbers john jacob bob dictzippeople phonenumbers jacob bob john finding person exist you quickly figure person key exist lookup table using name lookup phone number lookupname list people whose name matches substring this answer put right track and course search returns empty list matching names display appropriate message alternative suggestion another approach search list directly obtain index matches use retrieve phone number i offer example leave expand viable solution people john jacob bob jacklyn cojack samantha x x enumeratepeople jac x jacob jacklyn cojack if hit snag along way share done glad assist good luck fun response updated question note i provided two alternative solutions one using dict lookup table another searching list directly your updates indicate trying mix solutions together necessary if need search names substring matches might better second solution searching listdirectly the code example i provided returns list since may one name contain substring item tuple index name you need iterate throught list extract index name you use index retrieve phone number to avoid giving solution related example people john jacob bob jacklyn cojack samantha matches x x enumeratepeople jac x index name matches print index name jacob jacklyn cojack matches x x enumeratepeople doesnotexist x matches print matches matches,this homework question i got basics i seem find correct method searching two parallel arrays original question design program two parallel arrays string array named people initialized names seven people string array named phonenumbers initialized friends phone numbers the program allow user enter person name part person name it search person people array if person found get person phone number phonenumbers array display if person found program display message indicating my current code create main def main take name part persons name person rawinputwho looking n convert string lowercase easier searching person personlower run people search person parameters peoplesearchperson create module search people list def peoplesearchperson create list names people people john tom buddy bob sam timmy ames create list phone numbers indexes corresponding names people phonenumbers etc phonenumbers now entire problem begins how i conduct search partial search name return index persons name people array print phone number accordingly update i added bottom code order conduct search lookup dictzippeople phonenumbers person lookup print name person nphone lookupperson but works full matches i tried using get partial match x x enumeratepeople person x but i search tim example returns timmy how i get index apply print phonenumbers index returned search update finally got work perfectly used code conduct search person people list search x x enumeratepeople person x person matches search print name phone index person search print name phone person matches search print name person nphone phonenumbersindex nothing matches search search display message saying matches print no matches,3 just write import random def shufflex x listx randomshufflex return x x range shufflex print x print,is straightforward way return shuffled array python rather shuffling place eg instead x array randomshufflex i looking something like shufflex maintains x note i looking function something like xarray yx randomshufflex,3 you may better results replacing ossystem calls subprocess the subprocess module allows spawn new processes connect inputoutputerror pipes obtain return codes this module intends replace several older modules functions ossystem osspawn ospopen popen commands see also pep – pep proposing subprocess module,currently i exe i need pass commands thru python the code worked when i merged snippet final program failed work basically first two files upload using program shellstart upload f program passing commands python decides skip final upload bottom program called shellforward the final upload files program shellforward even work so main question confused program shellstart finishes uploading two commands files python shell allow type anything it acts like command prompt window let type anything code executed that i feel ctrlc needed terminate shellstartexe previous process python might let type execution here code import os time name rawinputinput name apn rawinputinput apn name ecid rawinputinput ecid name kernel rawinputinput kernel name ossystem shellstartexe f name timesleep ossystem shellstartexe f apn timesleep ossystem shellforwardexe imagefile myfileimg ecid xs kernel ys x ecid kernel,1 there function looking just copy list,is straightforward way return shuffled array python rather shuffling place eg instead x array randomshufflex i looking something like shufflex maintains x note i looking function something like xarray yx randomshufflex,2 it would pretty simple implement using random i would write follows def shufflel l l copy l l randomshufflel shuffle l return l return shuffled l,is straightforward way return shuffled array python rather shuffling place eg instead x array randomshufflex i looking something like shufflex maintains x note i looking function something like xarray yx randomshufflex,3 i thought i could hack something together minutes formatting text columns difficult i thought however i got far still pretty buggy class formatlinesobject text goes nd column text but really text goes hard add text column given format another point text def initself args kargs selfmaxcharwidth selfgutterwidth selfgutter selfgutterwidth selfpreviousline none selfpreviousline none selfpindex selfpindex print args print len args lenargs lenargs print starting test selfprintlinesargs args def printlinesself p p selfpindex lenpsplit selfformatlinep p pthis p pthis p print line problem format going messup words pushing next line could fixed function could rewritten def formatlineself p p must first figure amount words fit line pwords pwords p pwords psplit pwords pwordsselfpindex p pwords psplit pwords pwordsselfpindex format left side output loutput pwords lenloutput selfmaxcharwidth word enumeratepwords lenloutput lenword selfmaxcharwidth loutput formatword selfpindex else break selfpindex loop iteration starts index required elif lenloutput selfmaxcharwidth longword longwordappendloutputlenloutput longwordappendloutputlenloutput longword pwordslongword pwordsinsert longword p joinpwords else left output single word equal maxcharwidth pass need add index least element list going printed selfpindex format right side output routput pwords lenroutput selfmaxcharwidth word pwords lenroutput lenword selfmaxcharwidth routput formatword else break selfpindex elif lenroutput selfmaxcharwidth longword longwordappendroutputlenroutput longwordappendroutputlenroutput longword pwordslongword pwordsinsert longword p joinpwords else right output single word equal maxcharwidth pass selfpindex determin gutter size lenloutput selfmaxcharwidth loutput selfmaxcharwidthlenloutput need append spaces right hand size output previousline defined way previousline defined selfpreviousline must first line bullet point output formatselfgutter loutput selfgutter routput selfpreviousline loutput selfpreviousline routput else pwidth lenselfpreviousline pwidth lenselfpreviousline loutputpwidth loutput lenselfpreviouslinepwidth routputpwidth routput lenselfpreviouslinepwidth output formatselfgutter loutput selfgutter routput retval line output p joinpwords p joinpwords return retval name main long line text much larger fit one line another long line line little different first line test formatlinest,i trying nicely format text data database send emails django i encountering problems strings line breaks in particularmy desired output tcontinue tend tend scontinue send here strings taken database tntcontinuentend tntend snscontinuensend this desired output like see columns excel what i want say strings contain line breaks simple formatting print strindex col col work please share approach many thanks,1 well load image grayscale actually read bits per pixel bit float values here would imgf cvcreateimage cvgetsizeimg cvipldepthf cvscaleimg imgf also look dftpy example this give feel use dft well,i trying use opencv python wrapper calculate dct image supposedly images numpy arrays cv matrices i thought work import cv img cvimread myimagejpg cvcvloadimagegrayscale img cvdctimg however throws error cverror usrlocallibopencvmodulescoresrcdxtcpp error type cvfc type cvfc function dct i realize error means input either bit bit singlechannel floating point matrix however i thought image loaded specifying grayscale least close enough cv able figure conversion what appropriate way convert image dct using cv,1 try httpwikipythonorgmoinmacpythonbundlebuilder httpwikipythonorgmoinmacpythonpyapp,i want create command line app would run terminal mac os x eventually platforms i make python script running terminal etc problem comes user i like user download app install one normally would call app perhaps typing appname directly terminal how would i go would i need wrap python file kind objectivec mini app install thanks,1 to prevent chameleon escaping result variable need use structure result per documentation httpchameleonreadthedocsorgenlatestreferencehtmlstructure,i really new pyramid pretty new web frameworks general i trying get stage i return raw html view i markup data returned mongodb store my initpy pyramid project standard def mainglobalconfig settings this function returns pyramid wsgi application config configuratorrootfactory root settings settings configaddview hermeswebviewsmyview context hermeswebresourcesroot renderer hermeswebtemplatesmytemplatept configaddstaticview static hermeswebstatic cachemaxage viewsmydb connect connect mongodb my templatesmytemplatept looks like doctype html public wcdtd xhtml stricten httpwwwworgtrxhtmldtdxhtmlstrictdtd html xmlnshttpwwwworgxhtml xmllangen xmlnstalhttpxmlzopeorgnamespacestal headtitlemy test title titlehead body div hperform searchh form methodget action div input typetext nameid div input typesubmit valuesubmit form hresultsh results div body html finally viewspy looks like mydb ref database assigned startup def myviewrequest key requestgetget id none results key dbres mydbcallsomefindfunctionkey data dbres results li li results data results ul ul results return results results when i insert term form myview function gets called database queried correct results get pulled however rather string returned turning html webpage printed string webpage instead i suspect something content type but i really understand pyramid well enough yet can someone explain get return html interpreted browser html rather string extra question i even using viewspy type database call i still confused whole root object comes i using mongodb database backend,3 udp datagrams cannot partially deliveredâ¹ delivered asis so yes sure received datagram sent exactly see receiver end edit incorporate will comment best kind correct ie technically â¹they fragmented ip level network stack receiver side either fully reassemble datagram pass listening process sent acknowledge data received,most datagram receiving functions c recv read javas datagrampacket class pythons socketserver include possibility find amount received data c int amount recvsock buf n msgwaitall java int amount datagramsocketgetlength python class myudphandlersocketserverbaserequesthandler def handleself amount len selfrequest are reliable or possible parts message received due example packet fragmentation network delay in words when i send variable length chunk data via udp receive end amount values exactly equal size original chunk edit ninjalj made good point i want include what happens receiving function interrupted instance signal what happens two threads simultaneously try receive socket,3 you may want check imapclient library gets rid lot frustrations dealing imap this would get emails attachments using imapclient imapclient import imapclient host imapgmailcom username password ssl true server imapclienthost useuidtrue sslssl serverloginusername password serverselectfolder inbox messages serversearch xgmraw hasattachment print messages attachments lenmessages print print uids messages attachments print messages result messages attachments uids messages attachments l,how find emails attachments gmail account using imap access i python way check message thanks,3 it sounds like need anchor regex unless i understanding properly mylist var var varsomething vartext varvar import r recompiler var matches item item mylist rmatchitem print matches var so var match exactly var vartext varvar is i suppose one way handle edit would wvarw var variable name want the w shorthand character class matches anything w class w python basically alphanumeric characters plus underscore the means may matched zero times this results variablelist var var var varmore r recompiler wvarw matches item item variablelist rmatchitem print matches var var var if want name variable without extraneous stuff capture extract first capture group something like maybe probably bit inefficient since regex runs twice matched items r recompiler wvarw matches rmatchitemgroup item variablelist rmatchitem print matches var var var,like many people posting questions i recently started programming python i faced problem trying define regular expression extract variable name i list variable names saved list string i parsing part code i take line line file i make list variables variablelist var var varmore var varmore what i want define recompile something say found two var i want make exact match according example var match nothing var match first element list i presume answer may combining regex negation regex i sure solve problem ok i noticed i missed one important thing variable list gathered string possible space var name sign more accurate variablelist would something like variablelist var var var varmore in case recognize first last one var,1 this optimal assignment problem slingers kill birds view you twodimensional objective function number tradeoffs shots time determining minimum number shots particular time limit exactly set cover problem mhum suggests the set cover problem nphard hard approximate practice branch bound using dual linear programming formulation quite effective finding optimum,let us call problem slingerbird problem actually slinger analogous server bird request i nervous breakdown thinking i changed hoping get different perspective there s stone throwers slingers b birds the slingers within range slinging kill birds within sight slinger consume one shot one time unit i trying figure optimal solution minimizes time number shots takes kill birds given particular arrival pattern birds let give example absolute numbers slingers birds time slinger s b b b b b b s b b b bb s b b b bbbb data looks like print s b b s s b s b b b s b s b b s b s bb s s s b b s b b b b there number solutions i could think sx tk implies slinger sx takes shot time k s s s cost shots time units s s cost shots time units s s cost shots time units s cost shot time units to appears solution optimal one of course i hand possibility i may missed something i cannot think scalable way also i worried corner cases decision one shooter might alter decision others i global view may matter what fast good way solving problem python i hard time coming good data structure leave alone algorithm i thinking using dynamic programming seems involve state space exploration bit confused proceed any suggestions,2 there direct way disable init ways work around one flag class class initalready false initself classinitalready classinitalready true but ugly what really trying accomplish,is way call init method class one time or i disable calling init i create object class,1 if want singleton ever one instance class create decorator like following gotten pep def singletoncls instances def getinstance cls instances instancescls cls return instancescls return getinstance singleton class myclass pass try myclass b myclass b true,is way call init method class one time or i disable calling init i create object class,3 you put anything init want run each time create instance class init run if want customize creation class look creating metaclass basically lets define function run class first defined,is way call init method class one time or i disable calling init i create object class,1 in addition bundlebuilder pyapp i thought i would mention pyinstaller it cross platform seems support large packages eg pyqt matplotlib better pyapp,i want create command line app would run terminal mac os x eventually platforms i make python script running terminal etc problem comes user i like user download app install one normally would call app perhaps typing appname directly terminal how would i go would i need wrap python file kind objectivec mini app install thanks,1 my view bad practice the object know messing attributes consider example would happen profile later expanded attribute called age unrelated page code if want add attributes subclass profile external mapping profiles object custom attributes,in python assign arbitrary attribute outside defining class class profilemodelsmodel user modelsonetoonefielduser name modelscharfieldmaxlength p profile page the underlying mechanism dict attribute maintains dictionary attributes we told expose inner workings client code attaching new data encapsulation right is idiom common python code just what i mean… each tweet standard fields like id text owner when returning tweet list user want display tweet “favorited” user obviously obtain isfavorite need query manytomany relationship user would ok prefill tweet objects isfavorite corresponding current user sure i could expose method isfavoriteforuser i hitting django template language limitations allow call methods arguments inside template also i believe template calling methods i know work fine i wonder something like open source project would get developers look contempt sidenote i come cnet background dynamic types introduced recently adapted widely except niche areas interoperability ioc frameworks rest client frameworks etc,3 i think answer it depends first really want prevent defining slots class and generally good practice add attributes actually defined class confusing someone reading code rarely useful but certain times useful able python documentation discusses way get something similar c struct pascal record see httpdocspythonorgtutorialclasseshtml section odds ends,in python assign arbitrary attribute outside defining class class profilemodelsmodel user modelsonetoonefielduser name modelscharfieldmaxlength p profile page the underlying mechanism dict attribute maintains dictionary attributes we told expose inner workings client code attaching new data encapsulation right is idiom common python code just what i mean… each tweet standard fields like id text owner when returning tweet list user want display tweet “favorited” user obviously obtain isfavorite need query manytomany relationship user would ok prefill tweet objects isfavorite corresponding current user sure i could expose method isfavoriteforuser i hitting django template language limitations allow call methods arguments inside template also i believe template calling methods i know work fine i wonder something like open source project would get developers look contempt sidenote i come cnet background dynamic types introduced recently adapted widely except niche areas interoperability ioc frameworks rest client frameworks etc,1 if attribute sometimes risk getting attributeerror nowhere one object code worked fine another object class yes exact types important ducktyping objects class frequently assumed duck type even happen sure looking part code much harder check case so makes code less reliable then option providing default attribute class attribute property assigning object attribute differs default but stuff expected vary per object clarity every attribute ever listed init usually outweights potential advantages delaying instance attribute access that say acceptable make compelling argument considered good idea,in python assign arbitrary attribute outside defining class class profilemodelsmodel user modelsonetoonefielduser name modelscharfieldmaxlength p profile page the underlying mechanism dict attribute maintains dictionary attributes we told expose inner workings client code attaching new data encapsulation right is idiom common python code just what i mean… each tweet standard fields like id text owner when returning tweet list user want display tweet “favorited” user obviously obtain isfavorite need query manytomany relationship user would ok prefill tweet objects isfavorite corresponding current user sure i could expose method isfavoriteforuser i hitting django template language limitations allow call methods arguments inside template also i believe template calling methods i know work fine i wonder something like open source project would get developers look contempt sidenote i come cnet background dynamic types introduced recently adapted widely except niche areas interoperability ioc frameworks rest client frameworks etc,1 similar application keeping track progress loop i simply used pythonprogressbar their example goes something like progressbar import simple progress bar widgets test percentage barmarker left right eta filetransferspeed see docs options pbar progressbarwidgetswidgets maxval pbarstart range something long iteration pbarupdatei adds little symbol iteration pbarfinish print,how i use progress bar script task likely take time for example function takes time complete returns true done how i display progress bar time function executed note i need real time i figure do i need thread i idea right i printing anything function executed however progress bar would nice also i interested done code point view,3 you might able extra like something like blogobjectsextra select entrycount select count from blogentry where blogentryblogid blogblogid orderby entrycount i tested work the caveat work relational database,i using tastypie create json django models however i running problem i think simple fix i object blogs wich comment object children i want able something like json apivblogsorderbycommentcount but i figure sort field part original comment blog model i create commentcount dehydrate method takes array comments returns commentscount any help would much appreciated i seem find explanation,1 unfortunately satchmo uses sorlthumbnail version docs my guess support formats version x i luck finding docs probably dig code sure if i remember correctly swap library version go templates use template tag add endthumbnail tag time used endtag used back version x,someone please give example change sorlthumbnail format django template tag i read documentation httpthumbnailsorlnettemplatehtmlthumbnail tried various ways implimenting avail i get errors similar thumbnail tag received bad argument format my code works fine without formatpng part makes jpg thumbnail however i want png thumbnail thumbnail productmainimagepicture x formatpng image also adding thumbnailformat png settingspy nothing thanks update here how i fixed the problem so issac zachwood right this version dependent thing i resolved problem way upgrade newest sorl syncdb settings changed thumbnaildebug true added closing tag templates looked like thumbnail productmainimagepicture x formatpng image img src mediaurl image width imagewidth height imageheight alt productshortdescription endthumbnail it worked,2 create file called configpy paste follwing rã©cupã©ration du fichier de config ã partir des paramã¨tres du script import sys lensysargv configfile sysargv else configfile fconfigxml variables environnement du script server admincontrolquerynames node admincontrolgetnode typeserver servername admincontrolgetattributeserver name nodename admincontrolgetnode cellname admincontrolgetcell scope ã remplacer par clusterclustername lorsqu applicable scope node nodename server servername scopealt scope node nodename server servername scopeconfig servercells cellname nodes nodename servers servername serverxml scoperesources cells cellname nodes nodename servers servername resourcesxml authprefix nodename fonctions utilitaires def getattributedxmlelement name default xmlelementhasattributename return xmlelementgetattributename return default def getattributexmlelement name return xmlelementgetattributename regbuses def addbusbus regbusesbus name bus def getbusbusname return regbusesbusname regdataproviders def getdataprovideridprovidername providername regdataproviderskeys return regdataprovidersprovidername ps adminjdbclistjdbcprovidersprovidername lenps p ps else printjdbc provider non trouve providername p providername regdataprovidersprovidername p return p lecture du fichier de config print lecture du fichier de config configfile import javaxxmlparsersdocumentbuilderfactory documentbuilderfactory dbf documentbuilderfactorynewinstance db dbfnewdocumentbuilder document dbparseconfigfile config documentgetdocumentelement jvm properties jvm adminconfiglist javavirtualmachine props configgetelementsbytagname property rangepropsgetlength xmle propsitemi propname getattributexmle name propvalue getattributexmle value propdesc getattributedxmle description proprequired getattributedxmle required false print creation de la propriete jvm propname adminconfigcreate property jvm validationexpression name propname description propdesc value propvalue required proprequired authentication auths configgetelementsbytagname authentication rangeauthsgetlength xmle authsitemi name getattributexmle name user getattributexmle user pwd getattributexmle password desc getattributedxmle description print creation de l authentification name admintaskcreateauthdataentry alias name user user password pwd description desc jdbc providers providers configgetelementsbytagname jdbcprovider rangeprovidersgetlength xmle providersitemi name getattributexmle name shortname getattributedxmle shortname name dbtype getattributexmle databasetype providertype getattributexmle providertype implementationtype getattributexmle implementationtype classpath getattributexmle classpath nativepath getattributexmle nativepath desc getattributedxmle description print creation du fournisseur jdbc name admintaskcreatejdbcprovider scopealt databasetype dbtype providertype providertype implementationtype implementationtype name name description desc classpath classpath nativepath nativepath jdbc datasources dss configgetelementsbytagname jdbcdatasource rangedssgetlength xmle dssitemi name getattributexmle name jndiname getattributexmle jndiname providername getattributexmle jdbcprovider auth getattributexmle authentication dbname getattributexmle database dbhost getattributexmle host dbport getattributexmle port datastorehelperclassname getattributedxmle datastorehelperclassname comibmwebspherersadapterdbuniversaldatastorehelper print creation de la source de donnã©es name providerid getdataprovideridprovidername authx authprefix auth admintaskcreatedatasourceproviderid name name jndiname jndiname datastorehelperclassname datastorehelperclassname containermanagedpersistence false componentmanagedauthenticationalias authx xarecoveryauthalias authx configureresourceproperties databasename javalangstring dbname drivertype javalanginteger servername javalangstring dbhost portnumber javalanginteger dbport internal amp external buses jms buses configgetelementsbytagname internalbus rangebusesgetlength xmle busesitemi busname getattributexmle name busdesc getattributedxmle description logsize getattributedxmle logsize minstoresize getattributedxmle minstoresize maxstoresize getattributedxmle minstoresize unlimitedstoresize getattributedxmle unlimitedstoresize false print creation du bus interne busname admintaskcreatesibus bus busname description busdesc bussecurity false admintaskaddsibusmember bus busname scope filestore logsize logsize minpermanentstoresize minstoresize maxpermanentstoresize maxstoresize unlimitedpermanentstoresize unlimitedstoresize mintemporarystoresize minstoresize maxtemporarystoresize maxstoresize unlimitedtemporarystoresize unlimitedstoresize bus bus name busname bus type internal addbusbus buses configgetelementsbytagname externalbus rangebusesgetlength xmle busesitemi bus busname getattributexmle name print creation du bus externe busname bus name busname bus type external bus manager getattributexmle manager bus host getattributexmle host bus port getattributexmle port bus channel getattributexmle channel addbusbus jms connections factories wmqres websphere mq jms provider scoperesources builtinmqprovider cfs configgetelementsbytagname jmsconnectionfactory rangecfsgetlength xmle cfsitemi busname getattributexmle bus jmstype getattributexmle jmstype cfname getattributexmle name cfjndiname getattributexmle jndiname cfdesc getattributedxmle description nonpersistentmappinggetattributedxmle nonpersistentmapping expressnonpersistent persistentmappinggetattributedxmle persistentmapping reliablepersistent wmqtransporttypegetattributedxmle wmqtransporttype bindingsthenclient print creation de la fabrique de connection jms cfname bus getbusbusname bus type internal admintaskcreatesibjmsconnectionfactoryscopeconfig type jmstype name cfname jndiname cfjndiname description cfdesc category busname busname nonpersistentmapping nonpersistentmapping readahead default tempqueuenameprefix target targettype busmember targetsignificance preferred targettransportchain providerendpoints connectionproximity bus authdataalias containerauthalias mappingalias sharedatasourcewithcmp false logmissingtransactioncontext false managecachedhandles false xarecoveryauthalias persistentmapping persistentmapping consumerdoesnotmodifypayloadafterget false producerdoesnotmodifypayloadafterset false else jmstype topic cftype tcf else cftype tcf admintaskcreatewmqconnectionfactorywmqres type cftype name cfname jndiname cfjndiname description cfdesc qmgrname bus manager wmqtransporttype wmqtransporttype qmgrhostname bus host qmgrportnumber bus port qmgrsvrconnchannel bus channel destinations jms dests configgetelementsbytagname jmsdestination rangedestsgetlength xmle destsitemi busname getattributexmle bus jmstype getattributexmle jmstype destname getattributexmle name destjndiname getattributexmle jndiname destdest getattributexmle destination destdesc getattributedxmle description reliability getattributedxmle reliability expressnonpersistent deliverymode getattributedxmle deliverymode nonpersistent print creation de la destination jms destname bus getbusbusname bus type internal jmstype queue sibtype queue elif jmstype topic sibtype topic admintaskcreatesibdestination bus busname name destdest type sibtype reliability reliability description destdesc scope jmstype queue admintaskcreatesibjmsqueuescopeconfig name destname jndiname destjndiname description destdesc deliverymode deliverymode readahead asconnection busname busname queuename destdest scopetolocalqp false producerbind false producerpreferlocal true gathermessages false elif jmstype topic admintaskcreatesibjmstopicscopeconfig name destname jndiname destjndiname description destdesc topicname deliverymode deliverymode readahead asconnection busname busname topicspace destdest else jmstype queue admintaskcreatewmqqueuescopeconfig name destname jndiname destjndiname queuename destdest qmgr description destdesc elif jmstype topic admintaskcreatewmqtopicscopeconfig name destname jndiname destjndiname topicname destdest description destdesc jms activation specs wmqres websphere mq jms provider scoperesources builtinmqprovider specs configgetelementsbytagname jmsactivationspec rangespecsgetlength xmle specsitemi busname getattributexmle bus specname getattributexmle name specjndiname getattributexmle jndiname jmstype getattributexmle jmstype destjndiname getattributexmle jndidestinationname specdesc getattributedxmle description maxhandlers getattributedxmle maxhandlers wmqtransporttypegetattributedxmle wmqtransporttype bindingsthenclient print creation de la spec activation jms specname jmstype queue jmsdestclass queue elif jmstype topic jmsdestclass topic bus getbusbusname bus type internal admintaskcreatesibjmsactivationspecscopeconfig name specname jndiname specjndiname destinationjndiname destjndiname description specdesc busname busname clientid durablesubscriptionhome destinationtype javaxjms jmsdestclass messageselector acknowledgemode autoacknowledge subscriptionname maxbatchsize maxconcurrency maxhandlers subscriptiondurability nondurable sharedurablesubscriptions incluster authenticationalias readahead default target targettype busmember targetsignificance preferred targettransportchain providerendpoints sharedatasourcewithcmp false consumerdoesnotmodifypayloadafterget false forwarderdoesnotmodifypayloadafterset false alwaysactivateallmdbs false retryinterval autostopsequentialmessagefailure failingmessagedelay else admintaskcreatewmqactivationspecwmqres name specname jndiname specjndiname description specdesc destinationjndiname destjndiname destinationtype javaxjms jmsdestclass qmgrname bus manager wmqtransporttype wmqtransporttype qmgrhostname bus host qmgrportnumber bus port qmgrsvrconnchannel bus channel adminconfigsave copy code file called configxml xml version encodingutf config definition des propriã©tã©s jvm property namesomeproperty valuemyvalue property descriptiondifferent jvm properties namemyproperty valuetrue dã©finition des sources authentification authentication descriptionauthentification pour accã¨s db nameauth userdbuser passworddbuser dã©finition des fournisseurs jdbc jdbcprovider descriptiononephase commit db jcc provider supports jdbc shortnamedb namedb universal jdbc driver provider databasetypedb providertypedb universal jdbc driver provider implementationtypesource de donnã©es du pool de connexions classpathdbuniversaljdbcdriverpathdbjccjar universaljdbcdriverpathdbjcclicensecujar dbuniversaljdbcdriverpathdbjcclicensecisuzjar nativepathdbuniversaljdbcdrivernativepath jdbcprovider descriptiontwophase commit db jcc provider supports jdbc shortnamedbxa namedb universal jdbc driver provider xa databasetypedb providertypedb universal jdbc driver provider implementationtypesource de donnã©es xa classpathdbuniversaljdbcdriverpathdbjccjar universaljdbcdriverpathdbjcclicensecujar dbuniversaljdbcdriverpathdbjcclicensecisuzjar nativepathdbuniversaljdbcdrivernativepath dã©finition des sources de donnã©es jdbc jdbcdatasource descriptionsources de donnã©es des demandes namedbname jndinamejdbcdbname jdbcproviderdb universal jdbc driver provider xa authenticationauth databasedbxxxxx hosthostname port dã©finition des bus internes internalbus descriptionbus interne namebusinterne dã©finition des bus externes externalbus descriptionserveur websphere mq externe nameserveurmq managermanager hosthost port channelclientname dã©finition des fabriques de connexions jms jmsconnectionfactory descriptionqueue de rafraichissement des demandes nameqcf jndinamejmsqcf jmstypequeue bus businterne jmsconnectionfactory descriptiontopic nametcf jndinamejmstcf jmstypetopic bus serveurmq dã©finition des destinations jms jmsdestination descriptionqueue namequeue jndinamejmsqueue jmstypequeue bus businterne destinationqname jmsdestination descriptiontopic nametopic jndinametopic jmstypetopic bus serveurmq destinationqtopicname dã©finition des spã©cifications activation jms jmsactivationspec descriptionspec namespecs jndinamejmsspecs jmstypequeue bus businterne jndidestinationnamejmsqueue maxhandlers config after resources defined configxml file simply call following command prompt make sure access wsadmin wsadmin lang jython profilename myprofile f configpy configxml this create resources profile called myprofile hope helps,i requirement writing script python jacl script i need monitor pull information admin console application running remote server i require pull following information jdbc jms web container threads default work manager threads if anyone help writing script highly appreciated thanks,3 for simple command line app mac os x need package os x application bundle pyapp deprecated bundlebuilder and app bundle normal way access command line utility since user would reach execute something inside bundle if thirdparty c library dependencies app simplest way may package standard distutils distribution setuppy since apple supplies versions python setuptools recent os x releases uploaded app python package index pypi user could download install app one command terminal window sudo easyinstall yourappname that default install script usrlocalbin included default path os x users shells if want upload pypi could still use easyinstall install downloaded file url you also need take account python version dependencies pythons apple makes available os x releases intend support there versionspecific easyinstallx commands also distutils higher level tools use pip distribute setuptools et al crossplatform may need anything support installation unixy distributions on hand app python versionspecific dependencies thirdparty library dependencies need support multiple os x versions cannot use applesupplied python may better use pyapp bundle applicationspecific copy python in case perhaps could user doubleclick downloaded app bundle would run script authenticate create symlink usrlocalbin appropriate script file within app bundle that disadvantage making application bundle pathlocation dependent though there complicated ways something similar without restriction necessary,i want create command line app would run terminal mac os x eventually platforms i make python script running terminal etc problem comes user i like user download app install one normally would call app perhaps typing appname directly terminal how would i go would i need wrap python file kind objectivec mini app install thanks,3 this seems work def getrelatedmanagersself managers relatedobject selfmetagetallrelatedobjects managersappendgetattrself relatedobjectgetaccessorname return managers you also loop selfmetagetallrelatedmanytomanyobjects want many manys well,let say i set django models class articlemodelsmodel title modelscharfieldmaxlength default content modelstextfielddefault blankfalse createdat modelsdatetimefieldautonowtrue creator modelsforeignkeyuser nulltrue blanktrue score modelsforeignkey score blanktrue nulltrue points modelsmanytomanyfield points class scoremodelsmodel value modelsintegerfield createdat modelsdatetimefieldautonowaddtrue creator modelsforeignkeyuser nulltrue blanktrue class pointsmodelsmodel value modelsdecimalfieldmaxdigits decimalplaces caption modelscharfieldmaxlength default createdat modelsdatetimefieldautonowaddtrue creator modelsforeignkeyuser blanktrue nulltrue and i somehow get instance score model without actually knowing score model instance points model without knowing points model types class myappmodelsscore typep class myappmodelspoints now i get access set related article instances via following code sarticleset djangodbmodelsfieldsrelatedrelatedmanager object xde particleset djangodbmodelsfieldsrelatedmanyrelatedmanager object xde but case i know actual db schema i know attributes called articleset in case i know actual db scema and i want get relatedmanager attributes current model instance i think possible implement via meta attribute i manage trying so i would probably need actual working example something like getrelatedmanagersself method implementation,2 one way store references associated variables dictionary here example import tkinter tk data field field field field class sampleapptktk def initself args kwargs tktkinitself args kwargs selfvariables label sorteddatakeys selfvariableslabel tkintvar cb tkcheckbuttonself textlabel onvaluedatalabel offvalue variableselfvariableslabel cbpacksidetop fillx button tkbuttonself textsubmit commandselfonsubmit buttonpack def onsubmitself field sorteddatakeys print value field selfvariablesfieldget name main app sampleapp appmainloop if like creating variables fly like little extra effort create array buttons associated i gave example question how run code whenever tkinter widget value changes,i trying create gui small plotting program logging files i data dictionaryactually dictdictdictdictand would like use keys create tabquantities top keys checkboxes basically selected plot quantity versus time subkeys i looked pyttk looks similar i wanted though i running issues implement tabbutton creation thanks bunch advance,1 i tested part found interesting stuff django pythonmemcached on django using memcache servers cacheset cacheget returned i looked memcache server sharded using django setups pointing one memcache servers i simulated connectivity outage putting firewall original django instance memcache server stored cacheget paused seconds returned none cacheset cacheget returned right away the memcache client library update sharding strategy server goes then i removed firewall cacheget returned bit detected server back returned you read stale data memcache server drops comes back memcache anything clever try prevent this really mess things using caching strategy puts things memcache long time depends cache invalidation handle updates an old value written normal cache server key loose connectivity invalidation made window server becomes accessible read stale data able one note i reading objectquery caching libraries i think johnnycache immune problem it explicitly invalidate entries instead changes key query cached table changes so would never accidentally read old values edit i think note johnnycache working ok crap httpjmoironnetblogisjohnnycacheforyou says extra cache reads every request load current generations if generations stored cache scenario cause stale generation read,in django documentation says one excellent feature memcached ability share cache multiple servers this means run memcached daemons multiple machines program treat group machines single cache without need duplicate cache values machine to take advantage feature include server addresses location either separated semicolons list django cache framework memcached how exactly work i read answers site suggest accomplished sharding across servers based hashes keys multiple memcached servers question how memcachestore really work multiple servers that fine i need much specific detailed answer using django pylibmc pythonmemcached sharding actually performed does order ip addresses configuration setting matter what two different web servers running django app two different settings files ip addresses memcached servers different order will result machine using different sharding strategy causes duplicate keys inefficiencies what particular machine shows list twice for example i something like actually machine caches default backend djangocorecachebackendsmemcachedmemcachedcache location what one memcached servers capacity others if machine one mb memcached machine mb will sharding algorithm take account give machine greater proportion keys i also read memcached server lost keys lost that obvious sharding involved what important happen memcached server goes i leave ip address settings file will djangomemcached simply fail get keys would sharded failed server realize server failed come new sharding strategy if new sharding strategy intelligently take keys originally intended failed server divide among remaining servers come brand new strategy first server exist result keys duplicated i tried reading source code pythonmemcached figure i plan try reading code libmemcached pylibmc i figured asking would easier someone already knew,3 in addition using raw strings mentioned post also escape backslash so typing alpha beta also work,i using matplotlib produce graphics i using latex legends more specifically i trying use something like loglogxx r label alpha legend show however code present legend figure gets error i close image i using enthought package mac error comes pylabscipy the error appears exactly lpha char line col however use mu gamma works well i found problem beta alpha does anyone knows i believe python interpreting character i know i debug avoid,2 what want order role attribute rolepermission object passing orderby sets order role class try sqlalchemyorm import backref permissionlinks relationshiprolepermission backrefbackrefrole orderbyname setting order back reference,i using declarative sqlalchemy i three models role permission rolepermission in role model i following class rolebase name columnu name varchar nullablefalse uniquetrue permissionlinks relationshiprolepermission backrefrole orderbyname permissions relationshippermission backrefbackrefroles orderbyname secondaryrolepermissiontable orderbypermissionname now permissions declaration works fine permissions associated role come sorted i expect name however permissionlinks fails following error sqlalchemyexcprogrammingerror programmingerror microsoftodbc sql server driversql serverthe multipart identifier rolesname could bound sqlexecdirectw microsoftodbc sql server driversql serverstatements could prepared u select rolespermissionsroleid as rolespermissionsroleid rolespermissionspermissionid as rolespermissionspermissionid rolespermissionsisdenied as rolespermissionsisdenied nfrom rolespermissions nwhere rolespermissionsroleid order by rolesname the problem role joined sort rolename i tried specifying primaryjoinid rolepermissionid seem change anything how i specify join relationship i sort field one joined tables namely rolename,3 if rawinputenter verb b rawinputenter person c rawinputenter place work as explained python documentation input sort shortcut evalrawinputprompt need case,i starting very basics i trying create simple madlibsesque game user import verb noun etc program print paragraph using inputs far i rawinputenter verb inputnn b rawinputenter person inputnn c rawinputenter place inputnn previous miniprogram i used code inputnn which made program wait input enter key user however wait user enter anything simply runs entire program without delay i know really basic problem could somebody please point program waiting user input instance thanks advance i know i done python interpreter immediately closes anything even something i know correct i copied def newline print def threelines newline newline newline print first line threelines print second line what wrong,1 use urllib create request object hand urlopen httpdocspythonorglibraryurllibhtml i dont really use old urllib anymore req urllibrequesthttpgooglecom none useragent mozilla windows u windows nt de rv gecko firefox response urlliburlopenreqread untested,i pretty new python urllib what i need set custom header request sent server specifically i need set contenttype authorizations headers i looked python documentation i able find,3 rpy convert code it allows interface communicate r python issue r commands within python given r dependent upon statistical libraries available python conversion would generally tremendous amount work to convert single line like lmer x x id mydat something python would take great deal work if want run code python use rpy going way seems interested conversion could often bit straightforward however code would tend poorly optimized r run badly i recently optimized r code converted python someone wrote r code less direct translation line line the optimization came length times faster depending function,i know exists module rpy rpy convert r code python is easy way reverse,3 prefix suffix open sourcetxt r src open desttxt w dest line src destwrite sssn prefix linerstrip n suffix,i currently looking way write beginning end every line txt file python for example current txt document jimmy was here write st value beginning every line jimmy was here write nd value end every line jimmy was here can seem find anything google describes properly done i found methods writing specific lines way any help appreciated thanks,3 adding http headers using urllib docs import urllib req urllibrequest httpwwwexamplecom reqaddheader referer httpwwwpythonorg resp urlliburlopenreq content respread,i pretty new python urllib what i need set custom header request sent server specifically i need set contenttype authorizations headers i looked python documentation i able find,3 you make changes file without opening multiple files using fileinput inplace import fileinput line fileinputinput testtxt inplace print format linerstrip n,i currently looking way write beginning end every line txt file python for example current txt document jimmy was here write st value beginning every line jimmy was here write nd value end every line jimmy was here can seem find anything google describes properly done i found methods writing specific lines way any help appreciated thanks,2 if want run cgi something like apache opposed via custom server code like pasted create py file like py cgienabled directory usrbinenv python print contenttype texthtml print print hello world if using apache info set cgi executables edit as adrien p says python script made executable,i never setup server let alone python server bit lost how utilize following code i tried put cgi bin directory didnt work it returned internal server error look usrbinenv python funf open sensing framework copyright c nadav aharony wei pan alex pentland acknowledgments alan gardner basehttpserver import basehttprequesthandler httpserver socketserver import threadingmixin import sys import cgi import urlparse import ospath import shutil import time serverdir ospathdirnamefile configpath config configfilepath ospathjoinserverdir configjson uploadpath data uploaddir ospathjoinserverdir uploads def readconfig config none try openconfigfilepath configfile config configfileread except ioerror pass return config def backupfilefilepath shutilmovefilepath filepath strinttimetime bak def writefilefilename file ospathexistsuploaddir osmkdiruploaddir filepath ospathjoinuploaddir filename ospathexistsfilepath backupfilefilepath openfilepath wb outputfile true chunk fileread chunk break outputfilewritechunk class requesthandlerbasehttprequesthandler def dogetself parsedurl urlparseurlparseselfpath parsedurlpath configpath config readconfig config selfsendresponse selfendheaders selfwfilewriteconfig else selfsenderror elif parsedurlpath uploadpath selfsenderror else selfsenderror def dopostself parsedurl urlparseurlparseselfpath path parsedurlpath ctype pdict cgiparseheaderselfheaders contenttype path uploadpath ctype multipartformdata form cgifieldstorageselfrfile selfheaders environ requestmethod post try fileitem formuploadedfile fileitemfile try writefilefileitemfilename fileitemfile except exception e print e selfsenderror else selfsendresponse selfendheaders selfwfilewriteok return except keyerror pass bad request selfsenderror elif parsedurlpath configpath selfsenderror else selfsenderror class threadedhttpserverthreadingmixin httpserver handle requests separate thread name main sysargv port intsysargv else port serveraddress port httpd threadedhttpserverserveraddress requesthandler sa httpdsocketgetsockname print serving http sa port sa print use ctrlc stop httpdserveforever,2 reading httpcodegooglecomappenginedocspythonusersuserclasshtmluser under method call userid noted create user object userid field return none,i working small app allow user login app allow app oauth access service interact service using app via email i successfully enabled oauth using gdata gdatagauth storerecover oauth token userid easily user logged however receiving email i try get userid creating usersuseremailsendersemailgmailcom end getting none value userid ie logged currentuser usersgetcurrentuser currentuseruserid valid id user logged receiving email using mail handler currentuser usersuseremailsenderemailgmailcom currentuseruserid returns none any hints make work,1 i believe looking typo book x j x see lagrange interpolating polynomial reference edit i found errata list see item second edition book it indeed typo,link exercise httpbooksgooglenobooksidhikvomgcamplpgpaampotstyhyrampdqexercisepythonscientificamphlnoamppgpavonepageampqampffalse exercise bottom page what i actually struggeling notation sigma one that one multiplies there find xj and i see xj comes so i try program i wonder xj suppose come thank much help,3 i know intend filist variable add context if plan list institutions limits systematic way table simple enough retrieve amount data much way retrieved selected financial institution name if intend reveal user amounts institutions i think reveal i mean exists anywhere html code whether browser renders one thing encode filist json string make response script tag code like var fininst jqueryparsejson jsonstring function checklimitamount i know amount supposed fininstjquerythistext amount code else amount within limit with djangopython code like import json plan investments investmentobjectsallfilterplan planorderby maturitydate filtermaturitydategte filist investments financialinstitution ifinancialinstitution amount igetcurrentvaluedate filistfinancialinstitution amount context jsonstring jsondumpsfilist and finally whenever institution option selected web page trigger checklimit function honestly really bad code i think want expose amount values institution critically confidential info maybe so reliable way produce fly results would use ajax call django view whenever institution selected you might want look dajaxproject simplify requests,i need loop django list i passed template i code django view plan investments investmentobjectsallfilterplan planorderby maturitydate filtermaturitydategte investments financialinstitution ifinancialinstitution amount igetcurrentvaluedate filistappend fi financialinstitution amt amount context list filist which outputs financialinstitution example amount now i want loop list javascript variable matches item list code however i stuck here javascript far using jqeury function cdiclimitamount var limit var list list var fi idfinancialinstitution optionselectedtext down road i ultimately want selected institution list check make sure total amount exceeding k any suggestions,1 you set many one relationship parent one child child many parents if intended set child like parentchild child a child however could add parent like childparentsappendparent if intended switch relationship parents multiple children setting many many relationship switching direction many one,using example documentation i following code when i try append i get error attributeerror nonetype object attribute append obviously even without using append parentchild nonetype i know work relationship base declarativebase class parentbase tablename parent id columninteger primarykeytrue childid columninteger foreignkey childid child relationshipchild backrefparents class childbase tablename child id columninteger primarykeytrue sqlalchemy import createengine sqlalchemyorm import sessionmaker engine createenginemysqllocalhosttest echofalse session sessionmakerbindengine session session metadata basemetadata metadatadropallengine metadatacreateallengine parent parent child child parentchildappendchild,1 sorted key function returns random value import random sortedl keylambda args randomrandom or import os sortedl keyosurandom,is straightforward way return shuffled array python rather shuffling place eg instead x array randomshufflex i looking something like shufflex maintains x note i looking function something like xarray yx randomshufflex,3 print ninelines you printing result calling ninelines function since function explicitly return value using return statement seen yet soon python returns special value none to fix change line simply ninelines,i going tutorial defining functions example creating new lines code write def newline print def threelines newline newline newline def ninelines threelines threelines threelines print hello world print ninelines print goodbye could anybody explain includes none goodbye,3 ninelines return none default since specify return value just using ninelines should give desired output alternatively could use print n edit i changed i forgot print also adds new line character thanks sven pointing,i going tutorial defining functions example creating new lines code write def newline print def threelines newline newline newline def ninelines threelines threelines threelines print hello world print ninelines print goodbye could anybody explain includes none goodbye,1 when run function ninelines return anything means returns none because printed return value see none console,i going tutorial defining functions example creating new lines code write def newline print def threelines newline newline newline def ninelines threelines threelines threelines print hello world print ninelines print goodbye could anybody explain includes none goodbye,1 if i understood correctly help blogobjectsannotatecommentcountcount comments orderby commentcount,i using tastypie create json django models however i running problem i think simple fix i object blogs wich comment object children i want able something like json apivblogsorderbycommentcount but i figure sort field part original comment blog model i create commentcount dehydrate method takes array comments returns commentscount any help would much appreciated i seem find explanation,1 you calling function add end script repeatthiss n also inputs rawinput coerce number integer using int rather dangerously allowing python parse probably go function definition work either way better style put script stuff together function global variable definitions putting together def repeatthiss n print n rawinputenter word n intrawinputenter number repeatthiss n,i trying task tutorial define function repeat inputted word inputted number times far i rawinputenter word n inputenter number def repeatthiss n print n however n defined locally repeatthis i get user input work i defined n inside function could anyone provide tips get work nb when i run file containing accepts input n leaves blank line starts new empty line repeatthis defined,1 as today four available approaches two requiring certain storage backend djangoeav original package longer mantained thriving forks this solution based entity attribute value data model essentially uses several tables store dynamic attributes objects great parts solution uses several pure simple django models represent dynamic fields makes simple understand databaseagnostic allows effectively attachdetach dynamic attribute storage django model simple commands like eavunregisterencounter eavregisterpatient nicely integrates django admin at time really powerful downsides not efficient this criticism eav pattern requires manually merging data column format set keyvalue pairs model harder maintain maintaining data integrity requires multicolumn unique key constraint may inefficient databases you need select one forks since official package longer maintained clear leader the usage pretty straightforward import eav appmodels import patient encounter eavregisterencounter eavregisterpatient attributeobjectscreatename age datatypeattributetypeint attributeobjectscreatename height datatypeattributetypefloat attributeobjectscreatename weight datatypeattributetypefloat attributeobjectscreatename city datatypeattributetypetext attributeobjectscreatename country datatypeattributetypetext selfyes enumvalueobjectscreatevalue yes selfno enumvalueobjectscreatevalue selfunkown enumvalueobjectscreatevalue unkown ynu enumgroupobjectscreatename yes no unknown ynuenumsaddselfyes ynuenumsaddselfno ynuenumsaddselfunkown attributeobjectscreatename fever datatypeattributetypeenum enumgroupynu when register model within eav access eav attributes patientobjectscreatename bob eavage eavfeverno eavcity new york eavcountry usa you filter queries based eav fields query patientobjectsfilterqeavcitycontains y query qeavcitycontains y qeavfeverno hstore json jsonb fields postgresql postgresql supports several complex data types most supported via thirdparty packages recent years django adopted djangocontribpostgresfields hstorefield djangohstore originally thirdparty package django added hstorefield builtin along several postgresqlsupported field types this approach good sense lets best worlds dynamic fields relational database however hstore ideal performancewise especially going end storing thousands items one field it also supports strings values appmodelspy djangocontribpostgresfields import hstorefield class somethingmodelsmodel name modelscharfieldmaxlength data modelshstorefielddbindextrue in django shell use like instance somethingobjectscreate name something data b instancedata empty somethingobjectscreatename empty emptydata emptydata emptysave somethingobjectsgetname something data you issue indexed queries hstore fields equivalence somethingobjectsfilterdata b subset keyvalue mapping somethingobjectsfilterdataa subset list keys somethingobjectsfilterdatahaskeys b subset single key somethingobjectsfilterdatahaskey jsonfield jsonjsonb fields support jsonencodable data type keyvalue pairs also tend faster jsonb compact hstore several packages implement jsonjsonb fields including djangopgfields django jsonfield builtin using jsonb storage jsonfield similar hstorefield may perform better large dictionaries it also supports types strings integers booleans nested dictionaries appmodelspy djangocontribpostgresfields import jsonfield class somethingmodelsmodel name modelscharfieldmaxlength data jsonfielddbindextrue creating shell instance somethingobjectscreate name something data b nested c indexed queries nearly identical hstorefield except nesting possible complex indexes may require manually creation scripted migration somethingobjectsfilterdataa somethingobjectsfilterdatanestedc somethingobjectsfilterdatahaskey django mongodb or nosql django adaptations fully dynamic models nosql django libraries great keep mind djangocompatible example migrate djangononrel standard django need replace manytomany listfield among things checkout django mongodb example djangotoolboxfields import dictfield class imagemodelsmodel exif dictfield image imageobjectscreateexifgetexifdata imageexif u cameramodel spamcams exposuretime you even create embedded lists django models class containermodelsmodel stuff listfieldembeddedmodelfield class foomodelmodelsmodel foo modelsintegerfield class barmodelmodelsmodel bar modelscharfield containerobjectscreate stufffoomodelfoo barmodelbar spam djangomutant dynamic models based syncdb southhooks djangomutant implements fully dynamic foreign key mm fields and inspired incredible somewhat hackish solutions will hardy michael hall all based django south hooks according will hardy talk djangocon watch nevertheless robust tested production relevant source code first implement michael hall yes magic approaches achieve fully dynamic django apps models fields relational database backend but cost will stability application suffer upon heavy use these questions considered you need sure maintain proper lock order allow simultaneous database altering requests if using michael halls lib code look like dynamo import models testapp created modelsdynamicappobjectsgetorcreate name dynamo test created modelsdynamicmodelobjectsgetorcreate name test verbosename test model apptestapp foo created modelsdynamicmodelfieldobjectsgetorcreate name foo verbosename foo field model test fieldtype dynamiccharfield null true blank true unique false helptext test field foo bar created modelsdynamicmodelfieldobjectsgetorcreate name bar verbosename bar field model test fieldtype dynamicintegerfield null true blank true unique false helptext test field bar,i working multitenanted application users define data fields via admin collect additional data forms report data the latter bit makes jsonfield great option instead i following solution class customdatafieldmodelsmodel abstract specification arbitrary data fields not used holding data metadata fields site modelsforeignkeysite defaultsettingssiteid name modelscharfieldmaxlength class meta abstract true class customdatavaluemodelsmodel abstract specification arbitrary data value modelscharfieldmaxlength class meta abstract true note customdatafield foreignkey site site different set custom data fields use database then various concrete data fields defined class usercustomdatafieldcustomdatafield pass class usercustomdatavaluecustomdatavalue customfield modelsforeignkeyusercustomdatafield user modelsforeignkeyuser relatedname customdata class meta uniquetogether user customfield this leads following use customfield usercustomdatafieldobjectscreatename zodiac sitemysite probably created admin user userobjectscreateusername foo usersign usercustomdatavaluecustomfieldcustomfield useruser data libra usercustomdataaddusersign actually even but feels clunky particularly need manually create related data associate concrete model is better approach options preemptively discarded custom sql modify tables onthefly partly scale partly much hack schemaless solutions like nosql i nothing still good fit ultimately data typed possibility exists using thirdparty reporting application jsonfield listed going work well queries,3 john correct these converting languages interfacing languages language conversion particularly common though interfacing however object conversion quite common important part interfacing languages in addition rpy rpy take look rspython it also provides object conversion inspired rpy,i know exists module rpy rpy convert r code python is easy way reverse,1 function one line datagetnum datamindatakeys keylambda k absknum edit evaluate min key dict use datanum num data else datamindatakeys keylambda k absknum values data evaluate true use datagetnum datamindatakeys keylambda k absknum,i data form dictionary now i take input user anything and i trying following if key exists cool fetch value dictionary fetch nearest numeric sense for exampleif input key keys like then probably closest key now algorithm point view straight forward pythonic way thanks,3 another concise variant itertools import imap izip operator import itemgetter openapy f res maxizipf imaplen f keyitemgetter this treats every line label,i file follows format line string line line another string line short line i trying write python code get line x label string longest string length can help fix code please here i far f open testtxt r print f readnull topreadlinelength topreadlinenull line f checkifreadlinefind line checkifread print read label found means read line currentreadline else we sequence line currentread currentlengthlenline print currentlength print topreadlinelength inttopreadlinelength intcurrentlength print topreadline topreadlinecurrentreadnow topreadline label line string topreadlinelengthintcurrentlength print topreadline go next line print done print longest line print topreadline,1 you might want consider storing data easilysearchable structure using treectrl display otherwise iterate children treectrl root item like def itemexiststree match root item cookie treegetfirstchildroot itemisok treegetitemtextitem match return true treeitemhaschildrenitem itemexiststree match item return true item cookie treegetnextchildroot cookie return false result itemexiststree text treegetrootitem uncommenting commented lines make recursive search,how i check certain root wxtreectrl object certain child i writing manual functions update treectrl every time child added useris way automate,1 if python dictionary better checking entries dictionary will answer however want find closest key efficiently ie olog n instead on want balanced tree sort unfortunately i believe python datastructure standard library pythonic way use dict instead so expect make many queries large map best choice may find extension library even roll,i data form dictionary now i take input user anything and i trying following if key exists cool fetch value dictionary fetch nearest numeric sense for exampleif input key keys like then probably closest key now algorithm point view straight forward pythonic way thanks,1 i follow advice referenced so question it got upvotes would appear upvotes everything actually probably dated info it far better use presave signal requires absolutely zero changes model therefore negative consequences answer referenced essentially receiver method look instance object database since presave database changed yet as result compare instancesomefield objsomefield see different receiverpresave sendermymodel def sendemailifchangedsender instance kwargs try obj mymodelobjectsgetpkinstancepk except mymodeldoesnotexist pass it new email technically changed might want something else else objemail instanceemail email changed send email,in django application i like implement system email field jmodel mymodel changed email sent email address i modelform model mine how i implement should i override save method modelform send email should i try try trap kind model updated signal send email — what signal shoudl i trapping what good way check email changed this trivial thing implement i like code reside rightful place thanks checking field changed django when saving check field changed,1 one way work around use old formatting deprecated yet print name personnames personname joe name joe,say i got dictionary dots name fields like personname joe if i wanted use strformat possible my first instinct name personname format personname joe would work dict shaped like person name joe the relevant manual docs section mention anyway escaping dot sidenote i thought generally def funckw printkw func ab joe would cause error expanded function call seems work even valid identifiers it error nonstrings though oo,2 it possible use numpy arrays multiprocessing yet read a beginners guide using python performance computing cython version speeding python numpy cython weave without knowing specific calculations sizes arrays generic guidelines particular order measure performance code find hotspots your code might load input data longer calculations set goal define tradeoffs acceptable check automated tests get expected results check whether could use optimized libraries solve problem make sure algorithm adequate time complexity on algorithm pure python faster on algorithm c large n use slicing vectorized automatic looping calculations replace explicit loops pythononly solution rewrite places need optimization using weave fpy cython similar provide type information explore compiler options decide whether speedup worth keep c extensions minimize allocation data copying make cache friendly explore whether multiple threads might useful case eg cythonparallelprange release gil compare multiprocessing approach the link contains example compute different slices array parallel iterate,true number lensomelist otherlist arraynonenumber xrangenumber otherlisti numpy array calculation using ith element arrays array array array number number elements otherlist arrays calculated seperately however program timedependent cannot proceed job every number number elements processed will multiprocessing good solution operation i speed process maximally if better please suggest code please,2 there room opinion brevity second approach makes clear win far i concerned especially use item variable limited within loop i would choose syntax every time there problems involving buffers state changes within loop i chosen use but small minority,the problem quite simple i method returns list i want iterate every item list finished call method receive new list repeat at moment code looks something like generator iter condition try item nextgenerator except stopiteration generator iterlistreturiningmethod item nextgenerator however previously i using nested loop condition item listreturiningmethod while previous attempt looks nicer respects current method advantages condition set false loop ends without break loop extension reasons methods access condition end loop without going items said list implementing special check loop the first approach allows skipping items loop need arise there also one less level indentation this vanity anything else considering actual code part class method indent level already pretty high to say least im confused appropriate they seem unique advantages disadvantages anyone knows correct pythonic approach i really appreciate,1 i suggest use iterators items itertoolschainfromiterable iterlistreturningmethod none item items something item print item condition break itercallable sentinel returns iterator produces result callable return sentinel itertoolschainfromiterable returns iterator flattens original iterator produce values lists produced first iterator i think gives advantages method cleaner style,the problem quite simple i method returns list i want iterate every item list finished call method receive new list repeat at moment code looks something like generator iter condition try item nextgenerator except stopiteration generator iterlistreturiningmethod item nextgenerator however previously i using nested loop condition item listreturiningmethod while previous attempt looks nicer respects current method advantages condition set false loop ends without break loop extension reasons methods access condition end loop without going items said list implementing special check loop the first approach allows skipping items loop need arise there also one less level indentation this vanity anything else considering actual code part class method indent level already pretty high to say least im confused appropriate they seem unique advantages disadvantages anyone knows correct pythonic approach i really appreciate,1 name personname format personname joe,say i got dictionary dots name fields like personname joe if i wanted use strformat possible my first instinct name personname format personname joe would work dict shaped like person name joe the relevant manual docs section mention anyway escaping dot sidenote i thought generally def funckw printkw func ab joe would cause error expanded function call seems work even valid identifiers it error nonstrings though oo,2 i believe right wrong doubt reinventing wheel maybe different levels thinking gives hint how eat elephant level a software design at level would want stick best practice long operations done ui ui thread you need ui layer focuses gathering input including cancellation drawing including inprogressvisualization like progressbar hourglass this layer separated anything else dusk dawn any call outside layer must fast want intuitiveness responsiveness in tasks complex calls outside ui layer typically schecule work command queued smart layer pick whenever gets read results results queued smart layer could popped rendered cancelstopexit raise flag smart layer check flag don worry much user operations getting reaction slowly solid design core adjust priorities user input later or add shortterm hourglass similar or even cancel long operations get obsolete specific user input level b heavylifting smart layer there best framework kind hard work so i suggest design feeding ui layer simple possible frameworks involved internally implement using frameworks ability future redesign hardworking elements needed for example future could give math gpu share tasks serverfarms involve cloud computing for complex tasks picking framework top level design might prove obstacle future specifically may limit freedom applying technologies it hard tell sure seems silver bullet framework task so find strong tools eg threads queues implement good design practiceseg decoupling edit response edit your latest edit stresses perfectly hard challenges software designer meets for case acceptance silver bullet i suggest accept sooner better later the hint resides offered generic task defined int float this could make happy today fail tomorrow exactly lockingin superabstract framework the path right heavylifting task base design but define int float focus mentioned start read stop instead if see size elephant eating might fail eating end starving from level a design perspective could define task contain something like class anysuperpowerfultask def run scheduleforathreadtorunme def cancel dothesmartcancellationsonobodywouldcrash this gives basis neutral yet clean decoupled level a desing perspective however would need kind setting task getting real result right sure would fall level b thinking it would specific task group tasks implemented intermediate base final task could something along lines class calculatepossibilitiestosaveallthepandassuperpowerfultask def initsomeint somefloat anotherurl configpath anythingspecifictothiskindoftasks def getresults return partiallycalculateddimensionalevolutiongraphofpandasinoptimisticenvoronment the samples intentionally incorrect python order focus design syntax level c abstractionnirvana it looks like level mentioned post yes pitfall many good designers confirm the state could endlessly without results search generic solution ie silver bullet i suggest take peek get fast late falling pitfall shame normal development stage greatest designers at least i trying believe edit you said im working piece software design im stuck idea im feeling like im reinventing wheel any software designer get stuck maybe next level thinking might help here comes level d i stuck suggestion leave building walk cafe next corner order best coffee sit ask question what i need note different question what i want ping eliminated wrong answers start observing correct ones wrong answers i need framework would x y z i need screwdriver could run mph harvest forest farm nearby i need amazing internal structure user actually never see right answers forgive i understood problem wrong i need user able give input software i need user see calculations progress i need user visually see result calculations,im working piece software design im stuck idea im feeling like im reinventing wheel my situation following i designing scientific utility interactive ui user input trigger visual feedback duh directly ie editing domain geometry soon possible without blocking user interaction say solving pde said domain if i draw diagram operations i need perform i get rather awesomely dense graph exposing kinds opportunities paralellism cachingreuse partial results so i want primarily exploit paralellism transparant way selected subtasks executing seperate processes results outmatically joined downstream tasks waiting inputs ready plus needing recompute input branches actually input changed pyutilibworkflow seems come closest im looking except course isnt doesnt seem subprocessing begin that seems rather disappointing im software engineer id say im asking anything crazy another complicating factor tight userinterface integration i desire scientificworkflowsolutions seem designed handle for instance i would like pass draganddrop event transformation node processing the transformation node two inputs affine transform state input port pointset class knows if affine transform input port dirty waiting dependencies update event held becomes available but event passed node eventinput port marked handled refire affine transform changes due user input thats example one many issues come i dont see adressed anywhere or longrunning forkingjoining branch recieves new input middle crunching previous input so question do happen know good booksarticles workflow design patterns i read or i trying fit square peg round hole know completely different design pattern i know or python package i want regardless buzzwords comes dressed ive rolled solution top enthoughttraits im perfectly happy either feels like rough shoddy reinvention wheel except i cant seem find wheels anywhere internet note im looking webframeworks graphical workflow designers specialpurpose tools just something conceptually like pyutilibworkflow including documentation featureset i work edit im reading reflection issue the requirements one tack onto workflow architecture diverse single shoe fits do want tight integration disk storage tight integration web frameworks asynchronicity mix custom finite state machine logic task dispatch they valid requirements largely incompatible make senseless mixes however lost looking generic workflow system solve arbitrary problem like looking generic iterator solve custom iteration problem iterators primarily reusability cant reuse redblacktree iterator iterate tensor their strength lies clean seperation concerns definition uniform interface what im looking started writing going pretty cool look like base general implementationagnostic workflowdeclaration minilanguage based decorators metamagic transform statement like workflow declaration containing required information compositetaskinputsxint outputszfloat class mycompositetask taskinputsxint outputsyfloat def mytaskx return outputs x taskinputsxint yfloat outputszfloat def mytaskx return outputs z xy mytasky mytasky redundant illustration inputsoutputs matching name metadata autoconnect what decorators return taskcompositetaskworkflow declaration class instead type constraints metadata required workflowtype hand easily added syntax now concise pythonic declaration fed workflow instance factory returns actual workflow instance this declaration language fairly general probably need change much different design requirements workflow instantiation factory entirely design requirementsimagination aside common interface deliveringretrieving inputoutput in simplest incarnation wed something like wf workflowfactorymycompositetask wfz lambda result print result register callback zoutput socket wfx feed data x inputsocket wf trivial workflow instance nothing chain contained function bodies together thread inputs bound a quite verbose way chain two functions illustrates idea already achieves goal separating concern keeping definition flow information central place rather spread throughout classes would rather nothing thats less functionality ive got implemented far means i go working project due time ill add support fancier workflow instance factories for instance im thinking analyzing graph dependencies identify forks joins tracking activity generated input supplied workflowinstance level elegant load balancing cancellation effects specific inputs lost relevance still hogging resources either way i think project separating workflow declaration interface definition implementation instantiation worthwhile effort once i nontrivial types workflow instances working well i need least two project im working ive realized i hope find time publish public project despite diversity design requirements workflow systems groundwork covered makes implementing specific requirements lot simpler and instead single bloated workflow framework swiss army knife easily switchedout custom solutions could grow around core realizing i need split code two different workflow instance types rather trying bash design requirements one solution turned square peg round hole i mind two perfectly complementary holes pegs,3 not really elegant get close want using tuple store pointers arrays now i idea i would use case i done things like x nparray y nparray z x y z z array array x array,in numpy i concatenate two arrays endtoend npappend npconcatenate x nparray y nparray z npappendx y axis z array but make copies input arrays z z array x array is way concatenate two arrays view ie without copying would require npndarray subclass,1 emacs quite capable handling rej files however practical i try use hg pull rebase whenever possible often i find wanting rebase lineage patches onto another changeset i already pulled in cases i strip changeset pull hgstripbackup allowing use rebase,i looking better patch tool ones built mercurial visual tool help edit patches get accepted mercurial gnu patch the mercurial wiki topic handlingrejects shows simple patching fail i looking implement mercurial based workflow feature branch version control based feature branches relies exporting reviewing patches integrated in initial testing idea weakest link patch review accept modify patches way patch rejection shuts here common cases mercurial patch imports fail trivial changes upstream repoa feature branch repob single line added somewhere branches since branches history possible merge tool see someone added one line repoa someone else added one line repob in case patch imports though results patch import reject rej file turd repository ahve manually repair editing rej file applied the wiki page mentions mpatch tool found i looking better merge tools work mercurial b handle trivial case noted handling rejects wiki page note mpatch work purposes seems i need something rebase tool patch tool case i may make patch tool syntaxaware thus specific single programming language i looking tools available working windows either natively even via something like cygwin i using unixlinux environment although i comfortable linuxunix style tools i currently using mq extensions exporting ranges changes using hg export importing using hg import rest work inventions however i tagged mq mq users familiar rej handling problem related question shows ways resolving problems using tortoisehg,1 php distinction dictionaries tupleslists function normalizeinputnull isarrayinput return strvalinput res keys arraykeysinput sortkeys foreach keys k isintk res k res normalizev return res notably serialization sucks since cannot distinguish integers numbers you really using json php well python languageindependent humanreadable serialization format instead using string authentication one simply use hash json serialization,does anyone know convert function python php i around things python code i figure this function used follow context httpwwwdmcloudnetdocapigeneralhtmlauthentication def normalizeinputnone output typeinput list tuple element input typeelement dict list tuple element normalizeelement output strelement elif typeinput dict keys inputkeys keyssort key keys element inputkey typeelement dict list tuple element normalizeelement output ss key element else output strinput return output thank,1 this issue made lot harder dict keys particular order if play make dict order like example use python use ordereddict bisect make lightning fast import collections collectionsordereddict range ai import bisect ind bisectbisectleftakeys then check element ind ind see closer thus making lot fewer calculations,i data form dictionary now i take input user anything and i trying following if key exists cool fetch value dictionary fetch nearest numeric sense for exampleif input key keys like then probably closest key now algorithm point view straight forward pythonic way thanks,3 yes possiblei suggest two ways solve problem both uses http requests you check info http request easiest way recommended one login requests http humans python scrapy scrapy crawling screen scraping check example login spider example class loginspiderbasespider name examplecom starturls httpwwwexamplecomusersloginphp def parseself response return formrequestfromresponseresponse formdata username john password secret callbackselfafterlogin def afterloginself response check login succeed going authentication failed responsebody selfloglogin failed levellogerror return continue scraping authenticated session info,is possible sign website allow website visited browser without user sign via background process without user interaction allow user browse site without logging browser i guess i would need register created session web browser user system possibly simpler way think like automatically signing gmail background able browse without ever seeing login page,1 if astliteraleval unavailable use unsafe eval evals however really overthink serialization format if transferring data python applications need distinction tuples lists use pickle otherwise use json,how i convert list tuples i using planetlab shell support import ast so i unable use,2 if trust source string enough use eval use import tuplerx recompiledsd result match tuplerxfinditer resultappendintmatchgroup intmatchgroup the code straightforward works tuples integers if want parse complex structures better proper parser,how i convert list tuples i using planetlab shell support import ast so i unable use,1 if want remove newlines entirely allsents filesentreadreplace n if want replace spaces allsents filesentreadreplace n obviously could replace something else wanted,trying read file python program apply tokenizer split text set sentences however output getting n character like avoid output might hinder processes sentences i read input using read command also tried readline still getting newline characters output any suggestions avoiding filesent openpath r allsents filesentread sentall print allsents tokenizedsents senttokenizesentall,1 in python x use nonlocal keyword def outer string def inner nonlocal string string string changed nested function inner return string in python x could use list single element overwrite single element def outer string def inner string string changed nested function inner return string,suppose i following python code def outer string def inner string string changed nested function inner return string i want call outer return string changed nested function i get i conclude python thinks line string string changed nested function declaration new variable local inner my question i tell python use outer string i use global keyword string global lives outer scope ideas,3 first i confident i understand question let state assumption you want write file directory exist yet the path relative current directory you want change current directory so given check two functions osmakedirs ospathjoin since want specify relative path respect current directory want add initial dirpath ospathjoinselffeed selfaddress return feedaddress osmakedirsdirpath create directory currentpathfeedaddress output openospathjoindirpath filename wb,currently i following code filename contentsplit replace file gotten previously filename selffeed selfaddress filename add folders output openfilename wb outputwriteurlread outputclose my goal python write file filename file address folder feed folder current directory ie python script saved i looked os module i want change current directory directories already exist,3 this create file feedaddressfiletxt directory current script import os filename filetxt scriptdir ospathdirnameospathabspathfile destdir ospathjoinscriptdir feed address try osmakedirsdestdir except oserror pass already exists path ospathjoindestdir filename openpath wb stream streamwrite foon,currently i following code filename contentsplit replace file gotten previously filename selffeed selfaddress filename add folders output openfilename wb outputwriteurlread outputclose my goal python write file filename file address folder feed folder current directory ie python script saved i looked os module i want change current directory directories already exist,3 you want mystring item,i looking specific string list string part longer string basically loop trough text file add string different element list now objective scan whole list find elements string contain specific string example source file asfasdasdasd asdasdasdasdasd mystring asdasdasdasd asdasdasdasdasdasdadasdasdasdas now imagine string element list want know list string string elements need know many occurrence string list i tried get seems find occurrence worklistasfasdasdasd asdasdasdasd string asdasdasdasd asdadadasdasdasdas hasstringfalse item worklist mystring worklist hasstringtrue print has string true print njoinworklist the output list bool hasstring stays false am i missing something using statement wrong way,3 a concise usually faster way anymy string item item worklist hasstring true print found mystring but really done implement grep,i looking specific string list string part longer string basically loop trough text file add string different element list now objective scan whole list find elements string contain specific string example source file asfasdasdasd asdasdasdasdasd mystring asdasdasdasd asdasdasdasdasdasdadasdasdasdas now imagine string element list want know list string string elements need know many occurrence string list i tried get seems find occurrence worklistasfasdasdasd asdasdasdasd string asdasdasdasd asdadadasdasdasdas hasstringfalse item worklist mystring worklist hasstringtrue print has string true print njoinworklist the output list bool hasstring stays false am i missing something using statement wrong way,1 method stringlist string blah string blah string this yield list strings contain string method if want check exists somewhere faster anymy string stringlist truefalse this benefit terminating search first occurrence string method you want put function preferably lazy generator def searchstringlist query stringlist query yield list searchan apple banana cat banana cat,i looking specific string list string part longer string basically loop trough text file add string different element list now objective scan whole list find elements string contain specific string example source file asfasdasdasd asdasdasdasdasd mystring asdasdasdasd asdasdasdasdasdasdadasdasdasdas now imagine string element list want know list string string elements need know many occurrence string list i tried get seems find occurrence worklistasfasdasdasd asdasdasdasd string asdasdasdasd asdadadasdasdasdas hasstringfalse item worklist mystring worklist hasstringtrue print has string true print njoinworklist the output list bool hasstring stays false am i missing something using statement wrong way,2 there wellknown greedy approximation algorithm set cover also easy implement whatever language choice the algorithm described httpenwikipediaorgwikisetcoverproblemgreedyalgorithm it simple easiest thing write scratch notably also best polynomialtime approximation algorithm known set cover that means get better worstcase performance compact result set would need nonpolynomial running times slow algorithms large sets unfortunately wikipedia entry actually cover weighted set cover case the extension simple described eg httppagescswiscedushuchicoursessscribenoteslecturepdf some useful notes httpwwwcsucredunealnonarxivyoungsetcoverpdf httpwwwcsuiuceduclassspcslectureslecpdf,this question follows related question mine posted mhum suggested problem falls covering problem domain i tried encoding question minimum set cover problem currently i dataset form set cost the objective find good set cover covers numbers one attempts minimize total cost my dataset big least sets size varying elements like are good greedy implementations solve i implement i expert lp lpsolvers numpyscipy solve also acceptable,3 you use twilio send text messages appengine using twilio sms api check code weather phone app documented google appengine blog weather phone app pythonappengine howto i heard tropo also good try free developers i never done personally trick,with google app engine way send text message cell phone appwritten python data stored app database able retreive app browser vice versa searching days i come close finding answer cloud based solution think drop box say poems write poem haiku sms text account use mobile phone app publish account use web based service post account end result able access data fronts,2 the readselect selfconnection never returns one manually reads object data coming it looks like read selfrfile note calling select selfrfile return selfrfileread work that probably selfrfile python filelike object server process already read start post body os,i creating simple python proxy logs requests sent for everything works except post requests i vote stackoverflow questions i defined explicit post function i using get function instead could anyone tell problem this code usrlocalbinpython import basehttpserver select socket socketserver urlparse class proxyhandlerbasehttpserverbasehttprequesthandler def initself request clientaddress server selfrequest request selfclientaddress clientaddress selfserver server selfsetup selfsocket socket selfserverversion testproxy selfrequestbuffersize try selfhandle finally selffinish def connecttoself location destinationsocket locationfind host locationi port intlocationi else host location port print connecting formathost port try selfsocketconnecthost port except socketerror arg try msg arg except msg arg selfsenderror msg return return def doconnectself selfsocket socketsocketsocketafinet socketsockstream try selfconnecttoselfpath socket selflogrequest selfwfilewriteselfprotocolversion connection establishedn selfwfilewrite proxyagent n formatselfversionstring selfwfilewrite n selfreadwriteselfsocket finally print connection closed selfsocketclose selfconnectionclose def dogetself scm location path parameters query fragment urlparseurlparseselfpath http scm http fragment location selfsenderror bad url formatselfpath return selfsocket socketsocketsocketafinet socketsockstream try selfconnecttolocation selfsocket selflogrequest selfsocketsend n formatselfcommand urlparseurlunparse path parameters query selfrequestversion selfheaders connection close del selfheaders proxyconnection key value selfheadersitems selfsocketsend n formatkey value selfsocketsend n selfreadwriteselfsocket finally print closing connection selfsocketclose selfconnectionclose def readwriteself socket maxidling iw selfconnection socket ow count count maxidling count readlist writelist exceptionlist selectselectiw ow iw exceptionlist break readlist item readlist selfconnection item socket else socket data itemrecv data outsenddata count else pass print idle formatcount dohead doget dopost doget doput doget dodelete doget class threadinghttpserversocketserverthreadingmixin basehttpserverhttpserver pass name main basehttpservertestproxyhandler threadinghttpserver this part handles postget requests def dogetself scm location path parameters query fragment urlparseurlparseselfpath http scm http fragment location selfsenderror bad url formatselfpath return selfsocket socketsocketsocketafinet socketsockstream try selfconnecttolocation selfsocket selflogrequest selfsocketsend n formatselfcommand urlparseurlunparse path parameters query selfrequestversion selfheaders connection close del selfheaders proxyconnection key value selfheadersitems selfsocketsend n formatkey value selfsocketsend n selfreadwriteselfsocket finally print closing connection selfsocketclose selfconnectionclose,1 other sugestion subprocesspopenhhexe dhelpchmuserguidehtmtoc,how i open chm help file particular section using python actually i opening file following function def helpself open help file osstartfile osgetcwdconfighelpchm,1 if code excerpt accurately reflects program problem single line init constructor you need fix indentation self defined member functions your nonindented code part constructor actually getting run import class one great beauties python uses indenting recognize statement blocks rather curly braces begin end you must use indenting correctly interpreter understand code,back confusing script a lot spacing issues i fixed seem missing whats wrong saying line self defined here lines script case matters whats decompiled start mapnonelist ziplist class areasettoptsv def initself filename version toptsvinitself filename version selffrombinmap id ulong lpad x name str x rpad xc rgb color color rpad x sound effect id long color rgb rcolor rpad x lighting rgb value rcolor rpad x lighting angle float x f x is city ubyte rpad x i cant figure i think right many self defined errors i fix one least i know fix rest so i need,3 indentation matters python self defined within init assuming want self referred line indent match line,back confusing script a lot spacing issues i fixed seem missing whats wrong saying line self defined here lines script case matters whats decompiled start mapnonelist ziplist class areasettoptsv def initself filename version toptsvinitself filename version selffrombinmap id ulong lpad x name str x rpad xc rgb color color rpad x sound effect id long color rgb rcolor rpad x lighting rgb value rcolor rpad x lighting angle float x f x is city ubyte rpad x i cant figure i think right many self defined errors i fix one least i know fix rest so i need,2 i created youtube id parser without regexp def videoidvalue examples httpyoutubesaiwivdjie httpwwwyoutubecomwatchvopawaudwcampfeaturefeedu httpwwwyoutubecomembedsaiwivdjie httpwwwyoutubecomvsaiwivdjieversionampamphlenus query urlparsevalue queryhostname youtube return querypath queryhostname wwwyoutubecom youtubecom querypath watch p parseqsqueryquery return p v querypath embed return querypathsplit querypath v return querypathsplit fail return none,i know easily done using php parseurl parsestr functions subject httpwwwyoutubecomwatchvzabfpxtkmsampnr url parseurlsubject parsestrurl query query vardumpquery but achieve using python i urlparse next,3 to explore filesystem try oswalk it recursively follow directory yielding list files dirs dir for example given directory structure like ├── baz │â â └── bif │â â ├── bang │â â └── filedoc └── foo ├── bar │â â └── filedoc └── filedoc this code import os print listoswalk walk current directory would produce something like baz foo baz bif bazbif bang filedoc bazbifbang foo bar filedoc foobar filedoc you could loop results compile list files copy for copying files shutil package copy takes srcdest file paths for information see docs httpdocspythonorglibraryshutilhtml edit more helpful file searching things include the glob package as name suggests glob style file matching txt etc i believe supports recursive searching though in example i glob foodoc i would get result foofiledoc fnmatch fnmatch package glob style pattern matching strings example fnmatch footxt txt would return true,i quite new python attempting create basic backup program allow search files certain extension case doc throughout entire home drive computer copy predetermined directory program run usb i got handle basic io commands fair bit difficulty would anyone time able help thanks time liam,1 it quite possible my app currently listed httpitunesapplecomusappquickwhoidmtampls bundled pyapp worries,does apple accept python applications distribution new mac app store if application packaged is pyapp sufficient something else,1 it looks like byte cannot persisted check question nhibernate mappingexception persister byte may getting message happening ironpython c due c type checking here another link possible solution serializing byte ascii httpguildsocialwebdiscountaspnetdasblogcenhibernatemappingtobinarydataaspx here snippet post return new asciiencodinggetstringbytes public static string convertbytearraytostringbyte bytes try return new asciiencodinggetstringbytes catch exception return,so i wrote scraper passed c class card ironpython happily loaded i think binary image data byte like imageurl httpblablacomimageashxid cardid amptypecard imageresult urlliburlopenimageurlread imageresult print could find image cardtitle cardaddimageimageresult addimagebyte i persist pull database nhibernate tried pull back mvc front end var ms new memorystreamcardimage var image imagefromstreamms parameter valid had i written file instead c object python i fairly sure would work my question good way tell conversions look like ironpython clr data types my binary sucks i real sure case,1 grep alpha eof somejunk amp myfile file eof file,i large text file lot special characters like plus many i would like remove line text file special characters line the characters i want keep az az if file somejunk amp myfile file then thing would left would file a solution linux command line tools bash script python script would better anything works,3 if want keep only lines alpha characters op requested grep v azaz foo or want english characters grep v abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz foo but want remove nonalpha characters sed job cat foo sed sazazg or want kill binary nonprintable data use strings strings foo,i large text file lot special characters like plus many i would like remove line text file special characters line the characters i want keep az az if file somejunk amp myfile file then thing would left would file a solution linux command line tools bash script python script would better anything works,1 to fix second problem reinstall setuptools and fix first one install virtualenvwrapper basically install lion reinstall python sitepackages,i touched python virtualenv i believe i setup mbp virtualenv pip totally forgotten stuff works after installing lion i getting error i open new terminal window traceback recent call last file string line module importerror no module named virtualenvwrapperhookloader virtualenvwrappersh there problem running initialization hooks if python could import module virtualenvwrapperhookloader check virtualenv installed virtualenvwrapperpythonusrbinpython path set properly any tips fix trying easyinstall eventlet i got traceback recent call last file usrlocalbineasyinstall line module pkgresources import loadentrypoint file systemlibraryframeworkspythonframeworkversionsextraslibpythonpkgresourcespy line module parserequirementsrequires environment file systemlibraryframeworkspythonframeworkversionsextraslibpythonpkgresourcespy line resolve raise distributionnotfoundreq xxx put info pkgresourcesdistributionnotfound setuptoolsc,1 this seems work sed alphad sourcefile,i large text file lot special characters like plus many i would like remove line text file special characters line the characters i want keep az az if file somejunk amp myfile file then thing would left would file a solution linux command line tools bash script python script would better anything works,2 i fixed creating new virtualenv installing packages it seems old virtualenv still linking ubuntu general ssl package location updated,so yesterday i fresh install ubuntu keeping home directory virtualenvs i installed virtual env able logon previous virtual env i try run python managepy runserver virtualenv i get following error error loading shared libraries libsslso cannot open shared object file no file directory any idea fix i tried installing ssl package python fix,1 plotwireframe expects three darrays xyz input so xnparrayxdis ynparrayydis znparrayresis add xxreshape yyreshape zzreshape,right i got list x values values z values i think i converted arrays i want make surface plot working here i trying ignore code pretty irrelevant look end i xdis ydis dist i trying plot atm i getting valueerror need value unpack help much appreciated math import numpy import import pylab def sweep vpqrs range lenv j range lenv c ip jq c ir js c vijvi jvijvij vijcavija def main mpltoolkitsmplotd import axesd matplotlib import cm matplotlibticker import linearlocator formatstrformatter import matplotlibpyplot plt ydis xdis resis j range range v zeros float pq ri sj dv e lastdv count fabsdv lastdvefabsdv lastdv dv sweepvpqrs dvvpqvrs resisappenddv xdisappendrp ydisappendsq xarrayxdis yarrayydis zarrayresis fig pltfigure ax figaddsubplot projection axplotwireframexyz pltshow main,2 i assume would call locd filename cli if def looplocdfilename loops locd source files return subprocesscall locd filename def relocation subdir dirs files oswalkroot file files filename ospathjoinsubdir file return looplocdfilename in words open file let locd,i got problem short script great could look import os import subprocess root userssoftwarefmtomovremakerlastplotsourcerelocationobservedarrivalslocd def looplocdfilein loops locd source files return subprocesscall locd shelltrue def relocation subdir dirs files oswalkroot file files filein openospathjoinsubdir file r return looplocdfilein i think script quite easy understand simple however i getting result wanted in word i want locd operate files contents present observedarrivalslocd directory means i need open files i actually done in fact i try print files subdir dirs files oswalkroot i get name every file furthermore i try print filein filein openospathjoinsubdir file r i get something like line every file open file userssoftwarefmtomovremakerlastplotsourcerelocationobservedarrivalslocdevent mode r xfe subprocess tested alone one file working overall i getting errors means absolutely nothing the output locd completly different so code look fine is anything i missing any suggestion thanks help,1 currently relocation method return first iteration first file you need return def looplocdfilename loops locd source files return subprocesscall locd filename def relocation subdir dirs files oswalkroot file files filename ospathjoinsubdir file looplocdfilename this one issues the concerning locd try providing full path locd,i got problem short script great could look import os import subprocess root userssoftwarefmtomovremakerlastplotsourcerelocationobservedarrivalslocd def looplocdfilein loops locd source files return subprocesscall locd shelltrue def relocation subdir dirs files oswalkroot file files filein openospathjoinsubdir file r return looplocdfilein i think script quite easy understand simple however i getting result wanted in word i want locd operate files contents present observedarrivalslocd directory means i need open files i actually done in fact i try print files subdir dirs files oswalkroot i get name every file furthermore i try print filein filein openospathjoinsubdir file r i get something like line every file open file userssoftwarefmtomovremakerlastplotsourcerelocationobservedarrivalslocdevent mode r xfe subprocess tested alone one file working overall i getting errors means absolutely nothing the output locd completly different so code look fine is anything i missing any suggestion thanks help,1 if python starting point acceptable rpy lets go ways r python call python code executing r code doc,i know exists module rpy rpy convert r code python is easy way reverse,2 the code linked article djangomongodbenginemongodb engine setting you also need djangononrel work,i django installed server pymongo mongoenginemy django project settingspy file django settings debug true templatedebug debug admins your name youremailexamplecom managers admins databases default engine djangomongodbengine add postgresqlpsycopg postgresql mysql sqlite oracle name rtsdatabase or path database file using sqlite user not used sqlite password not used sqlite host localhost set empty string localhost not used sqlite port set empty string default not used sqlite supportstransactions false local time zone installation choices found httpenwikipediaorgwikilistoftzzonesbyname although choices may available operating systems on unix systems value none cause django use timezone operating system if running windows environment must set system time zone timezone americachicago language code installation all choices found httpwwwinguycomunicodelanguageidentifiershtml languagecode enus siteid if set false django make optimizations load internationalization machinery usein true if set false django format dates numbers calendars according current locale useln true absolute filesystem path directory hold useruploaded files example homemediamedialawrencecommedia mediaroot url handles media served mediaroot make sure use trailing slash examples httpmedialawrencecommedia httpexamplecommedia mediaurl absolute path directory static files collected don put anything directory store static files apps static subdirectories staticfilesdirs example homemediamedialawrencecomstatic staticroot url prefix static files example httpmedialawrencecomstatic staticurl static url prefix admin static files css javascript images make sure use trailing slash examples httpfoocomstaticadmin staticadmin adminmediaprefix staticadmin additional locations static files staticfilesdirs put strings like homehtmlstatic cwwwdjangostatic always use forward slashes even windows don forget use absolute paths relative paths list finder classes know find static files various locations staticfilesfinders djangocontribstaticfilesfindersfilesystemfinder djangocontribstaticfilesfindersappdirectoriesfinder djangocontribstaticfilesfindersdefaultstoragefinder make unique share anybody secretkey tpazgzlbsaiampfzsczuuampgswopsrastav list callables know import templates various sources templateloaders djangotemplateloadersfilesystemloader djangotemplateloadersappdirectoriesloader djangotemplateloaderseggsloader middlewareclasses djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware rooturlconf rtsurls templatedirs put strings like homehtmldjangotemplates cwwwdjangotemplates always use forward slashes even windows don forget use absolute paths relative paths installedapps djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles uncomment next line enable admin djangocontribadmin uncomment next line enable admin documentation djangocontribadmindocs rtsrestapi a sample logging configuration the tangible logging performed configuration send email site admins every http error see httpdocsdjangoprojectcomendevtopicslogging details customize logging configuration logging version disableexistingloggers false handlers mailadmins level error class djangoutilslogadminemailhandler loggers djangorequest handlers mailadmins level error propagate true whenever try access project gives error exception value djangomongodbengine available database backend try using djangodbbackendsxxx xxx one dummy mysql oracle postgresql postgresqlpsycopg sqlite error no module named djangomongodbenginebase i dont know i wrong settings filei following httpwwwchrisumbelcomarticledjangopythonmongodbenginemongo help,3 docs note return code testrunner script number failed erroneous tests if tests pass return code this feature useful using testrunner script shell script need test success failure level could something else going wrong wrapping test command something else returns,my django unit tests returns exit code unit tests passing unit tests failing because exit code cases i cannot qualify build success failure script any reason django version python version linux generic ubuntu smp fri mar utc x gnulinux,1 using two simplecookie objects solves c cookiesimplecookie cemailaddress selfrequestget emailaddress c cookiesimplecookie csecretcode selfrequestget secretcode csecretcodepath selfresponseheadersaddheadersetcookie coutputheader selfresponseheadersaddheadersetcookie coutputheader,i using google app engine how i set either multiple cookies multivalue cookie single response right i using code url httplocalhostservershowcookieemailaddressmyemailgmailcomampsecretcode c cookiesimplecookie cemailaddress selfrequestget emailaddress csecretcode selfrequestget secretcode csecretcodepath headervalue coutputheader selfresponseheadersaddheadersetcookie headervalue work value headervalue emailaddressmyemailgmailcom secretcode path well formed header missing comma how i create well formed cookie values,2 you could define default mixin class defaultobject def reprself return join strgetattrselfkey key selfdict keystartswith def eqselfother try return allgetattrselfkeygetattrotherkey key selfdict keystartswith except attributeerror return false class foodefault def initself selfbar selfbaz hi foofoo printfoo hi foofoo printfoofoo true foobar printfoofoo false,are ways add simple implementations str eq repr class basically i want eq whether non prefixed instance variables equal and str repr names variable calls strrepr variable is mechanism standard library,3 probably reconfigure pydev python interpreter get new added libs from pydev tutorial if add something python installation need either add manually new folder system pythonpath still folder pythonpath recommended remove interpreter add press apply note added library already folder pythonpath least go interpreter preferences press apply clears internal caches configuration done things set stone pydev,i imports python sometimes i package yet i install package the problem i test python interpreter resolves imports python r nov msc v bit amd win type help copyright credits license information termcolor import colored however eclipse i still get errors unresolved imports i fix are eclipse like editors python,1 you might want try psphere python library based suds give access entire vsphere web services sdk install pip install psphere find virtual machine print number cpus psphereclient import client pspheremanagedobjects import virtualmachine client clientservervcentermydomaincom usernameadministrator passwordstrong vm virtualmachinegetclient namegenesis vm pspheremanagedobjectsvirtualmachine object xdfbccc prints cpus vmname vmconfighardwarenumcpu genesis cpus you find examples documentation disclaimer i author psphere,how contact vsphere vmware form python either form library via suds get number number vcpu specific hostguestvirtualmachine currently trying sudsclient import client sudssudsobject import property client clienthttpsserversdkvimservicewsdl querycon clientwsdlservicesportsmethods queryconnectioninfo print querycon and works gives form output method name queryconnectioninfo location httpslocalhostsdkvimservice binding binding input sudsbindingsdocumentdocument instance xc output sudsbindingsdocumentdocument instance xc soap soap action urnvim style document input input body body parts part root part nameparameters elementvimqueryconnectioninfo name parameters qname parameters urnvim element u queryconnectioninfo u urnvim type none use literal namespace vim urnvim wrapped true headers empty output output body body parts part root part nameparameters elementvimqueryconnectioninforesponse name parameters qname parameters urnvim element u queryconnectioninforesponse u urnvim type none use literal namespace vim urnvim wrapped true headers empty faults fault name invalidloginfault use literal parts part root part namefault elementviminvalidloginfault name fault qname fault urnvim element u invalidloginfault u urnvim type none fault name hostconnectfaultfault use literal parts part root part namefault elementvimhostconnectfaultfault name fault qname fault urnvim element u hostconnectfaultfault u urnvim type none fault name runtimefault use literal parts part root part namefault elementvimruntimefaultfault name fault qname fault urnvim element u runtimefaultfault u urnvim type none i tried following following guides suds programmatic access methods types httpwwwvmwarecomsupportdevelopervcsdkvisdkpubsapireferencevimvirtualmachinehtmlfielddetail httpcommunitiesvmwarecomthread i know information probably see entire picture after trying get stuck client clienthttpsserversdkvimservicewsdl querycon clientwsdlservicesportsmethods queryconnectioninfo print clientservicequeryconnectioninfohttpsserversdk none r domainuser password and output urlliburlerror urlopen error errno sslc errorfcssl routinessslgetserverhellounknown protocol,1 you use foo case foo falsy value empty list etc result empty string another way would foo none else foo,something string var equal none i want statements verify value is simple way like strmyvar return string value none none,3 you may use gtktreeviewgetselection method get gtktreeselection next use gtktreeselectiongetselectedrows method get treemodel liststore selected items paths then use gtktreemodelgetiter order get iter path returned gtktreeselectiongetselectedrows method finally may use gtktreemodelgetvalue method get value corresponding column iter previously recovered example def onselectionchangedtreeselection model pathlist treeselectiongetselectedrows path pathlist treeiter modelgetiterpath value modelgetvaluetreeiter print value liststore gtkliststoreint treeview gtktreeview treeviewsetmodelliststore treeselection treeviewgetselection treeselectionsetmodegtkselectionmultiple treeselectionconnectchanged onselectionchanged,i learning pygtk i simple treeview column i get items treeview list how get value selected item treeview,3 this real solution problem type reset terminal closed app goes back normal i similar issues developing c application close pipe correctly maybe something similar happening aswell,i writing small utility application using python testcase also works python however pyqt uses code module spawn repl prompt allowing interaction qt window unfortunately i hit problem i unable solve when i exit app code inside input known rawinput python x linux terminal subsequently longer echoes typed characters ie terminal appears left broken state presumably due escape sequence issued input i tried variety approaches fix using curses module means reset terminal prior running exit trying emulate stdin stream exit actually handing exit input unfornunately codeinteractiveconsolepush work way one might think would trying write nonblocking input using threading i unable pull together something working here discussions similar problems finally reduced testcase demonstrate problem usrbinenv python import code import sys pyqtqtgui import qapplication qwidget app qapplicationsysargv applastwindowclosedconnectexit widget qwidget widgetshow codeinteract for unfamiliar pyqt open blank window closed connection app lastwindowclosed signal cause call builtin exit function happen this occurs code module executing call input read sysstdin and i close window typing terminal afterwards show types characters i mainly using python actual app uses python specific code i tried testcase python well shows problem,3 you could config module parses options global variable module include places need admittedly though i agree delnan comment avoid globals possible general push design better code personally i find evil delnan says cases still make sense,i like parse parameters vars using configparser however i pass instance every py order get parameters what elegant way make parameters visible every py thanks,1 try add following lines vimrc set nocompatible filetype syntax enabled quit relaunch vim execute vimrc reload settings nocompatible remove compatibility original vi recommended get fully functional vim filetype activate automatic file type detection option want python code colored syntax enabled activate code coloring sure mandatory you get help typing help filetype vim,i using mac osx lion terminalapp supports output echo amptco in vimrc i pathtovimvimrc syntax filetype plugin indent set nobackup when i vim blahpy colorscheme torte syntax colors loading for example python keyword proper colors they regular text color that works c files python i updated syntaxpythonvim still luck can someone tell thanks,2 the following code straightup interpretation definition import math def averagex assert lenx return floatsumx lenx def pearsondefx assert lenx leny n lenx assert n avgx averagex avgy averagey diffprod xdiff ydiff idx rangen xdiff xidx avgx ydiff yidx avgy diffprod xdiff ydiff xdiff xdiff xdiff ydiff ydiff ydiff return diffprod mathsqrtxdiff ydiff test print pearsondef returns this agrees excel calculator scipy also numpy return respectively r cor c c edit fixed bug pointed commenter,i looking function takes input two lists returns pearson correlation significance correlation,3 import lines cat one dog silver fox two king kong p ot then mark first foobar second fish horse yellow third blue line lines print refindallr bazwazb line output cat dog silver fox king kong p ot then foobar fish yellow blue explanation baz means match one capital letters start word this match yellow e horse waz means match zero nonword characters followed one capital letters this match ot bar kong wazb means make noncapturing group matches zero times end word this match silver fox t follows,i find working regex python split strings cat one desired cat dog silver fox two desired dog silver fox king kong desired king kong p ot then mark first desired p ot then just stupid examples need separate words full uppercase words capitalized i could n uppercase words n capitalized words my regexs weird catch string one uppercase word,1 i think i found quite dirty way looking creole sourcecode code turns links html def linkemitself node target nodecontent nodechildren inside selfemitchildrennode else inside selfhtmlescapetarget return hrefssa selfattrescapetarget inside in python shell i tried following code import creole creolecreolehtml import emitter def newemitterself node return blah emitterhtmlemitterlinkemit newemitter creolecreolehtmlulink u pblahp the exact code replace spaces left exercice reader i still looking correct way official way,my goal create locallybrowsable clone bitbucket wiki browser pages written using creole syntax i using pythoncreole render files html it works relatively fine difference way pythoncreole bitbucket render internal links on bitbucket site internal link spaces like system programming render something like hrefwikisystemprogrammingsystem programminga spaces replaced using pythoncreole render hrefsystem programmingsystem programminga can i tweak pythoncreole replacing spaces,1 when print dict list tuple repr called items container rather str like print directly see unicode escape codes if mydict dictu u kategori divisjon fotball herrer u u kategoridebutalbum u kategorimusikkalbum fra u kategoritre smxe kineserealbum u u kategoriserierundene adeccoligaen u u kategoritippeligaen u u kategorimusikkalbum fra u u kategoriluftforsvaret u u kategorideltagermedaljen u kategorifxfdsler u kategorinorske folkemusikere u kategorinorske trekkspillere u kategoripaul harris fellow u kategoripersoner fra vefsn kommune key value mydictiteritems print key elem value print elem print you see strings encoded properly terminal you need anything strings interpret escape codes everything stored properly displayed,i saving data dictionary saving dictionary i printed data see looks like i see unicode u u kategori divisjon fotball herrer u u kategoridebutalbum u kategorimusikkalbum fra u kategoritre smxe kineserealbum u u kategoriserierundene adeccoligaen u u kategoritippeligaen u u kategorimusikkalbum fra u u kategoriluftforsvaret u u kategorideltagermedaljen u kategorifxfdsler u kategorinorske folkemusikere u kategorinorske trekkspillere u kategoripaul harris fellow u kategoripersoner fra vefsn kommune i following code i used format option really work what also confuses iswhen i print id prior saving dictionary i see without integer here segment code pageid pagedata data query pages iteritems categorytitles idtitledictionarypageid print pageid try category pagedata categories categorytitlesappendcategory title idtitledictionaryformatpageidappendcategorytitles i trying figure encode prior saving dictionary,1 a non regex solution tests cat one dog silver fox two king kong p ot then mark first splitlines isalluppercase lambda allcupper c c itertools import takewhile tests print print jointakewhileisalluppercasetsplit print gives cat one cat dog silver fox two dog silver fox king kong king kong p ot then mark first p ot then,i find working regex python split strings cat one desired cat dog silver fox two desired dog silver fox king kong desired king kong p ot then mark first desired p ot then just stupid examples need separate words full uppercase words capitalized i could n uppercase words n capitalized words my regexs weird catch string one uppercase word,1 the deep parsing argument names unique php afaik if need simple list pass several parameters name use requestargsgetlistparamname documentation otherwise parse query string,i know php i could use get key key retrieve get data sent form array something possible python i receive string recognized arraylist i use flaskwerkzeug matters,3 requestargs multidict instance multidict flask request api requestargskey returns single value first multiple requestargsgetlistkey returns list if want submit structures complex encoded using simple keyvals consider sending json encoded object also look jquery recursive param serialisation pattern jqueryunparam lib deserialise,i know php i could use get key key retrieve get data sent form array something possible python i receive string recognized arraylist i use flaskwerkzeug matters,3 you use python global keyword shown def openfiles global file global file file open filetxt w file open filetxt w def writefiles filewritehello openfiles writefiles however i would recommend use class instead for example class fileoperations def openfilesself selffile open filetxt w selffile open filetxt w def writetofilesself selffilewritehello you filehandler fileoperations filehandleropenfiles filehandlerwritefiles,i currently function within code def openfiles file open filetxt w file open filetxt w what i hoping second method write open file however whenever i try write files using example filewritehello error returned informing global variable file defined i tried declaring file string beginning code obviously string object i unsure write any suggestions i want number functions access files hence i like separate function opens thanks edited represent class class testclass def openfiles file open filetxt w file open filetxt w def writetofiles,3 no this would require pass reference you change local variable precisely parameter self fine influence whatever location reference passed argument came w and given circumstances implicitly passed self even possible apply usual hacks using singleelement list mutate x even tricks would work even obscure hack highly discouraged it goes everything python programmers used just make wrapper object act replaces ie forward everything selfo that make identity checks succeed far simplest cleanest maintainable solution note for sake experimenting nonstandard absolutely nonportable pypy extension replacing object completely pypybecome needless say extremely illadvised use find another solution,class wrapperobject def initself get wrapped object something selfo def funself args kwargs self selfo want swap low level c api like someassignself selfo swaps id mem addr selfo return selffunargs kwargs class a class aobject def funself return afun a w wrappera print typew wrapper print wfun operation i want loose wrapper print w goes false i like true original a object is way python,2 assigning self inside method simply rebinds local variable self new object generally assignment bare name never changes objects rebinds name lefthand side point object righthand side so would need modify object self points match object selfo points this possible a wrapper newstyle classes none defines slots selfclass selfoclass selfdict selfodict this work cpython i sure python implementation and even cpython terrible idea note condition last line code still false i think intend,class wrapperobject def initself get wrapped object something selfo def funself args kwargs self selfo want swap low level c api like someassignself selfo swaps id mem addr selfo return selffunargs kwargs class a class aobject def funself return afun a w wrappera print typew wrapper print wfun operation i want loose wrapper print w goes false i like true original a object is way python,3 regular expression substitution good finding patterns repeated dots replacing single dot import resubr aabc aabc,how would i python i string formatted like aabc to make like aabc but i know beforehand many dots i it like tr function linux,3 you got one many layers iteration replace forloop writerwriterowsreader or change writerows writerow row reader writerwriterowrow,code f open testtxt r todo open fbtxt w reader csvreaderfdelimiter quotechar writer csvwritertodo row reader writerwriterowsrow i want output input look like dddd systems corporationnatechnologycomputer software etc instead i got dddd systems corporation software prepackaged help,1 i think use pip easyinstall installing python libraries easyinstall already available python installing django easyinstall django terminal pip replacement easyinstall installing pip easyinstall pip pip installed installing django via pip pip install django,i kind confused i installed django mac i moved django folder documents opens terminal cd documentsdjango setuppy install now sorts problems trying install psycopg how uninstall remove django install cleanly and possible paste django folder directory i beginner django using terminal,2 i getting identical results matlab python versions are sure matlab version giving for example matlab x rand pi rand sinx cosx area sumi pi this yields your purepython version import randommath densityinte x randomuniformmathpi rangedensity randomuniform rangedensity mathsinxxmathcosxx yy xxyy zipxy print sumifloatdensitymathpi this yields numpybased import numpy np x nprandomrandome nppi nprandomrandomxsize npsinx npcosx print nppi isum xsize this yields,it close cat montepy import randommath densityinte x randomuniformmathpi rangedensity randomuniform rangedensity mathsinxxmathcosxx yy xxyy zipxy print sumifloatdensitymathpi python montepy i trying rewrite reason python code even close x rand pi rand sinx cosx area sumi pi,1 your condition letter text says write comma space character whenever last character equal value last character case first character character last character you change condition check really last character character last character you could letter enumeratetext stuff lentext sysstdoutwrite better might use join method print u joinstrvalue value unicodevalues furthermore want use quotes make shell send script input one arg argparse nargs options docs like gathering many args present you would still escape quotes want however make assumption whitespace args something like joinargs would approximate input,i made quick python script converts unicode ascii back i taking input via argparse contained within quotation marks ie converterpy friend the script output comma separated unicode values of course break input i know i escape putting front however reason stops comma added for example convertpy hi outputs as see comma space this code def charcodetext print unicode values length lentext letter text unicodevalues ordletter sysstdoutwritestrunicodevalues letter text sysstdoutwrite sysstdoutwrite rn if i remove letter text this stops problem happening comma added end unicode value string i want my questions thus i prevent happening b better way take input type would i better setting rawinput instance any help much appreciated thanks,2 from python docs these two make possible view heap regular python list without surprises heap smallest item heapsort maintains heap invariant is reason treat heap list iterate,i making montecarlo simulation and part task i generate samples uniformly distributed interval generate lambda uniform the iterations stop closest generated points pairs meet criteria check lambda ab true ba else false i need structure effectively keep generated points able go ascending order perform check subsequent pairs there heapq module python supports effective heap structure and i decided use i faced problem i found traversal procedure supported module the way i found access values heap ascending order use heapqheappop but deletes values heap i found workaround copied heap object new one iterated heappop new one but i think quite effective copy whole structure memory one every iteration is way i go i trying effectively the simplified code illustration import heapq random import uniform itertools import tee izip count copy import copy def pairwiseiterable get values iterator pairs b teeiterable nextb none return izipa b check lambda ab true ba else false generate lambda uniform def iterateheapheap heap copyheap here i copy heap able traverse try true yield heapqheappopheap except indexerror return def trial items count item generate heapqheappushitems item iterateheapitems pairwiseit allcheckab ab returns values returns true return print the solution reached it took iterations trial paiwise function recipe update in implementation heappop complexity iteration onlogn copying heap on adding new value heap ologn traversing n elements ologn popping value heap onlogn result onlognnlogn onlogn but i expect traversal on resultant complexity would on by way use sorted list would need sort list adding onlogn traversal would no on so resultant complexity still onlogn i found solution it use bisect module finding place add would ologn adding list on implementation values insertion place moved traversing on so resultant complexity on still i wounder way solve task using heaps python,2 if want general format replace sequence repeated characters one characters import aaabbc resubr r abc if want limit certain characters resubr w r abc resubr r aaabbc and example aabc resubr r aabc,how would i python i string formatted like aabc to make like aabc but i know beforehand many dots i it like tr function linux,2 what wrong simple jython code stdin stdout work expect import subprocess import os subprocesscallosenvironget shell binsh assuming want spawn shell tty following seems give better results import os import subprocess subprocesscallosenvironget shell binsh devtty devtty amp shelltrue this run shell within another subshell replaces crippled stdin stdout streams active tty,i need example jython java code exec interactive os shell binsh our development environment java linux what i would like provide means developers write jython scripts drop shell allows inspect system the reason i need exec jython javaas opposed wrapping shell scriptis use java load libraries i need keep loaded interactive shell running if jvm terminate interactive shell runs custom hardware would reset i looked jython subprocess module however i seen run wait subrocess terminate ie noninteractive none examples show shell invoked interactively the true java javalangruntimeexec examples i seen,1 instead subclassing delegate subclass model return icon item decorationrole untested sketch solution class iconmodelqsqltablemodel def dataself index roleqtdisplayrole indexcolumn filenamecolumnindex role qtdecorationrole filename supericonmodel selfdataindex qtdisplayrole return iconforfilenamefilename elif role qtdisplayrole return other columnsroles return supericonmodel selfdataindex role subclassing delegates much pain,i using qtableview qsqltablemodel show data sqlite db in db model column fields contain either paths ie homefoobartxt nothing for column view i would like render one icon items path different icon items nothing render actual datapath view i think i need set qstyleditemdelegate render icons place data staritemdelelgate included examples highlights editor function delegate i want without shedding light render qicons maybe i missing i looked api i unclear subclass qstyleditemdelegate even i need use case some guidance whether viable method example use qstyleditemdelegate render icons column preferably python would appreciated edit petr post solved issue a full implementation situation i described based petr solution def dataself index roleqtcoreqtdisplayrole indexcolumn role qtcoreqtdecorationrole filename supermoviemodel selfdataindex qtcoreqtdisplayrole filename return selfyesicon else return selfnoicon elif role qtcoreqtdisplayrole return other columnsroles return supermoviemodel selfdataindex role hope helps,1 i would use listsort heap that leaves heap condition intact makes possible iterate underlying list directly fwiw timsort algorithm used listsort take advantage partial ordering already exists heap,i making montecarlo simulation and part task i generate samples uniformly distributed interval generate lambda uniform the iterations stop closest generated points pairs meet criteria check lambda ab true ba else false i need structure effectively keep generated points able go ascending order perform check subsequent pairs there heapq module python supports effective heap structure and i decided use i faced problem i found traversal procedure supported module the way i found access values heap ascending order use heapqheappop but deletes values heap i found workaround copied heap object new one iterated heappop new one but i think quite effective copy whole structure memory one every iteration is way i go i trying effectively the simplified code illustration import heapq random import uniform itertools import tee izip count copy import copy def pairwiseiterable get values iterator pairs b teeiterable nextb none return izipa b check lambda ab true ba else false generate lambda uniform def iterateheapheap heap copyheap here i copy heap able traverse try true yield heapqheappopheap except indexerror return def trial items count item generate heapqheappushitems item iterateheapitems pairwiseit allcheckab ab returns values returns true return print the solution reached it took iterations trial paiwise function recipe update in implementation heappop complexity iteration onlogn copying heap on adding new value heap ologn traversing n elements ologn popping value heap onlogn result onlognnlogn onlogn but i expect traversal on resultant complexity would on by way use sorted list would need sort list adding onlogn traversal would no on so resultant complexity still onlogn i found solution it use bisect module finding place add would ologn adding list on implementation values insertion place moved traversing on so resultant complexity on still i wounder way solve task using heaps python,3 you want replace every run two dots single dot that achieved like import resubr aabc aabc you want need replace every run one dots single dot resubr aabc aabc that produces result pointless substitutions lone dots example consequently much slower timings python mtimeit simport resubberrecompiler subs subber loops best usec per loop python mtimeit simport resubberrecompiler subs subber loops best usec per loop,how would i python i string formatted like aabc to make like aabc but i know beforehand many dots i it like tr function linux,1 the key argument sorted takes function attribute what looking class prediction def initself l selfstart l selfend l selfscore l def ltself return selfstart otherstart this allows sorted order iterable instances class automatically only lt actually needed sorting python pep recommends implement rich comparisons use totalordering decorator,i class class prediction def initself l selfstart l selfend l selfscore l and list element prediction it aptly named predictions i want sort predictions start attribute prediction class something like predictionsstartorder sortedpredictions keystart which work what i missing,1 predictionsstartorder sortedpredictions keylambda x xstart,i class class prediction def initself l selfstart l selfend l selfscore l and list element prediction it aptly named predictions i want sort predictions start attribute prediction class something like predictionsstartorder sortedpredictions keystart which work what i missing,2 if really use regex pure python version works dots joinfilterbool aabcsplit aabc,how would i python i string formatted like aabc to make like aabc but i know beforehand many dots i it like tr function linux,1 i recommend fabric made kind thing,i able fire aws ubuntu ec instance boto have anyone tried upload script remote ubuntu ec more execute script via ssh locally the main objective automate whole process using python script written localhost is alternative way amazon api tools made possible,1 generally speaking matplotlib usually contain plotting functions operate one axes object subplot case the expectation write simple function string things together however like i quite sure data looks like quite simple build function scratch if always going working structured rec arrays simplify touch ie there always name associated data series omit specify names as example import itertools import numpy np import matplotlibpyplot plt def main nprandomseed numvars numdata data nprandomrandomnumvars numdata fig scatterplotmatrixdata mpg disp drat wt linestyle none marker color black mfc none figsuptitle simple scatterplot matrix pltshow def scatterplotmatrixdata names kwargs plots scatterplot matrix subplots each row data plotted rows resulting nrows nrows grid subplots diagonal subplots labeled names additional keyword arguments passed matplotlib plot command returns matplotlib figure object containg subplot grid numvars numdata datashape fig axes pltsubplotsnrowsnumvars ncolsnumvars figsize figsubplotsadjusthspace wspace ax axesflat hide ticks labels axxaxissetvisiblefalse axyaxissetvisiblefalse set ticks one side edge subplots axisfirstcol axyaxissetticksposition left axislastcol axyaxissetticksposition right axisfirstrow axxaxissetticksposition top axislastrow axxaxissetticksposition bottom plot data j zipnptriuindicesfromaxes k x ij ji axesxyplotdatax datay kwargs label diagonal subplots label enumeratenames axesiiannotatelabel xycoords axes fraction ha center va center turn proper x axes ticks j ziprangenumvars itertoolscycle axesjixaxissetvisibletrue axesijyaxissetvisibletrue return fig main,example scatterplot matrix is function matplotlibpyplot,3 you copy abcpy module python it dependencies use features specific python the python source complicated dependency weakrefset in addition copying abcpy may create versions isinstance issubclass functions abcaware,i trying use abstract base classes python httpdocspythonorglibraryabchtml however feature new python can i copy source file abcpy pythonpath everything work properly if else would i get abstract base classes python,1 q both nparray npastype approaches work way underthehood using npastype involves little less typing clear reader intention change datatype,q when recasting column different data type nparray npastype preferred i seen examples using npastype seem return desired result return copies original array import numpy np recasting string integer x nprecarray b names colcol in x out recarray b dtype col s col s dt xdtypedescr dt dt int appropriate nparrayxdtypedt xastypedt in out recarray b dtype col s col q renaming columns integer columns become zero calling nparray retains values nprecarray why my understanding former get structured array latter returns record array purposes i thought and behavior surprising case rename nd column col v dt copydeepcopyydtype names listdtnames names v dtnames names right newy nparrayydtypedt in newy out array b dtype col s v correct newy nprecarrayydtypedt in newy out recarray b dtype col s v,1 i think may limitation python i tested executing package either installed egg easyinstall option works fine for example system ubuntu test package called pkgexec current directory mainpy simply prints sysargv xxxxtmppkgexec python pkgexec usrbinpython pkgexec package cannot directly executed xxxxtmppkgexec python pkgexec homexxtmppkgexecpkgexecmainpy also according docs changed version supply package name run main submodule,is way enable package executed script for example easyinstall pathtofooegg python foo name world hello world i tried creating mainpy file inside package executed i using python the following error raised foo package cannot directly executed the structure package follows foo setuppy foo initpy mainpy running python foomain name world works expected i would prefer former way execution is possible,1 many possible things happen the basic the contents class block executed first read to see action example class fooobject print bar def initself print baz will print bar module imported if class metaclass defined metaclasses new function run classes block code run example class mymetatype def newmcs name bases kwargs print i metaclass checking return typenewmcs name bases kwargs class fooobject metaclass mymeta print i foo class output i foo class i metaclass checking i sure bits run well i familiar,when i import module class code executed class first read class object created is way i influence happens edit i realize question might bit general i looking something lowlevel allow introspection c i extend c application python i classes defined c exposed python the user inherit classes scripts i want able grab details first defined,3 i got answer openssl mailing list it seems digicert high assurance ev root ca signed another certificate authority selfsigned now two versions certificate one bundled ssl implementations provided download digicert selfsigned used root ca verifying certificates signs the version one returned facebook server ssl handshake process signed entrust certificate both public key keyid nss ssl implementation firefox chrome apparently correctly follows x specification ignores last certificate chain sent server uses trusted version digicert high assurance ev root ca verify chain python implementation openssl verifies digicert high assurance ca using certificate provided host turn tries verify last one since signed ca i provided certificate fails i think behavior correct since i already trust certificate middle chain theoretically i need check rest my solutions provide ssl module entrust certificate verifies digicert high assurance ev root ca,by pointing browser httpsgraphfacebookcomme i get encrypted https connection certificate chain digicert high assurance ev root ca root digicert high assurance ca facebookcom so i downloaded root certificate httpswwwdigicertcomdigicertrootcertificateshtm i also exported browser diff shows thing tried use python builtin ssl module verify authenticity connection graphfacebookcom i executed example httpdocspythonorglibrarysslhtmlclientsideoperation replacing cacert digicerthighassuranceevrootcacrt address graphfacebookcom the connection attempt fails exception sslsslerror errno sslc errorssl routinessslgetservercertificatecertificate verify failed if i try code certificate evrootdigicertcom address provided digicert testing client verify certificate everything works nicely via browser i could verify chain used connection digicert high assurance ev root ca root digicert high assurance ev ca evrootdigicertcom by running sslgetservercertificate graphfacebookcom i get certificate identifyed facebookcom browser means python code browser gets certificate validate why chrome validate graphfacebookcom given root certficate python validate another site root certificate python validate graphfacebookcom,2 you might interested metaclasses classes control creation classes,when i import module class code executed class first read class object created is way i influence happens edit i realize question might bit general i looking something lowlevel allow introspection c i extend c application python i classes defined c exposed python the user inherit classes scripts i want able grab details first defined,2 defining class a inherits b c executes a type a b c dictionary containing members class you influence process using metaclass programming there shortage blog posts tutorials subject,when i import module class code executed class first read class object created is way i influence happens edit i realize question might bit general i looking something lowlevel allow introspection c i extend c application python i classes defined c exposed python the user inherit classes scripts i want able grab details first defined,2 the code class definition executed like code variables created including function definitions context class instead global this means change class definition dynamically adding conditional code class aobject def fself print world gone mad else def fself print sanity rules a af sanity rules however i never seen done think reason feels rather unpythonic as others pointed lots ways modifying behaviour class including metaclasses inheritance class decorators,when i import module class code executed class first read class object created is way i influence happens edit i realize question might bit general i looking something lowlevel allow introspection c i extend c application python i classes defined c exposed python the user inherit classes scripts i want able grab details first defined,1 you use inspect module import inspect class tester object def method self print i tester print inspectgetsourcetester output class tester object def method self print i tester,suppose following code defined testerpy class tester object def method self print i tester following defined mainpy tester import tester tester print definition anyway could get definitions classfunction object systematic way parse code extract code definition manually save string,3 i suppose case intercept slope following function could used extended accommodate slopes intercepts readjust axis limits changed autoscale turned back def abline gca pltgca gcasetautoscaleonfalse gcaplotgcagetxlimgcagetylim import matplotlibpyplot plt pltscatterrangerange abline pltdraw,in r function called abline line drawn plot based specification intercept first argument slope second argument for instance plot abline line intercept slope spans entire range plot is function matplotlibpyplot,2 you use channel api accomplish request token time make xmlhttprequest open channel listen messages when app processes http request corresponding user clicking link send message channel created user extension more detail basically optionshtml make xhr something like var channel var socket var handler onmessage functionevt evtdata server sends channelsendmessage var xhr new xmlhttprequest xhronreadystatechange function error handling whatnot elided xhrreadystate xhrstatus we got response server the responsetext channel token listen verified message token xhrresponsetext channel new googappenginechanneltoken socket channelopenhandler xhropenpost httptingappspotcomauthsender true xhrsendformdata then server handler authsender page something like class authsenderhandlerwebapprequesthandler def postself get whatever data form send email let say userid field extracted either cookie post parameters link httpyourservercomauthhandleruserids userid message mailemailmessage messagebody stuff link fill message fields send create channel token using userid return client token channelcreatechanneluserid selfresponseoutwritetoken the two functions get client listening channel the next step happens user clicks link before sent link email including userid parameter purposes illustration may want use something else now user clicks link make http request authhandler path userid parameter so use userid identify channel send message like class authhandlerwebapprequesthandler def getself userid selfrequestgetuserid send message indicating user received email verified client page you may want send data channelsendmessageuserid authorized probably want show nice authorized page something and handleronmessage callback called whatever need user verified email address hope helps bit,i developing user authentication bookmarking extension the extension works google app engine python backend httptingappspotcom the first time extension runs backgroundhtml opens optionshtml new tab user enters email address i send email address app like tried yet optionshtml var formdata new formdata formdataappendextensionuser useremail var xhr new xmlhttprequest xhropenpost httptingappspotcomauthsender true xhrsendformdata in app handler authsender sends confirmation email user class authsenderwebapprequesthandler def postself newuser selfrequestgetextensionuser mailsendmail senderting tinggmailcom tonewuser subjectting bookmarking confirm email bodyclick link confirm email hrefhttptingappspotcomauthhandlera happy bookmarking if user clicks link email authreceive handler app process request send confirmation extension but i could figure send confirmation extension when user clicks link i send confirmation back extension do i use xmlhttprequest how and kind listener i need put extension below sketch authreceive handler app class authreceiveinboundmailhandler def receiveself message receive email i know part send confirmation extension i need help and backgroundhtml add listener save variable localstorage thanks help update this code conform moishe answer everything works except last step handleronmessage triggered optionshtml html headtitleextension optionstitlehead body penter gmail addressp textarea idgetemail stylemarginbottom px width px height px textareabr button idsavesavebutton button idsaveclearbutton script typetextjavascript documentgetelementbyidgetemailplaceholder gmail address send entered gmail address server documentgetelementbyidsaveaddeventlistener click function var useremail documentgetelementbyidgetemailvalue var formdata new formdata formdataappendextensionuser useremail var channel var socket var handler new object handleronmessage function evt evtdata server sends channelsendmessage consolelogevtdata received authhandler evtdata var xhr new xmlhttprequest xhronreadystatechange function error handling etc included xhrreadystate ampamp xhrstatus token xhrresponsetext channel new googappenginechanneltoken socket channelopenhandler xhropenpost httptingappspotcomauthsender true xhrsendformdata consolelogformdata sent authsender formdata false script body html authsender authhandler class authsenderwebapprequesthandler def postself newuser selfrequestgetextensionuser link httptingappspotcomauthhandlernewusers newuser message mailemailmessage messagesenderting tinggmailcom messagetonewuser messagesubjectting bookmarking confirm email messagebodyclick link confirm email link messagesend logginginfomessage sent messageto token channelcreatechannelnewuser selfresponseoutwritetoken class authhandlerwebapprequesthandler def getself newuser selfrequestgetnewuser channelsendmessagenewuser newuser logginginfonewuser sent client newuser working version related question optionshtml html head titleextension optionstitle work local url script typetextjavascript srcahchanneljsapiscript script typetextjavascript srchttpstalkgadgetgooglecomtalkgadgetchanneljsscript head body penter gmail addressp textarea idgetemail stylemarginbottom px width px height px textareabr button idsavesavebutton script documentgetelementbyidgetemailplaceholder gmail address documentgetelementbyidsaveaddeventlistener click function var useremail documentgetelementbyidgetemailvalue var formdata new formdata formdataappendextensionuser useremail var channel var socket var handler onopen function alertonopen onerror function alertonerror onclose function alertonclose onmessage function evt alertevtdata evtdata var xhr new xmlhttprequest xhronreadystatechange function xhrreadystate ampamp xhrstatus token xhrresponsetext channel new googappenginechanneltoken socket channelopenhandler xhropenpost httptingappspotcomauthsender true xhrsendformdata false script body html authsender authhandler class authsenderwebapprequesthandler def postself newuser selfrequestgetextensionuser link httptingappspotcomauthhandlernewusers newuser message mailemailmessage messagesenderting tinggmailcom messagetonewuser messagesubjectting bookmarking confirm email messagebodyclick link confirm email link messagesend token channelcreatechannelnewuser selfresponseoutwritetoken class authhandlerwebapprequesthandler def getself newuser selfrequestgetnewuser selfresponseoutwritenewuser channelsendmessagenewuser newuser,2 it probably problem graphics drivers you could try installing dev packages whatever graphics driver using look packages dev one fglrxamd nvidia mesaopen source name you probably also want install freeglut now always careful messing around package manager easy way break system,i tried installing pyglet sudo python setuppy install sudo aptget install pythonpyglet i luck running simple script i ubuntu bits file testpy line module window pygletwindowwindow file usrlocallibpythondistpackagespygletinitpy line getattr importimportname file usrlocallibpythondistpackagespygletwindowinitpy line module pygletgl import glinfo file usrlocallibpythondistpackagespygletglinitpy line module pygletgllib import glexception file usrlocallibpythondistpackagespygletgllibpy line module pygletgllibglx import linkgl linkglu linkglx file usrlocallibpythondistpackagespygletgllibglxpy line module gllib pygletlibloadlibrary gl file usrlocallibpythondistpackagespygletlibpy line loadlibrary raise importerror library found names importerror library gl found,1 for record right data structure case btree there implementation blist import sortedlist the runtime complexity low gets onlogn construct list on iterate,i making montecarlo simulation and part task i generate samples uniformly distributed interval generate lambda uniform the iterations stop closest generated points pairs meet criteria check lambda ab true ba else false i need structure effectively keep generated points able go ascending order perform check subsequent pairs there heapq module python supports effective heap structure and i decided use i faced problem i found traversal procedure supported module the way i found access values heap ascending order use heapqheappop but deletes values heap i found workaround copied heap object new one iterated heappop new one but i think quite effective copy whole structure memory one every iteration is way i go i trying effectively the simplified code illustration import heapq random import uniform itertools import tee izip count copy import copy def pairwiseiterable get values iterator pairs b teeiterable nextb none return izipa b check lambda ab true ba else false generate lambda uniform def iterateheapheap heap copyheap here i copy heap able traverse try true yield heapqheappopheap except indexerror return def trial items count item generate heapqheappushitems item iterateheapitems pairwiseit allcheckab ab returns values returns true return print the solution reached it took iterations trial paiwise function recipe update in implementation heappop complexity iteration onlogn copying heap on adding new value heap ologn traversing n elements ologn popping value heap onlogn result onlognnlogn onlogn but i expect traversal on resultant complexity would on by way use sorted list would need sort list adding onlogn traversal would no on so resultant complexity still onlogn i found solution it use bisect module finding place add would ologn adding list on implementation values insertion place moved traversing on so resultant complexity on still i wounder way solve task using heaps python,1 you calculate numbers like go googlecom type choose type choose type choose see wikipedia actual formula it scales like factorial function,i bruteforce approach trying find combination extension puzzle i trying get large number combinations test combination see fit certain criteria i generate combinations using python excellent itertools essentially gives iterator i go test one this returns quickly gives combinations check itertoolscombinationsrange this takes couple minutes give combinations test itertoolscombinationsrange when i get next level i need answer itertoolscombinationsrange when i get way combinations set takes long time ages am i inherently asking great deal combinations how scale,1 you use create links objects model for example many members website inviter also member type following class membermodel inviter modelsforeignkey self relatednameinvitedset if want inviter memberobjectsgetidexactinviter if want members member invited use memberobjectsgetidexactinvitedset,text django docs provide to create recursive relationship – object manytoone relationship – use modelsforeignkey’self’ if need create relationship model yet defined use name model rather model object someone give example usage capabilities django thanks,2 you asking choose combinations that lot looping trillion elements going happen desktop python – way if looking many supposed formula calculate directly without considering wikipedia edit i looked problem seems like trying solve considering possible combinations weights seeing work bruteforcing clearly going work situation – think cleverer solution,i bruteforce approach trying find combination extension puzzle i trying get large number combinations test combination see fit certain criteria i generate combinations using python excellent itertools essentially gives iterator i go test one this returns quickly gives combinations check itertoolscombinationsrange this takes couple minutes give combinations test itertoolscombinationsrange when i get next level i need answer itertoolscombinationsrange when i get way combinations set takes long time ages am i inherently asking great deal combinations how scale,3 i certain function findfullurl works being certain certain piece code works best way waste hours debugging time looking wrong place in fact function work you missing return def findfullurld e sd subtract move back another letter return findfullurld e else fullurl httpdownloadtedcomtalks sde pmp printfullurl return fullurl also using recursion solve task you use rfind instead def findfullurld e srfind you probably want handle condition found return httpdownloadtedcomtalks sde pmp,i writing simple script download mp tedtalks given list tedtalk website links run list tedtalk website links download tedtalk high quality mp import urllibrequest list website links l httpwwwtedcomindexphptalksviewid httpwwwtedcomindexphptalksviewid function takes location string pmp less location string returns full movie download link def findfullurld e sd subtract move back another letter findfullurld e else fullurl httpdownloadtedcomtalks sde pmp printfullurl return fullurl iterate list links download movie def iteratelistl x l get html f urllibrequesturlopenx convert html file string strfread utf fclose find location string interesting bit ends e sfindpmp e the problem variable url url findfullurld e printdownloading url todo download file i certain function findfullurl works if uncomment printfullurl line end findfullurl function see output download link exactly i need however iteratelist function i try capture string via url findfullurld e variable url seems take value none i understand it simple following example works i try interpreter def hello return hello url hello printurl,3 findfullurl return statement first branch statement in python means returns none,i writing simple script download mp tedtalks given list tedtalk website links run list tedtalk website links download tedtalk high quality mp import urllibrequest list website links l httpwwwtedcomindexphptalksviewid httpwwwtedcomindexphptalksviewid function takes location string pmp less location string returns full movie download link def findfullurld e sd subtract move back another letter findfullurld e else fullurl httpdownloadtedcomtalks sde pmp printfullurl return fullurl iterate list links download movie def iteratelistl x l get html f urllibrequesturlopenx convert html file string strfread utf fclose find location string interesting bit ends e sfindpmp e the problem variable url url findfullurld e printdownloading url todo download file i certain function findfullurl works if uncomment printfullurl line end findfullurl function see output download link exactly i need however iteratelist function i try capture string via url findfullurld e variable url seems take value none i understand it simple following example works i try interpreter def hello return hello url hello printurl,1 you try patch httpscodedjangoprojectcomticket i think better way dump data sql,how get django dumpdata management command stream contents file instead loading everything memory i trying convert gb sqlite database postgresql one method i considering dumping database json using python managepy dumpdata formatjson mydatabasejson this ran minutes consumed memory crashed machine,2 for models yet defined class gallerymodelsmodel titleimage modelsforeignkey image class imagemodelsmodel partof modelsforeignkeygallery since classes refer least one needs refer class yet defined,text django docs provide to create recursive relationship – object manytoone relationship – use modelsforeignkey’self’ if need create relationship model yet defined use name model rather model object someone give example usage capabilities django thanks,1 are sure error actually coming flask getting generic apache error page you look apache error log see error messages first the problem could configuration wsgi script file wrong failing due wrong syspath etc,i running ubuntu flask modwsgi apache when error occurs i unable get flask custom error page trigger debug mode output either it works fine i run without wsgi via apprundebugtrue i tried setting wsgierroroverride on off apache settings result anyone gotten issue thanks,1 yep surprising behaviour indeed however look output lsof two parallel child processes easy notice second child process file descriptors open what happens two parallel child processes get started second child inherits pipes parent parent calls selfparentconnclose second child still pipe file descriptor open pipe file description get closed kernel reference count effect selfchildconnrecvbytes first parallel child process never read eof eoferror gets never thrown you may need send explicit shutdown message rather closing file descriptors seem little control file descriptors get shared processes closeonfork file descriptor flag,i trying write class calculate checksums using multiple processes thereby taking advantage multiple cores i quite simple class works great executing simple case but whenever i create two instances class worker never exits it seems like never get message pipe closed parent all code found i first calculate md sha checksums separately works i try perform calculation parallel program locks time close pipe what going why pipes working i expect i guess i could workaround sending stop message queue make child quit way i really like know working import multiprocessing import hashlib class checksumpipemultiprocessingprocess def initself csname multiprocessingprocessinitself name csname selfsummer evalhashlibs csname selfchildconn selfparentconn multiprocessingpipeduplex false selfresultqueue multiprocessingqueue selfdaemon true selfstart selfchildconnclose this parent close unused end def runself selfparentconnclose this child close unused end true try print waiting data self block selfchildconnrecvbytes print got data self except eoferror print finished work self break selfsummerupdateblock selfresultqueueputselfsummerhexdigest selfresultqueueclose selfchildconnclose def updateself block selfparentconnsendbytesblock def hexdigestself selfparentconnclose return selfresultqueueget def main calculating first checksum works md checksumpipemd mdupdatehello print md mdhexdigest calculating second checksum works sha checksumpipesha shaupdatehello print sha shahexdigest calculating checksums parallel causes lockup md sha checksumpipemd checksumpipesha mdupdatehello shaupdatehello print md sha mdhexdigest shahexdigest lockup main ps this problem solved here working version code anyone interested import multiprocessing import hashlib class checksumpipemultiprocessingprocess allopenparentconns def initself csname multiprocessingprocessinitself name csname selfsummer evalhashlibs csname selfchildconn selfparentconn multiprocessingpipeduplex false checksumpipeallopenparentconnsappendselfparentconn selfresultqueue multiprocessingqueue selfdaemon true selfstart selfchildconnclose this parent close unused end def runself conn checksumpipeallopenparentconns connclose this child close unused ends true try print waiting data self block selfchildconnrecvbytes print got data self except eoferror print finished work self break selfsummerupdateblock selfresultqueueputselfsummerhexdigest selfresultqueueclose selfchildconnclose def updateself block selfparentconnsendbytesblock def hexdigestself selfparentconnclose return selfresultqueueget def main calculating first checksum works md checksumpipemd mdupdatehello print md mdhexdigest calculating second checksum works sha checksumpipesha shaupdatehello print sha shahexdigest calculating checksums also works fine md sha checksumpipemd checksumpipesha mdupdatehello shaupdatehello print md sha mdhexdigest shahexdigest main,3 what sorts times getting vs need surely execution time spent clevel code finding set intersections much optimization with random data results may vary data course sure good values sets elements set unique elements weights random print generating test data numsets setsize elements range u setelements r u s rangenumsets randomshuffleelements sappendsetelementssetsize w randomrandint xrange c costs i got performance like cprofile function calls cpu seconds ordered standard name ncalls tottime percall cumtime percall filenamelinenofunction stringmodule testpyfindmin testpyfunc len method append list objects method difference set objects method disable lsprofprofiler objects method intersection set objects hm mostly apparently time set intersections but i personally optimize especially cost clarity there going much bother,i came following implementation greedy set cover much discussion regarding original question from help i received i encoded problem greedy set cover receiving help i came following implementation i thankful everyone helping the following implementation works fine i want make scalablefaster by scalablefaster i mean say my dataset contains kk sets s the number elements u small order the size set s could anywhere and goes attempt u set r u s set set set set set set set set set w c costs def findmins r mincost minelement enumerates try cost wilensintersectionr cost mincost mincost cost minelement except division zero ignore pass return sminelement wminelement lenr si cost findmins r cappendsi r rdifferencesi costsappendcost print cover c print total cost sumcosts costs i expert python pythonspecific optimizations code would really nice,1 i know anything nsolve call syntax i tell neither sympy mpmath find real root function if fxexpx fx real x f function decreases absx gets bigger either direction always positive certainly root it might worthwhile reading normal distribution integrating seems work integratefx pierf,i code scitoolsstd import sympy import xsymbol x integral function def fx i also tried return expx fexpx intacintegratefx printnsolvefx the interpreter gives local variable x referenced assignment if i try nsolvefx gives could find root within given tolerance also i tried findrootf without success i imported mpmath import mpdps mppretty true,1 from tutorial sqlalchemy import filterorusername ed username wendy,i looked docs i cant seem find or query sqlalchemy i want query select address from addressbook where city boston and lastname bulger or firstname whitey should something like addr sessionqueryaddressbookfiltercity bostonfilter,3 do works also check whitepaper myths indentation python that found it starts whitespace significant python source code no general only indentation level statements significant ie whitespace left statements everywhere else whitespace significant used like like language you also insert empty lines contain nothing arbitrary whitespace anywhere i hope helps,i code like should break occur periods myvar somethinglikethiswherewedothingswherewedomorewhereweeverdomore way myvar somethinglikethiswherewedothings wherewedomore whereweeverdomore way myvar somethinglikethiswherewedothings wherewedomore whereweeverdomore,1 personally i prefer using parenthesis need myvar somethinglikethis wherewedothings wherewedomore whereweeverdomore i changed indentation editor indents automatically i looked pep looks like mention line breaks but parenthesis characters help editor indent code automatically require modify beginning end expression edit here style guide says thanks delnan the preferred way wrapping long lines using python implied line continuation inside parentheses brackets braces long lines broken multiple lines wrapping expressions parentheses these used preference using backslash line continuation make sure indent continued line appropriately the preferred place break around binary operator operator some examples class rectangleblob def initself width height color black emphasisnone highlight width height color red emphasis strong highlight raise valueerrorsorry lose width height color red emphasis none raise valueerrori think values width height blobinitself width height color emphasis highlight edit the style guide recommends breaking binary operator thanks neapolitan httpswwwpythonorgdevpepspepshouldalinebreakbeforeorafterabinaryoperator,i code like should break occur periods myvar somethinglikethiswherewedothingswherewedomorewhereweeverdomore way myvar somethinglikethiswherewedothings wherewedomore whereweeverdomore way myvar somethinglikethiswherewedothings wherewedomore whereweeverdomore,3 in applications like sometimes helpful bypass low level detail use socketmakefile higherlevel api instead in client close replace data mysocketrecv f mysocketmakefile rb data fread file method call need the source code ftplib shows production code,i new python basic question client side network socket connection make receive data in question client one initiates connection probably obvious i wanted clear i ask i another server client python allows server receive file client it works perfectly i cannot get example client receives file python keeps telling pipe broken i suspect client side i use line data mysocketrecv my suspicion client see data flowing thus closes connection server the server sees broken pipe the server client server libraries import import socket import os import sys import mcrypto mc information server size message transferred serveraddress keyport maxtransferblock file openspubpemr socket public key transfer keysocket socketsocket socketafinet socketsockstream keysocketbindserveraddress keyport keysocketlisten conn clientaddr keysocketaccept print connected clientaddr sends data client data fileread keysocketsendalldata keysocketclose client specified libraries import socket import mcrypto mc file transferred file opentesttxt r address server serveraddr port server listening destport data fileread creates socket transfer mysocket socketsocket socketafinet socketsockstream mysocketconnect serveraddr destport data mysocketrecv print data creates new file store msg name serverpubkeypem opens new file writes msg file open name w filewritedata closes socket mysocketclose i would appreciate help matter thanks,1 you want define special getitem docs method class testobject def getitemself arg return strarg test test print test print test kitten result kittenkittenkitten,i would like create new class acts special type container objects accessed using square brackets for example suppose i class called listwrapper suppose obj listwrapper when i say obj i expect method objaccess called argument then i return whatever i want is possible,3 python standard objects series methods named something mostly used allow create objects hook api language for instance getitem setitem methods called getting setting values notation there example create something looks like subclass python dictionary httpsgithubcomwavetossedmcdict note actually subclass dictionary also update method both necessary want class properly masquerade python dictionary,i would like create new class acts special type container objects accessed using square brackets for example suppose i class called listwrapper suppose obj listwrapper when i say obj i expect method objaccess called argument then i return whatever i want is possible,3 no schedule format support commaseparated times you instead description cron url dothiscron schedule every hours,i read manual httpcodegooglecomappenginedocspythonconfigcronhtml but i want task specific times description cron url dothiscron schedule every day is legit i havent seen examples times seperated comma,3 it appears x xn yn projected coordinate kilometers constructed x y using meshgrid arangexxn arangeyyn arange implict assumption km resolution step size arange unless specify otherwise is want it could huge array eg cover one continent km resolution suggest reality check printing x x y see look reasonable edit after looking xy reading qs plus library used came following version i cannot test dont modis data so let know doesnt work going withdraw write case try wait brorfred solution work namemain filename hdf file i cumdata z readairslvisfilename x getlatlonfilename extent satellite data covers x xn xmin xmax yn ymin ymax center point data xo yo xxn yyn resolution output grid km resolution ncolnrow image array ncol intxn x resolution nrow intyn resolution lower left corner image array projected coord p xo resolution ncol q yo resolution nrow xy coordinate colomns rows image array proj coord p p nparangencol resolution q q nparangenrow resolution xy coordiate grid point image array projected coord x y npmeshgridp q img interpknnnpcolumnstackxravel yravel zravel npcolumnstackxravel yravel imgshape nrow ncol,i using python my system running window vista bits i piece code reads radiance latitude longitude image filein hdf extension and try perform approximated nearest neighbor map but tries approximated nearest neighbor gives memory error the hdf file alone mb seems like size large here code namemain filename hdf file i cumdata z readairslvisfilename x getlatlonfilename x xn intxmin intxmax yn intymin intymax ncol xn x nrow yn x y npmeshgridnparangex xn nparangey yn img interpknnnpcolumnstackxravel yravel zravel npcolumnstackxravel yravel imgshape nrow ncol then functions imports pyhdfsd import sd import scipy sc import numpy np import pylab os import pyproj proj import matplotlibpyplot plt mpltoolkitsbasemap import basemap import scikitsann ann def readairslvisfilenamevariablenone allz function read hdf file air level b vis input airs hdf file input variables parameter optional default radiances returns dictionary data meta ospathexistsfilename raise invalid filepath reader sdfilename avariables readerdatasetskeys variablenone variable radiances elif variable avariables pass else raise invalid variable specified data readerselectvariableget data nparraydata allzappenddata outdict variable variable filename filenamesplit data data return outdictnpvstackallz this def getlatlon def getlatlonpath allx ally reader sdpath lat readerselect latitude get lon readerselect longitude get xy projlonlat x allxappendx allyappendy return npvstackallxnpvstackally this def interpknn approximated nearest neighbor ann def interpknndata z p print building kdtree k annkdtreedata print kdtree lookup ind dist kknnp print done img zind imgdist nnan return img error traceback recent call last file readhdfpy line module zravel npcolumnstackxravel yravel file cpythonlibsitepackagesnumpylibshapebasepy line columnstack return nxconcatenatearrays memoryerror so column stack giving error if problem i solve please give light edit i typed lines print value print xx print xshapexshape print yy print yshapeyshape print xx print xshapexshape print yy print yshapeyshape print xx print xnxn print yy print ynyn i got reult x xshape yshape x xshape y yshape x xn yn,1 i agree yosukesabai print x i think also make things bit harder i might understand code seems like converting latlon coordinates km convert latlon vectors getlatlon matrix back vectors i think need least standard scipy kdtree function here class converts positions latlon vector corresponding ij positions grid grid cells positions defined latlon matrices this seems want the function llij called latlon vectors corresponding data you use returned ij pairs look values image imgmatrixivecjvec import numpy np import pylab pl scipyspatial import kdtree ckdtree import pycdf pyhdfsd import sdsdc class scb def initself datadirprojdatajplscbromsijarea latnonelatnonelonnonelonnone selfi selfi size grid selfj selfj selfdatadir datadir g sddatadir scbdasgridnc sdcread selflat gselect lat selflon gselect lon selfllonselfllat npmeshgridselflonselflat def addijself iselfi iselfijselfj jselfj selfjmatselfimat npmeshgridnparangeselfjselfj nparangeselfiselfi selfijvec npvstacknpravelselfimatnpravelselfjmatt def addkdself selfkd ckdtreelistnpvstacknpravelselfllon npravelselfllatt def llijselflonlatnei hasattrself kd selfaddkd selfaddij distij selfkdquerylistnpvstacklonlattnei return selfijvecijselfijvecij the reason stamens addkd addij costly generate kdinstance large matrices i generate reuse different datasets basic concept follows addkd ckdtree kdtree initiated long list latlong pairs one pair grid cell these pairs generate flattening lat lon matrices addij two matrices consisting j positions flattened fashion lat lon matrices vectors lat lon values observations sent kdquery function vector positions closest pairs returned let assume following grid consisting three matrices lat lon positions data lon lat data we observations following latlon location obs obs ckdtree would initiated following latlon pairs corresponding ij pairs would kdquery would return positions grid latlon pairs closest positions observations those positions also ij pairs leads obs grid j j since grid following values vals you use valsivecjvec ivec jvec get grid values closest corresponds observations ivec jvec output llij,i using python my system running window vista bits i piece code reads radiance latitude longitude image filein hdf extension and try perform approximated nearest neighbor map but tries approximated nearest neighbor gives memory error the hdf file alone mb seems like size large here code namemain filename hdf file i cumdata z readairslvisfilename x getlatlonfilename x xn intxmin intxmax yn intymin intymax ncol xn x nrow yn x y npmeshgridnparangex xn nparangey yn img interpknnnpcolumnstackxravel yravel zravel npcolumnstackxravel yravel imgshape nrow ncol then functions imports pyhdfsd import sd import scipy sc import numpy np import pylab os import pyproj proj import matplotlibpyplot plt mpltoolkitsbasemap import basemap import scikitsann ann def readairslvisfilenamevariablenone allz function read hdf file air level b vis input airs hdf file input variables parameter optional default radiances returns dictionary data meta ospathexistsfilename raise invalid filepath reader sdfilename avariables readerdatasetskeys variablenone variable radiances elif variable avariables pass else raise invalid variable specified data readerselectvariableget data nparraydata allzappenddata outdict variable variable filename filenamesplit data data return outdictnpvstackallz this def getlatlon def getlatlonpath allx ally reader sdpath lat readerselect latitude get lon readerselect longitude get xy projlonlat x allxappendx allyappendy return npvstackallxnpvstackally this def interpknn approximated nearest neighbor ann def interpknndata z p print building kdtree k annkdtreedata print kdtree lookup ind dist kknnp print done img zind imgdist nnan return img error traceback recent call last file readhdfpy line module zravel npcolumnstackxravel yravel file cpythonlibsitepackagesnumpylibshapebasepy line columnstack return nxconcatenatearrays memoryerror so column stack giving error if problem i solve please give light edit i typed lines print value print xx print xshapexshape print yy print yshapeyshape print xx print xshapexshape print yy print yshapeyshape print xx print xnxn print yy print ynyn i got reult x xshape yshape x xshape y yshape x xn yn,1 you need call instance irc class pass pong constructor class irc def connectself try host sysargv port sysargv except indexerror print usage sysargv server portn sysexit selfs socketsocketsocketafinet socketsockstream selfsconnecthost port class pongthreadingthread def initselfircclass selfmyirc ircclass def pongself selfmyircssendtest girc irc gircconnect mypong ponggirc etc,i felt like working network programming threading oop skills i encountered problem though i class named irc class named pong i want use irc stuff like connecting server sending messages etc i want use pong thread background checks message containing ping class irc def connectself try host sysargv port sysargv except indexerror print usage sysargv server portn sysexit socketsocketsocketafinet socketsockstream sconnecthost port class pongthreadingthread def pongself ircssendtest irc attribute keep mind code simplified testing purposes question i use variables one class another class the variable declared defined irc needed pong the interpreter complains class irc attribute i tried calling connect first sample variable see works how i solve i new comes threading object orientation thanks advance,2 i know i tardy party i ran across searching answer issue to allow testapp pass non xxxx responses back need tell request allow errors def testapiusersindexpostmalformedself r selftestapppost apiusers params expecterrorstrue assert rheader contenttype applicationjson assert rstatus happy hacking,i using paste functional testing controllers webpy app in one case i trying test response malformed post made api endpoint here test looks like def testapiusersindexpostmalformedself r selftestapppost apiusers params assert rheader contenttype applicationjson assert rstatus but i getting following exception apperror bad response bad request ok xx redirect apiusers i see paste httpexception middleware i find examples use even right way go any suggestions or i going wrong,3 it looks like file named copypy picked instead python standard library module copy rename delete file copypyc created or run different directory,i using ubuntu making mistake installing lamp unable connect database i came read important use aptget install pythonmysqldb instead deleted lamp reinstalled using aptget getting error trying run basic serverversionpy script the script serverversionpy found httpwwwkitebirdcomarticlespydbapihtml my serverversionpy script serverversionpy retrieve display database server version import mysqldb i also tried setting host localhost conn mysqldbconnect host optlamppvarmysqlmysqlsock user root passwd myrealpass db testdb cursor conncursor cursorexecute select version row cursorfetchone print server version row cursorclose connclose the error traceback recent call last file serverversionpy line db testdb file usrlibpymodulespythonmysqldb init py line connect return connectionargs kwargs file usrlibpymodulespythonmysqldbconnectionspy line init converters import conversions file usrlibpymodulespythonmysqldbconverterspy line decimal import decimal file usrlibpythondecimalpy line import copy copy file homebrowningcopypy line valueerror need value unpack just trying get basic experience using databases python i set mysql better option i attempted reinstall mysqldb multiple times using aptget pip,2 put qwidget inside another qwidget background set colour you use layout parent qwidget adjust width margin side done within qt designer edit here steps take qt designer achieve select frame widget containing text widget break layout add new qwidget frame widget could name borderwidget set background colour border widget using stylesheet property property editor eg backgroundcolor white nb might help temporarily set contrasting colour easily see going drag drop text widget onto border widget select border widget set layout eg lay out grid select frame widget set layout eg lay out grid select border widget go layout section property editor there see properties like layouttopmargin layoutleftmargin etc used adjust size border,i making changes existing pyqt project the ui created qt designer the relevant part qwidget displays text i trying put margins around text i think simplest way would put border around qwidget whose background color qwidget background white the qwidget qframe i like put white border inside qframe around edge qwidget the closest i come put short vertical horizontal spacers around qwidget displays underlying grey qframe i figure make white i prefer leaving frame grey add white border around qwidget any pointers would appreciated edit the ui file xml version encodingutf ui version classebookviewerclass widget classqmainwindow nameebookviewer property namegeometry rect xx yy widthwidth heightheight rect property property namewindowtitle stringebook viewerstring property property namewindowicon iconset resourceresourcesimagesqrc normaloffimagesviewerpngnormaloffimagesviewerpngiconset property widget classqwidget namecentralwidget layout classqgridlayout namegridlayout item row column widget classqsplitter namesplitter property nameorientation enumqthorizontalenum property widget classqtreeview nametoc property namefocuspolicy enumqtwheelfocusenum property widget widget classqframe nameframe property nameframeshape enumqframestyledpanelenum property property nameframeshadow enumqframeraisedenum property layout classqgridlayout namegridlayout item row column colspan widget classqwidget nameviewbg nativetrue property namesizepolicy sizepolicy hsizetypemaximum vsizetypemaximum horstretchhorstretch verstretchverstretch sizepolicy property property nameminimumsize size widthwidth heightheight size property property namestylesheet string notrtruebackgroundwhitestring property layout classqgridlayout namegridlayout property nameleftmargin numbernumber property property nametopmargin numbernumber property property namerightmargin numbernumber property property namebottommargin numbernumber property item row column widget classdocumentview nameview nativetrue property nameminimumsize size widthwidth heightheight size property widget item layout widget item item row column widget classqscrollbar nameverticalscrollbar property nameorientation enumqtverticalenum property widget item item row column widget classqscrollbar namehorizontalscrollbar property nameorientation enumqthorizontalenum property widget item item row column colspan widget classqframe namedictionarybox property nameframeshape enumqframestyledpanelenum property property nameframeshadow enumqframeraisedenum property layout classqhboxlayout namehorizontallayout item widget classqwebview namedictionaryview property nameminimumsize size widthwidth heightheight size property property nameurl url stringaboutblankstring url property widget item item widget classqtoolbutton nameclosedictionaryview property nametooltip stringclose dictionarystring property property nametext stringstring property property nameicon iconset resourceresourcesimagesqrc normaloffimageswindowclosepngnormaloffimageswindowclosepngiconset property widget item layout widget item layout widget widget item layout widget widget classqtoolbar nametoolbar property namesizepolicy sizepolicy hsizetypefixed vsizetypepreferred horstretchhorstretch verstretchverstretch sizepolicy property property namewindowtitle stringtoolbarstring property property namemovable booltruebool property property nameiconsize size widthwidth heightheight size property property namefloatable boolfalsebool property attribute nametoolbararea enumlefttoolbarareaenum attribute attribute nametoolbarbreak boolfalsebool attribute addaction nameactionback addaction nameactionforward addaction nameseparator addaction nameactionopenebook addaction nameactioncopy addaction nameactionfontsizelarger addaction nameactionfontsizesmaller addaction nameactiontableofcontents addaction nameactionfullscreen addaction nameseparator addaction nameactionpreviouspage addaction nameactionnextpage addaction nameseparator addaction nameactionbookmark addaction nameactionreferencemode addaction nameseparator addaction nameactionpreferences addaction nameactionmetadata addaction nameseparator addaction nameactionprint widget widget classqtoolbar nametoolbar attribute nametoolbararea enumtoptoolbarareaenum attribute attribute nametoolbarbreak boolfalsebool attribute addaction nameactionfindnext addaction nameactionfindprevious widget action nameactionback property nameicon iconset resourceresourcesimagesqrc normaloffimagesbackpngnormaloffimagesbackpngiconset property property nametext stringbackstring property action action nameactionforward property nameicon iconset resourceresourcesimagesqrc normaloffimagesforwardpngnormaloffimagesforwardpngiconset property property nametext stringforwardstring property action action nameactionnextpage property nameicon iconset resourceresourcesimagesqrc normaloffimagesnextpngnormaloffimagesnextpngiconset property property nametext stringnext pagestring property action action nameactionpreviouspage property nameicon iconset resourceresourcesimagesqrc normaloffimagespreviouspngnormaloffimagespreviouspngiconset property property nametext stringprevious pagestring property action action nameactionfontsizelarger property nameicon iconset resourceresourcesimagesqrc normaloffimagesfontsizelargerpngnormaloffimagesfontsizelargerpngiconset property property nametext stringfont size largerstring property action action nameactionfontsizesmaller property nameicon iconset resourceresourcesimagesqrc normaloffimagesfontsizesmallerpngnormaloffimagesfontsizesmallerpngiconset property property nametext stringfont size smallerstring property action action nameactiontableofcontents property nameicon iconset resourceresourcesimagesqrc normaloffimageschapterspngnormaloffimageschapterspngiconset property property nametext stringtable contentsstring property action action nameactionmetadata property nameicon iconset resourceresourcesimagesqrc normaloffimagesdialoginformationpngnormaloffimagesdialoginformationpngiconset property property nametext stringmetadatastring property action action nameactionopenebook property nameicon iconset resourceresourcesimagesqrc normaloffimagesdocumentopenpngnormaloffimagesdocumentopenpngiconset property property nametext stringopen ebookstring property action action nameactionfindnext property nameicon iconset resourceresourcesimagesqrc normaloffimagesarrowdownpngnormaloffimagesarrowdownpngiconset property property nametext stringfind nextstring property property nametooltip stringfind next occurrencestring property property nameshortcut stringfstring property action action nameactioncopy property nameicon iconset resourceresourcesimagesqrc normaloffimageseditcopypngnormaloffimageseditcopypngiconset property property nametext stringcopy clipboardstring property action action nameactionpreferences property nameicon iconset resourceresourcesimagesqrc normaloffimagesconfigpngnormaloffimagesconfigpngiconset property property nametext stringpreferencesstring property action action nameactionreferencemode property nameicon iconset resourceresourcesimagesqrc normaloffimageslookfeelpngnormaloffimageslookfeelpngiconset property property nametext stringreference modestring property action action nameactionbookmark property nameicon iconset resourceresourcesimagesqrc normaloffimagesbookmarkspngnormaloffimagesbookmarkspngiconset property property nametext stringbookmarkstring property action action nameactionfullscreen property nameicon iconset resourceresourcesimagesqrc normaloffimagespagepngnormaloffimagespagepngiconset property property nametext stringtoggle full screenstring property action action nameactionprint property nameicon iconset resourceresourcesimagesqrc normaloffimagesprintpngnormaloffimagesprintpngiconset property property nametext stringprintstring property action action nameactionfindprevious property nameicon iconset resourceresourcesimagesqrc normaloffimagesarrowuppngnormaloffimagesarrowuppngiconset property property nametext stringfind previousstring property property nametooltip stringfind previous occurrencestring property property nameshortcut stringshiftfstring property action widget customwidgets customwidget classqwebviewclass extendsqwidgetextends headerqtwebkitqwebviewheader customwidget customwidget classdocumentviewclass extendsqwidgetextends headercalibreguiviewerdocumentviewhheader containercontainer customwidget customwidgets resources include locationresourcesimagesqrc resources connections ui,1 because separate loops first one executed second one executed you want here layout take number input store inputnum inputnum determine whether inputnum positive negative add inputnum either posnumber negnumber print total get new inputnum that inside two whiles,i homework problem i cant figure someone help create function called sums prompt user enter integer values either positive negative the function keep separate running totals positive values negative values the user allowed continue entering values heshe enters zero stop here i got work number intrawinputenter positive negative integer def sumsnumber number posnumber intrawinputenter another number quit number number posnumber print the positive total number number negnumber intrawinputenter another number quit number number negnumber print the negative total number runs loop first iteration i confused correct,3 can help cpd consider trying clonedr duplicate code detector it python front end sample results clone detection runs site pretty much clonedr manages find clones everybody code especially good,i trying run gui version cpd python codebase duplicate code returned even set min chunk size my code isnt good anyone ever success running cpd python project,1 here script parses one million instrumentconfiguration elements mb file seconds machine without consuming large amount memory the throughput mbs the celementtree page reports mbs usrbinenv python itertools import imap islice izip operator import itemgetter xmletree import celementtree etree def parsexmlfilename imapitemgetter iteretreeiterparsefilename events start root nextit get root element elem elemtag httppsihupoorgmsmzmlinstrumentconfiguration values id elemget id parameter nextitget name cvparam componentlistcount intnextitget count parent child isliceizipit componentlistcount key parenttagpartition value childget name assert childtagendswith cvparam valuesappendkey value yield values rootclear preserve memory def printvaluesit line joinval conf val conf printline printvaluesparsexmlfilename output usrbintime python parsemxmlpy id qtof parameter qtof ultima source nanoelectrospray analyzer quadrupole analyzer timeofflight detector microchannel plate detector user system elapsed cpu avgtextavgdata maxresidentk inputsoutputs majorminorpagefaults swaps note the code fragile assumes first two children instrumentconfiguration cvparam componentlist values available tag names attributes on performance elementtree times slower celementtree case if replace rootclear elemclear code faster times memory lxmletree works elemclear variant performance celementtree consumes rootclear elemclear times much memory mb,i trying parse huge xml file ranging mbgb files samples coming different instrumentation so i finding necessary element information file inserting database django small part file sample namespace exist files interesting feature files node attributes text xml version encodingiso mzml xmlnshttppsihupoorgmsmzml xmlnsxshttpwwwworgxmlschemainstance xsschemalocationhttppsihupoorgmsmzml httppsidevinfofilesmsmzmlxsdmzmlxsd accessionplgsexample version idurnlsidproteiosorgmzmlplgsexample instrumentconfiguration idqtof cvparam cvrefms accessionms nameqtof ultima componentlist count source order cvparam cvrefms accessionms namenanoelectrospray source analyzer order cvparam cvrefms accessionms namequadrupole analyzer analyzer order cvparam cvrefms accessionms nametimeofflight analyzer detector order cvparam cvrefms accessionms namemicrochannel plate detector detector componentlist instrumentconfiguration small complete file so i done till using findall every element interest import xmletreeelementtree et treeetparse plgsexamplemzml roottreegetroot nshttppsihupoorgmsmzml streefindall httppsihupoorgmsmzmlinstrumentconfiguration ins rangelens insattribsinsattrib it print id attribute instrument print insattribid how i access childrengrandchildren instrumentconfiguration element streefindall httppsihupoorgmsmzmlinstrumentconfiguration example i want instrumentconfiguration idqtof parameter ttof ultima sourcenanoelectrospray analyzer quadrupole analyzer timeofflight detector microchannel plate decector is efficient way parsing elementsubelementsubelement namespace exist or i use findfindall every time access particular element tree namespace this small example i parse complex element hierarchy any suggestions edit didn got correct answer edit,2 i came across code today rhelp listserve maybe help things along sendemail functionto subject message attachmentnull username password serversmtpgmailcom confirmbeforesendtrue list object length using listrecipient recipsomewherenet send message address name appear instead address list object length same behavior subject character giving subject line message character giving body message attachment character giving location attachment username character giving username if missing using windows r prompt username password character giving password if missing using windows r prompt password server character giving smtp server confirmbeforesend logical if true dialog box appears seeking confirmation sending email this prevent send multiple updates collaborator i working interactively islistto islistfrom stop must lists lengthfrom stop must length lengthto stop sendemail currently supports one recipient email address lengthattachment stop sendemail currently send one attachment lengthmessage stop message must length message pastemessage collapsenn isnullnamesto namesto isnullnamesfrom namesfrom isnullattachment fileexistsattachment stoppaste attachment exist sep missingusername username windialogstringplease enter email username missingpassword password windialogstringplease enter email password requirerjython rjython rjython rjythonexecimport smtplib rjythonexecimport os rjythonexecfrom emailmimemultipart import mimemultipart rjythonexecfrom emailmimebase import mimebase rjythonexecfrom emailmimetext import mimetext rjythonexecfrom emailutils import commaspace formatdate rjythonexecfrom email import encoders rjythonexecimport emailutils mailc email settings pastefromaddr sep pastetoaddrs sep msg mimemultipart pastemsgattachmimetext message sep pastemsg from emailutilsformataddr namesfrom fromaddr sep pastemsg to emailutilsformataddr namesto toaddrs sep pastemsg subject subject sep isnullattachment mail cmail pastef attachment sep partmimebase application octetstream partsetpayloadopenf rb read encodersencodebasepart partaddheader contentdisposition attachment filenames ospathbasenamef msgattachpart smtp server credentials mail cmail pasteusername username sep pastepassword password sep set smtp server send email eg google mail smtp server pasteserver smtplibsmtp server sep serverehlo serverstarttls serverehlo serverloginusernamepassword serversendmailfromaddr toaddrs msgasstring serverquit messagedetails pasteto namesto unlistto n from namesfrom unlistfrom n using server server n subject subject n with attachments attachment n and messagen message n sep confirmbeforesend send windialogyesnocancel pasteare sure want send email unlistto sep else send yes send yes jythonexecrjythonmail catmessagedetails else catemail delivery canceled user now i try xpastegetwdeercise docsep sendemaillistbigbirdgmailcom listbigbirdgmailcom dogs i sent attachmentx bigbirdgmailcom mypassword serversmtpgmailcom confirmbeforesendfalse and the error xpastegetwdeercise docsep sendemaillistbigbirdgmailcom listbigbirdgmailcom dogs i sent attachmentx bigbirdgmailcom mypassword serversmtpgmailcom confirmbeforesendfalse error jcallrjavatools ljavalangobject invokemethod cl syntaxerror mismatched character n expecting string tpartaddheader contentdisposition attachmentn,i desiring send email r attachment using gmail i found sendmailr work gmail requires authentication i get work gmail i assume true unless someone tells i wrong case i post r output error message i found code snippet found link as site suggests code formatted send attachments i got send email i like extend code send attachments email correspondence author code unable extend code send attachments i want send emails r using gmail i windows user beta version r the code sends emails attachments requirerjython rjython rjython rjythonexec import smtplib rjythonexecfrom emailmimetext import mimetext rjythonexecimport emailutils mailc email settings fromaddr bigbirdgmailcom toaddrs oscarthegrouchgmailcom msg mimetext this body message msg from emailutilsformataddr sender name fromaddr msg to emailutilsformataddr recipient name toaddrs msg subject simple test message smtp server credentials username bigbirdgmailcom password pw set smtp server send email eg google mail smtp server server smtplibsmtp smtpgmailcom serverehlo serverstarttls serverehlo serverloginusernamepassword serversendmailfromaddr toaddrs msgasstring serverquit jythonexecrjythonmail note message cross posted talkstatscom i receive reply members telling wish could help if i receive workable solution also post well,2 research tune yards tune yards music sresrematch object xadb research tune yards tuneyards trombone sresrematch object xad and match objects always true possible returned value none result tested via,using python i want search example tune yards block text may say tuneyards hyphen may say tune yards without i want considered matches i using find function is good pythonic way treat spaces one instead stacking elif statements something like i know work p treating blockoftextfind tune yards something,2 as long csv valid example kml values properly quoted load fine if believe refine issue skip upload csv directly via fusion tables ui,i csv file area id area name url kml file area boundaries httplinktoareaidkml how i load kml column csv order upload fusion tables i working python the kml also available json helps i know i need add geometry column fusion table i literally understand get csv file i upload fusion tables thanks help update i tried write kml string column csv polygonpolygon fusion tables refusing import error perhaps file large,1 sure seduce developer flickr dev team get open back door or use mad haxr skills sans seduction seriously though flickr says need api key use api so get api key or could scrape entire flickr site building metadata site the compute storage budget might excessive,does anyone know something like possible do quick search using tags public flickr images without using api ley retrieve images based search i already read why i need flickr api key i want know libs search without or maybe give rss set listdictflickr object images,1 try using treebook update alternatively try something wxlibagwfoldpanelbar check demo demo suite depending actually need may enough if always make scratch,my question simple get make navigation panel similar finder mac os x explorer windows nautilus ubuntu as using wxtreectrl work example httppastepocooorgshow as see first problem huge pink strip left remove second root else put buffer hidden buffer second kludgy third really either three example looks like so i get navigation panel similar examples well except tree ctrl example p update on windows windows least problem left side white column might linux macos x tree ctrl widget generically drawn one could run example macos x see pink column pink example sets background color left tree ctrl update itunes example there seems little misunderstanding question file manager folder view i looking navigation panel side i for example itunes also file manager left side bunch click able tabs used navigate example itunes music movies tv shows audiobooks apps library also problem tree ctrl doesn t work linux see image,1 the following code a notes wokkel uses socalled subprotocol handlers cover support specific subprotocols usually split conceptual feature namespace per xep xmppclient socalled stream manager establishes connections takes care authentication server it works hookedup subprotocol handlers process traffic xml stream manages it automatically reconnects connection lost this example defines one new handler process incoming messages unlike original code request retrieve ip address done incoming message ip body in original code status never called i use presenceprotocol subprotocol handler send presence time connection established authentication taken place the example socalled twisted application started using twistd mentioned docstring this daemonize process logs go twistedlog if specify n detach log console instead usrbinpython xmpp example client replies ip address upon request usage twistd ipbottac import configparser twistedapplication import service twistedpython import log twistedwebclient import getpage twistedwordsprotocolsjabberjid import jid twistedwordsprotocolsjabberxmlstream import toresponse wokkelclient import xmppclient wokkelxmppim import presenceprotocol messageprotocol class iphandlermessageprotocol message handler sends presence returns ip upon request ivar presencehandler presence subprotocol handler type presencehandler lpresenceprotocol ivar show presence show value send upon connecting type show cunicode cnonetype def initself presencehandler shownone selfpresencehandler presencehandler selfshow show def connectioninitializedself connection established authenticated use given presence handler send presence messageprotocolconnectioninitializedself selfpresencehandleravailableshowselfshow priority def onmessageself message a message received if body incoming message equals cip retrieve ip address format response message callback def onpagepage address location pagesplitubr body us location address response toresponsemessage stanzatypemessage type responseaddelementbody contentbody selfsendresponse unicodemessagebody uip return getpagehttpapiwipmaniacom daddcallbackonpage dadderrbacklogerr read configuration file config configparserconfigparser configread ipbotconf user configget account login password configget account password presence configget presence presence set twisted application application serviceapplication xmpp client set xmpp client jid jiduser client xmppclientjid password clientlogtraffic true clientsetserviceparentapplication add presence handler presencehandler presenceprotocol presencehandlersethandlerparentclient add custom handler iphandler iphandlerpresencehandler presence iphandlersethandlerparentclient,i simple code xmpp bot python httpxmpppysourceforgenet usrbinpython coding utf import xmpp import urllib import configparser config configparserconfigparser configread ipbotconf user configget account login passwordconfigget account password presenceconfigget presence presence jidxmppprotocoljiduser clientxmppclientjidgetdomain clientconnect clientauthjidgetnodepassword parse ip strurl httpapiwipmaniacom f urlliburlopenurllibrequeststrurl response fread ipget responsesplitbr fclose def statusxstatus statusxmpppresencestatusxstatusshowpresencepriority clientsendmsging def messageconnmess global client messgetbody ip clientsendxmppprotocolmessagemessgetfromipget ipgetsend ip clientregisterhandler message message clientsendinitpresence true clientprocess please tell translate code use httpwokkeliknu twistedmatrixcom thanks lot,3 the equivalent python httpserver,what python equivalent python simplehttpserver,3 constantly reassigning adding strings together using operator slow i guess python yet optimizing so using stringjoin would preferable try import string def stringtohexstrings listhex c listhexappendhexlookupordc return stringjoinlisthex see faster,i using old version python embedded platform python telit platform the problem i function converting string hex it slow here function def stringtohexstrings strhex c strhex strhex hexloookupordc return strhex hexlookup lookup table python list containing hex representation character i willing try everything compact function language tricks i know to clear benchmarks resolution second platform n number input characters converted hex time seconds n time seconds yes i know slow i could gain something like seconds would progress so solution welcomed especially people know python performance thanks iulian ps testing suggestions offered keeping ord call def stringtohexstrings hexlist hexlistappendhexlistappend c hexlistappendhexloookupordc return joinhexlist with function i obtained following times clearly better ps explain blazingly fast a big thank sven marnach idea def stringtohexstrings return join maplambda paramhexloookupparam mapords times any ideasexplanations welcome,1 try string import join def stringtohexstrings charlist c charlistappendhexloookupordc return joincharlist each string addition takes time proportional length string join also take time proportional length entire string you could also make hexlookup dict mapping characters hex values call ord every character it microoptimization probably significant,i using old version python embedded platform python telit platform the problem i function converting string hex it slow here function def stringtohexstrings strhex c strhex strhex hexloookupordc return strhex hexlookup lookup table python list containing hex representation character i willing try everything compact function language tricks i know to clear benchmarks resolution second platform n number input characters converted hex time seconds n time seconds yes i know slow i could gain something like seconds would progress so solution welcomed especially people know python performance thanks iulian ps testing suggestions offered keeping ord call def stringtohexstrings hexlist hexlistappendhexlistappend c hexlistappendhexloookupordc return joinhexlist with function i obtained following times clearly better ps explain blazingly fast a big thank sven marnach idea def stringtohexstrings return join maplambda paramhexloookupparam mapords times any ideasexplanations welcome,1 make hexloookup dictionary indexed characters call ord time also concatenate build strings – used slow use join list instead string import join def stringtohexstrings strhex c strhexappendhexloookupc return joinstrhex,i using old version python embedded platform python telit platform the problem i function converting string hex it slow here function def stringtohexstrings strhex c strhex strhex hexloookupordc return strhex hexlookup lookup table python list containing hex representation character i willing try everything compact function language tricks i know to clear benchmarks resolution second platform n number input characters converted hex time seconds n time seconds yes i know slow i could gain something like seconds would progress so solution welcomed especially people know python performance thanks iulian ps testing suggestions offered keeping ord call def stringtohexstrings hexlist hexlistappendhexlistappend c hexlistappendhexloookupordc return joinhexlist with function i obtained following times clearly better ps explain blazingly fast a big thank sven marnach idea def stringtohexstrings return join maplambda paramhexloookupparam mapords times any ideasexplanations welcome,3 lol quite easy hope somebody help still though celerybincamqadm import camqadm camqadm queuepurge queuenameasstring the problem i still need stop celeryd purging que purging i need run celeryd handle tasks queue will update question succeed i succeeded please correct good method stop celeryd purge que start i know i using term i actually want terminated task killcommand ps auxww grep celeryd n twittersave awk print xargs kill subprocesscallkillcommand shelltrue camqadm queuepurge twittersave reruncommand homesamossoftwarevirtenvtwittersyncvbinpython smanagepy celeryd n twittersave l info q twittersave settingsprojectroot ospopenreruncommand amp sendtasksocialreporttaskstwittersave,how purge scheduled running tasks specific que celery python the questions seems pretty straigtforward add i looking command line code i following line defines que would like purge que manage tasks celeryroutes socialreporttaskstwittersave queue twittersave at point time i wanna purge tasks que twittersave python code maybe broadcast function i find documentation is possible,3 if root folder pythonpath make importable package follows initpy crawlpy crawlinitpy crawljohnpy testsinitpy teststestjohnpy crawljohn import john crawljohn import john,i python application like crawlpy crawlinitpy crawljohnpy teststestjohnpy what i trying run unit test testjohnpy needs use johnpy another folder in teststestjohnpy i get i run traceback recent call last file testjohnpy line module john import john importerror no module named john so i import class crawl folder,3 building petr viktorin answer could improve performance avoiding global vairable attribute lookups favour local variable lookups local variables optimized avoid dictionary lookup access they always i doublechecked optimization already place released string import join def stringtohexstrings strhex strhexappend strhexappend hexlookup hexloookup c strhexappendhexloookupc return joinstrhex,i using old version python embedded platform python telit platform the problem i function converting string hex it slow here function def stringtohexstrings strhex c strhex strhex hexloookupordc return strhex hexlookup lookup table python list containing hex representation character i willing try everything compact function language tricks i know to clear benchmarks resolution second platform n number input characters converted hex time seconds n time seconds yes i know slow i could gain something like seconds would progress so solution welcomed especially people know python performance thanks iulian ps testing suggestions offered keeping ord call def stringtohexstrings hexlist hexlistappendhexlistappend c hexlistappendhexloookupordc return joinhexlist with function i obtained following times clearly better ps explain blazingly fast a big thank sven marnach idea def stringtohexstrings return join maplambda paramhexloookupparam mapords times any ideasexplanations welcome,1 while element exist directly member tiles tiles twodimensional list list lists tiles list tile tiles single tile python recursively descend multidimensional list find element looking therefore tilesindextile fails tilesindextile would work to illustrate l lindex traceback recent call last file stdin line module valueerror list lindex,can someone explain funcion listindex functions i following code def getposselftile print selftiles print tile try myindex selftilesindextile code except print exception raised code the result tiletile instance xbceb tiletile instance xbceb exception raised do idea listindex returns exception although tile variable reference element tiles thanks lot ps btw i passing tiles specific case,2 selftiles appears sequence eg list tuple sequences elements selftiles sequences tiles selftilesindextile tries find sequence equals tile fails try instead def getposselftile irow enumerateselftiles jelt enumeraterow tile elt return ij raise valueerror tile found,can someone explain funcion listindex functions i following code def getposselftile print selftiles print tile try myindex selftilesindextile code except print exception raised code the result tiletile instance xbceb tiletile instance xbceb exception raised do idea listindex returns exception although tile variable reference element tiles thanks lot ps btw i passing tiles specific case,2 if want test whether duplicates list use lensetlistoemails lenlistoemails different else duplicate raise formsvalidationerror comment since set eliminate duplicates comparing lengths tell whether duplicates removed,consider list emails aamailcom bbmailcom ccmailcom i want compare list items for example emails would unique what way compare items list python,2 i familiar boostpython might feature makes easier i know custom rtti system works pretty well qt metaobject system reflection degree dynamic behavior added metaobject associated class knows class ancestors methods it kind like python class objects a virtual method used get metaobject instances a custom compiler used generate qt python bindings also create metaobjects python classes making look almost identical native qobjects classes far metaobject system concerned you need quite bit less qt general solution need info methodsproperties so instead custom compiler could go cclass definition macro stores information class ancestors and also update information metaclass python subclass created query dispatching message,i developing game engine c allows python scripting here example functions defined python called event manager whenever certain event occurs import classes defined c cppevent import playerdiesevent eventmanager def onplayerdeathevent pass em eventmanager emconnectplayerdiesevent onplayerdeath empostplayerdiesevent will call onplayerdeath the user also define new types events cppevent import event eventmanager class customeventevent pass def oncustomeventevent pass em eventmanager emconnectcustomevent oncustomevent empostcustomevent however i would also like messaging system work inheritance currently here i mean cppevent import playerdiesevent eventmanager class customeventplayerdiesevent pass def onplayerdeathevent pass def oncustomeventevent pass em eventmanager emconnectplayerdiesevent onplayerdeath emconnectcustomevent oncustomevent this notifies functions customevent playerdiesevent empostcustomevent this notifies onplayerdeath empostplayerdiesevent tlddr is c library would allow easily create custom rtti system works inheritance if ideas i might implement easily perhaps generally preferably way agnostic actual use case,1 terminal type python unix like system python x generally default python version use system language syntax drastically changed python python making incompatible thus cannot replace python python system may completely break essential systems packages python interpreter made available python command make distinction old python interpreter,i download python os x i installed harddisk but problem i go terminal i type python it still shows old version like python r jun gcc apple inc build darwin type help copyright credits license information then i go folder python i find file like update shell profilecommand so i run display something like applicationspython update shell profilecommand exit usersmacbook user applicationspython update shell profilecommand exit this script update shell profile bin directory python early enough path shell these changes effective shell windows open running script all right python lover already logout process compleuser but i still get python terminal did i something wrong thanks,3 refactoring code import matplotlibpyplot plt ax color zipax ax ax ax green green blue blue pltsetpaxspinesvalues colorcolor pltsetpaxgetxticklines axgetyticklines colorcolor,this kind followup question post coloring axes ticks labels discussed i hope alright open new extended question changing color complete frame ticks axes around doubleplot via addsubplot axes ax ax results lot code this snippet changes color frame upper plot axspines bottom setcolor green axspines top setcolor green axspines left setcolor green axspines right setcolor green axxaxisgetticklines tsetcolor green axyaxisgetticklines tsetcolor green axxaxisgetticklines tsetcolor green axyaxisgetticklines tsetcolor green so changing frame color two plots two yaxes i would need lines code this looks like other methods i dug far matplotlibrc discussed changes globally locally i want plots different colors please discussions many colors plots matplotlibrc axes edgecolor green dig spines axis change also discussed really elegant i think child axgetchildren isinstancechild matplotlibspinesspine childsetcolor dddddd is elegant way condensing block something pythonic i using python matplotlib ubuntu,3 you set range header request certain range bytes dependent server honor request import urllib req urllibrequest httpwwwpythonorg here request bytes downloaded the range inclusive starts reqheaders range bytesss f urlliburlopenreq this shows actual bytes downloaded contentrangefheadersget contentrange printcontentrange bytes,is possible fetch number bytes url close connection urlliburllib or even may part nth byte kth there page side i need load whole page piece,3 one way would add back extra deleted sl listsetls sl lscount alternatively always append new list set sl elem ls elem elem slappendelem saddelem using set allows constant time membership testing used lists would on you write list comprehension want normal loop readable set sl saddelem elem elem ls elem elem,i already know remove duplicates list using set ls listsetls what want know way remove duplicates except one element instances efficient method ls want keep matter duplicate want remove duplicates rest output ls one possible solution iterate element use conditional check i looking best solution,2 the coding utf line necessary files contain special characters directly depending want achieve ln take care process strings in python use unicode objects python normal str ings thing use,i django site contains english language strings i localising languages i set sort file encoding options do need convert python code utf good practice if i need actually convert file utf i simply need add snippet python files coding utf thanks,2 i thought rather simple solution define view function doworkreq param like would view url mapping return httpresponse set cron job timing preferences using at scheduled tasks windows runs curl httplocalhostyourmappedurlparamvalue you add parameters adding parameters url tell guys think update i using runjob command djangoextensions instead curl my cron looks something like hourly python pathtoprojectmanagepy runjobs hourly daily monthly etc you also set run specific job i find managable cleaner doesn require mapping url view just define job class crontab set,i working web app using django i curious way schedule job run periodically basically i want run database make calculationsupdates automatic regular basis i seem find documentation does anyone know set to clarify i know i set cron job i curious feature django provides functionality i like people able deploy app without much config preferably zero i considered triggering actions retroactively simply checking job run since last time request sent site i hoping something bit cleaner,2 use sessionflush instead sessioncommit with pyramidtm never need commit request handling code,i building first pyramid app coming pylons i trying figure handle exceptions pyramidtm for example pylons i would something like try sessionaddobject sessioncommit except integrityerror sessionrollback flashobject already present supposed done pyramidtm,3 i would use python prograam server triggered php i would look around python library working collada files eg httpcolladainlinescom i would use fbx python sdk convert fbx files collada for obj maybe something like httppygameorgwikiobjfileloader would helpful update i recently wrote blog post using fbx python web server,i building web form accommodate users uploading obj fbx d models site we need serverside solution convert files collada dae it would massively helpful someone could point right direction i solid ideas yet possible solution i like hear others think i go one path i think something along lines pythonperl script triggered php upload many thanks advance,2 no code initialise fs unless open calls completed successfully this work though fs try f files fsappendopenf rb finally f fs fclose note also fclose could fail may want catch ignore otherwise handle failures,i aware i open multiple files something like open rb open b rb b but i situation i list files open wondering preferred method number files unknown advance something like openf rb f files fs fails attributeerror since list implement exit i mind using something like try fs openf rb f files finally f fs fclose but sure happen files throw trying open will fs properly defined files manage open finally block,3 def matchess pattern return allcp dsetdefaultcp cs cs cs cp zips pattern resign resins redyed resist reeded print matchess print matchess prints redyed reeded,let say i list words resign resins redyed resist reeded i also string i need iterate list find words repeated characters locations numbers string for instance string would find word redyed since e another string would find word reeded e position my attempts python far really worth printing at moment i look string add array array try find repeated characters array positions but terribly clumsy work properly,3 this perfect use list comprehension anyemailscountemail email emails raise formsvalidationerroremails must unique,consider list emails aamailcom bbmailcom ccmailcom i want compare list items for example emails would unique what way compare items list python,1 doing two sends row may result two actual packets going great to fix concatenate two pieces use writev aka gather write tcpcork first send prevent turning packet as receive side receive big block much reasonable limit say couple megabytes something parse do try receive one two bytes size another receive thatthis inefficient may still end short reads sent message fragmented,i currently trying implement tlv protocol used top tcp a early version protocol built sending one message per sendrecv pair ie sendmessage transmit recv this really bad bandwidthwise i guess i sending really small packets so i trying switch lv protocol sending several messages seperated respective length i using protocol buffers serialize data i two questions in python i send socksendstructpackh lengtmessageserializetostring socksendgtmessageserializetostring if i put loop sent several messages i end old problem far i understand can i somehow string string sent together in c i receive receive first length message read number bytes indicated length field is better performancewise first read everything tcp parse i read one message parse read next bit wire edit so research i rephrase first question is socksendsomestring socksendsomestring socksendsomestringsomestring,1 the reason handled differently docs adding translations javascript poses problems javascript code access gettext implementation javascript code access po mo files need delivered server the translation catalogs javascript kept small possible so essentially internal python translation done server but js another file served server contains required translations user language and translation done user side so see completely different strategy django helps adding similar interface js files even though handled completely different way i guess works like rendering template django checks requested locale loads appropriate localisation file serves template js hand served static media get parsed django is you right first part handling templates handling js works i explained note django js translation mechanism treat js translations static files it uses django view generate js file everytime javascriptcatalog mentioned docs linked first line that one problems i encountered such files need generated every request there projects actually let pack js translations static files enable cache properly like djangomediagenerator,when localising django application makemessages command simply parses txt html py files generates po files localising js files need run djangojs command i delved django source figure done differently could someone explain i read production environments apache used serve application files simple proxy like nginx used serve static files greatly reduces load application server with scenario i guess works like rendering template django checks requested locale loads appropriate localisation file serves template js hand served static media get parsed django is its first foray world localisation django i packed full question many answers i seem find therefore post thanks,1 use regular expression import sub print subaz hello strreplace looking string abcdefghijklmnopqrstuvwxyz replace looking individual letter replace,import string word hello word wordreplacestringlowercase print word hello i want lowercase letters turn full stops what i wrong,3 think use replace mapping like want simple regular expression import word hello pattern want match ptn r az compile pattern patobj recompileptn use sub method replace text based pattern w patobjsub word w,import string word hello word wordreplacestringlowercase print word hello i want lowercase letters turn full stops what i wrong,1 stringlowercase abcdefghijklmnopqrstuvwxyz your code replacing every occurence entire letter string full stop instead want use module sub function import word hello word resub az word print word,import string word hello word wordreplacestringlowercase print word hello i want lowercase letters turn full stops what i wrong,1 you trying replace string abcxyz instead replacing every lowercase letter you achieve wanted result several ways regular expressions import sub subaz hello char char join lislower else l l word,import string word hello word wordreplacestringlowercase print word hello i want lowercase letters turn full stops what i wrong,1 use stringtranslate import string input abcabcaabbcc inputtranslatestringmaketransstringlowercase abcabc stringmaketrans function function helps building mapping suitable stringtranslate function alternatively simply iterate string using generator strjoin chrislower else chr chr input abcabc,import string word hello word wordreplacestringlowercase print word hello i want lowercase letters turn full stops what i wrong,2 mapping file location read setupcfg file generated distutils section extractmessages in section must add setting named mappingfile point your mapping file example this tells babel look mapping file named messageextractionini package directory extractmessages default options mappingfile messageextractionini,i currently trying use babel generate set static html pages different languages using jinja within simple script part web app i point i need extract messages translation i know i supposed modify babel mapping configuration file understand jinja templatessince i using commandline tool i assume i need create mapping file however i seem find documentation mapping configuration file named placed all i know i need place following jinja templateshtml encoding utf mapping file according jinja documentation has anyone done something similar know mapping configuration file thanks,1 errors occur attempting open file attempting read file rarely attempting close file so basic error handling structure might look like try stream openpath try data streamread finally streamclose except environmenterror exception print error strexception else print success process data this ensures close always called stream variable exists if stream exist open must failed file close case except block executed immediately do really need files open parallel processed sequentially if latter something like fileprocessing code put function called path list,i aware i open multiple files something like open rb open b rb b but i situation i list files open wondering preferred method number files unknown advance something like openf rb f files fs fails attributeerror since list implement exit i mind using something like try fs openf rb f files finally f fs fclose but sure happen files throw trying open will fs properly defined files manage open finally block,1 python implemented complex numbers default see edit maybe interested following your readdata work correctly following real input creates new local variable real you probably want modify selfreal thus write selfreal floatinput convert float moreover constructor needs give arguments thus call mycomplex values if want default values change init def initself real imag for readability could define method addself then use xy complex numbers,done c trying python difficultiesi code class mycomplex def initselfrealnoneimagnone selfrealreal selfimagimag def readdataself selfrealinputgive real part selfimaginputgive imag part def additionselfcomplex return mycomplexselfrealcomplexrealselfimagcompleximag def strself return formatthe complex selfrealselfimagj namemain amycomplex bmycomplex areaddata breaddata printa printb caadditionb printc first work init method arguments try create instance amycomplex gives error coursecan handle way without changing init in order understand want use addition method ways like say codeit help thinkit different say aaddition caadditionb if better suggestions implementing aboveplease say iti think understand trying show thank,1 python features builtin complex type readily available try typing j j python interpreter,done c trying python difficultiesi code class mycomplex def initselfrealnoneimagnone selfrealreal selfimagimag def readdataself selfrealinputgive real part selfimaginputgive imag part def additionselfcomplex return mycomplexselfrealcomplexrealselfimagcompleximag def strself return formatthe complex selfrealselfimagj namemain amycomplex bmycomplex areaddata breaddata printa printb caadditionb printc first work init method arguments try create instance amycomplex gives error coursecan handle way without changing init in order understand want use addition method ways like say codeit help thinkit different say aaddition caadditionb if better suggestions implementing aboveplease say iti think understand trying show thank,1 the line headingheading creates new local variable called heading different varaible called heading passed function you make function assign external variables adding global heading assign heading def function global heading headingheading print yes print heading,i somewhat beginner python i swear i got similar program i right work but reason i make work i able pinpoint problem created fake program play around here program global heading global heading global heading heading def function headingheading print yes print heading function print heading this appears yes why heading variable heading keep value i tried putting return heading didn work i tried putting variables parentheses function didn work either do know i wrong,2 global statement meaningless outside function if want modify global variable instead introducing local one need put global inside function def foo global x x x also use globals,i somewhat beginner python i swear i got similar program i right work but reason i make work i able pinpoint problem created fake program play around here program global heading global heading global heading heading def function headingheading print yes print heading function print heading this appears yes why heading variable heading keep value i tried putting return heading didn work i tried putting variables parentheses function didn work either do know i wrong,2 if want gain accesstokensecret sign could setup callback url httplocalhostblah fireup cliapp modifying callbackurl secret token ofcourse follow link browser allow app view addressbar page redirected browser allowing app it look something like httplocalhostblahoauthtokenxxxxxxxxxxxxxxxxxxxxxxxxxxabcdefghijklmnampoauthverifierxxxxxxxxxxxxxxxxxxxxxxxxxabcdefghijklmn use value queryparameter oauthverifier pin xxxxxxxxxxxxxxxxxxxxxxxxxabcdefghijklmn the cli print oauthtoken oauthtokensecret hth got working tumblr way,i new oauth in past twitter applications written python used pythonoauth library initialize client like consumer oauthconsumerkey consumerkey secret consumersecret token oauthtokenkey accesskey secret accesssecret client oauthclientconsumer token that easy twitter provides consumer access keys secrets but need tumblr the problem tumblr provides consumerkey consumersecret urls requesttoken url httpwwwtumblrcomoauthrequesttoken authorize url httpwwwtumblrcomoauthauthorize accesstoken url httpwwwtumblrcomoauthaccesstoken using data initialize client access tumblr api upd jterrace suggested code tried use the problem oauthcallback if specify api returns error no oauthcallback specified specify url like httpexamplecomoauthcb follow link httpwwwtumblrcomoauthauthorizeoauthtokenygtf press allow button tumblr show pin code page immediately redirects callback url useless since desktop application why pin code shown upd tumblr api support pin code authorization use xauth instead httpsgroupsgooglecomgrouptumblrapibrowsethreadthreadeabdccdlnkgstampqpindccd,3 you probably running python permutations it new you find python implementation permutations use code python docs httpdocspythonorglibraryitertoolshtmlitertoolspermutations,i trying use itertools module use permutations function i problems mac i programing another computer using linux problem use code import itertools ps itertoolspermutationsm this error i getting i working mac attributeerror module object attribute permutations anyone knows i use itertools mac,1 the documentation says new version might running older version at least osx lion python itertools import permutations works,i trying use itertools module use permutations function i problems mac i programing another computer using linux problem use code import itertools ps itertoolspermutationsm this error i getting i working mac attributeerror module object attribute permutations anyone knows i use itertools mac,1 checking source code looks need define handlers path without slash handlerscript handlerscriptendswith py handlerscript raise appinfoerrorsthreadsafewithcgihandler threadsafe cannot enabled cgi handler handlerscript move applicationpy root project modify handler path accordingly,i migrating gae app python this new appyaml application webfaze version main runtime python apiversion threadsafe true handlers url mapreduce script mapreducemainapplication url htmlcssjsgifjpgpngicoswf staticfiles static upload static expiration url script mainapplication url task script mainapplication login admin but i get error message error parsing yaml file invalid object threadsafe cannot enabled cgi handler mapreducemainapplication webfazeappyaml line column can tell resolve error,3 it would easier answer posted javascript code are submitting form submit button if jquery form handle everything not refresh page if submitting form javascript code look like jquery form examples attach handler form submit event myformid submitfunction submit form thisajaxsubmit return false prevent normal browser submit page navigation return false return false important otherwise user redirected for system work need phase submit comment append comment rest comments fetch new comments server append is current setup looks like,any way submit form without refreshing current page using python jquery ajax i want end results similar facebook comment works i currently using jquery form ajax however give user experience i want after submitting using jquery form url address bar refreshed form i submitted it refresh page i like especially let say i bottom page scrolled maximum after submitting form refreshed page focus redirected top page i hope i made point clear i want i need something like facebook comment system works someone commented comment submitted without refresh page edit jquery code reviewsubmit submitfunction var options thisajaxsubmitoptions return false namesubmitreviewbtn clickfunction reviewsubmit submit so python code handle submit need redirect page server side code redirect page url mainurlcom with jquery codes shown results the url appeared address bar mainurlcom formactionurl this form action i set submit form page redirected page i set server side i confused ajax experience,2 import commands easygui import output commandsgetstatusoutputcommand msgboxmsgoutput that get output command show message box,i questions so making python program backup restore selected directory this first program using easygui gui program want know take linux command executed display result msgbox would tkinter better kind thing would go showing flash drives plugged showing drop menu flash drives plugged pick,1 it appears staticfiles app work debug false only doesn’t pick files individual apps’ static directories it would serve files global staticroot directory settingspy to get static files copied staticroot need run collectstatic command python managepy collectstatic,how include stylesheets images page template using default view i created html file root site templates directory doctype html html head load static link relstylesheet href getstaticprefix csscss head body classpage pnot foundp body html ironically css found the css file located one apps static directory the server managepy runserver on every page static files served well update it appears setting debug false settingspy static files pages stopped served,1 looking recipe process popen data asynchronously i stumbled upon httpcodeactivestatecomrecipessubprocesswithasynciopipesclass this looks quite promising however i got impression might typos not tried yet,i running subprogram using subprocesspopen when i start python program command window cmdexe program writes info dates window program evolves when i run python code command window opens new command window subprogram output i want avoid when i used following code show cmd window also print status p subprocesspopencflowflowexe shelltrue stdoutsubprocesspipe print pstdoutread how i show subprogram output program output occurs,1 yes simply override init method class structstructure fields cint b cint def initself b superstruct selfinita b def printvaluesself print selfa selfb,in ctypes structure possible specify default values for example regular python function def funca b print b that would allow behaviour func prints func prints func b prints is possible ctypes structure example class structstructure fields cint b cint b default def printvaluesself print selfa selfb structinstance struct structinstanceprintvalues somehow print,3 that exactly supposed happen run command easyinstall the flask installation instructions link tell type easyinstall virtualenv easyinstall,when i follow instructions httpflaskpocooorgdocsinstallation i get following error i execute easyinstall windows command line interpreter error no urls filenames requirements specified see help why i get error btw i ran ezsetuppy works easyinstall files scripts folder python folder,1 sure here recipe create context manager pool enter arbitrary number contexts calling enter method cleaned end end suite class contextpoolobject def initself selfpool def enterself return self def exitself exctype excvalue exctb close reversedselfpool closeexctype excvalue exctb def enterself context close contextexit result contextenter selfpoolappendclose return result for example class stubcontextmanagerobject def initself name selfname name def reprself return sr typeselfname selfname def enterself print called renter self def exitself args print called rexitr self args contextpool pool poolenterstubcontextmanagerfoo poolenterstubcontextmanagerbar called stubcontextmanager foo enter called stubcontextmanager bar enter called stubcontextmanager bar exittype exceptionszerodivisionerror zerodivisionerror integer division modulo zero traceback object x called stubcontextmanager foo exittype exceptionszerodivisionerror zerodivisionerror integer division modulo zero traceback object x traceback recent call last file pyshell line module zerodivisionerror integer division modulo zero caveats context managers supposed raise exceptions exit methods recipe cleanup context managers similarly even every context manager indicates exception ignored returning true exit methods still allow exception raised,i aware i open multiple files something like open rb open b rb b but i situation i list files open wondering preferred method number files unknown advance something like openf rb f files fs fails attributeerror since list implement exit i mind using something like try fs openf rb f files finally f fs fclose but sure happen files throw trying open will fs properly defined files manage open finally block,3 having posted question i realised i simply following val pair zipl l val pair l l two lists,in python good way interleave two lists length say i given i like transform,3 you could starting building djangocms great cms much aimed extensibility it plugin architecture allows integrate existing third party apps if making auction site though much cms much appplatform builing so recommend look pinax project allows start project lot common requirements web apps already satisfied like profiles email auth social authentication commenting etc,if one build online auction site using django would good idea modify existing cms if could someone suggest cms scaffolding thanks,1 you formulated question correctly people watch youtube video understand want without watching video i assume want know random integers work import random x randomrandint if want rolling simply either make three variables display three random integers inside loop place loop here example import random import sys try rolls intsysargv except indexerror print usage sysargv rolls sysexit range rolls print roll stri range print randomrandint,i new programming i touched surface one language python i working moment i trying write program display random rolling numbers range like for lack able explain i would rather show video i looking httpwwwyoutubecomwatchvsenzezi at seconds see rolling numbers player must stop order assign character trait less pretty graphics everything what i want know possible write program serves type function python if python languages i becoming little familiar c java would possible write one combination if possible point direction resources effort i search posting i found coming empty lack knowing search thanks,1 try using method described lazy method reading big file python i specifically referring accepted answer let also copy ensure complete clarity response def readinchunksfileobject chunksize lazy function generator read file piece piece default chunk size k true data fileobjectreadchunksize data break yield data f open reallybigfiledat piece readinchunksf processdatapiece this likely adaptable needs reads file smaller chunks allowing processing without filling entire memory come back questions,i using python download file localfile openfilename w filemode localfilewritefread localfileclose this code works copies whole file memory first this problem big files program becomes memory hungry going m memory m memory mb file i would like know way python download small part file packet write file erase memory keep repeating process file completely downloaded,2 i like aix solution best another way i think work xrange x yrange sumzipxy traceback recent call last file stdin line module typeerror concatenate list tuple list summaplistzipxy one way axy aij j range sumlisti zipxy,in python good way interleave two lists length say i given i like transform,1 alternative l l x mapnonell x none this works map works lists parallel it works by none called functions map produces list tuples mapnonell abcd b c none none then flatten list tuples the advantage course map work number lists work even different lengths l l l x mapnonelll x none,in python good way interleave two lists length say i given i like transform,2 the “problem” directly possible using command line interface if looking game development probably going graphical interface anyway look find library gives options animating things nevertheless possible solution command line would involve multithreading the reason cannot print continuously changing numbers also wait keyboard input the normal command line actually quite limited way below find possible solution threading approach but going game development rather check actual graphic libraries even game libraries help random import randint time import sleep threading import thread import sys class rollanimation thread activated true number none def run self selfactivated selfnumber randint sysstdoutwrite r format selfnumber sysstdoutflush sleep rollanimation tstart waiting enter input use rawinput python x tactivated false print final roll result tnumber,i new programming i touched surface one language python i working moment i trying write program display random rolling numbers range like for lack able explain i would rather show video i looking httpwwwyoutubecomwatchvsenzezi at seconds see rolling numbers player must stop order assign character trait less pretty graphics everything what i want know possible write program serves type function python if python languages i becoming little familiar c java would possible write one combination if possible point direction resources effort i search posting i found coming empty lack knowing search thanks,1 there guarantee id enfoo given title foo in order find correct id topic either use search service get list candidate ids use mql exact phrase matches search httpswwwgoogleapiscomfreebasevsandboxsearchquerybol httptinyurlcomwyvyz,i using freebase library print article all working fine but i want ask something following example working fine suppose i title like bol film now i want use title like id enbolfilm but this working in wikipedia api we use title bolfilm can one help thanks much query id enbarakobama commontopicarticle id none commontopicimage id none edit i read freebase site but this working for example fullyqualified name represents left parenthesis represents right parenthesis see section full list legal characters fullyqualified names,1 if os supports put symbolic link crawl test directory use crawljohn import john,i python application like crawlpy crawlinitpy crawljohnpy teststestjohnpy what i trying run unit test testjohnpy needs use johnpy another folder in teststestjohnpy i get i run traceback recent call last file testjohnpy line module john import john importerror no module named john so i import class crawl folder,1 for python extended slice syntax b c b c c b c,in python good way interleave two lists length say i given i like transform,3 httpwwwpipinstallerorgenlatestindexhtml requirements files httpwwwbuildoutorg,is equivalent mavenivy dependency management python i mean something automatically download dependencies based simple specification done java thanks,2 python case sensitive use print print,i trying create simple program apply statement collatz conjecture integer user enter i def collatzn print n n n n elif n print collatz conjecture true n else n n inputnninsert positive integer def collatzn however saying syntax error line print collatz conjecture true n i see mistake ther line also i able test yet look though work ok,2 well syntax error python casesensitive need print rather print but got problems n prints string n i think want n print value variable make single string true n finally i think order run function collatz need def definition,i trying create simple program apply statement collatz conjecture integer user enter i def collatzn print n n n n elif n print collatz conjecture true n else n n inputnninsert positive integer def collatzn however saying syntax error line print collatz conjecture true n i see mistake ther line also i able test yet look though work ok,2 more problems the stopping condition n n you recur iterate making one step check input make sure really positive number,i trying create simple program apply statement collatz conjecture integer user enter i def collatzn print n n n n elif n print collatz conjecture true n else n n inputnninsert positive integer def collatzn however saying syntax error line print collatz conjecture true n i see mistake ther line also i able test yet look though work ok,1 using lxml might try something like import contextlib import seleniumwebdriver webdriver import lxmlhtml lh import lxmlhtmlclean clean urlhttpwwwyahoocom ignoretags script noscript style contextlibclosingwebdriverfirefox browser browsergeturl load page contentbrowserpagesource cleanercleancleaner contentcleanercleanhtmlcontent open tmpsourcehtml w f fwritecontentencode utf doclhfromstringcontent open tmpresulttxt w f elt dociterdescendants elttag ignoretags continue textelttext tailelttail words jointexttailstrip words wordswordsencode utf fwritewords n this seems get almost text wwwyahoocom except text images text changes time done javascript refresh perhaps,i googling day finding answer apologies advance already answered i trying get visible text large number different websites the reason i want process text eventually categorize websites after couple days research i decided selenium best chance i found way grab text selenium unfortunately text grabbed multiple times selenium import webdriver import codecs filen codecsopen outoputtxt encoding utf mode w driver webdriverfirefox drivergethttpwwwexamplepagecom allelements driverfindelementsbyxpath ferdigtxt allelements itext ferdigtxt pass else ferdigtxtappenditext filenwritelinesitext filenclose driverquit the condition inside loop attempt eliminating problem fetching text multiple times however work planned webpages also makes script a lot slower i guessing reason problem asking inner text element i also get inner text elements nested inside element question is way around is sort master element i grab inner text or completely different way would enable reach goal any help would greatly appreciated i ideas one edit reason i used selenium mechanize beautiful soup i wanted javascript tendered text,3 actually right comment notepad seems launch files directory you find solution problem httpdamienlearnsperlblogspotcomlaunchyourperlscriptfromnotepadhtml check lee comment still intend use notepad,i using python imaging library tkinter i currently trying display image label i getting exception my line source pil import image imagetk tkinter import tk frame label class exampleframe def initself parent frameinitself parent selfparent parent selfinitui def inituiself selfparenttitlelabel selfimg imageopendiesljpg diesl imagetkphotoimageselfimg label labelself imagediesl labelimage diesl labelpack selfpack def setgeometryself w h selfimgsize selfparentgeometrydxd w h def main root tk ex exampleroot exsetgeometry rootmainloop name main main,1 instead axesclear figaddsubplot use remove method mpltoolkitsmplotdartdpatchdcollection object in fig pltfigure in ax figaddsubplot projection in xs nprandomrandomsample in ys nprandomrandomsample in zs nprandomrandomsample in axscatterxs ys zs c r marker draws in aremove clean in axscatterxs ys zs c r marker draws if still problems play import numpy np matplotlib import pyplot plt mpltoolkitsmplotd import axesd matplotlib import interactive interactivetrue xs nprandomrandomsample ys nprandomrandomsample zs nprandomrandomsample fig pltfigure ax figaddsubplot projection axscatterxs ys zs c r marker pltdraw rawinput press new image aremove xs nprandomrandomsample ys nprandomrandomsample zs nprandomrandomsample axscatterxs ys zs c r marker pltdraw rawinput press end,i probably simple problem replotting d data using matplotlib initially i figure d projection canvas selffig pltfigure selfcanvas figcanvasselfmainpanel selffig selfaxes selffigaddsubplot projection i add data use canvasdraw update the plot updates expected i get additional d axis outside figure i work stop selfaxesclear selfaxes selffigaddsubplot projection xs nprandomrandomsample ys nprandomrandomsample zs nprandomrandomsample selfaxesscatterxs ys zs c r marker selfcanvasdraw any ideas i going circles right,2 itertools import combinations sumxy xy combinationsdcba hint using combinations like returns pair first pair occurs earlier string second listcombinationsdcba d c d b d a c b c a b a here alternate way might easier beginners follow dcba count rangelens j rangei lens sisj count count,i trying create function returns number pairs order for example function would return argument dcba my code far def calcoutoforderpairss res sum j resappendij test res pair pair sum return sum,2 use list comprehension zip b ab zipab are questions homework or selfstudy,i two lists a b and i need able find sum nth terms lists ie etc could someone please tell refer items lists time i read somewhere i could sum ai bi i convinced would work,3 import operator mapoperatoradd a b demonstrate pythons elegance,i two lists a b and i need able find sum nth terms lists ie etc could someone please tell refer items lists time i read somewhere i could sum ai bi i convinced would work,3 you correct indicating evalxstri evalxstr array thus subscripted what looks like may want since say want convert string int intxstr make whole line intxstr,im trying read file make sure value order i dont think im converting string integer correctly here code i also trying use flags filename inputwhat file name infile openfilename r correctorderflag false line infilereadline line xstr linesplit evalxstr correctorderflag true else correctorderflag false correctorderflag printyes numbers order else printno numbers order count printthere count numbers,2 for starters read whole file try openfilename f line f goes code not sure though mean value order using eval very bad idea purpose,im trying read file make sure value order i dont think im converting string integer correctly here code i also trying use flags filename inputwhat file name infile openfilename r correctorderflag false line infilereadline line xstr linesplit evalxstr correctorderflag true else correctorderflag false correctorderflag printyes numbers order else printno numbers order count printthere count numbers,1 you need learn basic terminology first the shell program interprets input command lines grep foo abctxt a terminal emulator program mimics terminal terminal device display keyboard one used access unix mainframe a pseudoterminal pty device node supporting terminal emulators opposed real terminal devices tty example now could either build shell would work terminal instead bash dash could build terminal emulator usable internet could run existing shell both challenging tasks python documentation much use i recommend start googling concepts first python references c c and lastly want run emacs nano advanced program shell want use pty module,i interested writing web based terminal execute autocomplete commands ubuntu terminal i fiddled anyterm httpwwwanytermorg uses rote simple c library vt terminal emulation backend server javascripthtml terminal ui the problem i open two terminals window after research i decided write terminal serverpseudo terminal whichever right terminology python execute commands ubuntu terminal ls grep etc autocomplete commands like gedi pressed tab gedit multiple instances terminal open time typed ls one terminal recognize ls last command since another terminal session i found pty python module i write pseudo terminal however i new python i even get example page work i planning python script serve http server javascripthtml terminal ui i would write main reason i wanted choose python project then i want let web ui talk backend terminal server get results back web ui if could point right direction maybe tell module i use pty give ideas write python pseudo terminal server i would appreciate i know javascriptphp familiar bash scripting at point i could go c based python based backend server python right project note i planning write ui uses ajax post get methods retrieve terminal output backend server,2 you remember law large numbers not many essays composed letter m try real comment text first character counting could work better expected also much faster using pil render text serverside,i web site comments comment could variable length longer comments naturally take space however i finite amount space page put comments naturally picking fixed number comments stack work could short liners line essays sending whole list client client javascript cut appropiate length rendering looks hopelessly wasteful counting characters work iii takes much less space mmm what i want way calculate height comment given content font font size weight even perfect i fudge server send perhaps many comments client javascript trim least bound wastage fraction comments i using python considering python image library render comment text server seeing tallwide final image first though standard way edit i could also render character maintain mapping character font weight size width height server since i dabbling kerning intercharacter relationships,1 that builtin zip finallist ziplist list list note finallist actually list tuples length length shortest input list the functions itertoolsizip itertoolsiziplongest also noteworthy,i sure pretty easy i sure i three lists lista listb b b listc c c i want pass list byitem merger three finallist b c b c b c how i,3 look maximum subsequence problem,i need return longest sequence positive numbers list currently i def longestsequenceposnums longestsequence currentsequence obj nums currentsequence currentsequence obj currentsequenceappendobj else currentsequence obj lencurrentsequence lenlongestsequence longestsequence currentsequence return sum obj longestsequence obj this returns total number positive numbers appear consequentially work sequence something like any help would appreciated,1 in python could def findlongestsequencesourcelist longestsequence currentsequence obj sourcelist currentsequence currentsequence obj currentsequenceappendobj else currentsequence obj lencurrentsequence lenlongestsequence longestsequence currentsequence return longestsequence print longest sequence findlongestsequence,i need return longest sequence positive numbers list currently i def longestsequenceposnums longestsequence currentsequence obj nums currentsequence currentsequence obj currentsequenceappendobj else currentsequence obj lencurrentsequence lenlongestsequence longestsequence currentsequence return sum obj longestsequence obj this returns total number positive numbers appear consequentially work sequence something like any help would appreciated,1 object instances like c cannot properties classes like c properties so need set property class instance python looks class cuser propertylambda self userobjectsgetselfuserid,i would like define python property outside class definition c c cuser propertylambda self userobjectsgetselfuserid print cuseremail but i get following error attributeerror property object attribute email what correct syntax defining property outside class definition edit i using lettuce lettuce import djangotestclient import client clientuserid propertylambda self selfbrowsersessionget authuserid clientuser propertylambda self userobjectsgetselfuserid beforeeachscenario def setbrowserscenario worldbrowser client,3 here hints parse input list lists csvreader rows listcsvreadersourcesplitlines loop list buildi dictionary summarize costs depending structure looking create buildup might look something like summary region company department expense cost rows summarysetdefaultregion company department appendexpense cost write result jsondump jsondumpsummary open destjson wb hopefully recursive function help get started it builds tree input please aware type want leaves label cost you need elaborate function buildup exact structure intend import csv itertools json def clusterrows result key group itertoolsgroupbyrows keylambda r r grouprows row row group lengrouprows resultappendkey dictgrouprows else resultappendkey clustergrouprows return result name main gondwanalandbobs bitsoperationsnuts gondwanalandbobs bitsoperationsbolts gondwanalandmaureens melonsoperationsnuts rows listcsvreaderssplitlines r clusterrows print jsondumpsr indent,trying create deep nested json csv based upon example regioncompanydepartmentexpensecost gondwanalandbobs bitsoperationsnuts gondwanalandbobs bitsoperationsbolts gondwanalandmaureens melonsoperationsnuts at level i would like sum costs include outputted json relevant level the structure outputted json look something like id auniqueidentifier name usually nodes name data key key value value key key value value children nodes empty ref httpblogthejitorgfeedingjsontreestructurestothejit thinking along lines recursive function python much success approach far suggestions quick easy solution greatly appreciated update gradually giving idea summarised costs i figure i much python coder yet simply able generate formatted json would good enough i plug numbers later i have reading googling reading solution way learnt lot still success creating nested json files csv strucutre must simple solution somewhere web maybe somebody else luck search terms,3 since specified python might want look opencv python interface,i project i want count things video based colour for example i might want roll marbles past camera computer count many green ones often come past more specifically i want take video practice streamed video identify object certain characteristics takes position specified place i fairly familiar common languages mainly web development thus image processing bit realm one idea i example python find good video streaming library image processing one calculations hard check certain region video certain range specified colours does method seem appropriate if libraries available,1 what you use list strai strbi rangelena instead list strai strbi rangelena in version never say want plus character output two elements this error sample output b b c list strai strbi rangelena list b c,i trying add together two lists first item one list added first item list second second form new list currently i def zipperab list ai bi rangelena print the combined list b print list inputnninsert list b inputnninsert another list equal length zipperab upon entering two lists one list integers one list strings i get type error can cocanenate str int objects i tried converting lists strings using list strai strbi rangelena however upon entering b c b i got output b c instead i wanted b c does anyone suggestions i wrong nb i write function essentially perform zipab i allowed use zip anywhere function,1 zip first add ss x x zipa b,i trying add together two lists first item one list added first item list second second form new list currently i def zipperab list ai bi rangelena print the combined list b print list inputnninsert list b inputnninsert another list equal length zipperab upon entering two lists one list integers one list strings i get type error can cocanenate str int objects i tried converting lists strings using list strai strbi rangelena however upon entering b c b i got output b c instead i wanted b c does anyone suggestions i wrong nb i write function essentially perform zipab i allowed use zip anywhere function,3 def countpositivenums return lenfilterlambda x x nums some timeit results new macbook air w gigs cpython filter len python timeit l lenfilterlambda x x l loops best usec per loop python timeit l lenfilterlambda x x l loops best usec per loop python timeit l lenfilterlambda x x l loops best msec per loop sum recommended hochl python timeit l sum x l x loops best usec per loop python timeit l sum x l x loops best usec per loop python timeit l sum x l x loops best msec per loop so sum version slightly faster i think len filter readable,for instance lets say call function countpositive return or array one positive function return so forth,3 def countpositivenums return sum x nums x,for instance lets say call function countpositive return or array one positive function return so forth,3 greaterthanzero array greaterthanzero return greaterthanzero,for instance lets say call function countpositive return or array one positive function return so forth,1 filewrite expects string list try filewritereprmylist,i trying write date txt file the following code i made always gives error import datetime mylist today datetimedatetoday mylistappendtoday print mylist file open datetxt filewritemylist fileclose this code gives following error traceback recent call last file volumeschrome usbstoragedatepy line filewritemylist typeerror argument must string readonly character buffer list will someone please give example working code,1 you write strings stated error so write liste converted string txt file filewritestrmylist simple example b stra b f opendataw fwriteb fclose cat data,i trying write date txt file the following code i made always gives error import datetime mylist today datetimedatetoday mylistappendtoday print mylist file open datetxt filewritemylist fileclose this code gives following error traceback recent call last file volumeschrome usbstoragedatepy line filewritemylist typeerror argument must string readonly character buffer list will someone please give example working code,1 if want write contents list like entry mylist filewritestrentry maplambda x filewritestrx mylist,i trying write date txt file the following code i made always gives error import datetime mylist today datetimedatetoday mylistappendtoday print mylist file open datetxt filewritemylist fileclose this code gives following error traceback recent call last file volumeschrome usbstoragedatepy line filewritemylist typeerror argument must string readonly character buffer list will someone please give example working code,1 better use timestrptime function depends locale if set english usually default get import time timestrptimetue tmwday,how would go converting weekday abbreviation weekday number u using python datetime module,1 here example using xml namespaces elementtree x channel xmlnsmediahttpwwwworgtrhtml titlepopular photography last weektitle item titlefootitle mediacategory labelmiscellaneousphotographymiscmediacategory mediacontent urlhttpfoocomjpg height width mediumimage item item item channel node elementtreefromstringx elem nodefindall itemhttpwwwworgtrhtmlcategory print elemtext photographymisc,i read tags except prefix i luck searching so previous question i need read mediacontent i tried image nodefindmediacontent rss input channel titlepopular photography last weektitle item titlefootitle mediacategory labelmiscellaneousphotographymiscmediacategory mediacontent urlhttpfoocomjpg height width mediumimage item item item channel i read sibling tag title xmletree import elementtree open cacherss rt f tree elementtreeparsef node treefindall channelitem title nodefindtitletext i using docs yet stuck prefix part,2 global variables always available local scopes python including functions in case within main a b c scope the global keyword seems think rather permits local scope manipulate global function makes global variables writable speak consider examples c print c def foo c print c foo print c here output now consider c print c def foo global c c print c foo print c in case output in first case c merely shadows c scope ie function definition ends in second case actually referring reference global c write global c changing value c lead permanent change,try a b c a b def main global c print a the output main why why main get know global variables used evaluate c,3 functions read variables enclosing scopes the global declaration used writing variables indiciate written global dictionary rather local dictionary,try a b c a b def main global c print a the output main why why main get know global variables used evaluate c,2 your error unable execute gcc no file directory which means gcc installed either downgrade upgrade gcc version modify package build gcc command a bit hacky would ln gcc gcc command,i trying install psycopg virtualenv enviroment heck time i think i may screwed something i installed virtualenv upgraded xcode myenviromentmyusersmacbookmyenviroment myuser pip install psycopg produces message downloadingunpacking psycopg running setuppy egginfo package psycopg previouslyincluded directories found matching docsrcbuild installing collected packages psycopg running setuppy install psycopg building psycopgpsycopg extension gcc fnostrictaliasing fnocommon dynamic isysroot developersdksmacosxsdk arch arch x g o dndebug g o dpsycopgdefaultpydatetime dpsycopgversion dt dec pq ext dpgversionhexx dpsycopgextensions dpsycopgnewboolean dhavepqfreemem ilibraryframeworkspythonframeworkversionsincludepython i iusrinclude iusrincludepostgresqlserver c psycopgpsycopgmodulec buildtempmacosxintelpsycopgpsycopgmoduleo unable execute gcc no file directory error command gcc failed exit status complete output command usersmyusermyenviromentbinpython c import setuptoolsfile usersmyusermyenviromentbuildpsycopgsetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record varfoldersbjfljbtdrzbxfmcyrkgntpiplojvkcrecordinstallrecordtxt installheaders usersmyusermyenviromentbinincludesitepython running install running build running buildpy running buildext building psycopgpsycopg extension gcc fnostrictaliasing fnocommon dynamic isysroot developersdksmacosxsdk arch arch x g o dndebug g o dpsycopgdefaultpydatetime dpsycopgversion dt dec pq ext dpgversionhexx dpsycopgextensions dpsycopgnewboolean dhavepqfreemem ilibraryframeworkspythonframeworkversionsincludepython i iusrinclude iusrincludepostgresqlserver c psycopgpsycopgmodulec buildtempmacosxintelpsycopgpsycopgmoduleo unable execute gcc no file directory error command gcc failed exit status command usersmyusermyenviromentbinpython c import setuptoolsfile usersmyusermyenviromentbuildpsycopgsetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record varfoldersbjfljbtdrzbxfmcyrkgntpiplojvkcrecordinstallrecordtxt installheaders usersmyusermyenviromentbinincludesitepython failed error code storing complete log usersmyuserpippiplog i running osx python pip xcode i tried following solutions success cannot install psycopg osx xcode gcc error command gcc failed exit status any thoughts what information would need know,2 instead associative list using dictionary filterassoc numbers jpg jpg shapes circlejpg squarejpg trianglejpg now see images group filterassoc numbers jpg jpg filterassoc shapes circlejpg squarejpg trianglejpg your processing function would become immensely simpler def processfilterdescriptionfilter association return associationfilter i think aloud i use function perform task dictionary def processfilterdescriptionindex images association returnlist index index toplevel association toplevel index item toplevel returnlistappenditem break return returnlist,i got assignment part asks define processfilterdescription basically i list images i want filter images jpg jpg circlejpg squarejpg trianglejpg now i association list i use filter images assclist numbers jpg jpg shapes circlejpg squarejpg trianglejpg i use filter description select association list i want apply filter keyword enclosed colons f numbers i exactly sure start in words i least think filter numbers compare term images term associated numbers association list if term matches append term empty list right i trying get code print terms numbers association list prints def processfilterdescriptionf images ia returnlist f f counter f iacounter print f equal iacounter key ial item key print item returnlistappenditem return returnlist,1 i added method model manager def getactivethreadsself user allthreads messagerecipientobjectsfilterrecipientuserorderby messagetimestamp deletedthreads finalthreads thread allthreads threadthread deletedthreads finalthreads threadstatus deleted deletedthreadsappendthreadthread else finalthreadsappendthread return finalthreads,i following models internal messaging app class messagethreadmodelsmodel subject modelscharfieldmaxlength blankfalse class messagemodelsmodel thread modelsforeignkeymessagethread content modelscharfieldmaxlength blankfalse timestamp modelsdatetimefieldautonowaddtrue blankfalse sender modelsforeignkeyuser class messagerecipientmodelsmodel message modelsforeignkeymessage thread modelsforeignkeymessagethread recipient modelsforeignkeyuser status modelscharfieldmaxlength choicesmessagestatus defaultunread for given user get list threads i distinctthreadsmessagethreadobjectsfiltermessagerecipientrecipientuser orderby messagetimestamp distinct how would i get rid threads message contains status deleted orm in words i want get list threads without thread containing message statusdeleted,1 i believe beautifulstonesoup pass list selfclosing tags the common shortcoming beautifulstonesoup know selfclosing tags html fixed set selfclosing tags xml depends dtd says you tell beautifulstonesoup certain tags selfclosing passing names selfclosingtags argument constructor beautifulsoup import beautifulstonesoup xml tagtext selfclosingtext print beautifulstonesoupxmlprettify tag text selfclosing text selfclosing tag print beautifulstonesoupxml selfclosingtags selfclosing prettify tag text selfclosing text tag,i need parse html i need python parsing library attempt fix html any suggestions tool method use python in situation html malformed script needs end processing i tried beautifulsoup fixed things i want fix i creating tool parse template files output another converted template style,1 this basically set designed computing differences sets items the gotcha things put set need hashable list however tuple convert put set postset settuplex x postitervalues preset settuplex x preitervalues itemsinonlyoneset postset preset for set httpdocspythonorglibrarystdtypeshtmlset to get original indices computed differences probably want generate reverse lookup tables postindices dicttuplevk kv postiteritems preindices dicttuplevk kv preiteritems then take given tuple look index via dictionaries index postindicesgetatuple preindicesgetatuple,i want compare large set data form dictionaries varying lengths edit post pre the answer need get this based fact comparing values indices i using key value pair remember sequence data the data type replaced listset need i need find keyvalue index value pairs elements common dictionaries the code i using simple new found range lenpost found j range lenpre posti prevalues posti new newi posti foundappendj break found f found prepopf new contains elements i need the problem i facing process slow it takes sometimes hour process the data much larger times i need faster is efficient way i trying achieve i would like dont depend external packages apart bundled python bit unless absolutely necessary thank,3 your problem likely nested loops combined use range creates new list time slow you probably get automatic speedups iterating pre post directly avoid nested fashion post pre create sets values independent dict key o lookup postsetsetmaptuple postvalues presetsetmaptuple prevalues iterate structure filtering items found sets created earlier updating newdiff itertools import ifilterfalse newdiffdictifilterfalselambda x tuplex preset postitems newdiffupdateifilterfalselambda x tuplex postset preitems newdiff dict value found post pre original index preserved print newdiff,i want compare large set data form dictionaries varying lengths edit post pre the answer need get this based fact comparing values indices i using key value pair remember sequence data the data type replaced listset need i need find keyvalue index value pairs elements common dictionaries the code i using simple new found range lenpost found j range lenpre posti prevalues posti new newi posti foundappendj break found f found prepopf new contains elements i need the problem i facing process slow it takes sometimes hour process the data much larger times i need faster is efficient way i trying achieve i would like dont depend external packages apart bundled python bit unless absolutely necessary thank,1 the book foundations python network programming detailed comparison looks like scrape web page beautiful soup lxml library general find lxml faster effective api adheres closely python standard elementtree api comes python standard library see blog post inimitable ian bicking idea looking lxml instead oldfashioned beautiful soup library parsing html httpblogianbickingorglxmlanunderappreciatedwebscrapinglibrary,i need parse html i need python parsing library attempt fix html any suggestions tool method use python in situation html malformed script needs end processing i tried beautifulsoup fixed things i want fix i creating tool parse template files output another converted template style,2 just loop file handle openfilename r line handle pdfname line print line handleclose,i test whether string text file python like following ifpdfname openfilenameread something but i i verify i want matching line show thanks,1 you print relevant lines second statement i added existing code illustration pdfname statementconcentrator pdfname openlinegoodread print found linenum line openlinegoodreadlines linenum linenum pdfname line print slinenum line this outputs current line plus output verification found statementconcentrator checking file indeed line found note simply use script follows jobs single loop pdfname statementconcentrator linenum count line openlinegoodreadlines linenum linenum pdfname line print slinenum line count count print found linescount,i test whether string text file python like following ifpdfname openfilenameread something but i i verify i want matching line show thanks,1 the peewee orm declarative syntax familiar django users used standalone here project docs,recently i become increasingly familiar django i new project i working using python desktop application is possible use django orm desktop application or i go something like sqlalchemy,1 the peewee orm fast extremely lightweight might good fit sqa heavy,can recommend highperformance threadsafe stable orm python the data i need work complex sqlalchemy probably overkill,3 struct support integers nonpoweroftwo size this common c support integers platform either well bitfields make array def unpackx x x x structunpack hhi x return x x x,i following bytes b xxxxxxxx i trying get two integers using structunpack one first bytes one last getting first two easy using structunpackhb but returns i want return following how i get integer value last bytes i want byte individually,3 you getting error trying push list items dictionary constructor takes two items dict constructor python thinks using list possible constructors dictone two dict one two dictzip one two dict two one taken python docs need split string differently find better way formatting data if reading csv file refer michael hoffman answer correct way read csv if please specify edit goal added answer updated input axe w th street apt bnew yorkny jab rivington street apt rnew yorkny ap boxer rdnew yorkny jb karas drjersey citynj jb xylon drjersey citynj ak main streetphiladelphiapa code citydict line open extxt itemsplit citydict citydictitemsplit else citydictitemsplit print citydict output desire ny nj pa,i file i reading splitting pushing dictionary i keep getting error i think street addresses contain comma here file contents axe w th street apt bnew yorkny jab rivington street apt rnew yorkny ap boxer rdnew yorkny jb karas drjersey citynj jb xylon drjersey citynj ak main streetphiladelphiapa here code fdata open extxt line fdata print linestripsplit citydict dictitemsplit item linestrip n split print citydict it keeps throwing error jk marfield lane plainview ny citydict dictitemsplit item linestrip n split valueerror dictionary update sequence element length required i new python really idea error means thoughts greatly appreciated,2 when create dict list like need list element lists tuples for example mydict dict axe new york jab new york this corresponds list keyvalue pairs the error getting one lists list passing five elements two,i file i reading splitting pushing dictionary i keep getting error i think street addresses contain comma here file contents axe w th street apt bnew yorkny jab rivington street apt rnew yorkny ap boxer rdnew yorkny jb karas drjersey citynj jb xylon drjersey citynj ak main streetphiladelphiapa here code fdata open extxt line fdata print linestripsplit citydict dictitemsplit item linestrip n split print citydict it keeps throwing error jk marfield lane plainview ny citydict dictitemsplit item linestrip n split valueerror dictionary update sequence element length required i new python really idea error means thoughts greatly appreciated,1 assuming python collections import counter open extxt fdata print countertupleitemsplit item fdata,i file i reading splitting pushing dictionary i keep getting error i think street addresses contain comma here file contents axe w th street apt bnew yorkny jab rivington street apt rnew yorkny ap boxer rdnew yorkny jb karas drjersey citynj jb xylon drjersey citynj ak main streetphiladelphiapa here code fdata open extxt line fdata print linestripsplit citydict dictitemsplit item linestrip n split print citydict it keeps throwing error jk marfield lane plainview ny citydict dictitemsplit item linestrip n split valueerror dictionary update sequence element length required i new python really idea error means thoughts greatly appreciated,1 appending anything list exiting loop nums positive integers need something like def longestsequenceposnums index list integ obj nums obj index index else listappendindex index listappendindex return maxlist append last count index list empty end loop also called list well list actually constructor list although problem something watch,i need function tell longest sequence positive numbers list def longestsequenceposnums index list integ obj nums obj index index else listappendindex index return maxlist list contain lengths sequences positives max function working,1 the best way protect typos use tool pyflakes pylint go code let know variable asuperimportantsesssssionnnn ever used well many things if insist code two options abuse slots primary purpose slots memory optimization times hundreds thousands millions objects need keep objects footprints small possible if go route make sure include weakref one allowed names weak references continue work abuse setattr primary purpose setattr allow code run validate manipulate otherwise take data given put correct format storage to reiterate two options intended used spellcheckers efforts limit usefulness code disallowing every possible attribute name except use may appreciated someone trying support usecase anticipate,consider following example class a def initself selfveryimportantsession a averyimportantsession none ok lines averyimportantsessssionnnn i wanna exception it typo how could i make exception raised i try set member set init code fail executed gives fun time debug problems like str lol sa traceback recent call last file stdin line module attributeerror str object attribute thanks,1 replace for example match words like delete use import rematchr bdeleteb nodelete sresrematch object x group nodelete rematchr bdeleteb mismatch,sample query select cname cid company c cname like hoder cname like stock amd cname like colour cname like delete cname like regular cname like filler cname like wipe cname like palce cname like double cname it wall spycorp signal query know list words implementing query regex form wrote regex like exact matching words pnexact it wall spycorp signal regexact recompilerbsb wordlower word pnexactlist regex object words contain string eg wipe pncontains wipe palce double pnregexobjcontains recompilers joinpncontains single regex object regex working fine able write regex hanle case words hoder stock color case delete regular filler please suggest regex handle two cases thanks,1 i would use copyright billy moonmatchcopyrightwdi which means word copyright followed nonword characters w followed four digits insensitive case,for validation i need see copyright line contains digit date this would valid copyright copyright fox however would copyright fox how could i use regular expressions check string contains fourdigit date thank,1 your first code ok dbsession scopedsession dbsession constructor accessor function threadlocal storage you might speed things bit passing session explicitly premature optimization root evil,so i controller renders page in controller i call multiple functions model create sessions for example def pagerequest userid authenticateduseridrequest user usergetbyiduserid things usergetthings return user user things things where model i class user def getbyidself userid return dbsessionqueryuser def getthingsself return dbsessionquerything my question creating new session function optimal i start session controller use session throughout controller assuming i querying well inserting database controller ex def pagerequest session dbsession userid authenticateduseridrequest user usergetbyiduserid session things usergetthingssession return user user things things class user def getbyidself userid sessionnone session session dbsession return sessionqueryuser def getthingsself sessionnone session session dbsession return sessionquerything,3 if want handle network unreachable let exceptions throw error following example try tricky code goes except ioerror e ioerror exception occurred socketerror subclass eerrno error code network unreachable dosomerecovery else exceptions reraise raise,i script running testing series urls availability this one functions def checkurlurl only downloads headers returns status code p urlparseurl conn httplibhttpconnectionpnetloc connrequest head ppath resp conngetresponse return respstatus occasionally vps lose connectivity entire script crashes occurs file usrlibpythonhttplibpy line request selfsendrequestmethod url body headers file usrlibpythonhttplibpy line sendrequest selfendheaders file usrlibpythonhttplibpy line endheaders selfsendoutput file usrlibpythonhttplibpy line sendoutput selfsendmsg file usrlibpythonhttplibpy line send selfconnect file usrlibpythonhttplibpy line connect selftimeout file usrlibpythonsocketpy line createconnection raise error msg socketerror errno network unreachable i familiar handling errors like python what appropriate way keep script crashing network connectivity temporarily lost edit i ended feedback def checkurlurl only downloads headers returns status code try p urlparseurl conn httplibhttpconnectionpnetloc connrequest head ppath resp conngetresponse return respstatus except ioerror e eerrno print network error timesleep checkurlurl else raise i sure i fully understand raise though,1 you need list count maxc obj nums obj count else maxc maxcount maxc count maxc maxcount maxc,i need function tell longest sequence positive numbers list def longestsequenceposnums index list integ obj nums obj index index else listappendindex index return maxlist list contain lengths sequences positives max function working,1 one important thing aware attributes stay class slots generation useless okay maybe useless make class attributes readonly probably want the easy way say okay i initialize none let disappear excellent here one way class bobject three none four none temp vars get local namespace dict slots tempkeys put names slots slotsremove temp remove nonslots names slotsremove module remove names local name slots namespace get readonly del tempname class attributes del temp get rid temp if want keep initial values takes bit work one possible solution class bobject three four def initself key value selfinitdefaultsitems setattrself key value temp vars slots tempkeys slotsremove temp slotsremove module slotsremove init initdefaults dict name slots initdefaultsname tempname del tempname del temp as see possible without metaclass wants boilerplate a metaclass could definitely help us clean class makeslotstype def newcls name bases attrs newattrs newattrs slots slots attrskeys slotsremove module slotsremove metaclass newattrs weakref none newattrs init init newinit initdefaults dict name slots initdefaultsname attrsname return supermakeslots clsnewcls name bases newattrs def newinitself key value selfinitdefaultsitems setattrself key value class aobject metaclass makeslots one two class bobject metaclass makeslots three four now tediousness kept metaclass actual class easy read hopefully understand if need anything else classes besides attributes i strongly suggest put whatever mixin class directly final class would complicate metaclass even,this unusual question i like dynamically generate slots attribute class based whatever attributes i happened added class for example i class class aobject one two slots one two i like dynamically rather specifying arguments hand would i,1 problem solution stands going run stack space many errors single url default due recursion also extra stack frames could make tracebacks hard read calls checkurl i rewrite iterative like def checkurlurl only downloads headers returns status code true try p urlparseurl conn httplibhttpconnectionpnetloc connrequest head ppath resp conngetresponse return respstatus except ioerror e eerrno print network error timesleep except raise also want last clause try bare except else your else gets executed control falls try suite never happen since last statement try suite return this easy change allow limited number retries just change true line xrange however many retries wish accept the function return none connect site attempts you return something else raise exception adding return raise someexception end function indented line,i script running testing series urls availability this one functions def checkurlurl only downloads headers returns status code p urlparseurl conn httplibhttpconnectionpnetloc connrequest head ppath resp conngetresponse return respstatus occasionally vps lose connectivity entire script crashes occurs file usrlibpythonhttplibpy line request selfsendrequestmethod url body headers file usrlibpythonhttplibpy line sendrequest selfendheaders file usrlibpythonhttplibpy line endheaders selfsendoutput file usrlibpythonhttplibpy line sendoutput selfsendmsg file usrlibpythonhttplibpy line send selfconnect file usrlibpythonhttplibpy line connect selftimeout file usrlibpythonsocketpy line createconnection raise error msg socketerror errno network unreachable i familiar handling errors like python what appropriate way keep script crashing network connectivity temporarily lost edit i ended feedback def checkurlurl only downloads headers returns status code try p urlparseurl conn httplibhttpconnectionpnetloc connrequest head ppath resp conngetresponse return respstatus except ioerror e eerrno print network error timesleep checkurlurl else raise i sure i fully understand raise though,1 you need convert pyx output bitmap include tkinter application while convenience method get pyx output pil image directly use pipegs method prepare bitmap load using pil here comes rather minimal example import tempfile os pyx import import tkinter import image imagetk first create pyx graphics c canvascanvas ctext hello world cstrokepathline use pipegs ghostscript create bitmap graphics fd fname tempfilemkstemp f osfdopenfd wb fclose cpipegsfname devicepngalpha resolution load pil imageopenfname iload already remove temporary file osunlinkfname finally use image tkinter root tkintertk rootgeometry dxd isizeisize tkpi imagetkphotoimagei labelimage tkinterlabelroot imagetkpi labelimageplacexywidthisizeheightisize rootmainloop,i working writing script run data create graph that easy done unfortunately graphing modules i using create graphs pdf format i would like graphs displayed interactive window though is way either add graph created pyx tkinter window load pdf frame something,2 have tried removing node tags end query rerunning get result do several times get something add items back cautiously query rectified also check target page validates xhtml invalid page would probably upset parser,i writing scrapy program extract data this url i want scrape code information i taken xpath firefox addon xpather this path htmlbodyptabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtd while i trying execute try templist hxsselecthtmlbodyptabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdextract print templist strtemplist except print error it returns empty list i struggling find answer last hours i newbie scrapy eventhough i handled issues well projects seems bit difficult,1 is bad practice define one exceptions per method yes one per module typical it depends course detailed semantics the question boils what really try catch if never going use except thisverydetailedexception code detailed exception helpful if except error e esomespecialcase times matters easily simplify one exception per module handle special cases attributes exception rather different types exceptions the common suggestions one per module named error means code often look like try something except somemoduleerror e carry this gives nice naming convention moduleerror this covers numerous sins on unrelated note think got potential race condition probably redesign things correctly stop trying use threads switch multiprocessing if use multiprocessing find easy avoid race conditions,in trying eliminate potential race condition python module i wrote monitor specialized workflows i learned python easier ask forgiveness permission eafp coding style i raising lots custom exceptions tryexcept blocks i used use ifthens i new python this eafp style makes sense logically seems make code robust something feels way overboard is bad practice define one exceptions per method these custom exceptions tend useful single method feels like functionally correct solution seems like lot code maintain here sample method example class uploadtimeoutfilemissingexception def initself value selfparameter value def strself return reprselfparameter class uploadtimeouttooslowexception def initself value selfparameter value def strself return reprselfparameter def checkuploadfile timeoutseconds maxageseconds minageseconds timeout timetime timeoutseconds check file found timeout timetime timeout timesleep try filetime ospathgetmtimefile filesize ospathgetsizefile except oserror print file found file continue fileage timetime filetime make sure file preexisting fileage maxageseconds print file old file continue make sure file still uploading elif fileage minageseconds print file new file continue returnfiletime filesize timeout try filetime filesize raise uploadtimeouttooslowfile still uploading except nameerror raise uploadtimeoutfilemissingfile sent,2 your question bit broad receive targeted answer in general eafp pythonic in practice however easy overdo for example i reading i raising lots custom exceptions tryexcept blocks i used use ifthens and worries exceptions meant exceptional situations replace control flow in cases replacing condition exception inappropriate could provide concrete sample one method added exceptions exception class defined purpose,in trying eliminate potential race condition python module i wrote monitor specialized workflows i learned python easier ask forgiveness permission eafp coding style i raising lots custom exceptions tryexcept blocks i used use ifthens i new python this eafp style makes sense logically seems make code robust something feels way overboard is bad practice define one exceptions per method these custom exceptions tend useful single method feels like functionally correct solution seems like lot code maintain here sample method example class uploadtimeoutfilemissingexception def initself value selfparameter value def strself return reprselfparameter class uploadtimeouttooslowexception def initself value selfparameter value def strself return reprselfparameter def checkuploadfile timeoutseconds maxageseconds minageseconds timeout timetime timeoutseconds check file found timeout timetime timeout timesleep try filetime ospathgetmtimefile filesize ospathgetsizefile except oserror print file found file continue fileage timetime filetime make sure file preexisting fileage maxageseconds print file old file continue make sure file still uploading elif fileage minageseconds print file new file continue returnfiletime filesize timeout try filetime filesize raise uploadtimeouttooslowfile still uploading except nameerror raise uploadtimeoutfilemissingfile sent,1 the detection code produces one detection object eg different scales slightly shifted etc the detections grouped number neighbours group number returned see also viola jones paper paragraph httpresearchmicrosoftcomenusumpeopleviolapubsdetectviolajonesijcvpdf opencv source you possibly use number neighbours measure confidence,i using opencv har cascade face detector cvhaardetectobjects python example faces cvhaardetectobjectsgrayscale cascade storage cvcvhaardocannypruning f faces printf this print list detections form where line represent detection the first numbers xy location topleft point height width bounding box the last number quoting opencv documentation number neighbors i guess i two questions what last number mean i find reference googling important is way get confidence score detection how much face classifier certain detection corresponds real face thanks,3 httpcodegooglecompgoogleappenginesourcebrowsetrunkpythongoogleappengineapiquotapy if class limited use trial error jython slow it appears want though import logging googleappengineapi import quota start quotagetrequestcpuusage dosomethingexpensive end quotagetrequestcpuusage logginginfodosomethingexpensive cost megacycles end start the new separate python section httpcodegooglecomappenginedocsquotashtml appears unfinished,is way get current cpu quota app engine python the value cpu time dashboard screen administrator console thx advance,1 your dbus method call failed due access policy it probably called method without specifying interface looks like bug script tried use dbus methods always called via interface try replacing def uditodeviceself udi return selfbusgetobjectorgfreedesktophal udi with def uditodeviceself udi obj selfbusgetobjectorgfreedesktophal udi return dbusinterfaceobj dbusinterface orgfreedesktophaldevice btw hal obsolete probably switch udisks see httpwwwfreedesktoporgwikisoftwarehal,i trying make script launch custom script usb stick connected i found nice python script calls getallproperties method i get exception errordbusconnectionexception handler dbus signal traceback recent call last file usrlibpythonsitepackagesdbusconnectionpy line maybehandlemessage selfhandlerargs kwargs file halautomount line deviceadded properties selfuditodeviceudigetallproperties file usrlibpythonsitepackagesdbusproxiespy line call return selfproxymethodargs keywords file usrlibpythonsitepackagesdbusproxiespy line call keywords file usrlibpythonsitepackagesdbusconnectionpy line callblocking message timeout dbusexception orgfreedesktopdbuserroraccessdenied rejected send message matched rules typemethodcall sender uid pid commpython interfaceunset membergetallproperties error nameunset requestedreply destination uid pid commusrsbinhald os opensuse i work dbus give hint wrong thanks,1 solved if look carefully formsmodelform class imageattachmentformformsmodelform formsform class audioattachmentformformsform i changed formsform formsmodelform everything works simple copypaste error,i using django model inheritance create two models workattachmentpicture workattachmentaudio class workattachmentmodelsmodel abstract class holds fields required attachment work modelsforeignkeywork added modelsdatetimefielddefaultdatetimedatetimenow views modelsintegerfielddefault class meta abstract true class workattachmentfilebasedworkattachment another base class file based attachments description modelscharfieldmaxlength blanktrue size modelsintegerfieldverbosename size bytes class meta abstract true class workattachmentpictureworkattachmentfilebased picture attached work image modelsimagefielduploadto worksimages widthfield width heightfield height width modelsintegerfield height modelsintegerfield class workattachmentaudioworkattachmentfilebased audio file attached work file modelsfilefielduploadto worksaudio one work multiple audio video attachments i using modelformsetfactory create forms class imageattachmentformformsmodelform image attached work image formsfilefield label file helptext jpeg gif png image description formscharfield widgetformstextarea label file description helptext max symbols maxlength class meta model workattachmentpicture fields image description imageattachmentformset modelformsetfactoryworkattachmentpicture formimageattachmentform class audioattachmentformformsform audio file attached work file formsfilefield label file helptext mp file description formscharfield widgetformstextarea label file description helptext max symbols maxlength class meta model workattachmentaudio fields file description audioattachmentformset modelformsetfactoryworkattachmentaudio formaudioattachmentform everything seems correct project startup i get error metaclass conflict metaclass derived class must nonstrict subclass metaclasses bases if i create one formset imageattachmentformset example everything ok but i adding another one error appears how i solve use modelformsets inherited models,3 if look view responsible activation account via email registrationviewsactivate see accepts successurl parameter the name url pattern redirect successful activation so simply overwrite url calls view provide page wish redirect so urlspy registrationviews import activate urlpatterns patterns urlr activatepactivationkeyw activate backend registrationbackendsdefaultdefaultbackend name registrationactivate you could use reverse instead url dry er successurl http alternatively could wrap djangoregistrations activate view view accept get parameter redirect registrationview import activate def customactivaterequest backend templatename registrationactivatehtml successurlnone extracontextnone kwargs successurl requestgetget next none return activaterequest templatenametemplatename successurlsuccessurl extracontextnone kwargs now template registrationactivationemailhtml append redirection location link url registrationviewactivate activationkey aurl thanks autoescape hrefhttp sitedomain aurl next httpsomepageorurl http sitedomain urlregistrationactivate endautoescape thanks edit ok deals hard coded redirects i guessing flow want user tries go page user gets redirected loginregistration page user signs page gets sent email user activates email gets redirected original page tried view this difficult page trying view step one needs passed way step four know http stateless the first suggestion comes mind save redirect session variable register retrieve activate to overwrite djangoregistrations default backend class methods outline functionality registration process called views specifically register postactivationredirect methods custombackendpy registrationbackendsdefault import defaultbackend class redirectbackenddefaultbackend def registerself request kwargs requestsession redirect requestgetgetnextnone superredirectbackend selfregisterrequest kwargs def postactivationredirectself request user returnrequestsession redirect make sure djangoregistration actually uses backend provide views via urlspy urlr activatepactivationkeyw activate backend custombackendredirectbackend name registrationactivate urlr register register backend custombackendredirectbackend name registrationregister,djangocontribauth awesome feature when try access page decorated loginrequired get redirected login page next argument login get redirected back page originally trying access that good user flow but apparently djangoregistration provide similar feature i expected register instead login would also get next thing registeringn activating get redirected page originally trying visit this case redirected success page this hurts flow does djangoregistration perhaps provide option i using correctly or easy way,3 import lambda regex rematchregex name mr delete name like delete mr delete name like delete mr delete name like delete to find whether name one words pnexact it wall spycorp signal use set list long name pnexact name it wall spycorp signal or like use regex mrs joinmapreescape pnexact,sample query select cname cid company c cname like hoder cname like stock amd cname like colour cname like delete cname like regular cname like filler cname like wipe cname like palce cname like double cname it wall spycorp signal query know list words implementing query regex form wrote regex like exact matching words pnexact it wall spycorp signal regexact recompilerbsb wordlower word pnexactlist regex object words contain string eg wipe pncontains wipe palce double pnregexobjcontains recompilers joinpncontains single regex object regex working fine able write regex hanle case words hoder stock color case delete regular filler please suggest regex handle two cases thanks,1 the output screwed calculation convert number seconds days hours minutes seconds wrong since post bit code i say note seconds day counts seconds output smaller the values output hours minutes seconds look fine calculation days wrong,in web application i writing existing database i need calculate difference timestamp stored database text field stupid i know here sqlalchemy ban class relevant method class banbase tablename bans id column banid integer primarykeytrue unbantimestamp column unban text bannedsteamid column id text foreignkey rpuserssteamid bannedname column name text bannersteamid column bannersteamid text foreignkey rpuserssteamid bannername column banner text reason column reason text def unbannedinself mode selfunbantimestamp return never else datetimedatetimeutcnow time datetimedatetimefromtimestampintselfunbantimestamp time return expired else remaining time mode readable return remaining elif mode int return strremainingsecondszfill i need integer pretty string representations i presenting html table javascript needs simple way sort the problem i facing integers strings matching see screenshot anyone make sense output screwed would appreciated information need answer question i gladly add edit record top screenshot unbannedin timestamp i run function result i get ban sessionquerydbbanfilterbyidone print banunbannedin int banunbannedin readable days,1 if want get number seconds time use remainingdays remainingseconds instead remainingseconds,in web application i writing existing database i need calculate difference timestamp stored database text field stupid i know here sqlalchemy ban class relevant method class banbase tablename bans id column banid integer primarykeytrue unbantimestamp column unban text bannedsteamid column id text foreignkey rpuserssteamid bannedname column name text bannersteamid column bannersteamid text foreignkey rpuserssteamid bannername column banner text reason column reason text def unbannedinself mode selfunbantimestamp return never else datetimedatetimeutcnow time datetimedatetimefromtimestampintselfunbantimestamp time return expired else remaining time mode readable return remaining elif mode int return strremainingsecondszfill i need integer pretty string representations i presenting html table javascript needs simple way sort the problem i facing integers strings matching see screenshot anyone make sense output screwed would appreciated information need answer question i gladly add edit record top screenshot unbannedin timestamp i run function result i get ban sessionquerydbbanfilterbyidone print banunbannedin int banunbannedin readable days,1 the standard struct module support possible sizes either join bits together see dietrich answer use external modules bitstring bitstring import bitarray b bitarraybytesb xxxxxxxx bunpack hb standard structunpack but instead unpack second item byte bit littleendian unsigned integer bunpack h uintle gives result dietrich answer also shows got something wrong way round question what need case bunpack uintle h note could also write h uintle wanted consistent notation,i following bytes b xxxxxxxx i trying get two integers using structunpack one first bytes one last getting first two easy using structunpackhb but returns i want return following how i get integer value last bytes i want byte individually,2 here best guess print join formati rangeselfsize print join formati humangrid if really want single call stringformat print join selfsizeformatrangeselfsize print lenhumangridformathumangrid,i formatted table printing i wondering could something like i think situation lambda i never used i sure print selfsizeformatfor rangeselfsize self size assumed example work something along line needed though basically thisbelow cleaner way ps know example work get drift print formathumangridhumangridhumangridhumangridhumangrid thanks,1 i use something like pyqt import qtgui qt pyqt import qtcore qc class mainwinqtqmainwindow def setkeepaboveself selfsetwindowflagsselfwindowflags qcqtwindowstaysontophint else selfsetwindowflagsselfwindowflags amp qcqtwindowstaysontophint,i would like keep pyqt window like i gtk setkeepabovetrue is possible edit code i know force window usrbinpython coding utf import os sys signal pyqtqtcore import pyqtqtgui import pyqtqtwebkit import pyqtqtscript import pyqtqtnetwork import ospathexistsforumsmileyscache pass else osmkdirforumsmileyscache app qapplicationsysargv signalsignalsignalsigint signalsigdfl webpage qwebview webpagesetwindowtitleforums smileys code manager webpagepagenetworkaccessmanager diskcache qnetworkdiskcachewebpage diskcachesetcachedirectoryforumsmileyscache managersetcachediskcache webpageshow webpagesetgeometry webpageresize webpageloadqurlhttpwwwsputnickareanetsmileyshtml sysexitappexec,1 assuming trying pring list names centered tabular way one way humangrid john jacob jezebel mary maria mel shareen sean shiva cellwidth maxleny x humangrid x get length longest name cellwidth optional padding row humangrid print joinnamecentercellwidth name row running give john jacob jezebel mary maria mel shareen sean shiva to change alignment table simply replace center ljust rjust one quite easily replace use format i find approach lot readable,i formatted table printing i wondering could something like i think situation lambda i never used i sure print selfsizeformatfor rangeselfsize self size assumed example work something along line needed though basically thisbelow cleaner way ps know example work get drift print formathumangridhumangridhumangridhumangridhumangrid thanks,1 define one exceptions per method if mean exception actually defined per method within method body yes that bad practice this true also define two exceptions would relate error create two two different methods raise if ask whether bad practice raise one exception per method good practice and errors category perfectly ok define several exceptions per module in general larger modules define one exception if would work arithmetic library would define zerodivisionerror overflowerror already defined python course reuse would perfectly fine,in trying eliminate potential race condition python module i wrote monitor specialized workflows i learned python easier ask forgiveness permission eafp coding style i raising lots custom exceptions tryexcept blocks i used use ifthens i new python this eafp style makes sense logically seems make code robust something feels way overboard is bad practice define one exceptions per method these custom exceptions tend useful single method feels like functionally correct solution seems like lot code maintain here sample method example class uploadtimeoutfilemissingexception def initself value selfparameter value def strself return reprselfparameter class uploadtimeouttooslowexception def initself value selfparameter value def strself return reprselfparameter def checkuploadfile timeoutseconds maxageseconds minageseconds timeout timetime timeoutseconds check file found timeout timetime timeout timesleep try filetime ospathgetmtimefile filesize ospathgetsizefile except oserror print file found file continue fileage timetime filetime make sure file preexisting fileage maxageseconds print file old file continue make sure file still uploading elif fileage minageseconds print file new file continue returnfiletime filesize timeout try filetime filesize raise uploadtimeouttooslowfile still uploading except nameerror raise uploadtimeoutfilemissingfile sent,3 joquin suggestions worked well highlighted i probably going plotting wrong way start however sake completeness i eventually found get rid d axis simply using selfaxesgetxaxissetvisiblefalse selfaxesgetyaxissetvisiblefalse this seems one way least removing d labels d plots appear,i probably simple problem replotting d data using matplotlib initially i figure d projection canvas selffig pltfigure selfcanvas figcanvasselfmainpanel selffig selfaxes selffigaddsubplot projection i add data use canvasdraw update the plot updates expected i get additional d axis outside figure i work stop selfaxesclear selfaxes selffigaddsubplot projection xs nprandomrandomsample ys nprandomrandomsample zs nprandomrandomsample selfaxesscatterxs ys zs c r marker selfcanvasdraw any ideas i going circles right,1 the best option make module say fixes exports fixed version external version btdtri depending scipy version example it done even simpler scipyversionversion def btdtri whatever else btdtri scipybtdtri this advantage version code checking tools like pyflakes choke import need fetch scipy api fixes module part needs fixing remember explicit better implicit,i recently following problem i developing numerical library python called spuq needs scipy core now one functions scipy called btdtri bug certain tuple input parameters this bug however fixed scipy version according developers scipy so code i something like import scipy def fooa b c scipyversion return btdtria b c else return myfixedbtdtria b c this works however i really like litter code bug fixes third party packages i would rather contained one module implements workaround modules uses patched module automatically now question would best practice handle cases like general eg write spuqcontribscipy say scipy import version btdtri myfixedbtdtri instead importing scipy import spuqcontribscipy everywhere i think complicated easy forget probably unpythonic ugly maybe way hook automatically package loading modify scipy module directly every package sees patched package i think problem quite common probably bestpractices around,1 take bar try block try foo except pass bar btw watch catchall except clauses prefer selectively catch exceptions know handleignore,eg try foo bar except pass when foo function raise exception skip next line bar execute,3 can done call bar inside try block either put call outside tryexcept block use else try foo except pass else bar if bar might throw exception well use separate try block bar,eg try foo bar except pass when foo function raise exception skip next line bar execute,2 you could monkey patch scipy module somewhere initialization code import scipyspecial scipyversionversion scipyspecialbtdtri mybtdtri since modules imported one module scipyspecial modules see monkeypatched version monkey patching often seen useful testing production code in case though i think fine since really change behaviour package fixing confirmed bug,i recently following problem i developing numerical library python called spuq needs scipy core now one functions scipy called btdtri bug certain tuple input parameters this bug however fixed scipy version according developers scipy so code i something like import scipy def fooa b c scipyversion return btdtria b c else return myfixedbtdtria b c this works however i really like litter code bug fixes third party packages i would rather contained one module implements workaround modules uses patched module automatically now question would best practice handle cases like general eg write spuqcontribscipy say scipy import version btdtri myfixedbtdtri instead importing scipy import spuqcontribscipy everywhere i think complicated easy forget probably unpythonic ugly maybe way hook automatically package loading modify scipy module directly every package sees patched package i think problem quite common probably bestpractices around,3 that intended way tryexcept blocks used if bar executed even foo fails put tryexcept block try foo except pass whatever try bar except pass whatever,eg try foo bar except pass when foo function raise exception skip next line bar execute,1 first get objects sorted last name def keyfunp return pnamesplit persons sortedpersonobjectsall key keyfun then use groupby itertools import groupby lname persons groupbypersons keyfun print joinpname p persons update yes solution works new requirement all need stable way generate keys item replace body keyfun import findall def keyfunp v v findallpname tot intv intv return tot your description generate key item clear enough although able figure example,i building app search objects database let assume objects search persons what i want group related objects example married couples in words two people share last name assume married great example get idea the last name thing identifies two people married in search results i want display married couples next persons let say search john i want john smith jane smith john adams nancy adams john washington john andersson john ryan each name link person profile page what i right function finds pairs returns list tuples tuple pair the problem search results every name pair listed twice i query search query personobjectsfilternamecontainsjohn result query sent match function i send original queryset match function result template i guess i could exclude every person match function finds match i know efficient solution edit as i wrote comment actual strings i want match identical to quote in fact strings i want match identical instead look like foobar foobar that two strings foo id bar id odd number match bar id i regular expression find matches,1 you could either python suggested let db dirty work you would need construct queryset containing threads deleted message particular user second queryset gets threads contained first delthreads messagethreadobjectsfiltermessagerecipientrecipientuser messagerecipientstatus deleted distinct result messagethreadobjectsfiltermessagerecipientrecipientuser excludemessagethreadindelthreadsdistinct however performance wise especially large tables hurt your model needs restructuring allow efficient queries consider class messagethreadmodelsmodel subject modelscharfieldmaxlength blankfalse class messagemodelsmodel thread modelsforeignkeymessagethread content modelscharfieldmaxlength blankfalse timestamp modelsdatetimefieldautonowaddtrue blankfalse sender modelsforeignkeyuser recipient modelsforeignkeyuser status modelscharfieldmaxlength choicesmessagestatus defaultunread if anticipate execute query often could add cache field messagethread update whenever someone deletes message thread class messagethreadmodelsmodel subject modelscharfieldmaxlength blankfalse dirty modelsbooleanfielddefaultfalse then would easy extract list threads deleted messages nondelthreads messagethreadobjectsfiltermessagerecipientuser dirtytruedistinct,i following models internal messaging app class messagethreadmodelsmodel subject modelscharfieldmaxlength blankfalse class messagemodelsmodel thread modelsforeignkeymessagethread content modelscharfieldmaxlength blankfalse timestamp modelsdatetimefieldautonowaddtrue blankfalse sender modelsforeignkeyuser class messagerecipientmodelsmodel message modelsforeignkeymessage thread modelsforeignkeymessagethread recipient modelsforeignkeyuser status modelscharfieldmaxlength choicesmessagestatus defaultunread for given user get list threads i distinctthreadsmessagethreadobjectsfiltermessagerecipientrecipientuser orderby messagetimestamp distinct how would i get rid threads message contains status deleted orm in words i want get list threads without thread containing message statusdeleted,1 i using opencv relies binaries etc i scripts every line silly error python dynamic language occasions considered errors i removed errors altogether going window preferences pydev editor code analysis undefined undefined variable from import ignore and it may also window preferences pydev editor code analysis imports import found ignore,i got python project using pydev eclipse pydev keeps generating false errors code i module settings defines settings object i import module b assign attribute settings import settings settingsmain object in codebut statements like settings import settings print settingsmain generate undefined variable import main messages eclipse code error pane even though code runs without problem how i correct,3 you may find pickle databases work well together python pickle serializing python objects format read back python objects python although easy serialize pickle query serialized format read program another language check cpickle another python module faster pickle ing databases hand great persisting data way queryable nonlanguagespecific but cost generally harder getput data intofrom database that special tools like sql alchemy endless blogbased debates benefitshorrors objectrelationmapping software pickle ing objects sending database mysql sql server probably good idea however check shelve another python module databaselike persistence python objects so sum use pickle shelve need save data later use python program map objects database want persist data general use understanding requires effort performancewise cpickle probably win database objectrelation mapping least without lot effort andor special libraries,i want classify text so i compare texts after representing texts vectors i store big lists float values sql database using later my idea using pickle module vectortexttovectortext presentpickledumpsbiglist somedbsavetextidpresent later presentsomedbgettextid vectorpickleloadspresent is fast effective i thousends texts,1 i believe i found one possible solution although seems result bit memory issue i suspect actually deleting initial plot data removing figure memory usage climb every time projection changed delete d subplot selffigdelaxesselfaxes create new subplot d selfaxes selffigaddsubplot d scatter selfaxesplotnprandomrandn nprandomrandn update figure selfcanvasdraw,i matplotlib figure i want able switch d d projections i go d d i seem work go way example import numpy np mpltoolkitsmplotd import axesd import matplotlibpyplot plt def randrangen vmin vmax return vmaxvminnprandomrandn vmin fig pltfigure create d scatter plot ax figaddsubplot projection n c zl zh r b xs randrangen ys randrangen zs randrangen zl zh axscatterxs ys zs cc markerm axsetxlabel x label axsetylabel y label axsetzlabel z label now i want d plot axcla ax figaddsubplot axplotxs ys pltshow the plot stays d projection projectiond valid kwarg i thought perhaps axclf would i wanted let define new figure but gives following error valueerror unknown element can anyone give hint solution is valueerror related problem hint something else wrong setup is kwarg switch projection d d many thanks advance pointer provide dan,1 the problem involves parents your buttons parent frame listbox parent panel give panel buttons parent issue go away by way usually good idea assign id numbers especially low ones since might used but really want follow instructions robin dunn wxpython book you ensure wxpython use explicit id elsewhere application calling global function wxregisterid to prevent program duplicating wxpython ids avoid using id numbers global constants wxidlowest wxidhighest edit here example sorts change wxbuttonself close wxbuttonself random move wxbuttonpanel close wxbuttonpanel random move then register ids wxregisterid wxregisterid personally i would create buttons like instead closebtn wxbuttonpanel wxidany close selfbindwxevtbutton selfonclose closebtn randombtn wxbuttonpanel wxidany random move selfbindwxevtbutton selfonrandommove randombtn,i problems wxpython when i run following code show listbox small form show listbox x i know happening much resources online help the listbox show correctly add buttons pardon easy fix however truly stumped if understand problem please run following code see import wx class myframewxframe make frame inherits wxframe def initselfparentid create frame parent default wxidany wxframeinitself parent id testing pos size panel wxpanelself samplelist dsakdsko listbox wxlistboxpanel samplelist wxlbsingle listboxsetselection selfsetbackgroundcolourwhite wxbuttonself close wxbuttonself random move selfbindwxevtbutton selfonclose id selfbindwxevtbutton selfonrandommove id show frame selfshowtrue menu bar statusselfcreatestatusbar menubarwxmenubar firstwxmenu secondwxmenu firstappendwxnewidnewcreates a new file firstappendwxnewidadidyo menubarappendfirstfile menubarappendsecondedit selfsetmenubarmenubar def oncloseself event selfclosetrue def onrandommoveself event screensize wxgetdisplaysize randx randomrandrange screensizex appsizex randy randomrandrange screensizey appsizey selfmoverandx randy name main application wxpysimpleapp framemyframeparentnoneid frameshow start event loop applicationmainloop thank much,1 pexpect may useful httppypipythonorgpypipexpect,is way send command another interactive shell let take example meterpreter shell used metasploit could way say command shell python code soon i get control computer meterpreter shell play i mean all python code thanks help rod,2 you close if want build dictionary sheet contains keys values first two columns simply print dictshrowvaluesrownum rownum rangeshnrows as john y mentioned need extract two specific columns indexes keys j values instead print dictshcellvaluerownum shcellvaluerownum j rownum rangeshnrows the key point dict build dictionary iterable key value tuples,i excel spreadsheet columns something like cola colb key value test test test i want read two columns dictionary i currently working figure extract key value pair sh wbsheetbyindex rownum rangeshnrows print shrowvaluesrownum,2 you extract data ease using robust xpaths instead taking direct output xpather for data matching xpath would lot better fontcontainstext code parenttdfollowingsiblingtdfonttext this match font tag containing code go td tag select next td font contains code looking,i writing scrapy program extract data this url i want scrape code information i taken xpath firefox addon xpather this path htmlbodyptabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtd while i trying execute try templist hxsselecthtmlbodyptabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdextract print templist strtemplist except print error it returns empty list i struggling find answer last hours i newbie scrapy eventhough i handled issues well projects seems bit difficult,1 how import argparse name main parser argparseargumentparserdescription print range parseraddargumentstart type int help specify start parseraddargumentstop type int help specify stop parseraddargumentstep type int help specify step argsparserparseargs printargs yields testpy h usage testpy h start stop step print range positional arguments start specify start stop specify stop step specify step optional arguments h help show help message exit,in argparse package metavar parameter modifies displayed help message program the following program intended work simply used demonstrate behavior metavar parameter import argparse name main parser argparseargumentparserdescription print range parseraddargumentrange nargs type int help specify range start stop step metavar start stop step parseraddargumentrange nargs type int help specify range start stop step metavar r the corresponding help message usage mainpy h range start stop step range r r r print range optional arguments h help show help message exit range start stop step specify range start stop step range r r r specify range start stop step please note differences behind range range clearly range preferred way help message up point everything clear however i change optional range argument positional range argument argparse cannot deal tuple metavar parameter valueerror many values unpack the way i able get work way range done but help message far good range case is way get help message range case positional argument instead optional,3 the sql query executed call contentquery query fail point something wrong contentclass example at least i noticed forgot objects first line contenttype contenttypeobjectsgetapplabel myproject model building edit i get str object attribute items error marks incorrectly interpreted this fixed build contentquery contentclassobjectsrawselect pmsbuilding namelike,help i two objects created using different techniques django djangocontribcontenttypesmodels import contenttype myprojectmodels import building method a contenttype contenttypeobjectsgetapplabel myproject model building contentclass contenttypemodelclass contentquery contentclassobjectsrawselect pmsbuilding name like build typecontentquery class djangodbmodelsqueryrawqueryset contentquery error attribute str object attribute items method b bld buildingobjectsrawselect pmsbuilding name like build typebld class djangodbmodelsqueryrawqueryset bld building building a my question two objects type behaving differently gath,1 after looking source exception occurs i suggest trying sl dbsessionquerypuestoidfilterpuestolocalesid idsubquery dbsessionqueryserviciofilterserviciopuestosidinsl deletesynchronizesession fetch see documentation delete method means passing fetch argument basically run query twice select delete if running two queries desired pass synchronizesessionfalse instead call sessionexpireall immediately delete avoid inconsistent state within metadata store,i trying delete child rows using filtered query without result sl dbsessionquerypuestoidfilterpuestolocalesid idsubquery dbsessionqueryserviciofilterserviciopuestosidinsldelete i getting invalidrequesterror could evaluate current criteria python specify fetch false synchronizesession parameter error full stack trace traceback recent call last file usrsrctgenvceafceafcontrollersrootpy line deletelocal dbsessionqueryserviciofilterserviciopuestosidinsldelete file usrsrctgenvlibpythonsitepackagessqlalchemypyeggsqlalchemyormquerypy line delete raise saexcinvalidrequesterror invalidrequesterror could evaluate current criteria python specify fetch false synchronizesession parameter i able find problem any idea regards,3 edit as ollie pointed comment post isinteger part standard library therefore reimplemented i this function uses fact every whole number least one number divisible two remainder any nonzero fractional representation either n n cause n n remainder this benefit whole numbers represented float values return true the function works correctly positive negative numbers zero far i determine as mentioned function fails values close integer def isintegern return true argument whole number false argument fractional part note values close integer test breaks during superficial testing closest value zero evaluated correctly e when dividing number python evaluated result zero n n return true return false,i would like determine numeric value python whole number for example given x i want distinguish values x evenly divisible,1 i assume candidate may take part one election election one candidates this mm relationship efficient way implement use listfields app engine you try use reference properties mind multiple entities candidate ever takes part one election another tip keeping datastore write limits mind sec instead every vote action updating counter candidate either use sharded counters create new tasks run taskqueue taskssec upper limit,i working gae python app running elections i election entity election each election around candidates i candidate entity candidate i considering three different options modeling entity relationship having election ancestor candidate adding reference property candidate refers election adding list property election contains list candidate keys since number candidates relatively small seems could work i currently first option since i using highrep data store i want strong consistency for election app pros cons three options,1 it clear want validations multiplechoicefield want multipleselectwidget solution simply change field studies formscharfieldwidgetformsselectmultiple validations def cleanstudiesself,i got view different forms the first form search field populates multiple choice field user types query search field ajax call sent bring records match query the user selects choices first multiple choice field clicks add move different multi select box similar multi select widget django admin httpimgimageshackusimgmultiselectwidgetgif this works fine form submits i receive error reads select valid choice one available choices i tried setting choices receiving arguments form init seem work my form class sitecoordinatorformformsmodelform selectedstudies formsmultiplechoicefieldrequired false site formschoicefieldrequired false studies formsmultiplechoicefieldrequired false studysearch formscharfieldmaxlength required false def initself args kwargs supersitecoordinatorform selfinitargs kwargs args studylist querydict args selffields selectedstudies choices intx x x querydictgetlist selectedstudies selffields site choices xpk xprimaryname xprimarynumber x siteobjectsallorderby primaryname class meta model sitecoordinator exclude studies site selectedstudies my ajax function populates box def searchstudiesrequest returndata studies makequery lambda terms fieldname reducelambda x x amp qfieldname icontains terms q searchtext requestpost terms requestpost searchtext split rec studyobjectsfiltermakequeryterms name studiesappend study id recid name recname number recid response status success count lenstudies studies studies return httpresponsesimplejsondumpsresponse mimetypeapplicationjson the function populate multiselectbox function showresultsdata statuscode request recs datastudies var selectbox documentgetelementbyid idstudies selectboxoptionslength var index index recslength index selectboxoptionsindex new optionrecsindexstudyname recsindexstudyid false false then jquery move choices add clickfunction idstudies optionselected removeappendto idselectedstudies return false remove clickfunction idselectedstudies optionselected removeappendto idstudies return false,2 since strings length could line days break if much assumption anylinestartswithday day days break another tip assuming python openfile source openfile w line source outwriteline anylinestartswithday day days break think closing files manually even exception occurs and still python lower build function def anyiterable element iterable element return true return false,source openfile openfile w days mon tue wed thu fri sat sun line source outwriteline linestartswith here is where i would like the days to be looped break outclose,2 try like line days true pass,source openfile openfile w days mon tue wed thu fri sat sun line source outwriteline linestartswith here is where i would like the days to be looped break outclose,1 hint def countcls attr attr attr dircls attrstartswith method getattrclsattr callablemethod setattrclsattrfunccountmethodattr return cls,i working learning python th edition i currently working exercises part vi book the exercise i currently kind confusing i hoping i could get little guidance i solve here prompt i working subclassing make subclass mylist exercise called mylistsub extends mylist print message stdout overloaded operation called counts number calls mylistsub inherit basic method behavior mylist adding sequence mylistsub print message increment counter calls perform superclass’s method also introduce new method prints operation counters stdout experiment class interactively do counters count calls per instance per class instances class how would program option hint depends object count members assigned class members shared instances self members perinstance data so part i really interested right make subclass mylist exercise called mylistsub extends mylist print message stdout overloaded operation called counts number calls i see good use dry right kill birds one stone but i know implement i know i implement kind method intercepts operations increments counter prints message but i know best go my basic idea something like def countopsself opcount intercept calls operator overloading methods opcount print number calls operator formatoper opcount note this code i written yet borderline pseudocode highlight i want can i get little help please give answer outright i want figure hints go much answers,1 call pterminate sigterm handler ppoll none child still around pterminate kill edit since stuck python use oskillppid signalsigterm instead pterminate the check make sure get exception reduce number times get one to make even better catch exception check message if means child process found ignore exception otherwise rethrow raise arguments,i script repeatedly runs ant buildfile scrapes output parsable format when i create subprocess using popen small time window hitting ctrlc kill script kill subprocess running ant leaving zombie printing output console killed using task manager once ant started printing output hitting ctrlc always kill script well ant is way make hitting ctrlc always kill subprocess running ant without leaving zombie behind also note i handler sigint performs cleanup operations calling exit if i manually kill subprocess handler using oskillppid signalsigterm sigint i successfully kill subprocess situations would normally zombify however hit ctrlc ant started producing output get stacktrace subprocess unable kill subprocess i already killed edit my code looked something like p popen ls def handlesigintsignum stackframe perform cleanup oskillppid signalsigterm exit signalsignalsignalsigint handlesigint pwait which would produce following stacktrace triggered incorrectly file py line runtest pwait file usrlibpythonsubprocesspy line wait pid sts oswaitpidselfpid file py line handlesigint oskillppid signalsigterm i fixed catching oserror raised pwait exiting try pwait except oserror exit the operation interrupted user this seems work vast majority test runs i occasionally get uname write error broken pipe though i know causes it seems happen i time ctrlc right child process start displaying output,1 the string argument well named it pointer python unicode object printf seeing lot binary data object type gc headers ref count encoded unicode code points happens find zero byte printf interprets end string the simplest way view string pyobjectprintstring you find c functions manipulating python unicode objects httpdocspythonorgcapiunicodehtmlunicodeobjects,i simple python script import tph str u ðŸñ€ð¸ð²ðµñ‚ bð¼ð¸ñ€b some unicode string russian characters tphstriptagsstr c library compiled tphso this striptags function pyobject striptagspyobject self pyobject args pyunicodeobject string pyssizet length pyargparsetupleargs u ampstring amplength printfd dn stringlength length printf function prints so str length really symbols deep hell i getting characters when i printing string i got str null char lot junk bytes junk memory looks like u ufuuuuu bucuubxxuubucubxubcucexucabxubububcubcubcubxxx how i get normal string,3 linestartswithtupledays documentation sstartswithprefix start end bool return true s starts specified prefix false otherwise with optional start test s beginning position with optional end stop comparing s position prefix also tuple strings try the last line answer question,source openfile openfile w days mon tue wed thu fri sat sun line source outwriteline linestartswith here is where i would like the days to be looped break outclose,2 looking helpstrstartswith see method accepts tuple strings search one step mon first day startswith mon tue wed thu fri sat sun true here variant runs older versions python import days mon tue wed thu fri sat sun pattern joindays rematchpattern tue first day print found found,source openfile openfile w days mon tue wed thu fri sat sun line source outwriteline linestartswith here is where i would like the days to be looped break outclose,2 pythonpath red herring virtualenv uses configure the virtualenv works adding prefix path points location alternate python executable overriding system python the problem vim python embedding look python executable path looks loads libpython library virtualenv virtualize this means vim always initialize system python regardless virtualenv however lost vim still run virtualenv initialization script python initialization jeremy cantrell wrote vim plugin help automate solve problem httpsgithubcomjmcantrellvimvirtualenv,if type vim command line python import osprint osgetenv pythonpath i get path if close vim terminal echo pythonpath i get another completly different path why vim getting path this relevant autocompletion find modules thus doesnt work i know try vim cli python import django it fails but exit vim type python import django no errors shown whats going i using virtualenv checked activate source changing pythonpath i tried without virtualenv problem update the line used configure vim source prior compiling configure prefixhomeappsvim withfeatureshuge enableguignome enablepythoninterp enablerubyinterp enablemultibyte withpythonconfigdirusrlibpythonconfig,2 you correct web application requires access private key user local computer pki store i developed solution web application usaf network users logon usaf computer cac card containing pki credentials private key in solution needed digitally sign pdf documents generated web application we built activex control would download pdf document web site via web service digitally sign pdf locally transmit signed pdf document back web site since signature authority documents limited audience able get authorization use activex control you heading right path locally authorized application access user key store,immagine web application written pythondjango users authenticate digital certificates via apachemodssl custom django authentication backend sign files the certificates released government approved cas if i wrong file needs signed private key certificate proof file really signed someone someoneelse pretending someone how web application access private key certificate stored browser user is possible without need software running user machine edit so done either activex control java applet right does need developed scratch anybody know open source solution,1 i assume csvcut python script otherwise functional throwing error tries close files exit if say script otherwise working assuming error csvcut throwing outputs stderr redirecting devnull would temp fix cat eof outputfile devnull naturally error messages heredoc also redirect,i written bash script exactly i want kicking following error close failed file object destructor sysexcepthook missing lost sysstderr i completely stumped address here script binbash usage echo inputfile outputfile exit usage inputfile outputfile all written cat command eof sent output file cat eof outputfile date generated mdy hms data audit column names csvcut n inputfile first ten rows of first five columns csvcut c inputfile head n column stats csvcut inputfile csvstat end audit eof echo audited i pretty new shell scripts new python i would grateful help,1 this another website different way access docs may even qualify api docs generous all need python interpreter import csv print csvdoc dircsv print csvreaderdoc i found great way quick check exactly spell method order arguments without bring webbrowser or pointed steven rumbalski also builtin function help this used interactively show information given module also pointed rplnt many shells syntactic sugar accessing helpself documentation features python if however actually serious programmatically creating documentation websitesystem decent start could crawl object hierarchy given module using dir builtin compiling docstrings different methodsfunctions doc accessing i personally opinion however combination interactive help using sitedocspythonorg google sufficient cases,i love python i disappointed offerings online documentation ruby seems many documentation sites httprubydocorgdocsprogrammingruby httpapirubyonrailsorg i know rails ruby httpapidockcomruby i course aware official docs httpdocspythonorg i looking something robust features search autocomplete commenting etc personally i find official docs little bit rigid navigate read if alternative site exists would recommend i go creating one is sort api query python docs note question related what good online documentation,1 no first approach guarantee data written since guaranteed file flushed closed handle longer referenced write member this likely case cpython necessarily python interpreters implementation detail python garbage collector you really use second approach except osfsync needed close file data available processes or even better python openselfstatusfile w f fwritestatus the version exceptionsafe file closed even write fails,one python process writes status updates file processes read in circumstances status updates happen repeatedly quickly loop the easiest fastest approach use openwrite one line openstatusfile w writestatus an alternate approach four lines force data disk this significant performance penalty f openselfstatusfile w fwritestatus osfsyncf fclose i trying protect os crash so approach force data os buffer processes read newest status data open file disk or i need use osfsync,3 are overloaded methods anything else besides counting calls in words write anyway if yes could use decorators seperate function like one call method if overloading needed subclass counting look getattribute be warned bit complicated want thorough understanding ever used production code other options include class decorator metaclass wrap methods care,i working learning python th edition i currently working exercises part vi book the exercise i currently kind confusing i hoping i could get little guidance i solve here prompt i working subclassing make subclass mylist exercise called mylistsub extends mylist print message stdout overloaded operation called counts number calls mylistsub inherit basic method behavior mylist adding sequence mylistsub print message increment counter calls perform superclass’s method also introduce new method prints operation counters stdout experiment class interactively do counters count calls per instance per class instances class how would program option hint depends object count members assigned class members shared instances self members perinstance data so part i really interested right make subclass mylist exercise called mylistsub extends mylist print message stdout overloaded operation called counts number calls i see good use dry right kill birds one stone but i know implement i know i implement kind method intercepts operations increments counter prints message but i know best go my basic idea something like def countopsself opcount intercept calls operator overloading methods opcount print number calls operator formatoper opcount note this code i written yet borderline pseudocode highlight i want can i get little help please give answer outright i want figure hints go much answers,1 webdriverfirefox fact webdriverfirefoxwebdriver just look code seleniumwebdriverinitpy seleniumwebdriverfirefoxwebdriverpy inherits lot remotewebdriver class there short introduction selenium python bindings have fun,note this may meta issue understand documentation rather specific issue selenium bindings i looking selenium python bindings i bit confused most examples start simple instance browser require something like selenium import webdriver browser webdriverfirefox browsergetwwwgooglecom now i look webdriverfirefox object i see four methods associated object i sure where instance get example so i start looking around i see bunch methods i use webdriverfirefox object webdriverremote but seem make sense i using webdriverremote why methods finally confusion compounded fact seleniumselenium host interesting powerful methods i idea use then work webdriverfirefox object i use why never appear examples,1 compute mean adding random numbers distribution list then simple plot nelement list the problem needed list scalars list arrays distribution range n randomnumbersrandomuniformsizen distributionappendarrayrandomnumbersmean,want create program calculates average n random numbers taken uniform random number distributionthe program must run î random numberstheni plot mean value function n i scitoolsstd import import matplotlibpyplot plt n distribution range n randomnumbersrandomuniformsizen distributionappendrandomnumbers pltsemilogxarrayrangenarraydistributionmean pltxlabel n pltgridtrue pltshow it gives error title line plot alsoif another pythonic way appreciate thank,1 import scipy import matplotlibpyplot plt nsi range meansscipyrandomuniformsizenmean n ns pltsemilogxnsmeans pltxlabel n pltgridtrue pltshow as already mentioned distribution list arrays inner arrays different shapes you form numpy array object calling nparraydistribution at least plotting purposes need save entire distribution just compute store means a succinct way use list comprehension don use module import scripts it makes hard trace variables come the module import made mainly use interactive sessions generally recommended scripts,want create program calculates average n random numbers taken uniform random number distributionthe program must run î random numberstheni plot mean value function n i scitoolsstd import import matplotlibpyplot plt n distribution range n randomnumbersrandomuniformsizen distributionappendrandomnumbers pltsemilogxarrayrangenarraydistributionmean pltxlabel n pltgridtrue pltshow it gives error title line plot alsoif another pythonic way appreciate thank,1 your cutting point http requests write mock library intercepts sending http requests instead sending convert string analyze test sending code for receiving code mock response handler save good response rest server string create http response object test receiver write test cases create requests real thing quickly verify requestsresponses good,i writing python library access ubuntu one rest api yes i know one already exists scratchmyitchandlearnwhiledoingit project the library relatively thin wrapper around rest calls i would like able unittest library without hitting u what best practise standard making possible at moment rest call explicit http request i see mock i create mockable ubuntuonerestapi class hiding http calls i suspect end including functionality wrapper library sort defeats purpose,1 the timeit module ya,i written functions exact thing i know one faster better how i compare functions see one better terms performance everything,2 thanks answers taking inspiration i come following i think hope works i intended i sure whether post answer addition question thought answer appropriate fails i asked commented appropriately it used example like contextlist open f rb f files fs like flock threadinglock contextlist flock open f rb f files lock fs and import inspect import collections import traceback class contextlist def initself contexts selfargs ctx contexts inspectisgeneratorctx selfargs ctx else selfargsappendctx def enterself hasattrself ctx raise runtimeerrorcannot reenter contextlist sctx selfctx try ctx selfargs isinstancectx collectionssequence ctx ctxctx sctxappendctx try ctxenter except exception sctxpop raise return sctx except selfexit raise def exitself excinfo hasattrself ctx raise runtimeerrorcannot exit unentered contextlist e ctx reversedselfctx try ctxexit except exception eappendtracebackformatexc del selfctx e raise exception n joinereplace n n,i aware i open multiple files something like open rb open b rb b but i situation i list files open wondering preferred method number files unknown advance something like openf rb f files fs fails attributeerror since list implement exit i mind using something like try fs openf rb f files finally f fs fclose but sure happen files throw trying open will fs properly defined files manage open finally block,1 i tried yet look python tools visual studio you specify version visual studio using pytools vs,i multiple python files school project i want open edit visual studio make simple i want solution project visual studio code provided though professor used emacs create files is way i directory py files opened together sln thanks,3 here two tested pieces code model print subprocesscheckoutput grep python apitalktxt discuss python api patterns limitations python introspection python print subprocesscheckoutput grep python txt shelltrue use latter want shell wildcard expansion when shell true sure put whole command single string rather list separate fields,i trying use grep command python script using subprocess module here i userid foo p subprocesspopen grep loguserid stdoutsubprocesspipe and returns nothing i entirely sure i wrong someone please explain the current method i using works adding shelltrue makes output correct output help pages pointed unsafe i need help trying make work script unsafe,3 i assuming want grep foo files end log get work subprocess need change code following userid foo p subprocesspopen grep log userid stdoutsubprocesspipe shelltrue shelltrue necessary wildcard expansion option set need provide string command instead list also make sure providing list arguments argument separate entry list initial code would equivalent following grep foo log,i trying use grep command python script using subprocess module here i userid foo p subprocesspopen grep loguserid stdoutsubprocesspipe and returns nothing i entirely sure i wrong someone please explain the current method i using works adding shelltrue makes output correct output help pages pointed unsafe i need help trying make work script unsafe,2 you look mapredtasktimeout if large amount data machines process task might timing you set value disables timeout alternatively call contextprogress equivalent function say something happening job timeout,i map reduce job running fine i started see failed map tasks like attemptm taskm worker failed task attemptm failed report status seconds killing task attemptm failed report status seconds killing last kb last kb all attemptm taskm master failed javalangruntimeexception javaioioexception spill failed orgapachehadoopstreamingpipemapredwaitoutputthreadspipemapredjava orgapachehadoopstreamingpipemapredmapredfinishedpipemapredjava orgapachehadoopstreamingpipemapperclosepipemapperjava orgapachehadoopmapredmaprunnerrunmaprunnerjava orgapachehadoopstreamingpipemaprunnerrunpipemaprunnerjava orgapachehadoopmapredmaptaskrunoldmappermaptaskjava orgapachehadoopmapredmaptaskrunmaptaskjava orgapachehadoopmapredchildrunchildjava javasecurityaccesscontrollerdoprivilegednative method javaxsecurityauthsubjectdoassubjectjava orgapachehadoopsecurityusergroupinformationdoasusergroupinformationjava orgapachehadoopmapredchildmainchildjava caused javaioioexception spill failed orgapachehadoopmapredmaptaskmapoutputbuffercollectmaptaskjava orgapachehadoopmapredmaptaskoldoutputcollectorcollectmaptaskjava orgapachehadoopstreamingpipemapredmroutputthreadrunpipemapredjava caused orgapachehadooputildiskcheckerdiskerrorexception could find valid local directory outputspillout orgapachehadoopfslocaldirallocatorallocatorpercontextgetlocalpathforwritelocaldirallocatorjava orgapachehadoopfslocaldirallocatorgetlocalpathforwritelocaldirallocatorjava orgapachehadoopfslocaldirallocatorgetlocalpathforwritelocaldirallocatorjava orgapachehadoopmapredmapoutputfilegetspillfileforwritemapoutputfilejava orgapachehadoopmapredmaptaskmapoutputbuffersortandspillmaptaskjava orgapachehadoopmapredmaptaskmapoutputbufferaccessmaptaskjava orgapachehadoopmapredmaptaskmapoutputbufferspillthreadrunmaptaskjava last kb last kb all reducer start executing earlier reducer used start copying data even map tasks running i see info streamingstreamjob map reduce info streamingstreamjob map reduce info streamingstreamjob map reduce info streamingstreamjob map reduce info streamingstreamjob map reduce info streamingstreamjob map reduce i newbie hadoop mapreduce really know might causing code fail running successfully earlier please help thank,1 i think running two problems this call p subprocesspopen grep loguserid work expected without shelltrue list arguments passed directly osexecvp requires item single string representing argument you squished two separate arguments together single string words grep interpreting foo log pattern search patternfile list you fix saying p subprocesspopen grep userid log the second issue without shelltrue execvp know mean log passes directly along grep without going shell wildcard expansion mechanism if want use shelltrue instead something like import glob args grep userid argsextendglobglob log p subprocesspopenargs,i trying use grep command python script using subprocess module here i userid foo p subprocesspopen grep loguserid stdoutsubprocesspipe and returns nothing i entirely sure i wrong someone please explain the current method i using works adding shelltrue makes output correct output help pages pointed unsafe i need help trying make work script unsafe,3 i ran code worked fine perhaps yellow image yellow think edit the potential difference i using opencv which version using ok one edit have tried looking yellow values that would give definitive answer values use cvinranges add two lines call cvcvtcolor uchar ptr ucharimghsvimagedata printfh sd vdn ptr ptr ptr for image i got h s v that code worked,hi i trying built simple color identifying program i taken image yellow amp pink convert hsv color space then used threshold identify yellow color region i getting output black image i want yellow region filled color rest black iplimage imgread cvloadimageyellowjpegcvloadimagecolor ifimgread fprintfstderr error reading imagen exit iplimage imghsv cvcreateimagecvgetsizeimgread cvcvtcolorimgread imghsvcvbgrhsv iplimage imgthreshold cvcreateimagecvgetsizeimgread cvinrangesimghsv cvscalar cvscalar imgthreshold cvshowimageimageimgthreshold cvwaitkey in code i calculated hsv value yellow in gimp hsv value yellow color in cvinranges except hue value i sure specify values cvscalar what values i need put am i missing anything,1 here variation unutbu answer usrbinenv python import sys contextlib import closing import lxmlhtml html pip install lxml lxmlhtmlclean import cleaner seleniumwebdriver import firefox pip install selenium werkzeugcontribcache import filesystemcache pip install werkzeug cache filesystemcache cachedir threshold url sysargv lensysargv else httpstackoverflowcomq get page pagesource cachegeturl pagesource none use firefox get page javascript generated content closingfirefox browser browsergeturl pagesource browserpagesource cacheseturl pagesource timeout week seconds extract text root htmldocumentfromstringpagesource remove flash images scriptstyle etc cleanerkilltags noscript styletrueroot lxml print roottextcontent extract text i separated task two get page including elements generated javascript extract text the code connected cache you fetch pages one process extract text another process defer later using different algorithm,i googling day finding answer apologies advance already answered i trying get visible text large number different websites the reason i want process text eventually categorize websites after couple days research i decided selenium best chance i found way grab text selenium unfortunately text grabbed multiple times selenium import webdriver import codecs filen codecsopen outoputtxt encoding utf mode w driver webdriverfirefox drivergethttpwwwexamplepagecom allelements driverfindelementsbyxpath ferdigtxt allelements itext ferdigtxt pass else ferdigtxtappenditext filenwritelinesitext filenclose driverquit the condition inside loop attempt eliminating problem fetching text multiple times however work planned webpages also makes script a lot slower i guessing reason problem asking inner text element i also get inner text elements nested inside element question is way around is sort master element i grab inner text or completely different way would enable reach goal any help would greatly appreciated i ideas one edit reason i used selenium mechanize beautiful soup i wanted javascript tendered text,2 i think problem due scaling hsv data fit bits normally i sure noticed using gimp hsv scales follows h s v but opencv remaps values follows h h values stored bits s v this calculated hue value instead so filter colors except yellow cvinranges call would look something like cvinrangesimghsv cvscalar cvscalar imgthreshold the fourth channel unused hsv this call would give counts noise color detector threshold dimension as mentioned ssteve threshold work may need expand threshold boundaries capture yellowish color image hope helps,hi i trying built simple color identifying program i taken image yellow amp pink convert hsv color space then used threshold identify yellow color region i getting output black image i want yellow region filled color rest black iplimage imgread cvloadimageyellowjpegcvloadimagecolor ifimgread fprintfstderr error reading imagen exit iplimage imghsv cvcreateimagecvgetsizeimgread cvcvtcolorimgread imghsvcvbgrhsv iplimage imgthreshold cvcreateimagecvgetsizeimgread cvinrangesimghsv cvscalar cvscalar imgthreshold cvshowimageimageimgthreshold cvwaitkey in code i calculated hsv value yellow in gimp hsv value yellow color in cvinranges except hue value i sure specify values cvscalar what values i need put am i missing anything,2 arch python will run binary bit mode if installed python via macports check actually built bit bit universal binary file python this output mine î» file usrlocalbinpython usrlocalbinpython macho universal binary architectures usrlocalbinpython architecture macho executable usrlocalbinpython architecture x macho bit executable x if see version bit build though run arch python fine since get error binary run bit mode also rely platformarchitecture tell bit universal binaries report bit mode even bit it better rely sysmaxsize changes depending bit bit mode python bit mode notice sysmaxsize î» arch python python default oct gcc based apple inc build llvm build darwin type help copyright credits license information import sys sysmaxsize false sysmaxsize import platform platformarchitecture bit python bit mode î» python python default oct gcc based apple inc build llvm build darwin type help copyright credits license information import sys sysmaxsize sysmaxsize true import platform platformarchitecture bit,i trouble triggering bit python macports python calvinsmacbook ttys tue nov calvin arch arch x python python default oct gcc compatible apple clang tagsappleclang darwin type help copyright credits license information import platform platformarchitecture bit exit calvinsmacbook ttys tue nov calvin arch arch python python default oct gcc compatible apple clang tagsappleclang darwin type help copyright credits license information import platform platformarchitecture bit how i go triggering use bit python,2 use init instead new initialize classes in cases overriding new necessary it called init object creation see also pythons use new init,what wrong following code python class testfailedbaseexception def newself selfmessage def strself return selfmessage try raise testfailed oops except testfailed x print x when i run i get traceback recent call last file xpy line module raise testfailed oops typeerror exceptions must oldstyle classes derived baseexception nonetype but looks testfailed derive baseexception,2 new staticmethod needs return instance instead use init method class testfailedexception def initself selfmessage def strself return selfmessage try raise testfailed oops except testfailed x print x oops,what wrong following code python class testfailedbaseexception def newself selfmessage def strself return selfmessage try raise testfailed oops except testfailed x print x when i run i get traceback recent call last file xpy line module raise testfailed oops typeerror exceptions must oldstyle classes derived baseexception nonetype but looks testfailed derive baseexception,3 the new implementation return instance class currently returning none default however looks like using init rather new,what wrong following code python class testfailedbaseexception def newself selfmessage def strself return selfmessage try raise testfailed oops except testfailed x print x when i run i get traceback recent call last file xpy line module raise testfailed oops typeerror exceptions must oldstyle classes derived baseexception nonetype but looks testfailed derive baseexception,1 once found function faster using timeit module also get precise details differences using profile module,i written functions exact thing i know one faster better how i compare functions see one better terms performance everything,1 you need install enchant library first on download page pyenchant indicates prerequisite building source there prebuild binaries listed python well i installed enchant via homebrew os x pyenchant installed without problem if decide use homebrew installing enchant note i brew install pkgconfig separate recipe seem install dependancy fails result,i trying install python bindings enchant library pyenchant according readme simple running python setuppy install but i try i get error oserror errno no file directory toolspyenchantbdistosxsourcesbuildlib can someone tell i tried google luck ps i question serverfault i thought appropriate place little help i trying,3 others shown fix implementation i feel important point behavior implementing already standard behavior exceptions python code completely unnecessary just derive exception appropriate base class runtime exceptions put pass body class testfailedexception pass,what wrong following code python class testfailedbaseexception def newself selfmessage def strself return selfmessage try raise testfailed oops except testfailed x print x when i run i get traceback recent call last file xpy line module raise testfailed oops typeerror exceptions must oldstyle classes derived baseexception nonetype but looks testfailed derive baseexception,3 your data format one easily parsed csv you could however split lines openfilename r f keysnextfsplit datarowsplit row f columnsmaplistzipdata resultdictzipkeyscolumns,what elegant way use csvdictreader create dictionary memory headers csv file keys columns lists domething like so csv file follows key key key the resulting dictionary key key key,1 you try list comprehension ideone result v k v diteritems kstartswith ev or approach using generator expression ideone result nextv k v diteritems kstartswith ev note require linear scan items dictionary unlike ordinary keylookup runs constant time average assuming good hash function the generator expression however stop soon finds key the list comprehension always scan entire dicitonary,i dictionary key called ev number i know ahead time there one type key dictionary key starts ev what cleanest way access key without knowing,2 based update question trying really feasible if want field able encryptdecrypt automatically information required must stored corresponding database field see danielroseman answer that essentially negates usefulness encryption database ever compromised though i guess intruder would still figure piece together properly there absolutely way store requisite information across multiple database fields yet one field pulls info together decrypt fields isolated entities they pretty obviously allowed information fields model used places fields might exist model your best bet store encrypted value info needed decrypt standard django model fields one model method decrypts value another encrypts value,updated i following custom field class class binarymodelsfield metaclass modelssubfieldbase def getprepvalueself value return encryptaeskey ivrandom strvalue def topythonself value return value def dbtypeself connection return varbinary this model i class receivedmodelsmodel user modelsforeignkeyuser uniquefalse editablefalse address binaryblanktrue aeskey binaryblanktrue iv binaryblanktrue i trying encryptdecrypt data using custom field class when form submitted user getprepvalue method needs encrypt data in django admin interface i need topython method decrypt data fields change view i thinking making following additions topython method def topythonself value return decryptaesaeskey iv value the problem i topython method loops field value individually whereas i need values field including fields aeskey iv decrypt data i know get aeskey iv fields hence question marks hope clears things,1 python equivalent module though twisted uses many basic concepts async apis callbackbased the python multiprocessing module actually uses subprocesses rather threads particularly equivalent either the best approach would probably one similar taken macruby create wrappers gcd apis use unlike python course macruby also designed gil global interpreter lock reduce effectiveness multithreading python various interpret threads hit gil different times not much redesign language i afraid,is way parallel processing python using concepts similar apple grand central dispatch grand central dispatch looks outset like nice way handling parallel processing if python mostly equivalent module fundamental concepts behind grand central dispatch could usefully implemented python i know much grand central dispatch hence question i would love know whether grand central dispatch uses paradigms yet available python andor could implemented python,1 have read docs it sounds like based saying i seem find additional information in case check links see still questions conceptually cross group transaction pretty similar typical gae transaction slower available hrd note general gae transactions normal xg different isolation characteristics may used coming sql database the second link discusses immediately xg section here excerpt first link showing simple using xg googleappengineext import db xgon dbcreatetransactionoptionsxgtrue def mytxn x mymodela xput mymodela yput dbrunintransactionoptionsxgon mytxn quick example slightly detail,the recent release gae states following changes datastore cross group xg transactions for need transactional writes entities multiple entity groups everyone right xg transactions thing this feature uses two phase commit make cross group writes atomic like single group writes i think i could use change within code project i created ago i would like information regarding update app engine i seem find additional information so how coding transactions changed regards update in layman terms i implement crossgroup transaction still limitations data store transactions i need aware i know rather vague question my problem sounds useful i sure correctly effectively use change,2 i highly suggest using google protocol buffers implemented python protobuf handle serialization ends line it python bindings allow easily use existing python program using example code would create proto file like message somecoolmessage required string key required double value then generating use like randkey randomchoice nodelistkeys data somecoolmessage datakey randkey datavalue nodelistrandkey mysocketsendto dataserializetostring address,to preface i new python days i experienced software eng undergrad i would like send data machines running python scripts the idea i order simplify things concatenate data strings amp ints string parsing clientside the udp packets send beautifully simple strings i try send useful data python always complains data i send specifically python let concatenate tuples in order parse data client i need seperate data dash character nodelist type dictionary key string value double randkey randomchoice nodelistkeys data strrandkey strnodelistrandkey mysocketsendto data address the code produces following error typeerror coercing unicode need string buffer tuple found i understand thinks tuple i trying concatenate so question i correct keep python happy someone suggest i better way sending data thank advance,1 i probably use json module serialize data,to preface i new python days i experienced software eng undergrad i would like send data machines running python scripts the idea i order simplify things concatenate data strings amp ints string parsing clientside the udp packets send beautifully simple strings i try send useful data python always complains data i send specifically python let concatenate tuples in order parse data client i need seperate data dash character nodelist type dictionary key string value double randkey randomchoice nodelistkeys data strrandkey strnodelistrandkey mysocketsendto data address the code produces following error typeerror coercing unicode need string buffer tuple found i understand thinks tuple i trying concatenate so question i correct keep python happy someone suggest i better way sending data thank advance,1 most likely comment column type unicode instead string,i using pyramid sqlalchemy following simplified code u uuc m mcomment u muserid sessionadd sessioncommit gives unicodeencodeerror latin codec encode character u uc position ordinal range i need fix edit comment mediumtext column mysql type,2 i error installing openstack ubuntu running locate showed i version locate libsslso libxlinuxgnulibsslso usrlibxlinuxgnulibsslso i fixed using sudo aptget install libssl,so yesterday i fresh install ubuntu keeping home directory virtualenvs i installed virtual env able logon previous virtual env i try run python managepy runserver virtualenv i get following error error loading shared libraries libsslso cannot open shared object file no file directory any idea fix i tried installing ssl package python fix,3 the rawinput executes keeps value if enter feed first time loop forever,i problems loop i running eclipse i typed source rawinputmom im hungry feed meeeee feed printthats gross the result i type wrong answer responds going thats gross thats gross,2 what really want rawinputmom im hungry feed meeeee feed printthats gross rawinputmom im hungry feed meeeee something may alter without nd line loop nothing alters variable hence still feed hence condition true hence content loop repeats,i problems loop i running eclipse i typed source rawinputmom im hungry feed meeeee feed printthats gross the result i type wrong answer responds going thats gross thats gross,3 rawinputmom im hungry feed meeeee feed printthats gross rawinputmom im hungry feed meeeee,i problems loop i running eclipse i typed source rawinputmom im hungry feed meeeee feed printthats gross the result i type wrong answer responds going thats gross thats gross,1 check see database tables encoded encoding unicode also want comments readable phpmyadmin whatever using connect db append charsetutfampuseunicode connection string application configuration file mysqluserpasslocalhostdbnamecharsetutfampuseunicode,i using pyramid sqlalchemy following simplified code u uuc m mcomment u muserid sessionadd sessioncommit gives unicodeencodeerror latin codec encode character u uc position ordinal range i need fix edit comment mediumtext column mysql type,2 use unichr unichri from documentation unichri return unicode string one character whose unicode code integer for example unichr returns string u,i want print unicode characters u u u u this work range sunicode u stri print,3 unichr function looking takes number returns unicode character point range print unichri,i want print unicode characters u u u u this work range sunicode u stri print,1 try following range print unichri,i want print unicode characters u u u u this work range sunicode u stri print,2 my guess set autonowadd autoadd modelspy field thus part form first place exclude try removing exclude statement,i following stack trace trying access django admin default app does anyone know fix i defined field datecreated clearly modelspy catalog app i sure else i need define improperlyconfigured admin productadminexclude refers field datecreated missing form request method get request url httplocalhostadmin django version exception type improperlyconfigured exception value productadminexclude refers field datecreated missing form exception location librarypythonsitepackagesdjangocontribadminvalidationpy checkformfield line python executable usrbinpython python version python path userschristopherfarmdesktopecomstore librarypythonsitepackagespythondateutilpyegg librarypythonsitepackagesmysqlpythonpymacosxuniversalegg librarypythonsitepackagesdjangodblogpyegg systemlibraryframeworkspythonframeworkversionslibpythonzip systemlibraryframeworkspythonframeworkversionslibpython systemlibraryframeworkspythonframeworkversionslibpythonplatdarwin systemlibraryframeworkspythonframeworkversionslibpythonplatmac systemlibraryframeworkspythonframeworkversionslibpythonplatmaclibscriptpackages systemlibraryframeworkspythonframeworkversionsextraslibpython systemlibraryframeworkspythonframeworkversionslibpythonlibtk systemlibraryframeworkspythonframeworkversionslibpythonlibold systemlibraryframeworkspythonframeworkversionslibpythonlibdynload librarypythonsitepackages systemlibraryframeworkspythonframeworkversionsextraslibpythonpyobjc systemlibraryframeworkspythonframeworkversionsextraslibpythonwxmacunicode server time mon oct,3 you want use unichr builtin function range print unichri note python chr suffice,i want print unicode characters u u u u this work range sunicode u stri print,3 just look difference red curve points bigger difference red curve dashed red curve remove diffnpabspointsredcurve index diffdashedcurveredcurve filteredpointsindex but please take comment nicklh serious your data looks pretty good without filtering outlieres big error affect fit much,i need compare theoretical data real data python the theoretical data comes resolving equation to improve comparative i would like remove data points fall far theoretical curve i mean i want remove points red dashed lines figure made matplotlib both theoretical curves data points arrays different length i try remove points roughlyeye way example first upper point detected using datadataredshiftampdatadmodulus recarray dtype snname s redshift f dmodulus f dmoduluserror f but i would like use less roughlyeye way so anyone help finding easy way removing problematic points thank,1 i think people would see code recommend using composition rather inheritance subject would define foo method dispatched correct class based boolean value alternatively could use factory function create either foo bar needed def subjectselector factory function chooses foo bar return foo selector else bar if needed make foo bar inherit common class factory function always returns instance subclass common class,i two classes method foo foo type foo object foo lambda foo method bar type bar object foo lambda bar method and i class i need subclassed one classes according parameter my solution class subjectobject def newcls key base foo key else bar name clsname basename dict dictclsdictitems basedictitems bases base cls typename bases dict return basenewt def barself return subject method testing printsubjecttruefoo subjecttruebar printsubjectfalsefoo subjectfalsebar output foo method subject method bar method subject method is solution safe enough or i need something know is pythonic way kind unregular stuff,1 try changing rawcommand date datetimestring to rawcommand date datetimestring and im positive i dont think rawcommandformatpatternapattern necessary datetimestring rawinputenter date time format command date datetimestring stdin stdout stderr sshexeccommandcommand dateresult stdoutreadsplitlines,okay someone tell i wrong simple request change time i win machine trying change time linux box i login search logs run commands course adjusting code but simple command changing datetime i must overlooking something datetimestring rawinputenter date time format ssh paramikosshclient sshsetmissinghostkeypolicyparamikoautoaddpolicy sshconnectipaddress username root password apath apattern datetimestring rawcommand date datetimestring command rawcommandformatpatternapattern stdin stdout stderr sshexeccommandcommand dateresult stdoutreadsplitlines,1 if avoid metaclasses magic code readable thus pythonic go approaches suggested chris raymond ie use composition class subjectobject def initself key selffoo foo key else barfoo def barself return subject method use factory function def subjectkey class subjectfoo key else bar def barself return subject method return subject,i two classes method foo foo type foo object foo lambda foo method bar type bar object foo lambda bar method and i class i need subclassed one classes according parameter my solution class subjectobject def newcls key base foo key else bar name clsname basename dict dictclsdictitems basedictitems bases base cls typename bases dict return basenewt def barself return subject method testing printsubjecttruefoo subjecttruebar printsubjectfalsefoo subjectfalsebar output foo method subject method bar method subject method is solution safe enough or i need something know is pythonic way kind unregular stuff,1 you talking xmlparseparsefile method right unfortunately value hardcoded bufsize pyexpatc,i parsing xml using python expat calling parser xmlparsersexpatparsercreate setting relevant callbacks methods it seems expat calls readnbytes return new data nbytes always i quite lot xml process suspect small reads making overall process rather slow as point reference i seeing throughput around mbs intel xeon x ghz running windows i tried setting parserbuffertext true parserbuffersize expat still calling read method argument is possible increase,1 make names set use inoperator fast o lookup you use regex parse possible names sentence import findnames recompiler azwsazw def isnameintexttext names possiblename setfindnamesfindalltext possiblename names return possiblename return false names set james john robert david paul isnameintext i saw james today names false isnameintext i saw james john today names james john isnameintext i met paul names paul,example names james john robert david paul list k items text i saw james today text i saw james john today text i met paul isnameintexttextnames returns false james list isnameintexttextnames returns james john isnameintexttextnames return paul isnameintext searches name list text the easy way check name list using operator list items efficient i split text words check words list going work one word matching line number fail case,1 you may use python set order get good performance using operator,example names james john robert david paul list k items text i saw james today text i saw james john today text i met paul isnameintexttextnames returns false james list isnameintexttextnames returns james john isnameintexttextnames return paul isnameintext searches name list text the easy way check name list using operator list items efficient i split text words check words list going work one word matching line number fail case,1 if mechanism pulling names phrases need worry partial matches full name always string use set rather list your code exactly addition line names setnames the operation function much faster,example names james john robert david paul list k items text i saw james today text i saw james john today text i met paul isnameintexttextnames returns false james list isnameintexttextnames returns james john isnameintexttextnames return paul isnameintext searches name list text the easy way check name list using operator list items efficient i split text words check words list going work one word matching line number fail case,1 build regular expression alternatives this way worry somehow pulling names phrases beforehand import namesre recompiler b r bb joinreescapename name names r b print namesresearch i saw james today,example names james john robert david paul list k items text i saw james today text i saw james john today text i met paul isnameintexttextnames returns false james list isnameintexttextnames returns james john isnameintexttextnames return paul isnameintext searches name list text the easy way check name list using operator list items efficient i split text words check words list going work one word matching line number fail case,1 you validate user input especially might passed unescaped shell usrbinenv python datetime import datetime import paramiko read new date stdin datetimeformat mdy hm newdatestring rawinputenter date time format validate newdate string datetimeformat newdate datetimestrptimenewdatestring datetimeformat print date change set date command date newdatestrftimedatetimeformat ssh paramikosshclient sshsetmissinghostkeypolicyparamikoautoaddpolicy sshconnectlocalhost use ssh keys authenticate run stdin stdout stderr sshexeccommandcommand stdinclose get output command print print stdout r stdoutread print print stderr r stderrread output echo python setdatepy enter date time format stdout tue jan est n stderr,okay someone tell i wrong simple request change time i win machine trying change time linux box i login search logs run commands course adjusting code but simple command changing datetime i must overlooking something datetimestring rawinputenter date time format ssh paramikosshclient sshsetmissinghostkeypolicyparamikoautoaddpolicy sshconnectipaddress username root password apath apattern datetimestring rawcommand date datetimestring command rawcommandformatpatternapattern stdin stdout stderr sshexeccommandcommand dateresult stdoutreadsplitlines,1 the problem advanced indexing creates copy array copy modified this contrast basic indexing results view original data when directly assigning advanced slice aindrow copy created using aindrow aindrow part creates copy part indexes temporary copy the copy indeed changed since hold references see changes immediately garbage collected this analogous slicing standard python lists also creates copies range a solution problem simple case obviously aindrow more complex cases could also rewritten similar way,import numpy np npzeros indrow nparray aindrow expected i want assign value subarray aindrow expect able follows aindrow however leaves unchanged why i expect,3 python dictionaries already unique keys are possibly interested unique values setdvalues if check length set see smaller number values this works sets eliminate duplicates input result smaller input means duplicates found eliminated,i need write function returns true dictionary duplicates so pretty much anything appears dictionary return true here i i far sure b c def hasduplicatesd seen set x x seen return true seenaddx return false print hasduplicatesd,1 def hasduplicatesd return false dictionaries contain duplicate keys ever your function btw equivalent definition correct tad long if want find duplicate values lensetdvalues lend assuming values hashable,i need write function returns true dictionary duplicates so pretty much anything appears dictionary return true here i i far sure b c def hasduplicatesd seen set x x seen return true seenaddx return false print hasduplicatesd,3 in code b c set dictionary neither dictionary keys sets contain duplicates if looking duplicate values check set values size dictionary def hasduplicatevaluesd return lensetdvalues lend,i need write function returns true dictionary duplicates so pretty much anything appears dictionary return true here i i far sure b c def hasduplicatesd seen set x x seen return true seenaddx return false print hasduplicatesd,2 if looking find duplication values dictionary def hasduplicatesd return lend lensetdvalues print hasduplicates b c outputs true,i need write function returns true dictionary duplicates so pretty much anything appears dictionary return true here i i far sure b c def hasduplicatesd seen set x x seen return true seenaddx return false print hasduplicatesd,3 this complete solution known work django courtesy zach smith ben class entrymodelsmodel objects entrymanager forget ispublic modelsbooleanfield owner modelsforeignkeyuser class entrymanagermodelsmanager use class define methods entryobjects def getquerysetself return entryquerysetselfmodel def getattrself name args namestartswith raise attributeerror return getattrselfgetqueryset name args def getstatsself a sample custom manager method return publiccount selfgetquerysetpubliccount class entryquerysetmodelsqueryqueryset use class define methods queryset def publicself return selffilterispublictrue def byself owner return selffilterownerowner stats entryobjectsgetstats myentries entryobjectsbyrequestuserpublic note getqueryset method deprecated django getqueryset used instead,in django i model class eg djangodb import models class transactionmodelsmodel i want add methods model store eg reasonably complex filters i add custom model manager eg class transactionmanagermodelsmanager def reasonablycomplexfilterself return selfgetquerysetfilter class transactionmodelsmodel objects transactionmanager and i transactionobjectsreasonablycomplexfilter is way i add custom method chained end query set model ie add custom method way i transactionobjectsfilterreasonablycomplexfilter,3 i think shutilcopyfile needs complete file name destination file directory so shutilcopyfileoldfile ospathjoindeleted newpagename trick,i need create subdirectory yet exist copy files however whenever i try i get permission denied error i tried chmod well statsiwrite i tried ossystem attrib r nothing works can anyone help work one i know similar question site says use chmod working here code beginpath cusersfoo fullpath ospathjoinbeginpath foldername print fullpath fullpath fullpathreplace n create folder hold deleted files deleted ospathjoinfullpath deleted print deleted ospathexistsdeleted osmakedirsdeleted oschmoddeleted statsiwrite print created processing oldfile ospathjoinfullpath newpagename shutilcopyfileoldfile deleted,1 how getting start page httpwwwscipyorgnumpyformatlabusers also brief description supposed would good,i trying convert code matlab python i unfamiliar considerable amount matlab syntax functionality i managed conversion using pil numpy python package i hoping someone would able explain going elements code clear allclose allclc set gray scale color images will need memory grayscale the physical mask placed close sensor harmonics therefore angular samples light field nangles cangles nangles the fundamental frequency cosine mask pixels fy fx cosine frequency pixels calibration image fx floorfx fy floorfy phaseshift due mask inplane translation wrt sensor phi phi read d image disp reading input image i doubleimread inputconespng ifgrayscale take green channel i i end make image odd size i iendend find size image mnch sizei compute spectral tile centers peak strengths phase nangles j nangles centyij icanglesfy centxij n jcanglesfx matij expsqrtphipiicangles phipijcangles end end mat onesnanglesnangles cannot negative values mask so strenght dc component times harmonics matcanglescangles matcanglescangles beginning d light field computation color channel ch ch disp dispsprintf processing channel ch find fft image disp computing fft d image f fftshiftfftich if want visaulize fft input d image figure paper uncomment next lines figureimshowlogabsfcolormap gray title d fft captured image figure paper note spectral replicas rearrange tiles d fft d planes obtain fft d lightfield disp rearranging d fft d nangles j nangles fftlfij f centyijfycentyijfy centxijfxcentxijfxmatij end end clear f k sqrt nangles j nangles shift phipiicangles phipijcangles fftlfij fftlfijexpkshift end end disp computing inverse d fft lf ifftnifftshiftfftlf compute lightfield d inverse fft clear fftlf ifch lfr lf elseifch lfg lf elseifch lfb lf end clear lf end clear i now d light fiel disp light field computed done disp digital refocusing code take d slice d light field for refocusing need fft light field light field disp synthesizing refocused images taking d slice d light field ifgrayscale fftlfr fftshiftfftnlfr clear lfr else fftlfr fftshiftfftnlfr clear lfr fftlfg fftshiftfftnlfg clear lfg fftlfb fftshiftfftnlfb clear lfb end height width refocused image h sizefftlfr w sizefftlfr count theta count count disp dispsprintf calculating new refocused image theta theta ifgrayscale refocusedimage refocusdfftlfrthetatheta else refocusedimage zeroshw refocusedimage refocusdfftlfrthetatheta refocusedimage refocusdfftlfgthetatheta refocusedimage refocusdfftlfbthetatheta end str sprintf refocusedimagedpng count scale refocusedimage refocusedimage refocusedimage minrefocusedimage refocusedimage refocusedimagemaxrefocusedimage write png image clear tt ii ch ttii fliplrrefocusedimageii end imwriteuintttstr dispsprintf refocused image written str end here refocusd function function iout refocusdfftlftheta mnpq sizefftlf theta theta theta theta ctem floorsizefftlf find coordinates d slice xxyy meshgridnm cc xx ctemsizefftlf cc thetacc ctem dd yy ctemsizefftlf dd thetadd ctem resample d light field along d slice v interpnfftlfyyxxddcc cubic set nan values zero idx findisnanv dispsprintf number nans sampling sizeidx visnanv take inverse d fft get image iout realifftifftshiftv if anyone could help would greatly appreciated thanks advance apologies here brief description code the code reads image light field prior knowledge plenoptic mask store relevant nangles fundamental frequencies mask phase shift used find multiple spectral replicas image once image read green channel extracted perform fast fourier transform image start taking slices image matrix represent one spectral replicas we take inverse fourier transform spectral replicas produce light field the refocusd function takes dimensional slice data recreate refocused image the things i struggling specifically fftlfij f centyijfycentyijfy centxijfxcentxijfxmatij we taking slice matrix f data fftlf what ij mean is multidimensional array size function return mnpq sizefftlf just brief explanation translates python would great help thanks everyone far,2 i sure exactly going podiumbid objects error valueerror invalid literal int base simply means python know convert empty string number int raise exception if intend empty string equal something like intmystring use input int mystring evaluates false empty strings,i trying create somewhat python the price right my problem i trying convert entry number see code podiumbid entrypoint podiumbid entrypoint podiumbid entrypoint podiumbid entrypoint bid intpodiumbidgettext bid intpodiumbidgettext bid intpodiumbidgettext bid intpodiumbidgettext the lines bid intpodiumbidgettext etc bid give error traceback recent call last file pyshell line module contestantsrow file pyshell line contestantsrow bid intpodiumbidgettext valueerror invalid literal int base i also tried using eval similar things i still get errors,2 if point entry classes could ddd int method entry class that teach class convertible integer in case python graphics library inspect objects using varspodiumbid see attributes directly accessible something like podiumbidwidth podiumbidpointx,i trying create somewhat python the price right my problem i trying convert entry number see code podiumbid entrypoint podiumbid entrypoint podiumbid entrypoint podiumbid entrypoint bid intpodiumbidgettext bid intpodiumbidgettext bid intpodiumbidgettext bid intpodiumbidgettext the lines bid intpodiumbidgettext etc bid give error traceback recent call last file pyshell line module contestantsrow file pyshell line contestantsrow bid intpodiumbidgettext valueerror invalid literal int base i also tried using eval similar things i still get errors,2 using django return attachment serve purpose here example returning csv file user in example top page httpsdocsdjangoprojectcomendevhowtooutputtingcsvfromolddocs you see setting response httpresponsemimetype textcsv response contentdisposition attachment filenamesomefilenamecsv specify file type set attachment if want implement push button i would actually separate view return file response then specify template call view button pushed make sure link view urlspy file it would look something like li class button href url appviewsfunction download li i actually similar issue long ago couple similar questions look question i know lame link question i think may help let know questions,i making website using django every time user clicks download button i want download dialog box appear browser i using following code file download urlliburlretrievefilename in case although file getting downloaded process happens background moreover file gets downloaded django project staged hence control save file how make download dialog box appear soon user clicks download button rather download process getting started background stealthily,1 the best way check problem lies putting import sys print n joinsortedsyspath entry program see pythonpath properly set expect see importing another project pydev details structure supposed look like worst case already configured could pydev cache bug restarting eclipse would fix case otherwise probably misconfiguration,i probably something really dumb driving crazy i two pydev projects eclipse one project analysis depends pycommon i sure i look project references analysis pycommon checked automatic importcode completion works i reference elements pycommon analysis i trying writerun module analysis the module fhbanalysislogparserspy i trying import element orderstatus fhbpycommontypesorderstatus pycommon project so import statement fhbpycommontypesorderstatus import orderstatus pydev clearly knows import statement written automatically pydev quickfix correction nonetheless i try run main function logparserspy i get traceback recent call last file workspaceanalysissrcfhbanalysislogparserspy line fhbpycommontypesordertype import ordertype importerror no module named pycommontypesorderstatus all packages proper source folder src project also even though analysis absolutely set reference pycommon i look pydevpythonpath analysis properties analysis src folder appears source folder tab project i see i click add source folder,2 in latest pydev work exactly want already tested pydev actually around time already,happy friday — does anyone know eclipse notion smart quotes like textmate the way works select words quote simply hitting key i newbie gentle fwiw i using pydev eclipse thanks rephrase what i looking given i word phrase selected screen i would like simply hit key entire word phrase enclosed quotes the would apply various keys — like so say i following code akeyword now python keyword quotes i able double click select keyword simply type viola whole word quoted right happens keyword replaced single quote sigh thanks,1 since write rate number entities low approaches work fine the best one depends access if need update multiple entities transaction use entity groups eg ancestors if need natural ordering candidates election list property provides otherwise reference candidate election natural choice or could use ndb embed candidate entities election entity,i working gae python app running elections i election entity election each election around candidates i candidate entity candidate i considering three different options modeling entity relationship having election ancestor candidate adding reference property candidate refers election adding list property election contains list candidate keys since number candidates relatively small seems could work i currently first option since i using highrep data store i want strong consistency for election app pros cons three options,1 using fileinput convenient way alter files inplace import fileinput import import sys line fileinputinputfilenameinplacetrue sysstdoutwriteresubr ddd r line resub used replace hyphens commas the first regex pattern matches dates leaving hyphens lines untouched the second argument r tells resub replace matched text first matched group followed comma second matched group followed another comma followed third matched group,i trying change date format text file commadelimited year month day currently yyyymmdd format i trying replace hyphens commas without affecting hyphenated text file trainkbwi fograinsnowthunderstormkbwi i dont want remove hyphens weather events a friend told use regex expression refindall ddd it find patterns dates formatted hyphens i clue replace hyphens commas lines textfile match i thinking creating new text file edited data i use another application any help would appreciated,1 the square brackets necessary around entries try using resub group numbers replace operation resubr ddd r,i trying change date format text file commadelimited year month day currently yyyymmdd format i trying replace hyphens commas without affecting hyphenated text file trainkbwi fograinsnowthunderstormkbwi i dont want remove hyphens weather events a friend told use regex expression refindall ddd it find patterns dates formatted hyphens i clue replace hyphens commas lines textfile match i thinking creating new text file edited data i use another application any help would appreciated,1 without using regexp simple openinputfile r openoutputfile w line line linesplit line linereplace outwrite joinline inclose outclose,i trying change date format text file commadelimited year month day currently yyyymmdd format i trying replace hyphens commas without affecting hyphenated text file trainkbwi fograinsnowthunderstormkbwi i dont want remove hyphens weather events a friend told use regex expression refindall ddd it find patterns dates formatted hyphens i clue replace hyphens commas lines textfile match i thinking creating new text file edited data i use another application any help would appreciated,1 if care order def removeduplicatesl return listsetl a set guaranteed duplicates,pretty much i need write program check list duplicates removes returns new list items werent duplicatedremoved this i honest i know def removeduplicates b c c tappendtremove return,3 it oneliner listsetsourcelist trick a set something possibly duplicates,pretty much i need write program check list duplicates removes returns new list items werent duplicatedremoved this i honest i know def removeduplicates b c c tappendtremove return,3 fwiw new v python way removing duplicates iterable keeping original order collections import ordereddict listordereddictfromkeys abracadabra b r c,pretty much i need write program check list duplicates removes returns new list items werent duplicatedremoved this i honest i know def removeduplicates b c c tappendtremove return,3 try using sets import sets setsset b c setsset b c print print,pretty much i need write program check list duplicates removes returns new list items werent duplicatedremoved this i honest i know def removeduplicates b c c tappendtremove return,3 try reversed builtin c reversedstring print c the reversed call make iterator rather copying entire string pep details motivation reversed advantages approaches,what best way loop python string backwards the following seems little awkward need offset string trick treat rangelenstring print stringi the following seems succinct actually generate reversed string minor performance penalty string trick treat c string print c,3 string trick treat c string print c i would use it probably quite fast although may slightly better way i doubt edit actually second test using program i hacked together reversed probably way go results sample using loop sample using reversed,what best way loop python string backwards the following seems little awkward need offset string trick treat rangelenstring print stringi the following seems succinct actually generate reversed string minor performance penalty string trick treat c string print c,1 yes second syntax shortcut creates intermediate string associated performance penalty the first version better written index char enumeratereverseds print pos index char which easy comprehend neither reversed enumerate need make copy string also careful using string variable name also name module standard library,what best way loop python string backwards the following seems little awkward need offset string trick treat rangelenstring print stringi the following seems succinct actually generate reversed string minor performance penalty string trick treat c string print c,1 less code usually faster python luckily guess python mtimeit ss x x pass loops best msec per loop python mtimeit ss x x reverseds pass loops best msec per loop python mtimeit ss x xrangelens si loops best msec per loop so shorter code bit faster comes memory overhead,what best way loop python string backwards the following seems little awkward need offset string trick treat rangelenstring print stringi the following seems succinct actually generate reversed string minor performance penalty string trick treat c string print c,2 reversed takes iterable returns iterator moves backwards string fine creates new reversed string instead if want iterate probably better c reversedstring print c if want use reversed string afterwards creating better,what best way loop python string backwards the following seems little awkward need offset string trick treat rangelenstring print stringi the following seems succinct actually generate reversed string minor performance penalty string trick treat c string print c,1 string trick treat c reversedstring print c will i think want it uses iterator this work anything reveresed len getitem implemented getitem would take int arguments starting,what best way loop python string backwards the following seems little awkward need offset string trick treat rangelenstring print stringi the following seems succinct actually generate reversed string minor performance penalty string trick treat c string print c,1 the django template engine support passing arguments methods like to accomplish thing try using date filter reportdatedatef a edited fixed syntax date string i stupid,i coming rails programming experience i coding app python google app engine django templates i call strftimeim p datetime in mainpy file i import datetime class reportdbmodel date dbdatetimepropertyautonowadd true i pass reports template template i report reports tr td reportdatestrftimeim p td tr endfor i know i datetime object i reportdateday reportdateminute just fine return supposed return when i reportdatestrftimeim p i get error raise templatesyntaxerror could parse remainder tokenupto templatesyntaxerror could parse remainder im p how i get strftime work,3 in python line but define aftertax variable first print aftertax base tax base print nafter taxes price aftertax,i learning python i challenging write little program asks user base price car saves base price variable called base it two variables called tax license percentages so gets base price gets seven percent base price adds base price it license fee etc however i want know runs print nafter taxes price base tax base i save result another variable next line i dont write print nafter taxes license fee price basetax baselicense base rewriting feels redundant like i wasting time calculation something already calculated i want save result first print line variable called aftertax i could write print nafter taxes license fee price aftertax baselicense i want first print command also save result math calculation variable called aftertax i reuse result without retype entire calculation get result below code entirety car salesman calculations program base intrawinputwhat base price car n tax license dealerprep destinationcharge print nafter taxes price base tax base print nafter taxes license fee price basetax baselicense base print nafter taxes license fee dealer prep price basetax baselicense base dealerprep print nafter taxes license fees dealer prep destination charge total price basetax baselicense base dealerprep destinationcharge rawinputnpress enter key close window,2 for python use collectionscounter mostcommon method import collections text abccccabcbb countcollectionscountertext printcountmostcommon c b print joinletterfreq letterfreq countmostcommon cccccbbbbaa for python lower use equivalent counter recipe,like title says i need write function sort list frequency letters normally i would supply code i far i idea get started i sure something simple i know i need sorted decreasing order help appreciated thanks,2 could calculations front recommend giving variables b c etc smarter names i illustrative enough base tax b baselicense c b base c dealerprep e destinationcharge print nafter taxes price base print nafter taxes license fee price c print nafter taxes license fee dealer prep price print nafter taxes license fees dealer prep destination charge total price e rawinputnpress enter key close window,i learning python i challenging write little program asks user base price car saves base price variable called base it two variables called tax license percentages so gets base price gets seven percent base price adds base price it license fee etc however i want know runs print nafter taxes price base tax base i save result another variable next line i dont write print nafter taxes license fee price basetax baselicense base rewriting feels redundant like i wasting time calculation something already calculated i want save result first print line variable called aftertax i could write print nafter taxes license fee price aftertax baselicense i want first print command also save result math calculation variable called aftertax i reuse result without retype entire calculation get result below code entirety car salesman calculations program base intrawinputwhat base price car n tax license dealerprep destinationcharge print nafter taxes price base tax base print nafter taxes license fee price basetax baselicense base print nafter taxes license fee dealer prep price basetax baselicense base dealerprep print nafter taxes license fees dealer prep destination charge total price basetax baselicense base dealerprep destinationcharge rawinputnpress enter key close window,1 python higher use counter httpdocspythonorgdevlibrarycollectionshtmlcollectionscounter mywords red blue red green blue blue cnt countermywords cnt counter blue red green per word frequency count using python need letters instead words go like mywords red blue red green blue blue myletterslistjoinmywords myletters r e b l u e r e g r e e n b l u e b l u e countermyletters,like title says i need write function sort list frequency letters normally i would supply code i far i idea get started i sure something simple i know i need sorted decreasing order help appreciated thanks,3 using dictionary key item original array value id related key course could access sorted order like key id keys akeys keyssort k keys print akey,i large array numerical data i need sort insert move values backwards forwards sorted order i previously using simple array now value linked id unique int along ride can i extend array class i need use list tuples what best option,1 you use list sake sorted well list if want associate additional data could either use tuple store data even create custom object stores id additional field you shouldn’t need extend list put object list for example would easily possible lst foobar value lstappend data value lst foobar value data value lstsort keylambda x x lst value data value foobar lstsort keylambda x x lst foobar value data value edit in case using python could also use collectionsordereddict type it extension normal dict maintains order like list,i large array numerical data i need sort insert move values backwards forwards sorted order i previously using simple array now value linked id unique int along ride can i extend array class i need use list tuples what best option,2 lxml bit fussy rdparty libraries uses often needs newer versions supplied apple suggest read follow instructions building lxml source mac os x including building statically linked libs that work i little surprised homebrew already lxml recipe update based limited information comments difficult sure exactly happening i suspect using version python think there number ways install lxml successfully part problem many options rather trying debug setup probably simplest way get working lxml using applesupplied system python sudo staticdepstrue usrbineasyinstall lxml you able use lxmletree way usrbinpython python r jun gcc based apple inc build llvm build darwin type help copyright credits license information lxml import etree etreefile librarypythonsitepackageslxmlpymacosxintelegglxmletreeso i notice though lxml static build process produce working universal build you probably see messages like lxml install ld warning ignoring file privatetmpeasyinstallmjsvlxmlbuildtmplibxmlliblibxslta file built archive architecture linked assuming default architecture machine bits try run bit mode arch usrbinpython python r jun gcc based apple inc build llvm build darwin type help copyright credits license information lxml import etree traceback recent call last file stdin line module importerror dlopenlibrarypythonsitepackageslxmlpymacosxintelegglxmletreeso symbol found htmlparsechunk referenced librarypythonsitepackageslxmlpymacosxintelegglxmletreeso expected flat namespace librarypythonsitepackageslxmlpymacosxintelegglxmletreeso d and error message originally reported so root cause appears static libraries libxml etc lxml builds universal as long need use lxml bit process unlikely uses problem chances python originally using bitonly one consistent messages reported,i struggling able lxml import etree import lxml works fine way the error importerror dlopenlibraryframeworkspythonframeworkversionslibpythonsite packageslxmletreeso symbol found htmlparsechunk referenced libraryframeworkspythonframeworkversionslibpythonsitepackageslxmletreeso expected flat namespace libraryframeworkspythonframeworkversionslibpythonsitepackageslxmletreeso used pip install lxml homebrew reinstall libxml right architecture think anyone ideas fixdiagnose i bit python,3 similar poke answer use array arrays big numpy generally good bet kind numerical data python just make d array looks like sort sort,i large array numerical data i need sort insert move values backwards forwards sorted order i previously using simple array now value linked id unique int along ride can i extend array class i need use list tuples what best option,1 if getting premature end script headers using daemon mode daemon process crashing seg fault similar make sure still loading modpython also try setting wsgiapplicationgroup global work around issues python c extension modules safe sub interpreters see httpcodegooglecompmodwsgiwikiapplicationissues look various reasons crashes listed,i get strange errors trying deploy flask app v i using apache modwsgi suggested docs almost letter what strange requests simply accessing via browser application loads fine often i get resource load errors fetch css image error log shows something like premature end script headers myappwsgi sometimes apache crashes internal server error i trying chase problem could figure cause my wsgi file looks simple myapp import app application any clues start looking,2 the syntax endifequal frequency patientmedsfrequency ifequal frequency tdhellowtd endifequal endfor,frequency patientmedsfrequency frequency tdhellowtd endif endfor getting error templatesyntaxerror statement improperly formatted know please help,1 in python happens default python va jun gcc apple inc build dot darwin type copyright credits license information def fooa b pass helpfoo help function foo module main fooa b in earlier versions python easy way change behavior,give follow python function define def fooa b pass i call helpfoo i get help function foo module main fooa b but i wish get help function foo module main fooa b dear way print pretty,1 yes python includes logging module one handlers supports handlerstimedrotatingfilehandler looking logging easy use example import logging import loggingconfig loggingfileconfig mylogconf logger logginggetlogger root the following config file logging mylogconf loggers keysroot handlers keysdefault formatters keysdefault loggerroot levelinfo handlersdefault qualnameroot note used nonroot loggers propagate note used nonroot loggers channel parent handlerdefault classhandlerstimedrotatingfilehandler levelinfo formatterdefault args trylog formatterdefault formatasctimes pathnameslinenod levelnames messages,i planning add logging mechanism pythonampgeodjango web service is logj look like logging mechanism pythongeodjango i looking logj dailyrollingfileappender equivalent then automatically delete month old log files any guidance appreciated updates i thinking format datetimemslog levelcurrent thread nameclient ip addresslogged usernamesource filesource file line numberlog message,2 there lot features overall i think one major reason people use nosedjanonose allows easily code coverage python managepy test myapp withcoverage coverpackagemyapp,i seeing reading lot people using nose run django tests i able figure added benefits using nose run django tests if someone could fill nose adds django project would helpful i able find good documentarticle outlining points thank,1 try x ord x you need sure convert character integer ord comparing value getch,i need catch tab key python for keys i x selfmyscreengetch x curseskeydown what constant tab key i searched bottom page tried every tab contant i tried is possible thank,2 import numpy np fnx lambda v nprandomrandint v a npzeros c rangeashape ac fnx a at a array,i creating numpy zero array x wish fill column shuffled list numbers however i problem fills first column listpop work plus think nested loops even though tried using row preferences different order any help would greatly appreciated j column matrix preferences randomshufflepreferences number preferences row matrix chosen preferencespop matrixji chosen j,1 since used pop example i thought may want repeat within column numpyrandomshuffle shuffles elements place m nrepeatnarange reshape m array range nrandomshufflemi m array,i creating numpy zero array x wish fill column shuffled list numbers however i problem fills first column listpop work plus think nested loops even though tried using row preferences different order any help would greatly appreciated j column matrix preferences randomshufflepreferences number preferences row matrix chosen preferencespop matrixji chosen j,3 collections import defaultdict target itsy wordsummary defaultdictlist open itsytxt r f lines freadlines idx line enumeratelines words wstriplower w linesplit word words wordsummarywordappendidx uniquewords lenwordsummarykeys targetoccurence lenwordsummarytarget linenums setwordsummarytarget print there unique words uniquewords print there occurences targetoccurence target print found lines target joinstri linenums,i txt file i written code finds unique words number times word appears file i need figure print lines words apear well how i go here sample output analyze file itsybitsyspidertxt concordance file itsybitsyspidertxt itsy total count line the itsy bitsy spider crawled water spout line itsy bitsy spider went spout function get unique words without stop words def openfilesopenfile openfile istrip linelistappendi b ilower thislist bsplit thislist stopwords continue else wordlistappenda print wordlist dictionary used count number times stop countdict def countwordsthislist word thislist depunct wordstrippunctuation depunct countdict countdictdepunct else countdictdepunct,1 here code i wrote several years ago class based presentation jurafskymartin nd edition chapter access book it really good code use numpy absolutely crap arrays indexed instead tweaking formulae indexed well maybe help baumwelch referred forwardbackward code the exampletest data based jason eisner spreadsheet implements hmmrelated algorithms note implemented version model uses absorbing end state states transition probabilities rather assuming preexisting fixed sequence length also available gist prefer hmmpy half testing code based following files usrbinenv python cs lab oct dougal sutherland implements hidden markov model based jurafsky martin presentation turn based work jason eisner we test program data eisner spreadsheets identity lambda x x class hiddenmarkovmodelobject a hidden markov model def initself states transitions emissions vocab states listtuple states eg start hot cold end start state needs first end state last states numbered order transitions probabilities go one state another transitionsfromstatetostate prob emissions probabilities observation given state emissionsstateobservation prob vocab listtuple names observable values order selfstates states selfrealstates states selfstartstate selfendstate lenstates selftransitions transitions selfemissions emissions selfvocab vocab functions get stuff oneindexed statenum lambda self n selfstatesn statenums lambda self xrange lenselfrealstates vocabnum lambda self n selfvocabn vocabnums lambda self xrange lenselfvocab numforvocab lambda self selfvocabindexs def transitionself fromstate tostate return selftransitionsfromstatetostate def emissionself state observed return selfemissionsstateobserved helper stuff def normalizeobservationsself observations return none selfnumforvocabo oclass str else observations def inittrellisself observed forwardtrue initfuncidentity trellis none j rangelenobserved rangelenselfrealstates forward v lambda selftransition selfemissions observed else v lambda selftransitions selfendstate initpos forward else state selfstatenums trellisstateinitpos initfunc vstate return trellis def followbackpointersself trellis start bother branching pointer start seq pointer selfendstate reversedxrange lentrellis val backs trellispointert pointer backs seqinsert pointer return seq actual algorithms def forwardprobself observations returntrellisfalse returns probability seeing given observations sequence using forward algorithm observed selfnormalizeobservationsobservations trellis selfinittrellisobserved range lenobserved state selfstatenums trellisstatet sum selftransitionoldstate state selfemissionstate observedt trellisoldstatet oldstate selfstatenums final sumtrellisstate selftransitionstate state selfstatenums return final trellis returntrellis else final def backwardprobself observations returntrellisfalse returns probability seeing given observations sequence using backward algorithm observed selfnormalizeobservationsobservations trellis selfinittrellisobserved forwardfalse reversedrange lenobserved state selfstatenums trellisstatet sum selftransitionstate nextstate selfemissionnextstate observedt trellisnextstatet nextstate selfstatenums final sumselftransition state selfemissionstate observed trellisstate state selfstatenums return final trellis returntrellis else final def viterbisequenceself observations returntrellisfalse returns likely sequence hidden states given sequence observations uses viterbi algorithm observed selfnormalizeobservationsobservations trellis selfinittrellisobserved initfunclambda val val range lenobserved state selfstatenums emissionprob selfemissionstate observedt last oldstate trellisoldstatet selftransitionoldstate state emissionprob oldstate selfstatenums highest maxlast keylambda p p backs val last val highest trellisstatet highest backs last oldstate trellisoldstate selftransitionoldstate selfendstate oldstate selfstatenums highest maxlast key lambda p p backs val last val highest seq selffollowbackpointerstrellis backs return seq trellis returntrellis else seq def trainonobsself observations returnprobsfalse trains model using forwardbackward algorithm this function returns new hmm instance rather modifying one observed selfnormalizeobservationsobservations forwardprob forwards selfforwardprob observations true backwardprob backwards selfbackwardprobobservations true gamma values probofstateattime posat none forwardsstatet backwardsstatet forwardprob range lenobservations state selfstatenums xi values proboftransition pot none none forwardsstatet selftransitionstate state selfemissionstate observedt backwardsstatet forwardprob range lenobservations state selfstatenums state selfstatenums new transition probabilities trans j rangelenselfstates rangelenselfstates transselfendstateselfendstate state selfstatenums stateprob sumposatstate transstate posatstate transstate posatstate stateprob oth selfstatenums transstateoth sumpotstateoth stateprob new emission probabilities emit j rangelenselfvocab rangelenselfstates state selfstatenums output range lenselfvocab n sumposatstatet range lenobservations observedt output emitstateoutput n sumposatstate trained hiddenmarkovmodelselfstates trans emit selfvocab return trained posat pot returnprobs else trained reading files def normalizestring string string stringstringindex return stringstrip def makehmmfromfilef def nextline line freadline line eof return none else return normalizeline nextline n intnextline states nextline rangen list comprehension abuse numvocab intnextline vocab nextline rangenumvocab transitions floatx x nextlinesplit rangen emissions floatx x nextlinesplit rangen assert nextline none return hiddenmarkovmodelstates transitions emissions vocab def readobservationsfromfilef return filterlambda x x normalizeline line freadlines tests import unittest class testhmmunittesttestcase def setupself complicated pass args testcase use globals selfhmm makehmmfromfilefilehmmfilename selfobs readobservationsfromfilefileobsfilename def testforwardself prob trellis selfhmmforwardprobselfobs true selfassertalmostequalprob e selfassertalmostequaltrellis selfassertalmostequaltrellis selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis selfassertalmostequaltrellis selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e def testbackwardself prob trellis selfhmmbackwardprobselfobs true selfassertalmostequalprob e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis def testviterbiself path trellis selfhmmviterbisequenceselfobs true selfassertequalpath selfassertalmostequaltrellis selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis selfassertalmostequaltrellis selfassertalmostequaltrellis selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e selfassertalmostequaltrellis e def testlearningprobsself trained gamma xi selfhmmtrainonobsselfobs true selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalgamma selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi selfassertalmostequalxi def testlearningresultsself trained selfhmmtrainonobsselfobs tr trainedtransition selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr em trainedemission selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem train times range trained trainedtrainonobsselfobs tr trainedtransition selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr selfassertalmostequaltr em trainedemission selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem selfassertalmostequalem name main import sys hmmfilename sysargv lensysargv else examplehmm obsfilename sysargv lensysargv else observationstxt unittestmain observationstxt sequence observations testing examplehmm model used generate data number states start cold hot end size vocab transition matrix start cold hot end emission matrix start cold hot end,i trying learn baumwelch algorithmto used hidden markov model i understand basic theory forwardbackward models would nice someone help explain codei find easier read code i play around understand i checked github bitbucket find anything easily understandable there many hmm tutorials net probabilities either already provided case spell checkers add occurrences words make models it would cool someone examples creating baumwelch model observations for example httpenwikipediaorgwikihiddenmarkovmodelaconcreteexample states rainy sunny observations walk shop clean this example i think example explains play good understand better great i specific problem i trying solve i thinking would maybe valuable show code people learn apply problemsif acceptable i post problem if possible though it would nice pythonor java thanks advance,3 using lists arrays problematic need insertions deletions on operations devastatingly slow large datasets consider using blist listlike api affords olg n insertion deletion,i large array numerical data i need sort insert move values backwards forwards sorted order i previously using simple array now value linked id unique int along ride can i extend array class i need use list tuples what best option,1 the simplest solution would avoid using pipe tail stick using stdin user input instead write tool open follow file want read natively without using tail tail terribly complex tool want reimplement part alternately could create named pipe allow pipe tail program read like file still access stdin if neither options i think going separate library directly polls keyboard might best bet for record pygame actually main loop event pump function call often possible main loop going die it buffer lots lots events pumps set filters discard events care keep ones keypresses the main problem pygame would pretty heavyweight library requiring simple tool i understand hesitation go route oh final option least desirable opinion could abuse keyboard interrupt mechanic create emacslike key chords like press ctrlc ctrlwhatever the ctrlc invokes keyboardinterrupt handler read next character stdin something once done return loop but ugly hacky i even sure would work reliably,setup i playing script pipe tail f highlight certain keywords not big project something i find useful right main loop basically line true line line sysstdinreadline sysstdoutwritehighlightline i like listen certain keypresses loop print marker line log the method i found looks like would work getting keypress described httpcodeactivestatecomrecipes reads single character time stdin work main loop reading entire lines question is way python listen keypresses also reading piped input i wrapped main function try block excepts keyboardinterrupt prints nice little goodbye message instead error stack trace is way piggyback behavior another key i rather use beefy compared small script module like pygame tkinter forced use main loop get access keypresses also i familiar either would behave receiving piped input,1 the obvious thing work smtpexception needs smtplibsmtpexception import unqualified use smtplib import smtpexception otherwise changing valid addresses smtp server code works fine,usrbinpython import smtplib sender fromfromdomaincom receivers totodomaincom message from from person fromfromdomaincom to to person testyahoocom subject smtp email test this test email message try smtpobj smtplibsmtp localhost smtpobjsendmailsender receivers message print successfully sent email except smtpexception print error unable send email i keep getting folllowing errors even though i imported everything i using linux missing file emailpy line module import smtplib file usrlibpythonsmtplibpy line module import emailutils file homeemailpy line module except smtpexception,2 from djangodblog project page this project longer updated please see httpgithubcomdcramerdjangosentry successor so i simply assume project compatible django due various deprecations,i tried install django db log httpsgithubcomdcramerdjangodblog running python setuppy install reason i add app settingspy file working error i get request method get request url httplocalhostadmin django version exception type importerror exception value cannot import name paginator exception location librarypythonsitepackagesdjangoutilsimportlibpy importmodule line python executable usrbinpython python version python path userschristopherfarmdesktopecomstore librarypythonsitepackagespythondateutilpyegg librarypythonsitepackagesmysqlpythonpymacosxuniversalegg librarypythonsitepackagesdjangodblogpyegg systemlibraryframeworkspythonframeworkversionslibpythonzip systemlibraryframeworkspythonframeworkversionslibpython systemlibraryframeworkspythonframeworkversionslibpythonplatdarwin systemlibraryframeworkspythonframeworkversionslibpythonplatmac systemlibraryframeworkspythonframeworkversionslibpythonplatmaclibscriptpackages systemlibraryframeworkspythonframeworkversionsextraslibpython systemlibraryframeworkspythonframeworkversionslibpythonlibtk systemlibraryframeworkspythonframeworkversionslibpythonlibold systemlibraryframeworkspythonframeworkversionslibpythonlibdynload librarypythonsitepackages systemlibraryframeworkspythonframeworkversionsextraslibpythonpyobjc systemlibraryframeworkspythonframeworkversionsextraslibpythonwxmacunicode server time,1 you use overload class qsettingsfilename format parentnone like selfsettings qsettingssettingsini qsettingsiniformat if path relative file already opened current working directory may want you may try one answers use directory script instead,for app run directly flashpenusbjumpthumb drive portability moving one machine another make sense user settings stored memory stick directory program run rather windowsmaclinux user system dirs per machine qsettings handy however told use current working directory here little example program keeps screen position run run using qsettings pyside import qtgui qtcore pysideqtgui import qtabwidget qapplication pysideqtcore import qsettings class abcappqtabwidget def initself superabcapp selfinit selfsettings qsettingsqsettingsiniformatqsettingssystemscope mybiz settings selfsettingssetfallbacksenabledfalse file registry setpath try save current working directory selfsettingssetpathqsettingsiniformatqsettingssystemscope settingsini initial window sizepos last saved selfresizeselfsettingsvaluesize qtcoreqsize selfmoveselfsettingsvaluepos qtcoreqpoint selftab qtguiqwidget selftextedit qtguiqtexteditselftab selftexteditsethtml font colorgreyqtextedit areafontpcenterfont colorblue sizeballo woyldbfontcenter selfaddtabselftab tab def closeeventself e write window size position config file selfsettingssetvaluesize selfsize selfsettingssetvaluepos selfpos eaccept name main app qapplication frame abcapp frameshow appexec this ini file created since i happen running windows moment cdocuments settingsall usersapplication datamybizsettingsini userscope instead systemscope help instead settingsini work setpath basicaly effect also tried avail filepath osgetcwd settingsini selfsettingssetpathqsettingsiniformatqsettingssystemscope filepath reference httpdocqtnokiacomstableqsettingshtml httpwwwpysideorgdocspysidepysideqtcoreqsettingshtml promising though i know adapt pyside httpwwwqtcentreorgarchiveindexphpthtml update the answer alexisdm works updated code pyside import qtgui qtcore pysideqtgui import qtabwidget qapplication pysideqtcore import qsettings class abcappqtabwidget def initself superabcapp selfinit selfsettings qsettings settingsini qsettingsiniformat selfsettingssetfallbacksenabledfalse file fallback registry initial window sizepos last saved available selfresizeselfsettingsvalue size qtcoreqsize selfmoveselfsettingsvalue pos qtcoreqpoint selftab qtguiqwidget selftextedit qtguiqtexteditselftab selftexteditsethtml font colorgreyqtextedit areafontpcenterfont colorblue sizeballo woyldbfontcenter selfaddtabselftab tab def closeeventself e selfsettingssetvalue size selfsize selfsettingssetvalue pos selfpos eaccept name main app qapplication frame abcapp frameshow appexec,3 this best i think workaround earlier versions def floatprettifierdigits formatter df digits class prettyfloatfloat def strself return formatter self repr str return prettyfloat def fooa floatprettifier b floatprettifier pass helpfoo,give follow python function define def fooa b pass i call helpfoo i get help function foo module main fooa b but i wish get help function foo module main fooa b dear way print pretty,1 def recursivedictsumhelperv v add two values added otherwise expect dictionaries treat appropriately try return v v except return recursivedictsumv v def recursivedictsumd recursively produce new keyvalue pair original keyvalue pair make dict results return dict k recursivedictsumhelperv dk k v ditems maindict recursivedictsummaindict b,i main dictionary maindict count abc additional missing changed now new dictionary keys maindict called dictionary b different values b count abc additional missing changed i want updateaddition operation values keys main dictionary maindict count maindict count b count i stuck updating values key if use maindictupdateb replace previous values any efficient solution the final output required maindict count abc additional missing changed thanks,2 looks like good sleep really helps refreshed mind much anyway i found solution studying python documentation class consumermultiprocessingprocess def initself taskqueue results consumersfinished multiprocessingprocessinitself selftaskqueue taskqueue selfresults results selfconsumersfinished consumersfinished def runself allflag flag selfconsumersfinishedvalues try task selftodoqueuegetfalse selfconsumersfinishedselfname false except queueempty selfconsumersstoppedselfname true continue taskresult selfdosomeprocessingtaskdata selftaskqueueputtaskresult class starterobject def startself manager multiprocessingmanager taskqueue managerqueue results managerlist consumersfinished managerdict consumers consumertaskqueue results consumersfinished rangeselfconsumerscount consumer consumers consumersfinishedconsumername false consumerstart taskqueueputtaskdata consumer consumers consumerjoin return results this part python documentation explains problem i think warning as mentioned child process put items queue used joinablequeuecanceljointhread process terminate buffered items flushed pipe this means try joining process may get deadlock unless sure items put queue consumed similarly child process nondaemonic parent process may hang exit tries join nondaemonic children note queue created using manager issue see programming guidelines so i changed queue created manager consumer run method tasks taken queue different way see code,the problem consumer never exits hangs nothing the code intended work like a queue created taskdata passed a specified number consumers created process data when consumer finds queue empty still chance another consumer could put something queue cannot leave however indicate consumersfinished list jobs the consumers loop goes every worker indicates finished work it known much work consumers put tasks queue i read something clear whether processes hang waiting forever feed class consumermultiprocessingprocess def initself taskqueue results consumersfinished multiprocessingprocessinitself selftaskqueue taskqueue selfresults results selfconsumersfinished consumersfinished def runself allflag flag selfconsumersfinishedvalues taskdata selftaskqueueget taskdata selfconsumersfinishedselfname true continue selfconsumersfinishedselfname false taskresult selfdosomeprocessingtaskdata selftaskqueueputtaskresult class starterobject def startself manager multiprocessingmanager taskqueue multiprocessingqueue results managerlist consumersfinished managerdict consumers consumertaskqueue results consumersfinished rangeselfconsumerscount consumer consumers consumersfinishedconsumername false consumerstart taskqueueputtaskdata consumer consumers consumerjoin return results,1 try something like colors red blue black yellow green numbers panels things more things ultra import random import wx class tabpanelwxpanel def initself args kwargs wxpanelinitself args kwargs selfsetbackgroundcolourrandomchoicecolors selflistbox wxlistboxself size choicesnumbers stylewxlbsingle selfbutton wxbuttonself labelsomething else maybe selfsizer wxboxsizer selfsizeraddselflistbox proportion flagwxall wxexpand border selfsizeraddselfbutton proportion flagwxall selfsetsizerselfsizer class mynotebookwxnotebook def initself args kwargs wxnotebookinitself args kwargs selfpanels name panels panel tabpanelself selfpanelsappendpanel selfaddpagepanel name class mypanelwxpanel def initself args kwargs wxpanelinitself args kwargs selfnotebook mynotebookself size selfbutton wxbuttonself labelsomething else maybe selfsizer wxboxsizer selfsizeraddselfnotebook proportion flagwxexpand selfsizeraddselfbutton proportion selfsetsizerselfsizer class mainwindowwxframe def initself args kwargs wxframeinitself args kwargs selfpanel mypanelself selfstatus selfcreatestatusbar selfmenubar wxmenubar firstwxmenu secondwxmenu firstappendwxnewid new creates a new file firstappendwxnewid adid yo selfmenubarappendfirst file selfmenubarappendsecond edit selfsetmenubarselfmenubar selfshow app wxappfalse win mainwindownone size appmainloop uncomment buttons see add stuff you may find useful hints wxpython programming code i lazy describe everything,troubles i believe sizers i cannot set size notebook way want right i put button position button determines size notebook stretch however want able without using button i played around however cannot get change please run following code understand i mean import random import wx wxidframe wxidframebutton wxidframebutton wxidframelistbox wxnewid initctrls range class tabpanelwxpanel def initself parent wxpanelinitself parentparent colors red blue gray yellow green selfsetbackgroundcolourrandomchoicecolors samplelist listbox wxlistboxself samplelist wxlbsingle listboxsetselection this button btn wxbuttonself labelcreate new sizer wxboxsizerwxvertical sizeraddbtn wxall selfsetsizersizer class demoframewxframe frame holds widgets def initself constructor wxframeinitself none wxidany notebook tutorial size panel wxpanelself notebook wxnotebookpanel tabone tabpanelnotebook notebookaddpagetabone things tabtwo tabpanelnotebook notebookaddpagetabtwo things sizer wxboxsizer sizeraddnotebook panelsetsizersizer menu bar statusselfcreatestatusbar menubarwxmenubar firstwxmenu secondwxmenu firstappendwxnewidnewcreates a new file firstappendwxnewidadidyo menubarappendfirstfile menubarappendsecondedit selfsetmenubarmenubar selflayout selfshow name main app wxappfalse frame demoframe appmainloop thank much looking,1 i write def sumdictsrecursived k v ditems isinstancev dict yield k dictprocessv dk else yield k v dk result dictsumdictsrecursivemaindict b count abc changed additional missing note sumdictsrecursive writter oneliner generator expression probably harder understand,i main dictionary maindict count abc additional missing changed now new dictionary keys maindict called dictionary b different values b count abc additional missing changed i want updateaddition operation values keys main dictionary maindict count maindict count b count i stuck updating values key if use maindictupdateb replace previous values any efficient solution the final output required maindict count abc additional missing changed thanks,1 you getting form value outside handler modulelevel code obviously defined module first loaded time first request you inside get method,i trying google appengine python today first time managed get simple example running it worked something wierd happening url parameter value changes registered unless i restart app in example i run httplocalhostxhello return x hello i change value x new value affect output i suspect kind internal caching going i sure googleappengineext import webapp googleappengineextwebapp import util import cgi form cgifieldstorage x formgetvalue x class mainhandlerwebapprequesthandler def getself x hello selfresponseoutwrite x hello else selfresponseoutwrite x hello def main application webappwsgiapplication mainhandler debugtrue utilrunwsgiappapplication name main main,3 clojure pretty much everything likely want live coding language main highlights interactive repl interact directly running program even i traditional programming i tend write code interactively copy bits i like source file later clojure designed work way pretty much everything program inspectable modifiable replaceable runtime great concurrency support kick concurrent background tasks trivially code like future somefunction more importantly clojure stm emphasis high performance immutable data structures take care subtle concurrency aspects eg happens i update live data structure middle rendered library availability jvm language pull audio visual io computational tools require java ecosystem it easy wrap line two clojure get concise interface functions need macros clojure homoiconic language take advantage lisp ability write powerful macros extend language you effectively build exact syntax want use live environment let compiler hard work creating complete code behind scenes dynamic typing benefits argued ways certainly huge benefit trying write code quickly concisely active community lot cool projects likely find lot people interested similar live coding techniques clojure community a couple links might find interesting paul graham lisp beating averages live clojure coding example overtone sound synthesizer frontend supercollider,i would like build live coding framework i explain meant live coding framework i comparing live coding traditional coding generally put traditional programming write code sometimes compile launch executable open script sort interpreter if want modify application must repeat process a live coding framework enables code updated application running reloaded demand perhaps reloading happens time file containing code changed action changes code reflected application running there need close program recompile relaunch in case application windowed app updatedraw loop likely using opengl graphics audio library sound processing supercollider ideally networking lib of course i preferred languages though i certain would well suited kind architecture ideally i would use python lua ruby another higher level language however friend recently suggested clojure possibility i considering well i would like know languages would suitable kind framework generally language features would make framework possible,2 your disk host reducer run small your reducer input takes approx gbs gb free maybe combiner could useful have look httptumblrmobocracynetpostusingacombinerwithhadoopjobs,my map task completes successfully i see application logs reducer stays pending state kind complete num tasks pending running complete killed failedkilled task attempts map reduce when i look reduce task i see all task attempts no task attempts found when i see hadoophduserjobtrackermasterlog i see following warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackermasterlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackermasterlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackermasterlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackermasterlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackermasterlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackermasterlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackermasterlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackermasterlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take how i fix issue please help,1 i marking answered correct way imagemodelimagefield path fileread programmatically saving image django imagefield,this killing i using djangofilebrowser i want create gallery app leverages upload capabilities manage images i gallery model allows user select create directory server upload files folder appear gallery i want automatically trawl directory user uploaded images selected automatically create image instances image folder class gallerymodelmodels gallerydirectory filebrowserfield title description class imagemodelmodels imagefield modelsimagefield the problem filebrowser represents images differently django i want use django imagefields i use apps sorl thumbnails template end i data necessary file ie filename path etc i get django create instance imagefield without actually uploading image i simply want populate i seen another thread suggests following image filebrowserimageobjectslist f fileopen pathtofileonserver r image iimagefield filenamepng fread giving suspiciousoperation error attempted access filenamepng denied suggests path read correctly i printed attributes file object opening correct image getting passed imagefield help would greately appreciated update i given trying get work messy the problem i i set uploadfield imagefield gone unnoticed meaning file written somethingpng i modified image using filebrowserfield well instead imagefield,3 just came across question i trying figure recursively download datasets zos i using simple python script years download ebcdic files mainframe it effectively def writelineline filewriteline n file openfilename w ftpretrlinesretr filename writeline,i trying automate downloading text files zos pds using python ftplib since host files ebcdic i simply use ftpretrbinary ftpretrlines used openfilewwritelines callback course provide eols so starters i come piece code looks ok i relative python noob anyone suggest better approach obviously keep question simple final bellsandwhistles thing many thanks pythonexe ftplib import ftp class xfile file def writelineswitheolself sequence sequence selfwritesrn sess ftpzosservertobe myid mypassword sesssendcmdsite sbdibmiso sesscwd foobarpds sessnlstrtb sessretrlinesretr xfilei w writelineswitheol sessquit update python platform mingw windows xp zos pdss fixed record structure rather relying line endings record separators however zos ftp server transmitting text mode provides record endings retrlines strips closing update here revised solution basis ongoing development removing builtin passwords example import ftplib import os sys import excinfo sess ftplibftpundisclosedservercom userid password sesssendcmdsite sbdibmiso dir asm asml asmm c cpp dlla dllc dlmc gen hdr mac sesscwd zltalmpreps dir try filelist sessnlst except ftpliberrorperm x xargs raise else try osmkdirdir except continue hostfile filelist lines sessretrlinesretr hostfile linesappend pcfile openss dirhostfile w line lines pcfilewritelinen pcfileclose print done dir sessquit my thanks john vinay,1 click edit signalslots tool create connection button for select button designer pressing left button mouse move mouse place main window create connection main window like red line earth connection when release mouse button configure connection dialog appears in dialog select signal left text control sender example pressed then press edit right text control receiver a dialog signalsslots mainwindow appears in slot panel add new slot green cross the text slot appears double click edit line write instead name function doitwhenyesispressed accept now configure connection dialog see function right text control select accept in designer see signal function widget,i use qt designer i want i click yes button code execute and i click code execute how i,3 you need instance class use methods or need access classes variables static parameters define method static used even class instantiated just add staticmethod decorator methods class mathsoperations staticmethod def testaddition x return x staticmethod def testmultiplication b return b docs httpdocspythonorglibraryfunctionshtmlstaticmethod,edit thank help edit adding staticmethod works however i still wondering getting type error i started oops completely new i basic question regarding different ways i call function class i testclasspy file code class mathsoperations def init self x selfa x selfb def testaddition self return selfa selfb def testmultiplication self return selfa selfb i calling class another file called mainpy following code testclass import mathsoperations xyz mathsoperations print xyztestaddition this works without issues however i wanted use class much simpler way i put following code testclasspy file i dropped init function time class mathsoperations def testaddition x return x def testmultiplication b return b calling using testclass import mathsoperations xyz mathsoperations print xyztestaddition works can someone explain happening wrongly case how i use class the error get typeerror testaddition takes exactly arguments given,1 your methods refer object self use staticmethod decorator class mathsoperations staticmethod def testaddition x return x staticmethod def testmultiplication b return b,edit thank help edit adding staticmethod works however i still wondering getting type error i started oops completely new i basic question regarding different ways i call function class i testclasspy file code class mathsoperations def init self x selfa x selfb def testaddition self return selfa selfb def testmultiplication self return selfa selfb i calling class another file called mainpy following code testclass import mathsoperations xyz mathsoperations print xyztestaddition this works without issues however i wanted use class much simpler way i put following code testclasspy file i dropped init function time class mathsoperations def testaddition x return x def testmultiplication b return b calling using testclass import mathsoperations xyz mathsoperations print xyztestaddition works can someone explain happening wrongly case how i use class the error get typeerror testaddition takes exactly arguments given,1 use self first parameters method second case use class mathoperations def testaddition selfx return x def testmultiplication selfa b return b code could following tmp mathoperations print tmptestaddition use class without instantiating variable first print mathoperationtestaddtion gives error typeerror unbound method want need staticmethod decorator for example class mathsoperations staticmethod def testaddition x return x staticmethod def testmultiplication b return b code could use print mathsoperationstestaddition,edit thank help edit adding staticmethod works however i still wondering getting type error i started oops completely new i basic question regarding different ways i call function class i testclasspy file code class mathsoperations def init self x selfa x selfb def testaddition self return selfa selfb def testmultiplication self return selfa selfb i calling class another file called mainpy following code testclass import mathsoperations xyz mathsoperations print xyztestaddition this works without issues however i wanted use class much simpler way i put following code testclasspy file i dropped init function time class mathsoperations def testaddition x return x def testmultiplication b return b calling using testclass import mathsoperations xyz mathsoperations print xyztestaddition works can someone explain happening wrongly case how i use class the error get typeerror testaddition takes exactly arguments given,3 disclaimer point answer like piece advice even answer found references imho object oriented programming python sucks quite lot the method dispatching straightforward need know boundunbound instanceclass static methods multiple inheritance need deal legacy new style classes old style know mro works properties in brief complex lots things happening hood let even say unpythonic many different ways achieve things my advice use oop really useful usually means writing classes implement well known protocols integrate seamlessly rest system do create lots classes sake writing object oriented code take good read pages httpdocspythonorgreferencedatamodelhtml httpdocspythonorgtutorialclasseshtml find quite useful if really want learn oop i suggest starting conventional language like java it half fun python predictable,edit thank help edit adding staticmethod works however i still wondering getting type error i started oops completely new i basic question regarding different ways i call function class i testclasspy file code class mathsoperations def init self x selfa x selfb def testaddition self return selfa selfb def testmultiplication self return selfa selfb i calling class another file called mainpy following code testclass import mathsoperations xyz mathsoperations print xyztestaddition this works without issues however i wanted use class much simpler way i put following code testclasspy file i dropped init function time class mathsoperations def testaddition x return x def testmultiplication b return b calling using testclass import mathsoperations xyz mathsoperations print xyztestaddition works can someone explain happening wrongly case how i use class the error get typeerror testaddition takes exactly arguments given,3 you set bins list integer eg bins to answer commnet excerpt documentation bins either integer number bins sequence giving bins if bins integer bins bin edges returned consistent numpyhistogram numpy version new true argument earlier versions unequally spaced bins supported bins sequence and example cumulative normalized histogram notice effect bins bar plot first two bars wider middle bars,i problem dealing data set value range tens thousand and problem show histogram whole data set using hist however i want show cumulative normed detailed histogram using say x i use bins assure detail the tricky problem i use range show normed cumulative hist end but actually far less real since normed within small range data could anyone ideas utilize hist matplotlib tackle problem i thought complicated i write another function draw hist i need,1 the example code give works fine data colons prints exactly expect you must something else incorrect,i issue code why special characters like colon printing lista kk go listb b bthree b print lista print listb works lista kk go print lista show nothing wrong i lost,1 you could handle instead using jquery form use jquery ajaxpost this allow serialize form get parameters able return js function want form submitted check jquerypost jsfiddle this refresh page post happens ajax call it allows run function post goes want post returns data available want another get post one success done forth,any way submit form without refreshing current page using python jquery ajax i want end results similar facebook comment works i currently using jquery form ajax however give user experience i want after submitting using jquery form url address bar refreshed form i submitted it refresh page i like especially let say i bottom page scrolled maximum after submitting form refreshed page focus redirected top page i hope i made point clear i want i need something like facebook comment system works someone commented comment submitted without refresh page edit jquery code reviewsubmit submitfunction var options thisajaxsubmitoptions return false namesubmitreviewbtn clickfunction reviewsubmit submit so python code handle submit need redirect page server side code redirect page url mainurlcom with jquery codes shown results the url appeared address bar mainurlcom formactionurl this form action i set submit form page redirected page i set server side i confused ajax experience,3 check pyv httpcodegooglecomppyv,i searched high low solution i also gone how execute javascript python windows asked ago in meantime world come better solution and pythonspidermonkey work windows anyone successful embedded javascript python alternativelyif developed using available libraries like pythonspidermonkey linux way end product could made run windows edithave also pydermonkey stop short build process following error pavementbuild pavementbuildspidermonkey running configure captured task output pavementbuild pavementbuildspidermonkey traceback recent call last file fashwinsuttaappembedding pythonpythonspidermonkeypydermonkeypythonmodulespavertaskspy line runtask return dotask file fashwinsuttaappembedding pythonpythonspidermonkeypydermonkeypythonmodulespavertaskspy line dotask task file fashwinsuttaappembedding pythonpythonspidermonkeypydermonkeypythonmodulespavertaskspy line call retval environmentruntaskselfname selfneeds selffunc file fashwinsuttaappembedding pythonpythonspidermonkeypydermonkeypythonmodulespavertaskspy line runtask return dotask file fashwinsuttaappembedding pythonpythonspidermonkeypydermonkeypythonmodulespavertaskspy line dotask return funckw file fashwinsuttaappembedding pythonpythonspidermonkeypydermonkeysetuppy line buildspidermonkey popen subprocesspopenosenviron shell c pwd file cpythonlibospy line getitem return selfdatakeyupper keyerror shell cheers,2 you override save method djangocontribauthformspasswordresetform pass new form argument passwordreset view,it seems django supports plain text messages password reset emails box how i use html templates purpose,3 your error seems typo library found you put webkit instead webkit additionaly use ubuntu check library existence locate girepository grep webkit usrlibgirepositorywebkittypelib if exist need install package girwebkit aptget install girwebkit then python script import gi girequireversion webkit girepository import webkit,when i try import webkit girepository gives importerror girepository import webkit errorrootcould find typelib webkit traceback recent call last file stdin line module importerror cannot import name webkit what i wrong,3 looking setattr def initself details fieldvalue detailsiteritems setattrself field value,i python class like class carbase def initself details fieldvalue detailsiteritems selffield value i call like cardetails make dodge cardetails model ram car carcardetails however fails typeerror car object support item assignment i trying set i use carmake class init,2 starting python functionality need included builtin unittest module for earlier versions python module backported name unittest if reason want roll test discovery basic approach import glob import sys import testbase syspathappendtests path globiglobtestspy module importospathbasenamepath name dirmodule obj getattrmodule name isinstanceobj type issubclassobj testbasetestbase test obj testtestfunction,i directory structure in project root directory i main python file say mainpy also root direcory folder called tests this test folder series test files known run time eg testpytestpy etc in testfiles eg testpy i sort structure testbase import testbase class testtestbase def testfunctionself dosomestuff in mainpy i want call testfunction how i use syspathappend add tests directory path x importtestfilename result xtestfunction something like method class testfilename,1 this creates fullscreen window pressing escape resizes window x default if move resize window escape toggles current geometry previous geometry import tkinter tk class fullscreenappobject def initself master kwargs selfmastermaster pad selfgeom x mastergeometryxformat masterwinfoscreenwidthpad masterwinfoscreenheightpad masterbind escape selftogglegeom def togglegeomselfevent geomselfmasterwinfogeometry printgeomselfgeom selfmastergeometryselfgeom selfgeomgeom roottktk appfullscreenapproot rootmainloop,how one get frame tkinter display fullscreen mode i saw code usefull import tkinter root tkintertk rootoverrideredirecttrue rootgeometryxformatrootwinfoscreenwidth rootwinfoscreenheight possible i hit esc automatically restore window probably complicated code pls help,3 not real answer i yet allowed comment sigh since diveintopython much usedcitedreferenced resource python programmers least begin really contact author flaw misleading also others there contact information home page diveintopython also file issue github,i read article supposedly introduced new concept up i sure python packages ie directories initpy file behave exactly java packages little namespaces help arrange code minus java package scoping but according link a short digression into multifile modules i put files package entire collection files presented python code single module — functions classes single py so i thought whole understanding python package thing wrong moreover entirely package rather multifile module author refers so i understood matter many files i divide funcs classes inside package outside package appear though i took code files inside package put one big file name package instead ie one module eg i following file structure base animals initpy dogpy dogpy def bark print woof exactly base animalspy animalspy def bark print woof thus next piece code run fine cases base import animals animalsbark this course yields first case traceback recent call last file console line module attributeerror module object attribute bark what i missing i see exception animals indeed treated module appears still explicitly state animalsdogbark ie internal file structure package abstracted outside am i missing author point implementing correctly edit just make sure one misses line quote functions classes single py regardless actually access funcs classes quote explicitly states func file func file b regardless path accessible denote path x according aforementioned quote xfunc xfunc work,1 try figaspect it works from docs create figure specified aspect ratio if arg number use aspect ratio if arg array figaspect determine width height figure would fit array preserving aspect ratio the figure width height inches returned be sure create axes equal height eg example usage make figure twice tall wide w h figaspect fig figurefigsizewh ax figaddaxes aximshowa kwargs make figure proper aspect array a rand w h figaspecta fig figurefigsizewh ax figaddaxes aximshowa kwargs edit i sure looking the code changes canvas plot size if want change size matplotlib window figure use in f figurefigsize produce window x wxh,i trying make square plot using imshow ie aspect ratio i none work import matplotlibpyplot plt ax figaddsubplotaspect equal ax figaddsubplotaspect axsetaspect equal pltaxessetaspect equal any ideas let know need info eg details calls it seems like calls ignored problem i often seem matplotlib thanks,1 subprocesscheckcalleditor filepath raise oserror exception editor fails run,i like open editor cli guibased via python script i ossystem vim file i also like get output case command fails subprocessgetstatusoutput vim file work opening programs specific interface what best alternative,1 this might overkill based comment both theoretical curves data points arrays different length i would following truncate data set x values lie within max min values theoretical set interpolate theoretical curve using scipyinterpolateinterpd truncated data x values the reason step satisfy constraints interpd use numpywhere find data values side range acceptable theory values dont discard values suggested comments answers if want clarity point plotting inliners one color outliers color here script close looking i think it hopefully help accomplish want import numpy np import scipyinterpolate interpolate import matplotlibpyplot plt make data def makeupdata make many data points xyyerr theory xy theory yerr corresponding constant sigma xy value nx datax nprandomrandnx datay dataxnprandomrandnxdatax dataerr nprandomrandnxdatax theoryx nparange theoryy theoryxtheoryx theoryerr return dataxdataydataerrtheoryxtheoryytheoryerr def makesamexrangetheoryxdataxdatay truncate datax datay ranges datax min max max min theoryx mintmaxt theoryxmintheoryxmax goodidxmax npwheredataxmaxt goodidxmin npwheredataxgoodidxmaxmint return dataxgoodidxmaxgoodidxmindataygoodidxmaxgoodidxmin take theory get values every data x point def theoryyatdataxtheoryxtheoryydatax for every datax point find interpolated thoeryy value theoryx needed interpolation f interpolateinterpdtheoryxtheoryy return fdataxnpwheredataxnpmaxtheoryx collect valid points def findinliersetdataxdatayinterptheoryythoeryerr find theoryytheoryerr datay theoryytheoryerr return valid indicies withinupper npwheredatayinterptheoryytheoryerr withinlower npwheredataywithinupper interptheoryywithinuppertheoryerr return dataxwithinupperwithinlowerdataywithinupperwithinlower def findoutliersetdataxdatayinterptheoryythoeryerr find theoryytheoryerr datay theoryytheoryerr return valid indicies withinupper npwheredatayinterptheoryytheoryerr withinlower npwheredatayinterptheoryytheoryerr return dataxwithinupperdataywithinupper dataxwithinlowerdataywithinlower name main dataxdataydataerrtheoryxtheoryytheoryerr makeupdata truncdataxtruncdatay makesamexrangetheoryxdataxdatay interptheoryy theoryyatdataxtheoryxtheoryytruncdatax indataxindatay findinliersettruncdataxtruncdatayinterptheoryy theoryerr outupxoutupyoutdownxoutdowny findoutliersettruncdatax truncdatay interptheoryy theoryerr print inlierindex fig pltfigure ax figaddsubplot axerrorbardataxdataydataerrfmt color k axplottheoryxtheoryy r axplottheoryxtheoryytheoryerr r axplottheoryxtheoryytheoryerr r axsetxlim axsetylim ax figaddsubplot axplotindataxindatay ko axplotoutupxoutupy bo axplotoutdownxoutdowny ro axplottheoryxtheoryy r axplottheoryxtheoryytheoryerr r axplottheoryxtheoryytheoryerr r axsetxlim axsetylim figsavefig findinlierspng this figure result,i need compare theoretical data real data python the theoretical data comes resolving equation to improve comparative i would like remove data points fall far theoretical curve i mean i want remove points red dashed lines figure made matplotlib both theoretical curves data points arrays different length i try remove points roughlyeye way example first upper point detected using datadataredshiftampdatadmodulus recarray dtype snname s redshift f dmodulus f dmoduluserror f but i would like use less roughlyeye way so anyone help finding easy way removing problematic points thank,2 you could use alex martelli bunch class carbase def initself details selfdictupdatedetails note change init call signature def initself details class carbase def initself details supercarselfinitdetails make initialization car even easier carcarmake dodge model ram,i python class like class carbase def initself details fieldvalue detailsiteritems selffield value i call like cardetails make dodge cardetails model ram car carcardetails however fails typeerror car object support item assignment i trying set i use carmake class init,1 that option latest version scrapy found github if using version latest stable seen scrapyorg use scrapy crawl openings set feeduriitemsjson set feedformatjson see also httpreadthedocsorgdocsscrapyenintrotutorialhtmlstoringthescrapeddata,when i run command scrapy crawl openings itemsjson json mentioned tutorial i get usage scrapy crawl options spiderurl crawl error option i simply following scrapy tutorial i run command without output option works fine scrapy crawl openings works fine i see crawl output however work i want export crawl json searched web extensively help mention issue,3 i see element hunting inside table firefox adds tbody tag every table even exists source html code that might reason xpath query works browser fails scrapy as suggested use anchors xpath query,i writing scrapy program extract data this url i want scrape code information i taken xpath firefox addon xpather this path htmlbodyptabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtd while i trying execute try templist hxsselecthtmlbodyptabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdtabletbodytrtdextract print templist strtemplist except print error it returns empty list i struggling find answer last hours i newbie scrapy eventhough i handled issues well projects seems bit difficult,1 it already contains one it called dict class fooobject def goself method getattrself method def aself def bself if reaaaally want numeric indices eg class fooobject methods b def goself n getattrself selfmethodsn but silly especially strings interned using magic integers place buy much except obscurity,how i go installing class variable table contains entry points methods for clarification consider following working code class aobject def goself n method selftablen methodself def addself print add def multiplyself print multiply table add multiply q a qgo add however i like much i would like table beginning readability real world project much bigger i like call using methodself i think confusing my question is better way code spoton thank,3 i sure i get want could solve differently like class aobject table add multiply def goself n method getattrself selftablen method def addself print add def multiplyself print multiply a ago add edit reading response cat plus plus if want aliases existing methods far easier way maybe want able call methods welsh class aobject table add multiply def goself n method getattrself selftablen method def addself print add def multiplyself print multiply ychwanegu add lluosi multiply a alluosi multiply,how i go installing class variable table contains entry points methods for clarification consider following working code class aobject def goself n method selftablen methodself def addself print add def multiplyself print multiply table add multiply q a qgo add however i like much i would like table beginning readability real world project much bigger i like call using methodself i think confusing my question is better way code spoton thank,1 not exactly asked since recommended use standard python tools instead regexes possible i something like import open numberstxt r f refindallr dd line line f linestartswith foo update and return numbers foo even anywhere string rather beginning open numberstxt r f refindallr dd linepartition foo line f,i got file looks like foo bar bar bar foo would like extract numbers lines beginning keyword foo expected result now easy i use two regexes like rematch foo line refindall dd line i wondering possible combine single regex thanks help md,2 how could work what event date could referring when call eventpastschoolyeareventsall model instance selfmodel name implies refers model class so could know date mean i actually work trying going get date do want start event get events year one in case i suspect want make pastschoolyearevents model method manager edit if want start specific year manager certainly appropriate need pass year manager method parameter for i use separate method manager rather overriding getqueryset fact add another method schoolyearmanager class schoolyearmanagermodelsmanager def liveeventsself startdate enddate return selffilterstatusselfmodellivefiltereventdaterangestartdate enddate def thisyearself datetimedatetimenow currentyear nowyear startdate datetimedatecurrentyear enddate datetimedatecurrentyear return selfliveeventsstartdate enddate def fromyearself year startdate datetimedateyear enddate datetimedateyear return selfliveeventsstartdate enddate now got one manager override getqueryset even need preserve default one keep one objects so eventobjectsthisyear year events eventobjectsfromyear events,i django model object datefield i also two managers filter objects specific date range class schoolyearmanagermodelsmanager def getquerysetself datetimedatetimenow currentyear nowyear startdate datetimedatecurrentyear enddate datetimedatecurrentyear return superschoolyearmanager selfgetquerysetfilterstatusselfmodellivefiltereventdaterangestartdate enddate class pastschoolyearmanagermodelsmanager def getquerysetself currentyear selfmodeleventdateyear startdate datetimedatecurrentyear enddate datetimedatecurrentyear return superpastschoolyearmanager selfgetquerysetfilterstatusselfmodellivefiltereventdaterangestartdate enddate class eventmodelsmodel live draft statuschoices live live draft draft status modelsintegerfieldchoicesstatuschoices default helptextonly entries status live displayed publically eventdate modelsdatefield objects modelsmanager schoolyearevents schoolyearmanager pastschoolyearevents pastschoolyearmanager my first manager schoolyearmanager works expected return events within date range but i try eventpastschoolyeareventsall i get attribute error type object event attribute eventdate my goal second manager pastschoolyearevents wrap generic year archive view return events within date range specific year why i call selfmodeleventdate within manager am i going right way if better way,1 if pythonbased nothing python would really care python based anyways yes project exists a pretty big one it called xulrunner the project maintained mozilla used gui every mozilla program it features xmlbased syntax xul xml version xmlstylesheet hrefchromeglobalskin typetextcss window idmain titlemy app width height xmlnshttpwwwmozillaorgkeymastergatekeeperthereisonlyxul script typeapplicationjavascript srcchromemyappcontentmainjs caption labelhello world separator button labelmore oncommandshowmore separator description idmoretext hiddentruethis simple xulrunner application xul simple use quite powerful even used mobile devicesdescription window and javascript function showmore documentgetelementbyidmoretexthidden false you even embed python scripts seems code httppyxpcomextmozdevorgnowraptutorialspyxulrunnerpythonxulrunnerabouthtml,i wonder python gui like pyqt etc works purely html javascript layouting desktop applications do know projects like does make sense or finding nice tool,3 since mention pyqt could perhaps create simple gui using tools entire application made qtwebkit module then point files created locally browse using appliction but would different compared using normal browser really point opinion,i wonder python gui like pyqt etc works purely html javascript layouting desktop applications do know projects like does make sense or finding nice tool,1 i sure i understood exactly want i got function want it search recursively object attributes yielding nested dictionary list structure ending points python objects dict attribute sqlalchemy case likely basic python types like numbers strings if fails replacing hasattr dict test soemthing sensible fix code needs def mydictobj hasattrobjdict return obj result key val objdictitems keystartswith continue element isinstanceval list item val elementappendmydictitem else element mydictval resultkey element return result,i sqlalchemy objects contain lists sqlalchemy objects levels i wish convert objects dictionaries i convert object dictionary using dict property problem however i trouble figuring best way convert nested objects well without level explicitly so far best i come recurse properly it basically breaks one pass clearly something wrong logic can see wrong i hoping alldict mydictobjdict def mydictd kv ditems isinstancevlist dk mydictidict v else dk v return,2 the point using static handlers able serve files without spinning instance python app if need custom authentication logic run first static handlers work as realworld applications i think people accept javascript html protectable people want steal code much think,i would like restrict access static html files google app engine the reason i want considerable amount application written javascript delivered html files i want authorized people access code i would also like restrict access http resources i written using webapp framework ideally i would like write authentication functionality even ideally i like use authentication control access static files i struggling fulfill requirements from i tell way restrict access static files using authentication provided app engine httpcodegooglecomappenginearticlesauthhtml the problem solution requires use whatever authentication scheme app engine provided i already see problems requires google account this requirement would appropriate application another idea would restrict all access static files instead application read send http resource i configured require authentication i confused good solution would often answer type question is done realworld applications does anyone know done realworld application nature or anyone ideas i handle thanks,2 you use defaultdict collections import defaultdict datasets foo bar bar foo result defaultdictlist dataset datasets eachdict dataset key value eachdictiteritems resultkeyappendvalue nested loops oneliner utterly unnecessary anyresultkeyappendvalue dataset datasets eachdict dataset key value eachdictiteritems really need output exactly format result key tuplevalues key values resultiteritems print result that seems like cleanest approach,i using python i two datasets list dictionaries the two datasets look like foo bar bar foo from two datasets i want create single list tuples would look like input data foo bar it important number first dataset come first resulting tuple btw i actually accomplished various means including nested list comprehension seems like simplercleaner i surprised nothing itertools jumped though i one implementation w chain resulted tuple ints list can anyone provide clean solution one,2 you use something like urlpatterns patterns urlr plocwpsubctgwptitlew betaviewsqueryfromindexdeep using regular expressions match view way easier recommended in view would match function defined like betaviewsqueryfromindexdeeprequest loc subctg title continue work variables extract relevant data defined models,i html form inserts data one table called srv i built urlspy way capture every insertion item srvobjectsall linksrv itemloclower srv itemsubctglower itemtitlelower urlpatterns patterns urlr linksrv betaviewsqueryfromindexdeep after one insertion made eg loc loc subctg subctg title title point browser locsrvsubctgtitle get http error matching url if i forcesave urlspy vim urlspy x locsubcttitle inserted i successfully access locsrvsubctgtitle anyone shed light it looks like urlpatterns need updated time row insterted srv table,1 sebastien deleteentry function deleting last entry db idselect maxidfrom entries what insert parameter url deletion like deleteid id id entry want deleted change template generate url href urlfor deleteentry entryid deletea and also change db query deletes entry gdbexecute delete entries id id edit i checked flask documentation order get variables routes modify route follows approute deleteintentryid in way obtain entryid python function def deleteentryentryid gdbexecute delete entries id entryid and finally specify entry id urlfor function href urlfor deleteentry entryid entryid deletea,i learning python tutorial app flask i figure reference certain row database i trying delete record using delete link templatei spent whole day trying everything i could find really understand i know simple i get here html template ul classentries entry entries lih entrytitle h entrytextsafe h sessionloggedin href urlfor deleteentry deletea endif else endfor ul as see next entry delete linkhow i supposed reference right id database here python function i far approute delete def deleteentry sessionget loggedin abort gdbexecute delete entries idselect maxidfrom entries gdbcommit flash the entry deleted return redirecturlfor showentries what i far works it i want thanks advance,2 this inner join operation tool ds foo bar ds bar foo import sqlite c sqliteconnect memory cexecute create table ds key text primary key value text cexecute create table ds key text primary key value text cexecutemany insert into ds values ditems ds cexecutemany insert into ds values ditems ds ccommit r cexecute select dskey dsvalue dsvalue from ds inner join ds on dskeydskey listr u foo u u u bar u u the sqlite module comes python require create maintain actual database order perform sql queries data sets so get data database alter query bring back form best suits application still massage data using sql convenient using sql approach several advantages code expresses intention clearly i joining two datasets common key makes easier consider correctness issues keys present one dataset easy extend multiple fields switch multifield key ordering may specified,i using python i two datasets list dictionaries the two datasets look like foo bar bar foo from two datasets i want create single list tuples would look like input data foo bar it important number first dataset come first resulting tuple btw i actually accomplished various means including nested list comprehension seems like simplercleaner i surprised nothing itertools jumped though i one implementation w chain resulted tuple ints list can anyone provide clean solution one,1 as people said cannot save oneshot document object manytomany field django create intermediatary join table need document object id defined point there savemm function modelform supposed called form described doc however work maybe trick call savemm view function like def uploaddocumentrequest requestmethod post form documentformrequestpost requestfiles formisvalid newdocument formsave formsavemm return httpresponseredirectthanks else form documentform return rendertoresponse uploadpagehtml form form contextinstancerequestcontextrequest hope helps stã©phane,i set document objects label objects i want two objects linked it typical manytomany relationship i following code modelspy class documentmodelsmodel title modelscharfieldmaxlength uniquetrue titleslug modelsslugfieldmaxlength uniquetrue editablefalse labels modelsmanytomanyfield label def saveself args kwargs selftitleslug slugifyselftitle superdocument selfsaveargs kwargs class labelmodelsmodel name modelscharfieldmaxlength uniquetrue slug modelsslugfieldmaxlength uniquetrue editablefalse def saveself args kwargs selfslug slugifyselfname superdocument selfsaveargs kwargs viewspy class documentformmodelform class meta model document fields titlelabels def uploaddocumentrequest requestmethod post form documentformrequestpost requestfiles formisvalid newdocument formsave return httpresponseredirectthanks else form documentform return rendertoresponse uploadpagehtml form form contextinstancerequestcontextrequest when i upload document gets added database however labels created associated document do i need explicitly add something document save function make happen or somewhere viewspy file i imagine go something like check see label added already exists if create new label grab current documentid newexisting labelid add record documentlabels table automatically created manytomany relationship i feel like pretty standard functionality i assumed would built manytomany relationship django seem working far i trying avoid reinventing wheel somewhat new django thanks advance,2 i think easy resolve understande forms fomsfactory django maybe doc help httpsdocsdjangoprojectcomentopicsformsmodelformsinlineformsets,i set document objects label objects i want two objects linked it typical manytomany relationship i following code modelspy class documentmodelsmodel title modelscharfieldmaxlength uniquetrue titleslug modelsslugfieldmaxlength uniquetrue editablefalse labels modelsmanytomanyfield label def saveself args kwargs selftitleslug slugifyselftitle superdocument selfsaveargs kwargs class labelmodelsmodel name modelscharfieldmaxlength uniquetrue slug modelsslugfieldmaxlength uniquetrue editablefalse def saveself args kwargs selfslug slugifyselfname superdocument selfsaveargs kwargs viewspy class documentformmodelform class meta model document fields titlelabels def uploaddocumentrequest requestmethod post form documentformrequestpost requestfiles formisvalid newdocument formsave return httpresponseredirectthanks else form documentform return rendertoresponse uploadpagehtml form form contextinstancerequestcontextrequest when i upload document gets added database however labels created associated document do i need explicitly add something document save function make happen or somewhere viewspy file i imagine go something like check see label added already exists if create new label grab current documentid newexisting labelid add record documentlabels table automatically created manytomany relationship i feel like pretty standard functionality i assumed would built manytomany relationship django seem working far i trying avoid reinventing wheel somewhat new django thanks advance,1 why concerns webpy performance as i mentioned use cherrypy web server built webpy behind nginx serve html oystercom nginx splits traffic across web servers running python processes easily handle requests per second oystercom highvolume website averaging dynamicallygenerated pageviewsday peaking much higher numbers however use content delivery network cdn static resources like images css we definitely care performance pages render less ms webpy bottleneck our bottlenecks template rendering use cheetah fast enough otherworldly fast database queries cache heavily keep number database queries per page accessing rdparty hotel pricing providers accessed search dates already cached remember premature optimization root evil unless serving googlecom webpy probably work,i know various frameworks benefits i personally want web development python straightforward possible less writing framework writing python the thing i found far lets obvious way possible webpy i slight concerns performance for using nginxor another flavourmodwsgiwebpy performance can improved for used webpy liked idea went write something better found something better care point source i like hear conspicuous minimal yet powerful approaches,1 i try existing applications general boils following steps get uimanager gobjectpropertytypegeditwindowgetuimanager acquire current ui definition using uimanagergetui use determine item remove retrieve item using buildergetobject using name found ui definition i sure menu retrieved item probably simply call destroy alternatively might get main menu item remove child want getchildren method ie menugetchildren menuremovei child want get rid probably inspect know one remove finally explicitly refresh ui uimanagerensureupdate as said i try i linux installation nearby verify i hope gives enough pointers reach solution,i developed plugin replace functionality gedit this functionality presented one menu item how could i remove current menu item add identical new one except new menu item bound callback,1 i really answering question directly i help asking using incr method atomically incrementing value maybe posted example kind misleading question,related question i trying implement counter increment memcached using memcache’s compare set can someone review code potential loopholes def incrementid client getcache memcache items counter clientcachegetsid counter none items clientcachecasid counter items break else items clientcacheaddid items break return items additionally since i using internal memcached api available django append key prefix i set settings if i append key internal api call memcache backend djangocorecachebackendsmemcachedmemcachedcache location keyprefix store,2 third times charm my guess bug zhenya answer suggests fixed latest version i version i created following solution import matplotlibpyplot plt import numpy np def forceaspectaxaspect im axgetimages extent imgetextent axsetaspectabsextentextentextentextentaspect data nprandomrand fig pltfigure ax figaddsubplot aximshowdata axsetxlabel xlabel axsetaspect figsavefig equalpng axsetaspect auto figsavefig autopng forceaspectaxaspect figsavefig forcepng this forcepng below unsuccessful yet hopefully informative attempts second answer my original answer overkill something similar axessetaspect i think want use axessetaspect auto i understand case produces square image plot example script import matplotlibpyplot plt import numpy np data nprandomrand fig pltfigure ax figaddsubplot aximshowdata axsetaspect equal figsavefig equalpng axsetaspect auto figsavefig autopng produces image plot equal aspect ratio one auto aspect ratio the code provided original answer provides starting point explicitly controlled aspect ratio seems ignored imshow called original answer here example routine adjust subplot parameters get desired aspect ratio import matplotlibpyplot plt def adjustfigaspectfigaspect adjust subplot parameters figure correct aspect ratio xsizeysize figgetsizeinches minsize minxsizeysize xlim minsizexsize ylim minsizeysize aspect xlim aspect else ylim aspect figsubplotsadjustleftxlim rightxlim bottomylim topylim fig pltfigure adjustfigaspectfigaspect ax figaddsubplot axplotrangerange figsavefig axaspectpng this produces figure like i imagine multiple subplots within figure would want include number x subplots keyword parameters defaulting routine provided then using numbers hspace wspace keywords make subplots correct aspect ratio,i trying make square plot using imshow ie aspect ratio i none work import matplotlibpyplot plt ax figaddsubplotaspect equal ax figaddsubplotaspect axsetaspect equal pltaxessetaspect equal any ideas let know need info eg details calls it seems like calls ignored problem i often seem matplotlib thanks,3 the designers arparse apparently felt would convenient access arguments argsargname rather argsargname this might matter taste though i would happily gone dictionary especially given fact namespace class standard library except one argparse use dictionary if really want namespace use initfunctionargsdict …but i recommend,this really questions is reason argparse uses namespace instead dictionary assuming i class initself initmethod args the initmethod parameter tells initfunction way i want initialize class arg parameter gives arguments neccesary init the arguments may different different methods should i use dictionary namespace assuming i use namespace i pass namespace init,3 following suggestion joe kington i found following modification easy baraxyaxissetlabelposition right baraxsetylabel yourlabel rotation horizontal,i want make contourplot horizontal colorbar the bar labels scientific notation everything goes well code however i want change position multiplicator specifying scientific scale i think called offset string axis does anybody know i want place multiplicator right colorbar would additional label httpmatplotlibsourceforgenetexamplespylabexamplesgriddatademohtml numpyrandom import uniform seed matplotlibmlab import griddata import matplotlibpyplot plt import matplotlibticker import numpy np matplotlib import rcparams matplotlib import rc make data seed npts x uniformnpts uniformnpts z xnpexpxy define grid xi nplinspace yi nplinspace grid data zi griddataxyzxiyiinterp linear rcparams axesformatterlimits pltfigure cs pltcontourxiyizicmappltcmjet bar pltcolorbarorientation horizontal draw colorbar plot data points pltxlim pltylim plttitle griddata test points npts pltshow,1 you use rolling window iterator case one old version itertools docs itertools import islice def windowseq n returns sliding window width n data iterable sssn sssn iterseq result tupleisliceit n lenresult n yield result elem result result elem yield result def doessegmentexistiterable sublist return tuplesublist windowiterable lensublist printdoessegmentexist if need work lists iterable use def doessegmentexistseq sublist seq sublist must lists n lensublist return sublist seqiin rangelenseq n a basic implementation method mentioned raymond def doessegmentexistseq sublist first sublist n lensublist true try seqindexfirst except valueerror return false sublist seqiin return true printdoessegmentexist the advantage method slice every index first match indexes corresponding matches first value segment,i list values i want following function doessegmentexista true doessegmentexista true doessegmentexista true doessegmentexista false doessegmentexista true doessegmentexista false so values must found consecutive order i clever way python,2 it easy convert namespace dictionary using vars varsargs,this really questions is reason argparse uses namespace instead dictionary assuming i class initself initmethod args the initmethod parameter tells initfunction way i want initialize class arg parameter gives arguments neccesary init the arguments may different different methods should i use dictionary namespace assuming i use namespace i pass namespace init,3 my recomendation def purgedir pattern inclusivetrue regexobj recompilepattern root dirs files oswalkdir topdownfalse name files path ospathjoinroot name boolregexobjsearchpath boolinclusive osremovepath name dirs path ospathjoinroot name lenoslistdirpath osrmdirpath this recursively remove every file matches pattern default every file inclusive true it remove empty folders directory tree,i made online gallery using python django i started add editing functionality starting rotation i use sorlthumbnail autogenerate thumbnails demand when i edit original file i need clean thumbnails new ones generated there three four per image i different ones different occasions i could hardcode filevarients but messy i change way i things i need revisit code ideally i like regexdelete in regex terms originals named like pphotoiddjpg so i want delete pphotoidddjpg where i replace photoid id i want clean,1 hmmm i guess related previous question memory error dealing huge data my suggestion seem work cumulative histogram i get plthist play nice cyborg suggestion i cumsum normalisation hand future import division import numpy np import matplotlibpyplot plt numpyrandom import normal inp npabsnormal bins range ab nphistograminp bins bins baredges b barwidth b b barheight npcumsuma suminpminbins leninp pltfigure pltbarbaredges barheight width barwidth pltshow,i problem dealing data set value range tens thousand and problem show histogram whole data set using hist however i want show cumulative normed detailed histogram using say x i use bins assure detail the tricky problem i use range show normed cumulative hist end but actually far less real since normed within small range data could anyone ideas utilize hist matplotlib tackle problem i thought complicated i write another function draw hist i need,1 you also use callable default field b modelscharfieldmaxlength defaultfoo and define callable def foo return bar,suppose i model class somemodelmodelsmodel id modelsautofieldprimarykeytrue modelscharfieldmaxlength b modelscharfieldmaxlength currently i using default admin createedit objects type how i remove field b admin object cannot created value rather receive default value,3 there many ways isomorphic substring search algorithms the easiest way naã¯ve search using listindex find common start point using slice check full match if match repeat search hit end list,i list values i want following function doessegmentexista true doessegmentexista true doessegmentexista true doessegmentexista false doessegmentexista true doessegmentexista false so values must found consecutive order i clever way python,1 in latest version scrapy available github raise closespider exception manually close spider in release note doc mentioned added closespider exception manually close spiders r example per docs def parsepageself response bandwidth exceeded responsebody raise closespider bandwidthexceeded see also httpreadthedocsorgdocsscrapyenlatesttopicsexceptionshtmlhighlightclosespider,chance stop crawling specific condition true like scrapitemid predefinevalue my problem similar scrapy identify already scraped urls i want force scrapy spider stop crawling discover last scraped item,3 the issue paste per se neoj python bindings use jpype paste creates threads handle incoming requests neoj supposed threadsafe jpype comes caveat documentation for part python threads based os level threads ie posix threads work without problem the thing remember call jpypeattachthreadtojvm thread body make jvm usable thread for threads start call isthreadattachedtojvm check i find code i think java code neoj bindings may call attachthreadtojvm import time if request handed worker thread paste thread goes fetch data neoj crossing thread boundaries jvm attachment rule may satisfied you avoid crash running import neoj within single thread in case callable targeted threadingthread unfortunately means even though neoj threadsafe must constrained single thread used python but disappointing considering update maintainers responded investigated problem checked fix i know release neoj available i longer find commit github repo stands retesting,the following code causes java segfault import ospath import neoj paste import httpserver fileapp import tempfile webobdec import wsgify webob import response request host port class debugappobject wsgify def callself req db neojgraphdatabasetempfilemkdtemp db neojgraphdatabaseospathjoinospathdirnameospathabspathfile data return responsebody worked def main app debugapp httpserverserveapp hosthost portport name main main to reproduce first save code file say apppy run python apppy then try httplocalhost browser see java crash handler the top java stack trace looks like stack xbexbae spxbaef free spacek native frames jcompiled java code jinterpreted vvvm code cnative code c jpypesox jpjavaenvnewobjectajclass jmethodid jvaluex c jpypesoxce jpmethodoverloadinvokeconstructorjclass stdvectorhostref stdallocatorhostref ampx c jpypesoxa jpmethodinvokeconstructorstdvectorhostref stdallocatorhostref ampx c jpypesoxbeba jpclassnewinstancestdvectorhostref stdallocatorhostref ampxa c jpypesoxbc pyjpclassnewclassinstanceobject objectxfc c pythonx pyevalevalframeexx c pythonxe pyevalevalcodeexx i believe neojgraphdatabase python triggering jpype go looking embeddedgraphdatabase neoj java running code interactive python session segfault import webob import app debugapp appdebugapp response debugappwebobrequestblank responsebody worked presumably i avoiding paste altogether example perhaps something paste use threads getting way neoj i noted somewhat similar problem neoj forums httpneojcommunitydiscussionsnnabblecomneojcpythonpylonsandthreadingtdhtml occurs shutdown,2 this work python newer def doessegmentexistsequence segment n lensequence lensegment return anysegment sequenceiim rangenm,i list values i want following function doessegmentexista true doessegmentexista true doessegmentexista true doessegmentexista false doessegmentexista true doessegmentexista false so values must found consecutive order i clever way python,1 what matplotlib version running i recently upgrade addsubplotaspect equal works,i trying make square plot using imshow ie aspect ratio i none work import matplotlibpyplot plt ax figaddsubplotaspect equal ax figaddsubplotaspect axsetaspect equal pltaxessetaspect equal any ideas let know need info eg details calls it seems like calls ignored problem i often seem matplotlib thanks,3 yes number less string including empty string python in python make arbitrary comparisons you get typeerror from link eryksun comment pynumbercheckv vname else vname vobtypetpname pynumbercheckw wname else wname wobtypetpname c strcmpvname wname so least recent versions cpython x type names compared empty string used instead type name numeric type,why return true python is i place single quotes around number python sees string strings bigger numbers,3 from python v documentation objects different types except numbers ordered type names objects types don’t support proper comparison ordered address when order two strings two numeric types ordering done expected way lexicographic ordering string numeric ordering integers when order string integer type names ordered str lexicographically int float long list bool etc however tuple order higher string tuple str hi false hi false hi true also see comparison uses lexicographical ordering docspythonorg in python x behaviour changed attempting order integer string raise error traceback recent call last file line typeerror unorderable types str int,why return true python is i place single quotes around number python sees string strings bigger numbers,3 the thing stops using urlopen directly file object fact builtin file object lacks len definition a simple way create subclass provides urlopen correct file i also modified contenttype header file import os import urllib class enhancedfilefile def initself args keyws fileinitself args keyws def lenself return intosfstatselffileno thefile enhancedfile axml r theurl httpexamplecomabcde theheaders contenttype textxml therequest urllibrequesttheurl thefile theheaders response urlliburlopentherequest thefileclose line response print line,is way send file using post python script,2 you strip unwanted characters beginning end string using strstrip method abcd strip abcd blahblah strip blahblah print abcd strip abcd print blahblah strip blahblah,can anyone help following query pythonic way cleanse following strings lets say i word abcd blahblah words actually abcd blahblah i think basic way actually i reading huge text file explicitly writing code read char char seems like overkill definitely pythonic i sure pythonic way thanks,1 they dictionary order first letter thing matters to want use valuesumordx x name,i studying upcoming assignment trying figure following program prints bob tom george susan mary n rawinputenter name assume user enters robert name name n print name print size len size di di temp di di di di temp else di nick name print name i confused i run program returns enter name robert bob george mary bob george nick mary nick i clearly confused calculate value words i thought assigned ascii value individual letters added together get value using method would get results could someone please help understand,3 devserversplit returns list seeing error trying concatenate string list you could try instead p subprocesspopen psftp devserver stdinsubprocesspipe stdoutsubprocesspipe shelltrue split longer needed since already cmd args seperate strings,i snippet code works p subprocesspopen psftp servername splitstdinsubprocesspipe tdoutsubprocesspipe shelltrue pstdinwrite lcd poracleunixdevelopmentn pstdinwrite get optjbosscurrentserverdefaultconfdmspropertiesn pstdinwrite byen pstdoutclose pstdinclose but i variable set i refer server parts devserv servername p subprocesspopen psftp devservsplitstdinsubprocesspipe stdoutsubprocesspipe shelltrue pstdinwrite lcd poracleunixdevelopmentn pstdinwrite get optjbosscurrentserverdefaultconfdmspropertiesn pstdinwrite byen pstdoutclose pstdinclose i always get typeerror cannot concatenate str list objects why,1 i think need replace psftp devservsplit psftp devservsplit you need build string first call split completed string,i snippet code works p subprocesspopen psftp servername splitstdinsubprocesspipe tdoutsubprocesspipe shelltrue pstdinwrite lcd poracleunixdevelopmentn pstdinwrite get optjbosscurrentserverdefaultconfdmspropertiesn pstdinwrite byen pstdoutclose pstdinclose but i variable set i refer server parts devserv servername p subprocesspopen psftp devservsplitstdinsubprocesspipe stdoutsubprocesspipe shelltrue pstdinwrite lcd poracleunixdevelopmentn pstdinwrite get optjbosscurrentserverdefaultconfdmspropertiesn pstdinwrite byen pstdoutclose pstdinclose i always get typeerror cannot concatenate str list objects why,1 it right way time filtering just use reverse much optimized manually,does python means foreach backwards i hoping filter list comprehension reverse list time i avoid separately i suspect slower i using python i unfortunately i also curious list comprehension solution would python edit both solutions appear python timeit x filterlambda x x reversedx loops best usec per loop python timeit x xreverse filterlambda x x x loops best usec per loop,1 you looking builtin reversed reversedrange print this iterates sequence reverse without creating additional copy list,does python means foreach backwards i hoping filter list comprehension reverse list time i avoid separately i suspect slower i using python i unfortunately i also curious list comprehension solution would python edit both solutions appear python timeit x filterlambda x x reversedx loops best usec per loop python timeit x xreverse filterlambda x x x loops best usec per loop,3 looks like want alphabetical characters word import regex r w word characters read input split input space get words word listofwords word resubregex word,can anyone help following query pythonic way cleanse following strings lets say i word abcd blahblah words actually abcd blahblah i think basic way actually i reading huge text file explicitly writing code read char char seems like overkill definitely pythonic i sure pythonic way thanks,1 you using totalm vars never resetting loop they automatically reset new iteration started fwiw try optimize code you generating lenplans queries could rather costly,i small issue annotatesum function now i want show total maturities given plan inside list which first one code get invesments maturing year p plans curinv investmentobjectsallfilterplan porderby financialinstitution filtermaturitydateyear currentyear nxtinv investmentobjectsallfilterplan porderby financialinstitution filtermaturitydateyear nextyr thrinv investmentobjectsallfilterplan porderby financialinstitution filtermaturitydateyear thryr frinv investmentobjectsallfilterplan porderby financialinstitution filtermaturitydateyear fryr fvinv investmentobjectsallfilterplan porderby financialinstitution filtermaturitydateyear fvyr inv curinv total invamount inv curinv totalm invmaturityamount inv nxtinv total invamount inv nxtinv totalm invmaturityamount inv thrinv total invamount inv thrinv totalm invmaturityamount inv frinv total invamount inv frinv totalm invmaturityamount inv fvinv total invamount inv fvinv totalm invmaturityamount calculate holding totals company totallist pinvestmentsetfiltermaturitydategte currentyearvalues financialinstitutionabbr annotatesum maturityamount orderby financialinstitutionabbr gtotal totalm totalm totalm totalm totalm planlistappend plan p investment curinv nxtinv nxtinv thrinv thrinv frinv frinv fvinv fvinv totallist totallist grand gtotal my issue goes next plan continues add grand total instead going back am i missing something any help would appreciated thanks,1 the gmpy library calculate hamming distance two integers even though may general require faster calling code via ctypes disclaimer i maintain gmpy,here sample code efficiently find binary strings low hamming distance large set static inline int distanceunsigned x unsigned return builtinpopcountxy is possible rewrite gcc code python using ctypes preferably winnix compatible tia,1 slap setcookie routine import datetime import cookie def setcookieself name value expiresnone set cookie value none value deleted expires datetimetimedeltaminutes jar cookiesimplecookie jarname value jarname path u expires isinstanceexpires datetimetimedelta expires datetimedatetimenow expires isinstanceexpires datetimedatetime expires expiresstrftime b y hms jarname expires expires selfresponseheadersaddheaderjaroutputsplitu you call function setcookie mycookie thingsyouwanttoaddinthecookie setcookie dcookie onlyoneday datetimetimedeltaminutes,i using google app engine how i set either multiple cookies multivalue cookie single response right i using code url httplocalhostservershowcookieemailaddressmyemailgmailcomampsecretcode c cookiesimplecookie cemailaddress selfrequestget emailaddress csecretcode selfrequestget secretcode csecretcodepath headervalue coutputheader selfresponseheadersaddheadersetcookie headervalue work value headervalue emailaddressmyemailgmailcom secretcode path well formed header missing comma how i create well formed cookie values,1 here good compilation things could achieve backward iteration httpchristophesimonisattinyblogspotcompythonreverseenumeratehtml,does python means foreach backwards i hoping filter list comprehension reverse list time i avoid separately i suspect slower i using python i unfortunately i also curious list comprehension solution would python edit both solutions appear python timeit x filterlambda x x reversedx loops best usec per loop python timeit x xreverse filterlambda x x x loops best usec per loop,1 usually never parse html regular expressions since html regular language here seems want get httplinks either a element text how getting remove duplicates try something like setrefindallhttp content see serves purpose,i seen questions parse either plain links anchor tags string nothing ideally regular expression able parse string like i using python import content hrefhttpwwwgooglecomhttpwwwgooglecoma some text and even text httpstackoverflowcom links refindall someregularexpression content print links u httpwwwgooglecom u httpstackoverflowcom is possible produce regular expression would result duplicate links returned is better way,1 have look class based views new you write views classes inherit necessary funcionality multiple base views also mixins this means break views constituant parts nice code separation httpsdocsdjangoprojectcomendevtopicsclassbasedviews furthermore mixins made particularly dealing forms httpsdocsdjangoprojectcomendevrefclassbasedviewsformmixin they take bit reading make i really like implementation looks like good approach overcoming problems mentioned,just shot dark maybe someone able suggest something interesting whenever i forms view lot ifelse statements hard follow logic is pattern python language feature simplify i problem long i remember found good solution day here example view renders page errors good search model returns page graphs def analysisrequest context mainnavigation analysis context noresults false template analysisanalysishtml search params requestget form analysissearchform context form form else form analysissearchformrequestget context form form formisvalid do search results formsearch lenresults context results jsondumpsresults defaultencode contextupdateformcleaneddata add compare form context compareform compareform add critical level one part formcleaneddataget part none part level levelgetpart default level none context level levelvalue template analysisanalysisgraphshtml else context noresults true return rendertoresponsetemplate context contextinstancerequestcontextrequest as see already simplified moving querying logic formsearch method uses form cleaneddata case contact remote api fetch results,1 you wrong first characters matched differently ab match either b case pibstrong match everything p b etc note negation your first regex matching merely coincidence also parsing htmlxml regex instead use proper xml parsing library like lxml beautifulsoup here simple example lxml lxml import html dom htmlfromstringyourcode illegal setdomcssselect setdomcssselect pb tag illegal dosomethingwithtag small probably suboptimal example serves show easy use library also note library wrap code p take consideration,for reason research pibstrongbrpibstrong b matches string research pibstrong b i trying match tags p b p b am i misunderstanding something works,1 to get modeless dialog open show rather exec to ensure dialog locked parent app set parent window dialog constructor pyqt import qtgui class windowqtguiqwidget def initself qtguiqwidgetinitself button qtguiqpushbutton open dialog self buttonclickedconnectselfhandleopendialog selfresize selfdialog none def handleopendialogself selfdialog none selfdialog qtguiqdialogself selfdialogresize selfdialogshow name main import sys app qtguiqapplicationsysargv win window winshow sysexitappexec,it difficult describe i want i want click button pops dialog this dialog however nonmodal i also like sort locked parent app i moved would come it seems like less trying describe inline popup i sure called even i go approaching problem so pyqt gurus would make something like thanks advance,1 no matter going messy nevertheless solution might resemble r asabw trnxcxa trnxcxa since pattern two groups return list tuples join could use list comprehension even map map join refindallpattern content if want src attribute anchor instead link text pattern gets even messier r assrc abw trnxcxa trnxcxa alternatively let second half pattern pick src attribute also alleviates need string join r bw trnxcxa trnxcxa once much place replace found links something look like link search update pattern collect missed you may also clean false positives particularly garbage end this pattern find links included spaces plain text particularly prone excess greediness warning do rely future user input particularly security line it best used manually collecting links existing data,i seen questions parse either plain links anchor tags string nothing ideally regular expression able parse string like i using python import content hrefhttpwwwgooglecomhttpwwwgooglecoma some text and even text httpstackoverflowcom links refindall someregularexpression content print links u httpwwwgooglecom u httpstackoverflowcom is possible produce regular expression would result duplicate links returned is better way,1 in python could use ordereddict import collections import itertools foocollectionsordereddict b c keyvalue itertoolsdropwhilelambda x x b fooiteritems printkeyvalue yields b c for python less could use ordereddict recipe,something i miss c stdmap sorted dictionary looking key returns iterator pointing correct location map this means lookup key start iterating eg key actually beginning range interested wanted item dictionary key is python dict supports kind functionality,1 total line infile line linestripn linestartswith name line else pattern linecount p total pattern print ss namepattern goes outside loop outwrite ssn nametotal,i text file follows mpprrsivevkvldvqkrrvpnkhyvyiirvtwssgateaiyrryskffdlqmqmldkfp meggqkdpkqriipflpgkilfrrshirdvavkrlipideyckaliqlppyisqcdevlq ffetrpedlnppkeehigkkksgndptsvdpmvleqyvvvadyqkqesseislsvgqvvd maevrkftkrlskpgtaaelrqsvseavrgsvvlekaklvepldyenvitqrktqiysdp lrdllmfpmedisisvigrqrrtvqstvpedaekraqslfvkeciktystdwhvvnykye dfsgdfrmlpckslrpekipnhvfeidedcekdedssslcsqkggvikqgwlhkanvnst i wanted count letter p sequences output to acheive python script follows infileopenfiletxt r outopenfilecsv w line infile line linestripn linestartswith nameline else pattern linecount p print ss namepattern outwrite ssn namepattern read line gives result follows but except put follows can body help thanks advance ni,1 don parse file line line just iterate entire file character character counting occurrances character looking,i text file follows mpprrsivevkvldvqkrrvpnkhyvyiirvtwssgateaiyrryskffdlqmqmldkfp meggqkdpkqriipflpgkilfrrshirdvavkrlipideyckaliqlppyisqcdevlq ffetrpedlnppkeehigkkksgndptsvdpmvleqyvvvadyqkqesseislsvgqvvd maevrkftkrlskpgtaaelrqsvseavrgsvvlekaklvepldyenvitqrktqiysdp lrdllmfpmedisisvigrqrrtvqstvpedaekraqslfvkeciktystdwhvvnykye dfsgdfrmlpckslrpekipnhvfeidedcekdedssslcsqkggvikqgwlhkanvnst i wanted count letter p sequences output to acheive python script follows infileopenfiletxt r outopenfilecsv w line infile line linestripn linestartswith nameline else pattern linecount p print ss namepattern outwrite ssn namepattern read line gives result follows but except put follows can body help thanks advance ni,1 edit for new questions i would use pubsub solve put listener init mydialog class publish message validate method run class in message handler theoretically create mydialog want show widget call layout dialog that cause resize appropriately you read tutorial pubsub httpwwwblogpythonlibraryorgwxpythonandpubsubasimpletutorial the following original question your validate method ever fire i rearranged validate onchar methods look like following import string def validateself win enter code return true def oncharself event txtobj eventgeteventobject txt txtobjgetvalue txt txt key chreventgetkeycode key stringdigits inttxtstrkey eventskip else msg you entered age greater wxmessageboxmsg improbable entry stylewxokwxiconerror problem arises here mydialogagewarningstshow mydialogmainsizerfitmydialog return false key eventgetkeycode key inwxwxkreturn wxwxkdelete wxwxkback eventskip elif chrkeyisdigit eventskip else return also note i imported string module makes things little easier the code probably needs clean worked machine,i working simple program collects checks userinput in addition displaying message box usersupplied input fails checks i also like add prompt right input field telling user type data required to accomplish i created singlerow flexgridsizer consisting following wxstatictext name wxtextctrl user inputs wxstatictext input guidance on initialization input guidance widget hidden if user fails enter anything provided field hits ok button i want three things happen field changes colour alert user problem the input guidance widget third row becomes visible the dialogbox automatically resized take account visible widget so far i get work looking help import wx class notemptywxpyvalidator def initself wxpyvalidatorinitself def cloneself return notempty def validateself win evtlocation selfgetwindow val evtlocationgetvalue val evtlocationsetbackgroundcolourwxcolor mydialognamewarningstshowtrue return false else return true def transfertowindowself return true def transferfromwindowself return true class mydialogwxdialog def initself wxdialoginitself parentnone id titlegetting input stylewxdefaultdialogstyle wxresizeborder create field labels name wxstatictextself name create userinput widgets nametc wxtextctrlself validatornotempty create hide warning boxes selfnamewarningst wxstatictextself labelfield cannot left empty nameemptyalert see i want dialog look like after user entered empty string change false true line selfnamewarningstshowfalse create acceptcancel buttons btns selfcreatebuttonsizerflagswxokwxcancel selfmainsizer wxboxsizerwxvertical fgs wxflexgridsizercols rows fgsaddmanyname wxall nametc wxall selfnamewarningst wxall selfmainsizeraddmanyfgs wxall btns wxallwxexpand selfsetsizerselfmainsizer selfmainsizerfitself name main app wxapp dlg mydialog dlgcenter dlgshowmodal dlgdestroy appmainloop,2 used ghex discover source file using carriage returns r instead newline n characters,i long string dna sequence n regular intervals i trying write file writing code i file cannot fully accessed getline c program istream seems think file dozen lines likewise i cat file i see dozen lines file however i open file editor like gedit whole file i resave i suddenly able read whole thing output openfilefasta w lines vseqsplit n tried outputwritevseq and line lines outputwriteline outputflush outputclose i obviously finishing file important way gedit ideas,1 python native ordereddict class collections module support operation advance forward key chosen random there implementations ordered dictionaries support operation one may meet needs httpdevpocooorghgsandboxrawfiletipodictpy httpbabeledgewallorgbrowsertrunkbabelutilpyrevl httpcodedjangoprojectcombrowserdjangotrunkdjangoutilsdatastructurespyrevl httpwwwvoidspaceorgukpythonodicthtml httpwwwxsallnlanthonpythonordereddict httppypipythonorgpypistabledict httpcodespeaknetsvnuserarigohackpyfuseordereddictpy,something i miss c stdmap sorted dictionary looking key returns iterator pointing correct location map this means lookup key start iterating eg key actually beginning range interested wanted item dictionary key is python dict supports kind functionality,2 this facebook oauth i actually able specify http site url callback url it took several minutes changes facebook app propagate worked,i building python application needs communicate oauth service provider the sp requires specify callback url specifying localhost obviously work i unable set public facing server any ideas besides paying serverhosting is even possible,1 qtexthtmlimporter even part qt api short answer way access pyqt you could course attempt port code pyqt i guessing would nontrivial task the question think need why use qtextcursorinserthtml qtextdocumentfragmentfromhtml edit here example set html text document without clearing undo history pyqt import qtgui qtcore class windowqtguiqwidget def initself qtguiqwidgetinitself layout qtguiqvboxlayoutself selfedit qtguiqtexteditself selfundo qtguiqpushbutton undo selfredo qtguiqpushbutton redo selfinsert qtguiqpushbutton set html layoutaddwidgetselfedit layoutaddwidgetselfundo layoutaddwidgetselfredo layoutaddwidgetselfinsert selfundoclickedconnectselfeditundo selfredoclickedconnectselfeditredo selfinsertclickedconnectselfhandleinsert selfeditappend one selfeditappend two selfeditappend three def handleinsertself cursor qtguiqtextcursorselfeditdocument cursorselectqtguiqtextcursordocument cursorinserthtmlpsome bhtmlb textp name main import sys app qtguiqapplicationsysargv win window winshow sysexitappexec,i writing cross platform app pyqt for particular feature i would like access qtexthtmlimporter class qt there direct python adapter class available pyqt the class part srcguitextqtextdocumentfragmentph file is way i access python i would like modify qtextdocumentsethtml code void qtextdocumentsethtmlconst qstring amphtml qdqtextdocument setundoredoenabledfalse dclear qtexthtmlimporterthis htmlimport setundoredoenabledtrue void qtextdocumentsethtmlconst qstring amphtml qdqtextdocument qtexthtmlimporterthis htmlimport basically setting html without clearing history i planned using derived class pyqt qtextdocument overriding sethtml function is way,1 you built two dictionaries using different types keys one dict integer key string key as mark byers said convert integer string lookup however i recommend instead build qdict integer keys wherever code builds qdict wrap key int force integer key either way work really but dmap int keys qdict str keys keys possible qdict cannot appear dmap two match better type key and int slightly efficient program scales large better choice,i trying retrieve values dictionary fairly easy for whatever reason i cannot use variable retrieve value i two dictionaries one mapping uids usernames via getent passwd second dictionary contains dictionary key basically dmap username qdict used grace none quota obviously many values dictionaries structure i shown basic concept they key qdict would uid mapped via dmap dictionary where i trouble following kv dmapitems print key k print qdictk when i run script i get traceback recent call last file testpy line main file testpy line main print qdictk keyerror if i comment print qdictk line print value k key names printed without issue i also reference dictionary outside loop actual keyname print dmap works print qdict works note below what i trying loop print dictionary given keyname kind printing dictionary dictionary what i think problem look note below line i need somehow present dictionary qdict properly formatted variable is something i missing easier way ps i also tried loop dmapkeys etc,1 method getattra method none getattra method none getattra method method this first look method method method the search stop soon one found if none methods found last getattr raise exception,is nicer way following try amethod except attributeerror try amethod except attributeerror try amethod except attributeerror raise it looks pretty nasty i rather hasattra method amethod else hasattra method amethod else hasattra method amethod else raise attributeerror maintain maximum efficiency,3 after much testing looking source sepfird help turns issue fact velx vely using bit floating point primitives needed bit that fixed,i attempting calculate derivatives optical flow referenced previous so question running typeerror performing calculation i first read video using opencv use optical flow methods find velocities then i use scipysignal library run gaussian filter velocities calculate derivatives cvcalcopticalflowlkprevframe currframe velx vely convert velx vely numpy arrays set gaussian filter derivative sigmablur sigmagrey gblursize nparound sigmablur x npmgridgblursize nparoundgblursize gfilt npexpx sigmablur gfilt npsumgfilt gxfilt x sigmablur gfilt now calculate derivative velocity res scipysignalsepfirdvelx gxfilt gfilt calls sepfird unfortunately call sepfird i get following error typeerror array cannot safely cast required type the documentation scipy website extremely sparse i find many examples use all three arguments sepfird numpy arrays velx matrix gxfilt gfilt vectors length case i think any thoughts type error occurring,1 there thing first n keys dict remember keys inserted first you get n keyvalue pairs though nitems taken diteritems this uses implementation take itertools recipes itertools import islice def taken iterable return first n items iterable list return listisliceiterable n see working online ideone,consider following dictionary b c i want return first n keyvalue pairs n case what efficient method,3 python dict ordered meaningless ask first n keys the collectionsordereddict class available need you could efficiently get first four elements import itertools import collections collectionsordereddict foo bar b c x itertoolsisliceditems key value x print key value itertoolsislice allows lazily take slice elements iterator if want result reusable need convert list something like x listitertoolsisliceditems,consider following dictionary b c i want return first n keyvalue pairs n case what efficient method,3 you mysql like substitute name table tablename update tablename set sluglowerreplace title this changes titles like this is a title slugs like thisisatitle edit to handle parentheses remove double spaces use update tablename set sluglower replace replace replace replace title,i table data is possible slug field automatically generated existing table or alternative thanks here table,1 see pep sorting dictionaries then use aforementioned iterable code if need efficiency sorted keyvalue pairs use different data structure that one maintains sorted order keyvalue associations eg import bisect kvlist b c e bisectinsortleftkvlist print kvlist b c e,consider following dictionary b c i want return first n keyvalue pairs n case what efficient method,1 using slugify template filter write script loop objects shell djangotemplatedefaultfilters import slugify obj mymodelobjectsall objslug slugifyobjtitle objsave,i table data is possible slug field automatically generated existing table or alternative thanks here table,3 it parameter function called avar hides global variable you call function afuncbvar argument value,the following program avar bvar evar def afuncavar print afunc avar avar bvar avar dvar avar print afunc bvar bvar print afunc dvar dvar print afunc evar evar return bvar cvar afuncbvar prints output afunc avar afunc bvar afunc dvar afunc evar i unsure afunc avar equal,1 your function takes avar parameter overrides global value since pass value bvar function sees avar,the following program avar bvar evar def afuncavar print afunc avar avar bvar avar dvar avar print afunc bvar bvar print afunc dvar dvar print afunc evar evar return bvar cvar afuncbvar prints output afunc avar afunc bvar afunc dvar afunc evar i unsure afunc avar equal,1 just pass dict constructorfunction it take iterable key value tuples create dictionary x l it l project management l creative l programming l sales l administration l av l human resources l conference rooms l testing l none dictx l it l project management l creative l programming l sales l administration l av l human resources l conference rooms l testing l none,so i got tuples inside tuples i would like turn key value pair l it l project management l creative l programming l sales l administration l av l human resources l conference rooms l testing l none how would i go,3 by calling dict tuple argument dictt,so i got tuples inside tuples i would like turn key value pair l it l project management l creative l programming l sales l administration l av l human resources l conference rooms l testing l none how would i go,1 i think python modules loaded i based chdir modules loaded folder started python shell folders pythonpath if want dynamically load modules maybe check imploadmodule sample bottom page,i trying learn python i trouble importing module i pyc file i trying import idle shell called dfapyc i file folder called xyz i navigate folder using oschdir usersxxxdesktopxyz so i try run command dfa import get error importerror no module named dfa if run command ospathisfile dfapyc returns true can someone explain get dfapyc file imported thanks,3 elementtree uses xpath subset selecting nodes within xml tree you use treefindall bar find bar nodes within tree,i used minidom library python but effbotorg elementtree library missing function getelementsbytagname bar getelementsbytagname finds children given name matter deep thus working recursively this usually good cause problems similar nodes exist multiple levels intervening nodes important source httpwikipythonorgmoinminidom does function also exist effbotorg elementtree library i looked docs find thanks advance best regards dan,3 i convenience model i use projects kinds things i think good example want djangotemplatedefaultfilters import slugify class nameandslugmodelsmodel convenience model things names name modelscharfieldmaxlength uniquetrue slug modelsslugfield def unicodeself return selfname def saveself args kwargs slugify name exist important check see slug dupe selfslug selfslug slugifyselfname supernameandslug selfsaveargs kwargs class meta abstract true,i table data is possible slug field automatically generated existing table or alternative thanks here table,2 you probably take look variable scoping understand things work way passedin parameters take precedence,the following program avar bvar evar def afuncavar print afunc avar avar bvar avar dvar avar print afunc bvar bvar print afunc dvar dvar print afunc evar evar return bvar cvar afuncbvar prints output afunc avar afunc bvar afunc dvar afunc evar i unsure afunc avar equal,1 add pythonpath code syspathappend newpath dfa import i believe changing current directory impact import process even i sure would want,i trying learn python i trouble importing module i pyc file i trying import idle shell called dfapyc i file folder called xyz i navigate folder using oschdir usersxxxdesktopxyz so i try run command dfa import get error importerror no module named dfa if run command ospathisfile dfapyc returns true can someone explain get dfapyc file imported thanks,3 no you must call next sequentially nontrivial generator next state determined current state def gennum j xrangenum j yield j there way parallelize calls generator without knowing state point yields value but knew need run,suppose i generator whose next function somewhat expensive i want try parallelize calls where i throw parallization to slightly concrete consider example fast splitting file example rawblocks b b blockgeneratorfin slow reading blocks checking values parsedblocks blockparserb b rawblocks get parsed blocks data structure data parsedblockstoordereddictparsedblocks the basic thing change nd line something parallelization is generator magic allows one unpack generator rd line parallel calling next parallel,2 assuming calls blockparserb performed parallel could try using multiprocessingpool import multiprocessing mp pool mppool rawblocks b b blockgeneratorfin parsedblocks poolimapblockparserrawblocks data parsedblockstoordereddictparsedblocks note if expect listparsedblocks fit entirely memory using poolmap much faster poolimap the items rawblocks return values blockparse must pickable since mppool transfers tasks results mpqueue,suppose i generator whose next function somewhat expensive i want try parallelize calls where i throw parallization to slightly concrete consider example fast splitting file example rawblocks b b blockgeneratorfin slow reading blocks checking values parsedblocks blockparserb b rawblocks get parsed blocks data structure data parsedblockstoordereddictparsedblocks the basic thing change nd line something parallelization is generator magic allows one unpack generator rd line parallel calling next parallel,1 have tried elementtree instead beautiful soup great pulling data html doubt but elementtree pretty much sets bar pythonic handling xml it since i needed i remember et anything untoward tag names,i attempting use beautiful stone soup bss modify existing xml casesensitive tag names when bss reads xml coerces tag names lower case i find easy way recover original capitalization pattern writing back file this causes problems downstream output xml longer validates schema schema expecting original capitalization is flag i set i first read tell bss treat tag names case sensitive,1 i suggest use binary search methodology select size value start large value one know large reduce half if faster reduce half if slower go next half interval continue hit best value,i writing file comparison function i know filecmpcmp dataset expected lot files i thought rather comparing potential match would better implement multifile comparison compare also since i new python i thought good learning exercise it seems going ok far fact inputs faster unix cmp actually little worried i quite believe possible therefore think maybe something wrong implementation so i code written i trying determine ideal chunk size read would part thinking data retrieved compared anyway i get memory one time better i wonder limitations python data structures may influence for example i maintaing potentially large lists chunks using dictionaries keys read chunks so i aware python builtin data structures may affect something determined hardware determined profiling particular machine reading back i realise clear question despite attempts i sure clarify i happy post code make things clearer bit longer average code sample bad though please comment clarification needed thanks update re sha i tested algorithm vs sha identical input files expected real data running times i realise thorough test results different enough worth commenting the computer load either test despite i said comments running target machine running one quite reasonable specs both tests potential run two threads sha occurred two threads two threads started mine due implementation one would used the single threaded sha version took much longer both tests read size chunk time three sets results given now i confused are comments sha right therefore indicative faulty implementation something else going sha real ms ms ms user ms ms ms sys ms ms ms mine real ms ms ms user ms ms ms sys ms ms ms,2 how sumlenval val dictionaryitervalues note uses generator instead creating temporary list lengths,i dictionary keys multiple values i trying count total number values for example key value abc bcd egf key value asjasfahafhsjhsafh total number values what pythonic way get count thanks,3 you want iterate keys values dictionary finding length set values the following uses list comprehension build list lengths takes sum sumlenvalue key value mydictiteritems if want efficient replace key value mydictiteritems value mydictitervalues use generator expression suggested cameron,i dictionary keys multiple values i trying count total number values for example key value abc bcd egf key value asjasfahafhsjhsafh total number values what pythonic way get count thanks,2 you something like access parameter value handler x selfrequestget x that populate value xvalue http get,i trying google appengine python today first time managed get simple example running it worked something wierd happening url parameter value changes registered unless i restart app in example i run httplocalhostxhello return x hello i change value x new value affect output i suspect kind internal caching going i sure googleappengineext import webapp googleappengineextwebapp import util import cgi form cgifieldstorage x formgetvalue x class mainhandlerwebapprequesthandler def getself x hello selfresponseoutwrite x hello else selfresponseoutwrite x hello def main application webappwsgiapplication mainhandler debugtrue utilrunwsgiappapplication name main main,1 if sure value dict list works sumlenval val ditervalues if bit care required probably bit info strings example also len count characters string you probably want strings count entry rather count proportional length if less readable version works sum isinstanceval basestring else lenval val ditervalues,i dictionary keys multiple values i trying count total number values for example key value abc bcd egf key value asjasfahafhsjhsafh total number values what pythonic way get count thanks,1 you follow instructions httpwwwpocketuniversecaarchivedecemberpilandaggdraw patch agg rather compiler allow bit incompatible code compile here one way could shell cd tmp svn co httpsvneffbotorgpublictagsaggdrawa cd aggdrawa patch p eof index aggincludeaggarrayh aggincludeaggarrayh revision aggincludeaggarrayh working copy intu ptr mbufptr ifalignment unsigned align alignment unsignedptr alignment alignment unsigned align alignment unsigned longptr alignment alignment size align ptr align ifsize mrest eof python setuppy buildext python selftestpy sudo python setuppy install,i trying install aggdraw python library create high quality graphics i keep getting error aggincludeaggarrayh in member function aggintu what workaround how i install,3 use filter technique described post though refers ip addresses easily use approach log unique request ids,i assigning unique id every incoming request want automatically included logs whenever logging done without explicitly including places i using middleware generate store unique id thread local i want modify django logging formatter include unique id directly logging formatters full format asctimes levelnames names messages how i add unique id component formatter without explicitly adding log statement,2 when call xsetter xgetter xdeleter creating new property object giving name function decorating so really matters last time use xer decorator class definition name actually want use but since would leave class namespace polluted incomplete versions property wish use best use name clean,i trying use newstyle properties declaration class cobject def initself selfx property def xself print getting return selfx xsetter def setxself value setting selfx value name main c c print cx cx print cx see following console pydev debugger starting getting file testpy line module cx attributeerror set attribute i wrong ps oldstyle declaration works fine,2 you use loop multiply digits instead hardcoding first second digits in pseudocode productsofar digitslefttomultipy number digits left multiply get next digit update produtssofar digitslefttomultiply also use n instead n range so couple comparisons instead sequential lookup takes time proportional length range,i trying make code following multiplying digits integer continuing process gives surprising result sequence products always arrives singledigit number for example the number products necessary reach singledigit number called persistence number integer thus persistence number persistence make program find twodigit number persistence greater i able come rough idea code seem work num num num numinputwhat number num range print step numnumnum num print step numnumnum elif numnum print step numnumnum elif numnum print step numnumnum elif numnum print step print num else break the program python i simply figure if someone could possibly help i would appreciate greatly,1 functions friends consider function getendsx passed integer x extract first digit last digit integers return result tuple form firstdigit lastdigit if x singledigit number tuple contain one element form x otherwise two a simple way turn number string extract firstlast digit string convert said strings back numbers however many ways make sure honor function contract stated hopefully function documentation then n current number finding persistence ends getendsn ends contains two elements n first element ends times second element ends ends getendsn terminates ends contained one element matter counting persistence for added points make sure appropriately nameddocumented function well consider use recursive function instead whileloop happy coding,i trying make code following multiplying digits integer continuing process gives surprising result sequence products always arrives singledigit number for example the number products necessary reach singledigit number called persistence number integer thus persistence number persistence make program find twodigit number persistence greater i able come rough idea code seem work num num num numinputwhat number num range print step numnumnum num print step numnumnum elif numnum print step numnumnum elif numnum print step numnumnum elif numnum print step print num else break the program python i simply figure if someone could possibly help i would appreciate greatly,1 this answer another question nice explanation going here summary the presence exec statement causes python compile f totally nonoptimized fashion locals dict instead array normally would the performance hit considerable,reading answer question what difference globals locals vars the following explanation given locals works locals called inside function constructs dictionary function namespace moment returns name assignments reflected returned dictionary assignments dictionary reflected actual local namespace in comment mentioned the part assignments dictionary reflected actual local namespace might worded bit definite linking following code def f exec pass localsx printx f this returns least cpython without line exec pass python throws nameerror find x this fits definition changes dictionary returned locals inside function reflected namespace why adding line exec pass allow changes reflected is somehow tricking python thinking excited function,2 you try pypdf httppybrarynetpypdf,i want shift pages existing pdf document right one inch three hole punched without hitting content the pdf documents already generated changing way generated possible it appears itext previous question what equivalent library way c python if platform dependent i need one would work linux update figured i would post little script i wrote case anyone else finds page needs working code thanks scott anderson suggestion rightshiftpy usrbinpython import sys import os pypdf import pdffilereader pdffilewriter sure default user space units guessed current document looking worked utoshift lensysargv print usage rightshift infile outfile sysexit ospathexistssysargv print exist sysargv sysexit pdfinput pdffilereaderfile sysargv rb pdfoutput pdffilewriter pagespdfinputgetnumpages rangepages p pdfinputgetpagei box pmediabox pcropbox pbleedbox ptrimbox partbox boxlowerleft boxgetlowerleftx utoshift boxgetlowerlefty boxupperright boxgetupperrightx utoshift boxgetupperrighty pdfoutputaddpage p outputstream filesysargv wb pdfoutputwriteoutputstream outputstreamclose,2 not full answer use latex pdfpages httpwwwctanorgtexarchivemacroslatexcontribpdfpages multiple commandline linux tools also use approach instance pdfjam uses httpwwwwarwickacukfacscistatisticsstaffacademicresearchfirthsoftwarepdfjam maybe pdfjam already provide need already,i want shift pages existing pdf document right one inch three hole punched without hitting content the pdf documents already generated changing way generated possible it appears itext previous question what equivalent library way c python if platform dependent i need one would work linux update figured i would post little script i wrote case anyone else finds page needs working code thanks scott anderson suggestion rightshiftpy usrbinpython import sys import os pypdf import pdffilereader pdffilewriter sure default user space units guessed current document looking worked utoshift lensysargv print usage rightshift infile outfile sysexit ospathexistssysargv print exist sysargv sysexit pdfinput pdffilereaderfile sysargv rb pdfoutput pdffilewriter pagespdfinputgetnumpages rangepages p pdfinputgetpagei box pmediabox pcropbox pbleedbox ptrimbox partbox boxlowerleft boxgetlowerleftx utoshift boxgetlowerlefty boxupperright boxgetupperrightx utoshift boxgetupperrighty pdfoutputaddpage p outputstream filesysargv wb pdfoutputwriteoutputstream outputstreamclose,1 probably relative reference css file try changing link relstylesheet typetextcss hrefmediastylecss link relstylesheet typetextcss hrefmediastylecss always look root mediastylecss,in django project mysterious least beinner outputs i understand working development environment i wanted base template includes stylesheet static media folderthis works farbut address httplocalhost urls template inherits base template now stylesheet httplocalhost looks niceif go httplocalhosthello included stylesheet whole html dom structure body doctype etc he somehow parses html site instead taking css file here code any ideas urlspy djangoviewsstatic import djangoconf import settings adminautodiscover urlpatterns patterns homeview hello hello r admin includeadminsiteurls useragent uadisplaygood r mediappath djangoviewsstaticserve viewspy djangohttp import httpresponse djangoshortcuts import rendertoresponse def hellorequest pagetitle hello world return rendertoresponse hellotpl pagetitle pagetitle def homeviewrequest pagetitle something return rendertoresponse hometpl pagetitle pagetitle def uadisplaygoodrequest try ua requestmeta remoteaddr except keyerror ua unknown return rendertoresponse basetpl ageone ua base template doctype html html langde meta namedescription contentmetadescription head link relstylesheet typetextcss hrefmediastylecss title block title pagetitle endblock title head body h block h ageone endblock h block content endblock block footer include footertpl endblock body html hello template extends basetpl block h home endblock block content welcome endblock,2 now set link css relative mediastylecss in home resolves mediastylecss hello resolves hellomediastylecss gives hello page just use absolute css link like mediastylecss,in django project mysterious least beinner outputs i understand working development environment i wanted base template includes stylesheet static media folderthis works farbut address httplocalhost urls template inherits base template now stylesheet httplocalhost looks niceif go httplocalhosthello included stylesheet whole html dom structure body doctype etc he somehow parses html site instead taking css file here code any ideas urlspy djangoviewsstatic import djangoconf import settings adminautodiscover urlpatterns patterns homeview hello hello r admin includeadminsiteurls useragent uadisplaygood r mediappath djangoviewsstaticserve viewspy djangohttp import httpresponse djangoshortcuts import rendertoresponse def hellorequest pagetitle hello world return rendertoresponse hellotpl pagetitle pagetitle def homeviewrequest pagetitle something return rendertoresponse hometpl pagetitle pagetitle def uadisplaygoodrequest try ua requestmeta remoteaddr except keyerror ua unknown return rendertoresponse basetpl ageone ua base template doctype html html langde meta namedescription contentmetadescription head link relstylesheet typetextcss hrefmediastylecss title block title pagetitle endblock title head body h block h ageone endblock h block content endblock block footer include footertpl endblock body html hello template extends basetpl block h home endblock block content welcome endblock,1 i confirm pypdf really good solution problem,i want shift pages existing pdf document right one inch three hole punched without hitting content the pdf documents already generated changing way generated possible it appears itext previous question what equivalent library way c python if platform dependent i need one would work linux update figured i would post little script i wrote case anyone else finds page needs working code thanks scott anderson suggestion rightshiftpy usrbinpython import sys import os pypdf import pdffilereader pdffilewriter sure default user space units guessed current document looking worked utoshift lensysargv print usage rightshift infile outfile sysexit ospathexistssysargv print exist sysargv sysexit pdfinput pdffilereaderfile sysargv rb pdfoutput pdffilewriter pagespdfinputgetnumpages rangepages p pdfinputgetpagei box pmediabox pcropbox pbleedbox ptrimbox partbox boxlowerleft boxgetlowerleftx utoshift boxgetlowerlefty boxupperright boxgetupperrightx utoshift boxgetupperrighty pdfoutputaddpage p outputstream filesysargv wb pdfoutputwriteoutputstream outputstreamclose,2 this somewhat famous question well answered famous pythonista long ago httpcodeactivestatecomrecipesremoveduplicatesfromasequence if assume equal records adjacent recipe itertools docs operator import itemgetter itertools import groupby imap def uniquejustseeniterable keynone list unique elements preserving order remember element seen uniquejustseen aaaabbbccdaabbb a b c d a b uniquejustseen abbccad strlower a b c a d return imapnext imapitemgetter groupbyiterable key if assume orderable elements variant using bisect module given n inputs r unique values search step costs on log r if new unique value found inserted seen list cost or r bisect import bisectleft insort def dedupseq remove duplicates preserve order first seen assume orderable hashable elements result seen x seq bisectleftseen x lenseen seeni x seeninserti x resultappendx return result,i datastructure like a b a b a c and i want obtain a b a c is good way preserving order shown commands copypasting sample sampleappend a b sampleappend a b sampleappend a c,3 pipe string command eg echo python setuppy install,i like bypass do want continue yn default n prompt via shell script i tried python setuppy install force python setuppy install wait work anyone ideas,3 if question displayed multiple times yes command however also aknowledge questions if want something sophisticated look expect,i like bypass do want continue yn default n prompt via shell script i tried python setuppy install force python setuppy install wait work anyone ideas,3 my reading list objects operation documentation suggests objects always listed alphabetical order object key if encode creation time object object key may able achieve want,i need download every hour newest files server bucketlist bucketlistprefix the code creates list files depend uploading time files since lists file name i nothing file name it given randomly thanks,1 i similar problem empty requestpost django due bug html i form actionfoo urlspy mapped foo view i expecting post data getting none django kindly serverside redirects requests foo foo post data resubmitted foo part deal in hindsight seems quite sensible changing form actionfoo fixed i suppose changing urlspy could worked,the following code works fine django fails django requestpost empty although form data posted correctly server def commitformrequest loggingdebugstrdatetimedatetimenow commit data requestrawpostdata purchase purchaseobjectsgettransactionidrequestpost transactionid breaks requestpost empty stuff return httpresponsegood mimetypetextplain why work i see error,1 here orderpreserving variant sortunique idiom this give on log n performance provided items least sortable def uniquea indices sortedrangelena keyagetitem indices setnextit k itertoolsgroupbyindices keyagetitem return x x enumeratea indices example hashable items simplicity f j b f v a e u b u z k uniquea f j b v a e u z k,i datastructure like a b a b a c and i want obtain a b a c is good way preserving order shown commands copypasting sample sampleappend a b sampleappend a b sampleappend a c,2 that one scenarios show weakness django configuration module settings there django supported way i think could choose go option minimal impact code maintenance portability so i suggest use middleware keep users configuration data structure django supported make settingsdatabase callable fetch users configuration django hack use django multiple database feature access models django supported,the scenario we two applications theapp theapp incredible app customers love each customer gets instance application means customer use different database nameuserpassword the database connection decided domain request comes req customerafootld dbappcust cust hunter req customerbfootld dbappcust cust hunter administration application should able createdelete theapp instances customers therefore setup new database write config somewhere the way decides db used incoming request perform well easy manageable the question which best way decide database connection used instance what performs best what scales best answers i came with™ i read stuff ways i came wsgi daemon settingspy per instance each customer get settingspy database credentials the settings may inherit common stuff shared settings file for new setting file new wsgi instance application started this may scale badly many customers also creating apache vhost files ugly using using amp one settingspy i could like mymodelobjectsusingthecurrentdball set thecurrentdb somewhere middleware thingy per request but seems ugly everywhere also settingspyapp rewritten everytime customer gets instance one settingspy application router i yet look i access information request router i maybe could decide dbs settingspy used kind like httpsdocsdjangoprojectcomentopicsdbmultidbanexample per model per request modify settings middleware just idea maybe db setting could altered middleware didn yet look middleware works django possible some obscure way as i pretty new django i may missed points totally silly bad what would jeswyou why everything one db well because i think separation stuff good and bad things happen everybody suddenly affected,1 you reading blank line python like you probably checking blank lines linevalue freadlinexstrip lenlinevalue linevalue intlinevalue,whenever i try run code open file f openitxt r line detect start point def findstart x length epsilon linevalue intfreadlinex linevalue length length x x findendx elif linevalue epsilon x x findstartx else x x findstartx detect end point def findendx linevalue intfreadlinex linevalue length length return accept length elif linevalue epsilon x x length length findendx else x x length length findendx findstartline i get error code traceback recent call last file cusersbrandondesktopdetectsequencespy line module findstartline file cusersbrandondesktopdetectsequencespy line findstart findendx file cusersbrandondesktopdetectsequencespy line findend linevalue intfreadlinex valueerror invalid literal int base can anyone help figure wrong it seems attempting read empty cell i know would the file i scanning currently two lines reading output success i get past error,1 i sure code error message suggests file empty line trying convert int for example lot text files empty line end i suggest first checking line converting line line linestrip strip whitespace line go line blank linevalue intline,whenever i try run code open file f openitxt r line detect start point def findstart x length epsilon linevalue intfreadlinex linevalue length length x x findendx elif linevalue epsilon x x findstartx else x x findstartx detect end point def findendx linevalue intfreadlinex linevalue length length return accept length elif linevalue epsilon x x length length findendx else x x length length findendx findstartline i get error code traceback recent call last file cusersbrandondesktopdetectsequencespy line module findstartline file cusersbrandondesktopdetectsequencespy line findstart findendx file cusersbrandondesktopdetectsequencespy line findend linevalue intfreadlinex valueerror invalid literal int base can anyone help figure wrong it seems attempting read empty cell i know would the file i scanning currently two lines reading output success i get past error,1 you scope issue variables length epsilon you define findstart try access findend also variable x passed readline think readline always returns next line file variable passed optional hint length line might line read to operate specific lines read entire file list first read lines file openitxt r f read lines remove newline end line lines lstrip l freadlines remove blank lines lines filterlambda l l lines epsilon a length detect start point def findstart x global length length linevalue intlinesx linevalue a length x findendx elif linevalue epsilon x findstartx else x findstartx detect end point def findendx global length linevalue intlinesx linevalue a length return accept length elif linevalue epsilon x length findendx else x length findendx findstart,whenever i try run code open file f openitxt r line detect start point def findstart x length epsilon linevalue intfreadlinex linevalue length length x x findendx elif linevalue epsilon x x findstartx else x x findstartx detect end point def findendx linevalue intfreadlinex linevalue length length return accept length elif linevalue epsilon x x length length findendx else x x length length findendx findstartline i get error code traceback recent call last file cusersbrandondesktopdetectsequencespy line module findstartline file cusersbrandondesktopdetectsequencespy line findstart findendx file cusersbrandondesktopdetectsequencespy line findend linevalue intfreadlinex valueerror invalid literal int base can anyone help figure wrong it seems attempting read empty cell i know would the file i scanning currently two lines reading output success i get past error,1 two ways perform task linux using ghostscript trough gsview look root home hidden file gsviewini go section pdfwrite options options xoffset yoffset change values x axis settling convenient value values postscript points inch postscript points pdfwrite options options xoffset yoffset close gsviewini open pdf file gsview file convert pdfwrite select first odd pages print new file name oddpdf repeat steps even pages open pdf file gsview pdfwrite options options xoffset yoffset file convert pdfwrite select first even pages print new file name evenpdf need mix two pdf odd even pages use pdf transformer httpsourceforgenetprojectspdftransformer java jar pdftransformerjar inputfilename inputfilename outputfilename merge j use podofobox pdftk first step pdftk separate whole pdf document two pdf files odd even pages pdftk filepdf cat endodd output oddpdf ampamp pdftk filepdf cat endeven output evenpdf podofobox included podofo utils httppodofosourceforgenetabouthtml podofobox filepdf oddpdf crop widht height odd pages podofobox filepdf evenpdf crop widht height even pages width height postscript point x found pdfinfo eg pdf file pagesize x enter podofobox filepdf oddpdf crop podofobox filepdf evenpdf crop mix together odd even unique file already cited pdf transformer httpsourceforgenetprojectspdftransformer,i want shift pages existing pdf document right one inch three hole punched without hitting content the pdf documents already generated changing way generated possible it appears itext previous question what equivalent library way c python if platform dependent i need one would work linux update figured i would post little script i wrote case anyone else finds page needs working code thanks scott anderson suggestion rightshiftpy usrbinpython import sys import os pypdf import pdffilereader pdffilewriter sure default user space units guessed current document looking worked utoshift lensysargv print usage rightshift infile outfile sysexit ospathexistssysargv print exist sysargv sysexit pdfinput pdffilereaderfile sysargv rb pdfoutput pdffilewriter pagespdfinputgetnumpages rangepages p pdfinputgetpagei box pmediabox pcropbox pbleedbox ptrimbox partbox boxlowerleft boxgetlowerleftx utoshift boxgetlowerlefty boxupperright boxgetupperrightx utoshift boxgetupperrighty pdfoutputaddpage p outputstream filesysargv wb pdfoutputwriteoutputstream outputstreamclose,1 i think best bet make function operator pass def fop x return opx flambda x x looks little redundant though f lambda x x f,i revisiting scheme excercises python makes sense find python terms fp my problem concerns lambda python can define general function python operator one arguments think def f opxy return lambda function combines x appropriate way ie op return xy op return xy etc edit added usage called like f return i know possible scheme something equivalent python i gotten impression lambda python shorter way defining method i found way define general combiner function python,1 you cannot syntactically pass operator python eg f syntax error however consider op function use def lambda def fop x def opfunc return opx return opfunc def fop x opfunc lambda opx return opfunc in case wish evaluate function def fop x return opx remember python interpreted even def statements evaluated runtime if reason need access builtin operators functions using operator module httpdocspythonorglibraryoperatorhtml,i revisiting scheme excercises python makes sense find python terms fp my problem concerns lambda python can define general function python operator one arguments think def f opxy return lambda function combines x appropriate way ie op return xy op return xy etc edit added usage called like f return i know possible scheme something equivalent python i gotten impression lambda python shorter way defining method i found way define general combiner function python,1 operators really function python like methods x short xaddy yraddx you use functions operator module emulate behavior want,i revisiting scheme excercises python makes sense find python terms fp my problem concerns lambda python can define general function python operator one arguments think def f opxy return lambda function combines x appropriate way ie op return xy op return xy etc edit added usage called like f return i know possible scheme something equivalent python i gotten impression lambda python shorter way defining method i found way define general combiner function python,3 i see points question lets go order can i pass function parameter someone yes def fop x return opx def addx return x fadd gives what operators unlike scheme python operators functions pass directly parameters you either create wrapper functions import operator module standard library import operator operatoradd lambda xy xy operators real functions little sad cases least python gives us chained comparisons like x exchange so difference python scheme in general sense functions python powerful functions scheme however things note the lambda keyword limited you single expression function body f lambda x x since bunch things python statements expressions assignments x print often need fall back named functions instead there closures def makeprintermsg def printer print msg return printer printer message but mutating variables pain this work it tries bind new n inner function instead using outer one def makecountern def inc n n return n return inc new x nonlocal keyword def makecountern def inc nonlocal n n n return n return inc workaround w mutable objects def makecountern nw n def inc nw nw return nw return inc objects instead closures uses magic call method pretend function class counter def initself n selfn n def callself selfn return selfn,i revisiting scheme excercises python makes sense find python terms fp my problem concerns lambda python can define general function python operator one arguments think def f opxy return lambda function combines x appropriate way ie op return xy op return xy etc edit added usage called like f return i know possible scheme something equivalent python i gotten impression lambda python shorter way defining method i found way define general combiner function python,3 based line file cuserskiwidropboxprogramming projectsdjango projectsponysiteforumadminpy forummodels import category thread post report subscription ban django finding forumadminpy forummodels import category thread post report subscription ban note ban end defined models remove error gone,i many problems django solved far weirdest incomprehensible one it happens i load page python managepy runserver validating models errors found django version using settings ponysitesettings development server running http quit server ctrlbreak nov get http traceback recent call last file cpythonlibsitepackagesdjangocoreserversbasehttppy line run selffinishresponse file cpythonlibsitepackagesdjangocoreserversbasehttppy line finishresponse selfwritedata file cpythonlibsitepackagesdjangocoreserversbasehttppy line write selfwritedata file cpythonlibsocketpy line write selfflush file cpythonlibsocketpy line flush selfsocksendallviewwriteoffsetwriteoffsetbuffersize error errno an existing connection forcibly closed remote host exception happened processing request traceback recent call last file cpythonlibsocketserverpy line handlerequestnoblock selfprocessrequestrequest clientaddress file cpythonlibsocketserverpy line processrequest selffinishrequestrequest clientaddress file cpythonlibsocketserverpy line finishrequest selfrequesthandlerclassrequest clientaddress self file cpythonlibsitepackagesdjangocoreserversbasehttppy line init basehttprequesthandlerinitself args kwargs file cpythonlibsocketserverpy line init selffinish file cpythonlibsocketserverpy line finish selfwfileflush file cpythonlibsocketpy line flush selfsocksendallviewwriteoffsetwriteoffsetbuffersize error errno an existing connection forcibly closed remote host traceback recent call last file cpythonlibsitepackagesdjangocoreserversbasehttppy line run selffinishresponse file cpythonlibsitepackagesdjangocoreserversbasehttppy line finishresponse selfwritedata file cpythonlibsitepackagesdjangocoreserversbasehttppy line write selfwritedata file cpythonlibsocketpy line write selfflush file cpythonlibsocketpy line flush selfsocksendallviewwriteoffsetwriteoffsetbuffersize error errno an existing connection forcibly closed remote host exception happened processing request traceback recent call last file cpythonlibsocketserverpy line handlerequestnoblock selfprocessrequestrequest clientaddress file cpythonlibsocketserverpy line processrequest selffinishrequestrequest clientaddress file cpythonlibsocketserverpy line finishrequest selfrequesthandlerclassrequest clientaddress self file cpythonlibsitepackagesdjangocoreserversbasehttppy line init basehttprequesthandlerinitself args kwargs file cpythonlibsocketserverpy line init selffinish file cpythonlibsocketserverpy line finish selfwfileflush file cpythonlibsocketpy line flush selfsocksendallviewwriteoffsetwriteoffsetbuffersize error errno an existing connection forcibly closed remote host nov get http i tried wiping recreating database stripping viewspy modelspy bare minimum avail i also tried running project another computer result both running windows x actually i think one computer running django x ther x error looks regardless here full traceback environment request method get request url http django version python version installed applications djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribsites djangocontribmessages djangocontribstaticfiles djangocontribadmin djangocontribadmindocs forum djangocontribmarkup installed middleware djangomiddlewarecommoncommonmiddleware djangocontribsessionsmiddlewaresessionmiddleware djangomiddlewarecsrfcsrfviewmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangocontribmessagesmiddlewaremessagemiddleware traceback file cpythonlibsitepackagesdjangocorehandlersbasepy getresponse requestpathinfo file cpythonlibsitepackagesdjangocoreurlresolverspy resolve pattern selfurlpatterns file cpythonlibsitepackagesdjangocoreurlresolverspy geturlpatterns patterns getattrselfurlconfmodule urlpatterns selfurlconfmodule file cpythonlibsitepackagesdjangocoreurlresolverspy geturlconfmodule selfurlconfmodule importmoduleselfurlconfname file cpythonlibsitepackagesdjangoutilsimportlibpy importmodule importname file cuserskiwidropboxprogramming projectsdjango projectsponysiteponysiteurlspy adminautodiscover file cpythonlibsitepackagesdjangocontribadmininitpy autodiscover importmodule sadmin app file cpythonlibsitepackagesdjangoutilsimportlibpy importmodule importname file cuserskiwidropboxprogramming projectsdjango projectsponysiteforumadminpy forummodels import category thread post report subscription ban exception type importerror exception value cannot import name ban ban model modelspy imported viewspy i played around currently commented everywhere model view controller i don’t know anything problem thanks advance guys,2 that data openinfile r read print datacount tmp,i trying count number times tmp occurs file file count belongs i created script works i setup input file output directory file to improve i would like script go file folder setting i experimenting import tkfiledialog import glob import os directory tkfiledialogaskdirectory infile globglobospathjoindirectory openinfile rread infilecounttmp currently i counting number times tmp occurs file name actual file i type print infile outputs contents text files directory i confused go,1 answers points wsgidaemonprocesswsgiprocessgroup indicate modwsgi fork separate process running wsgi application this fork forkexec modwsgi still control when detected url maps wsgi application running daemon mode modwsgi code apache child worker processes proxy request details daemon mode process modwsgi code reads calls wsgi application yes multiple requests operating concurrently wanting modify module global data time for time execution within python strictly running parallel global interpreter lock means one thread executing python code time the python interpreter periodically switch thread getting run if one threads calls c code releases gil least time thread state run parallel threads running python c code as example calls made apachemodwsgi layer write back response data gil released this means actual writing back response data lower layers prevent threads running,before posting i read quite resources online including modwsgi wiki i confused exactly apache processesthreads interact modwsgi this current understanding apache configured run one child processes handle incoming requests child processes configured turn use one threads service requests after things start getting hazy my doubts what wsgidaemonprocess actually calls django app using python sub interpreter if i django app running mode multiple threads allowed single apache child process mean multiple requests could simultaneously accessing app time if would something like setting module level variable say user id could overwritten parallel requests lead nonthread safe behavior for case python global interpreter lock would threads actually executing parallel,3 the fix case remove defaults envreset sudoers but i keep defaults envkeep pythonpath sudoers i actually added defaults envreset resets environment variables still works envkeep it seems envkeep envreset conflict eachother guess so whole process add export pythonpathyourcustompath bashrc etcbashbashrc add pythonpath defaults envkeep env env sudoers file remove defaults envreset sudoers file present,edit works root sudo problem read i directory libraries eg python libraries located homenamelibpy i added directory python path users including root adding following line etcbashbashrc export pythonpathpythonpathhomenamelibpy it works users including root but work sudo is way i make sudo use etcbashbashrc edit more information i added pythonpath sudoers file like defaults envkeep home pythonpath it sitll work env grep python pythondontwritebytecode pythonpathhomenamelibpy sudo env grep python pythondontwritebytecode sudo echo pythonpath homenamelibpy,3 i would use oswalk rather glob import tkfiledialog import os import ospath import directory tkfiledialogaskdirectory dirpath dirnames filenames oswalkdirectory filename filenames path ospathjoindirpath filename openpath file contents fileread print path contentscount tmp refindall tmpd contents,i trying count number times tmp occurs file file count belongs i created script works i setup input file output directory file to improve i would like script go file folder setting i experimenting import tkfiledialog import glob import os directory tkfiledialogaskdirectory infile globglobospathjoindirectory openinfile rread infilecounttmp currently i counting number times tmp occurs file name actual file i type print infile outputs contents text files directory i confused go,1 you treat one files python module make one import import standard python modules the latter refer objects including classes functions defined imported module the module also run whatever initialization code needs see httpdocspythonorgtutorialmoduleshtml,how i make one python file run for example i two py files i want one file run run py file,2 dictenumeratexrstrip x fdata but error key,searched pretty hard cant find question exactly pertains want i file called words lines random az sorted words th st nd rd th th th th th th aaa aaas aarhus aaron aau aba ababa aback abacus abalone abandon abase abash abate abater abbas abbe abbey abbot abbott abbreviate abc abdicate abdomen abdominal abduct abe abed abel abelian i trying load file dictionary using word key values keys actually autogenautoincremented word eg th st nd etcetc code hobbled together far seems sort works showing last entry file dict pair element fdata open words mydict line fdata print linestrip cmyline linesplit key mydict key cmyline print mydict,1 the use zerobased numeric keys dict suspicious consider whether simple list would suffice here example using list comprehension mylist wordstrip word open usrsharedictwords mylist a mylist aaron mylist addie mylist armand mylist loyd i use strstrip remove whitespace newlines present usrsharedictwords this may necessary data however really need dictionary python enumerate builtin function friend pass output directly dict function create mydict dictenumeratewordstrip word open usrsharedictwords mydict a mydict aaron mydict addie mydict armand mydict loyd,searched pretty hard cant find question exactly pertains want i file called words lines random az sorted words th st nd rd th th th th th th aaa aaas aarhus aaron aau aba ababa aback abacus abalone abandon abase abash abate abater abbas abbe abbey abbot abbott abbreviate abc abdicate abdomen abdominal abduct abe abed abel abelian i trying load file dictionary using word key values keys actually autogenautoincremented word eg th st nd etcetc code hobbled together far seems sort works showing last entry file dict pair element fdata open words mydict line fdata print linestrip cmyline linesplit key mydict key cmyline print mydict,1 key thing i assume meant key i also see reason split line one item per line however really reason looping open words fdata mydict dictenumeratelinestrip line fdata,searched pretty hard cant find question exactly pertains want i file called words lines random az sorted words th st nd rd th th th th th th aaa aaas aarhus aaron aau aba ababa aback abacus abalone abandon abase abash abate abater abbas abbe abbey abbot abbott abbreviate abc abdicate abdomen abdominal abduct abe abed abel abelian i trying load file dictionary using word key values keys actually autogenautoincremented word eg th st nd etcetc code hobbled together far seems sort works showing last entry file dict pair element fdata open words mydict line fdata print linestrip cmyline linesplit key mydict key cmyline print mydict,2 fdata open words print fdatareadlines,searched pretty hard cant find question exactly pertains want i file called words lines random az sorted words th st nd rd th th th th th th aaa aaas aarhus aaron aau aba ababa aback abacus abalone abandon abase abash abate abater abbas abbe abbey abbot abbott abbreviate abc abdicate abdomen abdominal abduct abe abed abel abelian i trying load file dictionary using word key values keys actually autogenautoincremented word eg th st nd etcetc code hobbled together far seems sort works showing last entry file dict pair element fdata open words mydict line fdata print linestrip cmyline linesplit key mydict key cmyline print mydict,1 there might good use record array i thought python dict good want know numpy way good dct dictzipdata causes data analyst alldata mlabrecappendfieldsdata analyst dctx x data causes,i trying join recarrys python value joins many elements the following code works ratio i trying many joins one instance import numpy np import matplotlib first data structure sex nparray m f m f m f causes nparray c c c c c c data npcorerecordsfromarrayssex causes names sex causes second data structure causes nparray c c c analyst nparray p p p data npcorerecordsfromarrayscauses analyst names causes analyst join cause alldata matplotlibmlabrecjoin causes data data jointype leftouter what i would like alldata recarray contain data data corresponding analyst indicated data,1 lifting batch limit batchsize rps limit rpslimit works i use batch size rps limit appcfgpy uploaddata url application filename email batchsize rpslimit,i trying upload moderetly sized csv file google app engine using bulkloader functionality appears die way following result info logging bulkloaderlog info throttling transfers info bandwidth bytessecond info http connections second info entities insertedfetchedmodified second info batch size info opening database bulkloaderprogresssql info connecting notmyrealappnameappspotcomahremoteapi info starting import maximum entities per post info unexpected thread death workerthread info an error occurred shutting error error workerthread urlopen error errno name service known info entites total previously transferred info entities bytes transferred seconds info some entities successfully transferred it uploads k entries i trying upload i wondering fails i checked csv file errors like additional commas could throw python csv reader non ascii characters stripped,3 set choices field initializer,i playing around using django arduinos from modelspy i class arduinomodelsmodel address modelscharfieldmaxlength i wondering possible address autogenerated choicetuple script even right approach i arduinos around house connected django server sensor monitoring i course put address hand i trying learn django programming general simple app configuration arduinos done admin interface thanks assistance,1 you missing into tablename clause that actual problem i see the changing ø¨ xdxa means unicode getting encoded utf way database probably want mysql reporting utfencoded bytes using xxx notation hexadecimal escape sequences example x means ascii space give allascii error message bit cryptic especially used problem,i using mysqldb i use cursorexecutequery where qyery insert abc valuessssomething k u w w is persian letter literally i replaced w case problem viewing persian letters something like ø¨ k english get traceback recent call last file ipy line module cdoitdb file ipy line doit dbcrexecute insert abc valuessssomething k u ø¨ file usrlibpymodulespythonmysqldbcursorspy line execute selferrorhandlerself exc value file usrlibpymodulespythonmysqldbconnectionspy line defaulterrorhandler raise errorclass errorvalue mysqlexceptionsprogrammingerror you error sql syntax check manual corresponds mysql server version right syntax use near termtittermdesctermcat valuesanxdxageneral line see w letter turns xdxa what update the mistake sql query fixed but xdxa problem persists retrieving data database get instead entered,2 in jinja functions methods must explicitly called keyvalue locationmapindiaitems valuename endfor,with jinja i make iteration like folllowing works django jinja keyvalue locationmapindiaitems valuename endfor the valid django jinja returns error message typeerror builtinfunctionormethod object iterable thanks advice,3 think see issue instead n ints try n lens,this homework i looking handout error messages really explained yet i know fix happening i know happens i try make integer i get different error i i little lost i also tried looking posts similar problems i new python i follow explanations it pretty straightforward function i think i tried converting integer i perform range function seem working the program supposed first put space letters blusson hall add additional space already one finally print design around final product thanks help def spaceds n int range n n n n n print print print str n print print write marks tester code spacedblusson hall,1 there ways i list order inverted preference ie best first worst last treat like module import file this good secure fast maintainable code gets reused supposed done most python libraries run using multiple methods stretched lots files highly recommended note file called filepy import include py extension end the infamous unsafe exec command execfile filepy insecure hacky usually wrong answer avoid possible spawn shell process ossystem python filepy use desperate,how i make one python file run for example i two py files i want one file run run py file,3 alternatives manipulating pythonpath virtualenv distutils,edit works root sudo problem read i directory libraries eg python libraries located homenamelibpy i added directory python path users including root adding following line etcbashbashrc export pythonpathpythonpathhomenamelibpy it works users including root but work sudo is way i make sudo use etcbashbashrc edit more information i added pythonpath sudoers file like defaults envkeep home pythonpath it sitll work env grep python pythondontwritebytecode pythonpathhomenamelibpy sudo env grep python pythondontwritebytecode sudo echo pythonpath homenamelibpy,1 your problem calling spaced nonnumeric string trying convert integer intblusson hall traceback recent call last file stdin line module valueerror invalid literal int base blusson hall if want range based length string use something like rangelens busson hall rangelens print and extra assistance would use si get th zero first one course character in addition probably want start empty string append individual characters original string whatever spaces want added gradually build returning for example snippet duplicates every character colon paxdiablo rangelens sss si si print ppaaxxddiiaabblloo short writing code intelligently decided asking probably help i give though feel free ask questions want i offer advice,this homework i looking handout error messages really explained yet i know fix happening i know happens i try make integer i get different error i i little lost i also tried looking posts similar problems i new python i follow explanations it pretty straightforward function i think i tried converting integer i perform range function seem working the program supposed first put space letters blusson hall add additional space already one finally print design around final product thanks help def spaceds n int range n n n n n print print print str n print print write marks tester code spacedblusson hall,3 the c version python interpreter probably using raise error eventually never return daemonloop i sure versions,this question curiosity utility if i writing function supposed run ever instance daemon would python handle i called function end function def daemonloop declare locals do stuff daemonloop i fairly sure c would result stack overflow given level abstraction c python i guessing stuff handled differently would i go hell,1 in almost python interpreters cause stack overflow would c the higherlevel feature would permit called tail call optimization tail recursion elimination benevolent dictator python opposes adding language this style considered nonidiomatic python simple true loop preferred,this question curiosity utility if i writing function supposed run ever instance daemon would python handle i called function end function def daemonloop declare locals do stuff daemonloop i fairly sure c would result stack overflow given level abstraction c python i guessing stuff handled differently would i go hell,3 the maximum recursion depth retrieved sysgetrecursionlimit set syssetrecursionlimit would i go hell yes cpython tail recursion elimination last call optimization def recurse recurse recurse error lines file line recurse runtimeerror maximum recursion depth exceeded,this question curiosity utility if i writing function supposed run ever instance daemon would python handle i called function end function def daemonloop declare locals do stuff daemonloop i fairly sure c would result stack overflow given level abstraction c python i guessing stuff handled differently would i go hell,3 i know think something like could simply infinite loop anyway question whether work file testpy line daemonloop daemonloop file testpy line daemonloop daemonloop runtimeerror maximum recursion depth exceeded so yeah hell,this question curiosity utility if i writing function supposed run ever instance daemon would python handle i called function end function def daemonloop declare locals do stuff daemonloop i fairly sure c would result stack overflow given level abstraction c python i guessing stuff handled differently would i go hell,1 if jpeg library supports set scaling parameters you probably need kxk output image showing screen speed factor several httpjpegcluborgdjpeg,i using pygame display images photos for larger image sizes load convert process slow eg taking seconds image size x the actual code slow image pgimageloadfnameconvert is alternative library method give better performance my target platforms windows os x i ok separate solutions although single solution would better,1 if trying solve fe cfd style equations mesh use meshpy dimensions meshpy nice wrapper around existing tools tetgen triangle if looking typical graphics style meshes interesting talk pycon algorithmic generation opengl geometry described pragmatic approach procedural mesh generation the code presentation available online if interested reconstruction surfaces data go past standford d scanning repository home stanford bunny edit a dependancy free alternative may use something like gmsh platform independent uses similar tools meshpy backend,i need python modulepackage provides mesh i computational science i graphics i think blender package i want does anyone know good package,3 i sure exactly mean wanting get get quoted substrings string note unlike python etc haskell one set quotes indicate something string namely possibilities consider the words lines functions the split package write custom parser using polyparse uuparsinglib parsec etc it may useful specified wanted functionality trying parse existing shell scripts then languagesh might use but using strings internally haskell instead using string something,how i split string shellstyle syntax haskell the equivalent python shlexsplit shlexsplit nosuchconf exist either yep nosuchconf exist either yep,1 kinda like one better p future import printfunction time import sleep range strdownloading file foofiletxt formati backblenstr printstr end sleep printback end,i new python writing scripts automate downloading files ftp servers etc i want show progress download i want stay position output downloading file foofiletxt i trying avoid something like downloading file foofiletxt downloading file foofiletxt downloading file foofiletxt how i go duplicate httpstackoverflowcomquestionshowcaniprintoverthecurrentlineinacommandlineapplication,3 you could use variables containing html a triple mustache like variable return unescaped html it exactly template extensions could render frontpagecontenthtml put output content variable gets passed basehtml i added content frontpagehtml filename expectation naming pattern help keep filenames manageable,i new mustache many templating languages eg django jinja let extend parent template like basehtml htmlheadhead body block content endblock body html frontpagehtml extends basehtml block content hfoobarh endblock rendered frontpagehtml htmlheadhead body hfoobarh body html i aware mustache partials eg content seem includes does template extension exist mustache or failing least design pattern effectively turns includes template extension equivalents,1 you real trouble storing amount data mysql although probably able store entire database memory expect io performance issues as always make sure appropriate indices running queries the important thing try load entire file memory loop file try use method like readlines load whole file make sure batch requests load thousand lines time send one big sql request this approach work def pushbatchbatch send big insert request mysql currentbatch open filename f line f batchappendline lencurrentbatch pushbatchcurrentbatch currentbatch pushbatchcurrentbatch zone files pretty normally formatted consider get away using load data infile you might also consider creating named pipe pushing partially formatted data python using load data infile read mysql mysql great tips optimizing inserts highlights use multiple value lists insert statement use insert delayed particularly pushing multiple clients eg using threading lock tables inserting tweak keybuffersize bulkinsertbuffersize the fastest processing done mysql consider get away queries need data db if need operations python threading going help only one thread python code execute time gil unless something spends considerable amount time c interfaces external resources going ever running one thread anyway the important optimization question bounding speed point spinning bunch threads read file database bounding factor the way really know try make tweaks fast enough purpose,i need loop large text file several gigabytes size zone file exact i need run queries entry zone file store results searchable database my weapons choice moment mainly i know python mysql i sure well either deal files size however does anyone experience area suggestions best way open loop file without overloading system how efficient way process file i open threading store processed data,2 change algorithm use mergesort quicksort bubblesort onn the reason exists show students sort arrays mergesort worst case on log n quicksort on n worst case average case on log n low constants usually faster merge sort search web if wrong rage i please i think i understood want def bubblelst n lenlst true newn range n lsti lsti lstilsti lstilsti newn counter newn return counter n newn the complexity however always on n notice important difference for example if list items use bubble sort o loop steps this huge o log loop steps manageable,def bubblelst swap true counter n lenlst lenlst swap true j rangen lstj lstj lstjlstj lstjlstj counter swap true else swap false n n return counter how i shorten time function takes i want use larger list,2 in linux pipe buffer limited k possible ending deadlock capture write audio write video ffmpeg read video gets audio,i capture process writes raw video data audio data files something like capture frames data capture n f videofile audiofile giving bytes audiofile bytes videofile these seems add expected x pixelsframe bytespixel frames k hz bytessample channels frames framess then i encode data like ffmpeg audiofile videofile outflv i get playable video sound actually i lot stuff command line important parts purposes question now i actually want live stream file i ok video something like capture f devstdout ffmpeg udp i get video stream audio broadcast udp i able receive play stream ok but i want add audio picture i troubles i think i send stdout i use stderr capture process chats already so i tried named pipes like mkfifo audiopipe mkfifo videopipe ffmpeg audiopipe videopipe outflv amp capture f videopipe audiopipe but working seems everything deadlocks i tested running capture f videofile audiofile opening two new shells cat videofile devnull cat audiofile devnull cats running unblocks capture process seems trouble writing pipes i peek source capture code way works frame arrived callback deeper api goes writes video frame audio data order blocking i know ffmpeg whether reads input video file audio file sequentially either order reads simultaneously threads i tried changing order ffmpeg videopipe audiopipe outflv unfortunately everything still locks using one named pipes video data works normally how i solve problem i script python subprocess module i understand best way avoid blocking problem,1 by default objects python evaluate true in order support false evaluations object class must either len method false nonzero method false false note nonzero bool python x because iterator protocol intentionally kept simple many types iteratorsgenerators able know values produce attempting produce true false evaluation part iterator protocol if really want behavior provide one way wrap generatoriterator class provides missing functionality note code evaluates false stopiteration raised as bonus code works pythons try next except nameerror show python def nextiter return iternext empty object class booleaniteratorobject adds abilities truefalse tests true means may items still remaining used def initself iterator selfiter iteriterator selfalive true def iterself return self def nextself try result nextselfiter except stopiteration selfalive false raise return result next next python x def boolself return selfalive nonzero bool python x if also want lookahead peek behavior code trick evaluates false stopiteration raised try next except nameerror show python def nextiter return iternext empty object class iteratorobject adds abilities truefalse tests true means items still remaining used peek get next item without removing sequence def initself iterator selfiter iteriterator selfpeek empty selfpeek def nextself peek selfpeek selfpeek empty selfpeek peek empty return peek raise stopiteration next next python x def boolself return selfpeek empty nonzero bool python x def peekself selfpeek empty return selfpeek selfpeek nextselfiter empty return selfpeek keep mind peek behaviour appropriate timing underlying iteratorgenerator relevant produced values also keep mind thirdparty code possibly stdlib may rely iteratorsgenerators always evaluating true if want peek without bool remove nonzero bool methods,other empty objects python evaluate false i get iteratorsgenerators well,2 guido want generators iterators behave way objects true default they false define len returns zero nonzero returns false latter called bool pyx you add one methods custom iterator match guido intent he rejected adding len iterators upcoming length known that got lengthhint instead so way tell iterator empty call next see raises stopiteration on aspn i believe recipes using technique lookahead wrapper if value fetched savedup upcoming next call,other empty objects python evaluate false i get iteratorsgenerators well,3 empty thing automatically iterator containers empty get iterators containers iterators falsey exhausted a good example iterators become falsey sysstdin the problem making sysstdin falsey reaches end input way actually knowing reached end stream without trying consume input the main reason wanting iterator falsey would peek see getting next item would valid sysstdin obviously practical another example x x xrange randomrandrange way knowing generator return numbers without bunch work actually find next value the solution get next value iterator if empty loop exit get stopiteration exception loop,other empty objects python evaluate false i get iteratorsgenerators well,2 if python use dictionary comprehensions kv kv listoftuples member tuple form aaland islands ax this general solution probably necessary scenario for older pythons simply call dictionary constructor list tuples argument dictlistoftuples get want,how would i put following information python dictionary httpuserpagechemiefuberlindediversedocisohtml keys would country values would twocharacter iso code for example i want result mappingofcountrytoiso aaland islands ax afghanistan af,2 the final workaround calling sessionremove start methods manipulating loading elixir entities what return connection pool used pool checkout event fired handler detect disconnection from sqlalchemy docs it’s strictly necessary remove session end request options include calling sessionclose sessionrollback sessioncommit end existing session returns connections pool removes existing transactional context doing nothing option individual controller methods take responsibility ensuring transactions remain open request ends quite important little piece information i wish mentioned elixir docs but i guess assumes prior knowledge sqlalchemy,update i done testing proved using checkout event handler check disconnects works elixir beginning think problem something calling sessioncommit subprocess update i disproved calling sessioncommit subprocess updated example i using multiprocessing module create subprocess here code shows work without even using poolrecycle sqlalchemy import exc sqlalchemy import event sqlalchemypool import pool elixir import import multiprocessing mp class subprocessmpprocess def runself testmodelnamemonkey sessioncommit class testmodelentity name fieldstring eventlistensforpool checkout def pingconnectiondbapiconnection connectionrecord connectionproxy cursor dbapiconnectioncursor try cursorexecuteselect except optional dispose whole pool instead invalidating one time connectionproxypooldispose raise disconnectionerror pool try connecting three times raising raise excdisconnectionerror cursorclose sqlalchemy import createengine metadatabind createenginemysqlfoobarlocalhostsomedb echopooltrue setupalltrue subp subprocess testmodelname foo sessioncommit pool size three print restart server rawinput subpstart testmodelname bar sessioncommit update i forced find another solution post versions mysqlpython drops support reconnect param anyone got solution update oldsolution work mysqlpython versions found solution passing connectargs reconnect true createengine call fixes problem automagically reconnects don even seem need checkout event handler so example question metadatabind createenginemysqlfoobarlocalhostdbname poolsize poolrecycle connectargs reconnect true original question done quite bit googling problem seem found solution specific elixir i trying use disconnect handling pessimistic example sqlalchemy docs handle mysql disconnects however i test restarting mysql server mysql server gone away error raised checkout event handler here code i use initialize elixir initialize elixirsqlalchemy disconnect handling sqlalchemy import exc sqlalchemy import event sqlalchemypool import pool eventlistensforpool checkout def pingconnectiondbapiconnection connectionrecord connectionproxy loggingdebugpingconnection cursor dbapiconnectioncursor try cursorexecuteselect except loggingdebug disconnection error optional dispose whole pool instead invalidating one time connectionproxypooldispose raise disconnectionerror pool try connecting three times raising raise excdisconnectionerror cursorclose metadatabind createenginemysqlfoobarlocalhostdbname poolsize poolrecycle setupall i create elixir entity objects save sessioncommit i see pingconnection message generated event defined however i restart mysql server test fails mysql server gone away message ping connection event here stack trace starting relevant lines file usrlocallibpythondistpackageselixirentitypy line getby return clsqueryfilterbyargs kwargsfirst file usrlocallibpythondistpackagessqlalchemyormquerypy line first ret listself file usrlocallibpythondistpackagessqlalchemyormquerypy line getitem return listres file usrlocallibpythondistpackagessqlalchemyormquerypy line iter return selfexecuteandinstancescontext file usrlocallibpythondistpackagessqlalchemyormquerypy line executeandinstances result connexecutequerycontextstatement selfparams file usrlocallibpythondistpackagessqlalchemyenginebasepy line execute params file usrlocallibpythondistpackagessqlalchemyenginebasepy line executeclauseelement compiledsql distilledparams file usrlocallibpythondistpackagessqlalchemyenginebasepy line executecontext context file usrlocallibpythondistpackagessqlalchemyenginebasepy line executecontext context file usrlocallibpythondistpackagessqlalchemyenginedefaultpy line doexecute cursorexecutestatement parameters file usrlibpymodulespythonmysqldbcursorspy line execute selferrorhandlerself exc value file usrlibpymodulespythonmysqldbconnectionspy line defaulterrorhandler raise errorclass errorvalue operationalerror operationalerror mysql server gone away,1 i copied pasted important data text file called countriestxt something like import string myfilename countriestxt mytuples myfile open myfilename r line myfilereadlines splitline stringsplit line code splitline country stringjoinsplitline mytuplesappendtuplecountry code mydict dictmytuples print mydict it probably best way seems work here following john machin helpful recommendations import string myfilename countriestxt mydict myfile open myfilename r line myfile splitline stringsplit line code splitline country joinsplitline mydictcountry code print mydict,how would i put following information python dictionary httpuserpagechemiefuberlindediversedocisohtml keys would country values would twocharacter iso code for example i want result mappingofcountrytoiso aaland islands ax afghanistan af,1 don mess parsing html likely change without notice get one csv files links bottom html pages parse csv module,i trying adapt code extract information wunderground however script i trying adapt written formating weather underground changed i trouble soupbodynobrbstring i want extract daily percipitation data given site httpwwwwundergroundcomhistoryairportkbufdailyhistoryhtml import urllib beautifulsoup import beautifulsoup createopen file called wundertxt commadelimited file f open wunderdatatxt w iterate year month day range range range check leap year leap true elif leap false elif leap true else leap false check already gone month leap continue elif continue elif continue open wundergroundcom url url httpwwwwundergroundcomhistoryairportkbufstry strm strd dailyhistoryhtml page urlliburlopenurl get temperature page soup beautifulsouppage daytemp soupbodynobrbstring format month timestamp lenstrm mstamp strm else mstamp strm format day timestamp lenstrd dstamp strd else dstamp strd build timestamp timestamp stry mstamp dstamp write timestamp temperature file fwritetimestamp daytemp n done getting data close file fclose,2 quote newline def underlinetitle print title n lentitle good point jeff statement returning none i pointing causing line continuation error as error says line continuation character expecting characters,here quiz question adding two strings making multiple copies string examples greetings hello world lengreetings get length string greetings get st character h print underlinegood day good day write function given string characters return string together length my first attempt def underlinetitle print title print lentitle somewhat passes visually returns none value also idea so instead i tried def underlinetitle print title nlentitle get unexpected character line continuation character error turning google less helpful error,1 well want print strings want return so create string combines together separated newline character return def underlinetitle return title n lentitle,here quiz question adding two strings making multiple copies string examples greetings hello world lengreetings get length string greetings get st character h print underlinegood day good day write function given string characters return string together length my first attempt def underlinetitle print title print lentitle somewhat passes visually returns none value also idea so instead i tried def underlinetitle print title nlentitle get unexpected character line continuation character error turning google less helpful error,2 how i repeat texture pardon wrong by using texture coordinates gltexcoord outside range,i beginner opengl i trying repeat texture glquads so far here code loading texture file ospathjoin image texturepng surface imageloadfile selft surfaceimagedatacreatetextureimagetexture glbindtexturegltextured tid gltexparameterigltextured gltexturewraps glrepeat gltexparameterigltextured gltexturewrapt glrepeat gltexparameterigltextured gltexturemagfilter glnearest gltexparameterigltextured gltextureminfilter glnearest drawing glbindtexturegltextured selftid glbeginglquads gltexcoordf glvertexf gltexcoordf glvertexfselfwidth gltexcoordf glvertexfselfwidth selfheight gltexcoordf glvertexf selfheight glend when selfwidth selfheight changed texture stretched distorted how i repeat texture pardon wrong thank,1 just thinking loud i would start first regarding website use easiest environment for example basic php page fine get site running python well i prefer using language that said i sure would need use hosted website given already forced externally accessible pc home communication run webserver directly apache nginx even something like cherrypy that webserver communicate python process running control arduino using eg python xmlrpclib if would run things via hosting company would still need process handle external requests securely something webserver quite good just running gives freedom want simplifies things lessening number components solution the updates site i keep quite basic commands want run handled request handlers webserver calling relevant xmlrpclib calls dynamically updating page best done ajax calls i reckon based story updates easily put json object suitable periodically updating relevant segments page,i looking bit web development advice i fairly new area i sure gurus willing part wisdom objective i interested controlling python application computer personal web hosted site i know question asked several times case requirements bit different to reduce length post i summarize objective bullet points personal site hosted web hosting company site uses html php mysql python javascript majority everything coded ground an application coded python run pc within home communicate arduino board the app receive commands internet control actuation via arduino transmit sensor data back site temperature looking communication bidirectional fast secure securing connection site python app would ideal i looking connect python application directly web server must serve middle man so far i considered http post html forms using sockets python app would run web server irc bot readingwriting text file stored web server i also hoping way communicate python app without needing refresh webpage perhaps using ajax javascipt maybe flash is something i considering i feel like i missing something thanks advance advice,2 add shebang python file question make python file executable eg chmod ax logserverpy start directly logserverpy a shebang line telling kernel interpreter use it simply line like usrbinenv python beginning file,i long term processes temporary processes python while shell c programs run names python processes run python filenamepy makes tough identify processes how i make python processes show logserverpy linux i use python ubuntu,3 if want explicit change name script running library pypi import setproctitle setproctitlesetproctitle logserver making script executable starting directly often enough though,i long term processes temporary processes python while shell c programs run names python processes run python filenamepy makes tough identify processes how i make python processes show logserverpy linux i use python ubuntu,2 here solution nested list comprehensions oswalk simple suffix matching instead glob import os cfiles ospathjoinroot filename root dirnames filenames oswalk src filename filenames filenameendswith c it compressed oneliner import oscfilesospathjoinrf rdfs oswalk src f fs fendswith c generalized function import os def recursiveglobrootdir suffix return ospathjoinlooproot filename looproot filenames oswalkrootdir filename filenames filenameendswithsuffix cfiles recursiveglob src c if need full glob style patterns follow alex bruno example use fnmatch import fnmatch import os def recursiveglobrootdir pattern return ospathjoinlooproot filename looproot filenames oswalkrootdir filename filenames fnmatchfnmatchfilename pattern cfiles recursiveglob src c,this i globospathjoin src c i want search subfolders src something like would work globospathjoin src c globospathjoin src c globospathjoin src c globospathjoin src c but obviously limited clunky,3 import string sortedditems keystringlower,example answer question j sortedditems print question answer i would like case insensitive list answer question i believe done simple pythonic way,2 if printing keys sorteddkeys keylambda x xlower print if need values afterwards could j sortedditems keylambda x xlower print j edit even shorter better since scope sortedd keystrlower print di,example answer question j sortedditems print question answer i would like case insensitive list answer question i believe done simple pythonic way,2 k sortedd keylambda k klower print k,example answer question j sortedditems print question answer i would like case insensitive list answer question i believe done simple pythonic way,1 this code works fine the problem default accounting format symbol if set pound symbol worksheet replace dollar symbol pound open file you need change setting show dollar symbol,i trying add dollar symbol excel file using python i coded number format see code i run code download excel file but i open excel file shows pound symbol please note my default accounting format symbol ⣠english uk i need show currency symbol using python how wb workbook ws wbaddsheet sheet currencystyle xfstyle currencystylenumformatstr range wswritei currencystyle selfresponseheaders contenttype applicationmsexcel selfresponseheaders contenttransferencoding binary selfresponseheaders contentdisposition attachment filenamemyfilexls wbsaveselfresponseout,1 you try something like cmd myprogramsh p subprocesspopen cmd shellfalse stdoutsubprocesspipe launch process ppoll none check process still alive pstdoutreadline still alive grab output dosomethingwithout want,i pretty long running job runs several minutes gets restarted the task outputs various information i capture like output subprocesspopencmdstdoutsubprocesspipecommunicate the thing i get entire output time i would like show output program sending stdout still pushing back buffer i need check output presence strings in ruby i would like iopopencmd io ioeachline line puts line buffer line end end,3 you could read one line time subprocess import popen pipe p popen grep ir graph stdoutpipe preturncode pstdoutreadline print ppoll in way blocking time takes process output single line,i pretty long running job runs several minutes gets restarted the task outputs various information i capture like output subprocesspopencmdstdoutsubprocesspipecommunicate the thing i get entire output time i would like show output program sending stdout still pushing back buffer i need check output presence strings in ruby i would like iopopencmd io ioeachline line puts line buffer line end end,2 the tuple numbers lstdata,variations operators seem work unfortunately lstdata str the numbers lstdata is easy way,1 data range the format numbers data the numbers,variations operators seem work unfortunately lstdata str the numbers lstdata is easy way,1 use format str the format numbers lstdata see docs details possible formatting floats decimal points conversion,variations operators seem work unfortunately lstdata str the numbers lstdata is easy way,2 indentation snippets xml tricky business xml processors allowed perform many transformation would expect allowed reindent elements way would like without explicit consent have look pretty printing xml python see indent full xml document,i trying append new child xml file problem i give appropriate format child inserting xml document i have created child minidomdocument appendchild books do i explained well thanks advance,1 try def tmp import maxcut mc import networkx nx g nxcompletegraph mclargesteigenvectorg timeittimers tmp the following might work timeittimersetups stmt mclargesteigenvectorg,i want time function i like use timeit library i find good example net i time function largesteigenvector maxcut library function takes input graph g wich returned function networkx library so i want time block code import maxcut mc import networkx nx g nxcompletegraph mclargesteigenvectorg it obviously works fine than time i import maxcut mc import networkx nx g nxcompletegraph timeittimers mclargesteigenvectorg but says unboundlocalerror local variable mc referenced assignment i know please someone help syntax problem i find decent documentation,1 you statement setup swapped pass arguments timer way round,i want time function i like use timeit library i find good example net i time function largesteigenvector maxcut library function takes input graph g wich returned function networkx library so i want time block code import maxcut mc import networkx nx g nxcompletegraph mclargesteigenvectorg it obviously works fine than time i import maxcut mc import networkx nx g nxcompletegraph timeittimers mclargesteigenvectorg but says unboundlocalerror local variable mc referenced assignment i know please someone help syntax problem i find decent documentation,2 it prefix view paths see documentation patterns the equivalent first example using argument urlpatterns patterns newsviews r articles specialcase r articlesd yeararchive the equivalent second example first argument set urlpatterns patterns urlr zinniaviewsentriesentryindex entryconfindex name zinniaentryarchiveindex,what significance first argument containing example patterns urlpatterns patterns r articles newsviewsspecialcase r articlesd newsviewsyeararchive sometimes i seen filled like urlpatterns patterns zinniaviewsentries urlr entryindex entryconfindex name zinniaentryarchiveindex,3 prefix urls example add newsviews case urlpatterns patterns newsviews r articles specialcase r articlesd nyeararchive,what significance first argument containing example patterns urlpatterns patterns r articles newsviewsspecialcase r articlesd newsviewsyeararchive sometimes i seen filled like urlpatterns patterns zinniaviewsentries urlr entryindex entryconfindex name zinniaentryarchiveindex,1 the fact networkx mostly written python mean scalable claims perfection there always tradeoff if throw money machines much scalability want plus benefits using pythonic graph library if solutions may consume less memory benchmark see i think igraph fully c backed may miss pythonic feel nx,i interested network analysis large networks millions nodes tens millions edges i want able things like parse networks many formats find connected components detect communities run centrality measures like pagerank i attracted networkx nice api good documentation active development years plus python quick develop in recent presentation slides available github claimed unlike many tools nx designed handle data scale relevant modern problemsmost core algorithms nx rely extremely fast legacy code the presentation also states base algorithms networkx implemented cfortran however looking source code looks like networkx mostly written python i familiar source code i aware couple examples networkx uses numpy heavy lifting turn uses cfortran linear algebra for example file networkxnetworkxalgorithmscentralityeigenvectorpy uses numpy calculate eigenvectors does anyone know strategy calling optimized library like numpy really prevalent throughout networkx algorithms also anyone describe scalability issues associated networkx reply networkx lead programmer i posed question networkx mailing list aric hagberg replied the data structures used networkx appropriate scaling large problems eg data structure adjacency list the algorithms various scaling properties ones mention usable eg pagerank connected components linear complexity number edges at point networkx pure python code the adjacency structure encoded python dictionaries provides great flexibility expense memory computational speed large graphs take lot memory eventually run networkx use numpy scipy algorithms primarily based linear algebra in case graph represented copied adjacency matrix using either numpy matrices scipy sparse matrices those algorithms benefit legacy c fortran code used hood numpy scipy,1 there many ways one way use strpartition text moneylogrotated beforeafter textpartition printafter another use strsplit beforeafter textsplit printafter strfind strrfind ind textfind ind textrfind printtextindind all methods rely desired substring immediately following first leftbracket the first two methods also rely desired substring ending nexttolast character text the last method using rfind searches right index rightbracket little general depend quite many potential offbyone constants,i string moneylogrotated i need string how python,1 if string always structure probably simplest solution r moneylogrotated ssfindsfind update after seeing answers slight improvement ssfind exploiting fact closing square bracket last character string,i string moneylogrotated i need string how python,1 if format fixed also use moneylogrotated,i string moneylogrotated i need string how python,1 you could use astype create new array string dtype import numpy np arrnparray printarrastype s yields,i array produced numpy looks follows how convert list so looks follows,2 here sample python script opens file edit editor assigned filetype import os ctypes import cint winfunctype windll ctypeswintypes import hwnd lpcstr uint prototype winfunctypecint hwnd lpcstr lpcstr uint paramflags hwnd text hi caption none flags messagebox prototypemessageboxa windlluser paramflags filename readmetxt osstartfilefilename edit try osstartfilefilename edit except windowserror e messageboxtextstre,how i open file edit command line windows mainly i looking open file default editor associated confused default action filetype this different executing file start filename solution note would require use shellexecute one way another update i added python alternative batch,1 hiding autocomplete going completely depend editor handles autocomplete my editor autocomplete i need use the standard python convention prefix underscore method name this tells user method private used you use double underscores method name invoke name mangling see page details httpdocspythonorgtutorialclasseshtm but still private called as far raising exceptions look inspect object frame info there ton q site tldr you make anything private make harder find,i know thing true private python sometimes need following prevent people calling methods warn allow called modules detect methods used raise warning console even exception would allow start marking methods private without breaking existing code hide private methods ide autocomplete optional probably using one underline name now i wondering someone found beautiful way obtain behaviour maybe one use annotations please remember work existing codebase support gradually factoring existing code the last point almost solved question i use one underscore two underscores,1 python philosophy consenting adults prefix methods underscore mark private don call methods leading underscore outside if you free warned to adopt convetion existing code base rename original methods names leading underscore add wrapper original name throws warning your ide configurable autocompletion if use emacs,i know thing true private python sometimes need following prevent people calling methods warn allow called modules detect methods used raise warning console even exception would allow start marking methods private without breaking existing code hide private methods ide autocomplete optional probably using one underline name now i wondering someone found beautiful way obtain behaviour maybe one use annotations please remember work existing codebase support gradually factoring existing code the last point almost solved question i use one underscore two underscores,3 your big issue memory python simply cannot handle tens millions objects without jumping hoops class implementation the memory overhead many objects high hit gb bit code work there ways around using slots arrays numpy it ok networkx written performance things work i check memory usage as scaling algorithms basically thing matter graphs graph algorithms tend really ugly scaling done wrong likely done right python language,i interested network analysis large networks millions nodes tens millions edges i want able things like parse networks many formats find connected components detect communities run centrality measures like pagerank i attracted networkx nice api good documentation active development years plus python quick develop in recent presentation slides available github claimed unlike many tools nx designed handle data scale relevant modern problemsmost core algorithms nx rely extremely fast legacy code the presentation also states base algorithms networkx implemented cfortran however looking source code looks like networkx mostly written python i familiar source code i aware couple examples networkx uses numpy heavy lifting turn uses cfortran linear algebra for example file networkxnetworkxalgorithmscentralityeigenvectorpy uses numpy calculate eigenvectors does anyone know strategy calling optimized library like numpy really prevalent throughout networkx algorithms also anyone describe scalability issues associated networkx reply networkx lead programmer i posed question networkx mailing list aric hagberg replied the data structures used networkx appropriate scaling large problems eg data structure adjacency list the algorithms various scaling properties ones mention usable eg pagerank connected components linear complexity number edges at point networkx pure python code the adjacency structure encoded python dictionaries provides great flexibility expense memory computational speed large graphs take lot memory eventually run networkx use numpy scipy algorithms primarily based linear algebra in case graph represented copied adjacency matrix using either numpy matrices scipy sparse matrices those algorithms benefit legacy c fortran code used hood numpy scipy,3 this weird way use event object if use none boolean i suggest use dedicated class test type get queue class stopprocessingobject pass qputstopprocessing true dat selfqget typedat stopprocessing or course could keep using multiprocessingevent test type however would probably quite misleading someone else reading code using dedicated type seems much cleaner pythonic edit ok apparently work new class picklable so another idea directly put type inside queue like class stopprocessingobject pass qputstopprocessing true dat selfqget dat stopprocessing according pickle doc classes defined top level module pickled,i code like following class processmultiprocessingprocess stop multiprocessingmanagerevent def initself queue processfn selfq queue selfp processfn superinit def runself true dat selfqget dat processstop selfpdat selfq selfqtaskdone else selfqtaskdone break i cannot compare stop successfully this surprising i using since i believe compares object id docs this address object memory so since i using multiple processes memory address different i compare either though i sure this happens object i create manager i use true singleton true false none work although appropriate solution since values may valid queue so i create variable like singletons compared across processes nb i tried using dedicated class get errors able pickled update the answer seem use class i receiving pickleing problems i trying inner class moving module scope fixed error works fine thanks schnouki here example pointless usage code shows error def fdata queue printdata q multiprocessingjoinablequeue range p processq f pdaemon true pstart qputi qjoin range qputprocessstop qjoin,2 if every entry block starts colon split open entriestxt fp contents fpread entry contentssplit something entry,i imaging going simple task i find i looking exactly previous stackoverflow questions goes i large text files proprietry format look comething like entry name john doe date entry name jane doe date and forth the text files range size kb mb i need split file entry delimiter how could i process file based entry blocks,1 you could use itertoolsgroupby group lines occur entry lists import itertools filename testdat openfilename r f keygroup itgroupbyflambda line linestartswith entry key group listgroup printgroup yields namen john doen n daten n n namen jane doen daten n or process groups really need convert group list openfilename r f keygroup itgroupbyflambda line linestartswith entry key line group,i imaging going simple task i find i looking exactly previous stackoverflow questions goes i large text files proprietry format look comething like entry name john doe date entry name jane doe date and forth the text files range size kb mb i need split file entry delimiter how could i process file based entry blocks,3 there solution using wrapper described link vinay provided started new console window windows start command code wrapper wrapperpy import subprocess time signal sys os def signalhandlersignal frame timesleep print ctrlc received wrapperpy signalsignalsignalsigint signalhandler print wrapperpy started subprocesspopenpython demopy timesleep replace ipc code waits fire ctrlc request oskillsignalctrlcevent code program catching ctrlc demopy import signal sys time def signalhandlersignal frame print ctrlc received demopy timesleep sysexit signalsignalsignalsigint signalhandler print demopy started signalpause work windows whiletrue timesleep launch wrapper like eg pythonprompt import subprocess pythonprompt subprocesspopenstart python wrapperpy shelltrue you need add ipc code allows control wrapper firing oskillsignalctrlcevent command i used sockets purpose application explanation preinformation sendsignalctrlcevent work ctrlcevent oskill ref oskillctrlcevent sends signal processes running current cmd window ref popen creationflagscreatenewprocessgroup work ctrlcevent ignored process groups ref this bug python documentation ref implemented solution let program run different cmd window windows shell command start add ctrlc request wrapper control application application get ctrlc signal the wrapper run cmd window application get ctrlc signal the wrapper shutdown program get ctrlc signal sending processes cmd window ctrlcevent the control program able request wrapper send ctrlc signal this might implemnted trough ipc means eg sockets helpful posts i remove http front links i new user allowed post two links httpsocialmsdnmicrosoftcomforumsenuswindowsgeneraldevelopmentissuesthreaddcabeeaaacfacfaebfca can i send ctrlc sigint application windows sending sigint subprocess python httpbugspythonorgissue httpsscomntstarthtml httpobjectmixcompythonsendingcntrlchtmlpost update ipc based ctrlc wrapper here find selfwritten python module providing ctrlc wrapping including socket based ipc the syntax quite similiar subprocess module usage import winctrlc p winctrlcpopenpython demopy p winctrlcpopenpython demopy p winctrlcpopenpython demopy psendctrlc psendctrlc psendctrlc code import socket import subprocess import time import random import signal os sys class popen port randomrandint connection def startctrlcwrapperself cmd cmdstr start python winctrlcpy cmd strselfport subprocesspopencmdstr shelltrue def createconnectionself selfconnection socketsocketsocketafinet socketsockstream selfconnectionconnect localhost selfport def sendctrlcself selfconnectionsendwrapperterminationreq selfconnectionclose def initself cmd selfstartctrlcwrappercmd selfcreateconnection class wrapper terminationreq terminate ctrlc def createconnectionself port socketsocketsocketafinet socketsockstream sbind localhost port slisten conn addr saccept return conn def waitonctrlcrequestself conn true data connrecv data selfterminationreq ctrlcreceived true break else ctrlcreceived false return ctrlcreceived def cleanupandfirectrlcself conn connclose oskillsignalctrlcevent def signalhandlerself signal frame timesleep sysexit def initself cmd port signalsignalsignalsigint selfsignalhandler subprocesspopencmd conn selfcreateconnectionport ctrlcreqreceived selfwaitonctrlcrequestconn ctrlcreqreceived selfcleanupandfirectrlcconn else sysexit name main commandstring sysargv portno intsysargv wrappercommandstring portno,i test harness written python needs shut program test written c sending c on unix procsendsignalsignalsigint works perfectly on windows throws error signal supported something like i using python windows i impression i able instead procsendsignalsignalctrlcevent anything what i this code creates subprocess windows needs extra argument passed subprocesspopen constant defined unix try kwargs creationflags subprocesscreatenewprocessgroup except attributeerror pass proc subprocesspopenargv stdinopenospathdevnull r stdoutsubprocesspipe stderrsubprocesspipe kwargs,3 you need use offerfull response group get full page offers offers per page the totalofferpages node returned response shows many pages offers to get particular page set offerpage request parameter number less equal totalofferpages for example pseudo request would get second offerpage httpwebservicesamazoncomoncaxml serviceawsecommerceserviceamp awsaccesskeyidaws access key idamp operationitemlookupamp itemidamp conditionallamp responsegroupofferfullamp offerpageamp parameter controls offerpage number versionamp timestampyyyymmddthhmmsszamp signaturerequest signature,i using itemsearch method amazon product api noticed even though total number offers returned pretty high offers returned itemsearch is way get itemsearch return offers i using large response group,1 sure thing add script called postreceive server side git repository githooks directory make sure file executable call makemessages script done i think you find example scripts directory already available hooks have look progit book need,i trying figure way django localistion stuff understood makemessages command needs run every time change strings code i thinking simplifying process using serverside git hook i knowledge git hooks find resources web something like is reason one git hook something like if could explain i could get makemessages command run every time someone commits code repository thanks,3 because string never equal tuple xy intuserx intusery,cords range x range cordsappendx print cords print cords userxrawinputx useryrawinputy xy userx usery print xy xy cords print found match my question print found match given match,3 because userx usery results string cords list contains tuples integers instead constructing string putting x values tuple like xy userx usery or even userx usery cords print found match,cords range x range cordsappendx print cords print cords userxrawinputx useryrawinputy xy userx usery print xy xy cords print found match my question print found match given match,1 if red price mean pointed image price product sold merchantid amazoncom returned offerfull response group to get amazoncom offer listings returned response set merchantid request attribute amazon you use node using offers offer offerlisting price formattedprice consistently get red price if offers returned using amazoncom merchantid amazon product stock perhaps sold third parties for example following pseudo request get offer listings sold amazoncom httpwebservicesamazoncomoncaxml serviceawsecommerceserviceamp awsaccesskeyidaws access key idamp operationitemlookupamp itemidamp conditionallamp responsegroupofferfullamp make sure set offerfull merchantidamazonamp set one get amazoncom offers versionamp timestampyyyymmddthhmmsszamp signaturerequest signature see documentation offerfull response group info,i trying get list products prices using itemsearch api corresponds list products amazon i able get matching set products able consistently get prices listed red website i getting price first offer offersofferofferlistingpriceformattedprice guessing right way get red price was wondering someone could help thanks,1 i run code looks like xy userx usery string like your list list tuples,cords range x range cordsappendx print cords print cords userxrawinputx useryrawinputy xy userx usery print xy xy cords print found match my question print found match given match,1 to prevent showing use three options set editablefalse model field use fields attribute modelform inner meta class use exclude attribute modelform inner meta class which one use depends often want field show never select cases see django docs information,i model class gallerymodelsmodel headimage modelsimagefielduploadtogallery with form class galleryformmodelform class meta model gallery and view gform galleryformrequestpost requestfiles instancegalleryinstance in template filled form shown for headimage field shows link image related headimage field fileinput change label gformheadimage now instead link picture i want put image img tag i template follows img src gformheadimagevalue what i link show form,1 first according documentation second instead seconds addcronjob method prototype def addcronjobself func yearnone monthnone daynone weeknone dayofweeknone hournone minutenone secondnone startdatenone argsnone kwargsnone options schedules job completed times match given expressions param func callable run param year year run param month month run param day day month run param week week year run param dayofweek weekday run monday param hour hour run param second second run param args list positional arguments call func param kwargs dict keyword arguments call func param name name job param jobstore alias job store add job param misfiregracetime seconds designated run time job still allowed run return scheduled job rtype classapschedulerjobjob case write something like apschedulerscheduler import scheduler def jobdefvar var print strvar strvar scheduler saddcronjobjobdef args hello second sstart,i trying schedule con style job using advanced python scheduler everything fine whenever i use function require parameters however i unable schedule job passing one arguments could please advise apschedulerscheduler import scheduler def jobdefvar var print strvar strvar scheduler saddcronjobjobdef hello seconds sstart error traceback recent call last file stdin line module file usrlocallibpythondistpackagesapschedulerpyeggapscheduler schedulerpy line addcronjob startdatestartdate file usrlocallibpythondistpackagesapschedulerpyeggapschedulertriggerscroninitpy line init field fieldclassfieldname exprs isdefault file usrlocallibpythondistpackagesapschedulerpyeggapschedulertriggerscronfieldspy line init selfcompileexpressionsexprs file usrlocallibpythondistpackagesapschedulerpyeggapschedulertriggerscronfieldspy line compileexpressions selfcompileexpressionexpr file usrlocallibpythondistpackagesapschedulerpyeggapschedulertriggerscronfieldspy line compileexpression expr selfname,3 look namespace prefixes docs if want element httpschemasgooglecomgsa namespace need search like import lxmletree et xml entry xmlnshttpwwwworgatom xmlnsgsahttpschemasgooglecomgsa gsacontent namereportnamebbbgsacontent gsacontent namecollectionnamedefaultcollectiongsacontent gsacontent namereportdatedategsacontent entry ns rootns httpwwwworgatom gsa httpschemasgooglecomgsa tree etfromstringxml el treexpath gsacontent namespacesns print elattrib name print lentreexpath rootnsentry namespacesns,how i escape forward slash character xpath query my tags contain url i need able i using lxml python alternatively possible xpath query substring path examples xml entry xmlnshttpwwwworgatom xmlnsgsahttpschemasgooglecomgsa gsacontent namereportnamebbbgsacontent gsacontent namecollectionnamedefaultcollectiongsacontent gsacontent namereportdatedategsacontent entry when i run following treefromstringxml elt treexpath elttag it returns httpwwwworgatomentry httpschemasgooglecomgsacontent httpschemasgooglecomgsacontent httpschemasgooglecomgsacontent running treexpath entry returns empty list i need able either query httpwwwworgatomentry tag query entry anywhere tag,2 you calling ospathbasename path variable that means trying zip file newdirfile drop new part path end dirfile valid path relative current directory if simply remove call ospathbasename zip files correctly myzipwriteospathjoinpath file although may want zipfile terms paths if start oswalk inside top level directory may get want name main pathospathjoinosgetcwd new myzip zipfilezipfile myzippedzip w change top level directory oschdirpath zipfunc myzip myzipclose given hierarchy like homelarsnew file file dir file file file this creates zipfile looks like archive myzippedzip length date time name file file dirfile dirfile dirfile files if actual goal zip files top level descend subdirectories really need oswalk you use oslistdir instead ospathisfile make sure dealing files subdirectories,i path homeminenew contains files sub directories i want zip files path new path zipped folder contains newfile newfile etc i tried import zipfile import osglob def zipfuncpath myzip pathdirs files oswalkpath file files ospathisfileospathjoinpathfile myzipwriteospathjoinospathbasenamepath file name main pathr homeggousnew myzip zipfilezipfile myzippedzip w zipfuncpathmyzip myzipclose but gives error no file directory newfiledoc,1 autocorrelation comes two versions statistical convolution they except little detail the former normalized interval here example statistical one def acfx length return numpyarraynumpycorrcoefxi xi range length,i need autocorrelation set numbers i understand correlation set i tried using numpy correlate function i believe result almost always gives vector first number largest ought so question really two questions what exactly numpycorrelate how i use something else autocorrelation,3 try ospathisfilesstidxgenome cmd python spacetierzuchtmgholamistampystampypy g sfa genome pathway in original code paretheses misplaced getting interpreted remainder operator interpreter complain syntax error,i trying run series commands two input files i want avoid thing already done to make clear commands subprocess import call import ospath pathway rawinputplease give pathway genome folder fa files genome rawinputplease type genome name eg chickbuild building genome stidx stampy cmd python spacetierzuchtmgholamistampystampypy g sfa genome pathway building genome fa bwa cmd cat sfa sfa pathway genome building index bwa cmd bwa index sfa genome callcmd shelltrue i want add loop command file already exists run command i tried work ospathisfilesstidx genome false cmd python spacetierzuchtmgholamistampystampypy g sfa genome pathway i trying check stidx format chosen file name already exists and i want fa format several others,1 this copyonwrite existing references continue exist replaced nothing see move along,suppose i copy existing list existinglist copiedlist existinglist copiedlist cow happens some edits i heard python uses copyonwrite either copiedlist existinglist mutated is true seems like overcomplication requires locking place think multithreading for clarity i looking cow impl i trying understand python standard behavior,1 most python implementations use locking place anyway ruins multithreading anyway gil but still i think copyonwrite used it requires locking organization pretty lowlevel optimization cost copying smaller usual everything reference copy n pointers you read source care enough i dissect methods may copy quick search copy write lock find anything indicating cow similar mechanism,suppose i copy existing list existinglist copiedlist existinglist copiedlist cow happens some edits i heard python uses copyonwrite either copiedlist existinglist mutated is true seems like overcomplication requires locking place think multithreading for clarity i looking cow impl i trying understand python standard behavior,1 no if want list implementation copyonwrite try blist,suppose i copy existing list existinglist copiedlist existinglist copiedlist cow happens some edits i heard python uses copyonwrite either copiedlist existinglist mutated is true seems like overcomplication requires locking place think multithreading for clarity i looking cow impl i trying understand python standard behavior,1 possible options could involve use mmap with map file memory area making contents accessible ram the components read soon accessedneeded probably normal page size os kib read complete file memory this essentially mmap without help os otoh done one run instead kib steps if data ram file use stringio emulate file feed arrayfromfile having second glance omit stringio stuff use arrayfromstring instead using one read normally faster repetitive infileseek datafromfileinfile calls especially read one value per call except maybe step size volumesize sufficiently big skipping several hundreds thousands bytes could faster way,i lot binary files containing output numerical model they flat binary files containing output floating point numbers the files correspond fourdimensional array sorted tzyx order x varying fastest the thing given xy z i need values the simple solution simply reading everything one large numpy array taking datazyx works course efficient i need read many files what i come following assuming startindex volumesize represent correct things dataarrayarray f filemyfilename rb infile hour rangeamountofsteps hour infileseekstartindexdataitemsize else infileseekdataitemsizevolumesize datafromfileinfile i bother enddianness portability although latter course merits the whole thing runs linux highly unlikely ever run something else so question is way higher performance this done many files i tried parallelization really help getting new hardware option ssds even less amount data involved neither changing fileformat,1 if i i take look numpymemmap i used past problem similar good results,i lot binary files containing output numerical model they flat binary files containing output floating point numbers the files correspond fourdimensional array sorted tzyx order x varying fastest the thing given xy z i need values the simple solution simply reading everything one large numpy array taking datazyx works course efficient i need read many files what i come following assuming startindex volumesize represent correct things dataarrayarray f filemyfilename rb infile hour rangeamountofsteps hour infileseekstartindexdataitemsize else infileseekdataitemsizevolumesize datafromfileinfile i bother enddianness portability although latter course merits the whole thing runs linux highly unlikely ever run something else so question is way higher performance this done many files i tried parallelization really help getting new hardware option ssds even less amount data involved neither changing fileformat,1 weird i think work anyway use talreplace wrong gonna replace whole tag what want replace contents tag talcontent tr talrepeatrow results td talcontentpythonrow name nametd td talcontentpythonrow value td tr the python also superfluous chameleon then also use attribute access instead dict access templates tr talrepeatrow results td talcontentrownamethe nametd td talcontentrowvaluetd tr lastly use substitution syntax instead talcontent that give much compact spelling tr talrepeatrow results tdrownametd tdrowvaluetd tr and maybe solve actual problem way,i really struggling get tal chameleonpyramid play nice i view pyramid returns example following def viewrequest return results name alice value name bob value name charlie value i template contains following bit html doctype html html headhead body table thead tr tdkeywordtd td classcentermean positiontd tr thead tbody tr talrepeatrow results tdrownametd tdrowvaluetd tr tbody table body html i hoping html output following table thead tr classodd tdnametd td classcentreagetd tr thead tbody tr tdalicetd tdtd tr tr tdbobtd tdtd tr tr tdcharlietd tdtd tr tbody table however pyramid throws error i try run raise parseerrorunexpected end tag token parseerror unexpected end tag string tr i thought rather weird i removed closing tr get following error nameerror row expression pythonrow name i really stuck help would appreciated,2 use remove method xmlelement treeetfromstringxml bad treexpathfruitstate rotten badgetparentremovebad i grab parent element call remove directly print ettostringtree prettyprinttrue xmldeclarationtrue if i compare acorn version mine work even elements remove directly root node xml,i need completely remove elements based contents attribute using python lxml example import lxmletree et xml groceries fruit staterottenapplefruit fruit statefreshpearfruit fruit statefreshstarfruitfruit fruit staterottenmangofruit fruit statefreshpeachfruit groceries treeetfromstringxml bad treexpathfruitstate rotten remove element tree print ettostringtree prettyprinttrue i would like print groceries fruit statefreshpearfruit fruit statefreshstarfruitfruit fruit statefreshpeachfruit groceries is way without storing temporary variable printing manually newxmlgroceriesn elt treexpath fruitstate fresh newxmlettostringelt newxmlgroceries,3 you looking remove function call tree remove method pass subelement remove import lxmletree et xml groceries fruit staterottenapplefruit fruit statefreshpearfruit punnet fruit staterottenstrawberryfruit fruit statefreshblueberryfruit punnet fruit statefreshstarfruitfruit fruit staterottenmangofruit fruit statefreshpeachfruit groceries treeetfromstringxml bad treexpathfruitstate rotten badgetparentremovebad print ettostringtree prettyprinttrue result groceries fruit statefreshpearfruit fruit statefreshstarfruitfruit fruit statefreshpeachfruit groceries,i need completely remove elements based contents attribute using python lxml example import lxmletree et xml groceries fruit staterottenapplefruit fruit statefreshpearfruit fruit statefreshstarfruitfruit fruit staterottenmangofruit fruit statefreshpeachfruit groceries treeetfromstringxml bad treexpathfruitstate rotten remove element tree print ettostringtree prettyprinttrue i would like print groceries fruit statefreshpearfruit fruit statefreshstarfruitfruit fruit statefreshpeachfruit groceries is way without storing temporary variable printing manually newxmlgroceriesn elt treexpath fruitstate fresh newxmlettostringelt newxmlgroceries,3 your regex wrong the following works import rx recompile note change var bla bla bla bla var rxfindallvar number int joinvar print number note code find digits inside string regardless whether consecutive merge single number to get groups consecutive digits change regex,example import rx recompile var bla bla bla var rxfindallvar number joinvar my question convert number variable int try int get error or way create variable int another method,2 you could use matplotlibdatesnumdate convert nums back datetime objects then call isoformat get date string iso format import numpy np import matplotlibdates md def numisodatenum resultmdnumdatenumisoformat return result rawtable nploadtxt ibtsampletxt delimiter skiprows converters mddatestrnum dtype names season isotime latitude longitude enum formats uint float f f uint convert isotime dtype object this allows column hold float values first strings later note astype returns copy calling copy explicitly longer needed also since called copy i assume holding two copies array memory problem if memory tight could write array linebyline using csv module instead using npsavetxt but since memory problem npsavetxt convenient sortable rawtableastype names season isotime latitude longitude enum formats uint object f f uint sortable npsortsortable order isotime sortable isotime numisodatenum num sortable isotime npsavetxt ibtsortedtxt sortable fmt dsffd ps i recommend never using module import especially module numpy it overwrites number python builtin functions abs min max sum round etc not make harder call python builtins also makes easy write code looks right contains hardtofind subtle bugs,i new python basic question i find solution net i table named ibtsampletxt containing seasonisotimelatitudelongitudeenum what i would like import numpy array processing time simply sort records par date export processed table new txt file numpy import import pylab rawtable loadtxt ibtsampletxt delimiter skiprows converters pylabdatestrnum dtype names season isotime latitude longitude enum formats uint float float float uint sortable sortrawtable order isotime copy savetxt ibtsortedtxt sortable fmt dfffd i ti use pylabdatestrnum function importation find inverse function export date time iso format any help idea would helful,2 it implementation detail here different implementations respond code apy bpy cpy cpython ok bad bad cpython ok bad bad jython ok ok bad jython bad bad bad ironpython ok bad ok my reading exlplicit line joining section python language reference three examples could treated valid two physical lines may joined logical lines using backslash characters follows physical line ends backslash part string literal comment joined following forming single logical line deleting backslash following endofline character if cpython changed accept three examples valid i doubt would noticed users change character language break code,i writing python parser learn flex bison i trying find first programs valid python apy this valid python produces error bpy this valid python produces error file bpy line indentationerror unexpected indent cpy true pass this valid python produces error file cpy line this valid python syntaxerror invalid syntax i using python r apr gcc linux ubuntu however testing ideonecom suggests behavior python,2 probably in end print call sysstdoutwrite but since print built function probably implemented c might even faster calling sysstdoutwrite since io go object sysstdout returns bottleneck the true sysstdin there magic tricks make faster if need faster io try things write file instead use buffered io pipe stdout using buffer command small shell script use memory mapped file make sure process reads output keep for example dos console pretty slow if pipe output slow command block python process edit seems like spojpl kind programmer shootout site in case io speed culprit you used bad algorithm solve problem the speed difference good fair performance easily times by changing lines code i could make code run less seconds took minutes,i solving problems spojpl using python peoples fast result simple problems makes wonder faster way handle input output i tried using input print sysstdinreadline sysstdoutwrite rather line sysstdin handle input sysstdoutwriteoutput process line i also tried collect output lists print everything processed but produce similar execution times is faster way handle input output stdinout,2 don use regular expressions filter uch easier quicker bla bla bla bla intfilterstrisdigit the code merge numbers string single string if want use bla bla bla mapint filterstrisdigit ssplit the recipes adapted python x bla bla bla bla intjoinfilterstrisdigit bla bla bla listmapint filterstrisdigit ssplit,example import rx recompile var bla bla bla var rxfindallvar number joinvar my question convert number variable int try int get error or way create variable int another method,2 select properties rundebug settings select related file right panel click edit button it open properties selected file there arguments tab,i new python amp eclipse difficulties understanding pass command line argument script running within eclipsepydev the following link explains pass command line argument python script to pass command line argument module argechopy code link argechopy import sys arg sysargv print arg i would need type python console youlocalhost py python argechopy argechopy youlocalhost py python argechopy abc def argechopy abc def how would i pass arguments python script within eclipsepydev thanks,1 steven quote relevant still directly explain situation i think key insight line continuation character makes python treat line whitespace apy it seems like treating first line whitespace it line continuation character reached newline removed since nothing else line exist purposes parsing single line comment note jython treats basically expected valid python code expected later line bpy never makes comment soon line continuation character reached line whitespace indentation becomes error cpy the comment irrelevant get error amount whitespace comment next line you need actual python code line following line continuation character,i writing python parser learn flex bison i trying find first programs valid python apy this valid python produces error bpy this valid python produces error file bpy line indentationerror unexpected indent cpy true pass this valid python produces error file cpy line this valid python syntaxerror invalid syntax i using python r apr gcc linux ubuntu however testing ideonecom suggests behavior python,1 the following probably fastest read input using osread somebigenoughnumber process output collecting results list results write output using oswrite joinresults i remember one case i noticed osread oswrite sometimes faster using python io i remember details,i solving problems spojpl using python peoples fast result simple problems makes wonder faster way handle input output i tried using input print sysstdinreadline sysstdoutwrite rather line sysstdin handle input sysstdoutwriteoutput process line i also tried collect output lists print everything processed but produce similar execution times is faster way handle input output stdinout,2 your regular expression simply character set containing characters b a k there test what probably meant bidask,can someone explain weird behavior python obviously string test contain either bid ask why matching import patr bidask regrecompilepat regsearch test print matched matched,1 defines character class matching character listed inside what wanted par r bidask however use regex following instead whatever bid ask one two else if need perform substring check thanks agf anyword whatever word bid ask one words sting whatever,can someone explain weird behavior python obviously string test contain either bid ask why matching import patr bidask regrecompilepat regsearch test print matched matched,3 character class matcher means match character set you probably wanted alternation like r bidask,can someone explain weird behavior python obviously string test contain either bid ask why matching import patr bidask regrecompilepat regsearch test print matched matched,3 i think want instead you told match single character group bidask string contains,can someone explain weird behavior python obviously string test contain either bid ask why matching import patr bidask regrecompilepat regsearch test print matched matched,1 there copyonwrite when run copiedlist existinglist new list built populated immediately here source httphgpythonorgcpythonfileobjectslistobjectcl,suppose i copy existing list existinglist copiedlist existinglist copiedlist cow happens some edits i heard python uses copyonwrite either copiedlist existinglist mutated is true seems like overcomplication requires locking place think multithreading for clarity i looking cow impl i trying understand python standard behavior,2 internet searches topic came surprisingly results i figured i post question answer others interested topic the following client server applications demonstrate accomplish linux standard python interpreter no extensions required due use embedded constants code linuxspecific server usrbinenv python import struct socket import socket afunix sockstream solsocket sopeercred pulled usrincludeasmgenericsocketh socketafunix sockstream sbind tmppasscred slisten conn addr saccept creds conngetsockoptsolsocket sopeercred structcalcsize pid uid gid structunpack creds print pid uid gid pid uid gid client usrbinenv python socket import socket afunix sockstream solsocket sopasscred pulled usrincludeasmgenericsocketh socketafunix sockstream ssetsockoptsolsocket sopasscred sconnect tmppasscred sclose unfortunately sopeercred sopasscred constants exported python socket module must entered hand although value unlikely change possible this considered applications using approach,how unix socket credential passing accomplished python,3 def buildtestsuite suite unittesttestsuite testcase globglob srctestsuitetestpy modname ospathsplitexttestcase moduleimportmodname suiteaddtestunittesttestloaderloadtestsfrommodulemodule return suite,tried def buildtestsuite suite unittesttestsuite testcase globglob srctestsuitetestpy module ospathsplitexttestcase print module print typemodule suiteaddtestimportmodulebuildtestsuite return suite get eror traceback recent call last file runtestspy line results main file runtestspy line main results unittesttexttestrunnerrunbuildtestsuite file runtestspy line buildtestsuite suiteaddtestimportmodulebuildtestsuite attributeerror module object attribute buildtestsuite,3 if content parsing xml using regular expressions use parser lxml import lxmletree et xml root name james gold name said meet name mable helen name tomorrow night root treeetfromstringxml name treexpathname print nametextstrip result james gold mable helen,i trying parse file contains annotation person names form name james gold name said meet name mable helen name tomorrow night i trying python regex working i using annotation refindall namename lines i want recover entries within name tag tags could different lines i tried concatenating lines removing newline characters avail ideas,2 spoj lets choose among variety programming languages are comparing execution time solutions written programming languages just fun i submitted following solutions first problem codename test compare runtimes c solution g include iostream int main int char int number stdcin number ampamp number stdcout number stdendl see submission python solution import sys line sysstdin number intline number break print number see submission conclusion i sure gets absolute best performance either languages much code optimize i get time measurement c measurement python code assuming sequence numbers submitted programs i think comparison runtimes solutions languages almost meaningless see next paragraph now true simple problems most advanced problems require choosing right algorithm problem choosing wrong one drastic consequences in cases carefully crafted python solutions might still slower carefully crafted c solutions good python solution beat naã¯ve solution written language,i solving problems spojpl using python peoples fast result simple problems makes wonder faster way handle input output i tried using input print sysstdinreadline sysstdoutwrite rather line sysstdin handle input sysstdoutwriteoutput process line i also tried collect output lists print everything processed but produce similar execution times is faster way handle input output stdinout,1 it also possible use ipython interface qt backend achieve similar result import matplotlib import pylab pl f plfigure fmanager plgetcurrentfigmanager fmanagerwindowmove plshow with fmanager basically pyqt object allows modify window properties like,can control matplotlib places figures screen i want generate four figures four separate windows overlap,2 assuming annotated file xml file use acorn solution case use flags skip newlines use better src name james gold name said meet name mable helen name tomorrow night sstrip refindallr namename src redotall james gold mable helen then strip results get proper string happened skip newline also regex missing operator therefore consuming everything last name tag,i trying parse file contains annotation person names form name james gold name said meet name mable helen name tomorrow night i trying python regex working i using annotation refindall namename lines i want recover entries within name tag tags could different lines i tried concatenating lines removing newline characters avail ideas,2 you probably looking max function mylist maxmylist,we given list numbers l example l what short form extracting maximum number words short form xl l xi xi,2 assuming file directory py file import os lines openospathjoinosgetcwd draculatxt r readlines,i trouble reading text file list i moment lines open draculatxt r readlines draculatxt text file directory program however upon running program python comes no file directory draculatxt i idea find text file read list called lines anyone ideas,1 the file name looked current working directory necessarily directory script lives try using full path file make sure working directory correct you check working directory py printing osgetcwd inside script make sure import os if casesensitive file system check case file name,i trouble reading text file list i moment lines open draculatxt r readlines draculatxt text file directory program however upon running program python comes no file directory draculatxt i idea find text file read list called lines anyone ideas,3 the bodyread method works properly request body processed happens requestprocessrequestbody true default request method requestmethodwithbodies put post default get probably used requesting page browser,i problems accessing http requests bodies cherrypy framework i using cherrypy x arch linux machine w python aptana web studio ide when i try access request body via usual cherrypyrequestbodyread get error file usrlibpythonsitepackagescherrypycpreqbodypy line read return selffpreadsize fpout typeerror read takes positional arguments given the code causing error import cherrypy class test def indexself printcherrypyrequestbodyread printcherrypyrequestbodyreadline works return helloworld indexexposed true name main cherrypyquickstarttest however using cherrypyrequestbodyreadline cherrypyrequestbodyreadlinesn instead cherrypyrequestbodyread skim request body fine i tried googling solution found none considering total python newbie must something wrong thanks advance precious help,3 looks like buffer getting filled your buffer fill network requests make cleared server acknowledges receipt data not sure better way could try giving server time acknowledge receipt short timepause within loop,here code conn httplibhttpconnection connrequestpost apijob someparams headers connclose problem sending request server use loop example rangen conn httplibhttpconnection connrequestpost apijob someparams headers connclose rises exception interesting request successfull traceback recent call last file usrlibpythonsitepackagesdjangocoreserversbasehttppy line run selffinishresponse file usrlibpythonsitepackagesdjangocoreserversbasehttppy line finishresponse selfwritedata file usrlibpythonsitepackagesdjangocoreserversbasehttppy line write selfsendheaders file usrlibpythonsitepackagesdjangocoreserversbasehttppy line sendheaders selfsendpreamble file usrlibpythonsitepackagesdjangocoreserversbasehttppy line sendpreamble date srn httpdate file usrlibpythonsocketpy line write selfflush file usrlibpythonsocketpy line flush selfsocksendallviewwriteoffsetwriteoffsetbuffersize error errno broken pipe exception happened processing request traceback recent call last file usrlibpythonsocketserverpy line handlerequestnoblock selfprocessrequestrequest clientaddress file usrlibpythonsocketserverpy line processrequest selffinishrequestrequest clientaddress file usrlibpythonsocketserverpy line finishrequest selfrequesthandlerclassrequest clientaddress self file usrlibpythonsitepackagesdjangocoreserversbasehttppy line init basehttprequesthandlerinitself args kwargs file usrlibpythonsocketserverpy line init selffinish file usrlibpythonsocketserverpy line finish selfwfileflush file usrlibpythonsocketpy line flush selfsocksendallviewwriteoffsetwriteoffsetbuffersize error errno broken pipe suggestions,1 i little surprised first example work check cookbook entry pyramid docs see helps httpdocspylonsprojectorgprojectspyramidcookbookenlateststaticassetsfileshtmlservingfilecontentdynamically,i new python pyramid framework kindly help i html dynamically generated this html generated python script dynamically writes tagstables extracted xyzhtml using beautifulsoup another abchtml now need send html page abchtml back response object pyramidresponse i tried following resp response respheaderlist contenttype texthtml charsetutf respappiter open abchtml r return resp also open abchtml r f data fread fclose return responsedatacontenttype texthtml work ps i cannot use rendererpackagesubpackabchtml similar renderer generated html stored dynamically generated location everytime cannot guess final storage location html file thanks advance help,1 you change collation text field utfgeneralci problem solved notice cannot done django,i got strange error message tried save firstname lastname django authuser model failed examples user userobjectcreateuserusername email password userfirstname u rytis userlastname u slatkeviäius usersave incorrect string value xcxdius column lastname row userfirstname u ð’ð°ð»ðµñ€ð¸ð¹ userlastname u ð‘ð¾ð³ð´ð°ð½ð¾ð² usersave incorrect string value xdxxdxbxdxbb column firstname row userfirstname u krzysztof userlastname u szukieå‚ojä‡ usersave incorrect string value xcxojxcx column lastname row succeed examples userfirstname u marcin userlastname u krã³l usersave succeed mysql settings mysql show variables like char variablename value charactersetclient utf charactersetconnection utf charactersetdatabase utf charactersetfilesystem binary charactersetresults utf charactersetserver utf charactersetsystem utf charactersetsdir usrsharemysqlcharsets rows set sec table charset collation table authuser utf charset utfgeneralci collation results update command it raise error updating values authuser table using update command mysql update authuser set lastname slatkeviäiusa id query ok row affected warning sec rows matched changed warnings mysql select lastname authuser id lastname slatkeviiusa row set sec postgresql the failed values listed updated postgresql table i switched database backend django it strange mysql show character set charset description default collation maxlen utf utf unicode utfgeneralci but httpwwwpostgresqlorgdocsinteractivemultibytehtml i found following name byteschar utf is means unicode char maxlen bytes postgresql bytes mysql caused error,3 x z w lst maxdvalues k v ditems lstv k printlst prints x z w,assume dictionary translates strings numbers how reverse list let assume fill mapped numbers empty string here example works dicintolist x z w x z w,2 the simplest way flip dict iterate maximum value key dict original x z w dictv k k v originaliteritems print dgeti rangemaxd,assume dictionary translates strings numbers how reverse list let assume fill mapped numbers empty string here example works dicintolist x z w x z w,1 it data buffer standard applicationxwwwformurlencoded format the urlliburlencode function takes mapping sequence tuples returns string format urllib doc,so i adapted urllib suggested answers another question class httprequesturllibrequest def initself args kwargs selfmethod kwargspop method get urllibrequestinitself args kwargs def getmethodself return selfmethod works nicely put json req httprequesturlurl method put datajsondumpsmetadata response urlliburlopenreq fails data binary data partial stacktrace file capplpythonliburllibpy line urlopen return openeropenurl data timeout file capplpythonliburllibpy line open response selfopenreq data file capplpythonliburllibpy line open open req file capplpythonliburllibpy line callchain result funcargs file capplpythonliburllibpy line httpopen return selfdoopenhttplibhttpconnection req file capplpythonliburllibpy line doopen hrequestreqgetmethod reqgetselector reqdata headers file capplpythonlibhttplibpy line request selfsendrequestmethod url body headers file capplpythonlibhttplibpy line sendrequest selfendheadersbody file capplpythonlibhttplibpy line endheaders selfsendoutputmessagebody file capplpythonlibhttplibpy line sendoutput msg messagebody unicodedecodeerror ascii codec decode byte xe position ordinal range is way i fix,1 complex python objects must representable dictionary simple types order serialize json the object json serializable error basically means python json encoder know serialize object so result geopt serialize like return jsondumps lat resultlat lon resultlon,i working simple app engine application utilize geosearching proximityfetch i perform search extra filtering data goes well i checked number returned results expected however i tried dump json using simple json i got following error typeerror backendmodelslisting object xcc json serializable this way i define object code class listinggeomodel currencydbintegerproperty default currencyeuro titledbstringpropertyrequired true admins dbreferenceproperty user some uninteresting properties goes only integer string properties active dbbooleanproperty staticmethod def getlistingfrompoint lat lon maxdistmaxsearchradius maxresultmaxsearchresult startdatenoneenddatenone richquery listingall result listingproximityfetch richquery geogeotypespoint lat lon maxresults maxresult maxdistance maxdist result list richquery validlist list result icheckavailability startdate enddate return validlist and method i call proximity search lon selfrequestargsgetlon none lat selfrequestargsgetlat none checkin selfrequestargsgetcheckin none checkout selfrequestargsgetcheckout none lon lat return response jsondumps error desription result listinggetlistingfrompoint lat floatlat lon floatlon startdate checkin enddate checkout return jsondumps result while attempting find reason problem i tried return dict first result search i i got following error typeerror datastoretypesgeopt json serializable which leads believe something wrong way i handle geo points i tried searching errors result clues ps complete stacktrace file cprogram filesgooglegoogleappenginegoogleappengineextappstatsrecordingpy line appstatswsgiwrapper result appenviron appstatsstartresponse file cusersroisemantvpycharmprojectsgayvilletipfytipfyapppy line dispatch rv selfhandleexceptionrequest e file cusersroisemantvpycharmprojectsgayvilletipfytipfyapppy line dispatch rv selfrouterdispatchrequest file cusersroisemantvpycharmprojectsgayvilletipfytipfyroutingpy line dispatch rv rv file cusersroisemantvpycharmprojectsgayvilletipfytipfyhandlerpy line call response selfdispatch file cusersroisemantvpycharmprojectsgayvilletipfytipfyhandlerpy line dispatch return selfhandleexceptionexceptione file cusersroisemantvpycharmprojectsgayvilletipfytipfyhandlerpy line dispatch return selfmakeresponsemethodrequestruleargs file cusersroisemantvpycharmprojectsgayvilletipfybackendhandlerspy line get return jsondumps result file cprogram filesgooglegoogleappenginelibdjangodjangoutilssimplejsoninitpy line dumps kwencodeobj file cprogram filesgooglegoogleappenginelibdjangodjangoutilssimplejsonencoderpy line encode chunks listselfiterencodeo file cprogram filesgooglegoogleappenginelibdjangodjangoutilssimplejsonencoderpy line iterencode chunk selfiterencodelisto markers file cprogram filesgooglegoogleappenginelibdjangodjangoutilssimplejsonencoderpy line iterencodelist chunk selfiterencodevalue markers file cprogram filesgooglegoogleappenginelibdjangodjangoutilssimplejsonencoderpy line iterencode chunk selfiterencodedefaulto markers file cprogram filesgooglegoogleappenginelibdjangodjangoutilssimplejsonencoderpy line iterencodedefault newobj selfdefaulto file cprogram filesgooglegoogleappenginelibdjangodjangoutilssimplejsonencoderpy line default raise typeerrorr json serializable,2 you trying automatically convert python unicode string regular byte string json always unicode http must send bytes if confident reciever understand json encoded data particular encoding encode way urlliburlopenurllibrequesthttpexamplecom datau uca traceback recent call last unicodeencodeerror ascii codec cannot encode character u uca position ordinal range urlliburlopenurllibrequesthttpexamplecom datau uca encode utf addinfourl whose fp socketfileobject object xdfbe note encode utf converts unicode str utf the implicit conversion would use ascii cant encode nonascii characters tldr datajsondumpsblablaencode utf,so i adapted urllib suggested answers another question class httprequesturllibrequest def initself args kwargs selfmethod kwargspop method get urllibrequestinitself args kwargs def getmethodself return selfmethod works nicely put json req httprequesturlurl method put datajsondumpsmetadata response urlliburlopenreq fails data binary data partial stacktrace file capplpythonliburllibpy line urlopen return openeropenurl data timeout file capplpythonliburllibpy line open response selfopenreq data file capplpythonliburllibpy line open open req file capplpythonliburllibpy line callchain result funcargs file capplpythonliburllibpy line httpopen return selfdoopenhttplibhttpconnection req file capplpythonliburllibpy line doopen hrequestreqgetmethod reqgetselector reqdata headers file capplpythonlibhttplibpy line request selfsendrequestmethod url body headers file capplpythonlibhttplibpy line sendrequest selfendheadersbody file capplpythonlibhttplibpy line endheaders selfsendoutputmessagebody file capplpythonlibhttplibpy line sendoutput msg messagebody unicodedecodeerror ascii codec decode byte xe position ordinal range is way i fix,1 if really looking browsing directory structure import os import wx class mainwindowwxframe def initself args kwargs wxframeinitself args kwargs selfpanel wxpanelself selfdir wxgenericdirctrlselfpanel size stylewxdirctrldironly selffiles wxlistctrlselfpanel stylewxlclist selfsizer wxboxsizer selfsizeraddselfdir flagwxexpand selfsizeraddselffiles proportion flagwxexpand selfborder wxboxsizer selfborderaddselfsizer wxall wxexpand selfpanelsetsizerandfitselfborder selfshow selfdirbindwxevttreeselchanged selfonselect def onselectself e selffilesclearall list oslistdirselfdirgetpath reversedlist selffilesinsertstringitem app wxappfalse win mainwindownone size appmainloop some helpful examples httpwikiwxpythonorganothertutorialfilehunter httpginstromcomscribblesfilelistwithiconsonwxpythonwindows if would like similar widget look wxlibagwcustomtreectrl it may exactly want source widget wxpython modify match needs import wx import wxlibagwcustomtreectrl ct class mainwindowwxframe def initself args kwargs wxframeinitself args kwargs selfpanel wxpanelself selfdir ctcustomtreectrlselfpanel size stylewxsunkenborder agwstylecttrfullrowhighlight cttrhideroot cttrnolines cttrrowlines root selfdiraddrootthe root item child selfdirappenditemroot test child selfdirappenditemchild test child selfdirappenditemchild test child selfdirappenditemroot test selfdirexpandall selfsizer wxboxsizer selfsizeraddselfdir proportion flagwxexpand selfborder wxboxsizer selfborderaddselfsizer wxall wxexpand selfpanelsetsizerandfitselfborder selfshow app wxappfalse win mainwindownone size appmainloop,my question simple get make navigation panel similar finder mac os x explorer windows nautilus ubuntu as using wxtreectrl work example httppastepocooorgshow as see first problem huge pink strip left remove second root else put buffer hidden buffer second kludgy third really either three example looks like so i get navigation panel similar examples well except tree ctrl example p update on windows windows least problem left side white column might linux macos x tree ctrl widget generically drawn one could run example macos x see pink column pink example sets background color left tree ctrl update itunes example there seems little misunderstanding question file manager folder view i looking navigation panel side i for example itunes also file manager left side bunch click able tabs used navigate example itunes music movies tv shows audiobooks apps library also problem tree ctrl doesn t work linux see image,1 byte order specified single character beginning format string values structunpack h data,i binary file i reading byte values stored reverse byte order little endian eg d b f the original program created values stores internally shorts those values correspond i trying read values using python although probably run much older systems eg i tried using val val val val val val val structunpackh h h h h h h data course values come wrong after looking documentation struct i thought i able use something like val structunpackh h testing i got structerror bad char struct format how i unpack values correct byte ordering am i stuck reading two bytes separately reassembling python code,3 what rather complicated def mkfibstrategy memoizerstrategystrategy def fibx x return else return fibx fibx return fib this way could fib mkfibmrumaxsize selfassertequalfib selfassertequalfib fib mkfibmrumaxsize produces another cache selfassertequalfib selfassertequalfib,i trying write unit tests ensure correctness various decorators i written here start code i trying write import unittest memoizer import memoizer strategiesmru import mru memoizerstrategymrumaxsize def fibx x return else return fibx fibx class testmemoizerunittesttestcase def testsimpleself selfassertequalfib selfassertequalfib selfassertequalfib name main unittestmain while works decently mru strategy i i plan write additional strategies case i need decorate fib function different ways recall fib calls fib setting fib memoizefib memoize intermediate values work what correct way test decorators,1 take look tests standard library examples httphgpythonorgcpythonfilelibtesttestfunctoolspyl i usually add instrumentation function wrapped i monitor calls instead memoizing test function module level i create memoized function inside test new one created test decorator variant,i trying write unit tests ensure correctness various decorators i written here start code i trying write import unittest memoizer import memoizer strategiesmru import mru memoizerstrategymrumaxsize def fibx x return else return fibx fibx class testmemoizerunittesttestcase def testsimpleself selfassertequalfib selfassertequalfib selfassertequalfib name main unittestmain while works decently mru strategy i i plan write additional strategies case i need decorate fib function different ways recall fib calls fib setting fib memoizefib memoize intermediate values work what correct way test decorators,3 using method mymodelobjects manager mymodelobjectsusing mynondefaultdatabase getorcreatenamebob if mymodel instance use using keyword specify database save the django docs point gotchas mymodel mymodelnamebob mymodelsaveusing mynondefaultdatabase,django orm supports querying specific database multiple defined project via using function filterbased operations eg mymodelobjectsfiltername bob using mynondefaultdatabase how would equivalent creating new records via class mymodel shortcut like getorcreate,3 that appears impossible use pyinstaller pyexe pyapp possible see also pyexe generate single executable file,in cxfreeze possible move pyd files libraryzip subdirectory i live two dlls along exe i rather hide files users even subdirectory,2 using part standard query chain so use anywhere query sent db getorcreate unlike filter atomic call thing immediately need call using mymodelobjectsusing mynondefaultdatabase getorcreatename bob,django orm supports querying specific database multiple defined project via using function filterbased operations eg mymodelobjectsfiltername bob using mynondefaultdatabase how would equivalent creating new records via class mymodel shortcut like getorcreate,2 this general change builtin types moving python x x list int example behaviour x x only set type changed bring line types discussed bug tracker issue i afraid really nice way make behave old way here code i able come class mysetset def copyself return mysetself def makebinaryopinplacemethod def binopself new selfcopy inplacemethodnew return new return binop rand makebinaryopsetiand intersection makebinaryopsetintersectionupdate ror makebinaryopsetior union makebinaryopsetupdate sub makebinaryopsetisub difference makebinaryopsetdifferenceupdate rxor xor makebinaryopsetixor symmetricdifference makebinaryopsetsymmetricdifferenceupdate del makebinaryop def rsubself new mysetother new self return new this simply overwrite methods versions return type there whole lot methods maybe application get away overwriting copy stick inplace methods,when subclassing builtin types i noticed rather important difference python python return type methods builtin types the following code illustrates sets class mysetset pass myset myset printtypesunions printtypesintersections printtypesdifferences with python return values type myset with python return types set i could find documentation result supposed documentation change python anyway i really care simple way python get behavior seen python without redefining every single method builtin types,3 consider using pickledump pickleload work that reasonable choice mind file python specific format also consider using sqlite store data this format readable programs queryable ie retrieve filename field instead entire record otherwise traditional solution reading straight text dump read file linebyline either parse evaluate text convert back python object extract fields interest line codecsopendatatxt r encodingutf tup astliteralevalline print tup,i looking way permanently store tuples created python program also runtime so i decided simplicity write data textfile much elegant yet simple solution recommend command looks like import codecs txt codecsopendatatxt w encodingutf data set set set print txt data resulting textfile looks like u name file date u name file date correct way access datatxt displaying second datasets example case file file etc i messed around loops read readline never got simple output second item file i hope someone help thanks lot advance,3 consider using pickle save variables,i looking way permanently store tuples created python program also runtime so i decided simplicity write data textfile much elegant yet simple solution recommend command looks like import codecs txt codecsopendatatxt w encodingutf data set set set print txt data resulting textfile looks like u name file date u name file date correct way access datatxt displaying second datasets example case file file etc i messed around loops read readline never got simple output second item file i hope someone help thanks lot advance,2 how xdxxxxxxbxxxxxxfx structunpack dh lena according struct documentation looks like need use specify littleendian,i binary file i reading byte values stored reverse byte order little endian eg d b f the original program created values stores internally shorts those values correspond i trying read values using python although probably run much older systems eg i tried using val val val val val val val structunpackh h h h h h h data course values come wrong after looking documentation struct i thought i able use something like val structunpackh h testing i got structerror bad char struct format how i unpack values correct byte ordering am i stuck reading two bytes separately reassembling python code,2 mylist thisn listn ofn wordsn mapstrstrip mylist list words,i take large list words form thisn listn ofn wordsn using strip function turn list words i thought i written would work i keep getting error saying list object attribute strip here code i tried striplist lengths range striplistappend longest word text file characters long lines striplistappendlinesastrip,3 list comprehension xstrip x lst,i take large list words form thisn listn ofn wordsn using strip function turn list words i thought i written would work i keep getting error saying list object attribute strip here code i tried striplist lengths range striplistappend longest word text file characters long lines striplistappendlinesastrip,3 you use lists comprehensions striplist itemstrip item lines or map function lambda striplist maplambda itstrip lines without lambda striplist mapstrstrip lines,i take large list words form thisn listn ofn wordsn using strip function turn list words i thought i written would work i keep getting error saying list object attribute strip here code i tried striplist lengths range striplistappend longest word text file characters long lines striplistappendlinesastrip,3 this done using list comprehensions defined pep wstrip w thisn listn ofn wordsn,i take large list words form thisn listn ofn wordsn using strip function turn list words i thought i written would work i keep getting error saying list object attribute strip here code i tried striplist lengths range striplistappend longest word text file characters long lines striplistappendlinesastrip,3 puka geventeventlet box hard modify puka blocks one place event loop replacing part enough,i reading newer python amqp library puka confused pika wondering way handles event loop would compatible gevent eventlet based limited knowledge seems like could automatically patch geventeventlet thanks source httpgithubcommajekpuka docs httpmajekgithubcompukapukahtml,2 all answers mainly list comprehension great but explain error striplist lengths range striplistappend longest word text file characters long lines striplistappendlinesastrip member list index what could write lines striplistappendastrip another important comment create empty list way striplist but useful append appends stuff list in case useful create list defaut values build item per item appending stripped strings so code like striplist lines striplistappendastrip but sure best one one exactly thing stripped linestrip line lines in case something complicated strip put function that readable way work lists,i take large list words form thisn listn ofn wordsn using strip function turn list words i thought i written would work i keep getting error saying list object attribute strip here code i tried striplist lengths range striplistappend longest word text file characters long lines striplistappendlinesastrip,1 you ask simplejson ignore when i got similar problem like i ran decode utf ignore encode utf proceed,my code makes gets content uservoice site as might know uservoice shitty piece software handle data correctly indeed reduce amount text search page cut text let say characters add end thing care cutting middle multibytes character resulting partial utf byte eg 㨠char i got xc instead xcxas of course i give horrible soup jsonloads fails unicodedecodeerror so question simple i ask jsonloads ignore bad bytes i would using decode utf ignore i access internals function thanks,3 in addition unutbu answer using latest version numpy native date dtype in case try something like import numpy np import dateutilparser rawtable npgenfromtxt testintxt namestrue delimiter convertersdateutilparserparse dtypenpuint npdatetime npfloat npfloat npuint sorttable npsortrawtable order isotime open testouttxt w outfile outfilewrite joinsorttabledtypenames n npsavetxtoutfile sorttable fmt irffi this yields seasonisotimelatitudelongitudeenum,i new python basic question i find solution net i table named ibtsampletxt containing seasonisotimelatitudelongitudeenum what i would like import numpy array processing time simply sort records par date export processed table new txt file numpy import import pylab rawtable loadtxt ibtsampletxt delimiter skiprows converters pylabdatestrnum dtype names season isotime latitude longitude enum formats uint float float float uint sortable sortrawtable order isotime copy savetxt ibtsortedtxt sortable fmt dfffd i ti use pylabdatestrnum function importation find inverse function export date time iso format any help idea would helful,1 here basic example msg code powmsg encrypt code l plaintext powcode decrypt plaintext see aspn cookbook recipe tools working mathematical part rsa style public key encryption the details characters get packed unpacked blocks numbers get encoded bit arcane here complete working rsa module pure python for particular packing pattern characters time padded spaces work plaintext pound plaintext â â â get thrown away even lengths range lenplaintext group plaintexti plainnumber ordgroup ordgroup encrypted powplainnumber print group plainnumber encrypted po un,i trying rsa encrypt word characters time padding space using python sure i go for example encryption exponent modulus word pound would i go i know i need start poword p need take consideration word characters i need characters time padding space i sure i also need use somewhere thank,2 scrapy executes correctly output messages stdout simple pipe redirect everything file stuff goes stdout say seems constructor with amp fetches messages scrapy puts log,scrapy crawler called shell script used command line crontab entry the shell script looks like scrapy crawl targethostcom time due execute seems constructor called i verified debug output the problem solved rewrite shell script scrapy crawl targethostcom amp cronloglog i know,1 your query two clauses called type valid json therefore valid mql query most json parsers overwrite first type clause second one means actually end running following query id null name commontopicimage limit type ​ try you see results posted this error results less interesting query to get around restriction one clause given property mql allows arbitrary prefixes added property like footype bartype the query editor actually automatically add forget add use api remember so query linked shows like query editor id null name type peopleperson commontopicimage limit nstype ​,i using freebase python access freebase api i following query i would like execute query id none name type peopleperson commontopicimage limit type results freebasemqlreadquery basically i want instances people also get types part but i try run i get errors u id u userroot u type u typeuser u commontopicimage u type u typecontent u commonimage u id u mkdqcb u name none u name u freebase staff u id u u type u typenamespace u commontopicimage u name u id u typenamespacekeys u type u typeproperty u commontopicimage u name u keys u id u boot u type u typenamespace u commontopicimage u name u id u bootrootpermission u type u typepermission u commontopicimage u name u root permission u id u typeobjectpermission u type u typeproperty u commontopicimage u name u permission u id u typeobjecttype u type u typeproperty u commontopicimage u name u type u id u type u type u typenamespace u typedomain u commontopicimage u name u metaweb system types u id u typetype u type u typetype u commontopicimage u name u type u id u typenamespace u type u typetype u commontopicimage u name u namespace however works fine i use query freebase query editor see query run any ideas thanks,1 couldn class override join class mystrunicode def joinself strs code this least cover case mystrjoin after bukzor comment i looked works looks like join c function always returns unicode object called using unicode seperator the code seen take look pyunicodejoin function especially line res pyunicodenewresalloc so result pyunicodejoin always instance pyunicode the error case i see input unicode convert item unicode pyunicodecheckitem ampamp pystringcheckitem pyerrformatpyexctypeerror sequence item zd expected string unicode found pytypeitemtpname goto onerror so i think possible make case fail least object extends unicode join mystr a b u c,we subclass str call mystr i need able control strjoin interacts subclass at minimum join mystr produce another mystr joining mystr plain str throw typeerror currently happens mystr subclasses unicode mystr mjoin mystr a mystr b u ab join mystr a b u c u abc,3 just pass unicode string jsonloads badstr qualitã© badstr qualitxc jsonstr badstr import json jsonloadsjsonstr traceback recent call last unicodedecodeerror utf codec decode byte xc position invalid continuation byte jsonloadsjsonstrdecode utf ignore u qualit,my code makes gets content uservoice site as might know uservoice shitty piece software handle data correctly indeed reduce amount text search page cut text let say characters add end thing care cutting middle multibytes character resulting partial utf byte eg 㨠char i got xc instead xcxas of course i give horrible soup jsonloads fails unicodedecodeerror so question simple i ask jsonloads ignore bad bytes i would using decode utf ignore i access internals function thanks,3 the collectionscounter class helpful sort thing collections import counter words quick brown fox jumped lazy dog split countermaplen words counter the code posted question works fine asis i sure stuck fwiw minor code improvements pythonic style strippedlist quick brown fox jumped lazy dog split tally print tally original tally strippedlist lengthword leni tallylengthword print tally,i taking words text file stripping word n creating new list words now i need go systematically word word finding length word adding tally word length ie i would start empty tally lengthofwords list stripped words contained x letter words x letter words i would end lengthofwords what boils calculate length word eg n add one lengthofwords lengthofwordsn still starts letter words th item i really stuck essentially increase value item list instead appending end list what i moment lines open epythonassessmentdraculatxt r readlines strippedlist itemstrip item lines tally empty set lengths lengths range tallyappend print tally original tally strippedlist lengthword intleni tallylengthword tallylengthword print tally,1 you want way around how like sss sss,i bit trouble looking good explanation pointing right direction would helpful following problem i need header printed pretty format along data unfortunately happened shown devicename kb used kb quota kb hard limit grace mediastuff none in order i built list header header devicename kb used thing entries i need print in order print i something like print join rjust header so obviously work rjust pads spaces right string is way print string takes exactly certain width string long enough fit width pad spaces ps i limited python means i use format python,1 rjust puts spaces assuming literal string you going substituting another string unknown length justify substitution however want explicitly rjust everything functionality built substitution engine just put field width you could build format string dynamically measuring lengths strings header use produce literal sign formatting thus ds turns produce field width thus something like formatstring join ds lenh h header print joinheader entry data print formatstring entry,i bit trouble looking good explanation pointing right direction would helpful following problem i need header printed pretty format along data unfortunately happened shown devicename kb used kb quota kb hard limit grace mediastuff none in order i built list header header devicename kb used thing entries i need print in order print i something like print join rjust header so obviously work rjust pads spaces right string is way print string takes exactly certain width string long enough fit width pad spaces ps i limited python means i use format python,1 i believe webob upgraded new python runtime you use resheadersadd setcookie headervalue as pointed webob documentation note webapp also replaced webapp,i use localization like django using custom request handler switching different languages upgrading python presents trouble since uses cookie djangoutilstranslation in worst case i must move custom request handler system switch languages us do idea resolve error is djangolanguage cookie still available like what alternatives localization depend django babel could i still use old po mo files should i use cookie class my custom request handler class djangoutils import translation class inhandlerwebapprequesthandler def initializeself request response webapprequesthandlerinitializeself request response selfrequestcookies cookiesself selfrequestmeta osenviron selfresetlanguage def resetlanguageself decide language cookiesheaders language translationgetlanguagefromrequestselfrequest translationactivatelanguage selfrequestlanguagecode translationgetlanguage set headers response selfresponseheaders contentlanguage translationgetlanguage class cookiesuserdictdictmixin def initself handler policy selfresponse handlerresponse selfin handlerrequestcookies selfpolicy policy secure policy handlerrequestenvironget https lower true policy secure true selfout def getitemself key key selfout return selfoutkey key selfin return selfinkey raise keyerrorkey def setitemself key item selfoutkey item selfsetcookiekey item selfpolicy def containsself key return key selfin key selfout def keysself return selfinkeys selfoutkeys def delitemself key key selfout del selfoutkey selfunsetcookiekey key selfin del selfinkey p path selfpolicy p path selfpolicy path domain selfpolicy p domain selfpolicy domain selfdeletecookiekey p begin webob functions def setcookie self key value maxagenone path domainnone securenone httponlyfalse versionnone commentnone set add cookie response cookies basecookie cookieskey value varname varvalue maxage maxage path path domain domain secure secure httponly httponly version version comment comment varvalue none varvalue false cookieskeyvarname strvarvalue maxage none cookieskey expires maxage headervalue cookieskeyoutputheader lstrip selfresponseheadersheadersappend setcookie headervalue def deletecookie self key path domainnone delete cookie client note path domain must match cookie originally set this sets cookie empty string maxage expire immediately selfsetcookiekey pathpath domaindomain maxage def unsetcookieself key unset cookie given name remove response if multiple cookies eg two cookies name different paths domains cookies deleted existing selfresponseheadersgetall setcookie existing raise keyerror no cookies set del selfresponseheaders setcookie found false header existing cookies basecookie cookiesloadheader key cookies found true del cookieskey header cookiesoutputheader lstrip header selfresponseheadersadd setcookie header found raise keyerror no cookie set name r key error trace traceback recent call last file basedatahomeappssmontaoprojectmainwebapppy line dispatch return methodargs kwargs file basedatahomeappssmontaoprojectmaininpy line get cookiedjangolanguage file basedatahomeappssmontaoprojectmainutilpy line setitem selfsetcookiekey item selfpolicy file basedatahomeappssmontaoprojectmainutilpy line setcookie selfresponseheadersheadersappend setcookie attributeerror responseheaders instance attribute headers thanks advance suggestion,2 you could use header devicename kb usedkb quotakb hard limit gracesplit data mediastuff none print joinheader print joins width val width val zipmaplenheader data output devicename kb usedkb quotakb hard limit grace mediastuff none,i bit trouble looking good explanation pointing right direction would helpful following problem i need header printed pretty format along data unfortunately happened shown devicename kb used kb quota kb hard limit grace mediastuff none in order i built list header header devicename kb used thing entries i need print in order print i something like print join rjust header so obviously work rjust pads spaces right string is way print string takes exactly certain width string long enough fit width pad spaces ps i limited python means i use format python,1 check resourceestimatorgetestimatedreduceinputsize as always comments around getestimatedreduceinputsize function sparse some effort put understand,i see following jobtracker log warn orgapachehadoopmapredjobinprogress no room reduce task node trackerworkerlocalhost bytes free expect reduce input take i want know hadoop calculated reducer input take i two small worker nodes gigs one reducer i resolve issue increasing number reducers,1 this seems fix problem import gtk def printsizewidget datanone print windowgetsize def deleteeventwidget datanone print windowgetsize return false def destroywidget datanone gtkmainquit window gtkwindow windowconnect deleteevent deleteevent windowconnect destroy destroy button gtkbuttonlabel print size buttonconnect clicked printsize windowaddbutton windowshowall gtkmain i think key calling getsize deleteevent signal rather destroy signal if destroy signal like describe returns default size,i trying use gtkwindowgetsize always returns default width height the documentation says the getsize method returns tuple containing current width height window if window onscreen returns size pygtk suggest window manager initial window size the size obtained getsize method last size received configure event pygtk uses locallystored size rather querying x server size as result call resize method immediately call getsize method size taken effect yet after window manager processes resize request pygtk receives notification size changed via configure event size window gets updated i tried resizing window manually waiting minute i still get default width height i trying use save window size quit i restore start is better way here code snipit i main quit def onmainwindowdestroyself widget datanone selfviewcurrentviewlayout list selfviewcurrentviewsetcolumnorder width selfmainwindowgetsize height selfmainwindowgetsize test statement print width height selfprefssetsizeprefswidth height selfprefssetviewprefsselfviewcurrentviewmedia selfviewcurrentviewlayout gtkmainquit i think i understand happening this inside destroy signal time code gets called window already gone is canonical way handling window resizing i hoping avoid handling resize events everytime user resized window,3 okay got part had add export pkgconfigpathoptlocallibpkgconfigpkgconfigpath python waf configure paths defined pkgconfigpath macosxenvironmentplist file got reading log file said checking cairo optlocalbinpkgconfig atleastversion cairo found and realized optlocalbinpkgconfig libs cairo looking somewhere else gtk directory some additional info after setting pkgconfigpath variable i able move next step,i trying install pycairo tarball source os x using bit python pythonorg cairo macports so i installing pycairo when i run python waf configure i get checking cairo found i cairo files ls optlocalincludecairo cairodeprecatedh cairogobjecth cairoscriptinterpreterh cairoteeh cairoxlibxrenderh cairoh cairofeaturesh cairopdfh cairoscripth cairoversionh cairoxlibh cairofth cairopsh cairosvgh cairoxcbh cairoxmlh ls optlocallibcairo cairofdrso cairofdrla cairosphinxso cairosphinxla libcairotracedylib libcairotracedylib cairofdra cairofdrso cairosphinxa cairosphinxso libcairotracea libcairotracela but directory i pass parameter these look relevant specifying cairo library python waf help options waf commands options main commands example waf build j build executes build clean cleans project configure configures project dist distcheck checks project compiles tarball dist distclean removes build directory install installs targets system list lists targets execute step executes tasks stepbystep fashion debugging uninstall removes targets installed update updates plugins waflibextras directory options version show program version number exit h help show help message exit j jobs jobsjobs amount parallel jobs k keep keep running happily even errors found v verbose verbosity level v vv vvv default nocache ignore wafcache set zoneszones debugging zones taskgen deps tasks etc nopyc do install bytecode compiled pyc files configuration defaultinstall nopyo do install optimised compiled pyo files configuration defaultinstall configure options out outout build dir project top toptop src dir project download try download tools missing build install options p progress p progress bar pp ide output targetstargets task generators eg targettarget step options filesfiles files process regexp eg mainctestmaino installuninstall options f force force file installation installation directories by default waf install put files usrlocalbin usrlocallib etc an installation prefix usrlocal given using prefix example prefixhome prefixprefix installation prefix default usrlocal destdirdestdir installation root default execprefixexecprefix installation prefix default prefix predefined installation directories bindirbindir user executables default execprefixbin sbindirsbindir system admin executables default execprefixsbin libexecdirlibexecdir program executables default execprefixlibexec sysconfdirsysconfdir readonly singlemachine data default prefixetc sharedstatedirsharedstatedir modifiable architectureindependent data default prefixcom localstatedirlocalstatedir modifiable singlemachine data default prefixvar libdirlibdir object code libraries default execprefixlib includedirincludedir c header files default prefixinclude oldincludediroldincludedir c header files nongcc default usrinclude datarootdirdatarootdir readonly archindependent data root default prefixshare datadirdatadir readonly architectureindependent data default datarootdir infodirinfodir info documentation default datarootdirinfo localedirlocaledir localedependent data default datarootdirlocale mandirmandir man documentation default datarootdirman docdirdocdir documentation root default datarootdirdocpackage htmldirhtmldir html documentation default docdir dvidirdvidir dvi documentation default docdir pdfdirpdfdir pdf documentation default docdir psdirpsdir ps documentation default docdir c compiler options checkccompilercheckccompiler on platform darwin following ccompiler checked default gcc thanks,3 i think code wanted newtally b enumeratenewtally print b b the cause original traceback list members looked using square brackets instead parentheses newtallyi function call newtallyi indexed lookup,i list integer percentages i need print using following pattern the index value tab spaces printed percentage point also value index print less percent i tried code b newtally b print newtallyb b else print less words length however i keep getting error code list index range i understand someone point i done wrong,3 how hypertreelist control trtwistbutton style applied that would make look like apple finder it also pure python easier hack normal treectrl if need windows explorer look might want look listctrl objectlistview ultimatelistctrl there demos wxpython demo except objectlistview since included wxpython,my question simple get make navigation panel similar finder mac os x explorer windows nautilus ubuntu as using wxtreectrl work example httppastepocooorgshow as see first problem huge pink strip left remove second root else put buffer hidden buffer second kludgy third really either three example looks like so i get navigation panel similar examples well except tree ctrl example p update on windows windows least problem left side white column might linux macos x tree ctrl widget generically drawn one could run example macos x see pink column pink example sets background color left tree ctrl update itunes example there seems little misunderstanding question file manager folder view i looking navigation panel side i for example itunes also file manager left side bunch click able tabs used navigate example itunes music movies tv shows audiobooks apps library also problem tree ctrl doesn t work linux see image,1 from doc the operators compare values two objects the objects need type if numbers converted common type otherwise objects different types always compare unequal ordered consistently arbitrarily,for reason python expressions form tuple list return true tuple list tuple list return false why this observation original means,3 tuple list type python something kind surprising comparing values type define comparators work across types compares dictionary order names classes class coffeeobject pass class teaobject pass c coffee tea c false c false c true thankfully python goes away comparing types raises exception,for reason python expressions form tuple list return true tuple list tuple list return false why this observation original means,3 because python objects different types compared arbitrarily arbitrarily means alphabetically type name least python therefore tuple always list the python language reference comparisons most objects builtin types compare unequal unless object choice whether one object considered smaller larger another one made arbitrarily consistently within one execution program the rules comparing objects different types relied upon may change future version language this c function comparing python objects python source defaultwaycomparepyobject v pyobject w int c const char vname wname vobtype wobtype when comparing pointers must cast integer types ie pyuintptrt spelling cx uintptrt ansi specifies pointer compares nonrelated structures undefined pyuintptrt vv pyuintptrtv pyuintptrt ww pyuintptrtw return vv ww vv ww none smaller anything v pynone return w pynone return different type compare type names numbers smaller pynumbercheckv vname else vname vobtypetpname pynumbercheckw wname else wname wobtypetpname c strcmpvname wname c return c return same type name likely incomparable numeric types return pyuintptrtvobtype pyuintptrtwobtype the main part look lines towards end else wname wobtypetpname c strcmpvname wname,for reason python expressions form tuple list return true tuple list tuple list return false why this observation original means,1 using dictget simplify code it bit cleaner using datetimereplace timedelta objects here something get started datetime import datetime options dictmonth day datetimenow starttime datetimeyearoptionsget year nowyear monthoptionsget month dayoptionsget day hour minute second stoptime datetimeyearoptionsget year nowyear monthoptionsget month nowmonth dayoptionsget day nowday hournowhour minutenowminute secondnowsecond,update i added solution bottom question i currently writing reporting code allows users optionally specify date range the way works simplified a user optionally specifies year a user optionally specifies month a user optionally specifies day here code snippet along comments describing i like datetime import datetime timedelta datetimenow starttime nowreplacehour minute second microsecond stoptime if user enters year month daythen simply run report spans current day start today options year starttime starttimereplaceyearoptions year month day stoptime stoptimereplaceyearoptions year if user specifies year value set stoptime last day minute hour second microsecond year way generate reports start specified year end specified year options month starttime starttimereplacemonthoptions month day stoptime stoptimereplacemonthoptions month if user specifies month value set stoptime last day minute hour second microsecond specified month way generate reports specified month options day starttime starttimereplacedayoptions day stoptime stoptimereplacedayoptions day if user specifies day value set stoptime last moment current day reports only run current day i trying find elegant way write code abovei trying find way timedelta seem figure any advice would appreciated thanks edit adding solution after looking answers really finding anything extremely elegant i poking around standard library found current solution i like quite well dateutil here i implemented datetime import date dateutilrelativedelta import relativedelta datetoday stoptime relativedeltadays starttime date note i dictget since implementation dict keys guaranteed exist year options year nowyear month options month nowmonth day options day nowday options year starttime dateyearoptions year nowyear month day stoptime starttime relativedeltayears options month starttime date year options year nowyear month options month nowmonth day stoptime starttime relativedeltamonths options day starttime date year options year nowyear month options month nowmonth day options day nowday stoptime starttime relativedeltadays stuff starttime stoptime what i like implementation python dateutilrelativedatarelativedata works really well edge cases it gets daysmonthsyears correct if i month relativedatamonths increment year set month works nicely also implementation user specifies none optional dates year month daywe fallback nice default starttime morning stoptime tonight way default stuff current day thanks everyone answersthey helpful research,2 i problem centos in addition installing unixodbcdevel i also install gccc yum install gccc,i running linux elcentosplus trying install pyodbc i pip install pyodbc get long list errors end error command gcc failed exit status i looked rootpippiplog saw following installationerror command usrlocalbinpython c import setuptools file homebuildpyodbcsetuppy execfile homebuildpyodbcsetuppy install singleversionexternallymanaged record tmppipmsvurecordinstallrecordtxt failed error code has anybody similar issue installing pyodbc thanks igor,1 to set stoptime advance starttime one year month day appropriate subtract one timedeltamicroseconds options year starttime starttimereplaceyearoptions year month day stoptime stoptimereplaceyearoptions year timedeltamicroseconds elif options month starttime starttimereplacemonthoptions month day monthsoptions month stoptime stoptimereplacemonthmonthsdaytimedeltamicroseconds else starttime starttimereplacedayoptions day stoptime stoptimereplacedayoptions day timedeltadaysmicroseconds,update i added solution bottom question i currently writing reporting code allows users optionally specify date range the way works simplified a user optionally specifies year a user optionally specifies month a user optionally specifies day here code snippet along comments describing i like datetime import datetime timedelta datetimenow starttime nowreplacehour minute second microsecond stoptime if user enters year month daythen simply run report spans current day start today options year starttime starttimereplaceyearoptions year month day stoptime stoptimereplaceyearoptions year if user specifies year value set stoptime last day minute hour second microsecond year way generate reports start specified year end specified year options month starttime starttimereplacemonthoptions month day stoptime stoptimereplacemonthoptions month if user specifies month value set stoptime last day minute hour second microsecond specified month way generate reports specified month options day starttime starttimereplacedayoptions day stoptime stoptimereplacedayoptions day if user specifies day value set stoptime last moment current day reports only run current day i trying find elegant way write code abovei trying find way timedelta seem figure any advice would appreciated thanks edit adding solution after looking answers really finding anything extremely elegant i poking around standard library found current solution i like quite well dateutil here i implemented datetime import date dateutilrelativedelta import relativedelta datetoday stoptime relativedeltadays starttime date note i dictget since implementation dict keys guaranteed exist year options year nowyear month options month nowmonth day options day nowday options year starttime dateyearoptions year nowyear month day stoptime starttime relativedeltayears options month starttime date year options year nowyear month options month nowmonth day stoptime starttime relativedeltamonths options day starttime date year options year nowyear month options month nowmonth day options day nowday stoptime starttime relativedeltadays stuff starttime stoptime what i like implementation python dateutilrelativedatarelativedata works really well edge cases it gets daysmonthsyears correct if i month relativedatamonths increment year set month works nicely also implementation user specifies none optional dates year month daywe fallback nice default starttime morning stoptime tonight way default stuff current day thanks everyone answersthey helpful research,2 uh i solved it becouse sysstdinreadline stops blocking gets n either twisted client strip meaning block indefinitly despite getting input,the server httpsgithubcomemeraldhazesocketdblobmasterservpy process httpsgithubcomemeraldhazeqftsomblobmastermainpy a client test httpwwwkongregatecomgamesemeraldhazethisiswhywehavemaps port forwarding whatnot set correctly the point someone connecting server sends something like ip process made io streams process user connected the reality process outputs something user sees user gives input server gets logs nothing happens any ideas the buffers flushed,1 have ever tried,i playing deus ex human revolutionand things access correct digit code i wondering could make script brute force sending keystrokes game i tried using send keys could make workany ideasthanks python sendkeys this i triedwhich i found import wincomclient import time import sendkeys import os ctypes import shell wincomclientdispatchwscriptshell osstartfile cexe timesleep shellsendkeys the way i trying first open game scriptput time delay load save gameand i open terminal hack key send pywinauto using pywinauto i pywinauto import application import time appapplicationapplication appconnecttitlere deus ex human revolution the missing link classname deusexhre now i searching dialogs available autohotkeys so except pythoni trying autohotkeys this works setkeydelay f send send send send send send send send send backspace send backspace return the keydelay minimum i found miss buttonsi looking way make fastermaybe using different send method updated pywinauto autohotkeys,2 you probably already thought case make sure try solutions couple places iirc couple spots deus ex discover code ingame use even though code hardwired game what really cool got something hacking minigames automatically,i playing deus ex human revolutionand things access correct digit code i wondering could make script brute force sending keystrokes game i tried using send keys could make workany ideasthanks python sendkeys this i triedwhich i found import wincomclient import time import sendkeys import os ctypes import shell wincomclientdispatchwscriptshell osstartfile cexe timesleep shellsendkeys the way i trying first open game scriptput time delay load save gameand i open terminal hack key send pywinauto using pywinauto i pywinauto import application import time appapplicationapplication appconnecttitlere deus ex human revolution the missing link classname deusexhre now i searching dialogs available autohotkeys so except pythoni trying autohotkeys this works setkeydelay f send send send send send send send send send backspace send backspace return the keydelay minimum i found miss buttonsi looking way make fastermaybe using different send method updated pywinauto autohotkeys,1 you able configcommon import configspecific import you mess python path either django managepy script add directory parent path,i trying tidy configuration file i wanted split several files edited based deployment need so project directy i subdirectory called config containing specific configuration files my main configuration file settingspy located project directory modelspy managepy subconfiguration files config directory projectname config commonpy specificpy settingspy this settingspy file looks like apppath pathtomyapp configpath pathtomyappconfig folders ospathdirnameapppath ospathdirnameconfigpath f folders f syspath syspathinsert f myappconfig import common myappconfig import specific however seem set settings i using commonpy specificpy files i also tried following myappconfig import common djangosettings myappconfigcommon import none seem work i initpy config directory thanks,1 the way call windows shellexecuteex api passing properties verb there various highlevel python wrappers i succeeded getting work properties verb instead i would use good old ctypes import time import ctypes import ctypeswintypes seemasknocloseprocess x seemaskinvokeidlist xc class shellexecuteinfoctypesstructure fields cbsizectypeswintypesdword fmaskctypesculong hwndctypeswintypeshandle lpverbctypesccharp lpfilectypesccharp lpparametersctypesccharp lpdirectoryctypesccharp nshowctypescint hinstappctypeswintypeshinstance lpidlistctypescvoidp lpclassctypesccharp hkeyclassctypeswintypeshkey dwhotkeyctypeswintypesdword hiconormonitorctypeswintypeshandle hprocessctypeswintypeshandle shellexecuteex ctypeswindllshellshellexecuteex shellexecuteexrestype ctypeswintypesbool sei shellexecuteinfo seicbsize ctypessizeofsei seifmask seemasknocloseprocess seemaskinvokeidlist seilpverb properties seilpfile cdesktoptesttxt seinshow shellexecuteexctypesbyrefsei timesleep the reason i put call sleep properties dialog shown window calling process if python executable terminates immediately following call shellexecuteex nothing service dialog show,is easy way show properties dialog file windows using python i trying show window pops right click file explorer choose properties,2 areadlines list strings trying convert float tttn map explains error seeing you need bit processing see inline comments x tttn to simulate areadlines list lines x strip newline separate values based tab control character linesvalues maplambda l lstripsplit lines linesvalues for value list lines values convert string float valuesfloat mapfloat v v values valuesfloat,to i curious someone help understand error valueerror invalid literal float i getting i passing text file list trying convert list float values openinputtxtr lines areadlines b mapfloat lines what odd least i process print reprlines i get tttn print typelines i get type str i understand therefore mapfloat lines work correctly am i using function incorrectly looking documentation map function given mapfunction iterable is list iterable also someone could explain errorpoint direction explanation error i would greatly appreciate thanks advance help question,1 this something special dictionaries it intrinsic python programming language whole you want either passbyreference mutable booleans case review understanding python semantics implementation sound like may confusing things python support and change could face several worth worms change design increasing order obscurity store object accesschange various attributes means eg getattr setattr dedicated method validation limit dynamicness creep accidents might even make newnom i really recommend it far simplest least surprising approach go dict value object change attribute directly eg store object attribute name tuple newnom dormcommon locationdict really dict object supporting dictionary operations routed manipulation newnom i would recommend hackery ton legacy code requires external dictionary,i want store attributes object dictionary i change attributes later the problem attributes booleans i put dictionary stores boolean value attribute variable ie locationdict dormcommon newnomdormcommon cafeteria newnomcafeteria comproom newnomcomproom i want iterate dict change newnomcomproom true the problem dictionary storing default value newnomcomproom none i set newnomcomproom i think plenty ways get around making newnomcomproom newnomcomproom using execv true going newnomdictk true i wondering another way override default behavior python dictionary,1 another trick use chr evaluates i recently clean string backslashes following trick cleanstring dirtystringreplacechr i realize take care thread attracts many people looking solution immediate problem,technically odd number backslashes described docs r file stdin line r syntaxerror eol scanning string literal r r file stdin line r syntaxerror eol scanning string literal it seems like parser could treat backslashes raw strings regular characters raw strings i probably missing something obvious tia,3 the valueerror coming character string you must split line individual columns converting one individually lines ttn ttn floatval val linestripsplit line lines,to i curious someone help understand error valueerror invalid literal float i getting i passing text file list trying convert list float values openinputtxtr lines areadlines b mapfloat lines what odd least i process print reprlines i get tttn print typelines i get type str i understand therefore mapfloat lines work correctly am i using function incorrectly looking documentation map function given mapfunction iterable is list iterable also someone could explain errorpoint direction explanation error i would greatly appreciate thanks advance help question,1 give figure number f plfigure f plfigure use f plfigure make f active,this hopefully simple question i figure moment i want use matplotlib show figures use interactively i create figures import matplotlib import pylab pl f plfigure f plfigure use matlablike pyplot interface plot draw figures with currentfigure plgcf i determine currently active figure pyplot interface depending figure i clicked now i want draw something first figure pyplot interface current figure either so something like plsetcurrentfigurefigure workaround i know i use object oriented interface interactive stuff using commands like plotx much nicer,3 pytz localize function httppytzsourceforgenetlocalizedtimesanddatearithmetic datetime import datetime import pytz tz pytztimezone uspacific naivedt datetime utcdt tzlocalizenaivedt isdstnoneastimezonepytzutc,i currently working backend calendaring system returns naive python datetimes the way front end works user creates various calendar events frontend returns naive version event created example user selects october pmpm frontend returns datetimedatetime start datetimedatetime end what i need take naive datetime convert utc storage database each user system already specified timezone preference naive datetime considered timezone timezone preference obviously datetimes need stored relative utc users change timezone existing events still render correct time scheduled the frontend outside control i change data i receiving the database design also outside control i change data stored here approximate approach i taken far import pytz def converttoutcnaivedatetime usertzpreference userdatetime naivedatetimereplacetzinfousertzpreference utcdatetime userdatetimeastimezonepytzutc the problem i ran related daylight savings time datetime import datetime import pytz usertzpreference pytztimezone uspacific naivedatetime datetime userdatetime naivedatetimereplacetzinfousertzpreference userdatetime datetimedatetime tzinfodsttzinfo uspacific pst day std receivedutc userdatetimeastimezonepytzutc receivedutc datetimedatetime tzinfoutc expectedutc datetime tzinfopytzutc expectedutc receivedutc false notice using replace sets timezone pst instead pdt regardless date gives utc offset hours instead expected hours dst offset time ends saved incorrectly what options i converting naive datetime correct pdt timezonerelative dst tzinfo also please note users live timezone observes dst may live timezone switches different times order solution like timedelta correction saving i would need know timezone supports dst dates switches,3 since results object looks like stringunicode version dict need eval a safe way python would use astliteraleval function results astliteralevalresponseasjson results value,sorry i completely neglected mention i using python let try i using python consume web service returns following json results paramname output datatype gpstring value city falls church isruralarea false zip isnotinbtoplmarea true longitude isgeocodable true county u falls church isnotinbiplmarea true state va islatlonginusbounds true address jackson st latitude messages here important snippets fetchingparsing code import urllib import httplib import json import simplejson http httplibhttp headers response httprequesturl get headers status responseasjson simplejsonloadsresponse print response reprresponseasjson results responseasjson results value unfortunately leaves following value results reported pyscripter debugger variables window u city falls church isruralarea false zip isnotinbtoplmarea true longitude isgeocodable true county u falls church isnotinbiplmarea true state va islatlonginusbounds true address jackson st latitude i know access address city keys instance can tell i wrong fix thanks jamie old version question obsolete here json i parsing response u messages u results u datatype u gpstring u value u city falls church isruralarea false zip isnotinbtoplmarea true longitude isgeocodable true county u falls church isnotinbiplmarea true state va islatlonginusbounds true address jackson st latitude u paramname u output i drilled node type unicode how i make dict i think fact unicode preventing creating dict accessing keys i sure u city falls church isruralarea false zip isnotinbtoplmarea true longitude isgeocodable true county u falls church isnotinbiplmarea true state va islatlonginusbounds true address jackson st latitude thanks jamie,1 read scapy httpwwwsecdevorgprojectsscapy,i previously worked python i written script parses trace files pcap files packetcapture files i read file display header information information source destination addresses ports i trying implement functionality looking network flow trace files my aim develop flow based ids using python looking network flow does mean i feed results tcpdump parse information better way are libraries help how i need approach problem realtime traffic analysis any help appreciated thanks,2 while i familiar python i bet way serialize data json return client fname bob lname johnson email emailemailcom on client side able traverse data like would javascript object var fname responsefname etc,i trying figure send multiple fields ajax would i use get post i using python server pages i want fields update based option selected select box far i know i gotten work far i wondering send multiple discrete pieces data via xmlhttprequest ie fname cexecuteselect fname employees where user uname lname cexecuteselect lname employees where user uname email cexecuteselect email employees where user uname deptid cexecuteselect deptid employees where user uname active cexecuteselect active employees where user uname sentient cexecuteselect sentient employees where user uname i would pieces data want send back page how would i updated async note i want send from server to client page ie fields sent back main page displayed user user selects different username select box client page show sent via post get,1 i assuming way handle requests client etc you decide protocol client server json quite convenient since javascript easily parse so serialize object python see httpdocspythonorglibraryjsonhtml import json print jsondumps fname fname lname lname etc then request page example jquery getjson urltopage function data something,i trying figure send multiple fields ajax would i use get post i using python server pages i want fields update based option selected select box far i know i gotten work far i wondering send multiple discrete pieces data via xmlhttprequest ie fname cexecuteselect fname employees where user uname lname cexecuteselect lname employees where user uname email cexecuteselect email employees where user uname deptid cexecuteselect deptid employees where user uname active cexecuteselect active employees where user uname sentient cexecuteselect sentient employees where user uname i would pieces data want send back page how would i updated async note i want send from server to client page ie fields sent back main page displayed user user selects different username select box client page show sent via post get,1 you use getoutput commands package simple case commands import getoutput response getoutput php myscriptphp,as i messing around python i wanted write application would web server i currently using written code website http server python web server direct link script this script handle html i wanted add php since i know ubuntu i run php commands within terminal i wanted implement logic script i added lines import os ossystem php filepath however plan go well planned the echo hello world testphp echoed string terminal ran webserverpy returned output message web browser is way capture output php file string bash i make python webserver script output string ossystem i using ubuntu,2 once object access app label name meta class construct name admin change url dynamically applabel objmetaapplabel model objmetamodulename reverse adminsschange applabel model argsobjid,how lookup admin change url arbitrary model if i know model i get url something like print urlresolversreverse adminmyappmymodelchange argsobjid adminmyappmymodel i generic foreign key model i like provide link admin object corresponding change page since type model i easily use reverse is way i could simply following getadminchangeurlobj adminmyappmymodel,3 you eschew use ossystem favor modern subprocess module you might especially look popencommunicate,as i messing around python i wanted write application would web server i currently using written code website http server python web server direct link script this script handle html i wanted add php since i know ubuntu i run php commands within terminal i wanted implement logic script i added lines import os ossystem php filepath however plan go well planned the echo hello world testphp echoed string terminal ran webserverpy returned output message web browser is way capture output php file string bash i make python webserver script output string ossystem i using ubuntu,1 okay might homework i’ll try give hints if homework please say i’ll restore original answer example code so first data set way entry single line as want work data entry split original data lines we use strsplit each entry constructed simple format namedatelocation so get segments use strsplit then end separated content entry to store want sort data name first so choose dictionary taking name key put visits data as don’t care date forget instead want count often single location occurs given name so keep another dictionary using locations key visit count data so end doubled dictionary looking like bob sears walmart mary so get final answers look dictionary immediately read values,say example want count many times bob visits sears walmart would creating dictionaries information given boboctsears boboctwalmart maryoctwalmart donoctsears boboctwalmart maryoctsears,1 you simply set figure f new current figure plfigurefnumber another option give names numbers figures might help make code easier read plfigureshare values plots plfigureprofits plots plfigureshare values selects first figure in fact figure numbers strings arguably explicit simple numbers ps the pyplot equivalent pylabfigure matplotlibpyplotfigure,this hopefully simple question i figure moment i want use matplotlib show figures use interactively i create figures import matplotlib import pylab pl f plfigure f plfigure use matlablike pyplot interface plot draw figures with currentfigure plgcf i determine currently active figure pyplot interface depending figure i clicked now i want draw something first figure pyplot interface current figure either so something like plsetcurrentfigurefigure workaround i know i use object oriented interface interactive stuff using commands like plotx much nicer,3 you need readlines case waste time memory if want list lists floats b floatv v linerstrip n split line one big list floats b floatv line v linerstrip n split,to i curious someone help understand error valueerror invalid literal float i getting i passing text file list trying convert list float values openinputtxtr lines areadlines b mapfloat lines what odd least i process print reprlines i get tttn print typelines i get type str i understand therefore mapfloat lines work correctly am i using function incorrectly looking documentation map function given mapfunction iterable is list iterable also someone could explain errorpoint direction explanation error i would greatly appreciate thanks advance help question,3 you need huge training set documents small subset collection still large set documents represent given domain using nltk calculate words statistics taking account morphology filter stopwords the good statistics tfidf roughly number occurenses word domain subset divided number documents containing word whole collection keywords words greatest tfidf,i trying determine popular keywords certain class documents collection assuming domain computer science course includes networking computer architecture etc best way preserve domainspecific keywords text i tried using wordnet i quite best use extract information are wellknown list words i use whitelist considering fact i aware domainspecific keywords beforehand or good nlpmachine learning techniques identity domain specific keywords,3 xdxcxdxxdxfxdxxdxaxdxxdx encoded representation string u לבן ורוד so second example write researchrcdecode utf you trying almost except setting encoding parameter it makes python try ascii encoding,i trying search pattern sqlalchemy results actually filter like op regexp pattern i believe implanted regex somewhere string search string hebrew presumably maybe i wrongunicode r u לבן c u לבן ורוד i researchrc i get srematch object i query db like f sessionqueryclassname c fcolor c gives xdxcxdxxdxfxdxxdxaxdxxdx print c לבןורוד practicaly running researchrc gives match object since i suspected unicode issue i tried transform unicode unicodec i get unicodedecodeerror ascii codec decode byte xd position ordinal i guess means already unicode string catch i would prefer using sqlalchemy like i get problem i know sure i showed example data contains string should i transform search stringpattern somehow related unicode something else the db table i quering collation utfunicodeci,1 c fcolor returning unicode string repr would show u kind string utf encoded string try c fcolordecodeutf results u udcududfudueudud u לבןורוד console display hebrew characters,i trying search pattern sqlalchemy results actually filter like op regexp pattern i believe implanted regex somewhere string search string hebrew presumably maybe i wrongunicode r u לבן c u לבן ורוד i researchrc i get srematch object i query db like f sessionqueryclassname c fcolor c gives xdxcxdxxdxfxdxxdxaxdxxdx print c לבןורוד practicaly running researchrc gives match object since i suspected unicode issue i tried transform unicode unicodec i get unicodedecodeerror ascii codec decode byte xd position ordinal i guess means already unicode string catch i would prefer using sqlalchemy like i get problem i know sure i showed example data contains string should i transform search stringpattern somehow related unicode something else the db table i quering collation utfunicodeci,2 it looks like pyqt allow sidebyside installation designer plugin handles custom widgets libpythonpluginso so normally single plugin linked either python python it would appear kubuntu currently installs python version plugin linux system way around if want python version plugin compile replacement source edit to compile replacement first ensure sip packages installed i expert ubuntu i think need pythonsipdev pythonsipdev packages plus dependencies course next download pyqt sources match version installed system i able find ubuntu pyqt source packages now unpack tarball cd resulting source directory looks like pyqtxgpl kubuntu configure build using python cd tmp tar xf pythonqtorigtargz cd pyqtxgpl usrbinpython configurepy c j if completes without error build install make using configuration options takes mins compile pyqt old iamdx system once complete libpythonpluginso plugin pyqtxgpldesigner directory you backup remove existing plugin system usrlibqtpluginsdesigner directory copy new plugin,i use script start qt designer custom widgets python visible usrbinenv python import os sys subprocess curdir ospathdirnameospathabspathfile params listsysargv copy list params designer designerqt linux widgetsdir ospathjoincurdir wic widgets add search path custom widgets plugins designer osputenv pyqtdesignerpath widgetsdir subprocesspopenparams but looks like designer using python use widget plugins vicubuntuwic python qtdesignerpyw vicubuntuwic file homevicwicwicwidgetswdateeditpluginpy line appexec syntaxerror invalid syntax how instruct designer use python python i use kubuntu kde python python pyqt v compiled python,1 im assuming form mapping itertools import chain def makemapd nodes setx x chainfromiterabledvalues return dictx dkeys x dy x nodes code edit heres massive one liner i recommend putting code though since unreadable def makemapd return dictx dkeys x dy x setx x chainfromiterabledvalues steps make set possible node values find node values dictionary values put key found mapped list,i dictionary numbers lists numbers like want create new dictionary comprehension based element list would linked key list that would something like b element key key akeys element akey gives course b instead b index gets overwritten i need something like b element key selfelement key akeys element akey b element key key akeys element akey working fashion is possible,1 it easy build dictionary using defaultdict two loops collections import defaultdict b defaultdictlist key value aiteritems elem value belemappendkey,i dictionary numbers lists numbers like want create new dictionary comprehension based element list would linked key list that would something like b element key key akeys element akey gives course b instead b index gets overwritten i need something like b element key selfelement key akeys element akey b element key key akeys element akey working fashion is possible,2 generate random number time since inner workings loop care single random number generate use inside loop example import random x xrangesomeverylargenumber n randomrandint whatever range random numbers do stuff n import random this list comprehension generates random numbers list numbers randomrandint x xrangesomeverylargenumber n numbers do stuff n obviously practical terms really matter unless dealing billions billions iterations bother generating numbers going using one time,i process working programming project involves pretty extensive monte carlo simulation python generation tremendous number random numbers very nearly able generated python built random module i something coding newbie unfamiliar efficient inefficient ways things is faster generate say random numbers list iterate list generate new random number time function called large loop or undoubtedly clever method,2 is reason inappropriate because replacing r first thing i try,is way avoid singlequotes around string i trying playcmd osascript e tell application itunes play track r thesong results play track thesong play track thesong like i want i would use playcmdrelpace singleqoutes tell app singlequotes thesong i easily any ideas,3 then want r use place string output verbatim without extra quotes really happening calls strvalue r calls reprvalue,is way avoid singlequotes around string i trying playcmd osascript e tell application itunes play track r thesong results play track thesong play track thesong like i want i would use playcmdrelpace singleqoutes tell app singlequotes thesong i easily any ideas,2 everything possible k v summaplambda x zipx xlenx aitems dsetdefaultk appendv,i dictionary numbers lists numbers like want create new dictionary comprehension based element list would linked key list that would something like b element key key akeys element akey gives course b instead b index gets overwritten i need something like b element key selfelement key akeys element akey b element key key akeys element akey working fashion is possible,1 here example flattening sorting rebuilding nested lists inerdia suggested comments i tried use generators iterators possible i sure cleverer efficient ways getting result itertools import izip l flatten list sort f sortedinner outer l inner outer group using izip newlist listl l izipiterf,example from list list i like print list is possible listsort function i write custom loop,1 look powerset recipe itertools docs itertools import chain combinations def powersetiterable powerset listiterable return chainfromiterablecombinationss r r rangelens def subsetss return mapset powersets,suppose need write function gives list subsets set the function doctest given and need complete whole definition function def subsetss return list subsets subsetstrue false false true false true set counts x x range a set comprehension subs subsetscounts lensubs counts subs true lencounts assert types set strs set return set element spop rest subsetss saddelement it use builtin function my approach add element rest return i really familiar use set list python,3 ssetrange llists subs lj j rangelenl jampi rangelenl subs true set subs false,suppose need write function gives list subsets set the function doctest given and need complete whole definition function def subsetss return list subsets subsetstrue false false true false true set counts x x range a set comprehension subs subsetscounts lensubs counts subs true lencounts assert types set strs set return set element spop rest subsetss saddelement it use builtin function my approach add element rest return i really familiar use set list python,2 to produce bit executables need install bit versions python cxfreeze,i already created bit program windows using cx freeze bit machine i using windows bit home premium pyexe working understand work python yet is option specify cx freeze compile bit instead bit thanks,2 there number problems code basic one final sql statement place quotation marks around value categoryname required strings sql languages what sending sqlite select idtitle textpubdatecategory entries category music select idtitle textpubdatecategory entries category music however never buildâ sql statements concatenating strings together since exposes possibility sneaky person bot put something one strings destroy database instead cur gdbexecute select idtitle textpubdatecategory entries category categoryname called parameterized query in case database make sure categoryname handled properly piece string data rather potentially part sql statement,i trying formulate right query select records category drop table exists entries create table entries id integer primary key autoincrement title string null text string null pubdate integer category string null i read sqlite documentation i still figure i get columnmusic where music dummy category here function approute categoryname def showentriescategoryname cur gdbexecute select idtitle textpubdatecategory entries category categoryname entries dictidrow titlerow textrow pubdaterowcategoryrow row curfetchall return rendertemplate showentrieshtml entriesentries thanks helping,1 the two error messages expained follows the qmainwidget automatically gets layout qformlayout redundant if want add layout create qwidget central widget make parent new layout other widgets added new layout the parent qwidget subclass must qwidget subclass qformlayout i modified example asked note qtexteditzoomin qtexteditzoomout take range argument controlling degree zoom pyside import qtgui qtcore class mainwindowqtguiqmainwindow def initself parentnone supermainwindow selfinitparent selftextedit editorself selftoolbar qtguiqtoolbarself selfactionzoomin qtguiqaction zoom in self selfactionzoomout qtguiqaction zoom out self selftexteditsethtml font colorbluehello bworldbfont selfsetcentralwidgetselftextedit selfaddtoolbarselftoolbar selftoolbaraddactionselfactionzoomin selftoolbaraddactionselfactionzoomout selfactionzoomintriggeredconnectselfonzoominclicked selfactionzoomouttriggeredconnectselfonzoomoutclicked def onzoominclickedself selftexteditzoom def onzoomoutclickedself selftexteditzoom class editorqtguiqtextedit def initself parentnone supereditor selfinitparent def zoomself delta delta selfzoomout elif delta selfzoomin def wheeleventself event eventmodifiers amp qtcoreqtcontrolmodifier selfzoomeventdelta else qtguiqtexteditwheeleventself event name main import sys app qtguiqapplicationsysargv window mainwindow windowshow appexec,is possible scale zoom qtextedit area i believe i read placing qtextedit inside qlayout allow scaling qtextedit area though find implement couple options ctrl roll mouse wheel running code holding ctrl control key rolling mouse wheel event captured text scale least windows however text grows larger wheel move much effect one goal able modify somehow maybe math increase increments greater degree increases plus direction the setreadonly would seem textedit readonlyfalse mouse event captured true able scale roll mouse wheel set back original state false release ctrl key toolbar button click the option toolbar buttons zoom onzoominclicked called some current problems code it prints qlayout attempting add qlayout mainwindow already layout i head wrapped around yet qtguiqtexteditselfformlayout instead self place textedit area inside layout produces typeerror pysideqtguiqtextedit called wrong argument types wheelevent could use way modify eventdelta maybe the toolbar button text currently run def clicked however contains print statement pyside import qtgui qtcore class mainwindowqtguiqmainwindow def initself parentnone supermainwindow selfinitparent selfformlayout qtguiqformlayoutself selftextedit qtguiqtexteditself selftoolbar qtguiqtoolbarself selfactionzoomin qtguiqactionself selftexteditsethtml font colorbluehello bworldbfont selfsetcentralwidgetselftextedit selfaddtoolbarselftoolbar selftoolbaraddactionselfactionzoomin selfactionzoominsettext zoom in selfactionzoominconnectselfactionzoomin qtcoresignal triggered selfonzoominclicked def onzoominclickedself print onzoominclickedself needs code def wheeleventself event print wheelevent captured eventmodifiers amp qtcoreqtcontrolmodifier selftexteditsetreadonlytrue eventaccept def keyreleaseeventself evt evtkey qtcoreqtkeycontrol selftexteditsetreadonlyfalse name main app qtguiqapplication frame mainwindow frameshow appexec i grappling days would great customizable qtextedit scalezoom working even possible,2 way ipython show exception caught rather showing code caught you could use sysexcepthook import sys def exchooktype value traceback print type sysexcepthook exchook from sys module documentation sysexcepthooktype value traceback this function prints given traceback exception sysstderr when exception raised uncaught interpreter calls sysexcepthook three arguments exception class exception instance traceback object in interactive session happens control returned prompt python program happens program exits the handling toplevel exceptions customized assigning another threeargument function sysexcepthook sysdisplayhook sysexcepthook these objects contain original values displayhook excepthook start program they saved displayhook excepthook restored case happen get replaced broken objects you also try starting ipython xmode option set plain from ipython reference ipython options files xmodemodename mode exception reporting valid modes plain context verbose plain similar python’s normal traceback printing context prints lines context source code around line traceback verbose similar context additionally prints variables currently visible exception happened shortening strings long this potentially slow happen huge data structure whose string representation complex compute your computer may appear freeze cpu usage if occurs cancel traceback ctrlc maybe hitting here example usages notice difference lines traceback xmodeplain jonhozbox sopython ipython xmodeplain ipythondebuggerfulltracebackoninteractivepdbpy traceback recent call last file ipythondebuggerfulltracebackoninteractivepdbpy line module zerodivisionerror integer division modulo zero xmodecontext jonhozbox sopython ipython xmodecontext ipythondebuggerfulltracebackoninteractivepdbpy zerodivisionerror traceback recent call last homejonsopythonipythondebuggerfulltracebackoninteractivepdbpy module usrbinpython zerodivisionerror integer division modulo zero xmodeverbose jonhozbox sopython ipython xmodeverbose ipythondebuggerfulltracebackoninteractivepdbpy zerodivisionerror traceback recent call last homejonsopythonipythondebuggerfulltracebackoninteractivepdbpy module usrbinpython zerodivisionerror integer division modulo zero and without specifying py file xmodeplain jonhozbox sopython ipython xmodeplain in traceback recent call last file ipython console line module zerodivisionerror integer division modulo zero xmodecontext jonhozbox sopython ipython xmodecontext in zerodivisionerror traceback recent call last homejonsopythonipython console module zerodivisionerror integer division modulo zero xmodeverbose jonhozbox sopython ipython xmodeverbose in zerodivisionerror traceback recent call last homejonsopythonipython console module zerodivisionerror integer division modulo zero using python debugger,i recently switched ipython ipython in ipython i see small snippet full traceback python debugger engages ie using pdb whereas ipython i see full traceback as far i tell full traceback directly accessible pdb command line navigate u see directly so way show full traceback such configuration parameter or even usefully way ipython show exception caught rather showing code caught edit example in pdb automatic pdb calling turned on in ipythoninputcacmodule ipdb q zerodivisionerror traceback recent call last usersadamipythoninputcac module zerodivisionerror integer division modulo zero i like see zerodivisionerror q ing pdb,3 okay two ways one would discreet number bins distances like pc pc pc pc this relatively easy need loops example raclose ramid rafar decdlose decmid decfar ii rangelendist distii racloseappendraii deccloseappenddecii elif distii rafarappendraii decfarappenddecii else ramidappendraii decmidappenddecii pltclf ax scatterraclose decclose marker colordarkgreen alpha ax scatterramid decmid marker colorgoldenrod alpha ax scatterrafar decfar marker colorfirebrick alpha line linedrange range marker colordarkgreen line linedrange range marker colorgoldenrod line linedrange range marker colorfirebrick pltlegendlinelineline pc pc pc pc numpoints loc show or contour plot stipulate ra xaxis dec yaxis fill plot distances both ra dec d arrays respective coordinates then make d array distance determine medianmean value distances divide d array value normalize finally plot using contour plot using contourf imshow like import matplotlibpyplot plt matplotlib import cm ax pylabcontourfradecdists levels cmappltcmspectral cbarpylabcolorbar,i looking way convert scatter plot x vs y color normalized z d pixel image ie i plot pixelized image pixels colored according third variable in case i list galaxies sky coordinate xy distance z i want make pixelized image x vs y pixels color normalized according z eg median z value galaxies pixel i know i could something like hexbin i would like square pixels hexagons something like imshow produces i still learning python simplequick way clear instructions complicated way great any help would much appreciated,1 you talking abstract base classes python language support natively however standard library module use help along check abc documentation,i super class method calls methods defined sub classes that i create instance super class call method cannot find method raises error here example class superclassobject def methodoneself value selfsubclassmethod print value class subclassonesuperclass def subclassmethodself return subclass class subclasstwosuperclass def subclassmethodself return nubclass subclassone smethodone subclasstwo smethodone c superclass cmethodone results subclass nubclass traceback recent call last file abstpy line module cmethodone file abstpy line methodone value selfsubclassmethod attributeerror superclass object attribute subclassmethod i thinking changing init super class verify type object new instance created if object belongs super class raise error however i sure pythonic way any recommendations,3 your approach typical framework pattern using init verify typeself superclass reasonable way make sure superclass instantiated directly the common approach provide stub methods raise notimplementederror called that reliable also validates subclasses overridden expected methods,i super class method calls methods defined sub classes that i create instance super class call method cannot find method raises error here example class superclassobject def methodoneself value selfsubclassmethod print value class subclassonesuperclass def subclassmethodself return subclass class subclasstwosuperclass def subclassmethodself return nubclass subclassone smethodone subclasstwo smethodone c superclass cmethodone results subclass nubclass traceback recent call last file abstpy line module cmethodone file abstpy line methodone value selfsubclassmethod attributeerror superclass object attribute subclassmethod i thinking changing init super class verify type object new instance created if object belongs super class raise error however i sure pythonic way any recommendations,3 that initializing current empty string wiping whatever may set as long inside quotes ie quote false see hit end field whatever accumulated current content field append retval reset current empty string ready next field that said looks like dealing csv input there csv module deal,i bit confused line python we use python custom function split line want quotes single entry array the line example la jolla bank fsbla jollacafebfeb so la jolla bank fsb single entry array and i sure understand code the first char quote variable quote set inverse set true then check comma and quote set inverse quote true case inside quotes we cut current i understand still quotes normally cut edit quote means false opposite thanks code def mysplit string quote false retval current char string char quote quote elif char quote first coma still quotes quote set true cut current retvalappendcurrent current else current char retvalappendcurrent return retval,1 you viewing though char elif char quote run however statement explicitly makes one run either quote inverted or current value get cut in case current char logic called invert quote flag but logic cut string run in case current char logic inverting flag not run logic cut string quote flag set,i bit confused line python we use python custom function split line want quotes single entry array the line example la jolla bank fsbla jollacafebfeb so la jolla bank fsb single entry array and i sure understand code the first char quote variable quote set inverse set true then check comma and quote set inverse quote true case inside quotes we cut current i understand still quotes normally cut edit quote means false opposite thanks code def mysplit string quote false retval current char string char quote quote elif char quote first coma still quotes quote set true cut current retvalappendcurrent current else current char retvalappendcurrent return retval,2 current reset empty case encountered quotes interpret end token this definitely pythonic char string makes cringe whoever wrote code used regex,i bit confused line python we use python custom function split line want quotes single entry array the line example la jolla bank fsbla jollacafebfeb so la jolla bank fsb single entry array and i sure understand code the first char quote variable quote set inverse set true then check comma and quote set inverse quote true case inside quotes we cut current i understand still quotes normally cut edit quote means false opposite thanks code def mysplit string quote false retval current char string char quote quote elif char quote first coma still quotes quote set true cut current retvalappendcurrent current else current char retvalappendcurrent return retval,1 what looking condensed version finite state machine used language parsing programs let see i annotate def mysplit string we start beginning string not quotes quote false hold element split retval this variable holds whatever current item interested eg if quote everything including commas otherwise every up until next comma current scan string character character char string we hit quote turn quote scanning mode if quote scanning mode turn char quote quote we hit comma quote scanning mode elif char quote we got want let put return value reset current item nothing prepare next item retvalappendcurrent current else nothing special let keep building current item current char we done characters let put together whatever working ran characters retvalappendcurrent return return retval,i bit confused line python we use python custom function split line want quotes single entry array the line example la jolla bank fsbla jollacafebfeb so la jolla bank fsb single entry array and i sure understand code the first char quote variable quote set inverse set true then check comma and quote set inverse quote true case inside quotes we cut current i understand still quotes normally cut edit quote means false opposite thanks code def mysplit string quote false retval current char string char quote quote elif char quote first coma still quotes quote set true cut current retvalappendcurrent current else current char retvalappendcurrent return retval,1 this best code splitting pretty straight forward current first set current empty string following line loop string split pull characters one one setting char value next character char string following code check line currently inside quote otherwise add current character current variable char quote quote elif char quote retvalappendcurrent see comma append whatever accumulated current return result reset value current let next word accumulate current cut current else current char last char seen still left characters current shove final result retvalappendcurrent return retval here example run let string abbbccc step char current retval current reset b b b bb b bbb abbb current reset,i bit confused line python we use python custom function split line want quotes single entry array the line example la jolla bank fsbla jollacafebfeb so la jolla bank fsb single entry array and i sure understand code the first char quote variable quote set inverse set true then check comma and quote set inverse quote true case inside quotes we cut current i understand still quotes normally cut edit quote means false opposite thanks code def mysplit string quote false retval current char string char quote quote elif char quote first coma still quotes quote set true cut current retvalappendcurrent current else current char retvalappendcurrent return retval,1 ok quite first char quote variable quote set inverse set true good quote set inverse whatever previously at beginning prog false seen becomes true but vice versa true quote seen becomes false in words line program changes quote whatever line it called toggling check coma and quote set inverse quote true case inside quotes this quite right quote means quote false this nothing whether set inverse no variable equal inverse like saying xtrue xfalse obviously nonsense quote always either true false nothing else cut current understand still quotes norm ally cut so hopefully see quotes reach line quote ensures cut inside quote quote really means quote,i bit confused line python we use python custom function split line want quotes single entry array the line example la jolla bank fsbla jollacafebfeb so la jolla bank fsb single entry array and i sure understand code the first char quote variable quote set inverse set true then check comma and quote set inverse quote true case inside quotes we cut current i understand still quotes normally cut edit quote means false opposite thanks code def mysplit string quote false retval current char string char quote quote elif char quote first coma still quotes quote set true cut current retvalappendcurrent current else current char retvalappendcurrent return retval,1 sounds like want zip def compareab awins aties alosses range whatever randomshufflelista randomshufflelistb ab zipab b awins elif b aties else alosses,working python i two different lists a b simplified make explanations clear a b i would like able compare positional values list ex a v b total instances a larger a wins instances two values a ties instances b larger a losses to make things little complicated i also using randomshuffle randomize order list every time loop i first tried using def listcomplista listb awins aties alosses range whatever randomshufflelista randomshufflelistb a b awins elif a b aties elif a b alosses and statements coding additional statements account possible variations obviously gets laborintensive size list grows there got easier way right,2 i think bad start i would add inner loop help hardcoding def listcomplista listb awins aties alosses range whatever randomshufflelista randomshufflelistb j range lenlista aj bj awins elif aj bj aties elif aj bj alosses this code sample assumes length lista length listb if true may want additional checks also may better pythony way,working python i two different lists a b simplified make explanations clear a b i would like able compare positional values list ex a v b total instances a larger a wins instances two values a ties instances b larger a losses to make things little complicated i also using randomshuffle randomize order list every time loop i first tried using def listcomplista listb awins aties alosses range whatever randomshufflelista randomshufflelistb a b awins elif a b aties elif a b alosses and statements coding additional statements account possible variations obviously gets laborintensive size list grows there got easier way right,1 i think want zip also sure shuffling inside loop i exactly sure accomplishing i move outside still get random effect def listcomplista listb wins ties losses shufflelista shufflelistb b ziplista listb b wins elif b ties else losses return wins ties losses one note zip give list items long shortest list given example zip b c output b note missing c,working python i two different lists a b simplified make explanations clear a b i would like able compare positional values list ex a v b total instances a larger a wins instances two values a ties instances b larger a losses to make things little complicated i also using randomshuffle randomize order list every time loop i first tried using def listcomplista listb awins aties alosses range whatever randomshufflelista randomshufflelistb a b awins elif a b aties elif a b alosses and statements coding additional statements account possible variations obviously gets laborintensive size list grows there got easier way right,1 either close output file writing write output context always close file even error occurs open path writefilecsv wb f writer csvwriterf line r,system info python mac osx problem background i large csv file gig needs minor editing every value th column needs characters long characters long need placed front the code shown reports errors run stops writing approximately lines file left thereby losing crucial data anyone know happening i recreated readfilecsv inspected i see anything place the code always aborts location i understand import csv path volumes r csvreaderopenpath readfilecsv ru f openpath writefilecsv wb writer csvwriterf line r lenline line line writerwriterowlinelinelinelinelinelinelineline,1 this i might class superclassobject def initself typeself superclass raise exceptionsuperclass must subclassed asserttypeself superclass class subclasssuperclass def initself superclassinitself subc subclassone supc superclass this line throw exception when run exception thrown jonhozbox sopython preventingdirectinstantiationpy traceback recent call last file preventingdirectinstantiationpy line module supc superclass file preventingdirectinstantiationpy line init raise exceptionsuperclass must subclassed exception superclass must subclassed edit comments jonhozbox sopython cat preventingdirectinstantiationpy usrbinpython class superclassobject def initself typeself superclass raise exceptionsuperclass must subclassed class subclassonesuperclass def initself superclassinitself class subsubclasssubclassone def initself subclassoneinitself class subclasstwosubclassone superclass def initself subclassoneinitself superclassinitself subc subclassone try supc superclass except exception e print failed supc superclass e else print success supc superclass try subsubc subsubclass except exception e print failed subsubc subsubclass e else print success subsubc subsubclass try subc subclasstwo except exception e print failed subc subclasstwo e else print success subc subclasstwo prints jonhozbox sopython preventingdirectinstantiationpy failed supc superclass superclass must subclassed success subsubc subsubclass success subc subclasstwo,i super class method calls methods defined sub classes that i create instance super class call method cannot find method raises error here example class superclassobject def methodoneself value selfsubclassmethod print value class subclassonesuperclass def subclassmethodself return subclass class subclasstwosuperclass def subclassmethodself return nubclass subclassone smethodone subclasstwo smethodone c superclass cmethodone results subclass nubclass traceback recent call last file abstpy line module cmethodone file abstpy line methodone value selfsubclassmethod attributeerror superclass object attribute subclassmethod i thinking changing init super class verify type object new instance created if object belongs super class raise error however i sure pythonic way any recommendations,3 the full deprecation message also explained translation docs translations project directory supported anymore localepaths setting instead this message perhaps bit unclear while automatic discovery translations project directory deprecated use localepaths reference projectlevel locale folder totally acceptable if projectlevel templates make sense templates translated appspecific locale location keep projectlevel locale directory reference localepaths,i similar issue found why doesnt django produce locale files template files another directory however i understand solution my structure project app locale templates app locale templates templates somefilethatneedstranslationhtml now i run command app python managepy app l nl it nicely creates po file app templates app locale folder however i want global templates translated aswell note i not want locale folder project root i tried adding symlink templates folder app append translation results applocalepo file app folder ln templateslocale translations python managepy app l nl symlinks what i missing note templates folder python managepy templates l nl could work obviously templates installed app seems i missing obvious,3 to add answers accomplish simplification digivampire attempted use free function cmp simplify comparison logic it returns depending two values larger we count number appearances value range whatever randomshufflelista randomshufflelistb results cmpa b b ziplista listb awins resultscount aties resultscount alosses resultscount to go approach let python outer loop logic summation us the idea build length lists count results using list comprehension iterate range use another list comprehension get results whatever many times zip make three lists wincounts tiecounts losscounts sum lists def triallista listb randomshufflelista randomshufflelistb results cmpa b b ziplista listb return resultscounti range awins aties alosses sumcounts counts zip triallista listb range whatever,working python i two different lists a b simplified make explanations clear a b i would like able compare positional values list ex a v b total instances a larger a wins instances two values a ties instances b larger a losses to make things little complicated i also using randomshuffle randomize order list every time loop i first tried using def listcomplista listb awins aties alosses range whatever randomshufflelista randomshufflelistb a b awins elif a b aties elif a b alosses and statements coding additional statements account possible variations obviously gets laborintensive size list grows there got easier way right,1 as general rules you also may misreading hdfso binding r hdf libraries eg linux box i ask linker given r library links i get something like eddmax ldd usrlibrsitelibraryxmllibsxmlso linuxvdsoso xfffcbf libxmlso usrliblibxmlso xfca libzso libxlinuxgnulibzso xfcafc librso usrliblibrso xfcad libcso libxlinuxgnulibcso xfcafe libdlso libxlinuxgnulibdlso xfcafa libmso libxlinuxgnulibmso xfca libblassogf usrlibatlasbaseatlaslibblassogf xfcfcff libgfortranso usrlibxlinuxgnulibgfortranso xfcfab libreadlineso liblibreadlineso xfcfd libpcreso libxlinuxgnulibpcreso xfcfc liblzmaso usrlibliblzmaso xfcfa libbzso liblibbzso xfcf librtso libxlinuxgnulibrtso xfcef libgompso usrlibxlinuxgnulibgompso xfced libpthreadso libxlinuxgnulibpthreadso xfceb libldlinuxxso xfcaab libgccsso libxlinuxgnulibgccsso xfcee libncursesso liblibncursesso xfced eddmax indicating r xml package depends libxml so instead providing libraries looking often link,when r installs package contains programslibraries eg hdf sqlite i use programs for instance i hdfso installed libraryframeworksrframeworkversionsresourceslibraryhdflibsx i use instead installing hdf use python hpy etc,3 pyramidformalchemy makes certain mostly undocumented assumptions setup forms file here gotchas i hit worked around if model user example need fieldset called userfieldset userfieldset must instance class be careful imports break assumptions pyramidformalchemy making if model class user import user package user class then reference class prefixing reference package name below working example using points myappmodel import user formalchemy import field formalchemy import fieldset formalchemy import grid userfieldset fieldsetuseruser userfieldsetconfigure usergrid griduseruser usergridconfigure you also post formalchemy group info,i problems creating custom forms pyramidformalchemy i suspect bug package wanted confirm i missing anything my setup looks like def includemeconfig configinclude pyramidformalchemy adding jquery libraries configinclude fajquery adding package specific routes configinclude myappwebformalchemyfaroutes configformalchemyadmin admin modelsuser formsfaforms sessionfactorysession view fajquerypyramidmodelview factory myappmodelrootfactory configformalchemymodel user model myappmodeluseruser sessionfactorysession view fajquerypyramidmodelview factory myappmodelrootfactory faforms module containing custom forms myappmodeluser import user formalchemy import fieldset formalchemy import grid class userfieldsetfieldset def initself fieldsetinitself user selfconfigure class usergridgrid def initself gridinitself user selfconfigure if i comment two classes formalchemy works fine i view users i edit when i put two classes i run problems the problem pyramidformalchemy grabs usergrid userfieldset module namespace tries use instantiated classes this breaks things on hand pyramidformalchemy find classes dynamically create classes and instantiate i believe offending code pyramidformalchemyviewspy line starting getgrid function def getgridself return grid object request selfrequest modelname requestmodelname formname sgrid modelname hasattrrequestforms formname g getattrrequestforms formname g class type gengine gengine selfengine instance greadonly true instantiated grequest selfrequest selfupdategridg return g model selfcontextgetmodel usergrid found faforms grid selfgridclassmodel module gridengine selfengine grid instantiated isinstancerequestforms list add default grid form module eg caching setattrrequestforms formname grid grid gridcopy gridrequest selfrequest selfupdategridgrid return grid here see matching grid fieldset found instantiated found class type used directly actually instantiated any thoughts am i setting something wrong basically i using csrf tokens i need customize forms grab tokens session thanks,3 i think good idea think underlying block memory used represent data points we tell numpy regard block representing array shape dtype int bit integers almost costless tell numpy regard block memory representing array shape dtype c bit complex so real cost calling npunique followed another virtually costless call view reshape import numpy np nprandomseed points nprandomrandint printpoints printlenpoints yields cpoints pointsview c cpoints npuniquecpoints points cpointsview reshape printpoints printlenpoints yields if need result sorted wim method faster you might want consider accepting answer import numpy np nprandomseed n points nprandomrandint n def usingunique cpoints pointsview c cpoints npuniquecpoints return cpointsview reshape def usingset return npvstacknparrayu u settuplep p points yields benchmarks python mtimeit import test testusingset loops best msec per loop python mtimeit import test testusingunique loops best msec per loop,what faster way finding unique xy points removing duplicates numpy array like points numpyrandomrandint i thought converting points complex numbers checking unique seems rather convoluted b numpyuniquepoints j points points numpycolumnstackbreal bimag,3 from documentation httpdocspythonorglibrarysubprocesshtml popenpid the process id child process note set shell argument true process id spawned shell if shell false behave expect i think,i working nifty little function def startprocessname path starts process background writes pid file returns integer pid check process already running status pid processstatusname status running raise alreadystartederrorpid start process process subprocesspopenpath devnull devnull amp shelltrue write pid file pidfilename ospathjoinpidpath name pid pidfile openpidfilename w pidfilewritestrprocesspid pidfileclose return processpid the problem processpid correct pid it seems always lower correct pid for instance says process started ps says running every time i tried i guessing pid returns pid current process started one new process gets next pid higher if case i rely returning processpid since i guarantee always correct why processpid return pid new process i achieve behaviour i,3 there automatic facility xlwt you follow general pattern describe keeping track max width writing setting column width end sometime seen data saved workbook note cleanest efficient approach available dealing excel files if notion data already written means already committed cell values writing actually saving workbook method described exactly if mean already saved workbook want read get max widths save new column widths much slower involve using xlwt xlrd possibly xlutils well also note using genuine microsoft excel notion updating file it may seem like user point view happening behind scenes every time save excel blows away existing file writes brand new one scratch,i trying create excel workbook i autoset autoadjust widths columns saving workbook i reading pythonexcel tutorial hopes finding functions xlwt emulate xlrd ones sheetnames cellnamerow col celltype cellvalue for example suppose i following xlwt import workbook wb workbook sh wbaddsheet sheet celloverwriteok true sh wbgetsheet wbgetsheet similar rbsheetbyindex function offered xlrd except former allows modify contents provided user set celloverwriteok true assuming xlwt does offer functions i looking i planning going every worksheet time keeping track content takes space particular column set column width based of course i also keep track max width specific column i write sheet i feel like would cleaner set widths data already written does anyone know i if recommend order adjust column widths,2 if using twitter api i imagine returning json back json supports arbitrary nesting regular expression never able parse correctly every scenario you would better served using json parser since yaml superset json could use yaml parser i would take look pyyaml it i know they probably json parsers then parsing would easy import yaml results yamlloadtwitterresponse print resultstext this would contain string interested,i trying parse input text file originally grabbed twitter api the file straight text i actually grabbing json case this snippet input text hootsuitea text for independent news reports crisis japan see democracynow news archive httpowlyhtq nuclear fukushima rdran japon createdat sat mar basically i need grab text for independent news reports crisis japan see democracynow news archive httpowlyhtq nuclear fukushima rdran japon here two i tried get working i trouble refindall text line refindall text line the first one allow grab everything created following section i want the second one kinda works well text includes go end information anybody experience regex could point right direction,1 sounds like text returned server html encoded whether value mongodb encoded result encoded sending response something tell looking actual records mongodb one easy way work encoded data var decodeddata div htmlencodeddatatext without jquery logic behind way coded fly var el documentcreateelementdiv elinnerhtml encodeddata shows text looks user like html var decodeddata elfirstchildnodevalue text node value use html later,i peculiar issue i reading html div contenteditable sending ajax request backend saves html mongodb document i also save exact html localstorage and guess happens when text loaded back later localstorage renders fine data retrieved database turns text ampnbsp div scattered throughout does mongodb something data saving,1 note tkinter solution work mac least work mac i tested python python if window withdrawn get focus therefore sense key events,when i push print screen button keyboard i would like trigger event like keyboardprint screen print,1 with little bit trickery courtesy genex entrylistextendxtitletext x feedentry or lc need keep list entrylist xtitletext x feedentry,i new python come java background i like know pythonic way writing code entrylist entry feedentry entrylistappendentrytitletext basically element feed i like append element title list i know i use map lambda function thanks,2 pythonic code i think entrylist entrytitletext entry feedentry this list comprehension construct new list elements feedentrytitletext to append need entrylistextendentrytitletext entry feedentry as side note extend operations normally fast generator expression much slower list comprehension,i new python come java background i like know pythonic way writing code entrylist entry feedentry entrylistappendentrytitletext basically element feed i like append element title list i know i use map lambda function thanks,3 i would override new base class simply fail instantiate base class class baseclassobject def newcls args kwargs cls baseclass raise typeerrorbase class may instantiated return objectnewcls args kwargs this separates concerns little better init fails fast,i super class method calls methods defined sub classes that i create instance super class call method cannot find method raises error here example class superclassobject def methodoneself value selfsubclassmethod print value class subclassonesuperclass def subclassmethodself return subclass class subclasstwosuperclass def subclassmethodself return nubclass subclassone smethodone subclasstwo smethodone c superclass cmethodone results subclass nubclass traceback recent call last file abstpy line module cmethodone file abstpy line methodone value selfsubclassmethod attributeerror superclass object attribute subclassmethod i thinking changing init super class verify type object new instance created if object belongs super class raise error however i sure pythonic way any recommendations,3 i would like numpyarraylistsettuplep p points for fast solution general case maybe recipe would interest httpcodeactivestatecomrecipesremoveduplicatesfromasequence,what faster way finding unique xy points removing duplicates numpy array like points numpyrandomrandint i thought converting points complex numbers checking unique seems rather convoluted b numpyuniquepoints j points points numpycolumnstackbreal bimag,3 always use list comprehension concise expressions entrylist entrytitletext entry feedentry if want entrylist iterate use generator expression entrylist entrytitletext entry feedentry notice difference using parenthesis when using generator format entrylist populated save memory you still able things like items entrylist something joinentrylist,i new python come java background i like know pythonic way writing code entrylist entry feedentry entrylistappendentrytitletext basically element feed i like append element title list i know i use map lambda function thanks,2 you need one specify one mechanize handle you might want use cookies already stored jar save cookies jar use scripts mechanize lets specify one,in mechanize method setcookiejar but need cookie jar anyway say mechanize automatic cookie handling please help,2 import sys oldstdout oldstderr sysstdout sysstderr sysstdout open devnull w sysstderr open devnull w,i writing python script fork child process the parent process able write stuff like started child xxxxx child process output redirected devnull how i within python,3 i think might assumed reshape modifies value original array it nprandomrandn ashape b areshape bshape ashape npasarray treats regular list array original numpy array said actually shape if want use list like array two easy approaches npasarraylstreshape – means however many needs dimension npasarraylstt – t means array transpose switches you could also reshape original array via aryreshape,i list values numpy array i would like calculate correlation coefficient using numpycorrcoefxyrowvar i get following error traceback recent call last file testlearnerpy line module corr npcorrcoefvaluestocomparequeryoutputrowvar file usrlocallibpythonsitepackagesnumpylibfunctionbasepy line corrcoef c covx rowvar bias ddof file usrlocallibpythonsitepackagesnumpylibfunctionbasepy line cov x concatenatexy axis valueerror array dimensions must agree except i printed shape numpy array got when i convert list array numpyasarrayy i get i believe problem i arrayreshape printed shape i still get what i missing thanks advance,1 your log level set info print default print anything less warning see loggersetlevel,import logging name main logginginfo info loggingwarn warning loggingerror error result warning error why logginginfo report thank,2 it spelling error you setting fieldnames variable calling repr feildnames note placement e,i googling i cannot find solution would someone please share working example import easygui multi enter box fieldnames situationexample waiting friend late thoughtsexample my friend bob always late emotionsexample mad amp stressed behaviorexample arguing family write file file open logtxt filewritefeildnames fileclose this error i struggling filewritereprfeildnames nameerror name feildnames defined,2 networkx good one may need graphviz visualization,for school project i need define social network analyze draw i could draw hand analyze calculate various metrics hand but python lover i hope python tool i dreaming social graph equivalent matplotlib ie i use interactively lines tell load data call render function render graph svg maybe metrics displayed eg relationship count node average relationships etc if know python module appreciated could provide toy example answer instead replying name module,2 you something like use example tup sequencetuple unknown length sql select from table where word in join tup cexecutesql tup this way dynamically creating placeholder list formatting sql string sqlite module parses,is way use variable length placeholders sql query right tuple i write something like cexecute select from table where word in tup but tup differing lengths perhaps tuple tuple is syntax using placeholders situation if preferred way write code,3 here one way handle import xlrd book xlrdopenworkbooksamplexls formattinginfotrue sheets booksheetnames print sheets sheets index sh enumeratesheets sheet booksheetbyindexindex print sheet sheetname rows cols sheetnrows sheetncols print number rows number cols rows cols row rangerows col rangecols print row col row col thecell sheetcellrow col could get dump value xfindex print thecellvalue xfx sheetcellxfindexrow col xf bookxflistxfx bgx xfbackgroundpatterncolourindex print bgx more info pythonexcel google group,i writing python script read data excel sheet using xlrd few cells work sheet highlighted different color i want identify color code cell is way an example would really appreciated,3 although strictly within parameters i done socialnetwork analysis using python it ok i ended using nodexl httpwwwnodexlcodeplexcom excel agast plugin project i think quite awesome does pretty much asking gui codeorientated way program,for school project i need define social network analyze draw i could draw hand analyze calculate various metrics hand but python lover i hope python tool i dreaming social graph equivalent matplotlib ie i use interactively lines tell load data call render function render graph svg maybe metrics displayed eg relationship count node average relationships etc if know python module appreciated could provide toy example answer instead replying name module,1 for visualization i recommend xdot also github josã© fonseca a combination networkx might suitable,for school project i need define social network analyze draw i could draw hand analyze calculate various metrics hand but python lover i hope python tool i dreaming social graph equivalent matplotlib ie i use interactively lines tell load data call render function render graph svg maybe metrics displayed eg relationship count node average relationships etc if know python module appreciated could provide toy example answer instead replying name module,1 try blogofile,i looking blog engine following features should able accept posts either pure text html i able blog offline update things online single command this probably require git the files stored humanreadable format i able move easily i preference database i comfortable moving database around need people able suscribe blog using rss atom feed it preferably run python framework no reason i suspect python solutions would better it look good preferably anything special recommend edit blog offline means i able use kind editor i want generate html file i want put blog,1 use unicode strings define source encoding top module you could use elementtree instead minidom it nicer api example usrbinenv python coding utf import xmletreecelementtree etree enjp ustate u州 ucity u都市 utown u町 english japanese tree etreeparsefilename field treeiterfind fieldsfield name alias fieldfindtag tag name aliasname name none nametext none alias none continue aliastext enjpgetnametextstrip aliastext treewrite outputxml encoding utf you need dictionary set text aliasname equal text name tag field usrbinenv python import xmletreecelementtree etree tree etreeparseinputxml field treeiterfind fieldsfieldarrayfield name alias fieldfindtag tag name aliasname name none alias none continue skip either name aliasname found aliastext nametext set aliasname text name treewrite outputxml encoding utf,how i replace japanese texts corresponding english texts i hundreds aliasname i need replace since i new python xml step step instruction would greatly appreciated here xml file looks like workspace dataset dataelement namepopname fields field namestatename aliasnamealiasname replace aliasnamestatealiasname field field namecityname aliasnamealiasname replace aliasnamecityaliasname field here far i came i created dictionary hoping i use replace x state 州 city 都市 town 町 dic dictxnn n xrange lenx print dic japanese appears strange python gui town xxac city xsxes state xfb i also managed select display japanese texts aliasnamealiasname xmldom import minidom xdoc minidomparserddesktoppythonsrcsamplexml workspace xdocgetelementsbytagnamealiasname element enumerateworkspace print elementchildnodesdata fom i stuck how i replace save updates xml,1 first indent i see incorrect the method constructor definition indented class roundfloatfloat def newcls val return floatnewcls roundval second use write something like roundfloat print receive expected means correct behaviour is asked let know,can someone please tell i use piece code i sure question i want ask i want define class needed play along commands i give interpreter this really making headspin supporting code i think might metaclass usage thank class roundfloatfloat def newcls val return floatnewcls roundval,1 nothing crazy going i annoate comments although formatted like inherit built type float used anywhere float class roundfloatfloat new takes care actually creating object def newcls val pass float initializer round value first return floatnewcls roundval it really quick way implementing float value always rounded decimal places,can someone please tell i use piece code i sure question i want ask i want define class needed play along commands i give interpreter this really making headspin supporting code i think might metaclass usage thank class roundfloatfloat def newcls val return floatnewcls roundval,2 you use like roundfloat print,can someone please tell i use piece code i sure question i want ask i want define class needed play along commands i give interpreter this really making headspin supporting code i think might metaclass usage thank class roundfloatfloat def newcls val return floatnewcls roundval,1 directly python doc return “identity” object this integer long integer guaranteed unique constant object lifetime two objects nonoverlapping lifetimes may id value you could get md hash compare theese objects import md mdnewstrrangehexdigest dafcbdbedfdbef mdnewstrrangehexdigest bcafacdbbfcbad,i found strange thing python i tried compare lists composed integers for example in idrangeidrangeidrange out q why id values and since look different q how i compare lists integers id values q to inquisitive id value computed python,3 this calling id ranges go scope ids reused if still accessible id different try abcrangerangerange idaidbidc l l l,i found strange thing python i tried compare lists composed integers for example in idrangeidrangeidrange out q why id values and since look different q how i compare lists integers id values q to inquisitive id value computed python,3 the id correspond somehow memory location object you use created objects conseaquence automatically deleted when create next one use address so id different objetcs try xyz rangerangerange idxidyidz,i found strange thing python i tried compare lists composed integers for example in idrangeidrangeidrange out q why id values and since look different q how i compare lists integers id values q to inquisitive id value computed python,3 i think fixed applying patch attached bug report httpbugspythonorgissue the problem arises file trying include zip file larger bytes original compressed form in scenario library need store file sizecompressed size allocate extra fields store actual size fit bit dword for reason patch accepted i tested works ok i think fix corner case writestr method use write store files works great,i run code zipping folders files def savefolderaszipself foldertozip saveas zipf zipfilezipfilestrsaveas modew allowziptrue selfcreatezipzipf foldertozip zipfclose return zipf def createzipself zipf directory folder directory directoryencodeutf item oslistdirdirectory tempfolder directory ossep continue try ospathisfileospathjoindirectory item zipfwriteospathjoindirectory item folder ossep item elif ospathisdirospathjoindirectory item selfcreatezipzipf ospathjoindirectory itemdecodeutf folder ossep item except exception e selfschedulemachinelogwarningstre but i get error l format requires number example filename happens wiitrackmaniapalwiisoscomwstramapiso any ideas i fix traceback traceback recent call last file testpy line module savefolderaszipusersfdownloads heizip file testpy line savefolderaszip createzipzipf foldertozip file testpy line createzip createzipzipf ospathjoindirectory itemdecodeutf folder ossep item file testpy line createzip zipfwriteospathjoindirectory item folder ossep item file systemlibraryframeworkspythonframeworkversionslibpythonzipfilepy line write zinfofilesize structerror l format requires number,1 use parsedatetime library,i date strings fri oct cest i want convert utc i tried implementation def localtoutclocaltime return datetimestrptimelocaltime hms z yisoformat z but i get valueerror valueerror time data fri oct cest match format hms z y any ideas,1 a method called new constructor class don confuse init class initialiser difference new called instance object must create return instance whereas init called object created usually subclass override initialiser initialisation often work subclassing immutable object cannot change actual value object constructed in case code changing float constructed overrides floatnew calls explicitly modified argument the whole class complete waste time want create rounded float def roundedfloatf return roundf functools import partial roundedfloat partialround ndigits either case call roundedfloat returns value rounded digits also remember using function roundedfloat give exactly gives nearest floating point representation if want exact value calculation purposes use decimal class output format number output,can someone please tell i use piece code i sure question i want ask i want define class needed play along commands i give interpreter this really making headspin supporting code i think might metaclass usage thank class roundfloatfloat def newcls val return floatnewcls roundval,2 newsgroups complangpython from fredrik lundh date mon may daniel nogradi wrote the source distribution version comes scripts directory find playerpy gifmakerpy explodepy deal animated gif still shipped work missing files script directory get httpsvneffbotorgpublicpilscripts playerpy run command line see one works tkinter import pil import image imagetk class mylabellabel def initself master filename im imageopenfilename seq try seqappendimcopy imseeklenseq skip next frame except eoferror pass done try selfdelay iminfo duration except keyerror selfdelay first seqconvert rgba selfframes imagetkphotoimagefirst labelinitself master imageselfframes temp seq image seq temppasteimage frame tempconvert rgba selfframesappendimagetkphotoimageframe selfidx selfcancel selfafterselfdelay selfplay def playself selfconfigimageselfframesselfidx selfidx selfidx lenselfframes selfidx selfcancel selfafterselfdelay selfplay root tk anim mylabelroot animatedgif animpack def stopit animaftercancelanimcancel buttonroot text stop commandstopitpack rootmainloop,is way display animated gif tkinter using python image library i thought imagesequence module would way i know use possible the first question easy way for example load gif using pil imagesequence draw tkinter window using imagetkphotoimage animated or i set function using method something like timesleep loop gif frames draw tkinter window the second question even i make function loop gif frames imagesequence module supposed pil another module i using python private port pil indicated topic,3 networkx gephi combo cool networkx capable outputting graphml format for information gephi httpgephiorg,for school project i need define social network analyze draw i could draw hand analyze calculate various metrics hand but python lover i hope python tool i dreaming social graph equivalent matplotlib ie i use interactively lines tell load data call render function render graph svg maybe metrics displayed eg relationship count node average relationships etc if know python module appreciated could provide toy example answer instead replying name module,3 trailing comma required oneelement tuples having trailing comma larger tuples matter style required its greatest advantage clean diff files multiline large tuples often modified eg configuration tuples,in case single element tuple trailing comma required foo what tuple multiple elements it seems whether trailing comma exists valid is correct having trailing comma easier editing opinion is bad coding style foo foo b foo foo,2 it required singleitem tuples disambiguate defining tuple expression surrounded parentheses for one item longer necessary since perfectly clear tuple however trailing comma allowed make defining using multiple lines easier you could add end rearrange items without breaking syntax left comma accident eg somebigtuple note applies collections eg lists dictionaries tuples,in case single element tuple trailing comma required foo what tuple multiple elements it seems whether trailing comma exists valid is correct having trailing comma easier editing opinion is bad coding style foo foo b foo foo,3 in cases except empty tuple comma important thing parentheses required required syntactic reasons distinguish tuple set function arguments operator precedence allow line breaks the trailing comma tuples lists function arguments good style especially long initialisation split multiple lines if always include trailing comma add another line end expecting add another element instead creating valid expression b c assuming started element list later extended gone wrong perhaps immediately obvious way always include trailing comma avoid trap,in case single element tuple trailing comma required foo what tuple multiple elements it seems whether trailing comma exists valid is correct having trailing comma easier editing opinion is bad coding style foo foo b foo foo,3 it optional see python wiki summary singleelement tuples need trailing comma optional multipleelement tuples,in case single element tuple trailing comma required foo what tuple multiple elements it seems whether trailing comma exists valid is correct having trailing comma easier editing opinion is bad coding style foo foo b foo foo,3 here function reads file attributes dictionary import winapi def getfilepropertiesfname read properties given file return dictionary propnames comments internalname productname companyname legalcopyright productversion filedescription legaltrademarks privatebuild fileversion originalfilename specialbuild props fixedfileinfo none stringfileinfo none fileversion none try backslash parm returns dictionary numeric info corresponding vsfixedfileinfo struc fixedinfo winapigetfileversioninfofname props fixedfileinfo fixedinfo props fileversion dddd fixedinfo fileversionms fixedinfo fileversionms fixedinfo fileversionls fixedinfo fileversionls varfileinfotranslation returns list available language codepage pairs used retreive string info we using first pair lang codepage winapigetfileversioninfofname varfileinfotranslation must form stringfileinfoxxparmname middle two languagecodepage pair returned strinfo propname propnames strinfopath u stringfileinfoxxs lang codepage propname print strinfo strinfopropname winapigetfileversioninfofname strinfopath props stringfileinfo strinfo except pass return props,last time i asked similar question svn related versioning info now i wondering query windows file version attribute eg dll i payed attention wmi winfile modules well without success,3 def initself parent b self wxframeparent parent id titleparameters here reassign self end reference paramwindow instance you never what trying achieve selfa b here assign self frame paramwindow paramwindowa never gets defined get error later maybe want inherit frame if code look like class paramwindowwxframe def initself parent b initialize superclass wxframe superparamwindow selfinitparentparent id titleparameters selfa b print selfa,could please help find problem python code works class paramwindow def initself b selfa b print selfa params paramwindow print paramsa prints ok then i class paramwindow def initself parent b self wxframeparent parent id titleparameters selfa b print selfa params paramwindownone print paramsa says paramwindow instance attribute why i told self frame added field error point ask print error print line forgets exists where i wrong thanks,3 there link managment site unless add using adminconsole the stats available yourappidappspotcomahstats,i enabled appstats python app engine application i access locally ahstats url i deploy application visit appspotcom application ui custom appstats link in yaml file i define builtins appstats i wrap application appengineconfigpy like def webappaddwsgimiddlewareapp app sessionmiddlewareapp cookiekeymyrandomstring app recordingappstatswsgimiddlewareapp return app i used configuration answer am i missing something,3 you mixing unicode bytestrings msg u abc unicode string messagebody b xc bytestring msg messagebody traceback recent call last file input line module unicodedecodeerror ascii codec decode byte xc position ordinal range to fix make sure selfheaders content properly encoded ie keys values headers bytestrings selfheaders dictkencode ascii isinstancek unicode else k vencode ascii isinstancev unicode else v kv selfheadersitems note character encoding headers nothing character encoding body ie xml text encoded independently octet stream http message point view the goes selfurl —if unicode type convert bytestring using ascii character encoding http message consists startline headers empty line possibly messagebody selfheaders used headers selfurl used startline http method goes probably host http header client http xml text goes message body binary blob it always safe use ascii encoding selfurl idna used nonascii domain names—the result also ascii here rfc says http headers character encoding historically http allowed field content text iso charset iso supporting charsets use rfc encoding in practice http header field values use subset usascii charset usascii newly defined header fields should limit field values usascii octets a recipient should treat octets field content obstext opaque data to convert xml bytestring see applicationxml encoding condsiderations the use utf without bom recommended xml mime entities,i implemented pivotal tracker api module python the pivotal tracker api expects post data xml document applicationxml content type my code uses urlibhttplib post document shown request urllibrequestselfurl xmlrequesttoxml utf xmlrequest else none selfheaders obj parsexmlselfopeneropenrequest this yields exception xml text contains nonascii characters file usrlibpythonhttplibpy line endheaders selfsendoutputmessagebody file usrlibpythonhttplibpy line sendoutput msg messagebody exceptionsunicodedecodeerror ascii codec decode byte xc position ordinal range as near i see httplibsendoutput creating ascii string message payload presumably expects data url encoded applicationxwwwformurlencoded it works fine applicationxml long ascii characters used is straightforward way post applicationxml data containing nonascii characters i going jump hoops eg using twistd custom producer post payload,3 use oschdir,what i want make subdirectory workingdirectory i want run commands subdirectory result new files made saved directory i different types file mainly bam sam txt this command individual rawinputplease type name individual osmkdirindividual cmdcd individual osmkdirtst callcmd shelltrue this workingin example i tried simply make another directory sub make less complicated i know i give pathway since i lot command i thought might easier way,2 use osmakedirs create folders recursively folder r folderstocreate osmakedirsfolder oschdirfolder your file saving code alternatively could construct full filename use saving folder r folderstocreate osmakedirsfolder fullfilename ospathjoinfolder filename your file saving code,what i want make subdirectory workingdirectory i want run commands subdirectory result new files made saved directory i different types file mainly bam sam txt this command individual rawinputplease type name individual osmkdirindividual cmdcd individual osmkdirtst callcmd shelltrue this workingin example i tried simply make another directory sub make less complicated i know i give pathway since i lot command i thought might easier way,1 django expects arrange apps certain ways requiring templatetags directory app exception some requirements modeladmin adminpy autodiscovery models modelspy management commands managementcommands directory fixtures fixtures directory unlike templates hooks specify templates loaded easy way store templatetags modules different location,i working template tags one thing i understood templatetags stored inside templatetags directory app is underlying reason is possible store templatetagspy file somehow i reduce extra bloat around extra directories,2 you probably escape backslash character msworddocumentsopenxbackofficeadamchecklistdocx edit explanation the backslash usually used declare special characters for example n special character newline if want literal escape,i get python print word doc what i trying open word document print close i open word word document import wincomclient msword wincomclientdispatchwordapplication msworddocumentsopenxbackofficeadamchecklistdocx mswordvisible true i tried next print mswordactivedocumentprintoutxbackofficeadamchecklistdocx i get error print valid could someone shed light i print file python i think might simple changing word printout thanks i new python,1 you try gstpython module refer gstpython documentation detail,i need make application streams live multimedia at present application taking image frames webcam using opencv sending client it also sending audio using pymedia module the problem image audio packets arrive client sync so i following questions is module python livemultimedia streaming can i make audio image frames somehow sync client ps pymedia development since working,2 you use gstreamer python module i mean gstpython mentioned use rtmp protocol synchronize clientserver videos last time i use gstpython support rtmp at time solution limit buffer size when buffer gets full oldest frames dropped,i need make application streams live multimedia at present application taking image frames webcam using opencv sending client it also sending audio using pymedia module the problem image audio packets arrive client sync so i following questions is module python livemultimedia streaming can i make audio image frames somehow sync client ps pymedia development since working,1 close joã«l answer i want elaborate bit possible comments if look crawler source code see crawlerprocess class start also stop function this stop function takes care cleaning internals crawling system ends state start so want restart crawling without leaving process call crawlerstop appropriate time later simply call crawlerstart resume operations edit retrospect possible due twisted reactor mentioned different answer stop takes care clean termination looking back code i happened wrapper crawler processes below find redacted code make work using python multiprocessing module in way easily restart crawlers note i found code online last month i include source someone knows came i update credits source scrapy import project signals scrapyconf import settings scrapycrawler import crawlerprocess scrapyxlibpydispatch import dispatcher multiprocessingqueues import queue multiprocessing import process class crawlerworkerprocess def initself spider results processinitself selfresults results selfcrawler crawlerprocesssettings hasattrproject crawler selfcrawlerinstall selfcrawlerconfigure selfitems selfspider spider dispatcherconnectselfitempassed signalsitempassed def itempassedself item selfitemsappenditem def runself selfcrawlercrawlselfspider selfcrawlerstart selfcrawlerstop selfresultsputselfitems the part called often want results queue crawler crawlerworkermyspidermyargs results crawlerstart item resultsget pass do something item,my scrapy script seems work fine i run one scenarios command line i try running code twice python session i get error reactornotrestartable why the offending code last line throws error crawler crawlerprocesssettings crawlerinstall crawlerconfigure schedule spider crawlercrawlmyspider spider myspider crawlerqueueappendspiderspider start engine scrapytwisted crawlerstart,3 mswordactivedocument gives current active document the printout method prints document take document filename parameter from httpmsdnmicrosoftcomenuslibraryaavofficeaspx expressionprintoutbackground append range outputfilename from to item copies pages pagetype printtofile collate filename activeprintermacgx manualduplexprint printzoomcolumn printzoomrow printzoompaperwidth printzoompaperheight specifically word trying use filename boolean background may set true print background edit case matters error bit bizarre mswordactivedocumentprintout print mswordactivedocumentprintout throws error complaining printout property i think happens internally python tries compensate match case properties get quite right methods or something like anyway activedocument activedocument interchangeable printout printout,i get python print word doc what i trying open word document print close i open word word document import wincomclient msword wincomclientdispatchwordapplication msworddocumentsopenxbackofficeadamchecklistdocx mswordvisible true i tried next print mswordactivedocumentprintoutxbackofficeadamchecklistdocx i get error print valid could someone shed light i print file python i think might simple changing word printout thanks i new python,1 crawlerstart starts twisted reactor there one reactor if want run spiders use anotherspider myanotherspider crawlerqueueappendspideranotherspider,my scrapy script seems work fine i run one scenarios command line i try running code twice python session i get error reactornotrestartable why the offending code last line throws error crawler crawlerprocesssettings crawlerinstall crawlerconfigure schedule spider crawlercrawlmyspider spider myspider crawlerqueueappendspiderspider start engine scrapytwisted crawlerstart,1 the following elevationelevation numpynan see indexing boolean arrays numpy tutorial,there got faster way place replacement values right i got d array representing grid elevationsbathymetry i want replace anything nan way super slow x rangeelevationshape rangeelevationshape elevationxy elevationxy numpynan it seems like much better way,3 npputmaskelevation elevation npnan,there got faster way place replacement values right i got d array representing grid elevationsbathymetry i want replace anything nan way super slow x rangeelevationshape rangeelevationshape elevationxy elevationxy numpynan it seems like much better way,2 the syntactic difference new style classes inherit object class old class newobject,while several articles written new classes versus old classed i able see basic example oldnew style,1 rpms built using rpmbuild spec file as example look pythonspec fedora if need build sources try rpm relocate switch prebuilt rpm distribution rpm relocate usroptpython pythonrpm,how create binary rpm package python sources installation nonstandard prefix optpython assume following builds correctly wget httppythonorgftppythonpythontgz tar zxvf pythontgz cd python configure prefixoptpython enableshared make make test sudo make install instead last command i like build binary rpm,2 b aathreshold i tested follows import numpy np datetime array zeros ones interleaved lrg nparangereshaperepeatflatten datetimedatetimenow flt lrglrg print datetimedatetimenow datetimedatetimenow flt nparrayfilterlambda xx lrg print datetimedatetimenow i got python testpy httpdocsscipyorgdocnumpyuserbasicsindexinghtmlbooleanormaskindexarrays,i need filter array remove elements lower certain threshold my current code like threshold numpyarrayrange testing data b numpyarrayfilterlambda x x threshold the problem creates temporary list using filter lambda function slow as quite simple operation maybe numpy function efficient way i unable find i thought another way achieve could sorting array finding index threshold returning slice index onwards even would faster small inputs noticeable anyway definitively asymptotically less efficient input size grows any ideas thanks update i took measurements sortingslicing still twice fast pure python filter input entries in r numpyrandomuniform in timeit testr filter loops best per loop in timeit testr sort slice loops best per loop in timeit testr boolean indexing loops best per loop,3 i disagree andy i agree appropriate testing done appropriate time unit tests ie ones interact anything outside unit replace forms testing but necessarily mean proper separation cannot use bdd framework i used lettuce runner tests i really like fact gherkin syntax pushed back towards business experts testers sponsors means capturing process follow i see reason one set specifications aimed unit level another could aimed system regression levels consider contrived obviously nowhere near enough granular example given my test server updated last nights build when i run regressiontestpack then regression results match known results regressiontestpack i also saying appropriate ever case you evaluate benefit get approach leaving tests different test running systems in particular consider experience base people performing testing so writing small technical project developer prefer syntax theres reason just careful still isolate unit tests system tests regression tests if however part large team devs testers business analysts case need much stronger unlikely actually valid,i like lettuce feel testing could i replace tests doctestsunit tests project lettuce features,1 if want number instances rounded floats defined class roundfloat ok numbers displayed rounded floats be rounded floats that means operations involving two numbers like x results operations rounded values results involving unrounded values maybe want but case wish work numbers keep exact value displayed rounded manner must override str result operation involving two instances give number instance must also override operations add div etc must take way like class floot defined the following code compares results addition two cases class flootfloat cut def initselfx self x def strself return df flootcut self def addselfy return flootsuperflootselfaddy def subselfy return flootsuperflootselfsuby def divselfy return flootsuperflootselfdivy def mulselfy return flootsuperflootselfmuly def powselfy return flootsuperflootselfpowy class roundfloatfloat def newcls val return floatnewcls roundval b print class flootn aa floota print print aa floota aa bb flootb print nb b print bb flootb bb c ab cc aa bb print nc b c print cc aabb cc print nroundc roundc print roundcc roundcc print nc roundc f c roundc rstrip print cc roundcc f cc roundcc rstrip print nnclass roundfloatn aa roundfloata print print aa roundfloata aa bb roundfloatb print nb b print bb roundfloatb bb c ab cc aa bb print nc b c print cc aabb cc print nroundc roundc print roundcc roundcc print nc roundc f c roundc rstrip print cc roundcc f cc roundcc rstrip the fact floot floot displayed despite fact floot displayed floot displayed betrays fact real values floot instances precise displaying the fact cc roundcc value c roundc betrays floota flootb b fact value despite displayed,can someone please tell i use piece code i sure question i want ask i want define class needed play along commands i give interpreter this really making headspin supporting code i think might metaclass usage thank class roundfloatfloat def newcls val return floatnewcls roundval,1 i used parsimonious language models lms success similar tasks separate documentspecific terms general corpus terms these known stronger tfidf statistics require setting parameter fitting you find python implementation use concatenate documents theme single document build parsimoniouslm various themes fetch topk terms per document,i trying determine popular keywords certain class documents collection assuming domain computer science course includes networking computer architecture etc best way preserve domainspecific keywords text i tried using wordnet i quite best use extract information are wellknown list words i use whitelist considering fact i aware domainspecific keywords beforehand or good nlpmachine learning techniques identity domain specific keywords,2 i going answer questions as say scheme community objects poor man closures closures firstclass functions blocks usually syntactic sugar closures for languages closures exist various solutions one common solutions use operator overloading c notion function objects define member operator operator function call python similar overloading mechanism define call class greeterobject def initself selfwho def callself printhello hello greeterworld hello yes might consider using python instead storing functions objects since functions pickled in languages without operator overloading see things like guava function interface,i program python includes class takes function argument init method this function stored attribute used various places within class the functions passed quite varied passing key selecting set predefined functions would give degree flexibility now apologies long list questions like cool is standard way achieve language functions first class objects do blocks like smalltalk objectivec count functions respect would blocks best way languages what blocks could add new method runtime in languages would possible easy or would better create object single method performs desired operation what i wanted pass lots functions would i create lots singleton objects would considered object oriented approach would anyone consider python functions first class objects,1 there two problems you using instead b the standard lib parse cest understands time zone names see also what possible values datetimestrptime accept z,i date strings fri oct cest i want convert utc i tried implementation def localtoutclocaltime return datetimestrptimelocaltime hms z yisoformat z but i get valueerror valueerror time data fri oct cest match format hms z y any ideas,1 you looking tkinterfiledialog noted docs tkinter import filedialog you look methodsclasses filedialog running helpfiledialog python interpreter i think filedialogloadfiledialog looking,where tkfiledialog module python the question choosing file python simple gui references module using tkinter import tk tkfiledialog import askopenfilename using changing tkinter tkinter python gets traceback recent call last file cdocuments settingsmemy documentsfilepyw line module import tkfiledialog importerror no module named tkfiledialog the python doc docspythonorg says tkfiledialog common dialogs allow user specify file open save these renamed well python made submodules new tkinter package gives hint new names would searching tkfiledialog askopenfilename docs returns nothing even mapping old names new submodule names trying obvious jack tkinter import askopenfilename asksaveasfilename importerror cannot import name askopenfilename how call equivalent askopenfilename python,3 aminaxis array,can anyone help snippet code using numpy python given numpy array array i want find minimun value column subtract value respective columns array,3 you could use strategy pattern basically pass object known interface different behavior it like passing function one wrapped object,i program python includes class takes function argument init method this function stored attribute used various places within class the functions passed quite varied passing key selecting set predefined functions would give degree flexibility now apologies long list questions like cool is standard way achieve language functions first class objects do blocks like smalltalk objectivec count functions respect would blocks best way languages what blocks could add new method runtime in languages would possible easy or would better create object single method performs desired operation what i wanted pass lots functions would i create lots singleton objects would considered object oriented approach would anyone consider python functions first class objects,1 while i agree rationale alasdair standard django expectation admin models templates templatetags within respective app folders i think unnecessary boilerplate associated i think reason plenty rd party apps httpsgithubcomojiidjangoclassytags httpsgithubcomjustquickdjangonativetags httpsgithubcomalexdjangotemplatetagsugar reduce boiler plate,i working template tags one thing i understood templatetags stored inside templatetags directory app is underlying reason is possible store templatetagspy file somehow i reduce extra bloat around extra directories,1 personnaly i think ask implicitly three points compatibility desktopmobile the first compatibility python library phone python library computer if use third party library sure include extra python library provided sla generally ok packaging the second point package python app android it easily done wrapper well described sla website in fact distribute copy chapter book sla describes so possible bear mind user required install python done already sort alert launch app ui the third thing mind free concerning widgetlayout use sla namely really whatever would able java scala so might consider altering ui webview instead communicate back forth python framework obtain mobile look feel hope helps,can i port existing python scripts android using sla ase what i specifically want create android application normal ui elements run python scripts application get output display is possible,1 install pyrex first work do following sudo pip install pyrex,i trying build python package pyregion contains pyx file error comes build process checking output python setuppy build running build running buildpy creating build creating buildlibmacosxx running buildext building pyregionregionfilter extension c compiler gcc fnostrictaliasing fnocommon dynamic arch x dndebug g o arch x error unknown file type pyx srcregionfilterpyx any ideas issue could just note i using enthought build python osx latest xcode cheers,2 uris namespaces never looked parser matter behind proxy but parser lxml checks whether valid uris so nsmap none defaultns gsa gsans,i scripts designed access online api google search appliance requires specific xml format posted i built xml document using lxml problem upon attempting create root node i given valueerror invalid namespace uri exception here full example gsanshttpschemasgooglecomgsa defaultnshttpwwwworgatom gsasgsans defaultsdefaultns nsmapnonedefault gsagsa entryetelementdefaultentrynsmapnsmap and exception thrown traceback recent call last file stdin line module file lxmletreepyx line lxmletreeelement srclxmllxmletreec file apihelperspxi line lxmletreemakeelement srclxmllxmletreec file apihelperspxi line lxmletreemakeelement srclxmllxmletreec file apihelperspxi line lxmletreeinitnodenamespaces srclxmllxmletreec file apihelperspxi line lxmletreeurivalidorraise srclxmllxmletreec valueerror invalid namespace uri u httpschemasgooglscomgsa can someone explain means i behind http proxy i think problem i remove gsa namespace keep worg namespace i get exception,1 i understand mean equivalent using object oriented approach in python since functions say firstclass objects objectoriented pass functions arguments standard way achieve language functions first class objects only extent standard way functions failing firstclass objects i would say in c common create another class often called functor functionoid defines overload operator allowing instances used like functions syntactically however also often possible get plain old functionpointers neither pointer pointedat function firstclass object interface rich enough this meshes well adhoc polymorphism achieved templates write functions actually care whether pass instance class function pointer similarly python make objects register callable defining call method class do blocks like smalltalk objectivec count functions respect i would say at least much lambdas count functions python actually crippled way python lambdas would blocks best way languages it depends need could add new method runtime in languages would possible easy languages offer introspection runtime access compiler python qualifies however nothing problem presented far suggests need jump hoops of course languages required boilerplate others new class or would better create object single method performs desired operation that pretty standard what i wanted pass lots functions would i create lots singleton objects you say might somehow accidentally create one instance class write tons boilerplate attempt prevent would considered object oriented approach again i fathom understanding term objectoriented it mean creating lots objects would anyone consider python functions first class objects not without need extra things class function with duck typing earth would bother,i program python includes class takes function argument init method this function stored attribute used various places within class the functions passed quite varied passing key selecting set predefined functions would give degree flexibility now apologies long list questions like cool is standard way achieve language functions first class objects do blocks like smalltalk objectivec count functions respect would blocks best way languages what blocks could add new method runtime in languages would possible easy or would better create object single method performs desired operation what i wanted pass lots functions would i create lots singleton objects would considered object oriented approach would anyone consider python functions first class objects,1 name value sortedosenvironitems print name value,i printing environment variables printed sorted way variable osenviron print variable osenvirongetvariable i would like sort osenviron i tried put osenviron list sort function working any clue thank,3 quick dirty solution predefined log levels without defining new class loggingaddlevelname loggingwarning msm logginggetlevelnameloggingwarning loggingaddlevelname loggingerror msm logginggetlevelnameloggingerror,some time ago i saw mono application colored output presumably log system messages standardized now python logging module lets specify lot options customize output so i imagining something similar would possible python i can’t find anywhere is way make python logging module output color what i want instance errors red debug messages blue yellow of course would probably require compatible terminal modern terminals i could fallback original logging output color supported any ideas i get colored output logging module,3 the subject encoded according rfc see internationalized headers section email module here example decoding subject unicode isoqmrkrfber mrkroebergmailcom emailheader import decodeheader decodeheaders mr krxfber iso mrkroebergmailcom none u u joinwdecodee ascii decodeheaders u u mr krxfber mrkroebergmailcom print u mr krã¶ber mrkroebergmailcom,i receiving emails google app engine python storing datastore class logsenderhandlerinboundmailhandler def receiveself mailmessage logginginforeceived message mailmessagesender when i receive email ascii address everything works fine me megmailcom stored me megmailcom however sender values contains nonascii chars data value stored looks like mr krã¶ber mrkroebergmailcom stored isoqmrkrfber mrkroebergmailcom,3 i using one used django seems pretty well def isvalidurlurl import regex recompile r https http https r azazazaz domain r localhost localhost r dddd ip r optional port r s reignorecase return url none regexsearchurl you always check last version httpscodedjangoprojectcombrowserdjangotrunkdjangocorevalidatorspyl,i building app google app engine i incredibly new python beating head following problem past days i class represent rss feed class i method called seturl input method url i trying use python module validate rfc regex httpwwwietforgrfcrfctxt below snipped work p recompile pmatchurl selfurl url return url,3 have tried opening file utf encoding flah fd open somexml mode r encoding utf xmletreeelementtreeiterparsefd or use decode fd open somexml mode r sio stringiofdreaddecodeutf xmletreeelementtreeiterparsesio,i trying parse medline xml documents using iterparse xmletreeelementtree module all working well except text includes nonascii characters i see way handling unicode using findtext any suggestions,1 obviously compile timeruntime distinction what check value sysplatform,yes i know way summarize i want for opening serial port i want use portfd osopenportname osordwr osononblock problem ononblock exist windows means blows i testing windows deployment os supports non block so i really want ononblock go away defined windows environment i go business without error any ideas ps please explain python compilesinterprets i get i trying communicate idea,1 you could use tryexcept block eg try options osordwr osononblock except nameerror options osordwr portfd osopenportname options this using python approach easier ask forgiveness permission,yes i know way summarize i want for opening serial port i want use portfd osopenportname osordwr osononblock problem ononblock exist windows means blows i testing windows deployment os supports non block so i really want ononblock go away defined windows environment i go business without error any ideas ps please explain python compilesinterprets i get i trying communicate idea,1 another method nobody yet suggested portfd osopenportname osordwr getattros ononblock this easy way default attribute might exist,yes i know way summarize i want for opening serial port i want use portfd osopenportname osordwr osononblock problem ononblock exist windows means blows i testing windows deployment os supports non block so i really want ononblock go away defined windows environment i go business without error any ideas ps please explain python compilesinterprets i get i trying communicate idea,2 def searchkeysadictionarysearchterm results kv adictionaryiteritems searchterm k searchterm v resultsk v return results shorter results dictkv kv aiteritems searchitem k searchitem v it however work example dictionary value cat string therefore cannot contain another string,i wrote simple function receives dictionary string parameter the function uses string search dictionary returns new dictionary results now need help modifying code creating new function passed string searches values keyvalue pair opposed keys so i pass parameter i get new dictionary includes cat hopefully clear thanks advance rainbows xbox solider miltary cat def searchkeysadictionarysearchterm results adictionary searchterm resultsi adictionaryi return results searchkeysa r rainbows xbox solider miltary,2 i find beautifulsoup awkward use here version based webscraping module webscraping import common download xpath download html d downloaddownload html dget httpwwwexpatistancomcostoflivingcomparisonmelbourneauckland extract data items xpathsearchhtml tdclassitemname cityprices xpathsearchhtml tdclassprice city cityprices xpathsearchhtml tdclassprice city display format item cityprice cityprice zipitems cityprices cityprices print itemstrip citypricestrip commonremovetagscityprice falsestrip output daily menu business district au nz combo meal fast food restaurant big mac meal similar au nz kg lb chicken breast au nz,this covered post python web scraping involving html tags attributes but i able something similar web page httpwwwexpatistancomcostoflivingcomparisonmelbourneauckland i trying scrape values td classprice city nz span stylewhitespacenowrapauspan td td classprice city au td basically price city price city nz au currently import urllib beautifulsoup import beautifulsoup url httpwwwexpatistancomcostoflivingcomparisonmelbourneauckland page urlliburlopenurl soup beautifulsouppage price soupfindall td attrs class price city price soupfindall td attrs class price city price price print price price price print price ideally i also like comma separated values th colspan classclickablefoodth extracting food td classitemnamedaily menu business districttd extracting daily menu business district values price city pricecity so printout would food daily menu business district nz au thanks,1 queryexpression querycondition zeroormorewordand querycondition this required parse entire line zeroormore means exactly it stops encounters something fails meet definition it always succeed zero valid option number times nested expression matched if want parse way end line need expression explicitly requires example tacking lineend lines special unless make a parsing expression default expects match prefix input entire input always might want use another expression parse next bit,i following snippet recursive statement pyparsing parser def parsequeryquerystr parsing stuff queryexpression querycondition zeroormorewordand querycondition try return queryexpressionparsestringquerystr except parseexception e loggerdebugerror parsing n formatquerystr e return none i feed query tokens parsequeryhree blaa thisisnotand klastt eq true printtokens yields hr ee bl aa silently skips last condition no exception thrown how i catch error string,1 with python simple solution def searchitemsadictionary searchterm return kv k v adictionaryiteritems searchterm k searchterm strv or sure values strings write v instead strv,i wrote simple function receives dictionary string parameter the function uses string search dictionary returns new dictionary results now need help modifying code creating new function passed string searches values keyvalue pair opposed keys so i pass parameter i get new dictionary includes cat hopefully clear thanks advance rainbows xbox solider miltary cat def searchkeysadictionarysearchterm results adictionary searchterm resultsi adictionaryi return results searchkeysa r rainbows xbox solider miltary,1 veusz runs user interface separate python process block python if look veuszembedpy tries start python veusz executable you need modify embedpy start exe sysexecutable frozen instead veusz pass special parameter program would interpret start running veuszembedremoterunremote the python multiprocessing module something similar need call multiprocess function checks whether program starting multiprocessing get around fact windows working fork,i would like distribute application written python exe file i already able using pyexe i incorporated veusz library code ideally program open veusz plot computer python numpy etc installed however i want distribute executable without install python when i try running setuppy pyexe everything goes fine exe built however application runs gets point display graph sends runtime error unable find veusz executable system path can i fix without install bunch stuff clients computers is possible and i must install something minimum amount software i need install,1 my advice reread input file may well recreate dictionary depends time needed dictionary creation as request maybe quicker analyze differences file update dictionary you look difflib module analyze differences based removals deleted dictionary addition added necessary sadly i bet hard time output meant humanreadable machinereadable may better answer edit want keep track changes two files version written comment compare dictionaries for keys already needed now updated values sure values always lists strings quite thing comparing dict keys def compolddict newdict key oldval olddictitems newval newdictkey warning used keys dict print evolutions key print new content x x newval x oldval print removed content x x oldval x newval testing simple example key b c n key b c compo n evolutions key new content removed content warning function works newdict contains keys olddict otherwise creation newval fail you easily go around concern adding comparisons keys function keys olddict newdict removed entries keys newdict olddict additions please publish result answer others may benefit,i want find optimal way iterate values key python i file structure key key key key key key key i need set second column keywith repetition link key values first column corresponding key key key key up i without using dictionary line file value key linestripsplitnone and i put dictionary dictionsetdefaultkey appendvalue i nice dictionary i needed but i reread file changes changes occur keyspairs addingremoving value addingremoving how i check change occured iteration keys values upd keys check less clear dictionkey iterate values inside key i need find difference addremove valuepairif last value key dictionary i suppose done iteritemitervalues smthng i familiar thank help upd thank joã«l finally i used checks first keys added setolddict setnewoldkeys setnewdict setnewdictkeys intersect setnewdictintersectionsetolddict def addedself return setnewdict intersect def removedself return setolddict intersect and i catch already processed situations i use function def compolddict newdict key oldval olddictitems newval newdictkey print evolutions key print new content x x newval x oldval print removed content x x oldval x newval,1 stringio gives filelike access strings use existing module deals file change almost nothing make work strings for example say logger writes things file want instead send log output network you read file write contents network write log stringio object ship network destination without touching filesystem stringio makes easy first way switch second way,i pro i scratching head understanding exactly stringio used i looking around internet examples however almost examples abstract and show use but none show circumstances one shouldwill use thanks advance ps confused question stackoverflow stringio usage compares string stringio,3 there pretty good tutorial ars technica using streaming api n python might helpful otherwise could try via curl,for research project i collecting tweets using pythontwitter however running program nonstop single computer week manage collect mb data per week i running program one machine collect tweets twice our program runs loop calls getpublictimeline every seconds i tried improve calling getusertimeline users appeared public timeline however consistently got banned collecting tweets half hour time even without ban seemed little speedup adding code i know twitter whitelisting allows user submit requests per hour i applied three weeks ago hear back since i looking alternatives allow program collect tweets efficiently without going standard rate limit does anyone know faster way collect public tweets twitter we like get mb per week thanks,1 it used api takes files need use string for example compress string using gzip module python import gzip import stringio stringio stringiostringio gzipfile gzipgzipfilefileobjstringio mode w gzipfilewrite hello world gzipfileclose stringiogetvalue,i pro i scratching head understanding exactly stringio used i looking around internet examples however almost examples abstract and show use but none show circumstances one shouldwill use thanks advance ps confused question stackoverflow stringio usage compares string stringio,3 in cases want filelike object acts like file writing inmemory string buffer stringio tool if building large strings plaintext documents lot string concatenation might find easier use stringio instead bunch mystr stuffn type operations,i pro i scratching head understanding exactly stringio used i looking around internet examples however almost examples abstract and show use but none show circumstances one shouldwill use thanks advance ps confused question stackoverflow stringio usage compares string stringio,3 build solution takes sample webpages structure eg forum threads analyzes dom tree find parts different different dynamic content posts user names etc this technique known wrapper induction,i would like scrape several different discussions forums different html formats rather dissecting html page would efficient fun implement sort learning algorithm could identify different messages ie structures page individually parse simultaneously ignoring extraneous crap ie ads nonsense could someone please point references sample code work already carried area moreover anyone know pseudocode arc readability code httpwwwminvolaicomblogdecruftarcsreadabilityinpython,1 say something like care second field myrowscexecuteselect valuesbust values where var also wondering really want create plot line dont want plot data one plot,i reading rows sqlite db looping using variables row arguments function generates plots something like following pseudo code connsqliteconnectdb cconncursor myrowscexecuteselect values where var burst myrows metburst makeplotmet cclose after certain amount time gives either one following errors items requested read segmentation fault unable alloc bytes aborted segmentation fault the makeplot read large file mb operations data elements myrows from errors i think i running memory i managed find anything would help track downdiagnose problem any ideas i would,1 you use sorted accepts key argument returns list li b c def ks sstartswith b return else return sortedli keyk b c k shall return something compared iterable items note sort change input inplace returns nothing sorted returns sorted list modify list both work way,i series lists looks like li b c e li b c e how i rearrange items list first item bsomething for example li b c e li b c e maintaining order first item important thanks help,2 python sorting stable maintain order first item regardless lisortkeylambda x xstartswith b,i series lists looks like li b c e li b c e how i rearrange items list first item bsomething for example li b c e li b c e maintaining order first item important thanks help,3 rearrange items list first item bsomething maintaining order first item important that sorting conceptually trying bring element front in words want list consists element followed everything element fudging little case multiple bsomething noting care happens long first element bsomething rephrase list every element meeting condition starts b followed every element meeting condition this sometimes called partitioning see example stdpartition c in python simple describing two listcomponents list comprehensions sticking together x x li xstartswith b x x li xstartswith b or pretend sorting bunch elements really two values key applied apply appropriate key ignacio vasquezabrams answer,i series lists looks like li b c e li b c e how i rearrange items list first item bsomething for example li b c e li b c e maintaining order first item important thanks help,2 flask request object well actually class returned localproxy instance request subclass werkzeug multidict data structure includes getlist method pageids requestformgetlistdodelete,i jinja template looks like form action methodpost table tr thth thidth thtitleth tr page pages tr tdinput typecheckbox namedodelete value page id td td page id td tda href page id page title atd tr endfor table with selected input typesubmit valuedelete form and i function delete pages according checkboxes checked delete button clicked dbsessionquerypagefilterpageidinpageidsdelete what i stuck i iterate checkboxes form pageids list checked ones,3 update python recent version you run afoul bug introduced almost immediately fixed from bug report in python builtin function input returns string trailing r windows cpythonpython python r feb msc v bit intel win type help copyright credits license information printreprinput test testr time line released issue reported issue fixed,the following block code ans x ans y n n ans inputdo something yn printans y n n produces following output do something yny false do something yny false do something ynn false do something ynn false do something ynasdf false do something yntraceback recent call last file numberpatternspy line module ans inputdo something yn keyboardinterrupt i want read user input repeatedly y n n but loop never stops there must something missing please help edit this result code run interactive mode version windows machine cusersjwalkerpython python r feb msc v bit amd win type help copyright credits license information ans x ans y n n ans inputdo something printans y n n printans typeans lenans ordans reprans print y type y len y ord y repr y do something asdf false class str asdfr y class str y do something y false class str yr y class str y do something n false class str nr y class str y do something traceback recent call last file stdin line module z,2 i done so project a project b project b wants call models project a project b connects database userlogin project a if import models project a project b interact like normal project b connects different database project a you define two databases settings file project b databases default name appdata engine djangodbbackendspostgresqlpsycopg user postgresuser password skrit users name userdata engine djangodbbackendsmysql user mysqluser password privte and either define db router django knows database go get data models project a or you explicity set db use making calls orm using something like authorobjectsusing,i looking way interact models django project within separate django project i mean different apps i mean separate projects separate settings files i process migrating old web store really old static html django based backend to i created separate django app would handle crawling parsing using django orm views human assisted parsing now i point i need populate catalog data backend data stored crawler project i spent better part last days trying figure method luck what i ideally like import store project module django command class interact way mind working separate settings files setupenviron work i like avoid serializing crawler data importing store interacting store database outside django orm project far i prefer keep things flexible possible what would suggest i wild ideas long i interact orm projects within single script,1 item myist item element element elementn something if order frequency items mylist matter also use item setmylist amp setelement element elementn something,i want check item list equals one element given set n elements yes thing for example intuitive course cumbersome ugly way item list item element item element item elementn something what better ways check,2 you item list something list properly initialized elements want match,i want check item list equals one element given set n elements yes thing for example intuitive course cumbersome ugly way item list item element item element item elementn something what better ways check,1 you use operator elements setelement element elementn item elements something use either set tuple elements set faster lookups requires elements hashable a tuple lighter weight elements gets slower elements also unless elements vary loop initialise collection outside loop avoid overhead creating settuple every time,i want check item list equals one element given set n elements yes thing for example intuitive course cumbersome ugly way item list item element item element item elementn something what better ways check,3 walkd function taking argument you call function pass argument get result example printwalkdcumsum,hello function walkd want calculate cumsum i use walkdlambda n sccumsumstepsn the result array trying walkdcumsum work typewalkd function if try scarraywalkdcumsum gives x how handle import matplotlibpyplot plt import scipy sc stepslambda scrandomrandomintegerssizem walkdlambda n sccumsumstepsn printscarraywalkdcumsum thanks,1 griddata uses spline fitting a rd order spline thing rd order polynomial instead different rd order polynomial every point if want fit d rd order polynomial data something like following estimate coefficients using data points import itertools import numpy np import matplotlibpyplot plt def main generate data numdata x nprandomrandomnumdata nprandomrandomnumdata z x x nprandomrandomnumdata fit rd order polynomial polyfitdxyz evaluate grid nx ny xx yy npmeshgridnplinspacexmin xmax nx nplinspaceymin ymax ny zz polyvaldxx yy plot pltimshowzz extentxmin ymax xmax ymin pltscatterx cz pltshow def polyfitdx z order ncols order g npzerosxsize ncols ij itertoolsproductrangeorder rangeorder k ij enumerateij gk xi yj nplinalglstsqg z return def polyvaldx order intnpsqrtlenm ij itertoolsproductrangeorder rangeorder z npzeroslikex ij zipm ij z xi yj return z main,i currently working astronomical data among i comet images i would like remove background sky gradient images due time capture twilight the first program i developed took user selected points matplotlib ginput xy pulled data coordinate z gridded data new array scipy griddata since background assumed vary slightly i would like fit low order polynomial set xyz points however griddata allow input order griddatapointsvalues dimensionxdimensiony method nearestlinearcubic any ideas another function may used method developing leassquares fit allow control order,3 couple things i personally used wholefile caching i script reads pdfs validation various things the pdf library i using takes open file document constructor i originally opened pdf i interested reading however i changed read entire file memory pass stringio object pdf library running time script cut half deferred printing same script prints header every pdf reads however i specify command line whether ignore certain tests configuration file include certain ones if i ignore tests given pdf i want header printed i know many tests i ran i done running tests tests defined dynamically well so i capture header stringio object changing sysstdout point time i run test i check see whether object anything if i print reset empty voila pdfs tests headers printed,i pro i scratching head understanding exactly stringio used i looking around internet examples however almost examples abstract and show use but none show circumstances one shouldwill use thanks advance ps confused question stackoverflow stringio usage compares string stringio,3 this completely correct the interactive python interpreter displaye repr string if want see proper string print print xexx –,i get following string database xexx output look like how i decode i tried utf decoding luck xdecodeutf u u thank,3 that code works perfectly well python ans x ans y n n ans inputdo something yn printans y n n do something yny true this makes suspect question hint complicated basic example where running code is function inside loop,the following block code ans x ans y n n ans inputdo something yn printans y n n produces following output do something yny false do something yny false do something ynn false do something ynn false do something ynasdf false do something yntraceback recent call last file numberpatternspy line module ans inputdo something yn keyboardinterrupt i want read user input repeatedly y n n but loop never stops there must something missing please help edit this result code run interactive mode version windows machine cusersjwalkerpython python r feb msc v bit amd win type help copyright credits license information ans x ans y n n ans inputdo something printans y n n printans typeans lenans ordans reprans print y type y len y ord y repr y do something asdf false class str asdfr y class str y do something y false class str yr y class str y do something n false class str nr y class str y do something traceback recent call last file stdin line module z,1 the standard way output enter batch echo line additional spaces to output enter followed y may try echoampecho y nameofbinary insert spaces echoamp if works would linefeed characters inserted first enter y the exact sequence bytes generated echoampecho y crlfycrlf cr carriage return lf line feed if previous method problems may create file cry bytes batch file echo echo enterytxt echo e echo echo w echo q debug enterytxt nul execute command way nameofbinary enterytxt ps please note echo nameofbinary generate crlf space echo nameofbinary,i trying run windows xp command line program prompts enter continue currently i respond running program echo nameofbinary batch file i figure tell shell respond enter required if gets press enter continue sort prompt many enough cause problems echoes get stuck weird loop accept input spews thousands press enter continue if i could echo first enter sequence might work none methods i tried echoing enter keypress worked i ultimately calling batch file ossystem python if way get python run binary ossystemnameofbinary and respond prompts would ideal i already tried ossystemecho nameofbinary behaved way batch file should i using different approach i solve modifying echo command i currently using,1 you always add subclass here basic implementation orderedset linked comment class indexorderedsetorderedset def indexself elem key selfmap return nexti e enumerateself e elem else raise keyerrorthat element set you mentioned need add index inorder iteration you get using ordereddict storage as bonus subclass collectionsset abstract class get set operations frozenset support itertools import count izip collections import ordereddict set class indexorderedsetset an orderedfrozensetlike object allows constant time index ing but allow remove elements def initself iterable selfnum count selfdict ordereddictizipiterable selfnum def addself elem elem self selfdictelem nextselfnum def indexself elem return selfdictelem def containsself elem return elem selfdict def lenself return lenselfdict def iterself return iterselfdict def reprself return indexorderedset formatselfdictkeys you subclass collectionsmutableset support removing elements set keep indexes correct,does anyone know fast orderedset implementation python remembers insertion order index method like one lists offer all implementations i found missing index method,3 randomcolor result randomrandom float if want get something use intrandomcolor another specific function random module,i one error says float attribute int error the question write function takes parameter image draws two vertical lines img one red line one made randomly colored pixels for reason random part i randomcolorint i error is something i need convert this code cimage import import random randomcolor randomrandom myimwin imagewinline image lineimage emptyimage redpixel pixel randomred pixelrandomcolorint range x range lineimagesetpixeliredpixel randomredsetpixelxrandomred lineimagedrawmyimwin randomredsavelineimagegif any suggestions would help thanks,1 randomrandom returns random floating point range if wanted integer intrandomcolor would random intrandomcolor get you want random number randomrandint,i one error says float attribute int error the question write function takes parameter image draws two vertical lines img one red line one made randomly colored pixels for reason random part i randomcolorint i error is something i need convert this code cimage import import random randomcolor randomrandom myimwin imagewinline image lineimage emptyimage redpixel pixel randomred pixelrandomcolorint range x range lineimagesetpixeliredpixel randomredsetpixelxrandomred lineimagedrawmyimwin randomredsavelineimagegif any suggestions would help thanks,3 this time listappend listextend def scoreaddteam exitscores e zipteam exitscores tappende print team b list lists exitscores list integers edit here cleanedup version whole code b zipt b textendb tappendt,working python i two lists simplified make explanation clear t b and three functions def exitscorelist exitscores length lenlist range length score listi listi exitscoresappendscore return exitscores first i append corresponding values b corresponding lists t def transt b b zipt b textendb exitscoret b t scoreaddb then using previously listed exitscore function i subtract value list position value list position fore list i append results another list exitscores finally i want add exitscores original list so i use scoreaddb function scoreaddteam exitscores e zipteam exitscores textende print team if everything working correctly i would get output like instead i get typeerror telling i iterate integer but i tried printing b list form when i change code make sure exit scores list def transt b es b zipt b textendb esappendexitscoret scoreaddt es the entire exitscores list es added end first list t for life i figure i wrong,2 the operating system make difference python syntax most likely cygwin installation includes python confirm typing python cygwin prompt checking banner note cygwin prompt unix if must install python cygwin,i got code years ago python it working properly back it something like try ospathexistsospathjointraceslogfilepath traceslogfilename osremoveospathjointraceslogfilepath traceslogfilename except ioerror e print stre now piece code working windows i get following error invalid syntax to resolve problem changed following try ospathexistsospathjointraceslogfilepath traceslogfilename osremoveospathjointraceslogfilepath traceslogfilename except ioerror e print stre i happy couple minutes later realized code working cygwin prompt compiler like switch back comma i would like know exact syntax try except i would like syntax windows unix mac os thank,1 standard input output bytebased unix systems that call unicode function get characterstrings the decode error indicates bytes coming valid utf basically problem assumption utf encoding guaranteed confirm changing encoding unicode call iso changing character encoding terminal emulator utf putty supports translation menu if experiment confirms challenge support locale user deduce correct encoding perhaps make user declare encoding command line argument configuration the lang environment variable best without explicit declaration i find poor indicator desired character encoding,i trouble encodings i using version python default oct gcc linux i chars accents like ã© ã my scripts uses utf encoding usrbinpython coding utf users type strings usings rawinput def rlinputprompt prefill readlinesetstartuphooklambda readlineinserttext prefill try return rawinputprompt finally readlinesetstartuphook called main loop pseudo shell tocontinue tocontinue feedback action unicoderlinputu todo utf ossystem clear print t un feedback data stored pickle files i managed app working finaly get stupid things like core file class task def strself r uok selfdone else ua faireljust selfgetdesc return rencode utf shell file feedback jaune strtdecode utf vert u supprimã©e that realize might totaly wrong encodingdecoding so i tried decode directly rlinput failed i read post stackoverflow reread httpdocspythonorglibrarycodecshtml waiting python book lost i guess lot bad code question related encoding issus you find code comments french sorry personnal use beginner also need yapsy httpyapsysourceforgenet configure paths pytodo todoshellpy httpbitlyrzpjm,1 mongoengine provides authentication django apps mongodb,switching sqlite mongodb i followed setupconfiguration settings django mongodb engine now i go add user returning http response adduser method viewspy def adduserrequest username requestpost username password requestpost password u userobjectscreateuserusername requestpost email password usave accountsuseru p passwordsuseru asave psave user authenticateusernameusername passwordpassword user none userisactive authloginrequest user return httpresponseredirects uid else return httpresponseredirectaccountinvalid this error i get databaseerror adduser relation authuser exist naturally relationship exist since mongodb nosql is auth system supported mongoengine better solution perhaps i move postgre sqlite cannot handle simultaneous users viable option i saw question year ago hopefully things changed mongodb gained lot popularity year,1 if qobject subclass parent qt delete parent deleted on hand qobject subclass parent eventually deleted python hopefully example make things somewhat clearer pyqt import qtgui class widgetqtguiqwidget def initself parent qtguiqwidgetinitself parent selfdestroyedconnectselfhandledestroyed def delself print del self def handledestroyedself source print destroyed source class foowidget def initself parent widgetinitself parent class barwidget def initself parent widgetinitself parent class windowwidget def initself parentnone widgetinitself parent selffoo fooself selfbar barnone name main app qtguiqapplicationfile widgetcount window window windowshow appexec which outputs del mainwindow object xfc destroyed mainfoo object xf del mainbar object xfdc widgets left max widgets edit on second thoughts appears may bug least difference behaviour versions pyqt as possible workaround seems creating two python names main widget explicitly deleting may help ensure c python sides object get destroyed if following line added script tmp window del tmp window then output becomes del mainwindow object xdac del mainfoo object xda del mainbar object xdadc widgets left max widgets,using code del method preview widget never gets called if i uncomment del window line why usrbinenv python pyqt import qtgui class previewqtguiqwidget def initself parent qtguiqwidgetinitself parent def delself printdeleting preview class previewwindowqtguiqmainwindow def initself qtguiqmainwindowinitself selfwidget previewself selfsetcentralwidgetselfwidget def delself printdeleting previewwindow name main app qtguiqapplicationdimension preview window previewwindow windowshow appexec del window,1 import put module namespace returns instead import calls import plus stores result variable the docs say import spam something similar spam import spam globals locals to get effect c api need assign emb global in words set emb attribute main module pyobject embmodule pyimportimportmoduleemb pyobject mainmodule pyimportaddmodulemain pyobjectsetattrstringmainmodule emb embmodule pyxdecrefembmodule mainmodule borrowed reference,here canonical example program extending embedded python x cc include pythonh definition emb python module static pyobject embfoopyobject self pyobject args char const n i foo return pybuildvalues n static pymethoddef embmethods foo embfoo methvarargs returns foo null null null static pymoduledef embmodule pymoduledefheadinit emb null embmethods null null null null static pyobject pyinitembvoid return pymodulecreateampembmodule embedded python emb loaded int main pyimportappendinittabemb amppyinitemb pyinitialize pyrunsimplestringimport embn pyimportimportmoduleemb pyrunsimplestringprintembfoon pyfinalize return i add emb module builtins embedded interpreter i also like import automatically users issue import emb statement scripts supplied embedded interpreter i trying two ways importing lines the works emb module found without explicit import simple test line however i comment line uncomment line import c api python call line produces error traceback recent call last file string line module nameerror name emb defined i like understand difference two manners importing do import module different namespaces scopes the python documentation led along path pyimportimportmodule best described referring builtin python function import import function invoked import statement perhaps i made mistake assuming pyimportimportmodule onetoone equivalent i using pyimportimportmoduleex correct exactly globals locals emb lands global namespace embedded interpreter,3 the utf representation en dash httpwwwfileformatinfoinfounicodecharindexhtm hex xe x x e uu it sounds like want replace endash character ascii hyphenminus xd store variable that ok variable contain character stored database replaced 㜠httpwwwfileformatinfoinfounicodechardcindexhtm ascii u replaced zero x capital o xf,i get following string database xexx output look like how i decode i tried utf decoding luck xdecodeutf u u thank,1 the first line travel travellocation implicitly marks name travel local whole function all lookups name look local name including one righthand side cited line at time value assigned local name though hence error there might global name travel since compiler identified travel local name look local namespace use different name local variable,i completing text based game intro python class it complete i working mainmenu function functions called within mainmenu function i ran error message i encountered error several times learning experience usually attributed basic mistake assigning variables one stumped this script question lines traceback commented bold import random sys import exit item variables coal coal coal used furnace engkey key key house bomb bomb combustible device creates powerfull explosion possibly used demolition tonic tonic weak healing tonic adds health points stonic super tonic strong healing tonic adds health points locations below possible locations travel along title first item tuple description items might found location discovered entered inventory search command location variable title description item discovery subbase subbase this deepblue base operations atlantis excavation zone your submarine docked ahead nothing useful cave underwater cave you entered mouth underwater cave sub nothing useful cemetery cemetery chamber you large chamber within cave this seems cemetery there symmetrically lined mounds dirt obelisks head nothing useful citygate city gate you stand crossroad sorts bottom upward sloping ramp nothing useful cityoutskirts city outskirts you find outside city walls nothing useful castleoutskirts rear castle ruins you standing rear castle ruins there layer rubble blocking way clearly see passage leading inside perhaps devise way move nothing useful castleinside inside grand castle atlantis you made inside castle all advanced knowledge atlanteans disposal nothing useful cityblock beginning main avenue city you standing beginning main avenue city nothing useful ruins rubble dilapidated house you standing middle ruins seems house tonic mystichouse mystic house you standing inside city mystic house stonic cityblock second block city you moved second block city main avenue nothing useful abandonedhouse abandoned house you standing middle abandoned house engkey blacksmithhouse blacksmith house you standing seems blacksmith building there furnace iron ore smith tools various components making swords no coal though nothing useful but right items something created cityblock third block city you moved third block city main avenue nothing useful marketplace abandoned marketplace you standing middle abandoned marketplace there might useful items laying around coal engineerhouse engineer house you standing engineer house there might useful items lying around bomb castlemain castle main entrance you standing front main entrance huge castle the grand entrance blocked massive amounts rubble there must another way nothing useful items items may added inventory items coal engineerhouse engkey engineerhouse bomb castleinside tonic anywhere stonic anywhere interactionslocationbased dictionary events each location certain events take place interactions dictionary location useitem response search response levents subbase cave cave subbase cemetery citygate cemetery cave cityoutskirts citygate cave cityoutskirts cityblock cityoutskirts cemetery castleoutskirts citygate castleoutskirts cityoutskirtscastleinside castleinside castleoutskirts cityblock citygate ruins mystichouse cityblock ruins cityblock mystichouse cityblock cityblock cityblock abandonedhouse blacksmithhouse cityblock abandonedhouse cityblock blacksmithhouse cityblock cityblock cityblock marketplace engineerhouse castlemain marketplace cityblock engineerhouse cityblock castlemain cityblock travel options below dictionary outlining possible places travel depending currently located peice essential travel function travelopt subbase cave cave subbase cemetery citygate cemetery cave cityoutskirts citygate cave cityoutskirts cityblock cityoutskirts cemetery castleoutskirts citygate castleoutskirts cityoutskirtscastleinside castleinside castleoutskirts cityblock citygate ruins mystichouse cityblock ruins cityblock mystichouse cityblock cityblock cityblock abandonedhouse blacksmithhouse cityblock abandonedhouse cityblock blacksmithhouse cityblock cityblock cityblock marketplace engineerhouse castlemain marketplace cityblock engineerhouse cityblock castlemain cityblock def ehouseaccessaction location ehouse ehouse locked print the door locked you need find key door travellocation else location traveloptlocationaction travellocation def cinsideaccessaction location cinside cinside blocked print the path blocked rubble you need find way clear rubble travellocation else location traveloptlocationaction travellocation def travellocation true print you location print location print you travel enumeratetraveloptlocation print action rawinputpick destination enter menu main menu action menu mainmenulocation inventory items else action intaction traveloptlocationaction engineerhouse ehouseaccessaction location ehouse elif traveloptlocationaction castleinside cinsideaccessaction location cinside else location traveloptlocationaction def mainmenulocation inventory items travel travellocation line invtry showinvinventory use useitems inventory quit exit true print you location menulist travel travel inventory invtry use use search search map map quit quit print choose one num enumeratemenulist print num mainchoice intrawinput action menulistmainchoice action def searchlocation pass def maplocation pass def showinvinventory inventory print your inventory empty inv empty return inv else num enumerateinventory print num inv inventory return inv def useitems inventory showinvinventory empty print there nothing use else showinvinventory uitem intrawinputchoose item use location subbase inventory ehouse locked cinside blocked hp map key indicates point entry castlecastle outsk irts city outsk city irts grave city yard gates cave sub base citymap key indicates point entry castle city engin market block eer place house aband city black oned block smith house house city rubble block mystic house name rawinputenter name print welcome atlantis excavation zone name print your first day job already new cave map lucky print the deepblue team takes sub base time get work mainmenulocation inventory items line and traceback traceback recent call last file expy line module mainmenulocation inventory items file expy line mainmenu travel travellocation unboundlocalerror local variable travel referenced assignment i thought variable assigned line what i missing,3 add wordboundary matcher b refindallr azazb movavx movsumy z x z b matches empty string two words looking letters followed word boundary immediately followed for details see docs,i regular expression i trying extract every group letters immediately followed symbol for example following regular expression operates mathematical formula includes variable names x z function names movav movsum composed entirely letters function names followed refindallazaz movavx movsumy z i would like expression return array x z instead returns array mova x movsu z i see theory regular expression would returning second result way i modify return array x z,2 you need limit matches whole words so use b match beginning end word refindallrbazazb movavx movsumy z,i regular expression i trying extract every group letters immediately followed symbol for example following regular expression operates mathematical formula includes variable names x z function names movav movsum composed entirely letters function names followed refindallazaz movavx movsumy z i would like expression return array x z instead returns array mova x movsu z i see theory regular expression would returning second result way i modify return array x z,1 i would seriously consider moving using client javascript library like jquery your code would simplified something like script typetextjavascript userunamechange function var selecteduname thisvalue function updateadduser var fields null ajaxurl ajaxuseraddpsp datatype json success functiondata fields data objectkeysfieldsforeachfunction name var input name inputvalue fieldsname script form actionadduserpsp methodget fieldset label forunameusernamelabel select nameuname iduseruname onchangeupdateadduser import mysqldb db c dbcursor cexecuteselect user employees tup cfetchall tupstr strtup tupstr tupstrreplace replace replace replace replace replace replace tupstr tupstrrstrip numlist tupstrsplit optionlist option valuessoption x x x numlist options njoinoptionlist options select fieldset fieldset label forfnamefirst namelabel input typetext namefname fieldset fieldset label forlnamelast namelabel input typetext namelname fieldset fieldset label foremailemaillabel input typetext nameemail fieldset,so i code i trying use make update form text boxes i select different drop user here code script typetextjavascript documentgetelementbyiduserunameonchange function var selecteduname thisvalue var xmlhttp function loadxmldoc windowxmlhttprequest xmlhttpnew xmlhttprequest else xmlhttpnew activexobjectmicrosoftxmlhttp function updateadduser loadxmldoc xmlhttponreadystatechangefunction xmlhttpreadystate ampamp xmlhttpstatus var json xmlhttpresponsetext var fields jsonparsejson objectkeysfieldsforeachfunction name var input documentgetelementsbynamename inputvalue fieldsname xmlhttpopenget ajaxuseraddpsp true xmlhttpsend script form actionadduserpsp methodget fieldset label forunameusernamelabel select nameuname iduseruname onchangeupdateadduser import mysqldb db mysqldbconnectlocalhost login password somethingelse c dbcursor cexecuteselect user employees tup cfetchall tupstr strtup tupstr tupstrreplace replace replace replace replace replace replace tupstr tupstrrstrip numlist tupstrsplit optionlist option valuessoption x x x numlist options njoinoptionlist options select fieldset fieldset label forfnamefirst namelabel input typetext namefname fieldset fieldset label forlnamelast namelabel input typetext namelname fieldset fieldset label foremailemaillabel input typetext nameemail fieldset,1 my guess would calling randomredsetpixel instead lineimagesetpixel,this code draw two vertical lines one red line one made random pixels where says randomredsetpixelxrandomred line points pixel object attribute setpixel error i cannot figure error i setpixel right cimage import import random myimwin imagewinline image lineimage emptyimage redpixel pixel randomred pixelrandomrandint range x range lineimagesetpixeliredpixel randomredsetpixelxrandomred error points lineimagedrawmyimwin randomredsavelineimagegif myimwinexitonclick,1 another solution rely word boundaries check letters followed either another letter refindallr azazazaz movavx movsumy z x z,i regular expression i trying extract every group letters immediately followed symbol for example following regular expression operates mathematical formula includes variable names x z function names movav movsum composed entirely letters function names followed refindallazaz movavx movsumy z i would like expression return array x z instead returns array mova x movsu z i see theory regular expression would returning second result way i modify return array x z,2 an alternate approach find strings letters followed either endofstring nonletter nonbracket character capture letter portion refindallazazazaz movavx movsumy z,i regular expression i trying extract every group letters immediately followed symbol for example following regular expression operates mathematical formula includes variable names x z function names movav movsum composed entirely letters function names followed refindallazaz movavx movsumy z i would like expression return array x z instead returns array mova x movsu z i see theory regular expression would returning second result way i modify return array x z,1 import datetime datetimedatetimenow print unicodenowreplacemicrosecond,i adding utc time strings bitbucket api responses currently contain amsterdam time strings for consistency utc time strings returned elsewhere desired format followed germane what best way create string without microsecond component datetime instance microsecond component import datetime print unicodedatetimedatetimenow i add best option occurred possible answer may well elegant solution edit i mention i actually printing current time – i used datetimenow provide quick example so solution assume datetime instances receives include microsecond components,3 datetimedatetimenowstrftimeymd hms,i adding utc time strings bitbucket api responses currently contain amsterdam time strings for consistency utc time strings returned elsewhere desired format followed germane what best way create string without microsecond component datetime instance microsecond component import datetime print unicodedatetimedatetimenow i add best option occurred possible answer may well elegant solution edit i mention i actually printing current time – i used datetimenow provide quick example so solution assume datetime instances receives include microsecond components,3 i tried yet i think able elegantly pyyaml using call representers resolvers edit after extensive exchange comments poster method achieve required behavior pyyaml important note if persistable instance another instance attribute contained somehow inside one attributes contained persistable instance saved yet another separate file rather saved inline file parent persistable instance to best understanding limitation also existed op picklebased system may acceptable hisher use cases i found elegant solution involve hacking yamlrepresenterbaserepresenter import yaml functools import partial class persistableobject simulate unique id unique def initself args kw persistableunique selfpersistentid sd selfclassname persistableunique def persistablerepresenterdumper data id datapersistentid print writing file id outfile openid w outfilewriteyamldumpdata outfileclose return dumperrepresentscalaru xref u id class persistingdumperyamldumper pass persistingdumperaddrepresenterpersistable persistablerepresenter myyamldump partialyamldump dumperpersistingdumper def persistableconstructorloader node xref loaderconstructscalarnode print reading file id infile openxref r value yamlloadinfileread infileclose return value yamladdconstructoru xref persistableconstructor example use also serves test class foopersistable def initself selfone persistableinitself class barpersistable def initself foo selffoo foo persistableinitself foo foo bar barfoo print foo dumpedfoo myyamldumpfoo print dumpedfoo print yamlloaddumpedfoo print yamlloaddumpedfooone print bar dumpedbar myyamldumpbar print dumpedbar print yamlloaddumpedbar print yamlloaddumpedbarfoo print yamlloaddumpedbarfooone baz barpersistable print baz dumpedbaz myyamldumpbaz print dumpedbaz print yamlloaddumpedbaz from use myyamldump instead yamldump want save instances persistable class separate files but use inside persistablerepresenter persistableconstructor no special loading function necessary use yamlload phew took work i hope helps,i using python pickle module implementing thin filebased persistence layer the persistence layer part larger library relies heavily pickle persistentid feature save objects specified classes separate files the issue approach pickle files human editable i much rather objects saved format human readable editable text editor eg yaml json do know library uses humaneditable format offers features similar pickle persistentid alternatively suggestions implementing top yaml jsonbased serialization library without rewriting large subset pickle,2 yet another option import time timestrftimeymd hms by default uses local time need utc use following timestrftimeymd hms timegmtime,i adding utc time strings bitbucket api responses currently contain amsterdam time strings for consistency utc time strings returned elsewhere desired format followed germane what best way create string without microsecond component datetime instance microsecond component import datetime print unicodedatetimedatetimenow i add best option occurred possible answer may well elegant solution edit i mention i actually printing current time – i used datetimenow provide quick example so solution assume datetime instances receives include microsecond components,3 here super lazy incorrect way import datetime unicodedatetimedatetimenow u,i adding utc time strings bitbucket api responses currently contain amsterdam time strings for consistency utc time strings returned elsewhere desired format followed germane what best way create string without microsecond component datetime instance microsecond component import datetime print unicodedatetimedatetimenow i add best option occurred possible answer may well elegant solution edit i mention i actually printing current time – i used datetimenow provide quick example so solution assume datetime instances receives include microsecond components,3 changegroup hook called per push if want analyse changeset want incoming hook input hook afaik — called changeset id hgnode environment variable you get commit message eg hg log r hgnode template desc via api,i would like write hook mercurial following struggling get going run central repo execute changesets pushed i think i use input changegroup hook search commit message string format issue if string found call webservice provide issue number commit message list files changed so starters i get commit message commit input changegroup hook any advice beyond achieve points would also appeciated thanks help,1 this asked answered can i use http basic authentication django the answer yes see httpdocsdjangoprojectcomendevhowtoauthremoteuser details,one system components using basic http authrozation httpenwikipediaorgwikibasicaccessauthentication log information another part system running django application uses djangocontribauth app authentication would code like work def urlhandlerrequest requestuserisauthenticated the urlhandler case would handle request authorization basic dxnlcjpwyxnz appended http get would django authorization backend integrate obviously i tried code seem work is middleware would work case thanks,1 probably behavior direct conversion counterintuitive know implementation details floats as stated docs note decimalfromfloat decimal since exactly representable binary floating point value stored nearest representable value xap that equivalent value decimal if convert string control precision want use get accurate conversion decimal the new method introduced python new features backported older versions,direct conversion float decimal implemented python decimal constructor decimalfromfloat classmethod python instead throws typeerror suggesting convert string first typeerror cannot convert float decimal first convert float string usual workaround sysversioninfo decimalfromfloat classmethodlambda cls x clsstrx that literary translation error message i bother implementing constructor if simple implement first place instead telling user typeerror is best method available extension one used python newer,2 you want use incoming hook called changeset applied repository either via pull push unbundle in calling script current changeset id accessible hgnode environment variable python access osenviron hgnode depending want look provided bugzilla hook starting point,i would like write hook mercurial following struggling get going run central repo execute changesets pushed i think i use input changegroup hook search commit message string format issue if string found call webservice provide issue number commit message list files changed so starters i get commit message commit input changegroup hook any advice beyond achieve points would also appeciated thanks help,1 since datetimedatetime instances microsecond component ie zero partition string take first item always work unicodedatetimedatetimenowpartition,i adding utc time strings bitbucket api responses currently contain amsterdam time strings for consistency utc time strings returned elsewhere desired format followed germane what best way create string without microsecond component datetime instance microsecond component import datetime print unicodedatetimedatetimenow i add best option occurred possible answer may well elegant solution edit i mention i actually printing current time – i used datetimenow provide quick example so solution assume datetime instances receives include microsecond components,3 the method execute returns long integer rows affected to get value fname need fetch results using example fetchall fetchone cursorexecuteselect fname employees where user useruname row cursorfetchone print row,i trying get single cell values mysqldb python here code fname cexecuteselect fname employees where user useruname however i get l i want fname contain string long integer why would,3 your workaround rightwaytodoittm loses information the lossless way convert shown recipe floattodecimal shown decimal faq the reason include decimalfromfloat python conservative introducing unintentional interactions binary floats decimal floats by python worked write decimalf f binary float other small nuisance i hope enjoying decimal module,direct conversion float decimal implemented python decimal constructor decimalfromfloat classmethod python instead throws typeerror suggesting convert string first typeerror cannot convert float decimal first convert float string usual workaround sysversioninfo decimalfromfloat classmethodlambda cls x clsstrx that literary translation error message i bother implementing constructor if simple implement first place instead telling user typeerror is best method available extension one used python newer,3 you using operator rather use simple constructing tuple instead fields fname lname email deptid deptid active active sentient sentient fname lname email anyway seems like trying generate json output in case look json module,i trying put information available web i using string formatting fields fname lname email deptid deptid active active sentient sentient fname lname email various values three variables anyway i try view fields still shows how i actually make replace,1 fields fname lname email deptid deptid active active sentient sentient fname lname email quite simply replace comma constructs tuple operator string formatting also i would recommend replacing triple quotes single quotes although wrong way i find readable way fields fname lname email deptid deptid active active sentient sentient fname lname email,i trying put information available web i using string formatting fields fname lname email deptid deptid active active sentient sentient fname lname email various values three variables anyway i try view fields still shows how i actually make replace,1 you need use operator bind list variables string like here string you got comma string list variables really get anything,i trying put information available web i using string formatting fields fname lname email deptid deptid active active sentient sentient fname lname email various values three variables anyway i try view fields still shows how i actually make replace,1 the character looking fields fname lname email deptid deptid active active sentient sentient fname lname email,i trying put information available web i using string formatting fields fname lname email deptid deptid active active sentient sentient fname lname email various values three variables anyway i try view fields still shows how i actually make replace,1 edit i asked wxpython irc channel fellow named rz came following edit code worked windows import wx class mypanelwxpanel def initself parent constructor wxpanelinitself parent selfbindwxevtpaint selfonpaint def onpaintself event pdc wxpaintdcself try dc wxgcdcpdc except dc pdc w h selfgetsizetuple w w h h dcclear dcdrawrectanglex widthw heighth def onsizeevent eventeventobjectrefresh eventskip name main app wxappfalse frame wxframenone titletest panel mypanelframe framebindwxevtsize onsize frameshow appmainloop alternately might look wxstaticbox widget edit you could also set frame style like skip whole onsize business frame wxframenone titletest stylewxdefaultframestylewxfullrepaintonresize,i trying make windows canvas type rectangle image issues understanding mean is way todo wxpython also way set automatically adjust window width px radius around window adjust users window size,2 use filter filterlambda obj objvalue b filter return list objects meet requirement specify docs httpdocspythonorglibraryfunctionshtmlfilter bascially filterfn list iterates list applies fn item it collects items fn returns true puts list returns nb filter always return list even one object matches so wanted return first instance matches something like def findinstancefn objs allmatches filterfn objs lenallmatches return false matches else return allmatches better yet def findinstancefn objs allmatches filterfn objs return lenallmatches allmatches uses fact returns second argument first argument evaluates true then would call function like instance findinstancelambda x xvalue b instance would,i sure term i looking good reason i trying fact silly but anyway i wondering whether quasi builtin way finding certain class instance property set certain value an example class klassobject def initself value selfvalue value def squarevalueself return selfvalue selfvalue klass b klass instance findinstancea b value instancesquarevalue instance findinstancea b value instancesquarevalue i know i could write function loops klass instances returns ones requested values on hand functionality feels exist within python already must good reasons in words i trying done much better way and course i looking way square value the example construct i trying look,2 you need reimplement qtreewidgetmimetypes returns list types want support def mimetypesself return qtcoreqstringlist texturilist applicationxqabstractitemmodeldatalist,i guess implementation quite qtreewidget i like able drop external file particularly image movie file qtreewidget i trying drag specific qtreewidgetitem rather tree whole here code class motreeqtreewidget def initself parent supermotree selfinitparent selfsetmousetrackingtrue selfsetacceptdropstrue def dragentereventself event eventmimedatahasurls eventaccept else eventignore def dropeventself event eventmimedatahasurls url eventmimedataurls handle stuff else eventignore the dragenterevent called dropevent i getting blocked icon any ideas,2 here regex solution import data john smith nchildren n samn kim match rematchr w w dchildren data res matchgroups john smith n samn kim you assign groups variables firstname lastname number matchgroups children cstrip c matchgroupstripsplit n result firstname john lastname smith number children sam kim,i file full data certain format i want fill data structure data example i file like john smith children sam kim i want something string order extract data example firstname john lastname smith number children sam kim i hope easier way using separators,2 a efficient version ord answer looking one matching instance would def findinstancefn objs allmatches objs fnobjs return nextallmatches none instance findinstancelambda x xvalue b this stop search soon find first match good test function expensive list large none matches note next function new python older version i think try return allmatchesnext except stopiteration return none of course could oneliner instance nexto b ovalue none the latter advantage bunch function calls might slightly faster though difference probably trivial,i sure term i looking good reason i trying fact silly but anyway i wondering whether quasi builtin way finding certain class instance property set certain value an example class klassobject def initself value selfvalue value def squarevalueself return selfvalue selfvalue klass b klass instance findinstancea b value instancesquarevalue instance findinstancea b value instancesquarevalue i know i could write function loops klass instances returns ones requested values on hand functionality feels exist within python already must good reasons in words i trying done much better way and course i looking way square value the example construct i trying look,1 you might find answers question helpful summary quick reference use modelforms based modelforms documentation save db use status field i think less ideal i might add documentation specifically explains deal mm fields section explains the save method of i recommend using modelforms hopefully helps,i system several steps each step increments one single object instance i want save instance db final step others update instance i saved session my model class seems like class propostamodelsmodel modelo modelsforeignkeymodeloversao verbosenamemodelo pacotes modelsmanytomanyfieldpacotemodelo nulltrue blanktrue opcionais modelsmanytomanyfielditemmodelo nulltrue blanktrue revestimentointerno modelsforeignkeyrevestimentointernomodelo verbosenamerevestimento interno cor modelsforeignkeycormodelo corsecundaria modelsforeignkeycormodelosecundaria verbosenamecor secundã¡ria nulltrue blanktrue data modelsdatetimefieldautonowadd true status modelscharfieldstatus choicesstatusproposta maxlength cliente modelsforeignkeycliente here problem when i try add retrieve mm fields obviously throws valueerror message proposta instance needs primary key value manytomany relationship used i successfully got wanted result creating obj instance pk i sure best way do exist way without cheating like any help would great thanks,1 the gae doc states deadline sec result urlfetchurldeadlinemethodurlfetchpost,i two instances app engine applications running i want communicate restful interface once data one updated calls web hook second retrieve fresh copy data system inside site googleappengineapi import urlfetch url wwwsitecomdataupdated result urlfetchfetchurl inside handler dataupdated site i url wwwsitecomgetnewdata result urlfetchfetchurl there little data passed two sites i receive following error i tried increasing deadline seconds still work deadlineexceedederror applicationerror can anyone provide insight might happening thanks richard,1 from documentation taskalias databasereset def databasereset,i like fabric tasks hyphens instead underscores for example databasereset instead databasereset however hyphens permitted python function names is possible fabric create tasks whose names exactly match corresponding python function,3 i used something like earlier it could bad code i experienced c coder worked the idea args python tuple anything could python tuple you check httpdocspythonorgcapituplehtml int parseargumentsunsigned long arrpyssizet size pyobject args get arbitrary number positive numbers pytuple pyssizet pyobject tempp tempp iisizei tempp pytuplegetitemargsi iftempp null return null check tempp numeric pynumberchecktempp pyerrsetstringpyexctypeerrornonnumeric argument return null convert number python long c unsigned long tempp pynumberlongtempp arri pylongasunsignedlongtempp pydecreftempp arri pyerrsetstringpyexcvalueerrorzero allowed argument return null pyerroccurred return null return i calling function like static pyobject functionnamewasherepyobject self pyobject args pyssizet tuplesize pytuplesizeargs pyssizet struct bigcouples temp mallocsizeofstruct bigcouples unsigned long current iftuplesize ifpyerroccurred pyerrsetstringpyexctypeerroryou must supply least one argument freetemp return null unsigned long nums malloctuplesize sizeofunsigned long ifparseargumentsnums tuplesize args make cleanup return null return null,i trying figure c extension modules variable maybe quite large number arguments function reading pyargparsetuple seems know many accept mandatory optional variable i hoping pyargunpacktuple would able handle seems give bus errors i try use appears wrong way as example take following python code one might want make extension module c def hypotvals lenvals return mathsqrtsumv v vals else return mathsqrtsumv v vals this called number arguments iterated hypot hypot hypot give answer the start c function looks like static pyobject hypottbpyobject self pyobject args lots code pyargparsetuple pyargunpacktuple many thinks yasar here next guy fully working extension module toolboxmodulec simply takes number integer arguments returns list made arguments poor name a toy illustrates needed done include pythonh int parseargumentslong arrpyssizet size pyobject args get arbitrary number positive numbers pytuple pyssizet pyobject tempp tempp iisizei tempp pytuplegetitemargsi iftempp null return null check tempp numeric pynumberchecktempp pyerrsetstringpyexctypeerrornonnumeric argument return null convert number python long c unsigned long tempp pynumberlongtempp arri pylongasunsignedlongtempp pydecreftempp return static pyobject hypottbpyobject self pyobject args pyssizet tuplesize pytuplesizeargs long nums malloctuplesize sizeofunsigned long pyobject listout int iftuplesize ifpyerroccurred pyerrsetstringpyexctypeerroryou must supply least one argument return null parseargumentsnums tuplesize args freenums return null listout pylistnewtuplesize foriituplesizei pylistsetitemlistout pyintfromlongnumsi freenums return pyobject listout static pymethoddef toolboxmethods hypot pycfunctionhypottb methvarargs add docs heren null terminate python looking object null null null pymodinitfunc inittoolboxvoid pyinitmoduletoolbox toolboxmethods toolbox module in python import toolbox toolboxhypotrange,3 the easiest way nest sizers so put sizer second sizer border want,selfsizeraddselflistbox proportion flagwxtop wxleft border border bottom left set border wxleft something else still apply item is something like wxleft wxtop if i use code set wxleft wxtop want i want set items different values if anyone knows answer would greatly appreciated i cannot use selfsizeraddselflistbox proportion flagwxleft border selfsizeraddselflistbox proportion flagwxtop border it return error,2 cat plus plus best solution want tangentially however technically possible python global variables function name global variable conform usual rules assigning globals dictionary def foobar print foobar globalsfoobar foobar globalsfoobar prints foobar the syntax nice though making quite hassle,i like fabric tasks hyphens instead underscores for example databasereset instead databasereset however hyphens permitted python function names is possible fabric create tasks whose names exactly match corresponding python function,1 absolutely if space path need put whole path double quotes,i line bat file cpythonpythonexe cmypythondirectorypy but fails giving error open file errno file directory could giving error space one folder names python directory,1 oh yes way print sorteddatakeylambda x x,i file reading creating nested lists want sort elementzipcode jk marfield laneplainviewny axe w th street apt bnew yorkny jab rivington street apt rnew yorkny ap boxer rdnew yorkny jb karas drjersey citynj jb xylon drjersey citynj ak main streetphiladelphiapa here code ex open extxt exw open exsortedtxt w data line ex items linerstripsplit dataappenditems print sorteddata keyoperatoritemgetter output jb karas dr jersey city nj jb xylon dr jersey city nj ak main street philadelphia pa jab rivington street apt r new york ny ap boxer rd new york ny jk marfield lane plainview ny axe w th street apt b new york ny works fine i wonder way without using import operator,2 a rough workalike would print sorteddata keylambda items items operatoritemgetter bit faster i using program benchmark approaches usrbinenv python import timeit withlambda lstsortkeylambda items items withgetter lstsortkeyoperatoritemgetter setup import random import operator randomseed lst randomrandrange randomrandrange randomrandrange randomrandrange randomrandrange range n print with lambda print timeittimeitwithlambda setup numbern print with getter print timeittimeitwithgetter setup numbern it creates random list item tuples runs sort list times on macbook pro python withlambda version runs withgetter runs note lists grow large time spent sorting algorithm grows faster time spent fetching keys therefore difference much greater sorting lots little lists running test item list repeated times yields withlambda vs withgetter,i file reading creating nested lists want sort elementzipcode jk marfield laneplainviewny axe w th street apt bnew yorkny jab rivington street apt rnew yorkny ap boxer rdnew yorkny jb karas drjersey citynj jb xylon drjersey citynj ak main streetphiladelphiapa here code ex open extxt exw open exsortedtxt w data line ex items linerstripsplit dataappenditems print sorteddata keyoperatoritemgetter output jb karas dr jersey city nj jb xylon dr jersey city nj ak main street philadelphia pa jab rivington street apt r new york ny ap boxer rd new york ny jk marfield lane plainview ny axe w th street apt b new york ny works fine i wonder way without using import operator,2 i recently found boat except i came mako background mustache allow template extensioninheritance options available i know you could use partials header hello name footer you could inject template preprocessing functions context template needs inherit page extendbase hello name extendbase hash name walden extendbase function return functiontext return htmlheadhead rendertext bodyhtml prepend append desired html relevant pages controller have layout template ala header body footer and render body controller passing layout template variable named body implement template inheritance premustache code loads templates i however use triple mustache i want unescaped html appearing anywhere risky opinion if someone else better solution problem i love hear well since i yet taken plunge one directions,i new mustache many templating languages eg django jinja let extend parent template like basehtml htmlheadhead body block content endblock body html frontpagehtml extends basehtml block content hfoobarh endblock rendered frontpagehtml htmlheadhead body hfoobarh body html i aware mustache partials eg content seem includes does template extension exist mustache or failing least design pattern effectively turns includes template extension equivalents,3 tried replicating error using clean install neoj flask jpipe using standard java default path could produce log but i got error traceback recent call last file stdin line module file teststackpy line initdb userindex dbnodeindexescreate users file usrlocallibpythondistpackagesneojindexpy line create return selfindexfornodesname tojavaconfig jpypejexceptionruntimeexceptionpyraisable javalangillegalargumentexception supplied index configuration match stored config valid way providerlucene typeexact users using initdb fixed userindex dbnodeindexescreateusers,i following flask tutorial flaskr order experiment using neojembedded python this virtualenv here main app code import os import jpype neoj import graphdatabase flask import flask request session g redirect urlfor abort rendertemplate flash app flaskname appconfigfrompyfileosenviron appsettings def connectdb return graphdatabaseappconfig database def initdb db connectdb dbtransaction users dbnode roles dbnode dbreferencenodeusersusers dbreferencenoderolesroles userindex dbnodeindexescreate users user dbnodenameappconfig admin userinstanceofusers userindex name appconfig admin user role dbnodetype superadmin roleinstanceofroles roleassigntouser dbshutdown print database initialized def testdb db connectdb dbtransaction userindex dbnodeindexesget users user userindex name appconfig admin single username user name dbshutdown print admin username database exists username appbeforerequest def beforerequest jpypeattachthreadtojvm gdb connectdb appteardownrequest def teardownrequestexception gdbshutdown approute def index gdbtransaction userindex gdbnodeindexesget users user userindex name appconfig admin single username user name fields dictusernameusername return rendertemplate indexhtml fieldsfields ospathexistsappconfig database false initdb else testdb initdb testdb work perfectly fine without gremlin pylucene etc jpype neojembedded initially jvm would fail app would terminate i would request index i scoured net learn i needed add line jpypeattachthreadtojvm beforerequest solve issue python threading jvm app terminate however leads immediately another issue traceback recent call last file htdevenvflasklibpythonsitepackagesflaskapppy line call return selfwsgiappenviron startresponse file htdevenvflasklibpythonsitepackagesflaskapppy line wsgiapp response selfmakeresponseselfhandleexceptione file htdevenvflasklibpythonsitepackagesflaskapppy line wsgiapp response selffulldispatchrequest file htdevenvflasklibpythonsitepackagesflaskapppy line fulldispatchrequest rv selfhandleuserexceptione file htdevenvflasklibpythonsitepackagesflaskapppy line fulldispatchrequest rv selfdispatchrequest file htdevenvflasklibpythonsitepackagesflaskapppy line dispatchrequest return selfviewfunctionsruleendpointreqviewargs file htdevappsevoboxevoboxinitpy line index userindex gdbnodeindexesget users file htdevenvflasklibpythonsitepackagesneojindexpy line get return selfindexfornodesname javalangruntimeexceptionpyraisable javalangillegalargumentexception no index provider lucene found maybe intended provider one dependencies classpath failed load google search entire last line go anywhere just searching javalangillegalargumentexception no index provider lucene found lead nothing context python the neoj messageslog seems show database opened times initdb testdb index the classpath instance class path htdevenvflasklocallibpythonsitepackagesneojjavalibneojjmxmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojluceneindexmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojgraphmatchingmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojkernelmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibgeronimojtaspecjarhtdevenvflasklocallibpythonsitepackagesneojjavaliblucenecorejarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojgraphalgomjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojudcmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojcyphermjarhtdevenvflasklocallibpythonsitepackagesneojjavalibscalalibraryjar i also modified index connectdb attachthreadtojvm directly like initdb testdb without using g global resulted exact error what i possibly missingoverlooking get neojembedded jpype working threaded request main app note i aware restful web service solutions pyneo rexsterbulbs i want avoid edit using jpype neojembeddedb javaopenjdk,2 just make sure single values contain delimiter char enclosed quotechar example thus time name field row form name itemdet row read something like name itemdet,i trying solve problem i reading data csv fiile following columns id name price so use following code read csv import sys import csv input def readfilepath try finput inputreaderopenpath rb delimiter quotechar except ioerror errnostrerror print io error formaterrnostrerror except print unexpected error sysexcinfo raise covert format list fmod listfinput return fmod problem name field like name itemdet creates trouble instead reading name field single entity comma description splits particular field how i solve thanks,1 csv exactly comma separated you either need quote name field nameitemdet or use escape character turn setting quoting quotenone reader csvreaderopenpath rb delimiter quotingcsvquotenone escapechar example nameitemdet otherwise use csv module,i trying solve problem i reading data csv fiile following columns id name price so use following code read csv import sys import csv input def readfilepath try finput inputreaderopenpath rb delimiter quotechar except ioerror errnostrerror print io error formaterrnostrerror except print unexpected error sysexcinfo raise covert format list fmod listfinput return fmod problem name field like name itemdet creates trouble instead reading name field single entity comma description splits particular field how i solve thanks,1 pytables files hdf files however i understand pytables adds extra metadata attributes entry hdf file if looking vanilla hdf solution pythonnumpy look hpy it less databaselike ie less tablelike pytables many nifty querying features much straightforward opinion if going accessing hdf file multiple different languages hpy probably better route take,is difference hdf files files created pytables pytables two functions ishdffile ispytablesfile suggesting difference two formats i done looking around google gathered pytables built top hdf i able find much beyond i specifically interested interoperability speed overhead thanks,3 plupload java backend support files size httpsgithubcomjakobadampluploadjavaruntime you need port uploading portion django it would something like although checksum verification def fileuploadrequest file upload plupload requestmethod post name requestrequestget name uploadedfile requestfiles file name name uploadedfilename nameext ospathsplitextname check see user uploaded file make upload directory uploaddir resultsreferencelibrarytemp ospathexistsuploaddir return rendertojsonerrorupload path exist destpath ssss uploaddirossepnameext chunk requestrequestget chunk chunks requestrequestget chunks mdchunk requestrequestget mdchunk false mdtotal requestrequestget mdtotal false debug chunk chunks mdchunk mdtotal opendestpath wb chunk else ab f content uploadedfilechunks fwritecontent intchunk intchunks upload finished pass return rendertojsonchuck posteddebug else return rendertojsonmethodonly post,we looking approach developing web based application facility upload large files size upto gb resume facility we want develop application using pythondjango caspnet any suggestion would appreciated,1 also type help python terminal gets page httpdocspythonorglibrarypydochtml,using windows xp python i tried run pydoc terminal unfortunately work since i allowed post screenshot newbie here says white black what i type cpythonpydoc rawinput pydoc rawinput my result it german roughly translates tothe command pydoc either spelled wrong found der befehl pydoc ist entweder falsch geschrieben oder konnte nicht gefunden werden what i wrong by way i started teach programming using zed shaws learn python hard way first issue i really figure using google i start believe windows broke afford mac scared learn linux,1 i used stringio practice two things to unittest script lot print ing redirecting sysstdout stringio instance easy analysis to create guaranteed wellformed xml document custom api request using elementtree write sending via http connection not need stringio often sometimes pretty useful,i pro i scratching head understanding exactly stringio used i looking around internet examples however almost examples abstract and show use but none show circumstances one shouldwill use thanks advance ps confused question stackoverflow stringio usage compares string stringio,3 p t u listsett q sump pt zippt u u u print q u,i two arrays p t pi number whose time stamp ti there might duplicated time stamps i want produce another two arrays q u qi time stamp ui qi sum elements p time stamp ui for example p t i produce q u is fast way numpy hopefully vectorizes,1 import numpy np p nparray t nparray u npuniquet q nparraypt usum u u gives in print q u not really vectorized faster solution lists if want powerful kind groupby functions maybe take look pandas,i two arrays p t pi number whose time stamp ti there might duplicated time stamps i want produce another two arrays q u qi time stamp ui qi sum elements p time stamp ui for example p t i produce q u is fast way numpy hopefully vectorizes,1 count number num count numnum count printhe payed num pounds a comments using number code best remove unused variables presence easily distract real flow code second starting num actually going come number grains cereal th square biggerthanusual board there neat algebraic trick available though n n so instead compute get number grains cereal asked note i given answer usual mathematical notation python notation something different python use instead exponentiation then divide number get pounds question ultimately wanted of course whole point exercise teach looping algebraic equality going purpose exercise sorts equalities important part programming,hello i program question bellow code however read question understand i need code also add previous numbers if someone could see code tell already i could go i tried something work answer kept coming the question as know inventor game chess quite clever fellow as story goes inventor presented game king king quite pleased the king asked inventor wanted payment he asked grain cereal first square next squares double previous square as story goes king agrees pleased final payment create program computes much grain king pay express answer pounds assume grains pound my code count number num count num num count print he payed num pounds,1 filenext filenext way,i trying figure way skip next two lines file condition first line true any ideas good way here i far def main file openr cuserstestdesktoptesttxt r ctr currentline file assert ctr currentline striu pass else ctr currentline str something ctr elif ctr currentline str pass i want skip next two lines loop elif ctr something ctr else raise valueerror,1 in python use nextfile nextfile skip two items iterator file ie next two lines,i trying figure way skip next two lines file condition first line true any ideas good way here i far def main file openr cuserstestdesktoptesttxt r ctr currentline file assert ctr currentline striu pass else ctr currentline str something ctr elif ctr currentline str pass i want skip next two lines loop elif ctr something ctr else raise valueerror,1 using numpy better import numpy np p nparray t nparray uinverse npuniquetreturninversetrue q npbincountinverseweightsp print q u array array please note fastest solution i tested speed way import numpy np n p nprepeatnparray n t nprepeatnparray n def usingbincount uinverse npuniquetreturninversetrue q npbincountinverseweightsp return qu array array def usinglc u listsett q sump pt zippt u u u return qu def usingslice u npuniquet q nparraypt usum u u return qu for small arrays wim solution faster n python mtimeit import test testusinglc loops best usec per loop python mtimeit import test testusingslice loops best usec per loop python mtimeit import test testusingbincount loops best usec per loop for large arrays joris solution faster n python mtimeit import test testusinglc loops best msec per loop python mtimeit import test testusingslice loops best usec per loop python mtimeit import test testusingbincount loops best usec per loop i doubt matters case benchmarks change depending version numpy python os hardware it would hurt repeat benchmarks machine,i two arrays p t pi number whose time stamp ti there might duplicated time stamps i want produce another two arrays q u qi time stamp ui qi sum elements p time stamp ui for example p t i produce q u is fast way numpy hopefully vectorizes,2 every number divisible a prime number natural number positive divisors therefore start forloop every number x pass condition x first iteration returning false to fix need start loop instead also sidenote need loop sqrtx since exists number q sqrtx divides x must also number p x q also divides x p sqrtx,i wrote function calculate whether number prime try might seems unable give correct response it also prints n value incremented here code function python way def isprimex n range x print n x n return false return true if i input isprime function returns false what going wrong,3 itertools module provides recipe need itertools import iziplongest def groupern iterable fillvaluenone grouper abcdefg x abc def gxx args iteriterable n return iziplongestfillvaluefillvalue args which looks like corpus listgrouper corpus print nn join n joingroup group grouper mapstr corpus,pretty easy question from code data made column numbers let say numbers see def blockgenerator open test r lines data linesreadlines line data linestartswith actually gives column numbers block get blocks lines yield block print line how i create blocks four numbers for example i need process blocks thanks reading,1 done categoryrow cursorfetchone print categoryrow categoryrow done true continue categoryresultsappendcategoryrow clto continue wrap point categoryrow going none then categoryrow clto encountered boom you probably want following want capture rows done categoryrow cursorfetchone print categoryrow categoryrow done true continue categoryresultsappendcategoryrow clto,based couple api calls i constructed following data structure dictionary i used python dictionary holding place a b a c d b k m z j f e i take value send query database get results set select something sometable sometablesomecol a then i trying save data another dictionary use future this error i currently trying deal clto column name query focusing traceback recent call last file categorypy line module categoryresultsappendcategoryrow clto typeerror nonetype object subscriptable clto epplateretterxcxar clto musikki none this code looks like dictionary save initial category rest clto basecategorytree categoryresults query get categories category linked categoryquery select clto sometable cl left join anothertable p clclfrom panothercolumn psomecolumn panothercolumn cursor dbcursorcursorsssdictcursor key value idtitledictionaryiteritems startcategory value print startcategory end query try basecategorytreestartcategory print categoryquery startcategory cursorexecutecategoryquery startcategory done false done categoryrow cursorfetchone print categoryrow categoryrow done true continue categoryresultsappendcategoryrow clto basecategorytreestartcategoryappendcategoryresults except exception e tracebackprintexc best nh,1 you might replace list bytearray assuming keep one bit information per voxel store voxels per byte you may also try ndarray numpy you efficiently construct ã—ã— array takes less space faster access manipulate normal python data structure certain ways,at moment i storing voxels simple list to retrieve voxel positon list i use function def getblockkeyself x z blockx x cfgchunksize blocky cfgchunksize blockz z cfgchunksize return blockx blocky cfgchunksize blockz cfgchunksize cfgchunksize but slow handling big amounts data for example iterating cube chunk takes seconds i guess faster use dict uses way much memory could help find compromise two,2 i know pygame perhaps want something like distance sqrtmousepositionx theballx mousepositiony thebally this standard distance formula get distance mouse position center ball then want return distance circleradius also sqrt work need go math import sqrt note could something like xgood mousepositionx rangetheballx theballx ygood mousepositiony rangethebally thebally return xgood ygood along lines written gives allowable area square to get circle need calculate distance shown nb my answer assumes mouseposition properties x i know actually true i know pygame i mentioned,i working project within python determine multitasking efficiency person part project user respond event screen using mouse i decided user click within ball however i issues code verifying mouse cursor actually within confines circle the code methods question radius circle boolean method determine cursor within position circle classmethod def isvalidmouseclickpositioncls theball mouseposition return mouseposition rangetheballx theballx rangethebally thebally method called pygameeventmousebuttondown detected def handlemouseclickself print ballisvalidmouseclickpositionselftheballpygamemousegetpos no matter i click within circle boolean still returns false,3 you using determine mouseposition within expression computing allowable positions range range range range false,i working project within python determine multitasking efficiency person part project user respond event screen using mouse i decided user click within ball however i issues code verifying mouse cursor actually within confines circle the code methods question radius circle boolean method determine cursor within position circle classmethod def isvalidmouseclickpositioncls theball mouseposition return mouseposition rangetheballx theballx rangethebally thebally method called pygameeventmousebuttondown detected def handlemouseclickself print ballisvalidmouseclickpositionselftheballpygamemousegetpos no matter i click within circle boolean still returns false,1 i think meant categoryresultsappendcategoryrow clto loop now looping categoryrow none try append get obvious error by way get rid end lines this python cc required want two statements single line like dosomething dosomeotherthing but generally bad thing readability use separate lines instead dosomething dosomeotherthing,based couple api calls i constructed following data structure dictionary i used python dictionary holding place a b a c d b k m z j f e i take value send query database get results set select something sometable sometablesomecol a then i trying save data another dictionary use future this error i currently trying deal clto column name query focusing traceback recent call last file categorypy line module categoryresultsappendcategoryrow clto typeerror nonetype object subscriptable clto epplateretterxcxar clto musikki none this code looks like dictionary save initial category rest clto basecategorytree categoryresults query get categories category linked categoryquery select clto sometable cl left join anothertable p clclfrom panothercolumn psomecolumn panothercolumn cursor dbcursorcursorsssdictcursor key value idtitledictionaryiteritems startcategory value print startcategory end query try basecategorytreestartcategory print categoryquery startcategory cursorexecutecategoryquery startcategory done false done categoryrow cursorfetchone print categoryrow categoryrow done true continue categoryresultsappendcategoryrow clto basecategorytreestartcategoryappendcategoryresults except exception e tracebackprintexc best nh,1 disclaimer i also know pygame i assume mouseposition xy coordinates mouse pointer x integers comparing list returned range this comparing whether lists,i working project within python determine multitasking efficiency person part project user respond event screen using mouse i decided user click within ball however i issues code verifying mouse cursor actually within confines circle the code methods question radius circle boolean method determine cursor within position circle classmethod def isvalidmouseclickpositioncls theball mouseposition return mouseposition rangetheballx theballx rangethebally thebally method called pygameeventmousebuttondown detected def handlemouseclickself print ballisvalidmouseclickpositionselftheballpygamemousegetpos no matter i click within circle boolean still returns false,1 crud manages insertsupdates internally use formaccepts you two options use sqlform formsqlformdbletter formacceptsrequestvars session tax floatpostageformvarstaxtypereplace i talking use crud events def myfunctionform stuff called form accepted def myotherfunctionform formerrors something case errors called form validation crudsettingscreateonvalidation myotherfunction crudsettingscreateonaccept myfunction crudcreateonaccept lambda form myfunctionform define events creation form formcrudcreatedbletter note sqlform bit different crud sqlform expects validate form formaccepts method crud internally uses events onvalidation onaccept custom validations,so worte function webpy create record table database condition webpy create record allthough condition filled function def buyproduct price pricesetdbauth product balance limitdbauth settings accountbalance balance none balance price formredirecturl order else formcrudcreatedbletter formacceptsrequestvars session tax floatpostageformvarstaxtypereplace i talking balance price tax responseflash you enough balance buy product redirecturl notprocessed else function updatefielddbauth settings accountbalance price responseflash done redirecturl products pass elif formerrors responseflash error else pass else formredirecturl settings return dictformform sepposed balance price tax user redirected notprocessed without creating new record database webpy redirect user notprocessed create record without executing part entered information user user see bought something processed see function updatefielddbauth settings accountbalance price responseflash done redirecturl products pass idea thank,2 inside loop near top refresh list rowdata otherwise adding one forever something like rowdata right print def createdatalists symbol symbols opensymbol csv r f print symbol rowdata reader csvreaderf readernext row reader rowdataappendrow databysymbolappendrowdata edit got rid really using,i lot csv files directory i like open loop within python first csv read list second csv read list unfortunately code loops csv files puts csv files list how i modify code i achieve goal many thanks john here code def createdatalists symbol symbols opensymbolsi csv r f print reader csvreaderf readernext row reader rowdataappendrow databysymbolappendrowdata ii,3 store readers list listofcsvfiles f filenames listofcsvfilesappendcsvdictreaderopenf this store reader list allowing later something row listofcsvfiles processing row the biggest advantage method taht stuff like filter columns easily using methods onerow rowname column heading row listofcsvfiles tworows rowname col rowname col row listofcsvfiles i suspect would helpful program storing preread thus destructured csv files really want csv files read stored list need list lists i recommend memory intensive listofcsvfiles f filenames listofcsvfilesappendrowvalues row csvdictreaderopenf,i lot csv files directory i like open loop within python first csv read list second csv read list unfortunately code loops csv files puts csv files list how i modify code i achieve goal many thanks john here code def createdatalists symbol symbols opensymbolsi csv r f print reader csvreaderf readernext row reader rowdataappendrow databysymbolappendrowdata ii,3 you probably want use python standard datetime stuff httpdocspythonorglibrarytimehtmltimestrptime httpmailpythonorgpipermailtutormarchhtml,i python newbie my script contains function named fnregexrawdatestring intended convert raw date string like mon oct pm date string like octpm question no when raw date string contains extraneous characters eg xxxxxmon oct pmyyyyyy i modify regular expression routine exclude extraneous characters i tempted remove comments script make simpler read i thought might helpful leave script question no i suspect i code another function replace oct octpm but i help wondering way include functionality fnregexrawdatestring function any help would much appreciated thank marceepoo import sys import pdb pdbsettrace def fngetdatestringsysarg thisscriptzfullname sysargv try datestringraw sysargv except exception e except exception datestringrawerror thisscriptzfullname sysargv error no command line argument supplied print datestringrawerror returnval thisscriptzfullname n datestringraw returnval datestringraw return returnval def fnregexrawdatestringdatestringraw do replacements pdatavbpythonmarcsprgspythonitworksfixcodefromlegislaturezcalifcodemikezcodepy see also fnmatch pdatavbpythonmarcsprgspythonitworksbookmarkpdfsaabpy srchstring rsunmontuewedthufrisat janfebmaraprmayjunjulaugsepoctnovdec dd apm srchstring rsunmontuewedthufrisat janfebmaraprmayjunjulaugsepoctnovdec dd apm srchstring recompilesrchstring replacement rm replacement rm regexrawdatestring srchstringsubreplacement datestringraw return regexrawdatestring mon oct pm name main try thisscriptzfullname sysargv datestringraw fngetdatestringsysarg datestringmbh fnregexrawdatestringdatestringraw print datestringmbh except print error occurred fngetdatestringsysarg,1 apparently case matters wordnet also use porterstemmer wnllemmatize americans american nltkstem import porterstemmer ps psstem americans american,ran following nltk import wordnetlemmatizer wnl wnllemmatizeamerican wnllemmatizeamericans both simply return argument i would like americans reduce american anybody idea make happen i assumed i modify whatever internal dictionary lemmatizer using is correct anybody know better way thanks,2 you monitoring hover events mysvg adding another qgraphicssvgitem view instance mysvgimage mysvg your mysvg even view try like usrbinpython import sys pyqtqtgui import pyqtqtcore import pyqtqtsvg import class mainqwidget def initself supermain selfinit hbox qhboxlayout selfsetlayouthbox selfview myviewself selfscene qgraphicsscene selfviewsetsceneselfscene hboxaddwidgetselfview class myviewqgraphicsview def initself parent supermyview selfinitparent selfparent parent def mousepresseventself event supermyview selfmousepresseventevent test mysvg selfparentsceneadditemtest class mysvgqgraphicssvgitem def initself supermysvg selfinit ubuntusvg selfsetflagsqgraphicsitemitemisselectable qgraphicsitemitemismovable selfsetacceptshovereventstrue def hoverentereventself event print enter def hoverleaveeventself event print leave def hovermoveeventself event print moving def runmain app qapplicationsysargv ex main exshow sysexitappexec name main runmain,i working time i figure i wrong i hope someone help i trying get hover events work i mouse svg item qgraphicsscene here code i playing usrbinpython import sys pyqtqtgui import pyqtqtcore import pyqtqtsvg import class mainqwidget def initself supermain selfinit hbox qhboxlayout selfsetlayouthbox selfview myviewself selfscene qgraphicsscene selfviewsetsceneselfscene hboxaddwidgetselfview class myviewqgraphicsview def initself parent supermyview selfinitparent selfparent parent def mousepresseventself event supermyview selfmousepresseventevent test mysvg selfparentsceneadditemtestimage class mysvgqgraphicssvgitem def initself supermysvg selfinit selfimage qgraphicssvgitem ubuntusvg selfimagesetflagsqgraphicsitemitemisselectable qgraphicsitemitemismovable selfsetacceptshovereventstrue def hoverentereventself event print enter def hoverleaveeventself event print leave def hovermoveeventself event print moving def runmain app qapplicationsysargv ex main exshow sysexitappexec name main runmain hope someone help,2 short answer yes class personobject def initself selffirstname will selfsecondname awesome myguy person myguygender male printmyguygender print male,for example object two attributes person object example first name second name is possible make gender attribute fly thanks,3 i dynamic site uses technology place we use dojo principles like posters said form needs onsubmitreturn false attribute form object submits page reloaded on server side use redirect reply json xml whatever tell response handler jquery dojo etc next most time process post form xhrpost call do work server return jsonxmltext handle return value javascript determine a concrete example something like user submits patient vitals server validates returns successvitals received errorinvalid number the javascript xhr callback handler determines next close dialog refresh form new entry call attention missing field edit link python web frameworks link link basic tutorial return json django jquery link one note when using json technically longer ajax x stands xml,any way submit form without refreshing current page using python jquery ajax i want end results similar facebook comment works i currently using jquery form ajax however give user experience i want after submitting using jquery form url address bar refreshed form i submitted it refresh page i like especially let say i bottom page scrolled maximum after submitting form refreshed page focus redirected top page i hope i made point clear i want i need something like facebook comment system works someone commented comment submitted without refresh page edit jquery code reviewsubmit submitfunction var options thisajaxsubmitoptions return false namesubmitreviewbtn clickfunction reviewsubmit submit so python code handle submit need redirect page server side code redirect page url mainurlcom with jquery codes shown results the url appeared address bar mainurlcom formactionurl this form action i set submit form page redirected page i set server side i confused ajax experience,1 in case even know attribute called write code myguy person attr secrethabit could read file keybrd etc value wont tell setattr myguy attr value printmyguysecrethabit get wont tell,for example object two attributes person object example first name second name is possible make gender attribute fly thanks,1 no the problem one module main therefore one main stanza run there nothing wrong code though except import monkeyreporter probably mean import reporter and accessing via reports change anything still class,i two files one performs step automated test second stores emails test results both files kicked using hudson server i need first module share information second i access static variables reporter module initial values none i cut files bare minimum order focus getting data sharing work file one usrbinpython reports import reporter import time class flashdevice def beginflashing self reporterflashstarttime timetime name main flasher flashdevice flasherbeginflashing the second file reporting file defined something like code usrbinpython class reporter flashstarttime none def reportresults self print flash start time reporterflashstarttime name main reporter reporter reporterreportresults what i hoping i execute flasherpy updates static variable flashstarttime access updated value executing reporterpy will work i make method beginflashing static,1 look docstring feature swig python probably putting following line file featureautodoc would want see httpwwwswigorgdocpythonhtmlpythonnn options,using swig generate python interface c application way comment functions generated py file i actually pulling entire h file file small example module example bool dosomethinginterestingint number string text swig python examplei generates def dosomethinginterestingargs return exampledosomethinginterestingargs dosomethinginteresting exampledosomethinginteresting ideally i would like automatically add comment original method signature bool dosomethinginterestingint number string text def dosomethinginterestingargs return exampledosomethinginterestingargs dosomethinginteresting exampledosomethinginteresting but i would perfectly amenable writing comment somewhere particularly comment could somehow h file i thought pythonprepend might possible solution inserts code inside function definition rather edit here i came h file not prettiest thing ever ifdef swig pythonprepend dosomethinginterestingint string do interesting thing numberint number textstring text endif bool dosomethinginterestingint number string text,2 mustache template extension if really want template extension may want use library purpose built functionality languageframework choice fyi i using nodejsexpress i probably end using httpsgithubcomfatstache,i new mustache many templating languages eg django jinja let extend parent template like basehtml htmlheadhead body block content endblock body html frontpagehtml extends basehtml block content hfoobarh endblock rendered frontpagehtml htmlheadhead body hfoobarh body html i aware mustache partials eg content seem includes does template extension exist mustache or failing least design pattern effectively turns includes template extension equivalents,2 from email docs you pass parser string file object parser return root message instance object structure for simple nonmime messages payload root object likely string containing text message for mime messages root object return true ismultipart method subparts accessed via getpayload walk methods so use getpayload message multipart call walk method use getpayload desirable subpart,hi everyone i using script involves import oauth oauth import oauthclientsimap imaplib import email conn imaplibimapssl imapgooglemailcom conndebug this thing api impaplibimapssl changed you authenticate url consumer token connauthenticateurl consumer token once authenticated everything impalibimapssl class work per usual without modification code connselect gmailall mail response itemids connsearchnone since jan itemids itemidssplit now iterate shit retrieve email parsing storing whatever db emailid itemids resp data connfetchemailid rfc emailbody data mail emailmessagefromstringemailbody my current problem i seem able retrieve body mail instance i able see content email printing mailasstring even mailkeys mailvalues actually unable see mail content main message what wrong email lib api rather i wrong,2 it way importing task example you importing task project instead app chorusprocessorstopics tasks instead processorstopicstasks this creates problems celery since name different client server here docs relate following issue,running script django shell import processorstopicstasks ttestdelay gives error notregistered processorstopicstaskstest the weird thing chorusprocessorstopicstaskstest definitely included tasks printout i run python celeryd verbosity loglevelinfo purge why i getting error,1 the problem calling repr list create single string list what wanting something like f open outputtxt fwrite n joinfieldnames fclose the write method automatically create newlines join list strings together using newline appropriate platform n you read file objects python documentation also i recommend using different variable file since file actually python function the code work aware potential surprises,how i make filewritereprfieldnames writes i input fieldnames import easygui multi enter box fieldnames situationexample waiting friend late thoughtsexample my friend bob always late emotionsexample mad amp stressed behaviorexample arguing family write file file open fieldnames testtxt filewritereprfieldnames fileclose makes file called fieldnames testtxt following text regardless i input fieldnnames situationexample waiting friend late thoughtsexample my friend bob always late emotionsexample mad amp stressed behaviorexample arguing family,1 first ought reread string interpolation the operator applicable string unicode objects object must precede usage so could def epts return good eptselfrequestget content applicable integers well different story,class guestbookwebapprequesthandler def postself selfresponseoutwrite hyou wroteh selfrequestget content i want pass selfrequestget content function and use function return old placei python newbie i triedbut failed need help this function i defined class def eptstr str str good return str and i call old place like eptselfrequestget content could anybody help wrong code,1 if i understand correctly may need use matplotlibtickerfixedlocator example puts labels data points last one import pylab plt matplotlibticker import fixedlocator matplotlibdates import dateformatter import numpy np datetime import datetime dates unequally spaced works exactly equally spaced dates dates pltdatenumdatetime nparray data data dates pltplotdatedatesdata ax pltgca axxaxissetmajorlocatorfixedlocatordates lendates reason needed get month displayed axxaxissetmajorformatterdateformatterym pltshow,i would like draw timeplot using matplotlibdates module from tutorial i know set regular interval date like following axxaxissetmajorlocatordaylocator axxaxissetmajorformatterdateformatterym axxaxissetminor however data months missing my xaxis date like jan feb may jul sep oct sep pattern formed how i deal situation,1 do want execute code jar open if open jar file format zip files use zipfile module manipulate example def showjarclassesjarfile prints class files jarfile zf zipfilezipfilejarfile r try lst zfinfolist zi lst fn zifilename fnendswith class printfn finally zfclose if want execute i prefer creating simple batchshell script execute java parameters like xmx environment settings required application,i trying open jar file python running problems i using import os ossystemrxfilejar appears open window shuts right away i know i missing simple command sure thanks help,2 you split regex pattern quoting segment no backslashes needed test recompile pfullpathdswarningsmember spmembernamespmembertypes classgroupnamespacespclassname sis documented selfmembertypes reignorecase you also use raw string flag r put segment see docs,is actually doable i long regex pattern rules hard understand fit screen example test recompile pfullpathdswarningsmemberspmembernamespmembertypes classgroupnamespacespclassnamesis documented selfmembertypes reignorecase backslash triple quotes work edit i ended using verbose here regexp pattern looks test recompile pfullpath capture group called fullpath it consists one characters type group ends a literal colon one numbers line number a literal colon swarningsparameterssofsmembers an almost static string pmembername capture group called membername match anything colon finding colon ends group match one characters group ends start unnamed group two literal colons pfunctionname start another group called functionname w it consists one alphanumeric characters end group this group entirely optional apply c saresnotsallsdocumented and line ends almost static string reignorecasereverbose let worry case seems differ doxygen versions,3 from httpdocspythonorgreferencelexicalanalysishtmlstringliteralconcatenation multiple adjacent string literals delimited whitespace possibly using different quoting conventions allowed meaning concatenation thus hello world equivalent helloworld this feature used reduce number backslashes needed split long strings conveniently across long lines even add comments parts strings example recompileazaz letter underscore azaz letter digit underscore note feature defined syntactical level implemented compile time the ‘’ operator must used concatenate string expressions run time also note literal concatenation use different quoting styles component even mixing raw strings triple quoted strings,is actually doable i long regex pattern rules hard understand fit screen example test recompile pfullpathdswarningsmemberspmembernamespmembertypes classgroupnamespacespclassnamesis documented selfmembertypes reignorecase backslash triple quotes work edit i ended using verbose here regexp pattern looks test recompile pfullpath capture group called fullpath it consists one characters type group ends a literal colon one numbers line number a literal colon swarningsparameterssofsmembers an almost static string pmembername capture group called membername match anything colon finding colon ends group match one characters group ends start unnamed group two literal colons pfunctionname start another group called functionname w it consists one alphanumeric characters end group this group entirely optional apply c saresnotsallsdocumented and line ends almost static string reignorecasereverbose let worry case seems differ doxygen versions,3 excel ole automation server built com means discoverable interface makes possible automate tool understands com providing windows python one many tools already easily obtain library need pythoncom see snippet example python script uses library talk excel it seem explicitly work charts need figure try using macro recorder get idea vba achieve want translate python if running windows going need code understands excel file format fairly achievable new xlsxxlsm xmlbased world available excel onwards rather difficult old binary xls form,i know python manipulate excel data i know whether generate charts does library exist,1 why want execute via python in windows environment jar file executed java cjrebinjavawexe jar of course os able change association open jar program on windows i use local menu open jar file java eclipse firefox i chose program,i jar file saved desktop way i ca get python pen i clicking link desk top i new python know dumb question would help alot,1 your code seems correct ie following simplified version correctly able get https front page google import httplib pprint import pprint conn httplibhttp resp content connrequesturihttpsencryptedgooglecom pprintresp cachecontrol private maxage contentlocation httpsencryptedgooglecom contenttype texthtml charsetiso date fri nov gmt expires server gws setcookie prefidefecdabfftmlmsaszhdpeqqxrsyow expiressun nov gmt path domaingooglecom nidrjxuwmiveqglvsnvlziitzvpmsxzbreyghwjvtkgrhsnsuxeyzajtbghsudqbqikgjesxkasstsvkmqrponbpnoelmnngenseoziuyh expiressat may gmt path domaingooglecom httponly status transferencoding chunked xframeoptions sameorigin xxssprotection modeblock so i guessing certificates causing remote server barf forcibly disconnect session do control server logs diagnostics server actually looking closer i trying understand addcertificate call why specify particular ip address domain certificate is server key actually representing ip address have tried empty string,i using httplib opening ssl connection following code import httplib name main conn httplibhttpdisablesslcertificatevalidationtrue connaddcertificate serverkeypem servercertpem resp content connrequesturi httpsxxxxxxxxxxxxxxxxkonfigurator restloginusernamexxxamppassxxx method post print resp error i getting traceback recent call last file ceclipseworkspacerestsrcexamplespy line module resp content connrequesturi httpsxxxxxxxxxxxxxxxkonfiguratorrestloginusernamexxxamppassxxx method post file cpythonlibsitepackageshttplibpyegghttplibinitpy line request response content selfrequestconn authority uri requesturi method body headers redirections cachekey file cpythonlibsitepackageshttplibpyegghttplibinitpy line request response content selfconnrequestconn requesturi method body headers file cpythonlibsitepackageshttplibpyegghttplibinitpy line connrequest connconnect file cpythonlibsitepackageshttplibpyegghttplibinitpy line connect raise socketerror msg socketerror errno an existing connection forcibly closed remote host is code correct i missing something,1 one issue pattern run risk starting multiple databases pointed location lead problems what would want single instance database follows full lifecycle application why finding lucene provider harder question the index provider loaded using java service loader means jpype affect as long jvm start alright luceneindex implementation jar classpath work it may related threading somehow i currently writing fix automaitcally handle attachthreadtojvm calls i add test case make sure reading indexes separate thread works expected well the threading work currently kept updated mailing list thread httpneojcommunitydiscussionsnnabblecomneojpythonembeddingproblemswithshutdownandthreadstdhtml,i following flask tutorial flaskr order experiment using neojembedded python this virtualenv here main app code import os import jpype neoj import graphdatabase flask import flask request session g redirect urlfor abort rendertemplate flash app flaskname appconfigfrompyfileosenviron appsettings def connectdb return graphdatabaseappconfig database def initdb db connectdb dbtransaction users dbnode roles dbnode dbreferencenodeusersusers dbreferencenoderolesroles userindex dbnodeindexescreate users user dbnodenameappconfig admin userinstanceofusers userindex name appconfig admin user role dbnodetype superadmin roleinstanceofroles roleassigntouser dbshutdown print database initialized def testdb db connectdb dbtransaction userindex dbnodeindexesget users user userindex name appconfig admin single username user name dbshutdown print admin username database exists username appbeforerequest def beforerequest jpypeattachthreadtojvm gdb connectdb appteardownrequest def teardownrequestexception gdbshutdown approute def index gdbtransaction userindex gdbnodeindexesget users user userindex name appconfig admin single username user name fields dictusernameusername return rendertemplate indexhtml fieldsfields ospathexistsappconfig database false initdb else testdb initdb testdb work perfectly fine without gremlin pylucene etc jpype neojembedded initially jvm would fail app would terminate i would request index i scoured net learn i needed add line jpypeattachthreadtojvm beforerequest solve issue python threading jvm app terminate however leads immediately another issue traceback recent call last file htdevenvflasklibpythonsitepackagesflaskapppy line call return selfwsgiappenviron startresponse file htdevenvflasklibpythonsitepackagesflaskapppy line wsgiapp response selfmakeresponseselfhandleexceptione file htdevenvflasklibpythonsitepackagesflaskapppy line wsgiapp response selffulldispatchrequest file htdevenvflasklibpythonsitepackagesflaskapppy line fulldispatchrequest rv selfhandleuserexceptione file htdevenvflasklibpythonsitepackagesflaskapppy line fulldispatchrequest rv selfdispatchrequest file htdevenvflasklibpythonsitepackagesflaskapppy line dispatchrequest return selfviewfunctionsruleendpointreqviewargs file htdevappsevoboxevoboxinitpy line index userindex gdbnodeindexesget users file htdevenvflasklibpythonsitepackagesneojindexpy line get return selfindexfornodesname javalangruntimeexceptionpyraisable javalangillegalargumentexception no index provider lucene found maybe intended provider one dependencies classpath failed load google search entire last line go anywhere just searching javalangillegalargumentexception no index provider lucene found lead nothing context python the neoj messageslog seems show database opened times initdb testdb index the classpath instance class path htdevenvflasklocallibpythonsitepackagesneojjavalibneojjmxmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojluceneindexmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojgraphmatchingmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojkernelmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibgeronimojtaspecjarhtdevenvflasklocallibpythonsitepackagesneojjavaliblucenecorejarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojgraphalgomjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojudcmjarhtdevenvflasklocallibpythonsitepackagesneojjavalibneojcyphermjarhtdevenvflasklocallibpythonsitepackagesneojjavalibscalalibraryjar i also modified index connectdb attachthreadtojvm directly like initdb testdb without using g global resulted exact error what i possibly missingoverlooking get neojembedded jpype working threaded request main app note i aware restful web service solutions pyneo rexsterbulbs i want avoid edit using jpype neojembeddedb javaopenjdk,3 querydict objects implement file interface so could decode json simply standard json library import json parsedjson jsonloadrequestpost or get depends using,i problems python django framework i first attempted send javascript array straight django except pulled last value so i use jsonstringify sends json python at python looks like querydict u keyinterfacednsvalue u and i add values adds first u how i make loop eg key value dictionary display because seams json stored position one dictionary any ideas,1 turns i completely wrong the exception indeed thrown sqlalchemy and streamed stdout default modwsgi silently ignored far i tell to answer main question how see errors produced wsgi app it actually simple redirect logs stderr the thing need add following wsgi script import logging sys loggingbasicconfigstreamsysstderr now mundane logging config as i put anything place yet application but i guess application matures sophisticated logging config anyways bite but quick dirty debugging fine,i currently developing application based flask it runs fine spawning server manually using apprun i tried run modwsgi strangely i get error nothing logs i investigated bit findings inserting line like print sysstderr hello works expected the message shows error log when calling method without using template works fine no error using simple template works fine but soon i trigger database access inside template example looping query i get error my gut tells sqlalchemy emits error maybe logging config causes log discarded point application additionally testing i using sqlite this far i recall accessed one thread so modwsgi spawns threads may break app i bit loss breaks running behind modwsgi also seems swallow errors what i make errors bubble apache errorlog for reference code seen github permalink,3 according blog need latest development version rope ropemacs emacs ropecompletions defined,i installed rope seems work fine i get error i try run autocomplete symbol function definition void ropecompletions i figure life any suggestions look error would great,1 you use djangononrel using django appengine google introduction it seems trying use django application called appenginedjango resolved do installed how install,i absolutely new django development trying hands google app engine requirement company getting error trying managepy syncdb error no module named appenginedjango here files settingspy django settings blogproject project debug true templatedebug debug admins your name youremaildomaincom managers admins databases default engine djangodbbackends add postgresqlpsycopg postgresql mysql sqlite oracle name or path database file using sqlite user not used sqlite password not used sqlite host set empty string localhost not used sqlite port set empty string default not used sqlite local time zone installation choices found httpenwikipediaorgwikilistoftzzonesbyname although choices may available operating systems on unix systems value none cause django use timezone operating system if running windows environment must set system time zone timezone americachicago language code installation all choices found httpwwwinguycomunicodelanguageidentifiershtml languagecode enus siteid if set false django make optimizations load internationalization machinery usein true if set false django format dates numbers calendars according current locale useln true absolute filesystem path directory hold useruploaded files example homemediamedialawrencecom mediaroot url handles media served mediaroot make sure use trailing slash path component optional cases examples httpmedialawrencecom httpexamplecommedia mediaurl url prefix admin media css javascript images make sure use trailing slash examples httpfoocommedia media adminmediaprefix media make unique share anybody secretkey pnwetampibfxpampygfovegjgdzusgjdirdn list callables know import templates various sources templateloaders djangotemplateloadersfilesystemloader djangotemplateloadersappdirectoriesloader djangotemplateloaderseggsloader middlewareclasses djangomiddlewarecommoncommonmiddleware rooturlconf blogprojecturls templatedirs put strings like homehtmldjangotemplates cwwwdjangotemplates always use forward slashes even windows don forget use absolute paths relative paths installedapps appenginedjango blogprojectblogs uncomment next line enable admin djangocontribadmin uncomment next line enable admin documentation djangocontribadmindocs urlspy djangoconfurlsdefaults import urlpatterns patterns r blogprojectblogsviewsindex viewspy djangohttp import httpresponse httpresponseredirect blogspoll import models import bforms djangoshortcuts import rendertoresponse def rendertemplate payload payload recents modelspollallorder createdon fetch return rendertoresponsetemplate payload def indexrequest polls modelspollallorder createdon fetch payload dictpolls polls return render indexhtml payload def createrequest requestmethod get pollform bformspollform choiceforms range choiceformsappendbformschoiceformprefix fs requestmethod post pollform bformspollformrequestpost choiceform bformschoiceform pollformisvalid poll pollformsave choiceforms range choiceformsappendbformschoiceformpollpoll prefix fs datarequestpost form choiceforms formisvalid formsave return httpresponseredirectpollgetabsoluteurl payload dictpollformpollform choiceformschoiceforms return render createhtml payload def polldetailrequest pollkey poll modelspollgetpollkey choices modelschoiceallfilter poll poll requestmethod post choicekey requestpost value choice modelschoicegetchoicekey choicevotes choiceput return httpresponseredirect results payload dictpoll poll choices choices return render polldetailshtml payload def pollresultsrequest pollkey poll modelspollgetpollkey choices modelschoiceallfilter poll poll payload dictpoll poll choices choices return render pollresultshtml payload modelspy appenginedjangomodels import basemodel googleappengineext import db class polldbmodel question dbstringproperty createdon dbdatetimepropertyautonowadd createdby dbuserproperty def strself return selfquestion def getabsoluteurlself return polls selfkey class choicedbmodel poll dbreferencepropertypoll choice dbstringproperty votes dbintegerpropertydefault please help thanks,2 if reason import blogs appsmodels relationship field post using lazy relationship instead as far i understand designed specifically deal import loops like one experiencing it quite easy instead appsmodels import blogs class postmodelsmodel myblog modelsforeignkeyblogs use something like class postmodelsmodel myblog modelsforeignkeyappsblogs,in django project i following appsmodelspy post model appsmodelspy blogs model appsfunctionspy getblogs method the appsmodelspy file imports blogs model appsmodelspy the appsmodelspy file imports getblogs method appsfunctionspy the appsfunctionspy file import post model appsmodelspy i getting following error importerror cannot import name post traceback adminautodiscover file appsmodelspy appsmodels import blogs file appsmodelspy appsfunctions import getblogs file appsfunctionspy appsmodels import post i thought might adminautodiscover importing post model first import loop trying import although i tried changing appsmodels import post otherpost help any idea happening is loop,3 please add urlspy url like r ajaxrequest appviewsieventajax change documentreadyfunction postajaxrequest lat searchresultpointlat lng searchresultpointlng text searchresulttext functiondata alertdata viewspy app def ieventajaxrequest return httpresponseok,i read theme i understand wrong documentreadyfunction posttweetpy lat searchresultpointlat lng searchresultpointlng text searchresulttext functiondata alertdata the handler code import django def ieventajaxrequest requestisajax return httpresponseok the alert message import django def ieventajaxrequest requestisajax return httpresponseok instead ok wrong,1 building second example tarfile module documentation could extract contained subfolder contents something like tarfileopensampletar tar subdirandfiles tarinfo tarinfo targetmembers tarinfonamestartswithsubfolder tarextractallmemberssubdirandfiles this creates list subfolder contents uses recommended extractall method extract of course replace subfolder actual path relative root tar file subfolder want extract,i working project python i need extract subfolder tar archive files i tried use tar tarfileopentarfile tarextractdirname targetdir but work extract given subdirectory also exception thrown i beginner python also function work directories whats difference command tarextractfile,3 check localepaths setting this tuple orderspecific put path custompo first achieve effect edit additional link detailed information how django discovers translations,in django app usual djangopo locale file languages however i like create custom locale file called custompo is way i could django first check translation string custompo file exist check djangopo file thanks,2 pymongo insert method takes dictionary string the error seeing pymongo attempts assign objectid new record since yet one sending database i think error onreceive function unless pycurl converting json automatically likely giving raw string result twitter api you use json module decode string handle resulting type appropriately array iterate item determine whether needs saved ie whether already database issue insert elements new edit you also add safetrue keyword argument insert if error caught server side get exception pymongo help diagnose problem,i python noob working less hours i trying read twitter data store mongo database i getting following error traceback recent call last file twittestpy line onreceive dbpostsinsertdata file librarypythonsitepackagespymongopymacosxuniversaleggpymongocollectionpy line insert file librarypythonsitepackagespymongopymacosxuniversaleggpymongodatabasepy line fixincoming file librarypythonsitepackagespymongopymacosxuniversaleggpymongosonmanipulatorpy line transformincoming typeerror str object support item assignment traceback recent call last file twittestpy line module connperform my code simple import pycurl json import pymongo streamurl httpsstreamtwittercomstatusessamplejson user xxxxxxxx pass xxxxxxxx def ontweetdata tweet jsonloadsdata dbpostsinserttweet pymongo import connection connection connection db connectiontest conn pycurlcurl connsetoptpycurluserpwd ss user pass connsetoptpycurlurl streamurl connsetoptpycurlwritefunction ontweet connperform i sure very simple fix hope guys help thanks,1 def quitself selfrootdestroy add parentheses destroy call method when use commandselfrootdestroy pass method tkinterbutton without parentheses want tkinterbutton store method future calling call immediately button created but define quit method need call selfrootdestroy body method method called,import tkinter class app def initself selfroot tkintertk button tkinterbuttonselfroot text root quit commandselfquit buttonpack selfrootmainloop def quitself selfrootdestroy app app how i make quit function close window,3 as said delnan comment it surprise different python interpreters generate different random sequences the official documentation refers c implementation algorithm other python implementations may choose algorithms in fact lowest common denominator might distribution produced random sequences if depend pseudorandom sequences reproduced across python interpreters write pseudorandom number generator a linear feedback shift register may good start relatively easy understand,i generating test data using known random seed i want use data cpython jython i found data different i use jython vs cpython boiling simple test i see prng giving different results two implementations in jython jython release mar java hotspottm server vm sun microsystems inc java type help copyright credits license information import random randomseed randomrandom in cpython python default oct gcc linux type help copyright credits license information import random randomseed randomrandom the test data i generating reproducible within python implementation is way around maybe i need code prng,1 not clear code i give pointers read huge file python best method use iter amp yield def readinchunksfileobj chunksize lazy function read file piece piece default chunk size kb true data fileobjreadchunksize data break yield data f open bigfile chuck readinchunksf dosomethingchunk but since file line based might even better go line open myfile dosomethingline for sake completeness methods probably good reading large files in python common way read lines file following line open myfile r readlines dosomethingline when done however readlines function loads entire file memory runs a better approach large files use fileinput module follows import fileinput line fileinputinput myfile dosomethingline fileinputinput call reads lines sequentially keep memory read even simply since file python iterable,i want iterate line entire file one way reading entire file saving list going line interest this method uses lot memory i looking alternative my code far eachline fileinputinputinputfile dosomethingeachline eachlineagain fileinputinputinputfile dosomethingeachlineagain executing code gives error message device active any suggestions edit the purpose calculate pairwise string similarity meaning line file i want calculate levenshtein distance every line,3 from python documentation fileinput input this iterates lines files listed sysargv defaulting sysstdin list empty definition function fileinputfileinputfiles inplace backup mode openhook reading lines tells files list could something like eachline fileinputinputinputfile inputfile dosomethingeachline see information,i want iterate line entire file one way reading entire file saving list going line interest this method uses lot memory i looking alternative my code far eachline fileinputinputinputfile dosomethingeachline eachlineagain fileinputinputinputfile dosomethingeachlineagain executing code gives error message device active any suggestions edit the purpose calculate pairwise string similarity meaning line file i want calculate levenshtein distance every line,1 canonical way reading file python f openinputfile line f dostuffline fclose allocate full list it iterates lines,i want iterate line entire file one way reading entire file saving list going line interest this method uses lot memory i looking alternative my code far eachline fileinputinputinputfile dosomethingeachline eachlineagain fileinputinputinputfile dosomethingeachlineagain executing code gives error message device active any suggestions edit the purpose calculate pairwise string similarity meaning line file i want calculate levenshtein distance every line,3 your regex runs catastrophic backtracking nested quantifiers since regex requires string end fails example regex engine tries permutations string vain hope find matching combination that gets stuck to illustrate let assume abcd input regex see happens w matches a good matches yay ws matches bcd ok fails match characters left match ok let back one character fails match d hum let back ws matches bc repeated ws matches d fails match back fails match d back ws matches b repeated ws matches cd fails match back fails match d back how ws matches b repeated ws matches c repeated ws matches d no let try something else ws matches bc let stop see happens darn still match d ws matches b still luck match c hey whole group optional nope still match b ok i give now string three letters yours trying permutations would keep computer busy end days i suppose trying get strings beforeafter case use pattern rwws,i trying execute code import pattern rwws recompiled recompilepattern results recompiledsearch coprohorizon hor printresultsgroups but python respond the process takes cpu stop i tried python python identical results,3 looks like might something pattern i sure trying last expression the following code seems work import pattern rwws recompiled recompilepattern results recompiledsearch coprohorizon hor printresultsgroups,i trying execute code import pattern rwws recompiled recompilepattern results recompiledsearch coprohorizon hor printresultsgroups but python respond the process takes cpu stop i tried python python identical results,1 using example guy matplotlib import pyplot import numpy numpyarangeinte fig pyplotfigure ax figaddsubplot lines axplota line enumerateaxlines axlinespopi lineremove,how i remove line lines matplotlib axes way actually gets garbage collected releases memory back the code appears delete line never releases memory even explicit calls gccollect matplotlib import pyplot import numpy numpyarangeinte large easily see memory footprint system monitor fig pyplotfigure ax pyplotaddsubplot lines axplota uses additional mb memory i get memory back l lines lremove del l del lines releasing memory axcla release memory also wipes lines so way delete one line axes get memory back this potential solution also work,1 personally i use reverbose i like escape blank spaces i want put instead blank spaces required the symbols regex pattern precise relatively characters sequences must catched faster regex object acts i nearly never use to avoid reverbose already said test recompile pfullpath dswarningsmembers comment pmembername pmembertypes comment classgroupnamespace underlining something point pclassname vvv overlining something important sis documented selfmembertypes reignorecase pushing strings left gives lot space write comments but manner good pattern long possible write test recompile pfullpath dswarningsmembers comment pmembername pmembertypes selfmembertypes incorrect syntax classgroupnamespace underlining something point pclassname vvv overlining something important sis documented reignorecase case pattern long number lines part selfmembertypes end string pmembertypes applied big loose easiness reading pattern that i like use tuple write long pattern pat join pfullpath put comment see long comment dswarningsmembers pmembername pmembertypes selfmembertypes comment comment classgroupnamespace underlining something point pclassname vvv overlining something important sis documented this manner allows define pattern function def patx return join pfullpath put comment see long comment dswarningsmembers pmembername pmembertypes x comment comment classgroupnamespace underlining something point pclassname vvv overlining something important sis documented test recompilepatselfmembertypes reignorecase,is actually doable i long regex pattern rules hard understand fit screen example test recompile pfullpathdswarningsmemberspmembernamespmembertypes classgroupnamespacespclassnamesis documented selfmembertypes reignorecase backslash triple quotes work edit i ended using verbose here regexp pattern looks test recompile pfullpath capture group called fullpath it consists one characters type group ends a literal colon one numbers line number a literal colon swarningsparameterssofsmembers an almost static string pmembername capture group called membername match anything colon finding colon ends group match one characters group ends start unnamed group two literal colons pfunctionname start another group called functionname w it consists one alphanumeric characters end group this group entirely optional apply c saresnotsallsdocumented and line ends almost static string reignorecasereverbose let worry case seems differ doxygen versions,1 katrielalex provided way open amp read one file however way algorithm goes reads whole file line file that means overall amount reading file computing levenshtein distance done nn n amount lines file since concerned file size want keep memory i concerned resulting quadratic runtime your algorithm on class algorithms often improved specialization i suspect already know tradeoff memory versus runtime maybe would want investigate efficient way compute multiple levenshtein distances parallel if would interesting share solution how many lines files kind machine mem amp cpu power algorithm run tolerated runtime code would look like fouter openinputfile r lineouter fouter finner openinputfile r lineinner finner computedistancelineouter lineinner but questions store distances matrix gain advantage preparing eg outerline processing caching intermediate results reuse,i want iterate line entire file one way reading entire file saving list going line interest this method uses lot memory i looking alternative my code far eachline fileinputinputinputfile dosomethingeachline eachlineagain fileinputinputinputfile dosomethingeachlineagain executing code gives error message device active any suggestions edit the purpose calculate pairwise string similarity meaning line file i want calculate levenshtein distance every line,2 looping n permutations much expensive instead generate n subsets itertools import chain combinations def weighta return sumweightsx x a copied example httpdocspythonorglibraryitertoolshtml def powersetiterable powerset listiterable return chainfromiterablecombinationss r r xrangelens x x powerset a b c d e weightx w yields a d c b c e a b e b e d this converted sorted tuples changing return part list comprehension tuplesortedx replacing list call powerset one sorted,i would like find possible combinations weighted elements set sum weights exactly equal given weight w say i want select k elements set a b c d e weights a b c d e w then would yield a b e a d b c b d e c e i realize brute force way would find permutations given set itertoolspermutations splice first k elements weighted sum w but i dealing least elements per set would computationally expensive i think using variant knapsack would help weight value considered sum weights must equal w inferior i want implement python cstheory hints would help bonus points elegance,2 i assume destructor mean del method from docs del it guaranteed del methods called objects still exist interpreter exits what might want register atexit handler for example module level import atexit def cleanupdirectories directories cprojectsprojectalphatmp path directories ospathexistspath ospathisdirpath shutilrmtreepath atexitregistercleanupdirectories functions registered atexit run interpreter exits regardless interpreter exits of course could also something hacky like force garbage collector run import gc gccollect may force del method run i going go limb say bad idea,i try delete created directory destructor shutilrmtreecprojectsprojectalphatmp it work python script i execute command via python console works tmpdirectory deleted where difference,2 firstly use logging methods clientlastreceived clientlastsent output xml suds sending also print client print client see complex types associated service guess keyvalue type create using kv clientfactorycreatenskeyvalue info help way olly,i trying access really simple soap web service via python script using suds library here wsdl body the python code i using submit two keyvalue pairs follows url httpsomewhereonthewebcomwsasmxwsdl client sudsclientclienturl try result clientservicesendkdirequestkey value key value display success except exception e display error entering directly soapui client suggests service working correctly so i pretty sure i sending keyvalue pairs web service expects i really appreciate help guys provide,1 i find better way i refactored application use highgui display opencv images it forces use extra window extra thread one tkinter gui application widgets one highgui least way application responsive,i got application converts opencv iplimages tkinter images display loop naturally i want efficient way possible increase app responsiveness here i currently frame iplimage pilimage pilimagefromstring rgb cvgetsizeframe frametostring raw bgr framewidth tkimage imagetkphotoimagepilimage so converting entire opencv image string feeding pil converting pil tk is better way,1 there way around both implementations include purepython wichmannhill prng it slower gives results jython cpython in code i replaced randomseed uuid randomchoicehexdigits rand randomwichmannhill uuid randchoicehexdigits,i generating test data using known random seed i want use data cpython jython i found data different i use jython vs cpython boiling simple test i see prng giving different results two implementations in jython jython release mar java hotspottm server vm sun microsystems inc java type help copyright credits license information import random randomseed randomrandom in cpython python default oct gcc linux type help copyright credits license information import random randomseed randomrandom the test data i generating reproducible within python implementation is way around maybe i need code prng,3 the easiest way seems x dist intmathlogabsx i interpreted second entry pair list desired result i chose int round logarithm towards zero intmathlogabsx x,simple problem find first nonzero digit decimal point what i really need distance decimal point first nonzero digit i know i could lines i like pythonic nice clean way solve so far i dist lambda x strfloatxfind x distx x,2 make sure crmstageclaim extends crmcasestage crmcasestage inherits object newstyle class supports super overridden super assigning something else masking python builtin crmcasestage fact gettypevalue method,i created customized module sales crm openerp while creating opportunity i click stage field gives following error list supercrmstageclaim selfgettypevaluecr user context attributeerror super object attribute gettypevalue any help would appreciated regards sameer,1 the answer easy in python float might bit double c in itk f bit float specifying right type ndarray makes work import itk imagetype itkimagef buf scipyzeros dtype numpyfloat itkimage itkpybufferimagetypegetimagefromarraybuf,i using python itk wrappers pythonxy i trying send d image numpyscipy itk processing import itk imagetype itkimagef buf scipyzeros dtype float itkimage itkpybufferimagetypegetimagefromarraybuf getimagefromarray fails following error runtimeerror contiguous array created input python object however i create buffer let itk create image getimagefromarray suddenly work import itk imagetype itkimagef itkimage imagetypenewregions buf itkpybufferimagetypegetarrayfromimageitkimage itkimage itkpybufferimagetypegetimagefromarraybuf how i create numpy array accepted getimagefromarray,3 do upper bound number items sets if meetinthemiddle algorithm described wikipedia page knapsack quite simple significantly lower complexity bruteforce computation note using memoryefficient data structure python dict could also work larger sets an efficient implementation easily handle sets size here sample implementation collections import defaultdict itertools import chain combinations product taken docs itertools module def powersetiterable powerset listiterable return chainfromiterablecombinationss r r xrangelens def gensumsweights given set weights generate sum subsets mapping for posible sum create list subsets weights sum gensums a b a b a b sums defaultdictlist weightitems powersetweightsitems weightitems sumsappend else keys weights zipweightitems sumssumweightsappendkeys return dictsums def meetinthemiddleweights targetsum find subsets given weights desired sum this uses simplified meetinthemiddle algorithm weights a b c d e listmeetinthemiddleweights b e d a d a b e c b c e split weights two groups weightslist weightsitems weightsset dictweightslistlenweights weightsset dictweightslistlenweightsset generate sum subsets mapping group weights sort groups descending order setsums sortedgensumssetitems setsums sortedgensumssetitems reversetrue run first sorted list meanwhile going second list looking exact matches setsums itersetsums try setsum subsets setsumsnext setsum subsets setsums settargetsum targetsum setsum setsum settargetsum setsum subsets setsumsnext setsum settargetsum subset subset productsubsets subsets yield subset subset except stopiteration done iterating setsums pass,i would like find possible combinations weighted elements set sum weights exactly equal given weight w say i want select k elements set a b c d e weights a b c d e w then would yield a b e a d b c b d e c e i realize brute force way would find permutations given set itertoolspermutations splice first k elements weighted sum w but i dealing least elements per set would computationally expensive i think using variant knapsack would help weight value considered sum weights must equal w inferior i want implement python cstheory hints would help bonus points elegance,1 alternatively def simpleaxisax axspines top setvisiblefalse axspines right setvisiblefalse axgetxaxistickbottom axgetyaxistickleft seems achieve effect axis without losing rotated label support matplotlib solution inspired,instead default boxed axis style i want left bottom axis ie this easy i find necessary options docs,3 the question dynamic library loaded the code show enginemodulec references engine library engine automatically loaded initialization code enginemodulec executed similarly libraries used engine loaded library engine loaded all loaded using flags python used load interface module rtdllocal guess any dlopen invoke later find module already loaded ignore requestmdashincluding ignoring options dlopen might passed the way solved create special loader module contained direct references modules python loads module implements initxxx function the initxxx function explicitly loads modules needed dependency determined order if a used b b loaded a with rtdlglobal course in case would libraries used engine engine the last module loaded would one python interface put python initialization code constructor static object would executed automatically object loaded also put named function long get address function using dlsym rather declaring extern fashion the important thing ensure libraries first loaded explicit dlopen implicitly result undefined external library loaded earlier,i attempting call c api python following code pseudo form class engine singleton class heavy duty work public static engine getengine bool init private static engine minstance engine following code wrap call engine call python its simplified form enginemodulec include engineh pyobject initengine engine e enginegetinstance einit return pybuildvalue pyobject initenginemodule init module python code import enginemodule status enginemoduleinit problem the engine class libengineso inits fails internally dynamiccast fails the engine turns loads libraries using dlopen i searched net add rtdlglobal e option linking still resolved am i supposed add e option compiling python what could reason engine class works perfectly well used c code work used python edit to clarify question cat libengineso many classes internally engineinit uses dynamiccast the classes involved dynamiccast exposed python only engineinit exposed edit the platform red hat linux compiler intel,1 you could make process fork background reading input the far easier variant though start process inside tmux gnu screen,i dealing large data set takes days run therefore i use nohup run script terminal this time i need first get rawinput terminal nohup codes starts running any suggestion i first i need get input terminal like python myprogrampy enterinput something process like nohup python myprogrampy amp but i want one step via terminal i hope explanation clear,1 character first embedded quote text invalid json typeurl texta hrefhttpwwwpeoplecommunicatingcomjargonwordshtmlhttpwwwpeoplecommunicatingcomjargonwordshtmla languageen this returned server note embedded quotes typeurl textxca hrefxdxhttpwwwpeoplecommunicatingcomjargonwordshtmlxxehttpwwwpeoplecommunicatingcomjargonwordshtmlxcaxe languageen the best way decode json first dehexify string need edit if really invalid json karl knechtel says comments google told api incorrect if python implementation barfing valid json told fix whatever workaround make easy remove gets fixed,import json import urllib import import binascii def asciireplmatch matchgroup return binasciiunhexlifys query google p urlliburlopen httpwwwgooglecomdictionaryjsoncallbackaampq query ampslenamptlenamprestrictprdeampclientte page pread as returned function call to replace hex characters ascii characters p recompiler xw asciistring psubasciirepl page now decoding cleaned json response data jsonloadsasciistring running i get error shadyabhiarchlinux tmp python definepy traceback recent call last file definepy line module data jsonloadsasciistring file usrlibpythonjsoninitpy line loads return defaultdecoderdecodes file usrlibpythonjsondecoderpy line decode obj end selfrawdecodes idxws end file usrlibpythonjsondecoderpy line rawdecode obj end selfscanonces idx valueerror expecting delimiter line column char as far i think json without errors i recieved google server all i removing hex characters any help would highly appreciated,1 you really close python automatically either garbage collection program exit but delnan noted better practice explicitly close various reasons so keep short simple explicit open pageheadsectionhtm r f output fread now two lines pretty readable i think,now i use pageheadsectionfile open pageheadsectionhtm r output pageheadsectionfileread pageheadsectionfileclose but make code look better i output open pageheadsectionhtm r read when using syntax i close file free system resources,3 using cpython file closed immediately line executed file object immediately garbage collected there two drawbacks though in python implementations different cpython file often immediately closed rather later time beyond control in python throw resourcewarning enabled better invest one additional line open pageheadsectionhtm r f output fread this ensure file correctly closed circumstances,now i use pageheadsectionfile open pageheadsectionhtm r output pageheadsectionfileread pageheadsectionfileclose but make code look better i output open pageheadsectionhtm r read when using syntax i close file free system resources,3 i next similar case class decimalencoderjsonjsonencoder def defaultself obj isinstanceobj decimal return floatobj return jsonjsonencoderdefaultself obj call jsondumpsmyvariable clsdecimalencoder so case like class dateencoderjsonjsonencoder def defaultself obj hasattrobj isoformat return objisoformat else return strobj return jsonjsonencoderdefaultself obj jsondumpsmyvariable clsdateencoder,i attempting send list records response ajax query this works well unless results include datetime field process fails error datetimedate json serializable i attempted combine answer i found similar question instructions cherrypy documentation use custom jsonout encoder clear signature function must the function i wrote def jsonencoderthing hasattrthing isoformat return thingisoformat else return strthing use jsonout even datetime output gives error typeerror jsonencoder takes exactly argument given but encoder take argument receive object encode also i assume use strthing default method encoding wrong done call whatever default handler json encoding i sure call method,3 what use statement open pageheadsectionhtm r fin output finread the statement take care call exit function given object even something bad happened code close try finally syntax for object returned open exit corresponds file closure this statement introduced python,now i use pageheadsectionfile open pageheadsectionhtm r output pageheadsectionfileread pageheadsectionfileclose but make code look better i output open pageheadsectionhtm r read when using syntax i close file free system resources,3 decoding x escapes may produce marks need reescaped appear within strings encoded within json data def asciireplmatch chr binasciiunhexlifymatchgroup return chr chr else chr that still handle control characters might instead want convert x escapes u escapes described json standard parsed json module this side benefit simpler def asciireplmatch return u matchgroup,import json import urllib import import binascii def asciireplmatch matchgroup return binasciiunhexlifys query google p urlliburlopen httpwwwgooglecomdictionaryjsoncallbackaampq query ampslenamptlenamprestrictprdeampclientte page pread as returned function call to replace hex characters ascii characters p recompiler xw asciistring psubasciirepl page now decoding cleaned json response data jsonloadsasciistring running i get error shadyabhiarchlinux tmp python definepy traceback recent call last file definepy line module data jsonloadsasciistring file usrlibpythonjsoninitpy line loads return defaultdecoderdecodes file usrlibpythonjsondecoderpy line decode obj end selfrawdecodes idxws end file usrlibpythonjsondecoderpy line rawdecode obj end selfscanonces idx valueerror expecting delimiter line column char as far i think json without errors i recieved google server all i removing hex characters any help would highly appreciated,2 the documentation claims varnish cache requests cookie header quick work around might include cookie … header alternatively include unused get parameter like cachebuster bypass caching,i trying fetch fresh content wordpress blog uses varnish server side is way bypass varnish cache control i get fresh content time i request site thanks,3 reprinted gnome pygobject bug report answer credit goes timo vanwynsberghe there couple things note drawingarea realised get gdkwindow apparently get window property directly need import gdkx xid method with mind minimal working example girepository import gdkx gtk class app def initself win gtkwindow winresize winconnect deleteevent gtkmainquit da gtkdrawingarea winaddda winshowall print dagetproperty window getxid name main app gtkmain,i following python pygobject pygst module girepository import gtk gdk gdkpixbuf import pango import pygst pygstrequire import gst import trailcrest import os sys import cairo math import pi class video def initself def onmessagebus message messagetype gstmessageeos end stream playerseek gstformattime gstseekflagflush gstseektypeset gstseektypenone elif messagetype gstmessageerror playersetstategststatenull err debug messageparseerror print error err debug def onsyncmessagebus message messagestructure none return false messagestructuregetname preparexwindowid gdkthreadsenter print run gdkdisplaygetdefaultsync print run winid videowidgetwindowxid imagesink messagesrc imagesinksetpropertyforceaspectratio true imagesinksetxwindowidwinid gtkgdkthreadsleave def clickmeevent datanone playerseek gstformattime gstseekflagflush gstseektypeset gstseektypenone win gtkwindow winsetresizablefalse winsetdecoratedfalse winsetpositiongtkwindowpositioncenter fixed gtkfixed winaddfixed fixedshow videowidget gtkdrawingarea fixedputvideowidget videowidgetsetsizerequest videowidgetshow setup gstreamer player gstelementfactorymakeplaybin multimediaplayer bus playergetbus busaddsignalwatch busenablesyncmessageemission used get messages gstreamer emits busconnectmessage onmessage used connecting video application busconnectsyncmessageelement onsyncmessage playersetpropertyuri file osgetcwd vidbgahabtogv playersetstategststateplaying winshow def main gdkthreadsenter gtkmain return name main video main i always getting error along video opening new window instead existing window traceback recent call last file videopy line onsyncmessage winid videowidgetwindowxid attributeerror drawingarea object attribute window how i fix video displays window i created instead new one by problem started occuring i switched pygobject pygtk,3 match researchr ddd sfile match version matchgroup,gents i trying grab version number string via python regex given filename factertargz when inside loop import version resplit ddd sfile print version how get bit version thanks,1 this development server singlethreaded it responding original request client request generated internally hang,i currently trying create rest web service django site scratch i want use external libraries supposed learning experience one applications act web application act web service i plenty examples implement web service return http responses problem generating sending http requests i example i want application send http request application receives responds the web service responds perfectly browsergenerated request i simply write resource address address bar i get expected response i tested using python builtin urllib urlopen hang forever possibly socket occupied i realize i specified timeout concern request never picked server there log request ever occurring the url code browser identical is way django simply generate httprequest send way without much fuss this offending line response urlliburlopen httpapibrowse,1 two logical problems since want portion want capture part first goes outside parentheses since want match pattern question grab using split makes sense instead use rematch this give match object use group method get actual matched text group entire matched pattern group matched stuff inside first set parentheses etc rematch ddd factortargz group although answer indicates actually point matching part anyway instead search string consists part want this look pattern anywhere within string matching expects beginning since need parentheses make pattern work logically going use entire matched portion longer need parentheses either research ddd factortargz group,gents i trying grab version number string via python regex given filename factertargz when inside loop import version resplit ddd sfile print version how get bit version thanks,1 you use defaultdict collections import defaultdict line hello firstnames lastnames print line defaultdictstr firstname mike explanation first argument defaultdict initializer must callable returns default value str callable returns empty string try str,the following works fine line hello firstnames lastnames print line dict firstname mike lastnamekane prints hello mike kane but i value lastname i still want work line hello firstnames lastnames print line dict firstname mike i want ignore lastname key print hello mike,3 you use make subclass dictionary supplies defaults missing values class dictdict def missingself key supply default value given key return key dictfirstname mike print hello firstnames lastnames hello mike lastname the techniques gives complete control returned here variants return missing returns default string return keyupper highlight missing key return return empty string,the following works fine line hello firstnames lastnames print line dict firstname mike lastnamekane prints hello mike kane but i value lastname i still want work line hello firstnames lastnames print line dict firstname mike i want ignore lastname key print hello mike,1 class mydictdict def missingself key return printhello firstnames lastnames mydictfirstname mike prints hello mike,the following works fine line hello firstnames lastnames print line dict firstname mike lastnamekane prints hello mike kane but i value lastname i still want work line hello firstnames lastnames print line dict firstname mike i want ignore lastname key print hello mike,1 instead using etreeparsefile parser loop lines file call parserfeed line this gives control break loop now set selfdonetrue target test targetdone feed loop import lxmletree et class haltingtargetobject def initself limitnone selfdonefalse selflimitlimit selfcounter selfresult def startself tag attrib selflimit selfcounterselflimit selfdonetrue return attrib selfresultappendattrib selfcounter def endself tag pass def dataself data pass def commentself text pass def closeself return def haltparser content node title ax my title title node ax node node ax node node targethaltingtarget parseretxmlparsertargettarget line contentsplitlines parserfeedlinestrip targetdone break we call parserclose since xml fed probably incomplete we plan use parser anymore delete del parser printtargetresult u x u x u x,i getting information large xml file i using python lxml target parsing interface i would like possibility set limit parsing stops here code parser target code class titletargetobject def initself limitnone selflimit limit selfcounter def startself tag attrib selflimit selfcounter selflimit break here return false doprocessingattrib selfcounter selfcounter def endself tag pass def dataself data pass def closeself pass code initiating parsing parser etreexmlparsertarget titletargetlimit etreeparsefile parser i know processing goes break here line i found method stop parsing i tried returning true false raising error none seem work it always processes file ends is way stop processing bu using method,1 python sets clean simple way b seta amp setb set if use done using dictionaries dictfromkeysb k k print k if elements hashable straight contains test k k b print k,for example i b what could i use i could search lists get values note i use set function,1 you use sets b print seta amp setb prints set which desired result,for example i b what could i use i could search lists get values note i use set function,1 values x x x b note allows duplicates but really use sets,for example i b what could i use i could search lists get values note i use set function,1 you first need convert fraction make work def rsubself return fractionother self since rsub gets called type fraction need type checking simply assume integer your current implementation sub also needs work returns nothing type fraction,i attempting use rsub function class i made called fraction here fraction class code def initself num denom creates new fraction object numdenom selfnum num selfdenom denom selfreduce def reprself returns string representation fraction return strselfnum strselfdenom def reduceself converts fractional representation reduced form divisor gcdselfnum selfdenom selfnum selfnum divisor selfdenom selfdenom divisor def subself isinstanceotherfraction true newnum selfnum otherdenom selfdenomothernum newdenom selfdenom otherdenom return fractionnewnum newdenom now i radd rmul using return self return self respectively perform desired result however rsub rtruediv work simply changing operator how i fix essentially code calling functions f fraction g fraction print f f print f f thanks help,2 because typecheck return none second operand fraction also isinstance isinstance true you need coerce argument instead,i attempting use rsub function class i made called fraction here fraction class code def initself num denom creates new fraction object numdenom selfnum num selfdenom denom selfreduce def reprself returns string representation fraction return strselfnum strselfdenom def reduceself converts fractional representation reduced form divisor gcdselfnum selfdenom selfnum selfnum divisor selfdenom selfdenom divisor def subself isinstanceotherfraction true newnum selfnum otherdenom selfdenomothernum newdenom selfdenom otherdenom return fractionnewnum newdenom now i radd rmul using return self return self respectively perform desired result however rsub rtruediv work simply changing operator how i fix essentially code calling functions f fraction g fraction print f f print f f thanks help,1 i would suggest b k minlenalenb zipak bk,given sequences different lengths in in b this want in c zipreversedareversedb in x x reversedc out but i like idea using reversed input parameters i also want reimplement zip function so is fastermore efficient way is simpler way,1 the following work even know longer zipalenb blena here example happens smaller list range so even though slice looks kind funky negative start value larger length list give entire list,given sequences different lengths in in b this want in c zipreversedareversedb in x x reversedc out but i like idea using reversed input parameters i also want reimplement zip function so is fastermore efficient way is simpler way,2 as far i know need ie compatibility available libraries js work require either canvas svg support you left static images flash java applets i would look processing good d support create java applets web use see d tutorials good examples interactive d surfaces if wanted get fancy could potentially also offer processingjs browsers support canvas element this would avoid loading java applet browsers making slightly smoother ui removing java dependency you need check browser compatibility load either applet code processingjs code the upside able use exactly processing code cases,i python web server cherrypy i want user able compute certain surfaces precise type this i able generate user input he gives parameters i compute things generate png server matplotlibnumpy send back jquery load problem pretty lame surfaces various aspects i like able actual widget would enable user rotate surface my major constraints work ie would cool well allow input data i compute somehow i seen many things web permit input parametric functions what i need able push raw data triplets i looking several things javascript would best i failed see something jquery equivalents i look quite long around webgl started implementing stufffrom scratch way long random behavior ie sometimes maybe i missing completely something technology format compatible python i spent days adopting temporary solution plotting pngs looking forward reading guys thanks advance,2 python script return verticespoints d model json format use mrdoob threejs create live javascriptpowered d webgl model directly browser check threejs httpsgithubcommrdoobthreejs look amazing examples inspiration probably get hold mrdoob insights also edit oops noticed ie requirement no webgl ie you use flash d rendering either python script create different angles view loaded images browser example user clicks right button next image loads rotated certain angle right edit looks like iewebgl enable webgl ie eidt processingjs looks really nice visualizations,i python web server cherrypy i want user able compute certain surfaces precise type this i able generate user input he gives parameters i compute things generate png server matplotlibnumpy send back jquery load problem pretty lame surfaces various aspects i like able actual widget would enable user rotate surface my major constraints work ie would cool well allow input data i compute somehow i seen many things web permit input parametric functions what i need able push raw data triplets i looking several things javascript would best i failed see something jquery equivalents i look quite long around webgl started implementing stufffrom scratch way long random behavior ie sometimes maybe i missing completely something technology format compatible python i spent days adopting temporary solution plotting pngs looking forward reading guys thanks advance,1 i guess seeing current behaviour want like replace text aliasname element text name corresponding key dictionary change line change aliasname key aliastext jpengetnametextstrip aliastext to aliastext jpengetnametextstrip nametext if key values come aliasname instead name replace line aliastext none aliastext jpengetaliastextstrip nametext else aliastext nametext,i would like replace text aliasname element text name corresponding key dictionary xml i working esriworkspace xmlnsesrihttpwwwesricomschemasarcgisxmlnsxsihttpwwwworgxmlschemainstance xmlnsxshttpwwwworgxmlschema workspacedefinition xsitypeesriworkspacedefinition workspacetypeesrilocaldatabaseworkspaceworkspacetype domains xsitypeesriarrayofdomain datasetdefinitions xsitypeesriarrayofdataelement dataelement xsitypeesridefeatureclass catalogpathfcchohcatalogpath namechohname datasettypeesridtfeatureclassdatasettype dsiddsid versionedfalseversioned canversionfalsecanversion configurationkeyword hasoidtruehasoid oidfieldnameobjectidoidfieldname fields xsitypeesrifields fieldarray xsitypeesriarrayoffield field xsitypeesrifield namekeycodename typeesrifieldtypestringtype isnullabletrueisnullable lengthlength precisionprecision scalescale aliasnameリンクコードaliasname keycode modelnamekeycodemodelname field field xsitypeesrifield namekenname typeesrifieldtypestringtype isnullabletrueisnullable lengthlength precisionprecision scalescale aliasname都道府県番号aliasname prefecturecode modelnamekenmodelname field field xsitypeesrifield namecityname typeesrifieldtypestringtype isnullabletrueisnullable lengthlength precisionprecision scalescale aliasname市区町村番号aliasname citycode modelnamecitymodelname field i wrote usrbinenv python coding utf import xmletreecelementtree etree jpen リンクコード keycode 都道府県番号 prefecturecode 市区町村番号 citycode tree etreeparse inputxml field treeiterfind fieldsfieldarrayfield name alias fieldfindtag tag name aliasname name none alias none continue aliastext jpengetnametextstrip nametext treewrite outputxml encoding utf however output text aliasname element replaced text name even corresponding key dictionary jpen like aliasnameリンクコードaliasname returns text keycode text name key aliasname都道府県番号aliasname returns text ken name instead key prefecturecode aliasname市区町村番号aliasname returns text city name instead key citycode i use python,1 the value used redirecturi must exactly request token requested code since actual redirect occurs requesting token easy miss small differences the error message particularly descriptive case really means the parameters sending correspond code value sending,i got django template initiates facebook oauth process windowlocation httpswwwfacebookcomdialogoauthclientidmyclientidampredirecturihttpalocalhostafbpanelexplorepython then django view i get resulting code follows import cgi import urllib code requestget code args clientid myclientid redirecturi httplocalhostfbpanelexplorepython clientsecret myclientsecret code code url httpsgraphfacebookcomoauthaccesstoken urlliburlencodeargs rawresponse urlliburlopenurlread response cgiparseqsrawresponse response error response accesstoken accesstoken response accesstoken response expires expires response expires else accesstoken no access token returned expires no expiration given error rawresponse invariably response none rawresponse contains error errormessageerror validating verification codetypeoauthexception the credentials validate fine javascript sdk i binding server localhost case localhost set official app domain before i javascript work after so i think localhost issue i manually stepped code printing code returned fb manually running code line line python interpreter i see anything i wrong what next debugging steps the fb documentation offers little guidance receive oauthexception,2 personally i would something along lines put initialisation map foosrowtypestring new maprowtype string populate map mapset headera specific params x mapset b headerb specific params x mapset c headerc specific params mapset map barsstringstring new mapstringstring barsset fooa ab barsset foob ac string commonheader http this would method row dbqueryforservice string outputheader commonheader barsgetfoonsplit outputheader foosgeti sendrequest in sort pseudo javapython the map would prefilled everything need pick want attach,i different services i send requests require slightly different set headers the bad legacy code something like row dbqueryforservice rowtype foo add common headers request add foo specific headers add foo specific header add foo specific header else rowtype foo add common headers request add foo specific header else rowtype foo add common headers request add foo specific header add foo specific header sendrequest what best way refactor i considered patterns may work strategy builder i sure i currently learning java python i would get thoughts solutions would differ two languages,1 you right idea you would need put something like rawinput somewhere script exits if python use input instead rawinput name main printapproximatesize false print approximatesize input press enter exit,so i started learning python set notepad run via cmd prompt is simple way stop cmd prompt autoexiting i run simple program do i need ask input every time something easier way i tried rawinput press enter exit luck here program introduction python book started httppastebincomzvjruzzz if makes difference i running straight pythonexe python version,1 seems broken download did try easyinstall sudo easyinstall pip,i trying install pythonshapely pip ubuntu i got unknown unsupported command install i tried userdesktop pip install shapely i tried installing pip got following error userdesktop sudo aptget install pythonpip reading package lists done building dependency tree reading state information done the following new packages installed pythonpip upgraded newly installed remove upgraded need get bkb archives after operation kb additional disk space used reading database files directories currently installed unpacking pythonpip pythonpipubuntualldeb dpkg error processing varcacheaptarchivespythonpipubuntualldeb unpack trying overwrite usrbinpip also package pip errors encountered processing varcacheaptarchivespythonpipubuntualldeb e subprocess usrbindpkg returned error code i appreciate commentsolution thanks,1 one way focus digits decimal point remove integer part number leaving fractional part something like x intx having isolated fractional part could let python counting e presentation also helps take care rounding issues e e intpartition,simple problem find first nonzero digit decimal point what i really need distance decimal point first nonzero digit i know i could lines i like pythonic nice clean way solve so far i dist lambda x strfloatxfind x distx x,2 what i personally like python script run completion without asking input write batch file windows shell script linuxunix press key thing that way i run script command line needlessly prompt input you could write batch file like pythonexe pause save pypausebat tell notepad run python scripts via batch file instead pythonexe,so i started learning python set notepad run via cmd prompt is simple way stop cmd prompt autoexiting i run simple program do i need ask input every time something easier way i tried rawinput press enter exit luck here program introduction python book started httppastebincomzvjruzzz if makes difference i running straight pythonexe python version,2 let see i get straight the year always current year not static text would written instead i right if want pass variable could create custom template tag use instead or could create base view class view classes inherits adds commonly used template variables like year,i new django i simple problem hope help solve i base template like doctype html html head title block title endblock title link typetextcss rel stylesheet hrefstylecss script typetextjavascript srcjqueryjs script head body block navmenu endblock block content endblock block footer endblock body html while template extended intermediate template structure like extends basehtml block navmenu ul lihomeli liprogrammingli liaboutli licontactli ul endblock block footer hcopyright amp year mel gibson h endblock both template look straight forward view renders different template extends intermediate template i simple problem the block called footer variable called year this constant page i keep passing variable context would redundancy easiest way render date passed code can i import datetime object html file build year field within template display,1 try using ordereddict instead regular python dictionaries unordered implemented using hash tables scramble key order per docs dictionaries best think dictionary unordered set key value pairs requirement keys unique within one dictionary,i following dictionary variable name divisiontotaldisplay l name total l totalpercentage totalright l l name total l totalpercentage totalright l l name total l totalpercentage totalright l i pass template follows return rendertoresponse sitereporttopicstandardstathtml reportdate reportdate etdisplay etdisplay statsdisplay statsdisplay divisiontotaldisplay divisiontotaldisplay school school board board standard standard standard standard subject subject fromtime fromtime termid termid whitelabel whitelabel contextinstancerequestcontextrequest however template i print divisiontotaldisplay l totalright l total l totalpercentage name l totalright l total l totalpercentage name l totalright l total l totalpercentage name please note ordering its starts instead i want start followed,1 you also need implement eq match hash implementation,i class definition hash function uses object properties create unique key comparison python sets the hash method looks like def hashself return int ds selfidselfcreatekey in module responsible implementing class several queries run could conceivably construct duplicate instances class queue created function responsible represented set make sure dupes omitted inset set outset set inid inids ps perceptrongetwherelinkedinidselfinents p ps insetaddp poolid poolids ps perceptrongetwherelinkedpoolidselfoutents p ps outsetaddp return insetunionoutset not sure indenting got mangled somehow despite calling union method i still getting two duplicate instances when printed str method perceptron class calls hash two hashes identical theoretically possible set any guidance would appreciated,1 the following faster clearer posted solutions zipreverseda reversedb sreverse inplace the reversed builtin creates iterator loops backwards speed forward iteration no additional memory full copies input produced slow trips around python evalloop present solutions use indicies,given sequences different lengths in in b this want in c zipreversedareversedb in x x reversedc out but i like idea using reversed input parameters i also want reimplement zip function so is fastermore efficient way is simpler way,3 if class define cmp eq method define hash operation either source define eq,i class definition hash function uses object properties create unique key comparison python sets the hash method looks like def hashself return int ds selfidselfcreatekey in module responsible implementing class several queries run could conceivably construct duplicate instances class queue created function responsible represented set make sure dupes omitted inset set outset set inid inids ps perceptrongetwherelinkedinidselfinents p ps insetaddp poolid poolids ps perceptrongetwherelinkedpoolidselfoutents p ps outsetaddp return insetunionoutset not sure indenting got mangled somehow despite calling union method i still getting two duplicate instances when printed str method perceptron class calls hash two hashes identical theoretically possible set any guidance would appreciated,2 the process i would use following once image uploaded s rails gets notified adds message amazon sqs queue see httpawsamazoncomsqs a background process running ec checks queue processes messages generating thumbnails once thumbnail generated notification sent using amazon sns see httpawsamazoncomsns rails app respons notification,ok quick summary setup want accomplish i rails server runs website i flash application site users upload images directly when upload completed rails notified at point image finished uploading rails notified want rails send post something located ec create two thumbnails x x when thumbnails created transferred want whatever process ec send post back rails notify thumbnail creation finished what best way accomplish i looked tools knife briefly i familiar using ec similar services thanks,3 this context processors,i new django i simple problem hope help solve i base template like doctype html html head title block title endblock title link typetextcss rel stylesheet hrefstylecss script typetextjavascript srcjqueryjs script head body block navmenu endblock block content endblock block footer endblock body html while template extended intermediate template structure like extends basehtml block navmenu ul lihomeli liprogrammingli liaboutli licontactli ul endblock block footer hcopyright amp year mel gibson h endblock both template look straight forward view renders different template extends intermediate template i simple problem the block called footer variable called year this constant page i keep passing variable context would redundancy easiest way render date passed code can i import datetime object html file build year field within template display,1 django supported solution use case requestcontext,i new django i simple problem hope help solve i base template like doctype html html head title block title endblock title link typetextcss rel stylesheet hrefstylecss script typetextjavascript srcjqueryjs script head body block navmenu endblock block content endblock block footer endblock body html while template extended intermediate template structure like extends basehtml block navmenu ul lihomeli liprogrammingli liaboutli licontactli ul endblock block footer hcopyright amp year mel gibson h endblock both template look straight forward view renders different template extends intermediate template i simple problem the block called footer variable called year this constant page i keep passing variable context would redundancy easiest way render date passed code can i import datetime object html file build year field within template display,1 dictionaries unordered use nested list instead,i following dictionary variable name divisiontotaldisplay l name total l totalpercentage totalright l l name total l totalpercentage totalright l l name total l totalpercentage totalright l i pass template follows return rendertoresponse sitereporttopicstandardstathtml reportdate reportdate etdisplay etdisplay statsdisplay statsdisplay divisiontotaldisplay divisiontotaldisplay school school board board standard standard standard standard subject subject fromtime fromtime termid termid whitelabel whitelabel contextinstancerequestcontextrequest however template i print divisiontotaldisplay l totalright l total l totalpercentage name l totalright l total l totalpercentage name l totalright l total l totalpercentage name please note ordering its starts instead i want start followed,2 does help httpsdocsdjangoprojectcomendevreftemplatesbuiltinsfromolddocsnow,i new django i simple problem hope help solve i base template like doctype html html head title block title endblock title link typetextcss rel stylesheet hrefstylecss script typetextjavascript srcjqueryjs script head body block navmenu endblock block content endblock block footer endblock body html while template extended intermediate template structure like extends basehtml block navmenu ul lihomeli liprogrammingli liaboutli licontactli ul endblock block footer hcopyright amp year mel gibson h endblock both template look straight forward view renders different template extends intermediate template i simple problem the block called footer variable called year this constant page i keep passing variable context would redundancy easiest way render date passed code can i import datetime object html file build year field within template display,1 there several approaches i really think tell information provided best approach you use orm like sqlalchemy you use object database you could pickle objects store relational database datastore including shelve included standard distribution these approaches i think top head only determine ones fit requirements intention best,i need store instances least state database the idea i able recreate instance demand since i define classes i choose i would like store data consider following diagram inheritance diagram a b c d e f the idea instance belong classes store objects i completely design control my first thought store state exclusively dictionary dump dictionary json store database at run time load json database convert dictionary create object passing dictionary get setup i sure good approach also issues might crop i already came across one use myobjdict actually get class parent attributes though any suggestions,1 the shelve module easiest way get started storing instances retrievable key it automatically pickles unpickles takes care reading writing file,i need store instances least state database the idea i able recreate instance demand since i define classes i choose i would like store data consider following diagram inheritance diagram a b c d e f the idea instance belong classes store objects i completely design control my first thought store state exclusively dictionary dump dictionary json store database at run time load json database convert dictionary create object passing dictionary get setup i sure good approach also issues might crop i already came across one use myobjdict actually get class parent attributes though any suggestions,1 there quick way tell install django toolbar then check queries tab it give sorts profiling info though i believe query per fk call,say i following models class bazmodelsmodel winning modelscharfieldmaxlength class barmodelsmodel baz modelsforeignkeybaz class foomodelsmodel bar modelsforeignkeybar now i instance foo foo how many queries following line execute winning foobarbazwinning does one foreignkey django smart enough one query,1 that require queries one get foo bar baz use selectrelated get fooobjectsgetidselectrelated barbazwinning,say i following models class bazmodelsmodel winning modelscharfieldmaxlength class barmodelsmodel baz modelsforeignkeybaz class foomodelsmodel bar modelsforeignkeybar now i instance foo foo how many queries following line execute winning foobarbazwinning does one foreignkey django smart enough one query,2 i new djangoi submit form run view i i run sth like logout view clicking anchor link logging via link instead form easy httpsdocsdjangoprojectcomendevtopicsauthdjangocontribauthlogout djangocontribauth import logout def logoutviewrequest logoutrequest return httphttpresponseyou logged just point url view like form go url,i view logoutnow i wanna user click anchor link logout view runhow i viewspy def logoutrequest authlogoutrequest return rendertoresponseairagencyindexhtml,1 here queries winning foobarbazwinning statement i counting fooobjects statemnt select foobarid foobarbazid from foobar where foobarid args select foobazid foobazwinning from foobaz where foobazid args and tip add logging djangodbbackends settings httpsdocsdjangoprojectcomendevtopicsloggingdjangodbbackends and see queries console or install django debug toolbar francis suggesting,say i following models class bazmodelsmodel winning modelscharfieldmaxlength class barmodelsmodel baz modelsforeignkeybaz class foomodelsmodel bar modelsforeignkeybar now i instance foo foo how many queries following line execute winning foobarbazwinning does one foreignkey django smart enough one query,1 you try pattern command the pseudo code something like interface command void execute class concretecommanda implements command override void execute action class concretecommandb implements command override void execute action use structure client mapstring command commands new hashmapstring command commandsputaction new concretecommanda commandsputaction new concretecommandb runcommandstring str command command commandsgetstr commandexecute,i different services i send requests require slightly different set headers the bad legacy code something like row dbqueryforservice rowtype foo add common headers request add foo specific headers add foo specific header add foo specific header else rowtype foo add common headers request add foo specific header else rowtype foo add common headers request add foo specific header add foo specific header sendrequest what best way refactor i considered patterns may work strategy builder i sure i currently learning java python i would get thoughts solutions would differ two languages,1 if scripts executed inside package various hacks need employed get imports work properly probably common manipulate syspath import sys os syspathinsert ospathdirnameospathdirnameospathabspathfile src import stringbuilder del syspath there way achieve using normal import statements a generally better solution simply avoid running scripts inside packages altogether instead put scripts outside package containing directory given directory currently running script automatically added start syspath guarantee package always directly imported matter script executed so directory structure might look something like project package initpy src initpy stringbuilderpy tests initpy stringbuildertestpy mainpy testpy the testpy script import tests like packagetests import stringbuildertest and stringbuildertestpy import src modules like packagesrc import stringbuilder,i checked many so pages i could tried everything i found none successful i also checked pep page regarding importing tried every example none worked i tests folder unit tests i need import module i want test the modules folder called src next src folder the foldersfiles look something like project src stringbuilderpy initpy tests stringbuildertestpy initpy mainpy initpy i tried everything i could adding initpy every folder making module including project main folder import srcmoduletotest srcmoduletotest import functiontotest src import moduletotest i tested combinations failed i starting think must something wrong either settings understanding i thought suppose simple if i making obvious errors please let know tests import stringbuilder error message stringbuildertestpy traceback recent call last file stringbuildertestpy line module tests import stringbuilder importerror no module named tests the error occurs tests src src import stringbuilder,2 just make asterisk lazy r httpswwwdomaincomppath the end ensures entire string matched trailing slash present always matched,currently i following python regex r httpswwwdomaincomppath that i replacing r gpath this works fine except scenario last character string slash in case greedily consumes last subbed string ends path essentially i stripping domain absolute path turning relative path trying ensure relative path begins ends any idea i exclude last character match it seems i probably need sort lookahead i sure exactly construct,2 don use regular expressions use urlparse module instead example docs urlparse import urlparse urlparse httpwwwcwinleguidopythonhtml parseresultscheme http netloc wwwcwinl path eguidopythonhtml params query fragment oscheme http oport ogeturl httpwwwcwinleguidopythonhtml,currently i following python regex r httpswwwdomaincomppath that i replacing r gpath this works fine except scenario last character string slash in case greedily consumes last subbed string ends path essentially i stripping domain absolute path turning relative path trying ensure relative path begins ends any idea i exclude last character match it seems i probably need sort lookahead i sure exactly construct,2 i think sphinx simply uses python command interpreter but according makefile specify python option running make installation,i try create documentation project written python x sphinx tool i want use according official site last version compatible python my os archlinux linux distribution uses python default python package the installation configuration straight forward easyinstall u sphinx sphinxquickinstall i never asked choose x x python interpreter but i ask sphinx create documentation project code analyzed i wrote python x is sphinx ready python x did i make mistake,1 could use subprocess pgrep import subprocess p subprocesscheckoutput pgrep f screen print p,how check python whether screen given name ex server running thanks,1 in following solution copy input lists done def rzipab minlenalenb xrangem yield amibmi ab print listrzipab length shortest list always transformed index shortest list transfomed index longest list result despite fact function rzip oneliner i think simple i bet faster solution edit at first function rzip eyquem following code i thought creating list zipped elements runing correct position list left right would good procedure in following code eyquembis function rzip slightly improved precalculation starting positions but i interested raymond hettinger claim exclusive use zip iterator reversed clearer faster solution so i imagined using iterators left right would better function rzip i used iter islice write functions eyquem eyquem following code i compared execution times diverse solutions proposed answers import random time import clock limalimb listrangelima b listrangelimb randomshufflea randomshuffleb abcdefghi n essays range te clock rep rangen k minlenalenb sam listzipak bk tref clockte aappendclockte sam hocevar deducted normal slicing zip nk minlenalenb nlistzipak bk te clock rep rangen k minlenalenb sam listzipalenak blenbk tref clockte bappendclockte sam hocevar exactly normal slicing zip nk minlenalenb nlistzipalenak blenbk te clock rep rangen fj listzipalenb blena cappendclockte fj deducted tricky slicing zip nlistzipalenb blena te clock rep rangen minlenalenb sleep listzipalenamblenbm dappendclockte sleeplessnerd exactly normal slicing zip nm minlenalenb nlistzipalenamblenbm te clock rep rangen minlenalenb ey amibmi rangem eappendclockte eyquem deducted normal slicing listcomp nm minlenalenb n amibmi rangem te clock rep rangen minlenalenb xy lenam lenbm eybis axibyi rangem fappendclockte eyquem improved exactly normal slicing listcomp nm minlenalenb nxy lenam lenbm naxibyi rangem te clock rep rangen ita itera itb iterb lenblena av rangelenblena itbnext else av rangelenalenb itbnext ey listzipitaitb gappendclockte eyquem use zip iterator iter nlistzipitaitb itertools import islice te clock rep rangen lenblena ey listzipitera isliceblenblenanone else ey listzipislicealenalenbnoneiterb happendclockte eyquem use zip iterators iter and islice nlistzipiteraisliceblenblenanone te clock rep rangen ray listreversedlistzipreversedareversedb iappendclockte raymond hettinger use zip iterator reversed nlistreversedlistzipreversedareversedb print lena dnlenb dn lenalenb tempi minx x abcdefghi tempisortreversetrue tref tempi print nn join f ttrefch tch tempi print nsamsamfjsleepeyeybiseyeyray samsamfjsleepeyeybiseyeyray a result lists different lengths lena lenb sam hocevar exactly normal slicing zip k minlenalenb listzipalenak blenbk sam hocevar deducted normal slicing zip k minlenalenb listzipak bk sleeplessnerd exactly normal slicing zip minlenalenb listzipalenamblenbm fj deducted tricky slicing zip listzipalenb blena eyquem use zip iterator iter listzipitaitb eyquem deducted normal slicing listcomp minlenalenb amibmi rangem eyquem improved exactly normal slicing listcomp minlenalenb xy lenam lenbm axibyi rangem eyquem use zip iterators iter and islice listzipiteraisliceblenblenanone raymond hettinger use zip iterator reversed listreversedlistzipreversedareversedb samsamfjsleepeyeybiseyeyray true result two lists similar lengths lena lenb sam hocevar deducted normal slicing zip k minlenalenb listzipak bk fj deducted tricky slicing zip listzipalenb blena sleeplessnerd exactly normal slicing zip minlenalenb listzipalenamblenbm sam hocevar exactly normal slicing zip k minlenalenb listzipalenak blenbk eyquem deducted normal slicing listcomp minlenalenb amibmi rangem eyquem improved exactly normal slicing listcomp minlenalenb xy lenam lenbm axibyi rangem raymond hettinger use zip iterator reversed listreversedlistzipreversedareversedb eyquem use zip iterator iter listzipitaitb eyquem use zip iterators iter and islice listzipiteraisliceblenblenanone samsamfjsleepeyeybiseyeyray true i conclude groups solutions solutions sam hocevar fj sleeplessnerd longest executions they use different combinations slicing function zip by way overwhelmingly approved sam solution longest function rzip rzipimproved execute time taken ones group they use list comprehension elements obtained indices solutions eyquem eyquem raymond hettinger solution take less said preceding times they use iterators the execution times solutions depend relative lengths list lists similar lengths solutions eyquem eyquem execution times divided but different lists eyquem surprisingly takes much reference time constant execution time around reference time raymond hettinger solution confirms claim my solution eyquem iter islice bad clear raymond hettinger one though latter little obscure first glance,given sequences different lengths in in b this want in c zipreversedareversedb in x x reversedc out but i like idea using reversed input parameters i also want reimplement zip function so is fastermore efficient way is simpler way,1 you using productpart instance mutating productpartdate moddate since pilottest objects reference productpart instance see mutation you need create new instance class iteration loop assign new instance productpart productpart something,i created object type initilializing i pushing list reason behavior expected let put sample code output def alligndatestowhenwasitemsoldpilotinstance unitssoldperday pilotinstanceunitssoldperday productpart pilotinstanceproduct date productpartdate quantity pilotinstanceproductquantity listofpilotinstance rangelenunitssoldperday perdayquantity unitssoldperdayi moddate date print perdayquantity moddate modifydatedate productpartdate moddate print pro productpartdate newpilotinstance pilottestproductpart pilotinstancenameperdayquantity print newpilotinstanceproductdatedate newpilotinstanceproductdatemonth newpilotinstanceunitssoldperday newpilotinstancesetdatemoddate listofpilotinstanceappendnewpilotinstance note line trouble k listofpilotinstance print kproductdatedate ele listofpilotinstance print eleproductdatedate eleproductdatemonth eleunitssoldperday return listofpilotinstance the put following shouldnt like i append teh first ele shoulnt overwrited so query since i append date element getting overwrited any clue i wrong thanks,1 put source variable url path cron description update source abc url cronabc schedule every minutes login admin description update source xyz url cronxyz schedule every minutes login admin webappwsgiapplication cron cronhandler class cronhandlerwebapprequesthandler def postself source something source variable,i application written python it collects parses data certain sources rss atom twitter etc new data found saved mysql database i many sources defined application checked time basis restrictions twitter queries per hour example idea cron separately passing sources arguments myscriptpy update source abc fetch parse check save data abc source myscriptpy update source xyz fetch parse check save data xyz source so far point i got working fine local cron i like get running google app engine something like cronyaml cron description update source abc url myscriptpy source abc schedule every minutes login admin description update source xyz url myscriptpy source xyz schedule every minutes login admin i found way get done app engine cron documentation any workarounds,1 use method set selfmylistboxsetlistofchoices resets list box list given choices—that current elements removed list replaced new list,i trouble updating listbox ive tried refresh update returned errors the listbox uses list get information it show initial items list however update list program running show changes live if difficulty understanding i mean please comment,2 generally declare shape list first fill values instead build list discover values your variables lot structure you got inner lists elements always order total pass fail perhaps tuples made namedtuples that way access three parts humanlyrecogizable names datatotal datapass datafail instead cryptic index numbers data data data next tuples differ prefixes spec nd addr etc these sound like keys dict rather elements list so perhaps consider making variables dict that way access particular tuple want humanlyrecognizable variables nd instead variables and access ndfail value variables nd fail instead variables import collections define namedtuple class point used point collectionsnamedtuple point total pass fail notice declare variables empty first fill values later variables keys spec nd addr pmtu icmp sections key keys page inputpage urlreference urlliburlopenpage htmlpage urlreferenceread researchr totalbtdtdtdtd htmlpage ntotal intmgroup researchr passbtdtdtdtd htmlpage npass intmgroup researchr failfontbtdtdtdtd htmlpage nfail intmgroup we create instance namedtuple righthand side store value variableskey thus building variables dict incrementally variableskeypointntotalnpassnfail,i trying grep results pages work eventually print html website someone manually look section how i would eventually use i feed function result page greps different sections i html output thats print substitute area different results ok massive edit i actually removed old code i asking many questions i fixed code taking suggestions i still interested advantage using humanreadable dict instead list here working code gets right results list lists i outputted first section eventual html block import urllib import import string import sys def ipvresultsinputpage sections specpsummaryhtml ndpsummaryhtml addrpsummaryhtml pmtupsummaryhtml icmppsummaryhtml variablesoutput sections templist page inputpage print page urlreference urlliburlopenpage htmlpage urlreferenceread researchr totalbtdtdtdtd htmlpage templistappendintmgroup researchr passbtdtdtdtd htmlpage templistappendintmgroup researchr failfontbtdtdtdtd htmlpage templistappendintmgroup variablesoutputappendtemplist print variables check print print variablesoutput print ready logo phase print section total pass fail next part eventually going output html block output stringtemplate rfcipv specs spectotal specpass specfail print outputsubstitutespectotalvariablesoutput specpassvariablesoutput specfailvariablesoutput return imagine tabbing correct i wish like paste bin suggestions welcome pasting code,2 like bash pythonscript inputtxt edit alternatively could write scripts take argv file name read you could reopen stdin file change lines,i downloaded scripts python bash prompt user command line input since i run scripts often i would like automatically supply input programs i prefer modify scripts is way without modifying original code update thanks enabrentane advice seems work pretty well i got line read password getpassgetpass password it complains following file usrlibpythongetpasspy line unixgetpass old termiostcgetattrfd copy save termioserror inappropriate ioctl device any way get around,2 since responses via stdin cat answers yourscriptpy,i downloaded scripts python bash prompt user command line input since i run scripts often i would like automatically supply input programs i prefer modify scripts is way without modifying original code update thanks enabrentane advice seems work pretty well i got line read password getpassgetpass password it complains following file usrlibpythongetpasspy line unixgetpass old termiostcgetattrfd copy save termioserror inappropriate ioctl device any way get around,1 if could embed python along script package app using something like pyapp i would imagine could addedit infoplist satisfy apple requirements signing similarly entitlements i would imagine could edit app entitlementsplist i think sandbox enforcer sandboxd language specific allowsblocks process access devices files example granting restricted file descriptors keep mind possible embedded python interpreter would default need access entitlements initialization may created sandboxing mind for ios devices must sandboxed sold store apple policy ios developer program agreement section an application may download install executable code interpreted code may used application scripts code interpreters packaged application downloaded it seems solution possible would satisfy requirement assuming similar stipulation would made os x apps however interested distributing app app store i think anything worry i much doubt require code signing entitlements running applications computer anytime soon instead sandboxing sold app store making safe place get apps,i curious know new security model os x lion affect future specifically i questioning entitlements sandboxing this question whether good ideas rather question best guess happen future i curious things like python my company makes small python app emergency situations webbased software this includes reading writing file system our app entitlements namely python code cocoa wrapping when mac app store requirements apps sandboxed list entitlements go effect i wonder apple roll update operating system say security application meet security model run secure i mixed emotions on one hand i think great making consumer machines secure less rogue code rot on hand going make development living hell lot developers methinks i also wonder update come lion update released either leopard snow leopard my thought would leopard two generations behind current os snow leopard depends long apple wants support older os so i open apple developers speak minds topic perhaps generate thoughts previously none,3 i believe werkzeug looking,which wsgi frameworks super lightweight minimal if familar ruby i looking something similar rails metal wsgi rack rails django sinatra flask rails metal,3 try r intc c playerinput lenr rappend x x r return x x,ok i made method python exactly i want really ugly repetitive needs get first integers string input return form int int int int there got better way maybe even one line using list comprehension something sort any ideas def getmoveplayerinput nextnum x x c playerinput try nextnum x intc nextnum elif nextnum intc nextnum elif nextnum x intc nextnum elif nextnum intc nextnum else return xyxy except valueerror break return xy xy thanks advance helpful comments,1 pyinstaller nice one create executables comes full pyqt support it says create executables windows osx linux i never used anything windows for windows quite painless easy,we designing open source ui controller application plone cms the application would simple startstop dialog window plone daemon process mainly aimed windows users however hoping use app osx linux we create code python qt application feel unsure deployment process in optimal case hope create static builds exe windows dmg osx megabyte qt included tiny python script maximize ease end user are examples scripts etc build qt friendly installers crossplatform what best practices consider,2 here want using regular expression simple list comprehension this pretty robust nasty input it complies request first integers string input finding first integers input separated any nonnumerical characters import def getmoveplayerinput research dddddddd playerinput nums intx x mgroups else raise valueerrorinvalid argument return nums numsnums nums examples inputoutput input wfxx output input output input ouptut note this always try best get numbers input instead raising valueerror choose numbers if come strict requirements input format regular expression match tweaked avoid problem if i misinterpreting input format let know i fix expression avoid behavior,ok i made method python exactly i want really ugly repetitive needs get first integers string input return form int int int int there got better way maybe even one line using list comprehension something sort any ideas def getmoveplayerinput nextnum x x c playerinput try nextnum x intc nextnum elif nextnum intc nextnum elif nextnum x intc nextnum elif nextnum intc nextnum else return xyxy except valueerror break return xy xy thanks advance helpful comments,1 wsgi interface it requires container eg modwsgi application eg django optional middleware applications built directly wsgi built top frameworks django handle wsgi bit don use builtin web server frameworks they usually designed performance usually integrate well nonwsgi parts server,i need create simple website server gonna running amazon ec web service but i done web development it seems like i need learn lot stuff javascript html css web framework wsgi apache web server etc and i confused stuff seems much so first question can anyone tell exactly i need set website is web framework thing i need server side th question i gonna use python server side really bunch web frameworks python what difference apache http server builtin wsgi http web servers web frameworks th question is wsgi best choice most web frameworks support wsgi mean wsgi built web frameworks or i need include modwsgi something alike also according benchmark python wsgi servers gevent modwsgi show great performance low memory footprint they claim web frameworks difference web frameworks like cherrypy webpy thanks,1 try export ccusrbingcc python setuppy build,i trying build python module scikittimeseries using python setuppy build erroring like versionslibpythonsitepackagesnumpycoreinclude ilibraryframeworkspythonframeworkversionsincludepython c gcc scikitstimeseriessrccseriesc sh gcc command found this i osx lion gcc exit gcc though gcc version based apple inc build llvm build aliased gcc gcc how i tell setuppy look gcc instead gcc thanks,3 you could read file time read line line files csv csv csv etc f files file openf r line file ray linesplit raystrip raystrip fout open outputcsv foutwriteraystrip raystrip raystrip f n foutclose fileclose tested works may need slight modifications,i multiple csv files date filename csv csv folder the csv files common headers the csv file looks like csv x y z csv x y z csv x y z csv x y z … i want write script would read rows given row x y whole row copied new csv file along filename giving following output x y z filename na any idea done suggestions modules look examples thanks time help cheers navin,1 one way achieve want use regex url check attribute methods handler example urls map urlpatterns want map url url url rurl oneandtwohandler and example corresponding handler class oneandtwohandlercustomrequesthandler def getself myparam args kwargs myparam raise httperror code first url def postself entry args kwargs myparam raise httperror code first url i would map myparam options dictionary keep things clear avoid dive handler i need change values i want add new urls mydicturls get post intmyparam mydicturlsget get,i trying implement sort api tornado i question possible route two urls one handler separating method class handler def getself first url def postself secornd url handlers rurlhandler get allowed rurlhandler post allowed so someone trying send post first url see error message,1 this due longstanding bug fixed python late backported python the documentation states unicode strings written file converted byte strings using fileencoding but honoured sysstdout instead using default unicode encoding this usually set ascii site module changed syssetdefaultencoding python r aug gcc linux u xan sysstdoutwritea traceback recent call last file stdin line module unicodeencodeerror ascii codec cant encode character u xa reloadsyssetdefaultencoding utf sysstdoutwritea ⦠however better solution might replace sysstdout wrapper class stdoutobject def writeself string isinstancestring unicode string stringencodesysstdoutencoding sysstdoutwritestring sysstdout stdout sysstdoutwritea â¦,i start saying i already seen post strange python print behavior unicode solution offered using pythonioencoding work here issue python r apr gcc red hat linux u xa print ã‚⦠works fine however sysstdoutwritea traceback recent call last file stdin line unicodeencodeerror ascii codec encode character u xa position ordinal range throws error the post i linked top suggests default console encoding ascii however case sysstdoutencoding utf so thoughts work fix issue thanks d,3 it seems sphinx installed python support although various ways install sphinx python use virtualenv create custom environment uses python default virtualenv p pathtopython foo and inside virtualenv install sphinx pip install sphinx as bonus approach allows create custom environments different projects ps you might want consider using virtualenvwrapper,i try create documentation project written python x sphinx tool i want use according official site last version compatible python my os archlinux linux distribution uses python default python package the installation configuration straight forward easyinstall u sphinx sphinxquickinstall i never asked choose x x python interpreter but i ask sphinx create documentation project code analyzed i wrote python x is sphinx ready python x did i make mistake,1 this job import glob import os outfile open outputcsv w outfilewrite x y z filenamen filename globglob csv filename outputcsv skip file writing continue openfilename r infile count lineno line infile lineno lineno skip header line continue fields linesplit x intfields intfields z floatfields x outfilewrite g sn x z filename count count handle case lines found outfilewrite na sn filename outfileclose note control trust file format may want handle exceptions thrown conversions intfloat,i multiple csv files date filename csv csv folder the csv files common headers the csv file looks like csv x y z csv x y z csv x y z csv x y z … i want write script would read rows given row x y whole row copied new csv file along filename giving following output x y z filename na any idea done suggestions modules look examples thanks time help cheers navin,1 in general multiprocessing easiest use functional style in case suggestion would return list result tuples instance worker function the extra complexity nested defaultdict really gain anything something like import sys collections import defaultdict multiprocessing import pool queue import globalconcordance defaultdictlambda defaultdictlambda defaultdictlist def concordanceworkerindexsentence sentindex sentence indexsentence words sentencesplit return word coloword coloindex sentindex word enumeratewords coloindex coloword enumeratewordsi def buildconcordancesentences global globalconcordance pool pool results poolmapconcordanceworker enumeratesentences result results word coloword coloindex sentindex result globalconcordancewordcolowordcoloindexappendsentindex print lenglobalconcordance def main sentences sentence sentence sentence sentence buildconcordancesentences name main main let know generate looking,i serial code like computes word concordances ie counting collocated word pairs the following program works except list sentences canned illustrative purposes import sys collections import defaultdict globalconcordance defaultdictlambda defaultdictlambda defaultdictlambda def buildconcordancesentences global globalconcordance sentenceindex sentence enumeratesentences words word word sentencesplit index word enumeratewords collocate enumeratewordsindexlenwords globalconcordancewordcollocateiappendsentenceindex def main sentences sentence sentence sentence sentence buildconcordancesentences print globalconcordance name main main to first loop parallelized numbers computed indepedent however data structure modified global one i tried using python pool module i facing pickling problems makes wonder i using right design pattern can someone suggest good way parallelize code,1 this wellformed question logic apparent for someone provide finished code would defeat purpose assignment first add homework tag question think want loop files keeping track filename opened read lines current file selection criteria x met write line to get started try import csv os fn oslistdir csv fn openfn r newline f reader csvreaderf delimiter row reader then extend solution open output file write selected lines using csvwriter,i multiple csv files date filename csv csv folder the csv files common headers the csv file looks like csv x y z csv x y z csv x y z csv x y z … i want write script would read rows given row x y whole row copied new csv file along filename giving following output x y z filename na any idea done suggestions modules look examples thanks time help cheers navin,2 i seriously doubt parallelizing calculation give benefit besides learning parallelization the data structure using efficient terms memory usage python dictionaries large memory overhead creating lot also adding large number items concordance sentence i think able eat computer ram running program minutes something like single chapter book this cause process grind halt crash have actually tried running large set inputs seeing happens if case irrelevant whether computation done parallel i think need find better way storing output parallelization real benefit only turn parallelization methods optimization actually witnessed diagnosed problem,i serial code like computes word concordances ie counting collocated word pairs the following program works except list sentences canned illustrative purposes import sys collections import defaultdict globalconcordance defaultdictlambda defaultdictlambda defaultdictlambda def buildconcordancesentences global globalconcordance sentenceindex sentence enumeratesentences words word word sentencesplit index word enumeratewords collocate enumeratewordsindexlenwords globalconcordancewordcollocateiappendsentenceindex def main sentences sentence sentence sentence sentence buildconcordancesentences print globalconcordance name main main to first loop parallelized numbers computed indepedent however data structure modified global one i tried using python pool module i facing pickling problems makes wonder i using right design pattern can someone suggest good way parallelize code,1 this sortedlst keylambda x x profile firstname,i want sort firstname list python list profile firstname lastname b profile firstname c lastname profile firstname e lastname f,3 use database storing values first add sentences one table ids you may call eg sentences second create table words contained within sentences call eg words give word id saving connection sentences table records words table records within separate table call eg sentenceswords two columns preferably wordid sentenceid when searching sentences containing mentioned words job simplified you first find records words table words exactly ones search the query could look like select id from words where word in word word word second find sentenceid values table sentences required wordid values corresponding words words table the initial query could look like select sentenceid wordid from sentenceswords where wordid in goes list words ids could simplified select sentenceid wordid from sentenceswords where wordid in select id from words where word in word word word filter result within python return sentenceid values required wordid ids need this basically solution based storing big amount data form best suited database edit if search two words even almost everything dbms side considering need also position difference store position word within third column sentenceswords table lets call position searching appropriate words calculate difference value associated words,this came another question i figured best ask separate question give large list sentences order thousands this sentence example this sentence another example this sentence this sentence another example this sentence best way code following function def getsentencesword word position return given two words word word position position function return list sentences satisfying constraint for example getsentencessentence another return sentences index sentences my current approach using dictionary like index defaultdictlambda defaultdictlambda defaultdictlambda sentenceindex sentence enumeratesentences words sentencesplit index word enumeratewords word enumeratewordsindex indexwordwordiappendsentenceindex but quickly blows everything proportion dataset mb size gb ram exhausted less minutes i somehow get feeling common problem find references solve efficiently any suggestions approach,3 you render web pages using jinja way would use python library twisted you call this work fine twisted although may run performance issues jinja something blocking note possible use blocking libraries twisted fine either via defertothread blocking mainloop performance problem so i inferring question really use jinja without blocking jinja templating library means reads template invokes view logic template writes html output so things block reading template writing result running view logic application code i know jinja i know exactly apis things structured i tell guess part easy i going give general answer rdparty templating libraries twisted so i address concerns although quite order reading template really reasonable thing care reading template probably really fast these frequentlyaccessed tiny files operating system almost certainly keeping filesystem cache it unlikely ever going block reading unless something nuts like putting nfs if profile application find problem – let say extremely slow disks remote filesystem – read template cstringio something similar startup time feed jinja writing response web pages big twisted provide blocking api write sockets instead offers api buffers whole result memory written my suggestion basically thing reading template unless seriously huge output probably fine burn little bit ram response fed client running view logic this area likely run problems jinja probably handle results deferred but actually actually jinja going give problems directly storm storm expects able block make database queries access certain attributes talking database blocks signifiant source blocking io web applications so need decide going deal you options just main thread worry maybe application workgroup people database local sure io going block still meets performance requirements cares not every application scale moon back prefetch everything storm defertothread call similar make sure jinja accessing objects memory this way run renderers main thread callback deferred database io if accessing objects memory renderer still might take little fine this question prompted post article blog distinction blocking running hanging draft quite may want go read do whole render thread subprocess treat blocking component program this loses benefits using twisted still perfectly viable strategy integrate blocking jinjastorm component nonblocking puretwisted component actual chatmessage relaying part if none options work twisted included templating library support deferred since version you may consider using twistedwebtemplate alternative jinja,i planning discussion software using python twisted storm jinja the problem jinja made twisted asynchronous socket libraries performance provided using twisted i plan using flask so i twisted render webpages using jinja,3 the default implementation qtexteditzoominout simply changes pointsize base font textedit the method used example change font size wraps selected word span tag uses inline css set fontsize property fixed value this means textedit subsequently zoomed unchanged text affected it would possible overcome problem using relative font sizes however looks like limted subset css properties supported possible set imprecise values like small large etc this implemented example making following changes font size selfcombosize qtguiqcomboboxselftoolbar selftoolbaraddwidgetselfcombosize selfcombosizeadditem small selfcombosizeadditem medium selfcombosizeadditem large selfcombosizeadditem xlarge selfcombosizeadditem xxlarge selfcombosizesetcurrentindex selfcombosizeactivatedintconnectselftextsize def textsizeself size fmt qtguiqtextcharformat fmtsetpropertyqtguiqtextformatfontsizeadjustment size selfmergeformatonwordorselectionfmt,this code runs little window toolbar qtextedit area if highlight bananas change font size using zoom either toolbar buttons ctrl mouse wheel resize apples anyone know pyside import qtgui qtcore class mainwindowqtguiqmainwindow def initself parentnone supermainwindow selfinitparent selftextedit editorself selftoolbar qtguiqtoolbarself selfaddtoolbarselftoolbar selfsetcentralwidgetselftextedit selftexteditsethtml font colorblueapples bananasfont zoom selfactionzoomin qtguiqaction zoom in self selfactionzoomout qtguiqaction zoom out self selftoolbaraddactionselfactionzoomin selftoolbaraddactionselfactionzoomout selfactionzoomintriggeredconnectselfonzoominclicked selfactionzoomouttriggeredconnectselfonzoomoutclicked font size selfcombosize qtguiqcomboboxselftoolbar selftoolbaraddwidgetselfcombosize selfcombosizeadditem selfcombosizeadditem selfcombosizeadditem selfcombosizeadditem selfcombosizeadditem selfcombosizesetcurrentindex selfcombosizeactivatedstrconnectselftextsize def textsizeself pointsize pointsize intpointsize pointsize fmt qtguiqtextcharformat fmtsetfontpointsizepointsize selfmergeformatonwordorselectionfmt def mergeformatonwordorselectionself format cursor selftextedittextcursor cursorhasselection cursorselectqtguiqtextcursorwordundercursor cursormergecharformatformat selftexteditmergecurrentcharformatformat def onzoominclickedself selftexteditzoom def onzoomoutclickedself selftexteditzoom class editorqtguiqtextedit def initself parentnone supereditor selfinitparent selfzoomvalue def zoomself delta zoomincrement delta zoomincrement zoomincrement selfzoominzoomincrement selfzoomvalue selfzoomvalue zoomincrement print selfzoomvalue selfzoomvalue def wheeleventself event eventmodifiers amp qtcoreqtcontrolmodifier selfzoomeventdelta name main app qtguiqapplication window mainwindow windowresize windowshow appexec,1 here i python though assuming needs done dbms right tool job however seems work pretty well million rows sentences this sentence example this sentence another example this sentence this sentence another example this sentence sentences sentences sentencesprocessed def preprocess global sentences global sentencesprocessed may want regex split whitespace sentencesprocessed sentencesplit sentence sentences deallocate sentences sentences none def getsentencesword word position results sentenceindex sentence enumeratesentencesprocessed wordindex word enumeratesentenceposition word word sentencewordindex position word resultsappendsentenceindex return results def main preprocess results getsentencessentence another print got lenresults results name main main,this came another question i figured best ask separate question give large list sentences order thousands this sentence example this sentence another example this sentence this sentence another example this sentence best way code following function def getsentencesword word position return given two words word word position position function return list sentences satisfying constraint for example getsentencessentence another return sentences index sentences my current approach using dictionary like index defaultdictlambda defaultdictlambda defaultdictlambda sentenceindex sentence enumeratesentences words sentencesplit index word enumeratewords word enumeratewordsindex indexwordwordiappendsentenceindex but quickly blows everything proportion dataset mb size gb ram exhausted less minutes i somehow get feeling common problem find references solve efficiently any suggestions approach,1 may getting point def montecarlostarter x result dictwln range x wln startertransstarter result w w result l l result n n return result return result w floatxresult l floatxresult n floatx,working python i argument takes list adds values argument list list team compares certain positional values returns win loss tie depending upon values def startertransstarter wins losses nd team randomshuffleteam zipteam starter textends scoreaddteam exitscoreteam starter length lenstarter range length teami teami teami teami wins elif teami teami teami losses elif teami teami teami nd return wins losses nd i want able simulate results many times using randomshuffleteam randomly order team list i using def montecarlostarter x range x print startertransstarter but i would like able sum wins losses ties simulations divide number simulations case x get average wins losses ties simulations i tried changing startertrans function totalwins variable equal wins i able figure any ideas,1 most projects would hierarchy eg projectpackagemoduleclass selectively run tests item levels report covers parts detail see statuses quite clearly most time entire package class fails implemented also in many test frameworks disable individual test cases removing annotationdecoration renaming methodfunction performs test this disadvantage showing implementation progress though decide fixed specific prefix probably grep info test source tree quite easily having said i would welcome test framework make distinction notimplemented addition standard test case status codes like pass warning failed i guess might,if middle tdd iteration know tests fail existing code genuinely incorrect fail either test features implemented yet please say care fix i ready move past mindset my general practice writing tests follows first i architect general structure test suite whole part that i go write names tests reminding features i intend implement i typically least python simply start testing one line selffail this way i ride stream consciousness listing every feature i think i want test say tests time second i pick one test actually write test logic third i run test runner see failures simply selffail genuine assertionerror fourth i write code causes test pass fifth i run test runner see pass failures sixth i go step ideally instead seeing tests terms passes failures exceptions i like fourth possibility notimplemented what best practice,1 i use piece paper create test list scratchpad keep track tests i miss i hope writing failing tests one go cause amount thrashing new knowledge comes redgreenrefactor cycle to mark test todo not implemented could also mark test equivalent ignorepending ignoretodo nunit example would tests yellow instead failed so red implies test failure yellow implies todo,if middle tdd iteration know tests fail existing code genuinely incorrect fail either test features implemented yet please say care fix i ready move past mindset my general practice writing tests follows first i architect general structure test suite whole part that i go write names tests reminding features i intend implement i typically least python simply start testing one line selffail this way i ride stream consciousness listing every feature i think i want test say tests time second i pick one test actually write test logic third i run test runner see failures simply selffail genuine assertionerror fourth i write code causes test pass fifth i run test runner see pass failures sixth i go step ideally instead seeing tests terms passes failures exceptions i like fourth possibility notimplemented what best practice,1 static class methods defined tpmethods adding methstatic methclass mlflags field pymethoddef structure this equivalent staticmethod classmethod decorators the first parameter method normally instance pointer null static methods pytypeobject class methods httpdocspythonorgcapistructureshtmlpymethoddef class attributes added setting tpdict dictionary attributes calling pytypeready module initialization function alternatively tpdict left null case pytypeready create dict the attributes added dict httpdocspythonorgcapitypeobjhtmltpdict computed class attributes require descriptor class exactly python an instance descriptor added tpdict class attributes,how would one go specifying static method variable python class cpython c in pytypeobject structure tpgetset tpmethods tpmembers seem assume instance class thanks much rob,1 the library called wxwidgets created exactly “wx” stands windows x their history page info the python bindings wxpython probably know apparently feels like another heavyweight gui library “just” wraps native gtkqtwindows widgets,i seen python pygtk vs pyqt vs wxpython vs tkinter question slightly different for instance i use ubuntu gnome pythonqt default installed i want use pythonqt application i download pythonqt plus qt libraries i expect may something similar kde desktops well often i need produce simple gui i like able run anywhere python however user already libraries i say use for complicated stuff obviously allencompassing wrapper would viable libraries crossplatform simple stuff like hello work examples maybe something already exists in comparison examples i imagine something like pseudocode appgui getcrossplatformgui mw appguigetmainwindow button appguigetbuttonargs appguiconnectbutton args appguishowbutton getcrossplatformgui linux would first look pythonqt found pythongtk wxwindows tkinter windows maybe different order etc would deliver windowapplication library found system defaulting cases tkinter i understand always built python many thanks advance answers cheers nbsp hellopyqtpy usrbinenv python httpenwikibooksorgwikipythonprogrammingpyqthellocworld import sys pyqt import qt qtcore def sayhello print hello world qtqapplicationsysargv hellobutton qtqpushbuttonsay hello world none aconnecthellobutton qtsignalclicked sayhello hellobuttonclickedconnectqtcoreqcoreapplicationinstancequit hellobuttonshow aexec hellopygtkpy usrbinenv python httpwwwpygtkorgpygtktutorialexampleshelloworldpy import pygtk pygtkrequire import gtk this callback function the data arguments ignored example more callbacks def sayhellowidget datanone print hello world def destroywidget datanone gtkmainquit window gtkwindowgtkwindowtoplevel windowconnectdestroy destroy hellobutton gtkbuttonsay hello world hellobuttonconnectclicked sayhello none hellobuttonconnectobjectclicked gtkwidgetdestroy window windowaddhellobutton hellobuttonshow windowshow gtkmain,3 a number tdd tools idea pending tests vs failing tests i think unittest makes distinction i think write def testthisthingself pass memory edit in unittest unittest mark test skip unittestexpectedfailure decorator see documentation,if middle tdd iteration know tests fail existing code genuinely incorrect fail either test features implemented yet please say care fix i ready move past mindset my general practice writing tests follows first i architect general structure test suite whole part that i go write names tests reminding features i intend implement i typically least python simply start testing one line selffail this way i ride stream consciousness listing every feature i think i want test say tests time second i pick one test actually write test logic third i run test runner see failures simply selffail genuine assertionerror fourth i write code causes test pass fifth i run test runner see pass failures sixth i go step ideally instead seeing tests terms passes failures exceptions i like fourth possibility notimplemented what best practice,2 our dms software reengineering toolkit could it accepts language definitions ebnf builds asts allow apply source source transformations ast regenerate text ast you need ebnf regular expression easy,i write regular expressions match tokenizable text cumbersome add amount whitespace insignificant required what i like function accepts regex list delimiter tokens add whitespace matching for example makewhitespaceregexfoowadelimiters return foossswssas maybe already better way achieve rather hacking existing regex i think using full parser generator would overkill i using python thanks,1 why install pyopenssl,i trying get https webpagefor eg httpsgithubcomtwitterbootstrap using urlopen returns page without problem but evaluating twisted new project trying use getpage fetch page but seems requires openssl module exceptionsimporterror no module named openssl is way get getpage without openssl module get https page way urlopen returns,1 if want keep limited area reimplement itemchanged declare ifndef graphich define graphich include qgraphicsrectitem class graphic public qgraphicsrectitem public graphicconst qrectf amp rect qgraphicsitem parent protected virtual qvariant itemchange graphicsitemchange change const qvariant amp value endif graphich implementation itemsendsgeometrychanges flag needed capture change position qgraphicsitem include graphich include qgraphicsscene graphicgraphicconst qrectf amp rect qgraphicsitem parent qgraphicsrectitemrectparent setflagsqgraphicsitemitemismovable qgraphicsitemitemsendsgeometrychanges qvariant graphicitemchange graphicsitemchange change const qvariant amp value change itempositionchange ampamp scene value new position qpointf newpos valuetopointf qrectf rect scenescenerect rectcontainsnewpos keep item inside scene rect newpossetxqminrectright qmaxnewposx rectleft newpossetyqminrectbottom qmaxnewposy recttop return newpos return qgraphicsitemitemchangechange value then define rectangle scene case x mainwindowmainwindowqwidget parent qmainwindowparent qgraphicsview view new qgraphicsviewthis qgraphicsscene scene new qgraphicssceneview scenesetscenerect viewsetscenescene setcentralwidgetview resize graphic graphic new graphicqrectf sceneadditemgraphic graphicsetpos this keep graph within area good luck,is way restrict area qgraphicsitem like qrect moved setflagitemismovable set i new pyqt trying find way move item mouse restrict verticallyhorizontally thanks,2 to sort list use lstsortkeylambda x x profile firstname to keep lst unsorted return sorted list use sortedlst keylambda x x profile firstname,i want sort firstname list python list profile firstname lastname b profile firstname c lastname profile firstname e lastname f,3 well specification actually randomly uppercase characters inclined could achieve following list comprehension import random join randomchoicekupper k k may nicer ways,i try append text strings randomly instead output like david i end something like david david code right import random import string print name year textfile opennamestxt r line textfile print linestripjoinrandomchoicestringdigits x range randomrandint outports john i want string somthing like john john john john,3 probably want something like import random lol lol apples def randomupperc randomrandom return cupper return clower lol joinmaprandomupper lol edit as pointed shawn chin comments simplified lol joincupper crandom c lol very cool slower using map edit running timer tests seems join randomchoicekupper k k times slower map method anyone confirm times map map randomchoice,i try append text strings randomly instead output like david i end something like david david code right import random import string print name year textfile opennamestxt r line textfile print linestripjoinrandomchoicestringdigits x range randomrandint outports john i want string somthing like john john john john,1 nobody able answer specific question depends lot factors when performance issue measure time spend function spot bottlenecks it called profiling nice tutorial python built profiler httpdocspythonorglibraryprofilehtml you looking two kind information functions spend time inside including calls function obviously first one list main since program runs inside still may spot function consume think functions spend time inside excluding calls functions there basic functions those called often etc again results surprise investigate eyes find time spend tkinter internals may use wrong way try isolate small stand alone program making calls tkinter showing similar performance issue post the profiling information useful task,in school create game using python tkinter group project since program getting rather large i want know problem caused tkinter trying search problems program the problem start creating units multiple units display time let say created using createrectangle method start moving around gets really choppy on part game displaying time couple elements using small gifs multiple menus canvas units i mentionned small buildings also using small gifs we use method callback method deletes everything canvas redraws buildings units correct positions every milliseconds should something easily handled tkinter problem program,3 to understand code first need understand list comprehensions generator expressions here example simple list comprehension stri range as see one line equivalent following regular loop lst range lstappendstri basically shorthand creating lists generator expressions similar except instead returning list return generator yield values list comprehension without actually creating full list this efficient going loop values now background way could expand code using regular loops def convexhullpts returns points convex hull pts ccw order xrangelenpts hulls xrange lenpts hullsappendgrahamscanptsii code as comment ptsii taking slice list index index basically read slices like first index include first index exclude step this answer pretty good explanation examples,i code understanding problem related python def convexhullpts returns points convex hull pts ccw order xrangelenpts hulls grahamscanptsii xrange lenpts code i figure two supposed work sadly command reference show usage example i really tell really means one left side assignment additionally could bottom assignment possibly mean does statement return value thanks sorry beginner question,3 i suposse asking wxnotebook talk tabs then use method getpagetext,i know use getselection get selected tab however return tab number would like get tab label i using print selfgetselection,1 i hit problem time ago i created snippet help def getvaluesinstance gointo exclude extra transforms django model instance object used serialization also transforms datetimes timestamps param instancedjangodbmodelsmodel model question param gointo relations models need expanding param exclude fields ignored param extra additional functionsproperties fields usage getvaluesmymodelobjectsgetpk user gointo clan exclude crestblob extra getcrestpath image so could use something like simplejsondumpsgetvaluesprojectsobjectsall gointo projectmanager gointo teams disclaimer i made script purposes may perfect may require modifications fit needs,i models class projectsmodelsmodel projectname modelscharfieldmaxlength uniquetruedbindextrue projectmanager embeddedmodelfield users class teamsmodelsmodel teamtype modelscharfieldmaxlength teamleader embeddedmodelfield users teamproject embeddedmodelfield projects class usersmodelsmodel name modelscharfieldmaxlength uniquetrue designation modelscharfieldmaxlength teams listfieldembeddedmodelfield teams i need return json view projects objects relations users teamsmy viewspy code djangocore import serializers data serializersserialize json projectsobjectsall this output json project object doesnot return json user object like pk ebbdedb model restapiprojects fields projectname hello projectmanager users object how i convert user object json well,1 try import os print ospathisfilercusersdesktopkkfasta output true try replace string original code see works if make sure typo path small r means raw it escape make sure path valid n become newline,i trying parse fasta file biopython using following codehow i solve error bio import seqio handle opencusersdesktopkkfasta ru file pyshell line module ioerror errno no file directory kkfasta i getting error but file already i using windows os python biopython any suggestions please,1 lets say data data b c you use dataitems method get dictionary elements note django templates not put also users mentioned values work case try valuesitems table tr tdatd tdbtd tdctd tr key values dataitems tr tdkeytd v values tdvtd endfor tr endfor table am pretty sure extend logic specific dict to iterate dict keys sorted order first sort python iterate amp render django template return rendertoresponse somepagehtml data sorteddataitems in template file key value data tr td key key td td value value td tr endfor,my dictionary looks like thisdictionary within dictionary chosenunit cost decimal unitnameabbrev u g supplier supplier usteve meat locker price decimal supplier address u nornaddress chosenunitamount u city name u joburg central supplier phonenumber u supplier website none supplier pricelist u supplier email u ssssssssssscom unit name u gram name u rump bone now i trying display information template i struggling my code template looks like landingdictingredients hr ingredient landingdictingredients ingredient endfor hrefprint landingdictrecipename else please search ingredient endif it shows template i also tried ingredient landingdictingredients ingredientcost endfor this even display result i thought perhaps i need iterate one level deeper tried landingdictingredients hr ingredient landingdictingredients field ingredient field endfor endfor hrefprint landingdictrecipename else please search ingredient endif but display anything what i wrong,3 just update unutbu said new code python def checkconnectivityreference try urllibrequesturlopenreference timeout return true except urllibrequesturlerror return false and note input reference url want check i suggest choosing something connects fast live ie i live south korea i would probably set reference httpwwwnavercom,i want see i access online api i need internet access how i see connection available active using python,3 in words array xn want subsets sumsubset sumx right that probably means whole set qualifies after drop element k xk sumx every coalition fine answer after proceed dropping elements one one stopping reached half sum this obviously effective solution want drop kk already tried kk —but i believe handle,i looking algorithm implemented c c python java calculates set winning coalitions n agents agent different amount votes i would appreciate hints thanks,2 keepleft returns list hull initially empty turns going left removed the current point added unless already last element list third parameter reduce it initial accumulator value passed keepleft thus making hull end lh uh initially empty it performs graham scan first sorting points going points twice lh uh stand lower half upper half sweep points accumulated list the points accumulated reduce result originally empty points passed keepleft one one sorted order point points causing right turn removed accumulated list then current point added accumulated list the return value keepleft bit tricky lenhull returns true list empty hull r checks r current point last element list hullappendr boolean expression side effect appending r list looks bit dirty last element hull r hull returned without appending r put words due short circuiting hull always returned r appended returning last element the logic easy implement nicer yet verbose way,i struggling understand reduce call written python i found several sources elsewhere state function equivalent aggregate lists c i unable understand calls actually expect possibly i really figure keepleft returns so anybody help telling keepleft return mean reduce call many thanks turnleft turnright turnnone def turnp q r returns pqr forms right straight left turn return cmpq pr p r pq p def keeplefthull r lenhull turnhull hull r turnleft hullpop return lenhull hull r hullappendr hull def grahamscanpoints returns points convex hull array points ccw order pointssort lh reducekeepleft points uh reducekeepleft reversedpoints return lhextenduhi xrange lenuh lh,2 i used solution search replace line file python tempfile import mkstemp shutil import move os import remove close def replacelinefile newrdline newlinen create temp file fh abspath mkstemp newfile openabspath w oldfile openfile counter line oldfile counter counter counter newfilewritenewrdline else newfilewriteline close temp file newfileclose closefh oldfileclose remove original file removefile move new file moveabspath file replaceline tmpann but work files contains non english charecters traceback recent call last file dxxxreplacepy line module replaceline tmpann file dxxxreplacepy line replaceline line oldfile file cpythonlibencodingscppy line decode return codecscharmapdecodeinputselferrorsdecodingtable unicodedecodeerror charmap codec decode byte x position character maps undefined that bad where python unicode file utf python file ñ„ð²ñ‹ð°ñ„ñ‹ð² sdadf 试试 阿斯达ð° 阿斯顿飞,i several files i need replace third line files filetxt filetxt newrdline new third line what best way files big enough several mb files,1 are looking dictionary mapping strings lists cars chevrolet toyota hummer ferrari computers mac windows linux amstrad dcars chevrolet toyota hummer ferrari,i looking python data structure equivalent dictionary i associate key for example i want associate cars chevrolet toyota hummer ferrari computer mac windows linux amstrad i need able search dictionary string cars computers others using something like mydictionaryhas cars loop keys corresponding cars using key mydictionary,2 probably looking something like print x print outputs x for question i think answer read data column actually expect string left aligned ab abc ab abc also text books left aligned for number natural formatting right aligned which istance way arranging numbers sum subtraction multiplication python choice actually reflects typographic conventions mixing text numbers table may considered special case,while thinking way pretty print table header found integers right aligned default strings left aligned for example x printformati x this easily fixed setting alignment explicitly wonder edit i looking way align strings easy x printformati x i thought objects would aligned way deafult asking,1 primes primes expensive it copies every element every pass loop converting elegant dynamic programming solution on algorithm use lists instead primes primesappendi also exit loop early passing sqrti and since guaranteed pass sqrti running end list primes update list inplace rather storing isprime later consumption j mathsqrti primesappendi break ij break finally though nothing performance pythonic use range instead range,this code python calculation sum prime numbers less given number what i optimize import math primes primes store prime numbers xrange test number x mathsqrti isprime true j primes j devider primes used deviders j x ij isprime false break isprime primesappendi print sum primes,2 another thing could optimize move sqrt computation outside inner loop after stays constant need recompute sqrti every time,this code python calculation sum prime numbers less given number what i optimize import math primes primes store prime numbers xrange test number x mathsqrti isprime true j primes j devider primes used deviders j x ij isprime false break isprime primesappendi print sum primes,2 on receive buffer content when rn comes get tweet stored mongodb def ontweetdata tweet jsonloadsdata dbpostsinserttweet buffer def onreceivedata buffer datastrip dataendswithrn buffer ontweetbuffer buffer edit i though using old streaming api ontweet function enough,i python noob working less hours i trying read twitter data store mongo database i getting following error traceback recent call last file twittestpy line onreceive dbpostsinsertdata file librarypythonsitepackagespymongopymacosxuniversaleggpymongocollectionpy line insert file librarypythonsitepackagespymongopymacosxuniversaleggpymongodatabasepy line fixincoming file librarypythonsitepackagespymongopymacosxuniversaleggpymongosonmanipulatorpy line transformincoming typeerror str object support item assignment traceback recent call last file twittestpy line module connperform my code simple import pycurl json import pymongo streamurl httpsstreamtwittercomstatusessamplejson user xxxxxxxx pass xxxxxxxx def ontweetdata tweet jsonloadsdata dbpostsinserttweet pymongo import connection connection connection db connectiontest conn pycurlcurl connsetoptpycurluserpwd ss user pass connsetoptpycurlurl streamurl connsetoptpycurlwritefunction ontweet connperform i sure very simple fix hope guys help thanks,1 can also done via getxpathcount ex numberofrow browsergetxpathcounttbodytr i checked code i think work,i structure table tbody tr id classon tr tr id tr tr id tr tr id tr tr id tr tr id tr tr id tr tbody i would like count number lines table i using python script the xpath table xpathhtmlbodyformdivdivdivdivdivdivtable anyone could help thank much regards vincent,2 you use different algorithm called sieve eratosthenes faster take memory keep array flags signifying whether number prime new prime set zero multiples prime n initialize array flags isprime num xrangen isprime indexing starts zero isprime one prime mark multiples def setprimenum num prime set multiples isprime zero x xrangenum n num isprimex iterate integers n update isprime array accordingly num xrangen isprimenum setprimenum primes num num xrangen isprimenum you actually pretty large n use efficient bit array example scroll page find sieve eratosthenes example,this code python calculation sum prime numbers less given number what i optimize import math primes primes store prime numbers xrange test number x mathsqrti isprime true j primes j devider primes used deviders j x ij isprime false break isprime primesappendi print sum primes,2 if i understand problem c program calls python when python finishes executing function want pause interpreter pick c code left some time later c program needs cal back python python interpreter pick left i think easily one thread before pause interpreter stack looks like top stack interpreter frames c frames to pause interpreter need save interpreter frames jump back topmost c frame then unpause need restore interpreter frames jump stack left jumping doable see httpenwikipediaorgwikisetjmph saving restoring stack harder i know api however could two threads the thread created start c program call thread runs c code creates thread run python interpreter initially running c code thread executing thread blocked say condition variable see httpscomputingllnlgovtutorialspthreads when run unpause interpreter thread signals condition variable waits this wakes thread runs interpreter causes thread block when interpreter needs pause thread signals condition variable waits thread blocks thread wakes you bounce back forth threads heart content hope helps,i would like use profiling functions python c api catch python interpreter returns specific functions i would like pause python interpreter send execution back function called interpreter c program finally return execution python interpreter starting line code stopped i would like maintain globals locals times execution belongs python part i finished part question i know save i return execution return execution given saved data from i could get python api docs i save part executing frame i found anything some additional questions what exactly pyframeobject contain the python api docs surprisingly never explain,1 you add label mainwindow the easiest solution lblqtguiqlabelself and proper solution using layout window appropriate size add lblsetpixmapp layout qtguiqhboxlayoutself layoutaddwidgetlbl,why code show window without image i try use qbytearray instead stringio result anyone know answer import sys pyqt import qtgui qtcore stringio import stringio class exampleqtguiqwidget def initself superexample selfinit selfinitui def inituiself csstringio cswriteopenimagejpeg rb read p qtguiqpixmap ploadfromdatacsgetvalue lblqtguiqlabel lblsetpixmapp layout qtguiqhboxlayoutself layoutaddwidgetlbl selfmove selfsetwindowtitle picture selfshow app qtguiqapplicationsysargv ex example sysexitappexec update i need show image stringio another object ram downloading pycurl without saving hdd update added layout using like petr viktorin advised code still working update petr viktorin code work want display png file image jpegjpg see empty form maybe problem qpixmap update tested various images httpitinypiccommqdjpg where problem,2 it nice think solving separating two cases recursively find winning coalitions including last agent without last agent now subproblems logic applied lower target number votes case last agent included stop recursion target number votes lower equal zero agents left note algorithm ordering agents according number votes beneficial example implmentation itertools import combinations def winningcoalitionsagents targetvotes recursive solving function param agents sequence name votes pairs param targetvotes minimum number votes coalition targetvotes stop recursion coalitionsize rangelenagents coalition combinationsagents coalitionsize yield coalition elif agents pass agents possible coalitions else agentname agentvotes agents agents agents coalition winningcoalitionsagents targetvotesagentvotes yield agentname agentvotes coalition sumvotes name votes coalition targetvotes yield coalition def winningcoalitionsagents find coalitions least targetvotes combined votes param agents dictionary form name number votes targetvotes sumagentsvalues agents sortedagentsitems keyoperatoritemgetter coalitions winningcoalitionsagents targetvotes return sortedsortedname name votes c c coalitions and python interpreter agents alice bob charlie dave divide sum votes rounding targetvotes sumagentsvalues solve coalitions winningcoalitionsagents targetvotes sortedsortedc c coalitions alice bob charlie alice bob charlie dave alice bob dave alice charlie alice charlie dave bob charlie bob charlie dave charlie dave,i looking algorithm implemented c c python java calculates set winning coalitions n agents agent different amount votes i would appreciate hints thanks,1 in idle menu go options configure idle general under at startup select open edit window instead open shell window hit apply ok idle save setting open editor window open file,python windows built support right clicking py file selecting edit idle instead usual action running file how i accomplish setup linux i running mint julia debiantype distribution selecting default program shortcut menu allow select idle open interpreter chevron file i want edit can i set open idle selection forgo interpreter i decide run file thanks,1 the nothingfancy way methods i post probably best way modulepy def initialize print initialize def dothethingargs print things args def functionargs functionargs def firsttimeargs global function initialize dothethingargs functiondothething functionfirsttime the idea simple add layer indirection function always calls function function points first firsttime forever dothething testpy module import function function function running testpy yields initialize things things my first thought use generator triptych points way pass args function use generator so way using coroutine unlike generator allows send args well receive values coroutine modulepy def coroutinefunc httpwwwdabeazcomcoroutinesindexhtml def startargskwargs cr funcargskwargs crnext return cr return start def initialize print initialize def dothethingargs kwargs print things args kwargs return result args coroutine def function args kwargs yield initialize true args kwargs yield dothethingargs kwargs function functionsend def functionargs kwargs this purely overcome limitation send accept argument return functionargskwargs running printfunction x printfunction yields initialize things x result things result,i writing module provides one function needs initialization step however due certain restrictions i need initialize first call i looking proper idiom python would allow get rid conditional conditional modulepy initialized false def functionargs initialized initialize dothethingargs i like get rid conditional something like thisit work conditional modulepy def functionargs initialize dothethingargs function dothething i realize i cannot use names module change runtime modules using module import function never affected functionotherfun inside module so pythonic idiom could right way,3 numpygenfromtxt guess dtypes set dtypenone import numpy np import io alist b f iobytesio n join joinrow row alist arr npgenfromtxtfdtypenone printarr printarrdtype b f f s f f note would better apply npgenfromtxt directly text file instead creating intermediate list list i called alist if need processing file sending npgenfromtxt could make filelike object wrapper around file processing passed npgenfromtxt,is function numpy determines whether strings integers floating point numbers automatically converts for instance i often collection records parsed text file using combination strstrip strsplit then i get something like list b which converted using numpyrecfromrecords in numpyrecfromrecordslist out recarray b dtype f s f s f s in r function called typeconvert vectorscolumns character strings passed determine type column ie mix strings numbers remain character vector excel also based first elements i recall correctly is function numpypython i know i could probably write function test whether element column could converted integer etc anything built i know examples prescription specify dtypes explicitly i would like skip step thanks,3 you could also use decorator maybe flexible several functions initialize import functools def initializeinitializefunction def wrapfn fninitialized false functoolswrapsfn def wrapperargs kwargs fninitialized initializefunction fninitialized true return fnargs kwargs return wrapper return wrap def initializefirstfn print first function initalized def initializesecondfn print second function initalized initializeinitializefirstfn def firstfnargs printargs initializeinitializesecondfn def secondfnargs printargs firstfn initialize please first function initalized initialize please firstfn works works secondfn initialize please second function initalized initialize please secondfn also works also works needs improved depending needs,i writing module provides one function needs initialization step however due certain restrictions i need initialize first call i looking proper idiom python would allow get rid conditional conditional modulepy initialized false def functionargs initialized initialize dothethingargs i like get rid conditional something like thisit work conditional modulepy def functionargs initialize dothethingargs function dothething i realize i cannot use names module change runtime modules using module import function never affected functionotherfun inside module so pythonic idiom could right way,1 if also want ctrld exit without confirmation ipython add cterminalinteractiveshellconfirmexit false config file if config file yet run ipython profile create create one note ticket working within django shell,it really irritating every time i type exit i get prompted confirmation exit course i want exit otherwise i would written exit is way override ipython default behaviour make exit without prompt,3 you try unofficial packages,i googled resizing images python i found nothing helpful python solution problem i need complicated image processing resizing function run python please give advises thanks,1 mylistsortkeylambda x x mylistsortkeyoperatoritemgetter the second option slightly faster,i list like xywumn pq i need sort outer list third last element inner list desired result would xymnwu pq what best way achieve,3 xrangelenmat printmati mati,mat i want cycle element matrix like mat mat mat how i change index elements loop like,1 my take in case need function initialization step normal work mode need class instance do try clever future readers code would hate modulepy class thingdoerobject def initself initialize def dothethingself args,i writing module provides one function needs initialization step however due certain restrictions i need initialize first call i looking proper idiom python would allow get rid conditional conditional modulepy initialized false def functionargs initialized initialize dothethingargs i like get rid conditional something like thisit work conditional modulepy def functionargs initialize dothethingargs function dothething i realize i cannot use names module change runtime modules using module import function never affected functionotherfun inside module so pythonic idiom could right way,2 tk perform moderately well writing game probably much better performance box use library like httppygameorg,in school create game using python tkinter group project since program getting rather large i want know problem caused tkinter trying search problems program the problem start creating units multiple units display time let say created using createrectangle method start moving around gets really choppy on part game displaying time couple elements using small gifs multiple menus canvas units i mentionned small buildings also using small gifs we use method callback method deletes everything canvas redraws buildings units correct positions every milliseconds should something easily handled tkinter problem program,2 python order dictionaries alphabetically in fact orders dictionaries arbitrarily if need dictionary object keeps original order look collectionsordereddict class available python,if i create dict dicts mydict zstuff zzz true aaa true astuff zzz true aaa true then use cycle dicts key mydict tag mydictkey print formatkeytag python outputs zstuffaaa zstuffzzz astuffaaa astuffzzz is way get python reorder second level dicts,3 for large lists using combination deque generator efficient import collectionsdeque def listcyclergenlst q collectionsdequelstlenlst true qappendleftqpop yield listq gen listcyclergen gennext gennext gennext this work anything place list also would wanted cycle direction could replace first loop line qappendqpopleft,mat i want cycle element matrix like mat mat mat how i change index elements loop like,1 import random tab randomchoice tab your code creates bunch numpy arrays list numpy arrays transforms list numpy array finally transforms everything back list the code skips rather pointless conversions uses python builtin random module instead numpy numpyrandom,ascarray bscarray cscarray dscarray orientationlistscarrayabcdtolist trying sth like tabscrandomrandomintegersorientationlist i want tab retrieve randomly one arraysfor example tab is way,1 collections import ordereddict mydict zstuff ordereddictzzztrue aaatrue astuff ordereddictzzztrue aaatrue,if i create dict dicts mydict zstuff zzz true aaa true astuff zzz true aaa true then use cycle dicts key mydict tag mydictkey print formatkeytag python outputs zstuffaaa zstuffzzz astuffaaa astuffzzz is way get python reorder second level dicts,1 the correct timezone warsaw europewarsaw just fix settingspy,i trying install fanofmongo web admin mongodb based django i think i believe i followed instructions httpsgithubcomfiedziafangofmongo when i run command python managepy runserver i get error file usrlibpythonsitepackagesdjangopyeggdjangoconfinitpy line init raise valueerrorincorrect timezone setting selftimezone valueerror incorrect timezone setting warsawpoland can anyone give idea fix,3 i current developer feedparser currently one ways get information monkeypatch feedparserfeedparsermixin edit local copy feedparserpy the methods want modify feedparserfeedparsermixinunknownstarttag feedparserfeedparsermixinunknownendtag at top method insert callback routine capture elements attributes encountered feedparser,i trying use feedparser retrieve specific information feeds also retrieve raw xml entry ie elements rss atom i see obviously i could parse xml hand elegant would require separate support rss atom i imagine could fall sync feedparser illformed feeds is better way thanks,1 this called symbolic evaluation need external library example sympy import sympy myfoo lambda xy x myspecfoo lambda x myfoox x sympyvarx print myspecfoox x,i two many lambdas myfoo lambda xy x myspecfoo lambda x myfoox i want print resulting expression myspecfoo smth like x var x printmyspecfoox i want see output lambda x x do know thank,2 string red blue white string first second third dictzipstringsplit stringsplit blue second red first white third,i trying convert two string values single dict like string red blue white string first second third dict red first blue second white third but use loops is way without loop help thank,3 please execute following code post result i write regex catch data want obtain nota would easier post email encumber so memory sock urlliburlopenrequest ch sockread sockclose print n joinstri reprline iline enumeratechsplitlinestrue a regex least times faster using beautifulsoup analyze text i say analyze not parse people believing html text must analyzed regex i say ã¹ã¹ampã¹ã¨ spâµã¹yã© ã¹ yyã©amp ã©fâ§nmiyuoâ£ã¶ sskrftttt â§ edit if text organized regularly seems even need regex analyze io import stringio ss input typehidden namefoo idfoo valuegarble script typetextjavascript cdata function convert var true true false false manateestart pageids usernames alice bob carol dave eve wordcounts linkcounts pageurls blogcafafcaccdfdatapdfblogdafebffdceedfcddbedatapdfblogffccadeebeadatapdfblogfcdafaabfcaebfdatapdfblogaeccaaafdebaadatapdf toolbar id manateetoolbar buttons id manateebrowser text enter fullscreen toggletext escape fullscreen script script typetextjavascriptvar blahscript similifile stringioss line similifile line ttpageurls urls tupleel el linelinefind split el print urls result blogcafafcaccdfdatapdf blogdafebffdceedfcddbedatapdf blogffccadeebeadatapdf blogfcdafaabfcaebfdatapdf blogaeccaaafdebaadatapdf edit in order make code safer relatively variations content file also use regex though ss input typehidden namefoo idfoo valuegarble script typetextjavascript cdata function convert var true true false false manateestart pageids usernames alice bob carol dave eve wordcounts linkcounts pageurls blogcafafcaccdfdatapdfblogdafebffdceedfcddbedatapdfblogffccadeebeadatapdfblogfcdafaabfcaebfdatapdfblogaeccaaafdebaadatapdf toolbar id manateetoolbar buttons id manateebrowser text enter fullscreen toggletext escape fullscreen script script typetextjavascriptvar blahscript import regx recompile tpageurlst remultiline mat regxfinditerss urls tupleel el matgroupsplit el print urls for good functioning two codes must urls in first code also must urls but i verified windows repertories names i wrote regex pattern second code order avoid problems due urls ending part regex requires character must followed blanks tabs end line because star presence tabs blanks end line possible mandatory,i trying read source website following import urllib beautifulsoup import beautifulsoup url httpwwwmyurlcom headers useragent mozilla request urllibrequesturlnoneheaders soup beautifulsoupurlliburlopenrequestread i narrow scriptresults soup script type textjavascript a sample contents follows scriptresults script typetextjavascript script script typetextjavascript comment function comment var true true false false funcstart token token tokenn valuevaluevaluek script now i interested extracting values tokenn i know unique entire document present webpages i trying read further number results scriptresults vary number tokens also vary i use position index access also i realize beautifulsoup html parser parse js how would i go extracting info using regex if easy way getting following compromise most values form stringxxxxstring xxxx random sha hash different i figure rest means so i find ones fit pattern ok edit in response eyquem i uploaded relevant portions i want pastebin i interested retrieving values pageurls,3 elementtree limited support xpath while support everything advanced things work you query attribute values elementtree builtin python python like treefind cookiediameter for full xpath support see documentation effbotorg,i installed elementtree library httpeffbotorgzoneelementhtm python i parsed xml file treeaparse homeusercookiesxml the question emerges i coudln extract information documentation effbot elementtree how i access node xmltree via calling attribute value something like treeagetnodemyattributemyattributevalue example treeagetnodecookiediameter query would return node xmltree cookiediameter attribute value does builtin function exist best regards daniyal,2 what trying change class signiture based arguments passed instance method make whole lot sense what probably define two classes class randomwalk ns number steps np number particles dimension choose d d def initselfnsnpdimensionnone selfnsns selfnpnp selfdimensiondimension stepstable trajectories constitute steps def stepsselfns return scrandomrandomintegerssizeselfns class randomwalkdrandomwalk def stepdselfns return step rangens and define factory function returns correct class def makerandomwalkns np dimensionsnone dimensions return randomwalkdns np else return randomwalkns np dimensions,i following code class randomwalk ns number steps np number particles dimension choose d d def initselfnsnpdimensionnone selfnsns selfnpnp selfdimensiondimension selfdimension these represent orientation movement steprandomchoice def stepdselfns return step rangens stepstable trajectories constitute steps def stepsselfns return scrandomrandomintegerssizeselfns if i rwrandomwalknsnp rwstepsns works ok but i try rwrandomwalknsnpdimension rwstepdns gives randomwalk instance attribute stepd as far i understand stepd function init method is way access thank,1 ed c unichrints,im using idle windows when i run following code uni uued binary uniencodeutf print binary it prints unicode character number ed correctly but i hardcode unicode number manually lets say i normal string format variable sed how i convert unicode character ie i want something like following pseudocode sed uniuus thanks,3 your roulette function computing partial sums list xfitness elements you reach result defining closure using map generator expression sum def partialsumx sum x return sum lst mappartialsum xfitness x selfdrinklist this certainly less readable loop could faster experiment map generally faster function calls slow substituting list comprehension generator expression might speed things expense memory,i function looks like def rouletteself sum lst x selfdrinklist sum xfitness lstappendsum return lst can replaced list comprehension expression something efficient loop ps apperars i randomrandrange raises exception valueerror empty range randrange is way avoid without using test,1 i aware way create new instances classic classes used example without calling init new instances newstyle classes descendants object created using objectnewcls cls type object would like create an alternative use copycopy copying possibly overwriting getstate setstate define copied edit to create new instance classic class cls without calling init use following hack class emptyclass pass newinstance emptyclass newinstanceclass cls newinstancedictupdatewhatever,this quite hard explain i class support method copystateonly it return crippled version object contains copied data members i want i hope example explains better everything inherits class superbase def initself selfstatevar copied future objects selfnonstatevar want copy def copystateonlyself newobj create instance without calling init newobjstatevar selfstatevar return newobj clases inherit class basesuperbase def initself superbaseinitself selfisflying true want copy state selfsprite spritesplanegenericpng must drop def copystateonlyself newobj superbasecopystateonlyself newobjisflying selfisflying return newobj class afighterbase def initself teamname note required init argument baseinitself selfcolors black grey want copy state selfname teamname must drop def copystateonlyself newobj basecopystateonlyself newobjcolors selfcolors return newobj plane afighterteamblue planestate planecopystateonly return afighter object statevar flying colors set python,3 most probably python install uses another unicode format ucs cxoracle compiled ucs you install cxoracle unicode flag that worked bug strange oracle error quotinvalid format textquot or compile latest cxoracle httpmrpolocomvep language know helped,i issiues installing cxoracle i installed oracle instantclient cxoracle oracle packages ones installed getting error importing cxoracle running ubuntu host import cxoracle traceback recent call last file console line module importerror usrlibpythondistpackagescxoracleso undefined symbolpyunicodeucsasencodedstring one idea resolve issue cheers,1 it actually possible peek list built list comprehension outermost list name course valid python identifier must accessed another way def rouletteself return drinkfitness locals locals else drink selfdrinklist but mean go loop looks like exactly also rely undocumented python feature,i function looks like def rouletteself sum lst x selfdrinklist sum xfitness lstappendsum return lst can replaced list comprehension expression something efficient loop ps apperars i randomrandrange raises exception valueerror empty range randrange is way avoid without using test,2 everything inherits class superbase def initself selfstatevar copied future objects selfnonstatevar want copy def getstateself return statevar selfstatevar def strself return selfclassname strvarsself clases inherit class basesuperbase def initself superbaseinitself selfisflying true want copy state selfsprite spritesplanegenericpng must drop def getstateself state superbasegetstateself state isflying selfisflying return state class afighterbase def initself teamname note required init argument baseinitself selfcolors black grey want copy state selfname teamname must drop def getstateself state basegetstateself state colors selfcolors return state plane afighterteamblue print plane import copy print copycopyplane manually import types print typesinstancetypeplaneclass planegetstate,this quite hard explain i class support method copystateonly it return crippled version object contains copied data members i want i hope example explains better everything inherits class superbase def initself selfstatevar copied future objects selfnonstatevar want copy def copystateonlyself newobj create instance without calling init newobjstatevar selfstatevar return newobj clases inherit class basesuperbase def initself superbaseinitself selfisflying true want copy state selfsprite spritesplanegenericpng must drop def copystateonlyself newobj superbasecopystateonlyself newobjisflying selfisflying return newobj class afighterbase def initself teamname note required init argument baseinitself selfcolors black grey want copy state selfname teamname must drop def copystateonlyself newobj basecopystateonlyself newobjcolors selfcolors return newobj plane afighterteamblue planestate planecopystateonly return afighter object statevar flying colors set python,1 although exactly algorithms seems totally compatible meaning compress example string using deflaterdeflate correctly uncompress using zlib what caused problem form variables post need percent escaped android application encoding data base sending modifying server decode using base uncompressing using zlib solved problem,i porting python application android point application communicate web service sending compressed data in order uses next method def stuffself data convert utf compress return zlibcompresssimplejsondumpsdata i using next method try emulate behavior android private string compressstringstring stringtocompress logitag compressing string stringtocompress byte input stringtocompressgetbytes create compressor highest level compression deflater compressor new deflater compressorsetleveldeflaterbestcompression give compressor data compress compressorsetinputinput compressorfinish create expandable byte array hold compressed data you cannot use array size orginal guarantee compressed data smaller uncompressed data bytearrayoutputstream bos new bytearrayoutputstreaminputlength compress data byte buf new byte compressorfinished int count compressordeflatebuf boswritebuf count try bosclose catch ioexception e get compressed data byte compresseddata bostobytearray logitag finished compress string stringtocompress return new stringcompresseddata but http response server correct i guess result compression java one python i ran little test compressing zlibcompress deflate python zlibcompress xcsjtma android deflaterdeflate hefbfbdkbb how i compress data android obtain value zlibcompress python any help guidance pointer greatly appreciated,1 the chrome developer tools two parts frontend backend api specifies protocol parts you see specification you use writing app instead standard devtools frontend also experimental debugging api chrome extensions,i working project wants get information google chrome developer tools more specifically i open developer tools target website resources tab folder populated called this folder populating list urls i curious possible somehow access get urls populated via coding language preferably pythonjavascriptajaxjava any input advice suggestions go accessing data within google chrome developer tools would greatly appreciated,2 i figured way i think best way i two files whitesvg greensvg hover functions i render image force show def hoverentereventself event selfrenderload greensvg selfshow def hoverleaveeventself event selfrenderload whitesvg selfshow self qgraphicssvgitem i like way i two svg files insted one if anyone better solution i open suggestions,how would i go adding interactive svg file qgraphicsscene i add interactive svg file displayed static image i reading qgraphicswebview figure add svg files examples lacking let little specific i looking let say i svg file draws box when i mouse box i want color change triggered hover event do i edit file redraw image feels like way interactive svg files qt,1 the unicode string uuedue consists two text characters 不 æ— when unicode string encoded converted sequence bytes binary depending encoding used may onetoone mapping text characters bytes the utf encoding instance use one three bytes represent single character u ue encode utf xexxa now sequence bytes printed python idle try decode but since way know encoding used forced guess for reason appears idle may wrongly guessed cp one examples text u ue encode utf decode cp text u xeuxa print text ã¦â€”â note three characters text last one nonbreaking space edit strictly speaking idle wrongly guesses cp three examples the second one succeeds byte coincidently maps valid text character cp bit singlebyte encoding the two examples contain byte xd defined cp for cases idle eventually falls back utf gives correct output,ok i another python unicode problem in idle windows the following code uni uuedue binary uniencodeutf print binary prints two chinese characters ä¸æ— correct ones however i replace first line uni uue ie second character prints ã¦â€” instead altough i replace first character uued gives correct output 不 is bug i wrong complete code uni uuedue binary uniencodeutf print binary uni uue binary uniencodeutf print binary uni uued binary uniencodeutf print binary output ä¸æ— ã¦â€”â 不,2 given datetimedatetime object dt could use dt datetimedatetimeutcfromtimestamptotalseconds example dt datetimedatetimenow timetime dt datetimedatetimeutcfromtimestamptotalseconds note timedeltatotalseconds method introduced python,in python i convert datetimedatetime kind float i would get timetime function,3 a combination datetimetimetuple timemktime import datetime import time datetimedatetimenow secondssinceepoch timemktimenowtimetuple,in python i convert datetimedatetime kind float i would get timetime function,2 i usually use qtextbrowser logging widget just create qtextbrowser widget main window ie selflogwidget qtextbrowser add layout visible part window log messages append method accepts string ie selflogwidgetappend hello qtextbrowser powerful widget also accept html formatted output,i porting console app qt gui the app get data website prints rsult line line console i use spyder each line strings now i want add gui app others use app well with qt designer i designed nice gui in main module i call ui now i trying connect app gui since i new qt pyside i would like build step step learn now i would like show print line line results widget eg qlistview can show example line this line two show two rows qt widget thanks,1 timemktimedtobjtimetuple should trick,in python i convert datetimedatetime kind float i would get timetime function,3 table cellspacing item incountrylistdictsortname forloopcounterdivisibleby tr styletextaligncenter endif td widthpx class communitytable img src itemimage styleheightpxbr href itemurl stylefontsizepx marginleftpx target blank itemname abr itemcomtype br itemincity br td forloopcounterdivisibleby tr endif endfor table,what i want quite simple i model i running regroup loop now i want show first items loop next continue next line next items list done if items cells line stay empty i tried understand i use iterations able figure fits i also i idea possible simpler way below i copied code i obviously shows first item loop times times second one etc i know similar questions website i able leverage develop solution question i running python google app engine any help greatly appreciated regroup communitiesdictsortincountry incountry communitylist incountry communitylist h stylefontsizepx incountrygrouper h table cellspacing item incountrylistdictsortname tr styletextaligncenter td widthpx class communitytable img src itemimage styleheightpxbr href itemurl stylefontsizepx marginleftpx target blank itemname abr itemcomtype br itemincity br td td widthpx class communitytable img src itemimage styleheightpxbr href itemurl stylefontsizepx marginleftpx target blank itemname abr itemcomtype br itemincity br td td widthpx class communitytable img src itemimage styleheightpxbr href itemurl stylefontsizepx marginleftpx target blank itemname abr itemcomtype br itemincity br td td widthpx class communitytable img src itemimage styleheightpxbr href itemurl stylefontsizepx marginleftpx target blank itemname abr itemcomtype br itemincity br td endfor table endfor,1 it hard use time tuple method still retain microseconds datetimedatetimenow datetimedatetime timemktimettimetuple tmicrosecond e,in python i convert datetimedatetime kind float i would get timetime function,3 the csetdefault castles line directly assigns c castles none this likely intended if intended make castles show repr use c castles instead for counter behave designed keys anything want count values need number as seen sortstep repr expects values numbers work one values set none it might seem setdefault would used give counter default values assign factory function setdefault and need step since counter objects automatically return default value zero no extra work required here works simply easily collections import counter c counterhouses c counter houses c castles counters automatically return zero missing items work required c missing items show repr counter houses c castles unless specifically add entry c counter houses castles,counter objects subclasses dict method setdefault collections import counter c counterhouses printcsetdefaultdoc dsetdefaultkd dgetkd also set dkd k d if i csetdefault castles ckeys dictkeys castles houses typec class collectionscounter everything seems pretty nice but c traceback recent call last file pyshell line module c file cpythonlibcollectionspy line repr items joinmap r r mod selfmostcommon file cpythonlibcollectionspy line mostcommon return sortedselfitems keyitemgetter reversetrue typeerror unorderable types nonetype int is bug should give csetdefault castles valuekey error instead silently accept key without value or maybe repr method taking account none values,1 yes looks like bug the problem setdefault without value argument assumes value none case counter really insert either one zero fail raising exception in python snippet works btw although still inserts none value violating counter invariants mind first bugdesign flaw i encounter collectionscounter,counter objects subclasses dict method setdefault collections import counter c counterhouses printcsetdefaultdoc dsetdefaultkd dgetkd also set dkd k d if i csetdefault castles ckeys dictkeys castles houses typec class collectionscounter everything seems pretty nice but c traceback recent call last file pyshell line module c file cpythonlibcollectionspy line repr items joinmap r r mod selfmostcommon file cpythonlibcollectionspy line mostcommon return sortedselfitems keyitemgetter reversetrue typeerror unorderable types nonetype int is bug should give csetdefault castles valuekey error instead silently accept key without value or maybe repr method taking account none values,1 need use directly index array boolean array resulting comparison operator aarray aa array aa array list expected output question i sure want,i working dimensional arrays purpose example imagine represent rgb values x y coordinates screen import numpy np npfloor nprandomrandom array what i would like set arbitrary value g channel pixels whose g channel already i manage isolate pixel i interested using anpwherea array i struggling understand assign new value g channel i tried anpwherea array seems produce effect i also tried anpwherea array failing understand happening finally i tried anpwherea array i suspect i missing something fundamental numpy works first time i use library i would appreciate help achieve i want well explanation happened previous attempts many thanks advance help expertise edit the outcome i would like get array changed second number changed second number,1 import numpy np nparray array aa array gives g channel i subsetted using index assigned value selected elements,i working dimensional arrays purpose example imagine represent rgb values x y coordinates screen import numpy np npfloor nprandomrandom array what i would like set arbitrary value g channel pixels whose g channel already i manage isolate pixel i interested using anpwherea array i struggling understand assign new value g channel i tried anpwherea array seems produce effect i also tried anpwherea array failing understand happening finally i tried anpwherea array i suspect i missing something fundamental numpy works first time i use library i would appreciate help achieve i want well explanation happened previous attempts many thanks advance help expertise edit the outcome i would like get array changed second number changed second number,2 you know libraries already written exact purpose python pywikipedia every language ever there list httpwwwmediawikiorgwikiapiclientcodeapiaccesslibraries lists four libraries python i use one instead rolling,i need help i parsing wikipedia article using wikimedia api i want read text here wikimedia api query i tried found luck one please help thank much def getcategorytitle paramsd action query prop revisions rvprop content format xmlfm rvsection titles title params urlliburlencodeparamsd req urllibrequesturl httpenwikipediaorgwapiphp dataparams f urlliburlopenreq,2 this typically solved using regex there many variations solutions however depending strict need custom requirements validation accept valid email address see page reference httpwwwregularexpressionsinfoemailhtml,is good way check form input using regex make sure proper style email address been searching since last night everybody answered peoples questions regarding topic also seems problems subdomained email address,2 email addresses incredibly complicated here sample regex match every rfcvalid address httpwwwexparrotcompdwmailrfcaddresshtml you notice probably longer rest program there even whole modules perl purpose validating email addresses so probably get anything perfect regex also readable here sample recursive descent parser httpcpansearchperlorgsrcabigailrfcrfcaddresslibrfcrfcaddresspm need decide whether need perfect parsing simple code,is good way check form input using regex make sure proper style email address been searching since last night everybody answered peoples questions regarding topic also seems problems subdomained email address,1 there point even verify email address syntactically valid still need check mistyped actually goes person think the way send email click link verify therefore basic check eg accidentally entered street address usually enough something like exactly one sign least one part you probably also want disallow whitespace probably valid email addresses whitespace i never seen one odds user error side if want full check look question update here could use regex import rematchr regex email whatever note r front string way need escape things twice if large number regexes check might faster compile regex first import emailregex recompiler regex emailregexmatchemail whatever,is good way check form input using regex make sure proper style email address been searching since last night everybody answered peoples questions regarding topic also seems problems subdomained email address,3 use loggingstreamhandler logging handler,i server running nginx uwsgi python uwsgi running daemon flag set daemonize varloguwsgilog logs application errors i noticed error i use python print statement write log error the standard python logging library seem affect log situation how i point python logging libraries use uwsgi log,2 email addresses simple seem for example bobo reillytagexamplecom valid email address i luck lepl package httpwwwacookeorglepl it validate email addresses indicated rfc httpwwwfaqsorgrfcsrfchtml found old code import leplappsrfc emailvalidator leplappsrfcemail emailvalidatoremailexamplecom print invalid email,is good way check form input using regex make sure proper style email address been searching since last night everybody answered peoples questions regarding topic also seems problems subdomained email address,3 uwsgi wsgi server passes stream environ dict passed application callable hosts using key wsgierrors if writing bare wsgi app writing stream job if using framework abstracts wsgi interface sound print would ordinarily write sysstdout gets closed daemonized process would never make log file probably need look framework handles error logging,i server running nginx uwsgi python uwsgi running daemon flag set daemonize varloguwsgilog logs application errors i noticed error i use python print statement write log error the standard python logging library seem affect log situation how i point python logging libraries use uwsgi log,1 use top check reducer cpu bound io bound possibly causing swapping runs hours jobs per host mins per mb job you could possibly use heapq data structure built memory kept sorted see section httpdocspythonorglibraryheapqhtml,i wrote mapreduce job took ngram counts dataset the results one hundred mb files format ngramtcount i want combine one result attempts combining crashed task tracker gone away i timeout hours crash occurred around hours might related i reducers nodes maybe i need leave time although error seem indicate i suspect nodes getting overloaded becoming unresponsive my theory reducer could use optimization i using cat mapper following python script reducer usrbinenv python import sys counts line sysstdin line linestrip key count linesplit try count intcount except valueerror continue key counts countskey countskey count key sortedcountskeys print sts key countskey update as i hinted one comments i confused sorting takes place hadoop automatically in web ui reducer status shows different phases includes sort reduce from i assume hadoop sorts mapper output sending reduce clear sorting data sent reducer file reduced in words mapper takes fiels splits outputs simply cat ing reducer reducers total receive streams does sort combine sort reduce etc based graphs could clearly nonindicative actual behavior sort process takes place reducing if sorting sort input files i simplify reducer store dictionary counts print keytotalcount pair key changes regarding use combiner i think would beneficial case since data i reducing already reduced files trying combine since nodes reducers amp nothing combine reducer already,1 you always use string cases class amodelsmodel details pass class bmodelsmodel modelsforeignkeya nulltrue blanktrue note quotes c modelsforeignkeyc nulltrue blanktrue note quotes class cmodelsmodel pass if extreme case use trick declaring c first a b cmethod def cmethod cmethod cmethod would way follow,i models app modelspy class amodelsmodel details pass class bmodelsmodel modelsforeignkeya nulltrue blanktrue c modelsforeignkeyc nulltrue blanktrue class cmodelsmodel pass def methodself blist bobjectsfiltercself alist b blist alistappendba return alist gives error launch webserver b declares c defined put models order a c b django tells b defined c method how resolve defined issue situation seems circular,2 i exactly sure trying example might lot easier understand used absolute imports avoided putting code init modules try something like app startpy print start package import module package initpy print init package modulepy print load packagemodule packagesubpackage import module subpackage initpy print init packagesubpackage modulepy print load packagesubpackagemodule package import subpackage after running startpy get output like start init package load packagemodule init packagesubpackage load packagesubpackagemodule,the directory structure app startpy import package package initpy print init package import module import subpackage modulepy print packagemodule import package works ok subpackage initpy print init packagesubpackage import module modulepy print init packagesubpackagemodule package import subpackage importerror cannot import name subpackage import subpackage importerror cannot import name subpackage import subpackage syntaxerror invalid syntax import packagesubpackage subpackage attributeerror module object attribute subpackage to avoid problems caused circular imports subpackagemodule want import module subpackage order refer modules subpackage form subpackagemodule because import module reference module could yet exist subpackage try import i tried different approaches none worked see comments code any help some time ago subpackage top level package worked see works source packagemodule now moved one level problem i know add package dir syspath ugly,1 it better compare dates date ranges rather strings assuming get strings birthday parts bmonth selfgetargument bmonth bday selfgetargument bday byear selfgetargument byear bd datetimedatetimeintbyear intbmonth intbday minage datetimetimedeltaweeks datetimedatetimenow bd minage response tornadoescapejsonencodeerrortrue msg you must years age older join usocial n,on join script join the problem i check certain dates works i month back curtime datetimedatetimeutcnow datetimetimedeltadays time strcurtimestrftimeymd bmonth selfgetargument bmonth bday selfgetargument bday byear selfgetargument byear birthday byear bmonth bday time birthday cage true else cage cage response tornadoescapejsonencodeerrortruemsgyou must years age older join usocial n,2 i believe need install python system first you telling virtualenvironment use version python exist anywhere cannot find this exist edit info given comment virtualenv p usrlocalbinpython,i trying understand create isolated python environment using alternative version python default case python virtualenv works system python i seem create virtual environment version python i tried specify python version outlined post like virtualenv p usrbinpython can anyone explain i create virtualenv specific version python thanks much,3 i use approach import datetime import logging import import urllib googleappengineext import blobstore googleappengineext import db googleappengineext import webapp googleappengineextwebapp import blobstorehandlers googleappengineextwebapp import util googleappengineextwebapp import template googleappengineapi import taskqueue googleappengineapi import users class indexhandlerwebapprequesthandler def getself selfresponseheaders contenttype textplain selfresponseoutwrite hello blobstore purgednn try query blobstoreblobinfoall index todelete blobs queryfetch lenblobs blob blobs blobdelete index hour datetimedatetimenowtimehour minute datetimedatetimenowtimeminute second datetimedatetimenowtimesecond selfresponseoutwritestrindex items deleted strhour strminute strsecond index selfredirectpurge except exception e selfresponseoutwrite error repre n pass app webappwsgiapplication purge indexhandler debugtrue def main utilrunwsgiappapp name main main my experience blobs fail i let reload every i tried blobstoredeletequeryfetch i think bug right nothing happened nothing deleted,what best way remove blob blobstore i using python i quite lot blobs i like delete i currently following class deleteblobswebapprequesthandler def getself blobstoreblobinfoall allcount blobstoredeleteall taskqueueaddurl deleteblobs method get which seems using tons cpu far i tell nothing useful,3 personally i would go solution uses something like djangoreversion however want create something robust less dependent rd party logic add mergedinto field organization mergedfrom field event organizationmodelsmodel name modelscharfieldmaxlength mergedinto modelsforeignkey self nulltrue blanktrue eventmodelsmodel organization modelsforeignkeyorganization name modelscharfieldmaxlength mergedfrom modelsforeignkeyorganization nulltrue blanktrue on merge choose update events well from sure redirect references mergedinto organizations new organization if want allow multiple merges example a b c ac d ef g dg h create new organization instance time merge parents copying events instead updating this keeps original events intact waiting rollback this also allows merging organizations new one one step,say i two tables i using django question mostly language agnostic organizationmodelsmodel name modelscharfieldmaxlength eventmodelsmodel organization modelsforeignkeyorganization name modelscharfieldmaxlength users allowed create events organizations there chance two separate users create organization objects supposed resemble real world organization when someone notices problem able merge two objects one organization the question i how i merge two organizations order ensure i unmerge user incorrectly merged thus simple solution deleting one organization objects pointing events one option i looking high level guidelines best practices a possible solutions add another table joins together organizations merged keep track merges way add foreign key field organization point organization merged keep copies original objects existed merge using something like djangoreversion,1 if want name age using items gives key key value tuples name age mydictitems age searchage print name you unpack tuple two separate variables right loop match age you also consider reversing dictionary generally going looking age two people age george amber look name age mydictsearchage i calling mydict instead list list name builtin type use name anything else you even get list people given age one line name name age mydictitems age searchage one person age nextname name age mydictitems age searchage none give none anyone age finally dict long python consider using iteritems instead items cat plus plus answer since need make copy list,i made function look ages dictionary show matching name list george amber searchage rawinputprovide age age listvalues age searchage name listage print name i know compare find age i know show name person additionally i getting keyerror line i know correct i figure make search backwards,3 there none dict intended used way name age listiteritems age searchage print name,i made function look ages dictionary show matching name list george amber searchage rawinputprovide age age listvalues age searchage name listage print name i know compare find age i know show name person additionally i getting keyerror line i know correct i figure make search backwards,3 read little ucs utf currently defined unicode character points true year pep written the initial implementation covered bmp first k codepoints,httpwwwpythonorgdevpepspep pep states internal format python unicode holds utf encodings addresses values ucs ucs compiled flag enableunicodeucs why utf chosen variable length format opposed ucs fixed length though two encodings largely utf already years old pep published mar was python unicode meant address backwards compatibility issues i really curious python internal format implemented using seemingly hybrid approach store encoded data internally a better way ask question might anyone citation link quote official document specifically states pep chose treat utf ucs instead using utf,1 just another approach give alternative data point here extractor problem using pyparsing instead regex you might find easier maintain long run pyparsing import literal quotedstring removequotes delimitedlist automatically strip quotes quoted strings quotedstring matches single double quotes quotedstringsetparseactionremovequotes define pattern extract pageurls entry pageurlsspec literal pageurls delimitedlistquotedstring urls pageurls pageurlsspecsearchstringss url pageurlsurls print url prints blogcafafcaccdfdatapdf blogdafebffdceedfcddbedatapdf blogffccadeebeadatapdf blogfcdafaabfcaebfdatapdf blogaeccaaafdebaadatapdf,i trying read source website following import urllib beautifulsoup import beautifulsoup url httpwwwmyurlcom headers useragent mozilla request urllibrequesturlnoneheaders soup beautifulsoupurlliburlopenrequestread i narrow scriptresults soup script type textjavascript a sample contents follows scriptresults script typetextjavascript script script typetextjavascript comment function comment var true true false false funcstart token token tokenn valuevaluevaluek script now i interested extracting values tokenn i know unique entire document present webpages i trying read further number results scriptresults vary number tokens also vary i use position index access also i realize beautifulsoup html parser parse js how would i go extracting info using regex if easy way getting following compromise most values form stringxxxxstring xxxx random sha hash different i figure rest means so i find ones fit pattern ok edit in response eyquem i uploaded relevant portions i want pastebin i interested retrieving values pageurls,1 it raw string literal it changes backslashes treated literally almost see this particularly useful writing regular expressions often contain backslashes use ordinary string literal may escape backslashes making regular expression harder read without r code would look like f recompilenothing dsearch note escaping backslashes also works case valid escape sequence f recompilenothing dsearch however relying behaviour may result errors unless everyone maintain code memorize list allowable escape sequences the rules raw string literals when r r prefix present character following backslash included string without change backslashes left string for example string literal rn consists two characters backslash lowercase n string quotes escaped backslash backslash remains string example r valid string literal consisting two characters backslash double quote r valid string literal even raw string cannot end odd number backslashes specifically raw string cannot end single backslash since backslash would escape following quote character note also single backslash followed newline interpreted two characters part string line continuation,i try understand code var recompilernothing dsearch want see affect r notation right sign know mean find decimal numbers mean special meaning mean without r notation would use know bash shell enough put one read httpdocspythonorglibraryrehtmlrawstringnotation understand affects snippets code thanks,2 floats store bits information affected roundoff use integers instead or use decimal module decimal import decimal decimal decimal decimal,i understand going following lines code shouldn result thanks cheers,3 there exact representation float e oops,i understand going following lines code shouldn result thanks cheers,2 float arithmetics common issue rounding problem what every computer scientist should know about floatingpoint arithmetic,i understand going following lines code shouldn result thanks cheers,1 floating point numbers stored bits mantissa plus bits exponent plus sign bit your numbers require bits represent nearest actual representable floating point value used floating point numbers usually model realworld measurements simulations realworld systems few physical constants measurements known anything even close bits precision normally works ok the rd bit hidden bit enough help dc p p number bigger actually requires bits p p,i understand going following lines code shouldn result thanks cheers,2 lets say want apy use bpy if code bpy written outside function class need run simply import b if however code function example code bpy def somefunc implementation then need either import b bsomefunc b import somefunc somefunc finally code function class example code bpy class classb def somefuncself implementation b import classb objb classb objbsomefunc,ok i tried looking question i getting lot answers confuse mesorry ignorance i wrote script i want import another script run terminal second script part first how i i appreciate help,1 if want script inserted inline like include doing it wrong this import symbols script defined locally exception global variable access imported code scoped imported module local module otherscript import,ok i tried looking question i getting lot answers confuse mesorry ignorance i wrote script i want import another script run terminal second script part first how i i appreciate help,1 i know anything wtform i guess like django forms need call validation function access data in case formvalidate form adformformdataselfrequestpost formvalidate adtitle formtitledata,hi i get variables http post wtforms post done blobstoreuploadhandler preferably also localized messages validation this code working class adformform name textfield name title textfield title text textareafield text widgettextarea phonenumber textfield phone number phonenumberhide booleanfield display phone number site price textfield price password passwordfield password email textfield email when i try access data posted via form data turns none form adformdataselfrequestpost formtitle logginginfo getting title formtitledata adtitle formtitledata adsave the save anything datastore template coming div classlabelform div classlabelform styleclearleft label filter capitalize trans title endtrans endfilter label div div tdtd formtitle formtitleerrors ul classerrors error formtitleerrors li error li endfor ul endif can help there something wtforms manual appengine i find working example update i added validation tests i still access variables logginginfo getting requests formvalidate formtitle logginginfo getting title formtitledata adtitle formtitledata adsave adput logging output info mainpy getting requests info mainpy getting title update i removed wtforms dependence still working the line logginginfo getting data selfrequestget title outputs even though form regular http post form form actionformurl nameupload methodpost enctypemultipartformdata acceptcharsetutf update this minimal config wtforms jinja works probably something jinja barebones example works webapp python i going add faulty code line line troubleshoot class guestpagebasehandler def getself selfresponseoutwrite html body form actionsign methodpost divtextarea namecontent rows colstextareadiv divinput typesubmit valuesign guestbookdiv form body html class guestbookbasehandler inhandler blobstorehandlersblobstoreuploadhandler csrfprotect false def postself selfresponseoutwrite htmlbodyyou wrotepre selfresponseoutwriteselfrequestget content selfresponseoutwrite prebodyhtml app webappwsgiapplication guest guestpage sign guestbook update my back basics working jinja i suppose i build example see breaks class guestpagebasehandler def getself selfrenderjinja formjinja class guestbookbasehandler inhandler blobstorehandlersblobstoreuploadhandler csrfprotect false def postself selfresponseoutwrite htmlbodyyou wrotepre selfresponseoutwriteselfrequestget content selfresponseoutwrite prebodyhtml update i reproduce error minimal example access http post variable class guestpagewebapprequesthandler def getself selfresponseoutwrite html body form action blobstorecreateuploadurl sign methodpost divtextarea namecontent rows colstextareadiv divinput typesubmit valuesign guestbookdiv form body html class guestbookblobstorehandlersblobstoreuploadhandler def postself selfresponseoutwrite htmlbodyyou wrotepre selfresponseoutwriteselfrequestget content selfresponseoutwrite prebodyhtml app webappwsgiapplication guest guestpage sign guestbook update from guestbook example code blobstoreuploadhandler i upload file production server i could make working example uses blobstoreuploadhandler i try build use case update i could get original code everything works except blob transfer i suspect diff devappserver production i posted google appengine group we see progresses update here another common use nothing works add wtforms logginginfo getting data selfrequestget title logginginfo http post data strselfrequestpost form adformformdataselfrequestdata logginginfo populated form logginginfo form data strformformdata formvalidate formtitle logginginfo getting title str formget title adtitle formtitledata adsave adput formtext logginginfo getting text strformtext adtext formtextdata selfrequestget currency adcurrency selfrequestget currency selfrequestget cg adcategory formcgdata selfrequestget companyad adcompanyad true adput else logginginfo form validate except exception ex logginginfo occured exception strex info mainpy getting datatest info mainpy occured exception post update finally form populates validate thank sean info got now i get past populated form object exception exception occurs i try validate logginginfo getting data selfrequestget title form aformselfrequestpost logginginfo populated form formvalidate logginginfo validated form the code logging output info mainpy getting datatest info mainpy populated form info mainpy occured exception builtinfunctionormethod object iterable what exception mean my form class class aformform name textfield name title textfield title text textareafield text widgettextarea phonenumber textfield phone number phonenumberhide booleanfield display phone number site price textfield price password passwordfield password email textfield email category selectfieldchoicescategorieskeys,1 i barely started learning awk i offer advice front however python code need class proteiniterator def initself file selffile openfile r selffirstline selffilereadline def iterself return self def nextself returns next protein build selffirstline reached end file raise stopiteration file selffile proteindata selffirstline true line filereadline linestartswith buildprotein line selffirstline line break proteindataappendline return proteinproteindata class protein def initself data selfdata data line data linestartswith buildprotein selfinitialcompounds tuplelinesplit elif linestartswith final result pieces linesplit every piece name selffinalcompounds tuplep p pieces elif linestartswith other compounds pieces linesplit every piece name selfothercompounds tuplep p pieces def reprself return proteins selfdata property def dataself return joinselfdata what iterator buildprotein text file returns one protein time protein object this protein object smart enough know inputs final results results you may modify code actual text file exactly represented question following short test code example usage name main testdata buildprotein compounda compoundb begin fusion calculate lots text multiple lines lines final result h value co value compound value other compounds x value y value z value open testpitxt w writetestdata protein proteiniterator testpitxt printproteininitialcompounds printproteinfinalcompounds printproteinothercompounds print co proteinfinalcompounds printproteindata i bother saving values add like hopefully get going,i trying run awk script using python i process data is way get awk script run python class without using system class invoke shell process the framework i run python scripts allow use subprocess call i stuck either figuring way convert awk script python possible running awk script python any suggestions my awk script basically read text file isolate blocks proteins contains specific chemical compound output generated framework i add example looks like isolate printing different file buildprotein compounda compoundb begin fusion calculate lots text multiple lines lines final result h value co value compound value other compounds x value y value zvalue another similar block so example i build protein i need see compounds i chcooh final result line i take whole block starting command buildprotein beginning next block save file move next see compound i looking forif i skip next end file file multiple occurrence compound i search sometimes contiguous times alternate blocks compound any help welcome banging head weeks finding site i decided ask help thanks advance kindness,1 try lname fname mydict see working online ideone,i function asks person first last name prints age trouble entering statement always skipping my dictionary prints like command line name subname lname rawinputenter last name fname rawinputenter first name lname fname mydictitems age mydictlnamefname print age thanks advance,2 you could use zopeinterface for example used twisted pyramid frameworks,i want implement project using interface oriented programming since python native support interface keyword i planning leverage zope package but zopecomponent package really huge package lots dependencies because i want keep project slim less external dependency i wonder usefulhelpful use zope packages especially i planning deploy project gae include zope package supported thirdparty package if using zope package best practice implement python project interface oriented concepts,2 like i said comment really vague but i try explain little concept filter python specifically filter function the prototype filter iterable filterfunction iterable iterable something iterated you look term docs exact explanation question know list iterable function function accepts single element iterable specify case element list returns boolean specifying whether element exist iterable returned if function returns true element appear returned list false here short example showing use filter function filter even numbers i point filtering odd numbers def isoddi return l this list fl filterisodd l print fl this display you convince isodd works first it return true odd numbers false even numbers in practice usually use lambda function instead defining singleuse toplevel function worry fine but anyway able something similar accomplish goal,def processfilterdescriptionfilter images ial return new list containing items list images pass description filter str ial related image association list matching done case insensitive manner images items ial those two lines code i far what troubling filter function i really know filter supposed use in way i asking full code i want help filter supposed i use,1 there module import webbrowser webbrowseropenhttpxkcdcom,i tkinter script i wondering anyway hit button takes web site tkinter import app tk appgeometryx apptitlelinks def link button buttonapp text to web site command link buttonpack appmainloop,3 this scans lists different approach def testlst lst p length lenlst e lst p rangep length e lstp p p break else return false return true for element lst searches subset list p end if found restricts range following searches updating p if found false returned true returned every element lst found,i trying write function returns true elements lst appear lst order appear lst necessarily consecutively for example test return true test return false here i far def testlst lst rangelenlstlenlst lst lstiilenlst return true return false,1 short answer use applescript intermediary demonstrated python url handler the information url passed python script arguments,i looking python script able register url protocol handler url handler os x the information i found httpwwwcocoadevcomindexplhowtoregisterurlhandler apps written objectivec i sure howit possible replicate python script,1 recursively clobbered lists new sublists failing early def findallneedle haystack npos hpos npos lenneedle return true try return findallneedle haystack npos haystackindexneedlenpos hpos except valueerror return false print findall true print findall false,i trying write function returns true elements lst appear lst order appear lst necessarily consecutively for example test return true test return false here i far def testlst lst rangelenlstlenlst lst lstiilenlst return true return false,1 you use dictonary remember words appear terms collections import defaultdict terms electronic rock alternative rock indie pop defaultdictlist term terms word termsplit dwordappendterm kv diteritems lenv print kv output rock electronic rock alternative rock see working online ideone,i list single multiword phrases terms electronic rock alternative rock indie pop i want detect terms terms share word rock is pythonic way instead using ton forloops temporary lists split basically i trying detect halfequality phrases,3 on machine listsi gives nice neat on the last one consumes gb memory lists thrashes hard drive causes machine misbehave delnan probably right i check machine free memory python memory consumption operation,i run oddity creating nested lists python consider following two functions def listsn starttime timetime lists nonen xrangen listsi nonen j xrangen listsij print timetime starttime def simplelistsn starttime timetime lists nonen xrangen listsi nonen j xrangen listsij false print timetime starttime they allocate array size nn one assigns values false one assigns values empty lists they run on far i see however seem case observe following test runs simplelistsi listsi as see simplelists seems grow roughly on lists seems grow on what going this quirk completely utterly ruining complexity code i explain behaving like does anyone ideas edit list comprehensions seem cause complexity issues redefining lists like def listsn starttime timetime lists xrangen x xrangen print timetime starttime causes following results listsi still clearly growing pace quicker on even quicker on sheesh edit after looking problem seems caused garbage collector after running gcdisable result original lists definition listsi pretty damn neatly on moral story trust garbage collector,1 this terribly inefficient solution simple list elements longer strings could use itertools combinations generate set entry lists difflib compare strings if dealing two three word phrases solution,i list single multiword phrases terms electronic rock alternative rock indie pop i want detect terms terms share word rock is pythonic way instead using ton forloops temporary lists split basically i trying detect halfequality phrases,1 just use absolute path opening filehandle writing import ospath savepath cexample nameoffile rawinputwhat name file completename ospathjoinsavepath nameoffiletxt file opencompletename w tofile rawinputwrite want field filewritetofile fileclose you could optionally combine ospathabspath described bryan answer automatically get path user documents folder cheers,how tell python save text file for example computer running python file desktop i want save text file documents folder desktop how i script like nameoffile rawinputwhat name file completename nameoffile txt alter line shape form file opencompletename w tofile rawinputwrite want field filewritetofile fileclose,3 use ospathjoin combine path documents directory completename filename supplied user import os openospathjoin pathtodocuments completename w file tofile rawinputwrite want field filewritetofile if want documents directory relative user home directory could use something like ospathjoinospathexpanduser documents completename others proposed using ospathabspath note ospathabspath resolve user home directory in cd tmp tmp in ospathabspath out tmp,how tell python save text file for example computer running python file desktop i want save text file documents folder desktop how i script like nameoffile rawinputwhat name file completename nameoffile txt alter line shape form file opencompletename w tofile rawinputwrite want field filewritetofile fileclose,3 visit python how find list intersection i think answer could think in question know result want present i think better list result want get here i list result give hint well without split i think clear understand atermssplit btermssplit listseta amp setb,i list single multiword phrases terms electronic rock alternative rock indie pop i want detect terms terms share word rock is pythonic way instead using ton forloops temporary lists split basically i trying detect halfequality phrases,1 import numpy np nparray inda amp aindaind printa yields if wish check membership set simple range i like mac idea using python loop bellamyj idea using npind which faster depends size checktuple testpy import numpy np nprandomseed n nprandomrandint checktuple nprandomrandint n def usinginda idx npinda checktuple idxidxreshapeashape aidx aidx return def usingina idx npzerosashapedtypebool n checktuple idx aidx aidx return assert npallcloseusingindausingina when n usingin slightly faster python timeit import test testusingindtesta loops best usec per loop python timeit import test testusingintesta loops best usec per loop when n usingind much faster python timeit import test testusingindtesta loops best usec per loop python timeit import test testusingintesta loops best msec per loop,it seems i still struggle operator numpy here situation nprandomrandint array i would like get indexes triplets whose second element the way i intuitively tried valueerror the truth value array one element my ultimate goal would insert positions number preceding multiplied two using example become array pos replaced pos pos replaced pos thank advance advice time,1 those cookies expire page load they expire browser closes what need every page load flash session display force remove session server side,when using suas gae setting flashmsg reason cookie expire the symptom mater many times i refresh page flash message always when i debugged chrome i see expiration flashmsg cookies set session even troubling i found cookies expiry set session any idea the change i made suas code removing error raising def parsestringself str pattcookiecookiepattern also note flashmsg cookie domain update all variables sessioned meant suas persist variable sets cookies session cookies persist as work around flash messages i use jquery plug cookies delete guys i display,1 some variations answer markbyers collections import defaultdict terms electronic rock alternative rock indie pop baa baa black sheep blackpool rock definition equality rock ages def process defaultdictlist term terms word termsplit dwordappendterm kv diteritems lenv print kv def process defaultdictset term terms word termsplit dwordloweraddterm kv diteritems lenv print k sortedlistv process rock electronic rock alternative rock blackpool rock baa baa baa black sheep baa baa black sheep process rock alternative rock blackpool rock electronic rock rock ages,i list single multiword phrases terms electronic rock alternative rock indie pop i want detect terms terms share word rock is pythonic way instead using ton forloops temporary lists split basically i trying detect halfequality phrases,1 here method work arbitrary length tuple it uses numpyind function import numpy np nprandomseed nprandomrandint printa checktuple boolarray npinda checktuple ind npwhereboolarray areshapelenboolarray areshapelenboolarray aind aind printa and output,it seems i still struggle operator numpy here situation nprandomrandint array i would like get indexes triplets whose second element the way i intuitively tried valueerror the truth value array one element my ultimate goal would insert positions number preceding multiplied two using example become array pos replaced pos pos replaced pos thank advance advice time,1 you use regular expressions parse html there html parser module python aptly named htmlparser httpdocspythonorglibraryhtmlparserhtml,i trying scrape website i able get contents website stringfile now i would like search specific line something like lispan classabckey spanampnbspspan classaompbvalue spanli there gauranteed one key website i need get value what best way if regular expression help look i havent used regex much regards amm,1 rather use regex i would start letting beautifulsoup parse html then use builtin find functions search abc aompb classes import beautifulsoup soup beautifulsoupbeautifulsoupdownloadedstr key soupfind span class abc text value soupfind span class aompb text if class tag unique loop find right one li soupfindall li lifind span attrs class abc text key print lifind span class aompb text the key point let parser turn tree navigation problem rather illdefined text search problem beautifulsoup single pure python file easy add setup it popular choice more sophisticated alternatives include htmllib lxml the standard library includes htmlparser somewhat simplistic handler illformed html well the regex approach bit fragile could try something like depending data usually laidout lispan classabckey spanampnbspspan classaompbvalue spanli researchr key value sgroup value,i trying scrape website i able get contents website stringfile now i would like search specific line something like lispan classabckey spanampnbspspan classaompbvalue spanli there gauranteed one key website i need get value what best way if regular expression help look i havent used regex much regards amm,3 you use parser lxml extract data html using regular expressions task a bad idea tm lxml allows use xpath expressions select elements case relevant key span selected using expression spanclass abc text key this expression searches whole tree span elements classes abc containing exact text key you use getnext element get following element contains data want here one would full import lxmlhtml lh html html head titletesttitle head body ul lispan classabckey spanampnbspspan classaompbmangospanli lispan classabckey spanampnbspspan classaompbpineapplespanli lispan classabckey spanampnbspspan classaompbapplespanli lispan classabckey spanampnbspspan classaompbpeachspanli ul body html tree lhfromstringhtml keyspan treexpathspanclass abc text key print keyspangetnexttext result pineapple,i trying scrape website i able get contents website stringfile now i would like search specific line something like lispan classabckey spanampnbspspan classaompbvalue spanli there gauranteed one key website i need get value what best way if regular expression help look i havent used regex much regards amm,2 another approach using beautifulsoup loop li elements check spans inside import beautifulsoup downloadedstr lispan classabckey spanampnbspspan classaompbvalue spanli lispan classabckey spanampnbspspan classaompbvalue spanli lispan classabckey spanampnbspspan classaompbvalue spanli soup beautifulsoupbeautifulsoupdownloadedstr li soupfindall li span lifind span class abc recursivefalse span spantext key return lifind span class aompb recursivefalsetext,i trying scrape website i able get contents website stringfile now i would like search specific line something like lispan classabckey spanampnbspspan classaompbvalue spanli there gauranteed one key website i need get value what best way if regular expression help look i havent used regex much regards amm,1 here iterative version method using index given triptych i think probably best way index faster manual indexing iteration def testlst lst start try item lst start lstindexitem start except valueerror return false return true it perform much better python recursive version it also correctly adds one start point search give false positives duplicates first list here two solutions iterate primarily lst instead lst otherwise similar jedwards version the first straightforward uses indexing indexes actually move different item lst rather every item lst def testlst lst length item lenlst lst x lst x item length return true item lsti return false the second uses manual iteration lst next rather indexing def testlst lst iterlst try nextit x lst x nextit except stopiteration return true return false both probably slight improvements less indexing need construct range every item lst,i trying write function returns true elements lst appear lst order appear lst necessarily consecutively for example test return true test return false here i far def testlst lst rangelenlstlenlst lst lstiilenlst return true return false,3 your code seems work using explicit numpy namespace i using numpy v in import numpy np in a nparray none dtypeobject in a in ashape out in a out array dtypeobject what version numpy using update this seems issue related numpy version since i reproduce op error using numpy v version comes packaged base python install osx lion i sure bug numpy fixed change implementation i would either update newer version numpy use simple workaround a nparray none dtypeobject a a array dtypeobject update here general fix hopefully adapt c npemptyobject b none c b c array none dtypeobject cshape c c array dtypeobject,i problem numpy array constructor i want initialize d array tuples work integers a array printa a printa a array none dtypeobject a traceback recent call last file stdin line module indexerror invalid index ashape i really need fill matrix hand any idea,2 option for sendmailr seems issues appending port you able specify destination port via sendmailoptionssmtpport prior using sendmail command i sure resolve issues get right port option if like invoke python script one looks relevant you may find easiest token substitution ie take base script put strings simply find ie tokens amp replace ie substitution desired strings execute revised script for instance using script link saved local directory sendmailbasepy basepy scansendmailbasepy character sep n outpy gsubyouremailgmailcom yourrealemailaddress infile outpy gsubyourpassword yourrealpassword outfile replacing header recipient etc text strings like use specification attachment file name finally save output new python file execute catoutpy file sendmailnewpy sep n systemchmod ux sendmailnewpy sendmailnewpy although naive approach simple debugging script involves examination whether output python program working whether r generating right output python program this contrast debugging going r passing objects various packages languages,i desiring send email r attachment using gmail i found sendmailr work gmail requires authentication i get work gmail i assume true unless someone tells i wrong case i post r output error message i found code snippet found link as site suggests code formatted send attachments i got send email i like extend code send attachments email correspondence author code unable extend code send attachments i want send emails r using gmail i windows user beta version r the code sends emails attachments requirerjython rjython rjython rjythonexec import smtplib rjythonexecfrom emailmimetext import mimetext rjythonexecimport emailutils mailc email settings fromaddr bigbirdgmailcom toaddrs oscarthegrouchgmailcom msg mimetext this body message msg from emailutilsformataddr sender name fromaddr msg to emailutilsformataddr recipient name toaddrs msg subject simple test message smtp server credentials username bigbirdgmailcom password pw set smtp server send email eg google mail smtp server server smtplibsmtp smtpgmailcom serverehlo serverstarttls serverehlo serverloginusernamepassword serversendmailfromaddr toaddrs msgasstring serverquit jythonexecrjythonmail note message cross posted talkstatscom i receive reply members telling wish could help if i receive workable solution also post well,3 there pretty printer json module try something like print jsondumpss indent pk model trial model fields brieftitle short title trialid print jsondumpss indent pk model trial model fields brieftitle short title trialid,im trying extract data large batch files convert specific json format importing database using django fixtures i able get far n pkn model trialsconditionsn fields n trialid nctn keyword brain central nervous system tumorsn n pkn model trialsconditionsn fields n trialid nctn keyword lymphoman n pk n model trialscriterian fields n trialid nctn gender bothn minimumage yearsn maximumage nan healthyvolunteers non textblock n nttpknttmodel trialskeywordnttfields ntttrialid nctnttkeyword primary central nervous system nonhodgkin lymphomanttntt many lines later after completion study treatment patients followed every months year everyn months year every months yearsnn projected accrual a total patients accrued studyn n overallstatus recruitingn phase phase n enrollment n studytype interventionaln condition n criteria n overallcontact testdatan location n lastchangeddate march n firstreceiveddate may n keyword n conditionmesh n n n n pk testdatan model trialscontactn fields n trialid nctn lastname pamela z new mdn phone n email n the output actually needs look like pk trialid model trialstrial fields trialid trialid brieftitle brieftitle officialtitle officialtitle briefsummary briefsummary detaileddescription detaileddescription overallstatus overallstatus phase phase enrollment enrollment studytype studytype condition elligibility elligibility criteria overallcontact location lastchangeddate lastchangeddate firstreceiveddate firstreceiveddate keyword conditionmesh conditionmesh pk null model trialslocations fields trialsid trialsid facility facility city city state state zip zip country country any advice would much appreciated,1 partial datagrams permissible udp lite,most datagram receiving functions c recv read javas datagrampacket class pythons socketserver include possibility find amount received data c int amount recvsock buf n msgwaitall java int amount datagramsocketgetlength python class myudphandlersocketserverbaserequesthandler def handleself amount len selfrequest are reliable or possible parts message received due example packet fragmentation network delay in words when i send variable length chunk data via udp receive end amount values exactly equal size original chunk edit ninjalj made good point i want include what happens receiving function interrupted instance signal what happens two threads simultaneously try receive socket,2 it string formatting operation httpdocspythonorglibrarystdtypeshtmlstringformatting,hey look following code works old new sel print onpagechanged oldd newd seldn old new sel it doesnt really make sense use mod string and old new sel work also person putting string sorry right place i know else ask question thanks anyone reads,1 the operator strings means interpolating following tuple values string it immediately familiar programmer c background here portion python documentation string unicode objects one unique builtin operation operator modulo this also known string formatting interpolation operator given format values format string unicode object conversion specifications format replaced zero elements values the effect similar using sprintf c language if format unicode object objects converted using conversion unicode objects result also unicode object old new sel tuple values python go ahead read tuples documentation endless amount python tutorials numeric format specifier more formally attempts convert argument signed integer,hey look following code works old new sel print onpagechanged oldd newd seldn old new sel it doesnt really make sense use mod string and old new sel work also person putting string sorry right place i know else ask question thanks anyone reads,2 when applied string modulo operator string formatting operator it substitutes values tuple provided operator case old new sel escape sequences like string for example result substitution onpagechanged old new seln you read documentation,hey look following code works old new sel print onpagechanged oldd newd seldn old new sel it doesnt really make sense use mod string and old new sel work also person putting string sorry right place i know else ask question thanks anyone reads,2 list comprehensions faster loops do something like check number def getdivsn divs x x range n x return divs you check length divs array see numbers present,i recently working project euler problems python i fairly new python still somewhat new programmer in case i ran speedrelated issue coding solution problem the problem smallest number divided numbers without remainder what smallest positive number evenly divisible numbers i checked around i able find anything problem pertaining python specifically there completed scripts i want avoid looking code full possible instead wanting improve the code i written runs successfully example range directly modifiable work question however upon running i get answer presumably high number code fast enough printing current number checked seems support reaching several million without getting answer the code current implementation follows rangemax def divcheckn xrangerangemax n continue else return false return true name main num divchecknum print num num print num i already made couple changes i think help speed for one number divisible numbers must even even numbers divisible hence i increment instead also although i think i found someone point number divisible divisible haven checked one seems reasonable the code still however fast enough what optimisations either programmatic mathematics i make make code run faster thanks advance help,1 this known limitation workarounds documented cython documentation,i experimenting cython write python extension c library i created setuppy file i try build pxd pyx files i get error after investigation appears cython cannot grok functions const parameters whenever i remove const specifier compilation continues next function protype const argument is known limitation cython i missing something fundamental i running cython python,1 since answer must divisible start increment instead two in general start rangemax increment rangemax this reduces number times divcheck called order magnitude,i recently working project euler problems python i fairly new python still somewhat new programmer in case i ran speedrelated issue coding solution problem the problem smallest number divided numbers without remainder what smallest positive number evenly divisible numbers i checked around i able find anything problem pertaining python specifically there completed scripts i want avoid looking code full possible instead wanting improve the code i written runs successfully example range directly modifiable work question however upon running i get answer presumably high number code fast enough printing current number checked seems support reaching several million without getting answer the code current implementation follows rangemax def divcheckn xrangerangemax n continue else return false return true name main num divchecknum print num num print num i already made couple changes i think help speed for one number divisible numbers must even even numbers divisible hence i increment instead also although i think i found someone point number divisible divisible haven checked one seems reasonable the code still however fast enough what optimisations either programmatic mathematics i make make code run faster thanks advance help,3 yes sqlite reasonable choice implementing dictionary for speed use memory option make sure create appropriate indexes lookups queries for large persistent databases also works well for speed take care commit large transactions instead perkey the suggested appropriate uses sqlite datastore covered website httpwwwsqliteorgfeatureshtml,i curious anyone could tell using sqlite store dictionary brute force use python script efficient method while i relatively new python i quite bit experience programming languages currently working pentesting tool use backtrack so far i quite impressed speed simplicity python sql queries seem working pretty ideally return needed prefixes brute force tool however i guess i wondering standard storing large data files python am i overlooking better faster way storing prefixes simply comfort sql please bear mind i using python query ids n use rather i using python narrow possibilities query dictionary entries match criteria any help opinions would much appreciated,2 as far i know mechanize handle javascript that means either generate form reading js creates form translating python inserting script automate actual browser understand javascript using something like ruby watir,html including two forms one generated dynamic js page loaded so i try fetch one form could return form generated dynamic found question fetch forms even generated js,1 i found culprit it autofmtxdate function date ticklabels often overlap useful rotate right align also common use case number subplots shared xaxes xaxis date data the ticklabels often long helps rotate bottom subplot turn subplots well turn xlabels it feature you achieve effect inserting code subplot pltxticksrotation,i trouble using multiple subplots dates xaxis i using matplotlib example i modified include another subplot data plotted this i getting output the ticks appear second subplot why how i make appear subplots here modified source i added code include new subplot block halfway source usrbinenv python show make date plots matplotlib using date tick locators formatters see majorminordemopy information controlling major minor ticks all matplotlib date plotting done converting date instances days since utc the conversion tick locating formatting done behind scenes transparent the dates module provides several converter functions datenum numdate import datetime import numpy np import matplotlib import matplotlibpyplot plt import matplotlibdates mdates import matplotlibmlab mlab import matplotlibcbook cbook years mdatesyearlocator every year months mdatesmonthlocator every month yearsfmt mdatesdateformatter y load numpy record array yahoo csv data fields date open close volume adjclose mpldataexample directory the record array stores python datetimedate object array date column datafile cbookgetsampledata goognpy datafile goognpy r nploaddatafileviewnprecarray fig pltfigure ax figaddsubplot axplotrdate radjclose format ticks axxaxissetmajorlocatoryears axxaxissetmajorformatteryearsfmt axxaxissetminorlocatormonths datemin datetimedaterdateminyear datemax datetimedaterdatemaxyear axsetxlimdatemin datemax format coords message box def pricex return f x axformatxdata mdatesdateformatter ymd axformatydata price axgridtrue second true second years mdatesyearlocator every year months mdatesmonthlocator every month yearsfmt mdatesdateformatter y ax figaddsubplot axplotrdate radjclose format ticks axxaxissetmajorlocatoryears axxaxissetmajorformatteryearsfmt axxaxissetminorlocatormonths datemin datetimedaterdateminyear datemax datetimedaterdatemaxyear axsetxlimdatemin datemax format coords message box axformatxdata mdatesdateformatter ymd axformatydata price axgridtrue rotates right aligns x labels moves bottom axes make room figautofmtxdate pltshow,3 could use ossystem sudo u hadoop binhadoopdaemonsh stop tasktracker dont sudo su ossystem su hadoop c binhadoopdaemonsh stop tasktracker,i writing simple script restarts hadoop slave in script i initial changes root user after i change user hadoop perform set commands i using ossystem run commands i doubt whether works well for example uidpwdgetpwnam hadoop ossetuiduid ossystem whoami oschdir homehadoophadoop ossystem binhadoopdaemonsh stop tasktracker again i perform commands root become user hadoop execute ossystem binhadoopdaemonsh stop tasktracker i three questions is ossystem best command i use issue linux commands i able change root user user hadoop commands i able change root user i understand security issues permit i want know possibility atleast passing password does ossetuid work whoami prints user hadoop process tasktracker stopped using command perform commands manually works fine i use su hadoop instead setuid trying manually thanks help sethu,3 if raymond hettinger also recommends sqlite probably best bet but native python solution would use pickle file you would build python dict holds data pickle dict later could unpickle dict if one key need search might possibly good way go for python x would likely want use cpickle module for python x pickle i believe fast cpickle httpdocspythonorglibrarypicklehtml on hand data set truly large large sqlite starting choke instead splitting multiple smaller sqlite files managing might make sense dump everything real database postgresql,i curious anyone could tell using sqlite store dictionary brute force use python script efficient method while i relatively new python i quite bit experience programming languages currently working pentesting tool use backtrack so far i quite impressed speed simplicity python sql queries seem working pretty ideally return needed prefixes brute force tool however i guess i wondering standard storing large data files python am i overlooking better faster way storing prefixes simply comfort sql please bear mind i using python query ids n use rather i using python narrow possibilities query dictionary entries match criteria any help opinions would much appreciated,1 semi offtopic useful links thchydra p also great video password policies using brute force httpwwwirongeekcomiphppagevideoshackrconmartinbosyourpasswordpolicysucks,i curious anyone could tell using sqlite store dictionary brute force use python script efficient method while i relatively new python i quite bit experience programming languages currently working pentesting tool use backtrack so far i quite impressed speed simplicity python sql queries seem working pretty ideally return needed prefixes brute force tool however i guess i wondering standard storing large data files python am i overlooking better faster way storing prefixes simply comfort sql please bear mind i using python query ids n use rather i using python narrow possibilities query dictionary entries match criteria any help opinions would much appreciated,1 taking advice michael mior poke i wrote solution i tried use tricks make fast since need relatively short list numbers tested prebuild list numbers rather repeatedly calling xrange range also would work put numbers list think little bit pull numbers just take every integer evenly divisible if leave need leave any integer evenly divisible evenly divisible reverse might true so leave take leave prime leave take if repeat process wind much shorter list numbers try we start step numbers michael mior suggested we use generator expression inside poke suggested instead loop i used loop xrange i think slightly faster the result checklist def findsolutionstep num xrangestep step allnum n n checklist return num return none name main solution findsolution solution none print no answer found else print found answer solution on computer finds answer nine seconds edit and take advice david zaslavsky realize start loop step if i computer i get correct answer tenth second i made findsolution take argument try calling findsolution,i recently working project euler problems python i fairly new python still somewhat new programmer in case i ran speedrelated issue coding solution problem the problem smallest number divided numbers without remainder what smallest positive number evenly divisible numbers i checked around i able find anything problem pertaining python specifically there completed scripts i want avoid looking code full possible instead wanting improve the code i written runs successfully example range directly modifiable work question however upon running i get answer presumably high number code fast enough printing current number checked seems support reaching several million without getting answer the code current implementation follows rangemax def divcheckn xrangerangemax n continue else return false return true name main num divchecknum print num num print num i already made couple changes i think help speed for one number divisible numbers must even even numbers divisible hence i increment instead also although i think i found someone point number divisible divisible haven checked one seems reasonable the code still however fast enough what optimisations either programmatic mathematics i make make code run faster thanks advance help,3 python gc designed traverse live objects locate eliminate reference cycles external references you validate happening running gccollect printing gcgarbage gcgetobjects,using objgraph i found bunch objects like will python garbage collector deal cycles like leak a slightly wider view loop,2 python standard reference counting mechanism cannot free cycles structure example would leak the supplemental garbage collection facility however enabled default able free structure none components reachable outside anymore del methods if garbage collector free cannot determine safe order run del methods,using objgraph i found bunch objects like will python garbage collector deal cycles like leak a slightly wider view loop,3 with sparse matrix get improvement density less a sparse matrix may faster depending whether include time required build matrix import timeit setup import numpy np dim a nponesdim dim array modify b nprandomrandomintegers dim dim values ignore c nparrayb dtype npbool d nprandomrandomdim dim array used modify a print mult strtimeittimeit a b d setup number print index strtimeittimeit ac dc setup number setup setup a npmaarraynponesdim dim mask nparrayb dtype npbool print strtimeittimeit a d setup number setup setup scipy import sparse s sparsecsrmatrixc ds smultiplyd print sparse strtimeittimeit a ds setup number setup setup scipy import sparse print sparse strtimeittimeit s sparsecsrmatrixc ds smultiplyd a ds setup number setup setup scipy import sparse class sparsematsparsecoomatrix def iaddself selfdata otherdata return self a sparsematsparseranddim dim coo array modify d nprandomrandomdim dim array used modify a anz anonzero stmt ds sparsematdanzanz anz shapeashape new graph based random weights a ds print sparse strtimeittimeitstmt setup number output mult index sparse sparse sparse edit you use code setup extend scipysparsecoomatrix it keeps sparse format,i interested bestfastest way array ops dot outer add etc ignoring values array i mostly interested cases maybe values ignored effectively zero moderately large arrays maybe elements there number solutions i think none seem really benefit possible advantages able ignore values for example import numpy np a nponesdim dim array modify b nprandomrandomintegers dim dim values ignore c nparrayb dtype npbool d nprandomrandomdim dim array used modify a option zero values using multiplication initial tests show fastest a b d option use indexing seems slowest ac dc option use masked arrays a npmaarraynponesdim dim mask nparrayb dtype npbool a d edit as suggested cyborg sparse arrays may another option unfortunately i familiar package unable get speed advantages i might able for example i weighted graph restricted connectivity defined sparse matrix a another sparse matrix b defines connectivity connected connected dense numpy matrix c i like able something like a a bmultiplyc take advantage a b sparse,1 my first answer sped original calculation question here another answer solves different way find prime factors number multiply together go straight answer in words automates process recommended poke comment it finishes fraction second i think faster way i google search find prime factors python found httpwwwstealthcoptercomblogpythonfactorsofanumber from i found link factorpy written mike hansen useful functions httpsagemathwashingtoneduhomemhansenfactorpy his functions quite i wanted i wrote new one used pullprimefactors hard work the result findprimefactors returns list tuples prime number count for example findprimefactors returns prime factors then i use simple defaultdict keep track many seen far prime factor finally loop multiplies everything together collections import defaultdict factor import pullofffactors pf defaultdictint primes def findprimefactorsn lst p primes n pullofffactorsn p lst return lst def findsolutionlow high num xrangelow high lst findprimefactorsnum n count lst pfn maxpfn count print prime factors pf solution n count pfitems solution ncount return solution name main solution findsolution print answer solution edit oh wow i took look jf sebastian answer related question his answer essentially thing code far simply elegantly and fact faster code least common multiple numbers i leave i think functions might uses project euler but jf sebastian solution def gcda b return greatest common divisor using euclid algorithm b b b b return def lcma b return lowest common multiple return b gcda b def lcmmargs return lcm args return reducelcm args def lcmseqseq return lcm sequence return reducelcm seq solution lcmseqxrange print lcmseq solution i added lcmseq could also call lcmmrange,i recently working project euler problems python i fairly new python still somewhat new programmer in case i ran speedrelated issue coding solution problem the problem smallest number divided numbers without remainder what smallest positive number evenly divisible numbers i checked around i able find anything problem pertaining python specifically there completed scripts i want avoid looking code full possible instead wanting improve the code i written runs successfully example range directly modifiable work question however upon running i get answer presumably high number code fast enough printing current number checked seems support reaching several million without getting answer the code current implementation follows rangemax def divcheckn xrangerangemax n continue else return false return true name main num divchecknum print num num print num i already made couple changes i think help speed for one number divisible numbers must even even numbers divisible hence i increment instead also although i think i found someone point number divisible divisible haven checked one seems reasonable the code still however fast enough what optimisations either programmatic mathematics i make make code run faster thanks advance help,3 i would say buglimitation matplotlib version i tried code matplotlib activepython win bit reproduced behavior matplotlib dev activepython winxp bit works expected there also comment avaris saying gets expected behavior mpl win bit so i recommend upgrade installation possible,in following minimal example i create point scatter plot later change color points loop using collectionsetcolor if i set colors first time scatter called setcolor change face color edge color whereas i specify scatterplot created face color change according setcolor pylab import numpy import collscattersc omit c face color changing later ion show linspace collsetcolorcollgetcmapa draw is bug i missing something documentation,1 turns weird behavior caused garbage collector turning gcdisable yielded following listsi fits on like glove,i run oddity creating nested lists python consider following two functions def listsn starttime timetime lists nonen xrangen listsi nonen j xrangen listsij print timetime starttime def simplelistsn starttime timetime lists nonen xrangen listsi nonen j xrangen listsij false print timetime starttime they allocate array size nn one assigns values false one assigns values empty lists they run on far i see however seem case observe following test runs simplelistsi listsi as see simplelists seems grow roughly on lists seems grow on what going this quirk completely utterly ruining complexity code i explain behaving like does anyone ideas edit list comprehensions seem cause complexity issues redefining lists like def listsn starttime timetime lists xrangen x xrangen print timetime starttime causes following results listsi still clearly growing pace quicker on even quicker on sheesh edit after looking problem seems caused garbage collector after running gcdisable result original lists definition listsi pretty damn neatly on moral story trust garbage collector,1 i think problem creating connection outside class fine i think problem creating one cursor using long time far i understand cursors meant used you use connexecute without manually creating cursor fine using database if i remember correctly behind scenes creates new cursor sql command you could also getsomedata create new cursor use close returning data in long run wish server robust need add errorhandling database operations fail connection lost a final note essentially written basic database proxy server there probably various existing solutions already already handle many issues likely run i recommend least considering using existing solution,trying serve database query results adhoc client requests want open connection individual query i sure right current solution something like server side heavily cut clarity import rpyc rpycutilsserver import threadedserver import cxoracle conn cxoracleconect whatever connect string cursor conncursor def getsomedatabarcode something return cursorexecutewhatever query barcode barcode class dataservicerpycservice def exposedgetsomedataself brcd return getsomedatabrcd name main threadedserverdataservice port autoregisterfalse sstart this runs okay however time time program crashes far able track what wish confirm see database connection created outside dataservice class is likely cause problems many thanks thoughts appreciated,1 launch firefox use http live headers inspect javascript imitate using mechanize relevant http requests,html including two forms one generated dynamic js page loaded so i try fetch one form could return form generated dynamic found question fetch forms even generated js,1 just set dbprinting false,i googled question dozen different ways find joy i think i asking wrong question using wrong words i making mysql entries queries python script linux server webpy framework everything works great good news the bad news i filling log responses mysql import web db webdatabasedbn mysql user myusername pw mypassword db mydatabase lookup dbqueryselect track from playlist order by timestamp asc select track from playlist order by timestamp asc to stop response sql gave i looking configuration mysql webpy setting i open db any advice greatly appreciated,1 in general python methods mutate object listappend listextend listsort return none if wish print new list def flist listappend flist,why following code give none how i resolve def flist flistappend def flist printlist f what also work def flist arg listappend farg,3 session loaded request processed cannot get attributes setup,i making webapp python using webpy i set tables login user everything initializer sessions seem work i following code store websessiondbstoredb sessions session websessionsessionapp store initializer loggedin username render webtemplaterender templates base base globals session session username sessionusername but throws error attributeerror threadeddict object attribute username what done i basically followed example httpwebpyorgcookbooksessions,1 it depends want if want list changed call f use def flist listappend flist see happens l fl modifies l inplace l if want list changed def flist flist now see l fl leaves l alone l,why following code give none how i resolve def flist flistappend def flist printlist f what also work def flist arg listappend farg,3 try changing url mapping urls index login login login work login login url paths it better show exception get,ive recently gotten webdesign python i tried multiple frameworks webpy seems favorite except one problem i cant seem figure make multiple pages multiple templates code far import web urls index login login app webapplicationurls globals render webtemplaterender templates class index def getself return renderindex class login def getself return renderlogin name main apprun i get error i try go login page,1 go throuh android device browser httpcodegooglecompandroidscripting download pythonapk file click open install installed case problem download download desktop machine copy computer far know urwid installit sla,how i download zipped files containing python source code android sla i tried going website downloading download always fails also i install pythonurwid android,1 the httpmywikisiteorgwapiphp example mediawiki domain try httpenwikipediaorgwapiphp searches english wikipedia,i using wikitools package parse wikipedia i copy example documentation but working when i run code i get following error invalid jsontrying requesting can please help thanks wikitools import wiki wikitools import api create wiki object site wikiwikihttpmywikisiteorgwapiphp define params query params action query titles papori create request object request apiapirequestsite params query api result requestquery,2 you need point python file need import keyword so mainpy file otherpythonfile import surfaceareacalculator scientificcalculator this way run otherpythonfilepy file within mainpy if want run content txt file i guess could use eval execfile don know good idea though,is possible run another python file main python file for example i file mainpy servers main directory following files surface area calculator scientific calculator how would import python file i hoping i keep organized could possible open file txt format written python thanks,1 check ahocorasick algorithm,i string like inputstring first sentence book first sentence really interesting first sentence always first dictionary like always first book first first sentence interesting always really interesting really sentence sentence first first sentence first sentence book what efficient way updating frequency counts dictionary one pass input string possible i get feeling must parser technique expert area stuck any suggestions,2 this kind scripts implemented much cleaner use fabric library httpdocsfabfileorgenindexhtml additionally provides nice commandline interface capabilities remote servers management via ssh all python available connect databases example import whatever need exactly question running commands user implemented sudo command user arg httpdocsfabfileorgenapicoreoperationshtmlfabricoperationssudo,i writing simple script restarts hadoop slave in script i initial changes root user after i change user hadoop perform set commands i using ossystem run commands i doubt whether works well for example uidpwdgetpwnam hadoop ossetuiduid ossystem whoami oschdir homehadoophadoop ossystem binhadoopdaemonsh stop tasktracker again i perform commands root become user hadoop execute ossystem binhadoopdaemonsh stop tasktracker i three questions is ossystem best command i use issue linux commands i able change root user user hadoop commands i able change root user i understand security issues permit i want know possibility atleast passing password does ossetuid work whoami prints user hadoop process tasktracker stopped using command perform commands manually works fine i use su hadoop instead setuid trying manually thanks help sethu,1 when confronted problem i think i know i use regular expressions start making list patterns sorted decreasing length patterns sortedcountskeys keylen reversetrue now make single massive regular expression alternation patterns allpatterns recompilejoinpatterns now run pattern input string count number hits pattern go pos true match allpatternssearchinputstring pos match none break pos matchstart countsmatchgroup countsmatchgroup you end counts strings an aside believe good regular expression libraries compile large alternation fixed strings like using ahocorasick algorithm edan mentioned using regular expression library probably easiest way applying algorithm with one problem pattern prefix another pattern eg first first sentence longer pattern got count this design sort length start we deal postprocessing step go counts whenever one pattern prefix another add longer pattern counts shorter pattern be careful doubleadd that simply done nested loop correctedcounts donor counts recipient counts donorstartswithrecipient correctedcountsrecipient correctedcountsgetrecipient countsdonor that dictionary contains actual counts,i string like inputstring first sentence book first sentence really interesting first sentence always first dictionary like always first book first first sentence interesting always really interesting really sentence sentence first first sentence first sentence book what efficient way updating frequency counts dictionary one pass input string possible i get feeling must parser technique expert area stuck any suggestions,1 in template use requestuserisauthenticated instead userusername that solve problem on hand i know trying explicitly add user variable view why using something like def mainpagerequest return rendertoresponse mainpagehtml contextinstancerequestcontextrequest,im using django in django code following template main page called mainpagehtml html head titlemy sitetitle head body hwelcomeh userusername pwelcome userusername p else pwelcome anonymous user you need hrefloginlogina endif body html i following view template def mainpagerequest template gettemplate mainpagehtml variables context user requestuser output templaterendervariables return httpresponseoutput this works expectedie checks user already logged greets accordingly but replace view code always get message anonymous user main page irrespective whether logged def mainpagerequest return rendertoresponse mainpagehtml user requestuser what could going wrong please help thank you,2 the aho–corasick seems definitely way go i needed simple python implementation i write import collections def consecutivegroupsseq n return seqiin rangelenseqn def getsnippetocurrencessnippets splitsnippets ssplit snippets maxsnippetlength maxlensp sp splitsnippets group consecutivegroupsinputstringsplit maxsnippetlength lst splitsnippets grouplenlst lst yield joinlst print collectionscountergetsnippetocurrencessnippets counter first sentence first sentence first first first sentence book book interesting really sentence really sentence interesting,i string like inputstring first sentence book first sentence really interesting first sentence always first dictionary like always first book first first sentence interesting always really interesting really sentence sentence first first sentence first sentence book what efficient way updating frequency counts dictionary one pass input string possible i get feeling must parser technique expert area stuck any suggestions,1 the modulus operator the remainder divide two number for example remainder divided remainer divided divides evenly,in tutorial example finding prime numbers n range x range n n x printn equals x nx break else loop fell without finding factor printn prime number i understand double test equality i understand n x part like i verbally walk part say statement example but i understand percentage sign falls what n x actually say,1 this code help believe show code import sys pyqt import qtgui qtcore pyqtqtgui import qdialog qapplication qpushbutton qlineedit qformlayout qsystemtrayicon class exampleqtguiqwidget def initself superexample selfinit selfinitui def inituiself selficon qsystemtrayicon r selficonissystemtrayavailable print r selficonseticonqtguiqicon homevzadesdesktopwebpng selficonshow selficonsetvisibletrue selfsetgeometry selfsetwindowiconqtguiqicon homevzadesdesktopwebpng selfsetwindowtitle message box selfshow selficonactivatedconnectselfactivate selfshow def closeeventself event reply qtguiqmessageboxquestionself message are sure quit qtguiqmessageboxyes qtguiqmessageboxno qtguiqmessageboxno reply qtguiqmessageboxyes eventaccept else selficonshow selfhide eventignore def activateself reason print reason reason selfshow def iconactivatedself reason reason qtguiqsystemtrayicondoubleclick selfshow def main app qtguiqapplicationsysargv ex example sysexitappexec name main main,is way minimize tray pyqt i already worked qsystemtrayicon class i would like minimize hide app window show tray icon has anybody done any direction would appreciated using python pyqt window xp pro,1 call mywindowstick,i working timer certain time show popup window i want force user accept fact time i would like set window visible workspaces i able set property manually window manager application how ask window manager make window show workspaces,2 i struggling unzipdecompressextract zip files python well create zipfile object loop namelist read files write file system lowlevel approach seem python so i started dig zipfile objects i believe well documented covered object methods zipfile import zipfile filepath srvpydocfilespackagesebookzip zip zipfilefilepath dirzip nametoinfo getcontents realgetcontents del doc enter exit init module allowzip didmodify extractmember filepassed writecheck close comment compression debug extract extractall filelist filename fp getinfo infolist mode namelist open printdir pwd read setpassword startdir testzip write writestr there go extractall method works like tarfile extractall python not then performance concerns file ebookzip mb mostly pdf files uncompressed folder mb zipped default archive utility macosx so i python timeit module timeit import timer timerfilepath srvpydocfilespackagesebookzip extractto tmppydocnetbuild zipfile import zipfile zipfilefilepathextractallpathextractto ttimeit took less seconds heavy loaded machine memory used applications hope helps someone,can somebody please explain following mystery i created binary file size mb zipping ubuntu using terminal took less sec i tried python zipping programatically using zipfile module took also sec i tried unzip zip file i created in ubuntu using terminal took less sec in python code unzip used zipfile module took close sec run ideas,1 it much better idea use su switch user id using ossetuid why su set login credentials correctly including group id supplemental groups su also useful things setting environment variables particularly use su maybe also set ulimit limits according limitsconf,i writing simple script restarts hadoop slave in script i initial changes root user after i change user hadoop perform set commands i using ossystem run commands i doubt whether works well for example uidpwdgetpwnam hadoop ossetuiduid ossystem whoami oschdir homehadoophadoop ossystem binhadoopdaemonsh stop tasktracker again i perform commands root become user hadoop execute ossystem binhadoopdaemonsh stop tasktracker i three questions is ossystem best command i use issue linux commands i able change root user user hadoop commands i able change root user i understand security issues permit i want know possibility atleast passing password does ossetuid work whoami prints user hadoop process tasktracker stopped using command perform commands manually works fine i use su hadoop instead setuid trying manually thanks help sethu,1 to extend frã©dã©ric answer bit reference counts section docs explains supplementary cycle detection nicely since i find explaining things good way confirm i understand examples with two classes class withdelobject def delself print deleting object selfclassname idself class nodelobject pass creating object losing reference triggers del method thanks refcounting withdel none leaving withdel object references deleting withdel object if make reference loop two objects del method still leakfree time thanks cycle detection first enable garbagecollection debug output import gc gcsetdebuggcdebugcollectable gcdebuguncollectable gcdebugobjects then make reference loop two objects nodel b nodel aother b bother cyclical reference none b none leave referencecycle gccollect gc collectable nodel xed gc collectable nodel xed gc collectable dict xc gc collectable dict xb gcgarbage dict objects internal dict attribute all fine even one objects cycle contains del method nodel b withdel aother b bother none b none gccollect gc uncollectable withdel xedd gc uncollectable dict xb gc uncollectable nodel xed gc uncollectable dict xc gcgarbage mainwithdel object xedd as paul mentioned loop broken weakref import weakref nodel b withdel aother weakrefrefb bother could also weakref then b reference withdel object lost gets deleted despite cycle b none deleting withdel object aother weakref xbf dead oh objgraph would helpfully indicated problematic del method like,using objgraph i found bunch objects like will python garbage collector deal cycles like leak a slightly wider view loop,3 you try pyscripter fast ide very small memory footprint intuitive interface supports codecompletion remotedebugging free amp opensource,i student year computer science class previously taught visual basic teacher looking language ide teach class crossplatform easy learn i suggested python language however would also like teach ide includes form builder addition typical functions ide editor project management code completion debugging etc having ever developed text editor usually nano relevant compiler i know next nothing ides would good use i also realised python bindings multitude graphical toolkits one probably chosen use behindthescenes ide form builder certainly another thing consider could anyone suggest free open source ide python would fit class needs would able run windows mac os x linuxbased operating systems least for recommend plain console programming best start beginners i agree if i teacher i direct students straight python console already installed computers start teaching programming tainted issues gui programming however i would still like find ide case says follow curriculum strictly needs teach gui programming ideform builder,2 you type ex import lexicon python shell typed command line command list mail hence varmail location you tell different error messages commands produce localhost ex import lexicon read varmailex localhost python python va jun gcc apple inc build dot darwin type help copyright credits license information ex import lexicon traceback recent call last file stdin line module importerror no module named ex,in ex told call lexiconpy file created ex following command when i try import lexicon file following command ex import lexicon returns following read varmailex i tried looking what mean is file wrong place,3 if used java know one public class per file name file sorry changed true i used java this javac compiling program find dependent notyetcompiled classes files python actually something similar one module per file module name file you notice explicitly declare module foopy class a pass barpy import foo printfooa see foo automatically become module so almost thing python classcentric java uses module main unit break files so answer question yes perfectly ok many classes want one file module,i learning python wxpython so far i following examples anothertutorial mainly wxpython related i trying understand following code import wx class mymenuwxframe def initself parent id title wxframeinitself parent id title wxdefaultposition wxsize menubar wxmenubar file wxmenu edit wxmenu help wxmenu fileappend ampopen open new document fileappend ampsave save document fileappendseparator quit wxmenuitemfile ampquittctrlq quit application quitsetbitmapwximage stockexitpng wxbitmaptypepngconverttobitmap fileappenditemquit editappend check item wxitemcheck editappend check item kindwxitemcheck submenu wxmenu submenuappend radio item kindwxitemradio submenuappend radio item kindwxitemradio submenuappend radio item kindwxitemradio editappendmenu submenu submenu menubarappendfile ampfile menubarappendedit ampedit menubarappendhelp amphelp selfsetmenubarmenubar selfcentre selfbindwxevtmenu selfonquit id def onquitself event selfclose class myappwxapp def oninitself frame mymenunone menupy frameshowtrue return true app myapp appmainloop it mainly line onwards confuses defines another class myapp should separate py module type class instantiates mymenu class i using eclipse typed entire code tired run got error messages traceback recent call last file cwssamplesimpleguimenupy line module app myapp file cpythonlibsitepackageswxmswunicodewxcorepy line init selfbootstrapapp file cpythonlibsitepackageswxmswunicodewxcorepy line bootstrapapp return corepyappbootstrapappargs kwargs file cwssamplesimpleguimenupy line oninit frame mymenunone menupy file cwssamplesimpleguimenupy line init menubarappendmenufile ampedit file cpythonlibsitepackageswxmswunicodewxcorepy line append return coremenubarappendargs kwargs wxcorepyassertionerror c assertion mmenubar failed srccommonmenucmncpp wxmenubaseattach attaching menu twice can anyone shed light would classes py module note noob assume entry level knowledge oop i got working machine but i really trying understand code especially appmyapp line what zero another number like text like hello,2 you regular expression matches refindall xxbeginendxx result beginxxxxxxend see working online ideone,lots questions split python i find corresponding problem i want split string need different values splitter depending condition for test case string xxxxxxbeginxxxxxxendxxxx i want process string chunks meaning i want step like split something split something split something split beginxxxxxxend something split something split something i tried recursive function import string mystring xxxxxxbeginxxxxxxendxxxx def makechunkss try splitter except nameerror splitter xx whole ssplitsplitter current whole try whole except nameerror return else rest whole currentfindbegin splitter end else splitter xx makechunksrest printaa current bb makechunksmystring but i getting error list index range maybe entire approach flawed better ways achieve i want i grateful hint thanks,3 another way hinges python interpreter started it requires start python using o production o debugging so require external discipline might hard maintain might fit processes perfectly from python docs see builtin constants debug this constant true python started o option usage would something like debug print python started without optimization,is simple way detect within python code code executed python debugger i small python application uses java code thanks jpype when i debugging python part i like embedded jvm given debug options,2 what splitting joining ones begin end ssplit mystringsplitxx bindex ssplitindexbegin eindex ssplitindexend bend xxjoinssplitbindexeindex others ssplitbindex sspliteindex beginend token bend remaining tokens others,lots questions split python i find corresponding problem i want split string need different values splitter depending condition for test case string xxxxxxbeginxxxxxxendxxxx i want process string chunks meaning i want step like split something split something split something split beginxxxxxxend something split something split something i tried recursive function import string mystring xxxxxxbeginxxxxxxendxxxx def makechunkss try splitter except nameerror splitter xx whole ssplitsplitter current whole try whole except nameerror return else rest whole currentfindbegin splitter end else splitter xx makechunksrest printaa current bb makechunksmystring but i getting error list index range maybe entire approach flawed better ways achieve i want i grateful hint thanks,1 better subjective i gladly offer opinion toolkit better tkinter task this task seemingly need much eye candy ability print tkinter weak points tkinter easy use modern stable customizable plus probably already it canvas widget incredibly easy use considering drawing heat maps charts graphs whatever others doubt say way wxpython better way pyqt better and frankly right they fine toolkits for i would argue toolkit matter pick toolkit use,i creating disk analyzer linux i would like know python toolkit help gui i currently trying tkinter something better,1 you might using isp fakes dns results order give spam page helpful search page instead error nonexistant names what ping nonexistentsitecom result machine tested python code,i new python network programming i trouble simple program i basically opening connection nonexistent website somehow seems connection succeeds moreover i get return code means http server responded exists connection ok here relevant part code import httplib conn httplibhttpconnectionnonexistentsitecom connrequestget r conngetresponse print rstatus rreason connclose and i try googlecom existing website instead nonexistentsitecom i get moved permanently could kindly clarify happening please i using visualstudioironpython matters,2 collections import counter b c abc li b c b c c sortedcounterx x liitems map list onto desperately want list lists,i have long list structure li b c bc ac i want write loop calculate amount elements lii identical value put information new list like li the problem know value many different values searching thank,2 class meetingmodelsmodel organizermodelsforeignkeyuser relatednamemeetingsorginizer participantsmodelsmanytomanyfielduser relatednamemeetingsparticipants if user object want follow relationship backwards find either meetings user organizer meetings user participant need specifically name relatedname field model distinguish now follow relationship backwards like userobjectsgetid meetings i organising memeetingsorginizerall meetings i participating memeetingsparticipantsall httpsdocsdjangoprojectcomendevtopicsdbmodelsbecarefulwithrelatedname relatedname mean django,i need define meeting model includes organiser number participants all participants derived standard user auth module djangodb import models djangocontribauthmodels import user class meetingmodelsmodel organizermodelsforeignkeyuser participantsmodelsmanytomanyfielduser however running syncdb i got following error error one models validate hubmeeting accessor field organizer clashes related mm field usermeetingset add relatedname argument definition organizer hubmeeting accessor mm field participants clashes related field usermeetingset add relatedname argument definition participants can anyone help solve,2 problem stated error message backwards relations define foreign key manymany django sets reverse relation usermeetingset however since two relations reverse relations clash specify related names manually see docs code answer,i need define meeting model includes organiser number participants all participants derived standard user auth module djangodb import models djangocontribauthmodels import user class meetingmodelsmodel organizermodelsforeignkeyuser participantsmodelsmanytomanyfielduser however running syncdb i got following error error one models validate hubmeeting accessor field organizer clashes related mm field usermeetingset add relatedname argument definition organizer hubmeeting accessor mm field participants clashes related field usermeetingset add relatedname argument definition participants can anyone help solve,1 if want locals mod sys locals mymodule importmod mymoduleversion r aug msc v bit intel would work globals,i writing python application takes command argument example python myapppy command i want application extensible able add new modules implement new commands without change main application source the tree looks something like myapp initpy commands initpy commandpy commandpy foopy barpy so i want application find available command modules runtime execute appropriate one currently implemented something like command sysargv try commandmodule importmyappcommandss command fromlistmyappcommands except importerror display error message commandmodulerun this works fine i wondering possibly idiomatic way accomplish code note i specifically want get using eggs extension points this opensource project i expect plugins the point simplify main application code remove need modify time new command module added,3 tornado intended used multithreading it based epoll switch context different parts code in general i would recommend sending data separate worker process via message queue like pika rabbitmq integrates well tornado worker processes accumulate messages data write database batch could implement logic data processing setup alternatively use example redis brukva asynchronously write incoming data inmemory database turn asynchronously dump disk depending redis configuration,i new tornado python threads what i would like achieve following i tornado web server takes requests users i want store data locally write periodically data base bulkinserts import tornadoioloop import tornadoweb import threading keep userdata locally memory userdata def backgroundf threading decorator use background function want thread run background def bgfa kw threadingthreadtargetf argsa kwargskwstart return bgf background def postrecentdatatodbthreaditer iter iter send data db userdata timesleep class addhandlertornadowebrequesthandler def postself userid selfgetargument ui data selfgetargument data userdatauserid data name main tornadooptionsparsecommandline printstart postrecentdatatodbthread here start thread periodically sends data data base the thread called every min postrecentdatatodbthread printstarted tornado port optionsport application tornadowebapplication r mainhandler radd addhandler applicationlistenoptionsport tornadoioloopioloopinstancestart is good way achieve goal i would like minimize server blocking time or i rather use gevent anything else can i run problems accessing userdata tornado thread data consistency important long server crash,3 adding object list prevent deleted child processes forking call osexit instead clearing whole stack the relevant code multiprocessingforkingpy constructor popen called pstart selfpid osfork selfpid random sysmodules import random randomseed code processobjbootstrap sysstdoutflush sysstderrflush osexitcode where bootstrap setups new process calls run code multiprocessingprocesspy,in following program i append process list seemingly pointless thing runs expected but i remove append processes destructor called many times even run there n constructions nn n number processes destructions this leads believe process copied new process immediately destroyed perhaps multiprocessing module works it makes sense since process fork current one but significance appending list why simply stop behaviour here test sample output import multiprocessing class procstop pass class procmultiprocessingprocess def initself q si selfi si selfq q print constructing si superinit def runself dat selfqget dat procstop selfqtaskdone dat selfqget selfqtaskdone print returning selfi def delself print destroying selfi name main q multiprocessingjoinablequeue multiprocessingmanagernamespace si pool range p procq pstart poolappendp this line comment range qputi qjoin range qputprocstop qjoin print complete sample output append constructing constructing constructing constructing returning returning complete returning returning destroying destroying destroying destroying sample output without append constructing constructing constructing destroying constructing destroying destroying destroying destroying destroying returning returning returning complete returning destroying destroying destroying destroying,1 yes seems like problem related subdomains using route tornado php without details hard tell fix but general maybe good idea map tornado relative url main domain mess subdomains ps storing loginpassword pairs cookies plain text secure i recomend use unique session id mapped users via common database php tornado,i using apache php frontend server tornado backend handle requests when allowing user login i want create cookies username password if i follows selfsetcookie emailaddress emailaddress domain mydomaincom expiresnone path expiresdaysexpired selfsetcookie password newpass domain mydomaincom expiresnone path expiresdaysexpired nothing created but i selfsetcookie emailaddress emailaddress selfsetcookie password newpass it works but even though cookies i see firefox firebug php frontend recognize also i know crossdomain i tornado server proxy apache,1 tornadio works well enough stable version socketio integrates tornadopowered application common request handler wrapped around class socket events callbacks works pretty stable but i recommend use provided socketserver class configure correctly common httpserver tornado take look socketserver implementation guideline,anyone show example handle generic socketio connection depends client browser could websockets xhrlongpolling etc using gevent flask maybe flask tornado async server thank,2 windows rename path open file it work move osrename call block file closed however repeating multiple files path directory name path longer exist renamed also oswalk traverse subdirectories renamed parent directory i would check config files walking tree append path newpath tuples list then i rename directories reverse order also match might none case trying access matchgroup raise attributeerror and windows system calls seem handle mixed separators fine case want skip windowsify step to clean path printinglogging ospathnormpath consistently uses ospathsep well resolving path,i wrote fast easy hack walk thru directories stepmania song dir find conffiles name directory conffiles certain name found conffile this works great linux box but wives windows xpbox running admin i get permissionerror what wrong here code usrbinenv python codingutf future import withstatement import os import import sys def renamerinpath path dirs files oswalkinpath exts sm dwi only search files suffix conffiles create list conffiles ext exts conffilesextendfile file files filelowerendswithext search conffiles directory conffile conffiles try openospathjoinpath conffile f match research titles fread search whatever follows title newdirname matchgroup the new dirname whatever title states conffile osrenamepath ospathjoinpath newdirname except indexerror print no conffile path name main path sysargvreplace windowsify path renamerpath,1 it sounds like want requesturl whatever user typed address bar requestget dictionary keyvalues query string requestpost dictionary keyvalues request body requestparams dictionary combination this might better explained webob documentation effectively pyramid using request response objects httpdocsweboborgenlatestindexhtml,i looking pyramid api able find method allows extract url user address bar specifically including query strings is method i keep skimming across httpdocspylonsprojectorgprojectspyramiddevapirequesthtml,2 define globally accessible env variable use select version versionaversionb then commoninitpy put import whenveryouputyourenv envloc envlocenv versiona import versionapackage package elif envlocenv versionb import versionbpackage package now whenever want use package file able import commonpackage good go,i two different packages name set modules classes names implemented differently what logical manner set packagemodule structure right i something like common utilitiespy versiona package modulexpy moduleypy versionb package modulexpy moduleypy i requiring environment modules used set path point correct version package on top one module packages share utilitiespy now i also asking installer add utiltiespy path this confusing feels like hack however i figure better way,2 here wxglade automaticallygenerated code showing use wxboxsizer it simply frame panel widget you change panel button work perfectly the idea could add widgets done wxpanel sizeraddselfpanel wxexpand produce widgets situated row if want another disposition could use different sizer you also add sizers widgets sizers the parameters sizeradd determine borders behavior sizer you check wxpythonwxglade documentation anyway estructure always like one import wx begin wxglade extracode end wxglade class myframewxframe def initself args kwds begin wxglade myframeinit kwdsstyle wxcloseboxwxsystemmenu wxcaption wxframeinitself args kwds selfpanel wxpanelself create widgets selfsetproperties selfdolayout end wxglade def setpropertiesself begin wxglade myframesetproperties selfsettitleframe selfsetminsize end wxglade def dolayoutself begin wxglade myframedolayout sizer wxboxsizerwxvertical sizeraddselfpanel wxexpand add widgets even sizers sizer selfsetsizersizer sizerfitself selflayout end wxglade end class myframe name main app wxpysimpleapp wxinitallimagehandlers frame myframenone appsettopwindowframe frameshow appmainloop,i sure i size i trying use sizer seems something wrong time basically code selfbutton wxbuttonself labelcreate new pos would like use sizer so adjust position always window the initial starting position the height initial window i would like button adjust accordingly window changes thank please comment questions need clarification,1 conceptually i think might you read django docs essentially django types inheritence abstract multitable proxy useful different situations abstract inheritance useful base class never need instantiated ie base model table children tables multitable inheritance useful base model useful extended ie base model table children tables proxy useful want extend functionality parent model ie base model table children tables quick example multi table class answermodelsmodel answertext modelscharfield class questionmodelsmodel what questions common title modelscharfield text modelscharfield answer modelsforeignkeyanswer class pythonquestionquestion what specifics python question might pythonversion modelscharfield you able enter data one go django admin multitable abstract inheritence furthremore you answer attached every question these answers uploaded via fixtures needs manually entered admin,i using django admin page put questions database my modelspy djangodb import models create models class questionmodelsmodel questionname modelscharfieldmaxlength questiontype modelscharfieldmaxlength def unicodeself return selfquestionname class pythonquestionmodelsmodel questionno modelsforeignkeyquestion questiontext modelstextfieldmaxlength questiontestcase modelstextfieldmaxlength questiondifflevel modelscharfieldmaxlength i want particular changes djangoadmin page as i able add contents question model pythonquestion model admin page what i want i able write question model directed page i write data pythonquestion model my pages running i need directing links i want upload answers questions file formatdoesn matter format herelets assume text file how i admin page,1 i found solution copying parts array new numpy array this new numpyarray could used every new binding using numpy arryy size xx size tmp nparray dtype arrdtype return tmp arr numpyarrayimage size tuple x coordinates,how i set roi numpy array since new pythonbindings cv support imageroi maybe i use right i want convert iplimage numpy thanks help,1 your regex catching everything first first country entry infobox if want everything first last want make inside braces greedy removing researchr msinfobox film text note find last input eg another template far end infobox find end may want when nesting things like regex always best way search,my regex working properly i showing regex text regex text i using regex researchr msinfobox film text you see regex displaying result country assam ind my regex stuck point will please help thanks before regex infobox film name papori released runtime minutes country assam ind language assamese languageassamese budget followed free after regex infobox film name papori released runtime minutes country assam ind why regex stuck point country assam ind edit expecting result infobox film name papori released runtime minutes country assam ind language assamese languageassamese budget followed free,1 often searching based lastprocessed field may worth indexing otherwise looks fine,i batch job processes records order oldest record in django i model defined similar class mymodelmodelsmodel name modelscharfield lastprocessed modelsdatetimefieldblanktrue editablefalse nulltrue i need get oldest record datetimefield lastprocessed i understand django way mymodelobjectsorderby lastprocessed get however faster efficient way execute query i expecting database grows possible million records continually running query seem efficient system specification centos python django postgresql,1 do index lastprocessed if query efficient regardless size table,i batch job processes records order oldest record in django i model defined similar class mymodelmodelsmodel name modelscharfield lastprocessed modelsdatetimefieldblanktrue editablefalse nulltrue i need get oldest record datetimefield lastprocessed i understand django way mymodelobjectsorderby lastprocessed get however faster efficient way execute query i expecting database grows possible million records continually running query seem efficient system specification centos python django postgresql,2 it clear need one application per site there possibilities difference sites templates static files need separate application every site if difference global really combine sites one project rather reuse common applications many projects one project per site as multiple databases probably look django builtin sites framework need within single database,i planning i going architecture cms and would like advice the plan i create project called cms in i create apps folder various apps admin module blog module etc and new site i develop i also create new app within project so means siteapp i create need database possible and secondly good idea general or i create new site new project i figured would good idea i easily reuse applications across sites thanks,1 some people confronted problem think i know i use regular expressions now two problems jamie zawinski actually use two regular expressions four problems first go break text alternating chapterheaders notchapterheadings then examine notchapterheading sentences paragraphs how would break following visiting leipzig chapter one thomaskirchhof st the bach museum thomaskirchhof opposite st thomas church van beethoven museum anywhere leipzig processing natural language devilishly difficult god thorough job he destroyed tower babel,i running text many sentences i regular expression able extract sentences terminated period question exclamation mark the end sentence must followed beginning next sentence white spacestabsnew lines capital letter number i read string stored data call regex basicpat recompiler w sazd result basicpatfindalldata this regex seems working take consideration abbreviation cases in text i may also chapter texts end period for example this first chapter here first sentence here second sentencehere ids third sent here fourth sent my question possible one regex reads chapter texts well regex reads sentences the chapters loose text line without period regular sentences may cover several lines that sentences may also text line without period is possible differentiate two situations chapter vs sentences regex,2 it possible seek position media source whilst still loading so connect handler media object statechanged signal wait state changes playingstate attempting seek selfplayermediaobjectstatechangedconnectselfhandlestatechanged def handlestatechangedself newstate oldstate newstate phononplayingstate selfplayerseek,i wrote simple video player using phonon pyqt the videos playing fine but i unable seek video given position this code i written usrbinpython pyqtqtcore import pyqtqtgui import pyqtphonon import phonon import sys class videoplayerqwidget def initself address parent none selfaddress address qwidgetinitself selfplayer phononvideoplayerphononvideocategory self selfplayerloadphononmediasourceselfaddress window qhboxlayoutself windowaddwidgetselfplayer selfsetwindowtitlesimple video player selfplayerplay selfplayerseek app qapplicationsysargv vp videoplayersysargv vpshow appexec all i trying start stop video given positions thanks advance,1 you could use tarfile library extract extractall extractfile methods you able access nontoplevel objects archive way just note path extractall path inside archive rather path want extract putting baz help you probably first call getmembers pare list want call one extract methods,premise i directory foobar i tar file containing directory baz problem extracting contents baz archive foobar example the archive contains baz filetxt the source directory contains foo bar filetxt after extraction i want foo bar filetxt filetxt solutions far extract temporary directory move contents baz target location works since i baz directory always name any ideas,1 modulepy import module works,python imports drive crazy experience python imports sometime correspond idiom explicit better implicit app startpy package import module package initpy print init package modulepy print init packagemodule import module modulepy print init packagemodule import sys pprint pprintpprintsysmodules import module i get vicubuntudesktopapp python startpy init package init packagemodule init packagemodule main module main startpy package module package homevicdesktopapppackageinitpy packagemodule module packagemodule homevicdesktopapppackagemodulepy packagemodule module packagemodule homevicdesktopapppackagemodulepy traceback recent call last file startpy line module package import module file homevicdesktopapppackagemodulepy line module import module file homevicdesktopapppackagemodulepy line module import module importerror cannot import name module vicubuntudesktopapp import packagemodule works want use import module want make package portable applications want use relative paths i using python i need circular imports a function module asserts one parameter instance class defined module viceversa in words sysmodules contains packagemodule module packagemodule homevicdesktopapppackagemodulepy i want get reference form import module tries get name package like case import packagemodule works fine i tried import module syntax error also import module module works fine import module module work update this hack works looking official way print init packagemodule import sys pprint pprintpprintsysmodules import module parentmodulename namerpartition module sysmodulesparentmodulename module,1 it perfectly feasible not sure doesnt work this example works perfectly mainpy import wx class mainframewxframe def initself parent wxframeinitself parent title main size button wxbuttonself call app pos size selfbindwxevtbutton selfcapp button def cappself event import datadeck datadeckrun name main app wxapp frame mainframenone frameshow appmainloop datadeckpy import wx class ddframewxframe def initself parent wxframeinitself parent title ddframe size button wxbuttonself print something pos size selfbindwxevtbutton selfsayhello button def sayhelloself event print something class datadeckwxapp def oninitself frame ddframenone frameshow return true def run app datadeck appsetappnamedatadeck appmainloop press call app button get new frame open and open many want created aplicationsframes independent you close without affecting others and system doesnt freeze,is possible run wxapp another wxapp i trying simply call program i wrote called datadeck method another wxapp like plugin something like def ondatadeckbtnclickself event import datadeckmain datadeckmainrun eventskip datadeckmainrun classic start wxapp def run app datadeck appsetappnamedatadeck appmainloop right correctly opens datadeck first time works reopen datadeck second time i close this would freeze everything update based mike driscoll answer i documented came following solution i added entry point datadeck def runasplugin stuff related xrc layouts sysout redirection maingui datadeckguimainguimaingui where constructor maingui automatically shows wxframe now application behaves like component caller wxapp therefore i modify application method follows def ondatadeckbtnclickself event import datadeckmain datadeckmainrunasplugin eventskip it simple indeed i modify objects deal stdout redirection part question i omit details everything worked fine,1 here you already pretty ready code look diferences you overwritting groceries reading value dictionary in python x shoud use rawinput instead input if pyk input ok also need parenthesis print pyx you pyk maybe bizarre thing homework use print it means substituted string last sign be careful cost groceries actually strings make mathematical operations first convert floats def main key infile open shoppinglisttxt r count infilereadline groceries print this program keeps running total shopping list print use exit exit grocery rawinput enter item line infile line linestrip take newlines codes key key line else grocerieskey line maybe use floatline instead key print your current total groceriesgrocery main for several inputs use tested pyk code remember convert costs floats total true grocery input enter item grocery exit print your final total total break else cost groceriesgrocery total cost print your current total total,i trying read simple text file looks like eggs milk bread coffee sugar flour apple cheese orange bananas potato what i trying ask input file name milk print price i trying use dictionaries here code def main key infile open shoppinglisttxt r count infilereadline groceries print this program keeps running total shopping list print use exit exit grocery input enter item line infile line linestrip key key line else grocerieskey line maybe use floatline instead key print your current total groceriesgrocery main expected output this program keeps running total shopping list use exit exit enter item eggs your current total enter item bread your current total enter item sugar your current total enter item exit your final total,1 circular imports generally avoided see also answer related question article effbotorg in case problem import current package so import x imports go package’s initpy you make problem bit visible explicitely import modules initpy give another name adjust imports use names course print init package import module import module now importing startpy package first initializes comes import line at point known initpy get import error if switch import statements initpy around load first finds import line fails reason if don’t explicitely import modules initpy something similar still happens background the difference get less flat structure imports longer started package as module module get “started” get respective initialization prints to make work could absolute import module that way could avoid package needs resolve everything first make reuse import startpy import path or even better get rid circular import it’s generally sign application structure good circular references i hope explanation makes sense i already difficulties writing general idea clear i hope… edit in response update use full package name get reference module this equivalent much complicated first possible option make work use absolute import using import path startpy,python imports drive crazy experience python imports sometime correspond idiom explicit better implicit app startpy package import module package initpy print init package modulepy print init packagemodule import module modulepy print init packagemodule import sys pprint pprintpprintsysmodules import module i get vicubuntudesktopapp python startpy init package init packagemodule init packagemodule main module main startpy package module package homevicdesktopapppackageinitpy packagemodule module packagemodule homevicdesktopapppackagemodulepy packagemodule module packagemodule homevicdesktopapppackagemodulepy traceback recent call last file startpy line module package import module file homevicdesktopapppackagemodulepy line module import module file homevicdesktopapppackagemodulepy line module import module importerror cannot import name module vicubuntudesktopapp import packagemodule works want use import module want make package portable applications want use relative paths i using python i need circular imports a function module asserts one parameter instance class defined module viceversa in words sysmodules contains packagemodule module packagemodule homevicdesktopapppackagemodulepy i want get reference form import module tries get name package like case import packagemodule works fine i tried import module syntax error also import module module works fine import module module work update this hack works looking official way print init packagemodule import sys pprint pprintpprintsysmodules import module parentmodulename namerpartition module sysmodulesparentmodulename module,3 try carefull devinputevent changed place repluging multiple usb hiddevices import struct inputdevice devinputevent keyboard system inputeventformat iihhi inputeventsize file openinputdevice rb standard binary file input event filereadinputeventsize event time time type code value structunpackinputeventformat event print typecodevalue event filereadinputeventsize fileclose def getusbhidsself sgetexecoutput cat procbusinputdevices events rangelens mresearch handlerskbdeventpname si events devevent mgroup name return events,i currently working embedded system needs read keyboard input actually needs read keyboardemulated barcode scanner i using sheevaplug debian squeeze hardware part i using pretty basic init script fires python program charge business logic it script needs read keyboard input we worked development versions basically full featured computers screen stuff worked pretty ok really acceptable i really grasp wrong although i admit i kinda expected so i like know would possible somehow connect keyboard script stdin init starts alternatively i interested someone knows python library would allow bypass problem entirely read directly inputeventx thanks advance,1 you want loop filenames lines input file simultaneously replace nested loops name line zipeventlist coordsfilereadlines adictsetdefaultname appendlinestrip i took liberty compressing loop body one line if amount data processed extremely large replace zip lazy cousin izip itertools import izip name line izipeventlist coordsfile btw chdir middle function grab single file code smell you easily open right file openospathjoinpath reloccoordcomplete,i using oslistdir file create dictionary i getting keys values respectively oslistdir gives event event event file i get the main problem final dictionary different keys always value i want what i trying get event event event so i think code looping keys values anyway code far def reloceventcoordsdic eventlist oslistdir usersworkingdirectoryobservedarrivalslocd adict oschdirpath declared somewhere else open reloccoordcomplete r coordsfile line coordsfile line linestrip gives values name eventlist name key entry adictget name entryappend line adict name entry return adict thanks reading,1 you could perhaps use true telnet ssh server set user login shell ipython for instance given user whose name adam perhaps could change user etcpasswd line something like adamxadam fristhomeadamusrbinipython typically final segment line actual login shell like bash the advantage skip coding solution may disadvantage might hack environment variable python path work you read etcpasswd file linux information project,i trying write simple telned server expose ipython shell connected client does someone know the question really embedding ipython shell telnet server i probably use twisted telnet server part thx,1 you create new one since ordereddict sorted insertion order in case code would look like foo ordereddictsortedfooiteritems keylambda x x depth see httpdocspythonorgdevlibrarycollectionshtmlordereddictexamplesandrecipes examples,i trying sort ordereddict ordereddict depth key is solution sort dictionary ordereddict ordereddict depth height width id ordereddict depth height width id ordereddict depth height width id sorted dict look like ordereddict ordereddict depth height width id ordereddict depth height width id ordereddict depth height width id idea get,3 i solved wxpostevent usrbinenv python coding utf generated wxglade mon oct import wx import timeospathglobthreading begin wxglade extracode end wxglade idstart wxnewid idstop wxnewid define notification event thread completion evtresultid wxnewid def evtresultwin func define result event winconnect evtresultid func class resulteventwxpyevent simple event carry arbitrary result data def initself data init result event wxpyeventinitself selfseteventtypeevtresultid selfdata data class myframewxframe def initself args kwds begin wxglade myframeinit kwdsstyle wxdefaultframestyle wxframeinitself args kwds selfbitmap wxstaticbitmapself wxnullbitmap selfsetproperties selfdolayout end wxglade selfframes evtresultselfselfonresult wxcallafterselfimg def setpropertiesself begin wxglade myframesetproperties selfsettitleframe end wxglade def dolayoutself begin wxglade myframedolayout sizer wxboxsizerwxvertical sizeraddselfbitmap selfsetsizersizer sizerfitself selflayout end wxglade def onresultself event show result status eventdata none pass else selfbitmapsetbitmapwxbitmapeventdata wxbitmaptypeany end class myframe def imgself thread threadingthreadtargetselfimg threadstart thread threadingthreadtargetselfimg threadstart def imgself frames globglobhomemitchpicturespng framessort rangelenframes ospathisfileframesi print framesi wxyield timesleep wxposteventself resulteventframesi def imgself frames globglobhomemitchpicturespng framessort rangelenframes ospathisfileframesi print framesi wxyield timesleep wxposteventself resulteventframesi name main app wxpysimpleapp wxinitallimagehandlers frame myframenone appsettopwindowframe frameshow appmainloop,i program time lapse maker two threads updates wxstaticbitmap when two threads access wxstaticbitmap crashes error python xcbioc pollforevent assertion long eventsequence long dpyrequest failed i tried google search answer i tried solve i still figure simple piece code reproduces error actual program usrbinenv python import wx import timeospathglobthreading class myframewxframe def initself args kwds kwdsstyle wxdefaultframestyle wxframeinitself args kwds selfbitmap wxstaticbitmapself wxnullbitmap selfsetproperties selfdolayout wxcallafterselfimg def setpropertiesself selfsettitleframe def dolayoutself sizer wxboxsizerwxvertical sizeraddselfbitmap selfsetsizersizer sizerfitself selflayout def imgself thread threadingthreadtargetselfimg threadstart thread threadingthreadtargetselfimg threadstart def imgself frames globglobpathtopngspng framessort rangelenframes ospathisfileframesi print framesi wxyield timesleep wxcallafterselfbitmapsetbitmapwxbitmapframesi wxbitmaptypeany wxcallafterselfupdate def imgself frames globglobpathtopngspng framessort rangelenframes ospathisfileframesi print framesi wxyield timesleep wxcallafterselfbitmapsetbitmapwxbitmapframesi wxbitmaptypeany wxcallafterselfupdate name main app wxpysimpleapp wxinitallimagehandlers frame myframenone appsettopwindowframe frameshow appmainloop i solved wxpostevent see answer,1 ordereddictsortedoditems keylambda item item depth,i trying sort ordereddict ordereddict depth key is solution sort dictionary ordereddict ordereddict depth height width id ordereddict depth height width id ordereddict depth height width id sorted dict look like ordereddict ordereddict depth height width id ordereddict depth height width id ordereddict depth height width id idea get,3 the len function counts length variable case length string characters to count words need split string whitespace count number items returned,i trying count number words string however first strip punctuations eg line want know name running en linetranslatestringmaketrans produces en want know name want count number words line lenen i get instead using split en tokenize find length work cases eg tried always work eg consider string ccc bcc abc ccc dd aaa abc en becomes ccc bcc abc ccc dd aaa abc lenen returns please help thanks,1 the problem ensplit extra whitespace string gives empty matches you could fix quite easily calling ensplit instead but perhaps could use different approach using regular expression need remove punctuation first import print lenrefindallr w line see working online ideone,i trying count number words string however first strip punctuations eg line want know name running en linetranslatestringmaketrans produces en want know name want count number words line lenen i get instead using split en tokenize find length work cases eg tried always work eg consider string ccc bcc abc ccc dd aaa abc en becomes ccc bcc abc ccc dd aaa abc lenen returns please help thanks,3 since cipher text short probably easiest brute force def breakvignereinput listofwords word listofwords crypt vignereword crypt input return word return none of course fail find input text listofwords,this problem i figure a message encryption using vigenere encryption method discussed class cipher text eqnvz intercepted break code assume key length message message key consist uppercase letters is way python i know way make cipher text python way go way,1 it trick question if key length message onetime pad conceals everything except message length,this problem i figure a message encryption using vigenere encryption method discussed class cipher text eqnvz intercepted break code assume key length message message key consist uppercase letters is way python i know way make cipher text python way go way,3 try future import division eliminate errors arising floor division,i porting code created octave pylab one ported equations gives dramatically different results python octave the best way explain show plots generated octave pylab equation here simplified snippet original equation octave in small test script result function phi held zero plotted pipi clear clc close l left servo arm length l left linkage length l right linkage length l right servo arm length l distance origin left servo l distance origin right servo thetaarray pipi phi pi lengththetaarray theta thetaarrayi ai lcosthetalsinphilsinthetalsinthetalllcosphilcosthetallsqrtllcosphilcosthetalsinphilsinthetalsinthetalllcosphilcosthetalcosthetalsinphilsinthetalllcosphilcosthetalsinphilsinthetallllllcosphilcosthetalsinphilsinthetalsqrtllcosphilcosthetalsinphilsinthetallllllcosphilcosthetalsinphilsinthetalcosthetalsqrtllcosphilcosthetalsinphilsinthetalsinthetalsinphilsinthetalllcosphilcosthetalcosthetalsinphilsinthetalllcosphilcosthetalsinphilsinthetalsqrtsinthetalsinphilllcosphilcosthetalsinphilsinthetalsinacosllcosphilcosthetalsinphilsinthetallllsqrtllcosphilcosthetalsinphilsinthetalasinsinthetalsinphilsqrtllcosphilcosthetalsinphilsinthetal end plotthetaarraya the resulting octave plot looks like the equation copied pasted octave python replaced acos replaced arccos asin replaced arcsin the range theta plotted phi held zero pylab import physical setup l left servo arm length l left linkage length l right linkage length l right servo arm length l distance origin left servo l distance origin right servo theta arangepipi phi pi def functhetaphi a lcosthetalsinphilsinthetalsinthetalllcosphilcosthetallsqrtllcosphilcosthetalsinphilsinthetalsinthetalllcosphilcosthetalcosthetalsinphilsinthetalllcosphilcosthetalsinphilsinthetallllllcosphilcosthetalsinphilsinthetalsqrtllcosphilcosthetalsinphilsinthetallllllcosphilcosthetalsinphilsinthetalcosthetalsqrtllcosphilcosthetalsinphilsinthetalsinthetalsinphilsinthetalllcosphilcosthetalcosthetalsinphilsinthetalllcosphilcosthetalsinphilsinthetalsqrtsinthetalsinphilllcosphilcosthetalsinphilsinthetalsinarccosllcosphilcosthetalsinphilsinthetallllsqrtllcosphilcosthetalsinphilsinthetalarcsinsinthetalsinphilsqrtllcosphilcosthetalsinphilsinthetal return a f figure faddsubplot aplotthetafuncthetaphi ginput timeout wait user click dont lose plot python result looks like i cant determine causing differences any ideas,3 use xpath method loop paragraphs para treexpathp,given flexibility html codes parsing paragraphs seen user browser seems quite nontrivial task for i robust solution tree lxmletreefromstringhtml lxmletreehtmlparser isinstancehtml basestring else html skiptag script iframe style link meta noscript option node treexpathskiptag nodegetparentremovenode paragraphs lxmletreetostringtree encodingunicode method text the problems i facing mainly tackle abnormality say freestyles one quite common case many paragraphs written one line eg code html code parse one paragraph pbla bla ppuspan classcoloredstrongbla bla strongspanuppbla bla ppbla bla p my questions good ways general parse paragraphs correctly particular case i optimize code correctly get paragraphs oneline html given p represent paragraph many ways may applied freestyle general advice,2 i familiar pyramid problem really seem line configinclude pyramidjinja whatever config thing seems dynamic import magic don the app engine environment handle imports way would normal python step line debugger wind replacement version import system soon see implements small part real python if possible use normal import statement otherwise going dig configinclude get play nice restricted importing features gae,i trying run pyramid jinja using new python runtime threadsafe mode gae prerelease sdk i made modifications app outlined ie i set runtime python threadsafe true appyaml got rid main function when i generate response works fine i try bring jinja equation i get following exception error wsgipy traceback recent call last file gaegoogleappengineruntimewsgipy line handle file myappsourcemyapptipmainpy line module configinclude pyramidjinja file myappsourcemyapptiplibdistpyramidconfiginitpy line include cconfigurator file libdistpyramidjinjainitpy line includeme getorbuilddefaultenvironmentconfigregistry file libdistpyramidjinjainitpy line getorbuilddefaultenvironment setupenvironmentregistry file libdistpyramidjinjainitpy line setupenvironment package callerpackage pyramidjinja jinja pyramidconfig file libdistpyramidjinjainitpy line callerpackage selfinspectstack file usrlibpythoninspectpy line stack return getouterframessysgetframe context file usrlibpythoninspectpy line getouterframes framelistappendframe getframeinfoframe context file usrlibpythoninspectpy line getframeinfo lines lnum findsourceframe file usrlibpythoninspectpy line findsource module getmoduleobject file file usrlibpythoninspectpy line getmodule main sysmodules main keyerror main i tried mess around bit pyramidjinja code work around issue left another exception error wsgipy traceback recent call last file gaegoogleappengineruntimewsgipy line handle handler confighandleaddwsgimiddlewareselfloadhandler file myappsourcemyapptipmainpy line module configaddjinjasearchpathtemplates file myappsourcemyapptiplibdistpyramidconfigutilpy line wrapper result wrappedself arg kw file libdistpyramidjinjainitpy line addjinjasearchpath envloadersearchpathappendabspathfromresourcespecd file myappsourcemyapptiplibdistpyramidassetpy line abspathfromassetspec return pkgresourcesresourcefilenamepname filename file myappsourcemyapptippkgresourcespy line resourcefilename return getproviderpackageorrequirementgetresourcefilename file myappsourcemyapptippkgresourcespy line getprovider importmoduleorreq file gaegoogleappenginetoolsdevappserverimporthookpy line decorate return funcself args kwargs file gaegoogleappenginetoolsdevappserverimporthookpy line loadmodule return selffindandloadmodulesubmodule fullname searchpath file gaegoogleappenginetoolsdevappserverimporthookpy line decorate return funcself args kwargs file gaegoogleappenginetoolsdevappserverimporthookpy line findandloadmodule description file gaegoogleappenginetoolsdevappserverimporthookpy line decorate return funcself args kwargs file gaegoogleappenginetoolsdevappserverimporthookpy line loadmodulerestricted description importerror cannot reinit internal module main i happy anybody could shed light pyramid trying hood judging latter stack trace seems trying resolve asset trying reload main i even sure problem caused pyramid gae thanks insight issue,1 did export apport environment variable it set port forwarded for example set forwarding port like adb forward tcp tcpsla port you need set apport entering python interpreter like export apport i script sets environment starts python interpreter httpsgithubcomgeorgegohandroidscriptingblobmasterpyastartsh i tested used ubuntu ymmv,i unable connect android scripting layer server when i run command i get following error androidandroid traceback recent call last file stdin line module file androidpy line init selfconn socketcreateconnectionaddr file libraryframeworkspythonframeworkversionslibpythonsocketpy line createconnection res getaddrinfohost port sockstream socketgaierror errno nodename servname provided known steps i taken setup adb forwarding made available androidpy file interpreter started private server connected device computer what could wrong,2 looks like problem sortedlist class defining way print try adding def strself return strselfl see discussion special methods,i trying insert new item sorted list entering item corrected sorted position list everytime test code see working though getting message really familiar know far correct able see wrong understand message getting btw allowed use builtin list functions your answer mainsortedlist object xc what far class sortedlist def initself selfl def insertself item data j rangelenselfl dataappendselflj return data,1 you code looks fine the problem data either wordsofar noletter object sqlite know store one solution pickle object another solution supply converter adapter functions use registeradapter register callable convert custom python type type one sqlite’s supported types the docs also describe supply converters handle reverse conversion sqlite natively supports types text integer float blob null if want use types must add support the detecttypes parameter using custom converters registered modulelevel registerconverter function allow easily here related so question answers,i looked answer question could find good answer i using python sqlite module query database the problem i cannot get sql query hold multiple variables for example i get query work perfectly wordsofar variable name cexecuteselect word from wordlist where word like wordsofar however i cannot get code work wordsofar noletter variable names cexecuteselect word from wordlist where word like and word not like wordsofar noletter it gives error error binding parameter i tried rewrite query instead using named convention shown httpdocspythonorgpyklibrarysqlitehtml half way page solve problem any help would much appreciated thankyou,1 your understanding code correct fwiw easy follow execution script using python trace trace somescriptpy see execution line counts python trace count somescriptpy for example latter call trace produces def somefuncastring global numas numes astring rangelenastring si numas continue si e numes numes numas break numas numes somefunc flammable,i attempting trace execution piece code contains loop two conditionals but i need help understanding exactly loops executed python please consider following example numas numes astr abcdefge def somefuncastring rangelenastring si numas continue si e numes numes numas break printsomefuncastr question using astr parameter many times line execute code my understanding line piece code rangelenastring executed while lines executed multiple times depending string passed when function encounters continue statement goes back line runs please confirm correct thinking thanks,2 a response works works well found httprnnabblecomemailoutofrcodetdhtml thank nutterb answer rhelp list thank tried assist patient ignorance python,i desiring send email r attachment using gmail i found sendmailr work gmail requires authentication i get work gmail i assume true unless someone tells i wrong case i post r output error message i found code snippet found link as site suggests code formatted send attachments i got send email i like extend code send attachments email correspondence author code unable extend code send attachments i want send emails r using gmail i windows user beta version r the code sends emails attachments requirerjython rjython rjython rjythonexec import smtplib rjythonexecfrom emailmimetext import mimetext rjythonexecimport emailutils mailc email settings fromaddr bigbirdgmailcom toaddrs oscarthegrouchgmailcom msg mimetext this body message msg from emailutilsformataddr sender name fromaddr msg to emailutilsformataddr recipient name toaddrs msg subject simple test message smtp server credentials username bigbirdgmailcom password pw set smtp server send email eg google mail smtp server server smtplibsmtp smtpgmailcom serverehlo serverstarttls serverehlo serverloginusernamepassword serversendmailfromaddr toaddrs msgasstring serverquit jythonexecrjythonmail note message cross posted talkstatscom i receive reply members telling wish could help if i receive workable solution also post well,3 this line say works shows wordsofar sequence one element cexecuteselect word from wordlist where word like wordsofar in case second line cexecuteselect word from wordlist where word like and word not like wordsofar noletter if noletter string wordsofar tuple say comment execute docs say second argument always parameters if use number parameters lenparameters equal number sql statement,i looked answer question could find good answer i using python sqlite module query database the problem i cannot get sql query hold multiple variables for example i get query work perfectly wordsofar variable name cexecuteselect word from wordlist where word like wordsofar however i cannot get code work wordsofar noletter variable names cexecuteselect word from wordlist where word like and word not like wordsofar noletter it gives error error binding parameter i tried rewrite query instead using named convention shown httpdocspythonorgpyklibrarysqlitehtml half way page solve problem any help would much appreciated thankyou,1 the problem quite simple i use mixin models inadvertently added basic model property abstract true example sqlalchemy import sqlalchemyextdeclarative import declarativebase sqlalchemyorm import sessionmaker scopedsession engine createengine sqlitememory echotrue base declarativebasebindengine session scopedsessionsessionmakerengine class mixobject abstract true id columninteger autoincrementtrue primarykeytrue class userbase mix tablename users name columnstring fullname columnstring password columnstring basemetadatacreateall u user print u but sqlalchemy works fine perhaps bug update information sqlalchemy abstract,i model class createdmixinobject abstract true declaredattr def createdbycls return columninteger foreignkey useruserid onupdatecascade ondeleterestrict declaredattr def updatedbycls return columninteger foreignkey useruserid onupdatecascade ondeleterestrict createdat columndatetime nullablefalse defaultdtnow updatedat columndatetime nullablefalse defaultdtnow onupdatedtnow class netbase createdmixin net subnet cidr columnpostgresqlcidr index true description columnunicodetext parentid columninteger foreignkey netid parent relationshipnet remotesidenetid def initself cidr selfcidr cidr def reprself return selfcidr to autofill fields createdby updateby i use sqlalchemyormeventsmapperevents sqlalchemy like def createdbeforeinsertlistenermapper connection target execute stored procedure upon insert apply value row inserted targetcalculatedvalue connectionscalar select myspecialfunctiond targetspecialnumber targetupdatedby associate listener function createdmixin execute beforeinsert hook eventlistencreatedmixin beforeinsert createdbeforeinsertlistener but run app got following error mapped sqlalchemyormexcunmappedclasserror class myappmodelnet what wrong,1 you want itertoolschain itertoolschain foo bar xrange print,i want add day front right makes drop menu numbers i want day choice top daychoices i hoping would work apparently generators work like day strx x x range i include snippet case voodoo i django import forms class signupformformsform day formschoicefieldchoicesdaychoices,3 you could read updated word list one thread process tweets another one using queue communication example thread reads tweets def readtweetsq words qget true tweetstreamfilterstreamtrackwords stream tweet stream noteit requires special handling blocks processtweet try words qgetnowait try read new word list except empty pass else break start new connection thread reads words def readwordsq words none true open wordstxt file newwords filereadsplitlines words newwords qputnewwords words newwords timesleep the main script could look like q queue threadtargetreadtweets argsq tdaemon true tstart readwordsq instead polling could use inotify similar monitor changes wordstxt file,i need save realtime database tweets twitter streaming api filtering certain list words course i achieved using tweetstream defining list words like calling filterstream words wordtwo wordsanotherword what i like able addchangeremove values without stoping script to i created plain text file containing words i want filtered separated line break using code i get list words perfectly file open wordstxt r words filereadsplitn i made lines work starts i need every time going check stream any ideas,1 daychoices strxx x else day x range,i want add day front right makes drop menu numbers i want day choice top daychoices i hoping would work apparently generators work like day strx x x range i include snippet case voodoo i django import forms class signupformformsform day formschoicefieldchoicesdaychoices,1 you assigning result resub back variable right eg lines resubpattern key lines it string changed strings immutable python therefore new string created returned if assign back name lose,i trying get resub replace pattern specified value example lines f pattern key researchpatternlines return line pattern found for example one test returns got test the problem following resubpatternkeylines nothing happens what missing for info keytest keyreplace trying whenever test encountered replace replace i problem finding test reason resub replacing,3 the following script correctly produces response server usrbinenv python import httpclient h httpclienthttpconnection wwwthomasbayercom timeout hrequest delete sqlrestcustomer headers contentlength response hgetresponse printresponsestatus responseversion printresponseinfo printresponseread python v curl x delete httpwwwthomasbayercomsqlrestcustomer curl empty reply server statusline optional http server must return or least send length required response curl h contentlength x delete httpwwwthomasbayercomsqlrestcustomer returns correctly,i trying use pythonrestclient httpcodegooglecomppythonrestclientwikiusingconnection perform testing restful webservices since i learning i pointing tests sample services provided httpwwwprediccomrestdemohtm i problems creating entries updating entries retrieving entries post get requests when i try make delete request fails i use firefox rest client perform delete requests work i also make delete requests services i driving crazy trying figure work case i using python updated httplib i also tried python i could use pythonrestclient included version httplib i see problem either case the code simple matching documented use restfullib import connection selfbaseurl httpwwwthomasbayercom selfconn connectionselfbaseurl response selfconnrequestdelete sqlrestcustomer i looked resulting http requests browser tool code i see one works this trace i receive traceback recent call last file homefmkpythonrestclientsrctestexampleservicepy line testcrud selfdelete file homefmkpythonrestclientsrctestexampleservicepy line delete response selfconnrequestdelete sqlrestcustomer file homefmkpythonrestclientsrcrestfullibpy line requestdelete return selfrequestresource delete args headersheaders file homefmkpythonrestclientsrcrestfullibpy line request resp content selfhrequestsss selfscheme selfhost joinrequestpath methodupper bodybody headersheaders file homefmkpythonrestclientsrchttplibinitpy line request response content selfrequestconn authority uri requesturi method body headers redirections cachekey file homefmkpythonrestclientsrchttplibinitpy line request response content selfconnrequestconn requesturi method body headers file homefmkpythonrestclientsrchttplibinitpy line connrequest response conngetresponse file usrlibpythonhttpclientpy line getresponse responsebegin file usrlibpythonhttpclientpy line begin version status reason selfreadstatus file usrlibpythonhttpclientpy line readstatus raise badstatuslineline httpclientbadstatusline what breaking what i actually i settle advice debugging i changed domain script pointed machine i could view request i viewedmodified firefox requests burpproxy make match script requests the modified burp requests still work python requests still,1 this seems like bad use generators a generator list function generates sequence values possible add tuple generator the generator exhausted model initialization you might instance want use daychoices later possible if specific reason using generator i would recommend turning daychoices list instead daychoices day strx x x range,i want add day front right makes drop menu numbers i want day choice top daychoices i hoping would work apparently generators work like day strx x x range i include snippet case voodoo i django import forms class signupformformsform day formschoicefieldchoicesdaychoices,1 if text run resub directly whole text follows import ss line another line line test test closing line printss n key test replace regx recompile formatkey print regxsubkeyss if read file interest read whole file put object ss runing resub instead reading replacing line line and list lines must process follows import key test replace regx recompile formatkey lines line another line line test test closing line iline enumeratelines linesi regxsubkeyline otherwise line containing test modified import key test replace regx recompile formatkey lines line another line line test test closing line line lines line regxsubkeyline print lines result line another line line test test closing line,i trying get resub replace pattern specified value example lines f pattern key researchpatternlines return line pattern found for example one test returns got test the problem following resubpatternkeylines nothing happens what missing for info keytest keyreplace trying whenever test encountered replace replace i problem finding test reason resub replacing,1 declares start comment line foopyx effectively empty include blunt instrument use pxd cimport instead,i managed build first c extension python using cython call existing c library i declared defined data types functions logical components following logical structure c library i combined one pyx file errors occured i tried add files individually iirc i got error something along lines init already defined researching issue google i found i combine pyx files info one pyx file see link this copy contents foopyx file include myarraypyx include mysetpyx include mycalcpyx copy setup file distutilscore import setup distutilsextension import extension cythondistutils import buildext setup cmdclass buildext buildext extmodules extensionfoo foopyx librariesfoocore the extension gets built succesfully fooso i type import foo python cli that also works however i try access classes i declareddefined myarraypxd myarraypyx etc i get error message attributeerror module object attribute myarray i tried dir see foo module exporting to surprise listed dirfoo builtins doc file name package test why cython failing export structs classes functions i declared defined i think anything wrong pxd pyx files like i said compiles succesfully shared lib python extendion produced i using cython python ubuntu,2 if want bind available ipv addresses specify ip address if behind router wish socket internetaccessible rather available lan need set port forwarding rule users outside lan access service see following serverfault question info httpserverfaultcomquestionswhatsthedifferencebetweenipaddressand,i small one sided message sender works specify ip connect code however trouble allowing socket accept connections ip here line problem mysocket socketsocket socketafinet socketsockstream mysocketbind the localhost works manually enter ip eg however leave open using wrong connection type,3 binding allow accept connections ipv address route,i small one sided message sender works specify ip connect code however trouble allowing socket accept connections ip here line problem mysocket socketsocket socketafinet socketsockstream mysocketbind the localhost works manually enter ip eg however leave open using wrong connection type,2 moving item list general means popping original location inserting desired location unfortunately question provides insufficient information hand card classes look like hand simple list following hi handindexmc mn mn handhi intmn mc handpophi note comparisons number suite omitted insufficient information,i trying make simple card game python i able move card hand list either spaces left card already spot matches either number suite i need replace here i tried far assume mn number spaces specified move assume mc card specified move many spaces assume hand list current cards hand mn handreplacehandhandindexmc int mc mn handreplacehandhandindexmc int mc so basically i gotta find move specified card mc correct number spaces mn list cards hand if hand looked like jc c d ks s then i able move s space left replace ks suite jc c d s thanks advance help,2 your update emulates absolute import import packagemodule module imported if like use dynamic parent package name import module modulepy import importlib module importlibimportmodule module package i need circular imports a function module asserts one parameter instance class defined module viceversa you could move one classes separate module resolve circular dependency make import function level want use absolute imports ├── startpy package import module └── package â â ├── initpy printinit package import module module ├── cpy printinit packagec class c pass â â ├── modulepy printinit packagemodule c import c module import c â â └── modulepy printinit packagemodule c import c class c pass def f module import c output init package init packagemodule init packagec init packagemodule another option might simpler refactoring cpy merge modulepy single commonpy modulepy make imports common case,python imports drive crazy experience python imports sometime correspond idiom explicit better implicit app startpy package import module package initpy print init package modulepy print init packagemodule import module modulepy print init packagemodule import sys pprint pprintpprintsysmodules import module i get vicubuntudesktopapp python startpy init package init packagemodule init packagemodule main module main startpy package module package homevicdesktopapppackageinitpy packagemodule module packagemodule homevicdesktopapppackagemodulepy packagemodule module packagemodule homevicdesktopapppackagemodulepy traceback recent call last file startpy line module package import module file homevicdesktopapppackagemodulepy line module import module file homevicdesktopapppackagemodulepy line module import module importerror cannot import name module vicubuntudesktopapp import packagemodule works want use import module want make package portable applications want use relative paths i using python i need circular imports a function module asserts one parameter instance class defined module viceversa in words sysmodules contains packagemodule module packagemodule homevicdesktopapppackagemodulepy i want get reference form import module tries get name package like case import packagemodule works fine i tried import module syntax error also import module module works fine import module module work update this hack works looking official way print init packagemodule import sys pprint pprintpprintsysmodules import module parentmodulename namerpartition module sysmodulesparentmodulename module,1 binding effect makes transition ipv easier depending os opening socketafinet socket listens ipv ipv,i small one sided message sender works specify ip connect code however trouble allowing socket accept connections ip here line problem mysocket socketsocket socketafinet socketsockstream mysocketbind the localhost works manually enter ip eg however leave open using wrong connection type,3 intdigits trueish value so convd digits none since digits none convd set true you probably wanted convd intdigits digits none else none remember string containing something number raise exception though if prefer none values write small function def toints try return ints except valueerror typeerror return none,i using ternary operator short conditional variable definition i wondering expression returned true instead given expression value digits convd digits none intdigits else none convd true intdigits explain please happens what logical difference ternary operator regular conditional expression python,3 the python conditional operator order languages and never compare equality none unless certain need convd intdigits digits none else none,i using ternary operator short conditional variable definition i wondering expression returned true instead given expression value digits convd digits none intdigits else none convd true intdigits explain please happens what logical difference ternary operator regular conditional expression python,3 here updated presentation september httpwwwyoutubecomwatchvastqppga httpmediablistorgpresentationsdjangoconreusableappspdf taken slide should application is completely unrelated app’s focus is orthogonal whatever else i’m will i need similar functionality sites if yes then best break separate application,i googled around i still trouble relating django defines apps should i create new app piece functionality site even though uses models main project do guys good rule thumb split new app keep functionality together main project apps,3 use plink root pw password ls l download plink copy windows machine,in work professor i ssh server i ssh node run programs i trying write python program let everything i need remote node local machine the commands i running nodes cp files local machine remote nodes run program node retrieve files nodes local machine maybe make possible copy fortran program compile nodes also check nodes see programs running right i make input files local machine scp server i copy files node run fluiddynamics program node i reverse get output back local machine i looking paramiko i figure i use get local machine nodes i must go server local ssh server ssh nodes is way python i try something else using ossystemssh server ssh node command making bash scripts server different commands compilesh moveinputssh retrieveoutputssh connecting server running bash scripts sorry make sense worded badly help appreciated additional info the reason i using python i want program able make input files send nodes retrieve output files finally generate graphs data i already code generate input files make graphs outputs,1 you also create htmlxpathselector giving html hxs htmlxpathselectortext divblahblahdiv,in order get data i need website using scrapy i first need create response object i use htmlxpathselector htmlxpathselector accept url string argument in following code sample response variable empty i know scrapyselector import htmlxpathselector scrapycontriblinkextractorssgml import sgmllinkextractor scrapycontribspiders import crawlspider rule tarantulaitems import olgaitem class olgaspidercrawlspider this crawler gets physician name homepage url name olga downloaddelay para tentar evitar ser banido robotstxtobey true concurrentrequests feeduri homemercutiogitcodemedicwebsitescsv feedformat csv useragent googlebot httpwwwgooglecombothtml alloweddomains guiareunimedicosmedbr starturls httpmedialsaudeguiareunimedicosmedbrindexplactsearc hampidampevsubmitampformsearchsubmitadefaultaamptypeampcountry ampqoncologiaresults httpwwwguiareunimedicosmedbrindexplactsearchampid ampevsubmitampformsearchsubmitadefaultaamptypeampcountryampqcancer ologiaresults rules rulesgmllinkextractorallowrv restrictxpaths atext callback parseitem followtrue def parseitemself response hxs htmlxpathselectorresponse mdata hxsselect divcontainsclass mdata links mdataselect ahref extract names mdataselect atext extract items index rangelennames olgaitem name namesindex link linksindex response hxs htmlxpathselectorresponse name hxsselect bigtext extract clinics hxsselect hatext extract data hxsselect divcontainsclass stab data addresses xselect ptext extract x data addresses joinx x addresses addresses xreplace telefones rnrnrn x addresses addresses x x addresses addresses addresses phones hxsselect spanidtext extract itemsappendi return items,2 collections import counter l k kv counterlitems v to clarify hashcounter counterx x selffilesforjson fileinodeimagehash selffilesforjson hashcounterhash duplicated hash,python how remove duplicate items list hey guys i list fileinodeimagehashtuples i need delete both items hash i much programming experience maybe hint look would already helpful i already searched internet thing found so far i come extremely awkward solution hashlist filestoberemoved file inode image hash selffilesforjson hashlisthash file inode image hash selffilesforjson hashlisthash kv hashlistiteritems v filestoberemovedappendk fileinodeimagehash selffilesforjson hash filestoberemoved path selfoutdir file osremovepath selffilesforjsonremovefileinodeimagehash any help appreciated thanks advance,1 instead providing subselect statement parameter value embed insert statement typeselect selectwidgettypescidwhere widgettypesctypebindparam typename insert widgetsinsert type typeselect connexecuteinsert name melon typename squidgy name lychee typename spiky,using sqlalchemy core orm i trying insert multiple rows using subqueries values for mysql actual sql would look something like insert into widgets name type values melon select type from widgettypes where type squidgy durian select type from widgettypes where type spiky but i seem able use subqueries using values method insert clause allows one insert time i like insert multiple values passing connection execute method list bind parameters seem supported is possible i want single call execute here self contained demonstration note uses sqlite engine support multiple inserts way mysql sqlalchemy code still fails way real mysql app sqlalchemy import name main construct database metadata metadata widgettypes table widgettypes metadata column id integer primarykeytrue column type varchar nullablefalse widgets table widgets metadata column id integer primarykeytrue column name varchar nullablefalse column type integer nullablefalse foreignkeyconstraint type widgettypesid engine createenginesqlite metadatacreateallengine connect populate db testing conn engineconnect connexecutewidgettypesinsert type spiky type squidgy some select queries later use selectsquidgyid selectwidgettypescidwhere widgettypesc type squidgy limit selectspikyid selectwidgettypescidwhere widgettypesc type squidgy limit one time works via values connexecutewidgetsinsertvalues name tomato type selectsquidgyid and multiple values work avoid subqueries connexecute widgetsinsert name melon type name durian type check inserts actually work print connexecutewidgetsselectfetchall but attempting insert many subqueries work connexecute widgetsinsert name raspberry type selectsquidgyid name lychee type selectspikyid run dies last execute call sqlalchemyexcinterfaceerror interfaceerror error binding parameter probably unsupported type u insert into widgets name type values raspberry sqlalchemysqlexpressionselect xfd select object lychee sqlalchemysqlexpressionselect xfa select object,2 this known bug python runtime result datastore query mb get response it fixed,i migrated gaepython app ms hrd activated new python runtime now datastore queries failing error responsetoolargeerror the response api call datastorevrunquery large the code still running older gae app ms python problems what going is new runtime hrd should i change modelsapp make request smaller thanks,2 to install python use script httpsgithubcombngsudheerbangadminblobmasterlinuxcentosxbuildpythonsh it also makes sure get sqlite readline support,can someone provide steps needed install python version suse redhat it version like i need least make script work so install i type python xterm get python command line interface,2 not function readable also reusable the inline expression may call cfind twice inefficient as useless mentioned comments already built functions really need define function case agentaddress cpartition by way callback function passed argument called later you callback since called later i think called function,i situation i would like conditionally slice string reported position symbol condition slice string else leave untouched i thought two ways one using function using inline conditional expression which method pythonic using function def slicefromatinp res inpfind res return none else return res c agentaddressagentaddress cslicefromatc agentaddress using inline conditional expression c agentaddressagentaddress cnone cfind else cfind agentaddress although using inline conditional expression terse may argue economical function method pythonic readable,3 most pythonic don reinvent wheel use strpartition def slicefromatinp inp return inppartition return inp if concerned speed readability try strrsplit def slicefromatinp return inprsplit neither examples includes callback nor a wellnamed function one thing one thing well pythonic gets if backedup unit tests much better,i situation i would like conditionally slice string reported position symbol condition slice string else leave untouched i thought two ways one using function using inline conditional expression which method pythonic using function def slicefromatinp res inpfind res return none else return res c agentaddressagentaddress cslicefromatc agentaddress using inline conditional expression c agentaddressagentaddress cnone cfind else cfind agentaddress although using inline conditional expression terse may argue economical function method pythonic readable,2 the server detects useragent if user agent match one robotstxt rules applied client by default mechanize returns pythonurllib see httpenwikipediaorgwikirobotsexclusionstandard,i trying mechanize make routine simpler i managed bypass error using brsethandlerobotsfalse there talks ethical use what i wonder error generated side server side i mean mechanize throw exception sees robotstxt rule server decline request detects i use automation tool,1 instead using regex w much faster use b counting words like import rewordboundaries recompiler b def numwordsline return lenrewordboundariesfindallline note halve number b matches beginning end word unfortunately unlike egrep python support matching beginning end if long lines concerned memory using iterator may better solution def numwordsline return sum word rewordboundariesfinditerline,i trying count number words string however first strip punctuations eg line want know name running en linetranslatestringmaketrans produces en want know name want count number words line lenen i get instead using split en tokenize find length work cases eg tried always work eg consider string ccc bcc abc ccc dd aaa abc en becomes ccc bcc abc ccc dd aaa abc lenen returns please help thanks,3 have tried message sysstdinread sysstdin open devtty selectedindex rawinput which url open this works linux maybe work osx,similar question asked answers suggested workaround applicable situation an email message piped mutt script read stdin message sysstdinread message parsed urls printed list choose selectedindex rawinput which url open i understand rawinput get eof left read way reset stdin,3 if mean python x syntax writing filelike sysstdout print it defined python docs the print statement around since least python i think earlier this syntax replaced file kwarg print function python,looking source code pstats i see syntax print selfstream f seconds selftotaltt print selfstream what syntax called use i never seen seen python bookstutorials i read,3 it extended form print statement redirects output filelike object immediately following see python docs,looking source code pstats i see syntax print selfstream f seconds selftotaltt print selfstream what syntax called use i never seen seen python bookstutorials i read,1 another option create new response object example htmlresponse textresponse also possibility response htmlresponseurlurl bodybody for supported keyword arguments response object types see httpreadthedocsorgdocsscrapyenlatesttopicsrequestresponsehtmlresponseobjects,in order get data i need website using scrapy i first need create response object i use htmlxpathselector htmlxpathselector accept url string argument in following code sample response variable empty i know scrapyselector import htmlxpathselector scrapycontriblinkextractorssgml import sgmllinkextractor scrapycontribspiders import crawlspider rule tarantulaitems import olgaitem class olgaspidercrawlspider this crawler gets physician name homepage url name olga downloaddelay para tentar evitar ser banido robotstxtobey true concurrentrequests feeduri homemercutiogitcodemedicwebsitescsv feedformat csv useragent googlebot httpwwwgooglecombothtml alloweddomains guiareunimedicosmedbr starturls httpmedialsaudeguiareunimedicosmedbrindexplactsearc hampidampevsubmitampformsearchsubmitadefaultaamptypeampcountry ampqoncologiaresults httpwwwguiareunimedicosmedbrindexplactsearchampid ampevsubmitampformsearchsubmitadefaultaamptypeampcountryampqcancer ologiaresults rules rulesgmllinkextractorallowrv restrictxpaths atext callback parseitem followtrue def parseitemself response hxs htmlxpathselectorresponse mdata hxsselect divcontainsclass mdata links mdataselect ahref extract names mdataselect atext extract items index rangelennames olgaitem name namesindex link linksindex response hxs htmlxpathselectorresponse name hxsselect bigtext extract clinics hxsselect hatext extract data hxsselect divcontainsclass stab data addresses xselect ptext extract x data addresses joinx x addresses addresses xreplace telefones rnrnrn x addresses addresses x x addresses addresses addresses phones hxsselect spanidtext extract itemsappendi return items,2 install packages binary version python so example version usrlocalbin installing would either usrlocalbinpython setuppy usrlocalbineasyinstall usrlocalbinpip install,i used easyinstall get one two modules i used pip install twitter module however newer version python i downloaded see modules built osx version also i unable download nltk i need examples i working really good book called mining social web any thoughts,1 the function osread returns class str python class bytes python so python read n readctemp never true you may change like strreadascii oslinesep read ctemp maybe exactly import ossys read osread strreadsysstdinencoding oslinesep read ctemp,i working python the user option entering value console let default value used hits enter eg if user hits enter value set ctemp shown code snippet readosread read n readctemp this code used work python work python in read remains empty any suggestions please improve code,3 removing mongodlock varlibmongodb and restarting service for example ubuntu installation restarting server something like sudo service mongod start,i trying run simple connection pymongo keeps returning connection refused here i tried pymongo import connection connection connection localhost i get traceback recent call last file stdin line module file usrlocallibpythondistpackagespymongopylinux ieggpymongoconnectionpy line init selffindnode file usrlocallibpythondistpackagespymongopylinux ieggpymongoconnectionpy line findnode raise autoreconnect joinerrors pymongoerrorsautoreconnect could connect localhost errno connection refused how i fix,3 python made changes string handling osread returns binary string code fixed read b n readctemp,i working python the user option entering value console let default value used hits enter eg if user hits enter value set ctemp shown code snippet readosread read n readctemp this code used work python work python in read remains empty any suggestions please improve code,1 all python bindings gtk clutter moved introspectionbased pygobject able use cluttergtk cluttergst pygobject simply girepository import gtkclutter you follow documentation gnome wiki entry introspectionporting,i using python want embed gtk widgets clutter stage however seems pycluttergtk pycluttergsk stopped is alternative binding use python i tried google luck there one projecthttpcodegooglecomppyclutterwidgets seems interesting inactive year,1 i reproduce error way python python default oct gcc linux type help copyright credits license information kxfe u kxfe main unicodewarning unicode equal comparison failed convert arguments unicode interpreting unequal false so perhaps str object liste ordliste contains unicode eryksun points comments vice versa the solution decode str object likely utf codec make unicode if help please print post output printreprs printreprliste printreprordliste i believe problem avoided converting strings unicode when generate ordliste norsktxt use codecsopen norsktxt r utf encoding sysstdinencoding codecsopen norsktxt r utf fil ordliste linerstripu n line fil convert user input unicode soon possible def getunicodewidget streng widgetget try streng strengdecode utf except unicodeencodeerror pass return streng so perhaps try import tkinter tk import tkmessagebox import codecs import itertools import sys alfabetet uabcdefghijklmnopqrstuvwxyz unlatin small letter ae unlatin small letter o with stroke unlatin small letter a with ring above encoding sysstdinencoding codecsopen norsktxt r encoding fil ordliste setlinerstripu n line fil def getunicodewidget streng widgetget isinstancestrengstr streng strengdecode latin return streng def siord alfalagtabell try streng getunicodeordinn ordenefinnordstrengalfa lenordene there words match tkmessageboxshowinfo dessverre det er ingen ord som passer else done the words fit pattern tkmessageboxshowinfo ferdig ordene som passer ern ordeneencode utf except exception err there mistake check word printreprerr tkmessageboxshowerror error det har skjedd en feil sjekk ordet ditt def finnordstrengalfa liste set substitution itertoolspermutationsalfastrengcountu streng ch substitution sreplaceu ch ordliste listeadds liste strenglistliste return u joinlisteu def lagtabell tinbox getunicodebokstinn tinboxisalpha alfa alfabetet else alfa tinboxlower return alfa root tktk roottitle feudhjelper av martin skow rã¸ed rootgeometry x rooticonbitmap dataikonico skrift tklabelroot text velkommen til feudhjelper skriv inn de bokstavene du har og erstatt ukjente med f eks slge det er kun lov til 㥠bruke tre stjerner alts㥠tre ukjente bokstaver font verdana wraplength skriftpackpady ordinn tkstringvarnone tekstboks tkentryroot textvariable ordinn tekstbokspackpady what letters eg ahneki leave blank want words skrift tklabelroot text hvilke bokstaver har du f eks ahneki la det vã¦re blankt hvis du vil ha alle ordene font verdana wraplength skriftpackpady bokstinn tkstringvarnone tekstboks tkentryroot textvariable bokstinn tekstbokspack knapp tkbuttontext finn ord command siord knapppackpady rootmainloop,i written program tkinter python scrabblehelper norwegian contains special characters ã¦ã¸ã¥ means wordlist ordliste contains words special characters when i run function finnordc returns cd i using entryget get word put function my problem encoding entryget i local coding utf i get unicodeerror i writing special characters entrybox matching wordliste here output warning warnings module file cpythonprogscrabblefeudpy line liste ordliste unicodewarning unicode equal comparison failed convert arguments unicode interpreting unequal when write shell ordinnget u kxfe ordinngetencode utf kxcxbe print ordinnget kã¸e print ordinngetencode utf kãƒâ¸e anyone knows i match ordinnget entry wordlist,3 this want def funcx smallindices x xsmallindices xinvertsmallindices return x invert numpyfunction note modifies argument to prevent modify return copy x,i using matplotlib numpy produce plots i wish define function given array returns another array values calculated elementwise example def funcx return x x numpyarrange funcx this fine now however i wish ifstatement inside func example def funcx x return else return x x numpyarrange funcx this unfortunately throws following error traceback recent call last file dscriptstestpy line module funcx file dscriptstestpy line func x valueerror the truth value array one element ambiguous use aany aall i looked documentation fit bill i need so nice way make function handle arrays element wise first example,3 if i understand correctly want redirect stdout process start right then use subprocesspopen command then use mywriter class,i try implement option save console output additionally file option activated i found two ways use logging module write class like class mywriter def initself stdout filename selfstdout stdout selflogfile filefilename def writeself text selfstdoutwritetext selflogfilewritetext def closeself selfstdoutclose selflogfileclose but i got problem some pieces code execute new process and ways catch prints when i start program like myscriptpy mylogtxt works he got prints but i simulate functionally script,1 gvim gtk wrapper vim it version vim uses gtk widgets instead stdin stdout you add smooth gtk support programs modifying source code implement gui scratch alternatively could embed vte terminal widget gtk program but i think looking,i like create application similar gvim i gtk application console application included case vim console text editor what best way if way i comunicate console editor gui i runnable linux i really appreciate works windows systems well thank,2 use numpyvectorize wrap func applying array x numpy import vectorize vfunc vectorizefunc vfuncx,i using matplotlib numpy produce plots i wish define function given array returns another array values calculated elementwise example def funcx return x x numpyarrange funcx this fine now however i wish ifstatement inside func example def funcx x return else return x x numpyarrange funcx this unfortunately throws following error traceback recent call last file dscriptstestpy line module funcx file dscriptstestpy line func x valueerror the truth value array one element ambiguous use aany aall i looked documentation fit bill i need so nice way make function handle arrays element wise first example,3 anydictitervalues or allnot x x dictitervalues whichever find clearer,i dictionary n items their values strings i looking easy way detect empty strings u b u c u,3 x numpyarrange mask x numpyzeroslenx ymask xmask mask boolean array equates true array indices matching condition false elsewhere the last line replaces values original array value mulitplied edited reflect bjorn pertinent comment,i using matplotlib numpy produce plots i wish define function given array returns another array values calculated elementwise example def funcx return x x numpyarrange funcx this fine now however i wish ifstatement inside func example def funcx x return else return x x numpyarrange funcx this unfortunately throws following error traceback recent call last file dscriptstestpy line module funcx file dscriptstestpy line func x valueerror the truth value array one element ambiguous use aany aall i looked documentation fit bill i need so nice way make function handle arrays element wise first example,1 try b c anymapbool dvalues false b c oaeu anymapbool dvalues true,i dictionary n items their values strings i looking easy way detect empty strings u b u c u,1 my suggestion would use logging module use sockethandler push socket server would write received logs file i hope helps,i try implement option save console output additionally file option activated i found two ways use logging module write class like class mywriter def initself stdout filename selfstdout stdout selflogfile filefilename def writeself text selfstdoutwritetext selflogfilewritetext def closeself selfstdoutclose selflogfileclose but i got problem some pieces code execute new process and ways catch prints when i start program like myscriptpy mylogtxt works he got prints but i simulate functionally script,1 as discussed comments python output buffered programs run sleeps right time etc see output if running python nonstandard console need pass u option python disable buffering ie python u foopy,i teaching python aid head first programming i thought i might tweak example liking i think i missing something timesleep my code printwelcome superbeans timesleep answer inputdo need price yn but rather pausing three seconds welcome message waits minutes displays message input request what i missing additionally program seems hang indefinitely running poll function i defined without ever displaying polling notice i know getprice working prints another section def poll price printprice price printpolling price getprice timesleep printbuy so welcome pausing i think poll function hanging,1 if multiple apps share database table one apps must define table migratefalse prevent migration attempts note authdefinetables also takes migrate argument turn migrations specifically auth tables authdefinetablesmigratefalse you also turn migrations entire database connection within application db dal migrateenabledfalse see interapp cooperation,i apps webpy framework can i use one single mysql database prefixing tables users need one single registration access apps i fail attempts or solutions thanks much,1 import pytz pytzcountrytimezones il israel asiajerusalem does describe timezone if yes use datetime import datetime import pytz dt pytztimezone asiajerusalem localizedatetimestrptimea ymd hms astimezonepytzutc dt datetimedatetime tzinfoutc jerusalem in order convert epoch seconds unix timestamp ie seconds since utc directly use import calendar datetime import datetime import pytz epoch calendartimegmpytztimezone asiajerusalem localizedatetimestrptimea ymd hms utctimetuple epoch,i program recieves datetime string local time israel need convert epoch seconds i could use format utc guess problem daytime savings israels watch behaves differently countries is way get epoch time dependant country,2 this probably use textproperty fields textproperty multiline texts indexed you lookup nonindexed values query you use stringproperty singleline text values,i running gqlquery lookup user entered correct credentials class userdbmodel username dbtextproperty password dbtextproperty ticket dbtextproperty class authenticationwebapprequesthandler def postself struser selfrequestget user strpassword selfrequestget password user dbgqlqueryselect from user where username and password struser strpassword selfresponseoutwritestruser selfresponseoutwritestrpassword selfresponseoutwritestruusername u user usercount ticket struuiduuid userticket ticket selfresponseoutwriteticket else selfresponseoutwrite not authorized the query always return empty result set whereclause although i sure i passed correct parameters i tried concat query string result remains if i remove whereclause get users db i guess dbconnection okay,2 if want place use lst lst this faster save memory changes object place semantics need,i wondering way python modify collections without creating new ones eg lst newlst lst works fine new collection created is reason python collections lack filter method similar would modify collection object place,3 the lst solution sven marnach one option you also perform operation inplace using constant extra memory lenlst lsti del lsti else lst solution readable takes quadratic time due element shifting involved,i wondering way python modify collections without creating new ones eg lst newlst lst works fine new collection created is reason python collections lack filter method similar would modify collection object place,1 the answers correct want names pointing old list point new list use slice assignment however truly inplace creation new list first created elsewhere the link sven answer good the reason one truly operates inplace making new list like on truly inplace item removal would ok k length list removal point the way avoid python lists use temporary storage using slice assignment an example inplace on filter collectionsdeque case need store data list collections import deque def dequefilterdeck condition xrangelendeck item deckpopleft conditionitem deckappenditem deck deque dequefilterdeck lambda x x operatorgt print deck deque,i wondering way python modify collections without creating new ones eg lst newlst lst works fine new collection created is reason python collections lack filter method similar would modify collection object place,3 as complete guess i say cygwinbuilt dll incompatible msvcbuilt interpreter either abi issue use two different libcs build dll mingw instead,i want test wrapping dll ctypes i written following test code compiled using codeblocks cygwin dll define dllexport extern c declspecdllexport dllexport int sumint int b return b note this whole code maybe something missing now i copy testdlldll desktop start python interpreter but i want load interpreter exits cusersniklasdesktoppython python default jun msc v bit intel win type help copyright credits license information import ctypes dll ctypeswindll testdll cusersniklasdesktop however loading library works giving error library could found can tell i wrong using cygwin g,1 check objdump p testdlldll grep dll see linked cygwindll nm testdlldll grep dll see dllmain the following command build dll correctly g testdllc mnocygwin shared testdlldll also need use cdll cdecl calling convention windll import ctypes dll ctypescdll testdll dllsum edit i compiled iwmingwgexe cygwin repository i used use default cygwin gcc without problem given mnocygwin option,i want test wrapping dll ctypes i written following test code compiled using codeblocks cygwin dll define dllexport extern c declspecdllexport dllexport int sumint int b return b note this whole code maybe something missing now i copy testdlldll desktop start python interpreter but i want load interpreter exits cusersniklasdesktoppython python default jun msc v bit intel win type help copyright credits license information import ctypes dll ctypeswindll testdll cusersniklasdesktop however loading library works giving error library could found can tell i wrong using cygwin g,1 correcting larsmans original solution could either lenlst lsti del lsti else lenlst lsti del lsti reason index shift happens del if i del ceratin index i reexamine index holds different value,i wondering way python modify collections without creating new ones eg lst newlst lst works fine new collection created is reason python collections lack filter method similar would modify collection object place,1 the translation results list presumably many results if sure interested first result result searchresponse translation results translatedterm,i trouble bing json api here json data receiving apibingnetjsonaspx searchresponseversionquerysearchtermsnewstranslationresultstranslatedtermnoticias i need parse translatedterm value noticias seems problem json decode i using result jloadsbytes print result searchresponse translation results and python gives u translatedterm u noticias if add use like result searchresponse translation results translatedterm python raises error like print result searchresponse translation results translatedterm typeerror list indices must integers how get noticias plain string much appriciated,2 since call parsed shell need quotes p subprocesspopen git log prettyformats nnb hash stdoutsubprocesspipe,what right code case p subprocesspopengit log prettyformat nnb hash stdoutsubprocesspipe err pcommunicate print message n i always get error fatal ambiguous argument unknown revision path working tree output use separate paths revisions i working tree,3 revision foreign key version and reversiongetforobjectmodel simply returns queryset version so item query set simply access user versionrevisionuser update just explicit versions reversiongetforobjectmymodel version versions print made revision versionrevisionuserusername,i using djangoreversion providing history models i discovered reversion creates two tables table reversionrevision reversionversion and reversionrevision stored user id makes last changes but cant get information i use function reversiongetforobjectmodel get versions certain model function return information stored table reversionversion need get user id table reversionrevision someone get user id,3 i think glob meant customisable you might want try oslistdir instead import osre f oslistdirpathtodir rematchrdtxt f printf,i need get text files numeric names txt txt txt is possible glob import glob file globglob txt printfile does return txt and seems regex one operator what i,1 there wxapp from i read online two wxapp objects running one script you could probably using subprocess module open new process though take look editra see examples plugins it included wxpython download separately,is possible run wxapp another wxapp i trying simply call program i wrote called datadeck method another wxapp like plugin something like def ondatadeckbtnclickself event import datadeckmain datadeckmainrun eventskip datadeckmainrun classic start wxapp def run app datadeck appsetappnamedatadeck appmainloop right correctly opens datadeck first time works reopen datadeck second time i close this would freeze everything update based mike driscoll answer i documented came following solution i added entry point datadeck def runasplugin stuff related xrc layouts sysout redirection maingui datadeckguimainguimaingui where constructor maingui automatically shows wxframe now application behaves like component caller wxapp therefore i modify application method follows def ondatadeckbtnclickself event import datadeckmain datadeckmainrunasplugin eventskip it simple indeed i modify objects deal stdout redirection part question i omit details everything worked fine,1 from tfm no tilde expansion done character ranges expressed correctly matched so operators regex you use glob firstpass glob txt filter regex,i need get text files numeric names txt txt txt is possible glob import glob file globglob txt printfile does return txt and seems regex one operator what i,1 you download windows installer httpbitnamiorgstackosqa just tried works great installer prompts information needs end launch site works,i want install osqa local windows system i downloaded bitnamidjangostackwindowsinstallerexe django python mysql apache built i run django example given django website working fine but i confused install osaq i downloaded source code osqa site read installation instructions requires django i make work,3 you easily change senderconnecttcplocalhost senderbindtcplocalhost viseversa receiver it gives ability connect receiver wherever like sender would work matter receivers,i would like communicate two processes sender receiver using zeromq now receiver process running i would like sender process continues execution even message lost trying implement using pubsub pattern i noticed receiver running sender hangs for instance following sender source code import zmq context zmqcontext sender contextsocketzmqpub senderconnecttcplocalhost sendersendsending nobody noblock print msg sent receiver message msg sent never printed sender remains sendersendsending nobody noblock forever besides i tried check receiver getting return connect function always none cases i using python zeromq somebody knows happening alternative solution i tried using pullpush reqrep similar results thank much advance,2 after fixing sample import zmq context zmqcontext sender contextsocketzmqpub senderconnecttcplocalhost sendersendsending nobody zmqnoblock print msg sent the behavior i see msg sent phrase printed script hangs never actually exits the problem hanging close system call you change behavior setting linger option socket sender contextsocketzmqpub sendersetsockoptzmqlinger this value linger time milliseconds see man page zmqsetsockopt information the practical impact zmq wait linger milliseconds closing socket don set value low cause messages lost even sender listening zmq may close socket message actually delivered,i would like communicate two processes sender receiver using zeromq now receiver process running i would like sender process continues execution even message lost trying implement using pubsub pattern i noticed receiver running sender hangs for instance following sender source code import zmq context zmqcontext sender contextsocketzmqpub senderconnecttcplocalhost sendersendsending nobody noblock print msg sent receiver message msg sent never printed sender remains sendersendsending nobody noblock forever besides i tried check receiver getting return connect function always none cases i using python zeromq somebody knows happening alternative solution i tried using pullpush reqrep similar results thank much advance,2 the cost instances part cost app i use java runtime right i know much less efficient things would python go i imagine orders magnitude different i know instances cost need consider depending app may find api storage costs significant minor differences runtimes all api costs whatever runtime use language might affect costs ondemand frontend instances reserved frontend instances backed instances language independent costs high replication datastore per gig stored outgoing bandwidth per gig datastore api per ops blobstore api storge per gig email api per email xmpp api per stanza channel api per channel,will google go use less resources python java appengine are instance startup times go faster java python startup times is go program uploaded binaries source code uploaded source code compiled instance startup in words will i benefit using go app engine cost perspective taking account cost appengine resources development time,3 collections import defaultdict defaultdictlist k v dkappendv avg k sumv lenv k v diteritems print avg prints note uses integer division compute averages you might want use floating point division instead,i list follows a from list a i would like generate output list like average any tips would really grateful,2 in simple way result key value a resultsetdefaultkey appendvalue print k sumv lenv kv resultiteritems,i list follows a from list a i would like generate output list like average any tips would really grateful,1 you use boolean array select required indices selectedvalues edata nodata eps amp edata nodata eps pyplothistedataselectedvalues edata nodata eps create array npbool shape edata set true given index value index greater nodata eps amp elementwise operator satisfy conditions alternatively nodata convention i would set values numpynan instead use edatanumpyisfiniteedata,i got d numpy array e data value i like generate histogram data i succeeded best way matplotlib import pyplot import sys eps sysfloatinfoepsilon nodata e edata elevationreshapeelevationsize edataclean xrangelenedata val edatai floating point equality check val aprox equal nodata val nodata eps val nodata eps edatacleanappendval pyplothistedataclean bins it seems like clean much faster one liner is,3 if ok use win use tkinter python standard library shown how i copy string clipboard windows using python,i downloaded win python site this code getset clipboard def test openclipboard dgetclipboarddatawinconcftext get clipboard data setclipboarddatawinconcftext hello set clipboard data closeclipboard name main sysplatform win winclipboard import import wingui wincon test it works well getclipboardata setclipboarddata seem work i run test i expect get hello v something i copied what might wrong,1 i seen many suggestions use win module tkinter provides shortest easiest method i seen post how i copy string clipboard windows using python plus tkinter python standard library,how i read text windows clipboard python,3 if got https enabled sending along request usually post acceptable standard method logging if want get clever could hash password using sha client end even sslstrip reveal password plaintext though prevent replay attacks,what accepted way get authentication credentials login password using webapp i pretty sure get submitted andor interpreted differently rest information coming request i afraid i remember exactly i supposed get fyi the requests forced https thanks,1 you storing text bottom the place assign values dictionary entries lentemp since text paragraph equal sign part simply fall nothing done you need else somewhere,i long text and i converting string dict here code datadict filterdict textsplitn temp eachsplit lentemp datadicttemp temp data dictkstrip vstrip k v datadictiteritems here output convert text dict producer sailadhar baruah image paporithefilmjpg distributor alt image size gross writer jahnu barua cinematography binod pradhan music satya baruah p p vidyanathan followed narrator director jahnu barua released studio dolphin pvt ltd starring gopi desai biju phukan sushil goswami chetana das dulal roy editing name papori language assamese languageassamese country assam ind budget caption a screenshot preceded runtime minutes i want know last paragraph gone can i store last paragraph text varible thanks,1 the likely explanation running script using python x there could multiple interpreters installed system i suggest making sure using interpreter think using try printing sysversion within script,i currently testing mac python program developed windows python when program run windows problem run mac i get syntax error pointing following print function logfile open testlog w print testing startedn file logfile syntaxerror invalid syntax i running python i think correct syntax i cannot understand wrong bizarrely i changes old x syntax print logfile test startedn ran without error could reason python interpreter using old syntax even though version thanks,3 as pointed matching key value format try something like instead text filetexttxt rreadlines skipkeys film datadict text temp xstrip x eachsplit temp skipkeys continue lentemp datadicttemp temp else datadict nokey temp print datadict here paragraph added nokey i started answer using defaultdict collections module setting value lists could track unkeyed values format consistent work,i long text and i converting string dict here code datadict filterdict textsplitn temp eachsplit lentemp datadicttemp temp data dictkstrip vstrip k v datadictiteritems here output convert text dict producer sailadhar baruah image paporithefilmjpg distributor alt image size gross writer jahnu barua cinematography binod pradhan music satya baruah p p vidyanathan followed narrator director jahnu barua released studio dolphin pvt ltd starring gopi desai biju phukan sushil goswami chetana das dulal roy editing name papori language assamese languageassamese country assam ind budget caption a screenshot preceded runtime minutes i want know last paragraph gone can i store last paragraph text varible thanks,1 my initial thought would store data elsewhere like relational database possibly using zset if continuous data meaning consistently set n interval time periods could store hash key member date int timestamp value then could zrank particular date use zrevrange query first rank value get zrank,i store several properties objects hashsets among things something like creation date there several hashsets db so question i find objects older week example can suggest algorithm faster on naive implementation thanks oles,1 author sorry simplepyged support anything like but wish code together,does anyone know way use python package simplepyged parsing gedcom files graphical representation family trees xypic matlibplot pictex i appreciate help thanks,1 it probably allocate resources language choice i read gae built languageagnostic probably builtin advantage language get advantage choosing language comfortable motivated i use python made deployment much costeffective upgrade python make upgrade use correct subset good so choose language comfortable likely gain advantage ability using language rather combo language environment in short i recommend python app engine language i tried choice even though i know java rather well code project much compact using favorite language python my apps small medium sized cost like nothing,will google go use less resources python java appengine are instance startup times go faster java python startup times is go program uploaded binaries source code uploaded source code compiled instance startup in words will i benefit using go app engine cost perspective taking account cost appengine resources development time,1 try datetimeisoformat mydate datetimedatetimenow myxmldate startsstart mydateisoformat,way pass datetime directly format mydate datetimedatetimenow myxmldate startstart mydate pass like string i need pass xml datetime structure thanks,1 interestingly perl runs quickly perl e print matchn coprohorizon hor mwws perl e print matchn coprohorizon hor mwws match,i trying execute code import pattern rwws recompiled recompilepattern results recompiledsearch coprohorizon hor printresultsgroups but python respond the process takes cpu stop i tried python python identical results,1 try reed mydateisoformat mydatestrftimedmy mydatestrftimea b y monday march and version using typespecific import datetime datetimedatetime ymd hms formatd,way pass datetime directly format mydate datetimedatetimenow myxmldate startstart mydate pass like string i need pass xml datetime structure thanks,1 because vague question i provide general answer you need decide gui framework there number choose pyqt httpqtnokiacomproducts httpwwwriverbankcomputingcouksoftwarepyqtdownload pyside lgpl version pyqt httpwwwpysideorg gtk httpwwwpygtkorg wxpython httpwwwwxpythonorg tkinter httpwikipythonorgmointkinter you could even write web interface communicates python script via rpc http rest interface take pick my vote pysidepyqt its flexible easy use at point would use something like pyapp package entire environment standalone app distributed,is possible convert py script app works text box something thanks,2 have look htmltext it may exactly want line script pretty easy adapt particular needs,given flexibility html codes parsing paragraphs seen user browser seems quite nontrivial task for i robust solution tree lxmletreefromstringhtml lxmletreehtmlparser isinstancehtml basestring else html skiptag script iframe style link meta noscript option node treexpathskiptag nodegetparentremovenode paragraphs lxmletreetostringtree encodingunicode method text the problems i facing mainly tackle abnormality say freestyles one quite common case many paragraphs written one line eg code html code parse one paragraph pbla bla ppuspan classcoloredstrongbla bla strongspanuppbla bla ppbla bla p my questions good ways general parse paragraphs correctly particular case i optimize code correctly get paragraphs oneline html given p represent paragraph many ways may applied freestyle general advice,1 on smaller lattice see happening import numpy populate lattice lattice numpyconcatenatenumpyones numpyzeros numpyrandomshufflelattice intialize problem intrap false steps pos intnumpyrandomrandintlenlattice history intrap false step backward forward step numpyrandompermutation check position edges fix required pos step lenlattice pos elif pos step pos lenlattice else pos step keep track random walk historyappendpos check trap latticepos intrap true if continue steps print steps print history print lattice i would encourage thrown print statements throughout see values variable holding trying smaller lattices help understand works edit i going let figure specifics i would wrap function like follows it sets function prepares empty steps histories lists hold results run we run function append results lists def lattice code return steps history steps histories range numsteps history lattice stepsappendnumsteps historiesappendhistory,i problem create program constructs lattice one dimension sites in lattice put random positions number trap molecules concentration c put particle random position lattice let perform random walk in walk place time restriction namely declare specific number steps the walk stop particle falls trap beware boundary conditions when particle reaches borders lattice shouldn’t allowed escape remain lattice either returning former position placed opposite site lattice my approach shown code created comments def stepsdselfposc pos number positions c concentration trapparticles array full traps zeros myzeros sczerosselfcselfpos grid full available positionsones grid sconesselfpos distribute cpos zerostraps random positions number positions pos traps scrandompermutationposcpos grid particle moving traps inside gridtraps myzeros stepscount list holds number steps free rangepos step particle stepscrandomrandomintegers step grid step free stepscountappendfree else break return stepscount i problems the results taking example pos sth like i would expect numbers run variable pos i sure handle boundary conditions i thinking something like free gridsize free free but i test alsoi sure applies borders grid if want first step begin middle grid i if someone hint i grateful,1 for following html select ideditbirthdayday classformselect namebirthdayday option selectedselected valueoption option valueoption option valueoption select use use following scripting python selselectideditbirthdayday label please also refer selenium documentation select selectlocatoroptionlocator select option dropdown using option locator option locators provide different ways specifying options html select element eg selecting specific option asserting selected option satisfies specification there several forms select option locator labellabelpattern matches options based labels ie visible text this default labelregexpoother valuevaluepattern matches options based values valueother idid matches options based ids idoption indexindex matches option based index offset zero index if option locator prefix provided default behaviour match label arguments selectlocator element locator identifying dropdown menu optionlocator option locator label default,i dropdown calendar i need select date using selenium i using python scripting language i also new selenium,1 what fine single simple replacement however going anything complex method quickly become clumsy it worth noting quite existing solutions creating text templates especially html jinja django templates two examples mature widely used python templating libraries several others well i highly recommend using one,right i solution works looking examples it looks like pagetemp stringtemplateopenindextemplatehtmlread print pagetemptemplate f openindexhtmlw fwritepagetempsubstituteseanfinaloutputseanfinaloutput fclose return seanfinaloutput html block code i use seanfinaloutput template proper way ie instead template file i directly edit indexhtml i guess advantage i substitute way i i feel like i reading one file outputting another i dont know efficient way i want learn python way,1 myarr lenmyarr,i list python i know exactly long i know less items long i want pad exactly items long appending empty strings items i need add is efficient way python i hoping myarr myarr might work currently i lenmyarr range lenmyarr myarrappend any compact suggestions,3 the external documentation mechanize quite small contains examples incode documentation far extensive not tested htmlform instance called form able call formfindcontrolidtopicid get want i sure browser object tried brfindcontrolidtopicid,the html i trying make mechanize parse select idtopicid nametopics titleblabla tabindex classcreateselect go options but right another dropdown following code select idtopicid nametopics titleoptional tabindex classcreateselect now helps i need select value latter one since optional when i try br mechanizebrowser brselectformnameform brtopics internet i get mechanizeformambiguityerror one control matching name topics is way i select control based id using mechanizebrowser retaining form syntax thanks,1 oneliner way myarrextend lenmyarr,i list python i know exactly long i know less items long i want pad exactly items long appending empty strings items i need add is efficient way python i hoping myarr myarr might work currently i lenmyarr range lenmyarr myarrappend any compact suggestions,2 your regex basically means find words possible unwanted character words find newline immediately words the wordchecking part find unwanted characters part words lookahead assertion redundant newline unwanted character what seem want find line last character one unwanted characters this probably really call regexes want use obvious way imo take text line time search something like,i regex find heading lines contain text end period titpat recompilerw nreunicode res titparfindalldata example chapter x test this test test test test test this test text textthis test text text text text this text text tex text chapter aaa this test this test text text text text text text text text bbbb the end the regex finding heading lines contain text without period new line that expected negative look ahead statement checks periods accepting however i may sentence starts line ends period next line the regex finding line text without period is explanation behavior,1 could try function anyd devdevices name devname,i got lines code iterating dict within list i looking shorten it works perfectly seems like much code i trying get feel keep code efficient python general really dev devices name devname devfound true break the structure dev bit confusing data i care dev dict devices list n dict value name key within inner numbered dict varies depending search value elsewhere needs checked user input devname any input much appreciated,2 basically rewritten builtin function generator devfound anyd name devname dev devices,i got lines code iterating dict within list i looking shorten it works perfectly seems like much code i trying get feel keep code efficient python general really dev devices name devname devfound true break the structure dev bit confusing data i care dev dict devices list n dict value name key within inner numbered dict varies depending search value elsewhere needs checked user input devname any input much appreciated,3 wsgi app must return iterable one way another if want send partial responses turn application generator return iterator import wsgiref wsgirefsimpleserver time def appenviron start start ok contenttype textplain yield hello timesleep yield world httpd wsgirefsimpleservermakeserver localhost app httpdserveforever,is way wrap wsgi application method server send response particular method called rather application method returns sequence basically i like equivalent finishresponseresponsevalue method,2 i problem today rolled solution i thought check so this dictiacounti really really slow large lists my solution def occurdictitems items di di else di return actually bit faster counter solution least python,given item i count occurrences list python,3 the first thing make sure subdirectory file named initpy this file blank able imports without then know importing subdirectory include something like module importsubdirectoryjack that need include name subdirectory module stored importing module if want import directory subdirectory whatever directory working make sure included python path you modify path setting syspath simply importing sys module appending new path wherever modules stored import sys syspathappendfullpathtodirectorytoimportfrom edit response comments when using builtin function import important realize returns toplevel module one like import so want access module imported need something like module importmymodule result modulemymodulemyfunction,im trying get python load module depening page requested browser i working py file root script cant seem get working subdirectory html files work everywhere id appreciate someone could help get python files work aswell directory im running python win bit sp import stringcgitime os import curdir sep basehttpserver import basehttprequesthandler httpserver import os import mimetypes import pri port host class myhandlerbasehttprequesthandler def dogetself try requestedurl selfpath mimetype mimetypesguesstypeselfpath filetype mimetypesguessextensionmimetype infolist mimetype filetype infolist py selfsendresponse selfsendheader contenttype mimetype selfendheaders f opencurdir sep selfpath rb selfwfilewritefread fclose return filetype py pythonfilename selfpathlstrip selfsendresponse selfsendheader contenttype texthtml selfendheaders pyname pythonfilenamereplace print pythonfilename print pyname temp pynamesplit temp temp print temp module importrootindex selfwfilewritemodulerootindexdowork module importtestindex selfwfilewrite moduleindexdowork return return except ioerror selfsenderror file not found selfpath def dopostself global rootnode try ctype pdict cgiparseheaderselfheadersgetheader contenttype ctype multipartformdata querycgiparsemultipartselfrfile pdict selfsendresponse selfendheaders upfilecontent queryget upfile print filecontent upfilecontent selfwfilewritehtmlpost okbrbr selfwfilewriteupfilecontent except pass def main try server httpserverhost port myhandler print started httpserver print host host print port strport serverserveforever except keyboardinterrupt print c received shutting server serversocketclose name main main,1 a function defined cpdef callable python c if arguments declared c data types cython attempt automatically convert objects passed function called python but conversions possible numeric string types types result compiletime error did mean expose function python if define cdef otherwise need create wrappers c types want pass python see cython tutorials examples,i using cython create extension python i created pxd file pyx file here contents pyx file cimport capifuncs cdef class myarray cdef capifuncsmyarray myarray def cinitself size selfmyarray capifuncsarraynewsize selfmyarray null raise memoryerror def deallocself selfmyarray null capifuncsarrayfreeselfmyarray def boolself return capifuncsisemptyselfmyarray array methods cpdef getitemself unsigned int pos capifuncsisemptyselfmyarray raise indexerrorarray empty raise indexerrorarray bounds exceeded return capifuncsarraygetitemselfmyarray pos cpdef setitemself unsigned int pos double val capifuncsisemptyselfmyarray raise indexerrorarray empty raise indexerrorarray bounds exceeded capifuncsarraysetitemselfmyarray pos val free functions cpdef long somecapifunccallcapifuncsfoobar fb capifuncsmyarray arr long start long stop return capifuncsdosomethinginterestingfb arr start stop if i comment free ie nonmember function definition statement code compiles correctly extension produced however i uncomment try compile file i get following error message cafuncspyx cannot convert python object argument type foobar what cause i fix,2 i think li abcd abyet abcd betry outry rumunu abyetin takama eli com betry rumunu foutrym la x li anyx el el x el la laappendx print li print print la result abcd abyet abcd betry outry rumunu abyetin takama eli com betry rumunu foutrym abcd abyet outry takama eli com betry rumunu ps but abyet rumunu abyetin interchanged former list deducted list wil rumunu abyetin abyet why abyet authorized deducted list first case second place first list you must precise additional criteria accept refuse string resulting list moment seems several combinations respond question given list ps this answer mine clearly deserve upvote the upvoter kindly asked remove upvote,i list strings from list want generate new list strings strings unique know use set new list string new list subset string list edit from comments received try put clarifications the word subset accurate substring,1 here instructions httpwwwimladriscomscriptspythonforwindowshtml,can anyone help set python run wampserver from i read far would need use combination wampser python modpyhton adjustment apache httpconf file i tried belive conflict comes versions does anyone know cobination versions work local python development using wampserver links download would greatly appreciated my current config wampserver c apache version php version mysql version b,1 use rootafter call update periodically use strl tkstringvar tklabeltextvariablestrl allow label text change call strlset change label text a default value screenroot equal displaydisplayscreenroot added mousepos long chain function calls repeated every time mousepos called calling mousepos without arguments continue work usual import tkinter tk import xlibdisplay display def mouseposscreenrootdisplaydisplayscreenroot pointer screenrootquerypointer data pointerdata return datarootx datarooty def update strlsetmouse formatmousepos rootafter update root tktk strl tkstringvar lab tklabelroottextvariablestrl labpack rootafter update roottitlemouseposition rootmainloop,i want track mouseposition show tiny window for i created piece code usrbinpython tkinter import xlib import display def mousepos data displaydisplayscreenrootquerypointerdata return datarootx datarooty root tk strl mouse formatmousepos lab labelroottextstrl labpack roottitlemouseposition rootmainloop this little script shows mouseposition startup refresh mousemovement i get behind i say i new python i think i use event xlib tells script mouse moving how i refresh mouseposition,1 it works it also best practice initialize random generator calling randomseed beginning script even necessary mistake omit if want test add following printrolldie end script print result since return keyword print anything screen used let result function,i need run random sided dice twice return sum i sure right i think i still learning python i pretty new comes kind stuff import random def rolldie roll randomrandint roll randomrandint total roll roll return total,1 i think work def uniquesublistlst sortedlst sortedlst keylen reversetrue subs set result sortedlst subs subsupdatesij range lens j rangei lens resultappends return sortedresult keylstindex uniquesublist man ran catamaran boat man catamaran boat uniquesublist abcd abyet abcd betry outry rumunu abyetin takama eli com betry rumunu foutrym abcd betry rumunu abyetin takama eli com betry foutrym my edit fixes issues previous code note prefers longer words shorter ones,i list strings from list want generate new list strings strings unique know use set new list string new list subset string list edit from comments received try put clarifications the word subset accurate substring,1 here something may work asis hopefully point right direction class testdataobject def getattrself name name data data data raise attributeerrortestdata name name data result selfgeneratedata data setattrselfclass name result elif name data result selfgeneratedata data setattrselfclass name result elif name data result selfgeneratedata data setattrselfclass name result return result def generatedataself dataname return dataname intdataname the testdata class uses getattr method generate data needed saving generated date back class instance data kept around future use well class usessomedataobject def initself func selffunc func def callself args kwargs global testdata testdata testdata return selffuncargs kwargs a simple decorator set global name binding testdata in fact version decorator simple easily replaced module level name binding testdata testdata usessomedata def testingtest printtestdatadata and test function if like global level testdata could get fancier decorator assign testdata function class usessomedataobject def initself func selffunc func def callself args kwargs selffunctestdata testdata return selffuncargs kwargs in case make sure testing functions reference usessomedata def testingtest printtestingtesttestdatadata,i trying build nice base around pytest some tests needs certain test data work today specify mock object function argument setup generator clearly desirable here example could look today def testsomethingself somedata somedata unused test i like something like usessomedata def testsomethingself the data loaded test run though i figured properly i cannot use class setup i want data persistant entire session setuptorn every test class my first idea still use funcargs instead letting test funcarg let decorator request funcarg function basically hiding ugliness the problem i need pytest object request funcarg is way i get object wrong approach together it would awesome bonus data loaded none collected tests requires data downside using decorators seeing always run matter test run,1 this called elsewhere script asyncscriptstartoptionsscript that invokation wrong you calling threadingthread nullary arguments counting self start method script string self instead instanciating asyncscript class passing string init calling resulting thread object start method obviously string thread threading code fails give one self it probably asyncscriptoptionsscriptstart,i running problem following python code the code attempt timing tests another application i testing the idea another script variety get passed timer program make changes environment that script run separate thread i start timing start script instead end the rest script times application reaction script i attempted draw threading module documentation create i confident i read thoroughly i consistently running following error using code traceback recent call last file stdin line module file cpythonlibthreadingpy line start selfinitialized attributeerror str object attribute initialized here thread class definition import threading class asyncscriptthreadingthread def initself selfscript def runself print beginning script try ossystemcmd k selfscript except sysexiterror running script selfscript this called elsewhere script asyncscriptstartoptionsscript options class contains options passed script using argparse module any ideas i might wrong okay update the following strippeddown version code does work i honestly sure i see difference import threading class asyncscriptthreadingthread def initself threadingthreadinitself selfscript def runself printthis would run script selfscript asyncscriptsample script path stringstart output appropriately this would run script sample script path string aside inclusion threadingthreadinitself i previously included earlier versions code without success i really sure different what i missing,1 apparently issue server expects message body delete requests that unusual expectation delete specifying contentlength headers i able successfully perform deletes somewhere along way pythonrestclient httplib contentlength header wiped i try restfullib import connection selfbaseurl httpwwwthomasbayercom selfconn connectionselfbaseurl response selfconnrequestdelete sqlrestcustomer headers contentlength just prove concept i went point stack trace request happening file homefmkpythonrestclientsrchttplibinitpy line connrequest response conngetresponse i printed headers parameter confirm content length i added ifmethod delete headers contentlength request i think real answer service wonky least i got know httplib little better i seen confused people looking help rest python hopefully i one got something,i trying use pythonrestclient httpcodegooglecomppythonrestclientwikiusingconnection perform testing restful webservices since i learning i pointing tests sample services provided httpwwwprediccomrestdemohtm i problems creating entries updating entries retrieving entries post get requests when i try make delete request fails i use firefox rest client perform delete requests work i also make delete requests services i driving crazy trying figure work case i using python updated httplib i also tried python i could use pythonrestclient included version httplib i see problem either case the code simple matching documented use restfullib import connection selfbaseurl httpwwwthomasbayercom selfconn connectionselfbaseurl response selfconnrequestdelete sqlrestcustomer i looked resulting http requests browser tool code i see one works this trace i receive traceback recent call last file homefmkpythonrestclientsrctestexampleservicepy line testcrud selfdelete file homefmkpythonrestclientsrctestexampleservicepy line delete response selfconnrequestdelete sqlrestcustomer file homefmkpythonrestclientsrcrestfullibpy line requestdelete return selfrequestresource delete args headersheaders file homefmkpythonrestclientsrcrestfullibpy line request resp content selfhrequestsss selfscheme selfhost joinrequestpath methodupper bodybody headersheaders file homefmkpythonrestclientsrchttplibinitpy line request response content selfrequestconn authority uri requesturi method body headers redirections cachekey file homefmkpythonrestclientsrchttplibinitpy line request response content selfconnrequestconn requesturi method body headers file homefmkpythonrestclientsrchttplibinitpy line connrequest response conngetresponse file usrlibpythonhttpclientpy line getresponse responsebegin file usrlibpythonhttpclientpy line begin version status reason selfreadstatus file usrlibpythonhttpclientpy line readstatus raise badstatuslineline httpclientbadstatusline what breaking what i actually i settle advice debugging i changed domain script pointed machine i could view request i viewedmodified firefox requests burpproxy make match script requests the modified burp requests still work python requests still,2 alist man ran catamaran boat result set word alist word result continue shortcut performance reasons toremove word result word word break word word toremoveappendword else resultaddword word toremove resultremoveword print result gives set catamaran boat man,i list strings from list want generate new list strings strings unique know use set new list string new list subset string list edit from comments received try put clarifications the word subset accurate substring,1 logical and naturallanguage one therefore code gets interpreted var var thequestion true var thequestion since bool var true var thequestion you want connect two tests logical and var thequestion var thequestion alternatively large numbers tests allk thequestion k var var,i making sort qampa script python it gets rawinput sets thequestion i tried var var thequestion looks either string is way i make work one statement x z,3 how x z z something,i making sort qampa script python it gets rawinput sets thequestion i tried var var thequestion looks either string is way i make work one statement x z,1 txt open thefiletxt r read keyword foo bar keyword txt do something keyword found print matched keyword keyword,i list keywords i need ensure present string this string could either plain text plain text svn git repository syntax patch how exactly would implement search pythondjango environment regex loop grep i ideally also like get line happens i display user,1 since windows fork system call multiprocessing module black magic fork process basically tries guess entry point program skips code executed fork supposed happen probably include name main guard code necessary code work windows see platformspecific documentation information,i running python version linux amp windows box i running script generates child processes using multiprocessingprocess wait desire task amp exit eventually this works fine linux windows giving error processstart the following sample code snippet pobj processtarget foo argsbar pobjstart error windows system windowserror error the system cannot find file specified i basic debugging found error coming cpythonlibmultiprocessingforkingpy file line,2 this simple code def funkyalist result sortedalist keylen reversetrue anys item item result resultappends return result ordering requirement specified print funky man ran catamaran boat print funky abcd abyet abcd betry outry rumunu abyetin takama eli com betry rumunu foutrym produces catamaran boat man rumunu abyetin abcd betry takama eli com betry foutrym,i list strings from list want generate new list strings strings unique know use set new list string new list subset string list edit from comments received try put clarifications the word subset accurate substring,1 python dll cwindowssystempythondll cwindowssyswowpythondll wxpython dlls cpythonlibsitepackageswxmswunicodewxwxbaseuhnetvcdll cpythonlibsitepackageswxmswunicodewxwxbaseuhvcdll cpythonlibsitepackageswxmswunicodewxwxbaseuhxmlvcdll cpythonlibsitepackageswxmswunicodewxwxmswuhadvvcdll cpythonlibsitepackageswxmswunicodewxwxmswuhauivcdll cpythonlibsitepackageswxmswunicodewxwxmswuhcorevcdll cpythonlibsitepackageswxmswunicodewxwxmswuhgizmosvcdll cpythonlibsitepackageswxmswunicodewxwxmswuhgizmosxrcvcdll cpythonlibsitepackageswxmswunicodewxwxmswuhglvcdll cpythonlibsitepackageswxmswunicodewxwxmswuhhtmlvcdll cpythonlibsitepackageswxmswunicodewxwxmswuhmediavcdll cpythonlibsitepackageswxmswunicodewxwxmswuhqavcdll cpythonlibsitepackageswxmswunicodewxwxmswuhrichtextvcdll cpythonlibsitepackageswxmswunicodewxwxmswuhstcvcdll cpythonlibsitepackageswxmswunicodewxwxmswuhxrcvcdll but install python wxpython using installer need copy anywhere building binary if building standalone binary see blender comment,our current project made python wxpython it working fine but upgrading python wxpython as i new python installation dlls i need little guidence there following files present nsis installation folder old python pythondll wxmswhdll as project made previous programmer i know got dlls made dll i think make installation program new python i need following dlls pythondll wxmswhdll as per i understand wxmsw dll i need compile wxpythonsrc sure i please let know i get dlls if i need create please let know i create dlls thanks advance,2 to use pure slicing call len padded source maxlenmaxlen if called many times initialize allempty list module scope then padded source allemptymaxlen,i list python i know exactly long i know less items long i want pad exactly items long appending empty strings items i need add is efficient way python i hoping myarr myarr might work currently i lenmyarr range lenmyarr myarrappend any compact suggestions,2 first try simply install pytestxdist pypi run existing tests pytest n parallel processes if basically works means modifying pytestxdist use lsf transport worthwhile option effectively need look extending execnet httpcodespeaknetexecnet underlying library distributing execution hth,i need parallelize python unittests i wrote using default unittest module i trying decide two approaches keep using unittest use custom multiprocess runner spawn test using platform lsf remote execution tool example found testoob project use pytest customize pytestxdist plugin run lsf instead ssh i lean towards since i already working setup particularly test suite generation using generator parse excel spreadsheet trivial any recommendation particular approach follow note company using lsf i must use resource sharing teams,1 replying i ended using solution import flask patch flaskrendertemplate rendertemplate flaskrendertemplate def myrendertemplateargs kwargs detectmobilebrowserflaskrequestuseragentstring args args args return rendertemplateargs kwargs flaskrendertemplate myrendertemplate far seems work i put mobile templates subdirectory,i writing application flask i like generate different code desktop mobile browsers imho good idea keep application code identical push problem serving different content stack template level essentially becomes matter writing two sets templates two use cases finding way choose correct one use every single request i using default jinja template engine flask i mention i experience flask i learning way i write code i taking exercise what mechanism would use address problem keep source code clean possible,2 ok turns simple rather obvious find from rse perspective rightclick folder containing source files select create remote project this seems work fairly well i still one problem it seems debugger wants local copy file i debugging consider rse copy local enough so i copy file remote server workstation i start debugging it kind defeats purpose integration is better way i looking ssh filesystems really want it feels like i close edit this recently addressed pydev developers as today installing nightly pydev update adds option fetch source remote server details,i new eclipsepydev probably really basic question i want use edit debug python files remote system i able using rse pydevd i really seem integrated ide that i go rse perspective edit files i lauch script remote system step debugger but files part project eclipse maintains it fairly disjointed is way make remote files part eclipse project i drag files project makes local copy am i approaching wrong thanks jerry,3 first construct dictionary mapping strings list corresponding ids then use list comprehension apply mapping list hello bye third list bye second forth list dictziplist list printdgetx x x list prints second forth,i three lists python the first two contain strings third one contains ids match first one i would like compare strings second list terms first list i find string i want take id third list replace string second list eg list hello bye third list bye second forth list see common term bye so i want take id list corresponds string list replace bye string list id is easy way python,1 my tests directory structure looks way root tests unittests someapptests anotherapptests runtestspy integratetests someapptests anotherapptests runtestspy projectroot someapp anotherapp for individual app i create coresponding directory tests unit integrate directory each directory separate django project custom settings management command used run tests also placing tests one directory one nice advantage project deployed reason deploy tests so i strip one directory run tests i use djangosanetesting httpsgithubcomalmaddjangosanetesting,i following typical python project file structure packagea subpackage classapy subpackage classbpy test subpackage classatestpy subpackage classbtestpy i currently trying organize unittests functional tests i run unittests functional tests separately using nose also option run tests the tests would live packageatestsubpackage packageatestsubpackage what good way organize different tests by folder functional vs unit by naming convention test class classatest vs classafunctionaltest naming convention test methods classafootest vs classabarfunctionaltest can someone explain nosetests regex matching works the options e seem run i expect run does regex match directories subpackage files classatest test classes classatest test methods classafootest i extremely confused,2 after playing around i found works def pytestfuncargsomedatarequest def create load test data print test data loaded return requestcachedsetup setupcreate scope session extrakey somedata def usessomedatafunc the funcarg actually requested def wrapperself somedata return func return wrapper class testsomethingobject usessomedata def testsomethingself some data available pass,i trying build nice base around pytest some tests needs certain test data work today specify mock object function argument setup generator clearly desirable here example could look today def testsomethingself somedata somedata unused test i like something like usessomedata def testsomethingself the data loaded test run though i figured properly i cannot use class setup i want data persistant entire session setuptorn every test class my first idea still use funcargs instead letting test funcarg let decorator request funcarg function basically hiding ugliness the problem i need pytest object request funcarg is way i get object wrong approach together it would awesome bonus data loaded none collected tests requires data downside using decorators seeing always run matter test run,1 i would like point probably somewhat different direction a lot designers developers included see future website design templates separated one template responds environment dynamically that reorders elements way suites best given display it called responsive design i know probably solution looking could become way better one,i writing application flask i like generate different code desktop mobile browsers imho good idea keep application code identical push problem serving different content stack template level essentially becomes matter writing two sets templates two use cases finding way choose correct one use every single request i using default jinja template engine flask i mention i experience flask i learning way i write code i taking exercise what mechanism would use address problem keep source code clean possible,2 according django track inputformats setting ignored useln set true,i searched several threads bug reports find solution i changed locale django project ptbr made difference i excepted input fields outputs localize dates numbers specially decimalseparator thousandseparator including admin api but dates continue appear yyyymmdd decimal separator generates error upon input i everything i found changed settings added localization middleware classes enabled usein useln tried force setlocale manually etc here glimpse settingspy languagecode ptbr usein true useln true middlewareclasses djangomiddlewarecommoncommonmiddleware djangomiddlewarelocalelocalemiddleware djangocontribsessionsmiddlewaresessionmiddleware djangocontribauthmiddlewareauthenticationmiddleware djangomiddlewaretransactiontransactionmiddleware dateformat dmy shortdateformat dmy dateinputformats dmy dmy ymd decimalseparator thousandseparator is weird python console running brazilian portuguese windows outputs localesetlocalelocalelcall ptbr cp traceback recent call last file stdin line module file cpythonliblocalepy line setlocale return setlocalecategory locale localeerror unsupported locale setting any ideas i forgot try,1 i really sure game supposed work may help usrbinenv python import random import sys pegs range def rolldice return randomrandint randomrandint true roll rolldice print you rolled roll availablechoices setp p pegs p x setrangeroll lenavailablechoices print fail sauce sysexit true choice rawinputchoose number joinstrx x sortedlistavailablechoices choice q sysexit choice intchoice choice availablechoices break print nice try buddy pick number range picked pegschoice x print joins p p pegs lenx x pegs x x print winner sysexit,so i creating basic python game i need help step i stuck the concept game program roll two die add sums with number choose number available number list peg they keep going numbers pegged options earlier program i created two functions i using step those two asknumber validmoves basically ask number asks number want peg actually peg number yet the validmoves function checks numbers still available player select the game pretty much looks like halfway xxx the x numbers already pegged in part game i need figure replace number x i far i know i way i trouble figuring pegholes name list move number picked asknumber function thanks much pegged x def enterpegpegholes roll total asknumber asknumber validmoves pegholesappendasknumberpegged return pegholes move,1 looks like version beautiful soup released almost year ago there also htmlparser httpdocspythonorglibraryhtmlparserhtml,i need make web crawler extract information web pages i made research found beautiful soup excellent since could parse document create dom objects iterate extract attributes etcsimilitar jquery but i using python stable version iti think i saw home page so i need good alternatives,2 i recommend bottle really easy build simple little json services bottle import get def servejson return msg some message error some error runhost localhost port one neat feature bottle automatically serve json route returns dict you execute python servejsonpy run app using builtin http server host wsgi application etc,i searched high low answer figure wrong i creating api returns json data i would prefer response printed browser well possible what i wrong usrbinpython import simplejson json class servejson def initself x msg some message error some error htmltodisplay contenttype applicationjsonnn htmltodisplay jsondumpsx print htmltodisplay servejson the code work print result browser if i change contenttype texthtml prints screen fine still work json data i using framework everything straight pythonjavascript this script executed http post request this script executed via cgi httpgroupedcomcgibinuploadexamplephp works perfectly httpgroupedcomcgibinuploadexamplepy does work contenttype texthtml the code listed also work either represents identical example one except contenttype set applicationjson,2 two possible solutions would embedding matplotlib plot pyqt example using pyqwt extensions examples,i would like plot d histogram bar chart python application using pyqt anyone code example refer example many thanks,1 sum list straight python manual def sumseq def addxy return xy return reduceadd seq sumrange sum this could done oneliner ish using lambda python anonymous function syntax def sumseq return reducelambda x x seq don want use reduce def sumseq total seq total return total,i know python builtin list functions i curious one would write function sum list function reverse list i able figure write list functions sort count index etc i imagine languages builtin functions could someone show python code functions using builtin functions,1 for summing list sum and reversing list return new reversed list using python slices now want use builtin functions def sumlst e lst e return def reverselst l e lst l e l return l,i know python builtin list functions i curious one would write function sum list function reverse list i able figure write list functions sort count index etc i imagine languages builtin functions could someone show python code functions using builtin functions,1 you could subclass simplehttprequesthandler import cgi os socketserver sys time urllib simplehttpserver import simplehttprequesthandler stringio import stringio class directoryhandlersimplehttprequesthandler def listdirectoryself path try list oslistdirpath except oserror selfsenderror no permission list directory return none listsortkeylambda alower f stringio displaypath cgiescapeurllibunquoteselfpath fwrite doctype html public wcdtd html finalen fwritehtmlntitledirectory listing stitlen displaypath fwritebodynhdirectory listing shn displaypath fwritehrnuln name list fullname ospathjoinpath name displayname linkname name datemodified timectimeospathgetmtimefullname append directories symbolic links ospathisdirfullname displayname name linkname name ospathislinkfullname displayname name note link directory displays links fwrite lia hrefss san urllibquotelinkname cgiescapedisplayname datemodified fwriteulnhrnbodynhtmln length ftell fseek selfsendresponse encoding sysgetfilesystemencoding selfsendheadercontenttype texthtml charsets encoding selfsendheadercontentlength strlength selfendheaders return f httpd socketservertcpserver directoryhandler print serving port httpdserveforever this might look like lot work really i adding one line listdirectory method datemodified timectimeospathgetmtimefullname adding directory listing output,i using python simplehttpserver simple web server internal users access data files test server the default listing simplehttpserver simple it shows file links how i make show file timestamp well i happy write custom class extend simplehttpserver i using python moment,3 i know old i found function finditemstext qtmatchflags qlistwidget so iterate items listwidget qlistwidget full items allitems listwidgetfinditems qtcoreqtmatchregexp item allitems print item and whatever need item,currently i use following loop class inherits qtguiqlistwidget iterate items selfcount item selfitemi i hoping i could use item selfitems items method wants qmimedata object i know construct return items is cleaner approach loop,3 this could lxml lovely requests import requests import lxmlhtml lh beautifulsoup import unicodedammit url httpenwikipediaorgwindexphptitledataminingampprintableyes headers useragent mozilla def lhgetargs kwargs r requestsgetargs kwargs html unicodedammitrcontentunicode tree lhfromstringhtml return tree def removeel elgetparentremoveel tree lhgeturl headersheaders el treexpathdivclass mwcontentltr p ref elxpathsupclass reference removeref print lhtostringel prettyprinttrue print eltextcontent,i trying crawl wikipedia get data text mining i using python urllib beautifulsoup my question easy way getting rid unnecessary tagslike links span text i read scenario import urllib beautifulsoup import opener urllibbuildopener openeraddheaders useragent mozilla infile openeropenhttpenwikipediaorgwindexphptitledataminingampprintableyespool beautifulsoupinfileread respoolfindall div attrs class mwcontentltr get content directly paragrapgsresfindallp get paragraphs i get paragraphs lots reference tags like paragrapgs pbdata miningb analysis step bknowledge discovery databasesb processsup idcitereffayyad classreferencea hrefcitenotefayyadspanspanspanspanasup kdd relatively young interdisciplinary field hrefwikicomputerscience titlecomputer sciencecomputer scienceasup idciterefacm classreferencea hrefcitenoteacmspanspanspanspanasupsup idciterefbrittanica classreferencea hrefcitenotebrittanicaspanspanspanspanasup process discovering new patterns large hrefwikidataset titledata setdata setsa involving methods intersection hrefwikiartificialintelligence titleartificial intelligenceartificial intelligencea hrefwikimachinelearning titlemachine learningmachine learninga hrefwikistatistics titlestatisticsstatisticsa hrefwikidatabasesystem titledatabase systemdatabase systemsasup idciterefacm classreferencea hrefcitenoteacmspanspanspanspanasup the goal data mining extract knowledge data set humanunderstandable structuresup idciterefacm classreferencea hrefcitenoteacmspanspanspanspanasup involves database hrefwikidatamanagement titledata managementdata managementa hrefwikidatapreprocessing titledata preprocessingdata preprocessinga hrefwikistatisticalmodel titlestatistical modelmodela hrefwikistatisticalinference titlestatistical inferenceinferencea considerations interestingness metrics hrefwikicomputationalcomplexitytheory titlecomputational complexity theorycomplexitya considerations postprocessing found structure hrefwikidatavisualization titledata visualizationvisualizationa hrefwikionlinealgorithm titleonline algorithmonline updatingasup idciterefacm classreferencea hrefcitenoteacmspanspanspanspanasupp any ideas remove pure text,1 p paragraphstexttrue print p additionally could use apiphp instead indexphp usrbinenv python import sys import time import urllib urllib import xmletreecelementtree etree prepare request maxattempts many times try request giving maxlag seconds httpwwwmediawikiorgwikimanualmaxlagparameter params dictactionquery formatxml maxlagmaxlag proprevisions rvpropcontent rvsection titlesdatamining request urllibrequest httpenwikipediaorgwapiphp urlliburlencodeparams headersuseragent wikidownloader referer httpstackoverflowcomq make request rangemaxattempts response urlliburlopenrequest responseheadersget mediawikiapierror maxlag responseheadersget retryafter print retrying seconds timesleepfloatt else break ready read else exhausted attempts sysexit download amp parse xml tree etreeparseresponse find rev data revdata treefindtext rev revdata print mediawikiapierror responseheadersget mediawikiapierror treewritesysstdout print sysexit printrevdata output distinguishanalyticsinformation extractiondata analysis data mining analysis step knowledge discovery databases,i trying crawl wikipedia get data text mining i using python urllib beautifulsoup my question easy way getting rid unnecessary tagslike links span text i read scenario import urllib beautifulsoup import opener urllibbuildopener openeraddheaders useragent mozilla infile openeropenhttpenwikipediaorgwindexphptitledataminingampprintableyespool beautifulsoupinfileread respoolfindall div attrs class mwcontentltr get content directly paragrapgsresfindallp get paragraphs i get paragraphs lots reference tags like paragrapgs pbdata miningb analysis step bknowledge discovery databasesb processsup idcitereffayyad classreferencea hrefcitenotefayyadspanspanspanspanasup kdd relatively young interdisciplinary field hrefwikicomputerscience titlecomputer sciencecomputer scienceasup idciterefacm classreferencea hrefcitenoteacmspanspanspanspanasupsup idciterefbrittanica classreferencea hrefcitenotebrittanicaspanspanspanspanasup process discovering new patterns large hrefwikidataset titledata setdata setsa involving methods intersection hrefwikiartificialintelligence titleartificial intelligenceartificial intelligencea hrefwikimachinelearning titlemachine learningmachine learninga hrefwikistatistics titlestatisticsstatisticsa hrefwikidatabasesystem titledatabase systemdatabase systemsasup idciterefacm classreferencea hrefcitenoteacmspanspanspanspanasup the goal data mining extract knowledge data set humanunderstandable structuresup idciterefacm classreferencea hrefcitenoteacmspanspanspanspanasup involves database hrefwikidatamanagement titledata managementdata managementa hrefwikidatapreprocessing titledata preprocessingdata preprocessinga hrefwikistatisticalmodel titlestatistical modelmodela hrefwikistatisticalinference titlestatistical inferenceinferencea considerations interestingness metrics hrefwikicomputationalcomplexitytheory titlecomputational complexity theorycomplexitya considerations postprocessing found structure hrefwikidatavisualization titledata visualizationvisualizationa hrefwikionlinealgorithm titleonline algorithmonline updatingasup idciterefacm classreferencea hrefcitenoteacmspanspanspanspanasupp any ideas remove pure text,2 here import badwords spam ham badwordsre recompilerbsb joinbadwords line enumerateopenfiletxtreadlines words setbadwordsrefindallline words print found following words line joinwords print line,i list keywords i need ensure present string this string could either plain text plain text svn git repository syntax patch how exactly would implement search pythondjango environment regex loop grep i ideally also like get line happens i display user,1 you always find workaround something like numpynansumdat axis numpysumnumpyisfinitedat axis numpy numpymean skipna option take care,how i calculate matrix mean values along matrix remove nan values calculation for r people think narm true here nonworking example import numpy np dat nparray npnan npnan npnan npnan npnan npnan printdat printdatmean nan nan nan with nans removed expected output would array nan,3 i say virtualenv httpspypipythonorgpypivirtualenv it seems like thing use pip install packages virtual python environments,is python equivalent perlbrew ideally equivalent would least following two features allow multiple python isolated installs ie perlbrew install list use allow installation noncore python modules specific python installs combination perlbrew say cpanminus thanks ☺,3 you hit big reason php popular pieces serverembeddable package there really many solutions ease deployment php written specifically want strength weakness it weak generalpurpose language everyone dog knows it everywhere barrier entry near zero php language plus templating plus web framework baked one package to get equivalent going need web framework even small one something like sinatra super lightweight way similar ruby though requires separate server process you could look something like perl cgipm may step wrong direction wanting something cleaner php i know python packages well enough offer suggestions twisted makes easy bind python program web interface that end running server process though you need little work standard php deploy want use something besides php often choice people consider reasonable tradeoff gains productivity,i first learned web programming php back it features i find helpful overall language something i enjoy matter personal preference i wondering alternatives i could use provide similar functionality using different underlying programming language python ruby what i looking general purpose programming capability inline serverside code embedded html ie i want able make documents pure html desired rather demanding special syntax even i want dynamic content access request parameters ability send headers set cookies etc preferably require separate server process easy connect apache does anyone suggestions one thing i tried embedded ruby erb cgi this looked like good fit paper unfortunately i able get work i following different guides result combining work at rate seems would allow set arbitrary headers importantly use sessions cookies note i looking full web framework moment just relatively small amounts dynamic content among otherwise html pages thanks,3 other question full page topic,i trying remove item sorted list if item list list remains unchanged if item occurs multiple times one occurrence item removed again i allowed use buildin list functions time i trying get code work class sortedlist def initself selfslist def insertself item selfslistappenditem def removeself item finalset item selfslist item finalset finalsetappenditem return finalset def strself return strselfslist,1 you could use memoization cache intermediate values regardless function called first second able take advantage memoized value cache def expensivecalcx if x numpy array need convert x something hashable used key cache keytuplex try return cachekey except keyerror expensive calc result cachekey result return result def funcx yexpensivecalcx return somethingbasedony def funcderx yexpensivecalcx return somethingelsebasedony def optimizefminbfgs xopt fminbfgsfunc xguess fprimefuncder,i fairly complex function fx i want optimize i using fminbfgs function scipyoptimize module scipy it forces give function minimize function gradient f x separately pity computations gradient done evaluating function fx is way combining functions i considering saving intermediate values required functions i know fminbfgs function guarantees fx evaluated f x thank,1 python flask good web framework fits requirements easy learn scales gracefully go tutorial see,i first learned web programming php back it features i find helpful overall language something i enjoy matter personal preference i wondering alternatives i could use provide similar functionality using different underlying programming language python ruby what i looking general purpose programming capability inline serverside code embedded html ie i want able make documents pure html desired rather demanding special syntax even i want dynamic content access request parameters ability send headers set cookies etc preferably require separate server process easy connect apache does anyone suggestions one thing i tried embedded ruby erb cgi this looked like good fit paper unfortunately i able get work i following different guides result combining work at rate seems would allow set arbitrary headers importantly use sessions cookies note i looking full web framework moment just relatively small amounts dynamic content among otherwise html pages thanks,2 i three suggestions the first ruby rails it pretty fun get i would recommend going rails zombies get general idea whether like httprailsforzombiesorg it really easy get something running heroku free spend money get something web my second suggestion one i trying called nodejs i recommend watching video get idea httpwwwyoutubecomwatchvjoblthii if javascript i think get right away you also build open source nodejs project wwwcloudidecom pretty nifty a third one learning java play a cool video httpvimeocom i used much list things check overall i suggest dipping toes water bunch different frameworks get idea work naturally pursue whatever makes sense good luck,i first learned web programming php back it features i find helpful overall language something i enjoy matter personal preference i wondering alternatives i could use provide similar functionality using different underlying programming language python ruby what i looking general purpose programming capability inline serverside code embedded html ie i want able make documents pure html desired rather demanding special syntax even i want dynamic content access request parameters ability send headers set cookies etc preferably require separate server process easy connect apache does anyone suggestions one thing i tried embedded ruby erb cgi this looked like good fit paper unfortunately i able get work i following different guides result combining work at rate seems would allow set arbitrary headers importantly use sessions cookies note i looking full web framework moment just relatively small amounts dynamic content among otherwise html pages thanks,2 way late answer original string utf xcxa utf nobreak space simply decode original string sdecode utf xa displays space decoded incorrectly windows latin example python b xcxaxcxaxcxa printsdecode latin incorrectly decoded u sdecode utf correctly decoded printu printureplace nnobreak space printureplace xa xa unicode nobreak space output ã‚â ã‚â ã‚â â â â,i string looks like ã‚â ã‚â ã‚â the clear cut way trim string i understand python simply say string variable called get sreplace ゠that trick but course complains nonascii character xc file blablapy encoded i never quite could understand switch different encodings here code really context the file saved utf notepad following header usrbinpython coding utf the code f urlliburlopenurl soup beautifulsoupf soupfind div id maincount making print goes well shows ゠゠゠sreplace ゠savemaincounts it gets sreplace,2 i say given requirement just relatively small amounts dynamic content among otherwise html pages php going hard beat getting going quickly minimum learning overhead it avoids cgi issues would otherwise deal fact templating language that many get started once get past point goal mixing little programming logic html pages developing flexible maintainable testable applications frameworks rails django others worth time learn,i first learned web programming php back it features i find helpful overall language something i enjoy matter personal preference i wondering alternatives i could use provide similar functionality using different underlying programming language python ruby what i looking general purpose programming capability inline serverside code embedded html ie i want able make documents pure html desired rather demanding special syntax even i want dynamic content access request parameters ability send headers set cookies etc preferably require separate server process easy connect apache does anyone suggestions one thing i tried embedded ruby erb cgi this looked like good fit paper unfortunately i able get work i following different guides result combining work at rate seems would allow set arbitrary headers importantly use sessions cookies note i looking full web framework moment just relatively small amounts dynamic content among otherwise html pages thanks,2 while true setcombinestderr diverts stderr stdout stream chaotic order get result probably want namely lines combined order written running command local terminal window instead use getpty that cause server run lines pseudoterminal keeping chronological sequence here test program outerrpy writes alternating lines stdout stdin assume sitting home directory llmpsmeerkat usrbinenv python import sys x xrange sysstdout sysstderrxwrite this line stdsn x err x now try following code run remotely usrbinenv python import paramiko def connect ssh paramikosshclient sshsetmissinghostkeypolicyparamikoautoaddpolicy sshconnect meerkat username llmps password return ssh def runtestssh tran sshgettransport chan tranopensession chansetcombinestderrtrue changetpty f chanmakefile chanexeccommand outerrpy print fread name main ssh connect runtestssh sshclose if run see lines order written if instead comment changetpty call uncomment chansetcombinestderrtrue call get clumps stdout stderr lines interspersed randomly run run,i trying combine output stdout stderr my belief done setcombinestderr channel object this i ssh paramikosshclient i connect everything ok chan sshinvokeshell chansetcombinestderrtrue chanexeccommand python subirpy resultado chanmakefile rb however i get following error i try store result last line chanmakefile error channel closed any help would greatly appreciated,3 the way bypass get accessing class attribute look via class dictionary rather using dotted access this easy demonstrate using function objects for example class aobject def fself pass af dotted access calls fget unbound method af varsa f dict access bypasses fget function f x a af dotted access calls fget bound method af maina object xe varsaclass f dict access bypasses fget function f x the piece information missing inherited get runs getattr runs attribute found this logic controlled getattribute inherited object so want bypass get either need write new get subclass change lookup logic defining getattribute subclass to fix lazyobject class replace getattr class lazyobjectlazyobject def getattributeself key bypass get return objectgetattributeself dict key in summary key pieces knowledge used solve problem objectgetattribute controls lookup logic it first looks get whether defined current class inherited only nothing found attempt call objectgetattr the three steps happen dotted lookup those step bypassed directly accessing dict via dict vars the full details descriptor logic found writeup presentation,i made lazy variable class used another class how i access attributes lazy variable class i tried getattr without luck here example class lazyobjectobject def initselfvarnamesomething this something i want access selfvarname varname selfsomething something def getself obj typenone objdicthaskeyselfvarname print already computed selfvarname return objdictselfvarname else print computing selfvarname objdictselfvarname something else return objdictselfvarname class lazyobjectlazyobject def getattrself return selfsomething class dummyobject def initself setattrselfclass lazy lazyobject lazy class dummyobject def initself setattrselfclass lazy lazyobject lazy dummy dummy try print dlazysomething getattr dlazysomething except print dlazy already computed get something string print dlazy getattr dlazy try print dlazysomething getattr dlazysomething except print dlazy already computed get something string print dlazy getattr dlazy this prints dlazysomething getattr computing lazy dlazy already computed get something string dlazy getattr something else dlazysomething getattr computing lazy dlazy already computed get something string dlazy getattr something else what i would like print dlazysomething getattr this something i want access computing lazy dlazy getattr something else the example contrived i hope gets point across another way phrase question how i bypass get method accessing class attribute,2 you use statement make sure files closed execution from blog entry open file process contents make sure close simply openxtxt f data fread something data,what efficient fastest way simultaneously read two large files processing i two files atxt btxt containing hundred thousand corresponding lines my goal read two files processing line pair def kernel afileopen atxt r bfileopen btxt r aline afilereadline bline bfilereadline aline processasplbspl process requiring corresponding file lines i looked xreadlines readlines wondering better speed paramount importance task thank,1 there way client make sure server tells truth you create selfsigned certificate googlecom,i tornado server provide https connection self signed certificate i generated way openssl genrsa privatekeypem openssl req new key privatekeypem certrequestcsr openssl x req certrequestcsr signkey privatekeypem certificatepem the code server following import tornadoioloop import tornadoweb import tornadohttpserver import os class mainhandlertornadowebrequesthandler def getself print new client strself selfwritehello world application tornadowebapplication r mainhandler httpserver tornadohttpserverhttpserverapplication ssloptions certfile ospathjoin certificatepem keyfile ospathjoin privatekeypem name main httpserverlisten tornadoioloopioloopinstancestart i want python client connect server check server right server i guess certificate for moment i simple client like import httplib hostname localhost conn httplibhttpsconnectionhostname connputrequest get connendheaders response conngetresponse print responseread what would suggest the client later mobile app i use python prototyping thanks,1 string io pretty fast probably processing slows things consider simple input loop feed queue like queue multiprocessingqueue afile open atxt bfile open btxt pair itertoolsizipafile bfile queueputpair blocks full queue you set pool processes pulling items queue taking action assuming problem parallelised way,what efficient fastest way simultaneously read two large files processing i two files atxt btxt containing hundred thousand corresponding lines my goal read two files processing line pair def kernel afileopen atxt r bfileopen btxt r aline afilereadline bline bfilereadline aline processasplbspl process requiring corresponding file lines i looked xreadlines readlines wondering better speed paramount importance task thank,1 your remove function seems confused def removeself item finalset item selfslist item finalset finalsetappenditem return finalset why creating new list modifying existing list there two different item function one parameter function loop the one loop replaces parameter give different names you return list almost right away probably want return loop completed your return statement intended far since confused two different variables giving name i guess actually trying inside loop,i trying remove item sorted list if item list list remains unchanged if item occurs multiple times one occurrence item removed again i allowed use buildin list functions time i trying get code work class sortedlist def initself selfslist def insertself item selfslistappenditem def removeself item finalset item selfslist item finalset finalsetappenditem return finalset def strself return strselfslist,1 based docs i pretty sure mass belong hist call,when i try run following code import matplotlibpyplot plt import math import numpy np numpyrandom import normal masses f open myfiletxt r freadline line f line line linestrip strips end line character columns linesplit splits coloumn mass columns column contains mass values mass floatmass massesappendmass mass mathlogmass printmass gaussiannumbers normalsize plthistmass bins normed true plttitlegaussian histogram pltxlabelvalue pltylabelfrequency pltshow i get error traceback recent call last file cdocuments settingskharymy documentspythonhalomassreaderplotterpy line module plthistmass bins normed true file cpythonlibsitepackagesmatplotlibpyplotpy line hist ret axhistx bins range normed weights cumulative bottom histtype align orientation rwidth log color label kwargs file cpythonlibsitepackagesmatplotlibaxespy line hist isinstancex npndarray iterablex typeerror float object subscriptable can one use floats histograms i missing something else any help would appreciated,1 if control client side like android iphone app add selfsigned certificate trusted certificate store it well explained android app,i tornado server provide https connection self signed certificate i generated way openssl genrsa privatekeypem openssl req new key privatekeypem certrequestcsr openssl x req certrequestcsr signkey privatekeypem certificatepem the code server following import tornadoioloop import tornadoweb import tornadohttpserver import os class mainhandlertornadowebrequesthandler def getself print new client strself selfwritehello world application tornadowebapplication r mainhandler httpserver tornadohttpserverhttpserverapplication ssloptions certfile ospathjoin certificatepem keyfile ospathjoin privatekeypem name main httpserverlisten tornadoioloopioloopinstancestart i want python client connect server check server right server i guess certificate for moment i simple client like import httplib hostname localhost conn httplibhttpsconnectionhostname connputrequest get connendheaders response conngetresponse print responseread what would suggest the client later mobile app i use python prototyping thanks,2 you repeating captured group instead capturing repeated group reason getting last capture you using pat recompile see repeating captured group vs capturing repeated group httpwwwregularexpressionsinfocaptureallhtml,i parsing log python need quick fetch values simple equivalent regex usage example pat recompile it work expected last match group returned patmatchgroups what simplest solution problems updated wiki engine says use edit rather creating new post i need repeated matches course tomatch regex find need applyed twice recursively i bear options,1 just make function def dothingswiththosefunctions abspath ospathabspath dirname ospathdirname etc you scope def outerfunction def innerfunction printa innerfunction,sometimes i find i use functions long names ospathabspath ospathdirname lot lines code i think worth littering global namespace functions would incredibly helpful able define scope around lines i need functions as example would perfect import os sys closure abspath ospathabspath dirname ospathdirname lines heavy usage functions can access abspath dirname i love know doable somehow,1 python temporary namespace tool like let lisp scheme the usual technique python put names current namespace take done this technique used heavily standard library abspath ospathabspath dirname ospathdirname lines heavy usage functions abspathsomepath dirnamesomepath del abspath dirname an alternative technique reduce typing effort shorten recurring prefix import math msinx msinx mpi p ospath pabspathsomepath pdirnamesomepath another technique commonly used standard library worry contaminating module namespace rely list names intend make public the effect discussed docs import statement of course also create namespace storing names dictionary though solution common dictabspath ospathabspath dirname ospathdirname abspath somepath dirname somepath lastly put code function local namespace number disadvantages setup awkward atypical mysterious use functions need declare global assignments want temporary code run call function def temp disadvantage awkward setup global disadvantage global declarations abspath ospathabspath dirname ospathdirname lines heavy usage functions abspathsomepath dirnamesomepath temp disadvantage invoking code,sometimes i find i use functions long names ospathabspath ospathdirname lot lines code i think worth littering global namespace functions would incredibly helpful able define scope around lines i need functions as example would perfect import os sys closure abspath ospathabspath dirname ospathdirname lines heavy usage functions can access abspath dirname i love know doable somehow,3 use argparse there section mutually exclusive groups argparseaddmutuallyexclusivegrouprequiredfalse create mutually exclusive group argparse make sure one arguments mutually exclusive group present command line parser argparseargumentparserprog prog group parseraddmutuallyexclusivegroup groupaddargument foo action storetrue groupaddargument bar action storefalse parserparseargs foo namespacebartrue footrue parserparseargs bar namespacebarfalse foofalse parserparseargs foo bar usage prog h foo bar prog error argument bar allowed argument foo optparse deprecated anyway,take following rather standard code optparse import optionparser opts optionparser optsaddoption f actionstoretrue optsaddoptionx destx typeint default options args optsparseargs assume x f mutually exclusive x f explicitly present error reported how i detect x present explicitly even options list default value one way would avoid setting default value i rather help prints default values nicely another way would checking sysargv instances x bit awkward one name x longname one pair mutually exclusive options it elegant solution,3 you misunderstanding documentation line says unless shallow given false files identical osstat signatures taken equal files identical osstat signatures taken equal logical inverse true files unequal osstat signatures necessarily taken unequal rather may unequal case actual file contents compared since file contents found identical filecmpcmp returns true as per third clause determines files equal cache result bother rereading file contents ask compare files long files osstat structures change,the python docs filecmp say unless shallow given false files identical osstat signatures taken equal which sounds like two files identical except osstat signature considered unequal however seem case illustrated running following code snippet import filecmp import os import shutil import time open testfile w f fwrite file contents shutilcopy testfile testfile timesleep pause get different timestamp osutime testfile none change copied file timestamp print testfile osstat testfile print testfile osstat testfile print filecmpcmp filecmpcmp testfile testfile output testfile ntstatresultstmode stinol stdev stnlink stuid stgid stsizel statimel stmtimel stctimel testfile ntstatresultstmode stinol stdev stnlink stuid stgid stsizel statimel stmtimel stctimel filecmpcmp true as see two files time stamps mdash statime stmtime stctime mdash clearly yet filecmpcmp indicates two identical am i misunderstanding something bug either filecmpcmp implementation documentation update the python documentation rephrased currently says following imho improvement sense better implies files different time stamps might still considered equal even shallow true if shallow true files identical osstat signatures taken equal otherwise contents files compared fwiw i think would better simply said something like if shallow true file content compared osstat signatures unequal,3 you accomplish optparse using callback building code optparse import optionparser def setxoption opt value parser parservaluesx value parservaluesxsetexplicitly true opts optionparser optsaddoption f actionstoretrue optsaddoptionx destx typeint default action callback callbacksetx options args optsparseargs optsvaluesensurevalue xsetexplicitly false optionsxsetexplicitly optionsf optserror options x f mutually exclusive let call script oppy if i python oppy x f response usage oppy options oppy error options x f mutually exclusive,take following rather standard code optparse import optionparser opts optionparser optsaddoption f actionstoretrue optsaddoptionx destx typeint default options args optsparseargs assume x f mutually exclusive x f explicitly present error reported how i detect x present explicitly even options list default value one way would avoid setting default value i rather help prints default values nicely another way would checking sysargv instances x bit awkward one name x longname one pair mutually exclusive options it elegant solution,3 this code open file read line print open read file buffer f openfiler lines freadlines if need read line assign variable x lines printx,i want go line txt file read how would python,2 the short answer no python three scopes it function scope global aka module scope builtin scope you declare scopes a class declaration looks sort like scope it basically shorthand assigning bunch fields object the functions class access fields without going object defined this sounds bit limiting in python also nest function definitions a nested function definition gets readonly access outer scope this dynamic the name mentioned function defined here example def joex def bar return def bazz x return x x return bar baz b joe b so sort get effect without sacrificing much locality defining nested function creates values need uses returns result i remember learning python getting used rather strange scoping rules one difficult parts when nested functions introduced opinion made scoping rules even stranger readonly semantics outer scopes dynamic scoping closures apparently python way importing variable enclosing scope using nonlocal keyword analogous global keyword use readwrite context def joex def bar return def bazz nonlocal x return x x return bar baz b joe b otherwise whenever python sees variable lefthand side sign assumes creating new local variable the global nonlocal keywords way stating intend modify variable scope function,sometimes i find i use functions long names ospathabspath ospathdirname lot lines code i think worth littering global namespace functions would incredibly helpful able define scope around lines i need functions as example would perfect import os sys closure abspath ospathabspath dirname ospathdirname lines heavy usage functions can access abspath dirname i love know doable somehow,1 this sort want repeat names try abspath ospathabspath dirname ospathdirname fifteen lines code finally del abspath del dirname this avoids pollution namespace exception situation try try abspath ospathabspath dirname ospathdirname fifteen lines code finally del abspath del dirname want abspath dirname scope even exception block except,sometimes i find i use functions long names ospathabspath ospathdirname lot lines code i think worth littering global namespace functions would incredibly helpful able define scope around lines i need functions as example would perfect import os sys closure abspath ospathabspath dirname ospathdirname lines heavy usage functions can access abspath dirname i love know doable somehow,2 this general problem opencv see it seems builtin first usb cam buildin cam works opencv how use camera opencv cannot access usb webcam opencv cygwin opencv capture usb isight osx currently way extract number cameras listed feature request httpscoderosorgtracopencvticket,i two webcams attached laptop one built work if i use cheese webcam thingy comes ubuntu uses external one if i use cap cvcreatecameracapture cap cvcreatecameracapture i get built webcam if i use cap cvcreatecameracapture it work object cap displays capture nil same capturefromcam so i like know opencv trying seem know second camera there two devices available devvideon entries,3 looking httpsdocsdjangoprojectcomendevreftemplatesbuiltinsfromolddocscomment,i curious following code codegoeshere i comment html file,1 django templates comments note these comments multiline,i curious following code codegoeshere i comment html file,2 i implemented following python waitforcondition since python selenium driver support function def waitforconditionc x range print waiting ajax c x browserexecutescriptreturn c ifx return timesleep used wait extjs ajax call pending waitforconditionextajaxisloading a javascript variable set waitforconditioncgdiscovery undefined etc,how i write function selenium wait table class identifier python i devil time learning use selenium python webdriver functions,1 the reason fails httpwwwwindowsphonecom attempts set cookie checked httpsloginlivecom creates another cookie redirects back windowsphonecom successful you look httpdocspythonorglibrarycookielibhtml if want use curl allow create cookiefile like curl devnull httpwwwwindowsphonecomenusappslistfree c mycookiejar run mycookiejar shell see something like netscape http cookie file httpwwwnetscapecomnewsrefstdcookiespechtml this file generated libcurl edit risk wwwwindowsphonecom true false wpmslss slss loginlivecom false false msprequ ltampcoampid run notice b option mycookiejar curl windowsphonehtml httpwwwwindowsphonecomenusappslistfree b mycookiejar get contents page file windowsphonehtml see browser,please try curl httpwwwwindowsphonecomenusappslistfree result htmlheadtitleobject movedtitleheadbody hobject moved hrefhttpsloginlivecomloginsrfwawsigninampamprpsnvampampcheckdaampampctampamprverampampwpmbiampampwreplyhttpffwwwwindowsphonecomfenusfappsflistdfreeampamplcampampidhereah bodyhtml def downloadsourceurl try socketsetdefaulttimeout agents mozilla compatible msie windows nt mozilla compatible msie b windows nt microsoft internet explorerb windows opera windows nt u en ree urllibrequestsourceurl reeaddheader useragent randomchoiceagents resp urlliburlopenree htmlsource respread return htmlsource except exception e print e return download httpwwwwindowsphonecomenusappslistfree result htmlheadmeta httpequivrefresh content urlhttpwwwwindowsphonecomenusappslistfreescript typetextjavascriptfunction onbackscriptheadhtml i want download actual source webpage,1 it worked changes usepythonyes usepydistutilsyes and usepython defines python versions working port if yes python version supported run make makesum create distinfo file port you also would need create packing list list files installed port for using helper script written freebsd developer amdmi link for run pt ampamp pt plist inside port dir,i trying create new freebsd port cogapp i use following makefile actually fetches targz expected use easy install install package new ports collection makefile cogapp whom karthick freebsd portsdevelpyvirtualenvmakefilev nivit exp portname cogapp portversion categories devel python mastersites httppypipythonorgpackagessourceccogapp maintainer xyzfreebsdorg comment cog port usepydistutils easyinstall include bsdportmk it rather throws following error vulnerability check disabled database found license check disabled port defined license extracting cogapp no checksum file tmpcogappdistinfo patching cogapp configuring cogapp building cogapp make cannot open makefile error code stop tmpcogapp can anyone suggest solution,1 ok try learned accept answers pat recompile print patfindalls remove quantifier use instead findall this result list,i parsing log python need quick fetch values simple equivalent regex usage example pat recompile it work expected last match group returned patmatchgroups what simplest solution problems updated wiki engine says use edit rather creating new post i need repeated matches course tomatch regex find need applyed twice recursively i bear options,1 everything mystuffpy placed mystuffinitpy instead,i growing number scripts make program i writing decided time clean source tree package correctly i sure simple question i find if i group modules fit together one toplevel module others prefixed module name actually go lower level packages i for example say i wanted able import mystuff get mystuff i also able import mystufftesttest i thought i would create source tree like myprogram mystuffpy mystuff initpy tests initpy testpy testpy but case seems mystuff always takes precedence mystuffpy import mystuff nothing long mystuff initpy empty what would correct approach get desired behaviour or possible must i move mystuffpy mystuff access mystuffmystuff seem like unnecessary repetion sorry i missed something obvious i assume must documented somewhere i seem find somewhere update while i believe ignacio method correct one i really like if i multiple files open editor called initpy things could get messy so i decided leave structure link mystuffpy mystuffinitpy if anyone opinions i i like hear actually end i linking way around since i find way make distutils dereference symlinks creating targz i ended broken links output this way effect keeps happy,2 i suggest using annotations creating multiple trees for ex import btrees zope import annotation followerskey myproductfollowers followskey myproductfollows friendskey myproductfriends portal selfcontextportalurlgetportalobject annotations annotationinterfacesiannotationsportal annotationsgetfollowerskey none annotationsfollowerskey btreesiibtreeiitreeset annotationsgetfollowskey none annotationsfollowskey btreesiibtreeiitreeset annotationsgetfriendskey none annotationsfriendskey btreesiibtreeiitreeset followers annotationgetfollowerskey follows annotationgetfollowskey friends annotationgetfriendskey,i making social networking site powered plone would like set relationships users friends followers etc how i achieve plone,2 i think create form multiplechoicefield class myformformsform toselect formsmultiplechoicefieldwidgetformscheckboxinput choices in case override forms save method did try create model form subgroup class class myformformsmodelform class meta modelsubgroup,i following models class groupmodelsmodel name modelscharfieldmaxlength uniquetrue class subgroupmodelsmodel name modelscharfieldmaxlength uniquetrue group modelsforeignkeygroup class keywordsmodelsmodel name modelscharfieldmaxlength uniquetrue subgroup modelsforeignkeysubgroup for subgroup i need manage list keywords i trying use django forms automatically display list select box i add remove values list issue formsave automatically updates models data how exactly i are models designed properly allow,1 the first one readable standards one file read operation per line it may memory efficient line reallocates one buffer vs loading whole file memory depending underlying the second one uglier io efficient all probably much difference unless ludicrous amount work,line open filetxt printresub windows linux line printresub windows linux open filetxt read which one better is differences btw is good idea manipulate huge string regex,1 as polynomial said second one reads whole file ram may may better but another solution open filetxt file line file printresub windows linux line this ensures file closed immediately needing longer similiarly open filetxt file printresub windows linux fileread used well,line open filetxt printresub windows linux line printresub windows linux open filetxt read which one better is differences btw is good idea manipulate huge string regex,1 yourmodule sysmodules don actually use though what library is “have dependency libcotdpy” i think you made design choice testdriven write test demonstrates want use library don think going implement for example player mylibplayercharacter assert playerposition whatever assert syntax pymock uses presskey k assert playerposition or something similar i know want library much libtcod provides,i make game using python libtcod roguelike game library more point i using pymock i starting learn testdriven development i determined cheat i really want get habit properly according tdd i need failing unit test i write first line code i figure first test production code dependency libcotdpy imported my testing file usrbinpython import pymock mocking unit testing import game empty production code file gamepy class initializetestpymockpymocktestcase def testlibtcodisimportedself how i test production file imports libtcodpy module namemain import unittest unittestmain please python people how i test module loaded tdd people should i unit testing something basic if first thing i testing,3 coming late party i recently implemented dedicated section config file list paths path somepath path anotherpath using configitems paths get iterable list path items like pathitems configitems paths key path pathitems something path hope helps folk googling question,the typical configparser generated file looks like section barfoo section bar baz now way index lists like instance section barlist item item related question python’s configparser unique keys per section thanks advance,3 flesk really answer one another straightforward way debug http connections netcat basically powerful telnet utility so let say want debug going http request nc wwwwindowsphonecom get enusappslistfree http host wwwwindowsphonecom useragent mozilla compatible msie windows nt that send request header server need press enter key twice send after server respond http found location httpsloginlivecomloginsrfwawsigninamprpsnvampcheckdaampctamprverampwpmbiampwreplyhttpffwwwwindowsphonecomfenusfappsflistdfreeamplcampid server microsoftiis setcookie wpmslssslss domainwwwwindowsphonecom path httponly xpoweredby aspnet xserver snconxwwba date tue nov gmt connection close contentlength htmlheadtitleobject movedtitleheadbody hobject moved hrefhttpsloginlivecomloginsrfwawsigninampamprpsnvampampcheckdaampampctampamprverampampwpmbiampampwreplyhttpffwwwwindowsphonecomfenusfappsflistdfreeampamplcampampidhereah bodyhtml so server returns http status code redirect thereby prompts browser open url passed locationheader netcat great tool debug trace kinds network communication helped lot i wanted dig little deeper http protocol,please try curl httpwwwwindowsphonecomenusappslistfree result htmlheadtitleobject movedtitleheadbody hobject moved hrefhttpsloginlivecomloginsrfwawsigninampamprpsnvampampcheckdaampampctampamprverampampwpmbiampampwreplyhttpffwwwwindowsphonecomfenusfappsflistdfreeampamplcampampidhereah bodyhtml def downloadsourceurl try socketsetdefaulttimeout agents mozilla compatible msie windows nt mozilla compatible msie b windows nt microsoft internet explorerb windows opera windows nt u en ree urllibrequestsourceurl reeaddheader useragent randomchoiceagents resp urlliburlopenree htmlsource respread return htmlsource except exception e print e return download httpwwwwindowsphonecomenusappslistfree result htmlheadmeta httpequivrefresh content urlhttpwwwwindowsphonecomenusappslistfreescript typetextjavascriptfunction onbackscriptheadhtml i want download actual source webpage,1 the tal specification says this url merely unique identifier do expect browser resolve successfully httpwikizopeorgzpttalspecification,where i find zope namespaces templates i setup pyramid project using sqlalchemy url dispatch chameleon templates these urls exist anymore httpxmlzopeorgnamespacestal httpxmlzopeorgnamespacesmetal thanks,1 you print list immediately returning as efficency algorithm consider sieve erathostenes,where i put print statement print final list still retain return ways think improve function i wrote function unsure relative quality def buildprimelist primelist possibleprime print to display prime values less equal number x rawinputenter number higher possibleprime x divisor isprime true divisor possibleprime isprime possibleprime divisor isprime false divisor divisor isprime primelistappendpossibleprime possibleprime possibleprime return primelist buildprimelist,1 try rule like pers per pers per,i trying parse grammar similar per noun noun noun pers per this valid grammar nltk recursive descent parser how specifiy one repeating tokens grammar,1 you might want take look httpsgithubcomstepankpyws expose python functions soap methods provides wsdl description i released version interoperability tested several clients seems quite friendly,i looking implement soap web service python top iis is recommended library would take given python class expose functions web methods it would great said library would also autogenerate wsdl file based interface,1 you quote argument contains spaces like commandline tools uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx,i problems writing gerrit httpcodegooglecompgerrit hooks httpgerritgooglecodecomsvndocumentationconfighookshtml if i parse command line patchsetcreated change changeurl project branch uploader commit patchset def main lensysargv showusage exit sysargv updateprojects updateprojects exit need action change changeurl commit project branch uploader patchset abandoner reason submitter comment crvw vrif patchset restorer author print sysargv print optlist args getoptgetoptsysargv need id url hash comment reason codereview verified restorer print optlist optlist change id elif changeurl url elif commit hash elif action elif uploader elif submitter elif abandoner elif author elif branch branch elif comment comment elif crvw codereview elif vrif verified elif patchset patchset elif restorer elif reason reason command line input change ifdddaaacaebeecca changeurl httphostname project privatebar branch master uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx commit aaebefafafedebffb patchset print sysargv action new change ifdddaaacaebeecca changeurl httphostname project privatebar branch master uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx commit aaebefafafedebffb patchset print optlist action new change ifdddaaacaebeecca changeurl httphostname project privatebar branch master uploader xxxxxxxxxxxx i know script generates uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx script dont parse commit patchset when i parse commentadded things works command line input change ifdddaaacaebeecca changeurl httphostnameintra project privatebar branch master author xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx commit aaebefafafedebffb comment asdf crvw vrif print sysargv action comment change ifdddaaacaebeecca changeurl httphostname project privatebar branch master author xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx that right commit aaebefafafedebffb comment asdf crvw vrif,1 as options names values spaceseparated put values quotes contain spaces if write uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx last two strings actually end args line optlist args getoptgetoptsysargv need associated uploader,i problems writing gerrit httpcodegooglecompgerrit hooks httpgerritgooglecodecomsvndocumentationconfighookshtml if i parse command line patchsetcreated change changeurl project branch uploader commit patchset def main lensysargv showusage exit sysargv updateprojects updateprojects exit need action change changeurl commit project branch uploader patchset abandoner reason submitter comment crvw vrif patchset restorer author print sysargv print optlist args getoptgetoptsysargv need id url hash comment reason codereview verified restorer print optlist optlist change id elif changeurl url elif commit hash elif action elif uploader elif submitter elif abandoner elif author elif branch branch elif comment comment elif crvw codereview elif vrif verified elif patchset patchset elif restorer elif reason reason command line input change ifdddaaacaebeecca changeurl httphostname project privatebar branch master uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx commit aaebefafafedebffb patchset print sysargv action new change ifdddaaacaebeecca changeurl httphostname project privatebar branch master uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx commit aaebefafafedebffb patchset print optlist action new change ifdddaaacaebeecca changeurl httphostname project privatebar branch master uploader xxxxxxxxxxxx i know script generates uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx uploader xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx script dont parse commit patchset when i parse commentadded things works command line input change ifdddaaacaebeecca changeurl httphostnameintra project privatebar branch master author xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx commit aaebefafafedebffb comment asdf crvw vrif print sysargv action comment change ifdddaaacaebeecca changeurl httphostname project privatebar branch master author xxxxxxxxxxxx xxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx that right commit aaebefafafedebffb comment asdf crvw vrif,1 why use galleryimagesetall related name images gallery model images,i models class gallerymodelsmodel headimage modelsimagefielduploadtogallery class imagemodelsmodel image modelsimagefielduploadtogallery gallery modelsforeignkeygallery relatedname images template gallery objectnow i wanna iterate image objects galleryimagesetall tdimg srcmedialurliimageurl widthpx heightpxtd endfor i check rendered htmli see generate thingwhat wrong tnx advance,2 it quite straightforward print result function print buildprimelist also i noticed convert rawinput result string int x intrawinputenter number higher another way thing python might look like itertools import count def isprimen checks given number n prime xrange n n return false else return true def primenumbers generator function lazily yields prime numbers one one count isprimei yield name main maxprime intrawinputenter number prime primenumbers prime maxprime print prime else break a number python idioms language features used generator functions iterators snakecasemethodnaming docstrings name main httpwwwibmcomdeveloperworkslibrarylpyconindexhtml pep style guide python code httpwwwlearningpythoncomintroducingdocstrings what namequotmainquot ps as jellybean rpint noted answers comments number ways speed things but likely unless absolutely simple better complex pep the zen python,where i put print statement print final list still retain return ways think improve function i wrote function unsure relative quality def buildprimelist primelist possibleprime print to display prime values less equal number x rawinputenter number higher possibleprime x divisor isprime true divisor possibleprime isprime possibleprime divisor isprime false divisor divisor isprime primelistappendpossibleprime possibleprime possibleprime return primelist buildprimelist,1 it sounds like data really looking accessed via secondary url called javascript primary page while could try running javascript server handle simpler approach might load page using firefox use tool like charles firebug identify exactly secondary url then query url directly data interested,i trying develop simple web scraper i want extract text without html code in fact i achieve goal i seen pages javascript loaded i obtain good results for example javascript code adds text i see i call response urlliburlopenrequest i get original text without added one javascript executed client so i looking ideas solve problem,3 xospopen mpinfo p s fread missing closing quote xospopen mpinfo p s fread you may also want use safer subprocess module import subprocess x subprocesscheckoutput mpinfo p s f,i using mpinfo calculate file length using following syntax mpinfo p s pathtofile whenever i use code filename i get correct output mpinfo p s farfromlovemp however storing filename string variable using variable i get error syntaxerror invalid syntax could anyone tell correctly use command variable filename python code uses mpinfo listingoslistdircpython f listing fnmatchfnmatchf mp extf extract name file without extension waveoutputfilenameswavext print waveoutputfilenamesave output filename wav extension print f xospopen mpinfo p s fread print x,1 you make simply varname selfdateeditdate this get variable qdate format if need format would easier work use tempvar selfdateeditdate varname tempvartopydate the first one gives pyqtqtcoreqdate while second returns,i built simple widget qt designer button qdateedit the user enter date qdateedit presses button date saved variable how i,3 the short answer yes correct understanding there catch way normally use nested list comprehension python code operate multidimensional arrays a typical example operate matrices matrix el el row row matrix as see nesting works operating dimension matrix in examples provided seems yset unfortunate name btw sets one types provided python generic counter makes bit harder follow going hood as first example rows minrowi row rowsmaxrowi row rows rangelenrows you might wish look zip builtin function ziprows rows maximum brevity elegance ziprows hth,i want understand nested list comprehension below i listed list comprehension expression loop equivalent i wonder understanding correct for example minrowi row rowsmaxrowi row rows rangelenrows equivalent result rangelenrows innerresult row rows innerresultappendrowi innerresult row rows innerresultappendrowi tuplemininnerresult maxinnerresult resultappendtuple if i may generalize i guess expexp x xset yset form translated following i hope i correct result yset innerresult x xset innerresultappendexp expresult expinnerresult resultappendexpresult for simpler case exp x xset yset equal result x xset yset resultappendexp whereas exp x xset yset equal result yset innerresult x xset innerresultappendexp resultappendinnerresult i asked similar question equivalent loop expression complex list comprehension the answers given reconstruct form understanding internally i like know works systematically i apply concept slightly varying examples,3 i use phonon pyqt code lines output phononaudiooutputphononmusiccategory mmedia phononmediaobject phononcreatepathmmedia output mmediasetcurrentsourcephononmediasourcefilessongmp mmediaplay but honestly i found phonon able play specific songs weird id tags i switched pyaudiere httpspypipythonorgpypipyaudiere much stable yes less integrated qt,i trying play single mp file software button pressed here qtcoreqobjectconnectselfpushbutton qtcoresignalfromutfclicked playsong function def playsong mmedia phononmediaobject mmediasetcurrentsourcephononmediasourcefilessongmp mmediaplay this doesnt raise error but song wont play i seen lot exemples c python lot songs playlist etc i want play single song missing something,2 yes code something like phoneme group vowel else consonants,i global dict code something like following group vowel aa ae ah ao eh er ey ih iy uh uw consonant b ch dh dx f g hh jh k l n ng p r sh th v w z zh it single key multiple values i need dict i make sure phoneme either vowel consonant proceed code later code i something like phoneme vowel else consonants thank,1 it effective use sets group dict want vowels set aa ae ah ao eh er ey ih iy uh uw consonants set b ch dh dx f g hh jh k l n ng p r sh th v w z zh phoneme vowels else consonants,i global dict code something like following group vowel aa ae ah ao eh er ey ih iy uh uw consonant b ch dh dx f g hh jh k l n ng p r sh th v w z zh it single key multiple values i need dict i make sure phoneme either vowel consonant proceed code later code i something like phoneme vowel else consonants thank,3 yes code use probably look something like phoneme groupvowel that said might want consider using set instead list give faster lookups ie group vowel set aa ae ah ao eh er ey ih iy uh uw consonant set b ch dh dx f g hh jh k l n ng p r sh th v w z zh,i global dict code something like following group vowel aa ae ah ao eh er ey ih iy uh uw consonant b ch dh dx f g hh jh k l n ng p r sh th v w z zh it single key multiple values i need dict i make sure phoneme either vowel consonant proceed code later code i something like phoneme vowel else consonants thank,2 you create reverse dictionary action value import operator op group vowel aa ae ah ao eh er ey ih iy uh uw consonant b ch dh dx f g hh jh k l n ng p r sh th v w z zh define methods functionvowel functionconsonant action vowel lambda x opmethodcallerfunctionvowel x consonant lambda x opmethodcallerfunctionconsonant x actionphoneme dictchar actionk kv groupiteritems phoneme v call directly actionphonemephoneme,i global dict code something like following group vowel aa ae ah ao eh er ey ih iy uh uw consonant b ch dh dx f g hh jh k l n ng p r sh th v w z zh it single key multiple values i need dict i make sure phoneme either vowel consonant proceed code later code i something like phoneme vowel else consonants thank,2 indeed correct this described detail expressions section python language reference note especially order nesting several single list comprehension always lefttoright matrix item item row row matrix oops traceback recent call last file pyshell line module item item row row matrix nameerror name row defined item row matrix item row nesting lefttoright order,i want understand nested list comprehension below i listed list comprehension expression loop equivalent i wonder understanding correct for example minrowi row rowsmaxrowi row rows rangelenrows equivalent result rangelenrows innerresult row rows innerresultappendrowi innerresult row rows innerresultappendrowi tuplemininnerresult maxinnerresult resultappendtuple if i may generalize i guess expexp x xset yset form translated following i hope i correct result yset innerresult x xset innerresultappendexp expresult expinnerresult resultappendexpresult for simpler case exp x xset yset equal result x xset yset resultappendexp whereas exp x xset yset equal result yset innerresult x xset innerresultappendexp resultappendinnerresult i asked similar question equivalent loop expression complex list comprehension the answers given reconstruct form understanding internally i like know works systematically i apply concept slightly varying examples,3 using imagemagick import subprocess import shlex args bgcolor transparent fgcolor light slate grey fgoutlinecolor red text example size geometry x output tmpoutpng font helvetica cmd convert xcbgcolorr resize geometry gravity center font font pointsize sizer fill fgcolorr stroke fgoutlinecolorr draw text textr trim outputr formatargs procsubprocesspopenshlexsplitcmd proccommunicate,how i draw text different stroke fill colors images python here text red stroke gray fill i tried pil option setting stroke color,2 pil support fake render text four eight times outline color using one pixel offsets xy xy x x four times version xy x xy xy xy xy x xy eight times version xy fill color,how i draw text different stroke fill colors images python here text red stroke gray fill i tried pil option setting stroke color,3 in csv format first header zerolength string space use selectedsignals you could also add fake column name nameindex dict example nameindex header nameindex use header selectedsignals alternatively could use default value dict find header want would use default value nameindexgetname instead nameindexname writeindices expression,i large csv file header names first one empty i want get chosen columns copy new outputcsv file my problem comes grabbing header name empty first element header so inputcsv looks something like headerheaderheaderheader header value value value value value value etc rows number elements even empty after reading various questions i recycled code write csv columns different order python write import csv operator import itemgetter selectedsignals header header fiinopen inputcsv rb open read r binary mode b fioutopen outputcsv wb open write w binary mode b reader csvreaderfiin delimiter writer csvwriterfiout delimiter allsignalnames readernext nameindex dictname index index name enumerateallsignalnames writeindices nameindexname name selectedsignals reorderfunc itemgetterwriteindices itemgetter imported operator module writerwriterowselectedsignals row reader writerwriterowreorderfuncrow gives desired output say headerheader value value problem selectedsignals header header grab first column returns keyerror i python beginner hints appreciated,1 using cairo much code taken import cairo def textextentfont fontsize text args kwargs surface cairoimagesurfacecairoformatargb ctx cairocontextsurface ctxselectfontfacefont args kwargs ctxsetfontsizefontsize return ctxtextextentstext text example fontsans fontsize fontargscairofontslantnormal xbearing ybearing textwidth textheight xadvance yadvance textextentfont fontsize text fontargs surface cairoimagesurfacecairoformatargb inttextwidth inttextheight ctx cairocontextsurface ctxselectfontfacefont fontargs ctxsetfontsizefontsize ctxmovetoxbearing ybearing ctxtextpathtext ctxsetsourcergb ctxfillpreserve ctxsetsourcergb ctxsetlinewidth ctxstroke surfacewritetopngtmpoutpng,how i draw text different stroke fill colors images python here text red stroke gray fill i tried pil option setting stroke color,3 iencode latin isinstancei unicode else row,i got array follows row u arun dc u yes u yes u yes u yes u yes u u xa xa clear u xa xa clear u xa xa clear u xa xa clear u water sites u st years rent free i want write csv file i get following error writerwriterowrow unicodeencodeerror ascii codec encode character u xa position ordinal range so i tried encoding first gives error i encode float items writerwriterowiencode latin row attributeerror int object attribute encode any thoughts neat way get around,1 aencode latin row returns list strings you could use write csv,i got array follows row u arun dc u yes u yes u yes u yes u yes u u xa xa clear u xa xa clear u xa xa clear u xa xa clear u water sites u st years rent free i want write csv file i get following error writerwriterowrow unicodeencodeerror ascii codec encode character u xa position ordinal range so i tried encoding first gives error i encode float items writerwriterowiencode latin row attributeerror int object attribute encode any thoughts neat way get around,1 xencode latin isinstancex unicode else x x row,i got array follows row u arun dc u yes u yes u yes u yes u yes u u xa xa clear u xa xa clear u xa xa clear u xa xa clear u water sites u st years rent free i want write csv file i get following error writerwriterowrow unicodeencodeerror ascii codec encode character u xa position ordinal range so i tried encoding first gives error i encode float items writerwriterowiencode latin row attributeerror int object attribute encode any thoughts neat way get around,3 looking closely seems various versions python path environment variable the standard python installer windows add path i always manually version python i want use default if using different python installer activestate enthought may cause i tried in case edit path environment variable manually clean leaving path version python wish default described scroll bit get relevant section,i versions python installed windows machine default one first path default open action now weird thing appear i run python script filenamepy without specifying interpreter clicking file explorer python running script expected but python path inserted original system path still i look command line seems python executed where first record path cptyhon comming i assure added scripts runs as already observed i several versions python path something anormal also versioned executables instead windows always picks first one path,1 i scraping blackberry website problem updates far are using absolute xpaths root document extract data you make robust scraper using relative xpaths dividpriceareadivclasscontentlic,i collecting stats mobile applications using python i looking best solution access blackberry app world data so far i got solution ios httpwwwapplecomitunesaffiliatesresourcesdocumentationitunesstorewebservicesearchapihtml android httpsgithubcomliatoandroidmarketapipy the ios solution uses api provided apple android solution simulates phone gathers data way real phone structured way now i seem find similar solution blackberry app world question best way go i scrape site i rather since scraper break change site ideally i use either provided api simulate blackberry access app world data structured way any suggestions,1 this possible sorry the rolled array cannot described different set strides would necessary numpy view work,is way perform roll array instead copy data different visualisation an example might clarify given b rolled version nprandomrandint array b nprolla axis b array i perform assignment array b b b array content change array contrarily i would like array observe changed thanks advance time expertise,3 precedingsiblingcomment followingsiblingcomment or stricter version precedingsiblingcomment comment followingsiblingcomment comment,this html file div divdiv divdiv comment divdiv divdiv divdiv comment divdiv divdiv divdiv div i want select divs comment comment with xpath divcomment i select commentcomment but i want select divdiv divdiv divdiv,3 options access url within iframe directly form login login site browser use extension like firebug track posted data then replicate request login automatically,i want enter text login password inside page frames the structure something like html xmlnshttpwwwworgxhtml headwhateverhead body idbody form idfrmm onsubmitjavascriptreturn whatever actionloginaspx methodpost div idalldata div idheader iframe idloginssl scrollingno frameborder srchttpswwwwhatevercomuserloginframeaspxrediruserloginaspx html xmlnshttpwwwworgxhtml body onloadrefreshparent form idform actionloginframeaspxredirfuserfloginaspx methodpost div idloginrow classloginmenurow onkeypressjavascriptreturn webformfiredefaultbuttonevent cmdlogin input idcmdlogin typesubmit tabindex onclickaspnetformtarget top valuelogin namecmdlogin input idpassword classtextbox typepassword tabindex namepassword span idlblpassword classloginmenupasswordspan div form body html iframe div div form body html if i try find form i see top level one available brselectformform formnotfounderror form matching name form fattrs id f brforms frmm how i go logging site,2 httpploneorgdocumentationmanualplonecommunitydeveloperdocumentationcontentrename need the important part parentmanagerenameobjectid id old loop subobjects contextobjectids obj contexti contextmanagerenameobjecti pdf context folder put script folder pdfs,on plone site i hundreds files pdf doc filefield archetypes objects something went wrong importation filenames missing the problem somebody wants open file since extension missing browser always propose open viewer the user save file add extension open can i write python script rename files extension depending filetype thank,2 you might interested python launcher windows project aka pep install remove python dirs path leaving launcher one use py pyw instead python pythonw,i versions python installed windows machine default one first path default open action now weird thing appear i run python script filenamepy without specifying interpreter clicking file explorer python running script expected but python path inserted original system path still i look command line seems python executed where first record path cptyhon comming i assure added scripts runs as already observed i several versions python path something anormal also versioned executables instead windows always picks first one path,1 the way i usually think tdd bdd two levels development acceptancetesting level unittesting level first thing i would write stories acceptance criteria what core feature application define endtoend scenario explicit one feature goes endtoend that first story write test using acceptance testing integration testing framework unfortunately i know python tools java i would use jbehave fitnesse it would something highlevel far away code considers application black box something like when input parameters xxx i run application expected output yyyy run test fail underlying application exist create minimal amount classes make go red throw exception anymore that need start second phase tdd unittdd it basically descending analysis toplevel details phase contain lot redgreenrefactor cycles bringing lot different units game from time time rerun original acceptance test refine growing architecture analysis forced make changes specifications theoretically happen stage practice often when acceptance test completely green done story rinse repeat all brings point pure tdd i mean unittdd practical i mean i really like tdd trying follow religiously hassle help long run sometimes go spike approach see goes well rest project without writing tests first potentially rewrite using tdd long acceptance tests cover whole lot fine,i make game using python libtcod roguelike game library more point i using pymock i starting learn testdriven development i determined cheat i really want get habit properly according tdd i need failing unit test i write first line code i figure first test production code dependency libcotdpy imported my testing file usrbinpython import pymock mocking unit testing import game empty production code file gamepy class initializetestpymockpymocktestcase def testlibtcodisimportedself how i test production file imports libtcodpy module namemain import unittest unittestmain please python people how i test module loaded tdd people should i unit testing something basic if first thing i testing,2 you hand sqlite xmlstarlet convert xml csv import csv db maybe want handy content xml file cat artistxml resultsartistidaedbccidname莎拉 布莱曼sarah brightmannamehotsongsfreemusicsongresultsafbdfsongidsafbdfidnamegloomy sundaynameartist莎拉 布莱曼sarah brightmanartistartistidaedbccartistidalbumæœˆå ‰å¥³ç¥žalbumdurationdurationcanbedownloadedtruecanbedownloadedhasfulllyricstruehasfulllyricscanbestreamedtruecanbestreamedalbumidbfefdaalbumidhassimilarsongstruehassimilarsongshasrecommendationfalsehasrecommendationsongfreemusicsongresultsbbfaabsongidsbbfaabidnameæˆ‘å’Œä½ å¹´å¥¥è¿ä¼šä¸»é¢˜æ›²you and menameartist刘欢artistartist莎拉 布莱曼sarah brightmanartistartistidadbdbdfcartistidartistidaedbccartistidalbumæˆ‘å’Œä½ åŒ—äº¬å¥¥è¿ä¼šä¸»é¢˜æ­Œalbumdurationdurationcanbedownloadedtruecanbedownloadedhasfulllyricstruehasfulllyricscanbestreamedtruecanbestreamedalbumidbabfabbefeedalbumidhassimilarsongstruehassimilarsongshasrecommendationfalsehasrecommendationsongfreemusicsongresultsabefffsongidsabefffidnamescarborough fairnameartist莎拉 布莱曼sarah brightmanartistartistidaedbccartistidalbumæœˆå ‰å¥³ç¥žalbumdurationdurationcanbedownloadedtruecanbedownloadedhasfulllyricstruehasfulllyricscanbestreamedtruecanbestreamedalbumidbfefdaalbumidhassimilarsongstruehassimilarsongshasrecommendationfalsehasrecommendationsongfreemusicsongresultsdeaadaddfesongidsdeaadaddfeidnametime to say goodbyenameartist莎拉 布莱曼sarah brightmanartistartistidaedbccartistidalbumsymphony live in viennaalbumdurationdurationcanbedownloadedtruecanbedownloadedhasfulllyricstruehasfulllyricscanbestreamedtruecanbestreamedalbumidbabfalbumidhassimilarsongstruehassimilarsongshasrecommendationfalsehasrecommendationsongfreemusicsongresultscccebbbsongidscccebbbidnameamazing gracenameartist莎拉 布莱曼sarah brightmanartistartistidaedbccartistidalbum真爱永恒 冬之歌albumdurationdurationcanbedownloadedtruecanbedownloadedhasfulllyricstruehasfulllyricscanbestreamedtruecanbestreamedalbumidbeaccalbumidhassimilarsongstruehassimilarsongshasrecommendationfalsehasrecommendationsongfreemusicsongresultsdcedesongidsdcedeidnamethis lovenameartist莎拉 布莱曼sarah brightmanartistartistidaedbccartistidalbumæœˆå ‰å¥³ç¥žalbumdurationdurationcanbedownloadedtruecanbedownloadedhasfulllyricstruehasfulllyricscanbestreamedtruecanbestreamedalbumidbfefdaalbumidhassimilarsongstruehassimilarsongshasrecommendationfalsehasrecommendationsongfreemusicsongresultscfbbesongidscfbbeidnamehere with menameartist莎拉 布莱曼sarah brightmanartistartistidaedbccartistidalbumæœˆå ‰å¥³ç¥žalbumdurationdurationcanbedownloadedtruecanbedownloadedhasfulllyricstruehasfulllyricscanbestreamedtruecanbestreamedalbumidbfefdaalbumidhassimilarsongstruehassimilarsongshasrecommendationfalsehasrecommendationsongfreemusicsongresultsbafcbcsongidsbafcbcidnamela lunenameartist莎拉 布莱曼sarah brightmanartistartistidaedbccartistidalbumæœˆå ‰å¥³ç¥žalbumdurationdurationcanbedownloadedtruecanbedownloadedhasfulllyricsfalsehasfulllyricscanbestreamedtruecanbestreamedalbumidbfefdaalbumidhassimilarsongstruehassimilarsongshasrecommendationfalsehasrecommendationsonghotsongsartistresults convert xml csv file using xmlstarlet xml sel song v concatid name duration n artistxml sed artistcsv content csv file cat artistcsv safbdfgloomy sunday sbbfaabæˆ‘å’Œä½ å¹´å¥¥è¿ä¼šä¸»é¢˜æ›²you and me sabefffscarborough fair sdeaadaddfetime to say goodbye scccebbbamazing grace sdcedethis love scfbbehere with me sbafcbcla lune create sqlite database sqlite songdb sqlite create table songid name duration enter csv mode import csv file sqlite mode csv sqlite import artistcsv song check everything ok sqlite mode column sqlite header sqlite select song id name duration safbdf gloomy sunday sbbfaab æˆ‘å’Œä½ sabefff scarborough f sdeaadaddfe time to say g scccebbb amazing grace sdcede this love scfbbe here with me sbafcbc la lune,i question related guidances solve problem i xml file i populate database system whatever might sqlite mysql using scripting language python does anyone idea proceed which technologies i need read which environments i install any tutorials topic i already tried parse xml using treebased sax method language start python i know start i already know design database i need another question python alone possible executing database ddl queries,3 the query must data ready inserted you calling function query guess want provides data wont work you need pass data variables locate tuple index like tuplename tuplename etc example mytuple b c e f g curexecutemanyinsert into rehberimnames phone mobile email photo address note date values format mytuple mytuple mytuple mytuple mytuple mytuple mytuple,i tuple wanna store elements i trying insert following gives following error wrong recordstobeinserted tuple elements selfconnection cur selfconnectioncursor curexecutemanyinsert into rehberimnames phone mobile email photo address note date values selfrecordstobeinserted traceback recent call last file hometayfunworkspacepersonalguidemodulesmainwindowpy line saverecords photo address note date values selfrecordstobeinserted sqliteprogrammingerror incorrect number bindings supplied the current statement uses supplied,1 in xpath one use general kayessian method intersection two nodesets ns ns nscountns countns when replace ns ns specific selecting expressions particular case get commentfollowingsiblingdiv count commentprecedingsiblingdiv countcommentprecedingsiblingdiv xsltbased verification xslstylesheet version xmlnsxslhttpwwwworgxsltransform xsloutput omitxmldeclarationyes indentyes xsltemplate match xslcopyof select commentfollowingsiblingdiv count commentprecedingsiblingdiv countcommentprecedingsiblingdiv xsltemplate xslstylesheet transformation applied provided xml document div divdiv divdiv comment divdiv divdiv divdiv comment divdiv divdiv divdiv div the exact wanted nodes selected output divdiv divdiv divdiv in xpath one uses intersect operator commentfollowingsiblingdiv intersect commentprecedingsiblingdiv,this html file div divdiv divdiv comment divdiv divdiv divdiv comment divdiv divdiv divdiv div i want select divs comment comment with xpath divcomment i select commentcomment but i want select divdiv divdiv divdiv,1 the standard library function osrenamesrc dst trick that need know extension eg files pdf if mixed bag doc pdf jpg xls files extensions need examine file contents determine proper extension using something like pythonmagic import os fn oslistdirpath osrenamefn fn pdf,on plone site i hundreds files pdf doc filefield archetypes objects something went wrong importation filenames missing the problem somebody wants open file since extension missing browser always propose open viewer the user save file add extension open can i write python script rename files extension depending filetype thank,1 as panoply statements usual approach file handles mapping extensions mime types look list all mimetypes planet mapped file extensions read appropriate data structure you probably opening files binary unless text mime type ensure line endings specified appropriate rfc years since i needed consult standards account writing web server deployment anger and syntactical point foo foo foo foo your brackets redundant you index value extracting,i going correct way ive never done anything like im sure i the code far gets html css files works fine images wont load i create new every different file type i silly wayhere i import stringcgitime os import curdir sep basehttpserver import basehttprequesthandler httpserver import os import mimetypes import pri port host class myhandlerbasehttprequesthandler def dogetself try requestedurl selfpath mimetype mimetypesguesstypeselfpath filetype mimetypesguessextensionmimetype infolist mimetype filetype infolist py selfsendresponse selfsendheader contenttype mimetype selfendheaders f opencurdir sep selfpath rb selfwfilewritefread fclose return filetype py pythonfilename selfpathlstrip selfsendresponse selfsendheader contenttype texthtml selfendheaders pyname pythonfilenamereplace print pythonfilename print pyname temp pynamesplit temp temp print temp module importrootindex selfwfilewritemodulerootindexdowork module importtestindex selfwfilewrite moduleindexdowork return return except ioerror selfsenderror file not found selfpath def dopostself global rootnode try ctype pdict cgiparseheaderselfheadersgetheader contenttype ctype multipartformdata querycgiparsemultipartselfrfile pdict selfsendresponse selfendheaders upfilecontent queryget upfile print filecontent upfilecontent selfwfilewritehtmlpost okbrbr selfwfilewriteupfilecontent except pass def main try server httpserverhost port myhandler print started httpserver print host host print port strport serverserveforever except keyboardinterrupt print c received shutting server serversocketclose name main main html css works png images load,1 what appid there currently issue sending mail application whose appid owner gmail name fail eg i gmail address moishel gmail dot com i created app whose appid moishel version fail trying send mail note problem exist apps created version here issue httpcodegooglecompgoogleappengineissuesdetailid,years back i built simple mail form working like champ last couple months logs show i getting error emailmessage send method gets called i wrote quick test see stripped version emailmessage would work without error class testemailwebapprequesthandler def getself fromaddress appowneremailgmailcom email mailemailmessagesenderfromaddress emailto selfrequestget gmailcom emailsubject test email emailbody testing email system emailhtml strongtesting ememailem systemstrong emailcheckinitialized emailsend simple enough i call httpmyappnameappspotcomtestemailtototallylegitemail i still get error note checkinitialized throwing error traceback recent call last file basepythonruntimepythonlibversionsgoogleappengineextwebappwebapppy line call handlergetgroups file basedatahomeappssmyappnamemyappnamepy line get emailsend file basepythonruntimepythonlibversionsgoogleappengineapimailpy line send raise e applicationerror applicationerror internal error i made recent changes app lightly used app well quota sending email associated app owner spending hours scrutinizing code i still closer answer even distressing every google search i come offers new help the best i could find question google app engine send mail service raises exception sounds exactly like problem case solution problem went away any idea i track one let know i need clarify anything thanks,1 at end i use yann code def theoryyatdataxtheoryxtheoryydatax for every datax point find interpolated theoryy value theoryx needed interpolation f interpolateinterpdtheoryxtheoryy return fdataxnpwheredataxnpmaxtheoryx def findoutliersetdatainterptheoryytheoryerr find theoryytheoryerr datay theoryytheoryerr return valid indicies npwheredatadmodulus interptheoryytheoryerr low npwheredatadmodulus interptheoryytheoryerr join index together flat array nphstackuplowravel index nparraynponeslendatadtypebool indexoutfalse datain dataindex dataout dataout return datain dataout def selectdatadatatheoryxtheoryy data selection z lflrw separation select data redshift z data datadataredshift from modulus light distance datadmodulus datadmoduluserror modulusdistancedatadmodulusdatadmoduluserror redshift data order datasortorder redshift outliers distance lflrw curve bigger theoryerr theory curve interpolation get points data interpy theoryyatdataxtheoryxtheoryydataredshift datain dataout findoutliersetdatainterpytheoryerr return datain dataout using functions i finally obtain thank help,i need compare theoretical data real data python the theoretical data comes resolving equation to improve comparative i would like remove data points fall far theoretical curve i mean i want remove points red dashed lines figure made matplotlib both theoretical curves data points arrays different length i try remove points roughlyeye way example first upper point detected using datadataredshiftampdatadmodulus recarray dtype snname s redshift f dmodulus f dmoduluserror f but i would like use less roughlyeye way so anyone help finding easy way removing problematic points thank,2 i tried pythondocx succes enables make edit docx within python,i like create word document using python however i want reuse much existing documentcreation code possible i currently using xslt generate html file i programatically convert pdf file however client requesting document made available word doc format so far i much luck finding solutions problem is anyone aware open source library gulp proprietary solution may help resolve issue note all possible solutions must run linux i believe eliminates pywin,3 if package project name myapp app project import package files myappmodels import apples oranges p applesobjectsgetid this error myapp import models myapp import apples oranges importerror apples oranges inside modelspy perhaps also need read modules packages hope helps,i trying follow django tutorial create two tables unique key table might appear several times table different unique key create table apples id integer not null primary key value varchar not null create table oranges id integer not null primary key id integer not null references myappapples id value datetime not null trying run import package package import myapp packagemyapp import models packagemyapp import apples oranges p applesobjectsgetid porangessetcreatevalue i get error stack i post end need tell please file usrlibpymodulespythondjangoutilstranslationtransrealpy line fetch app importmoduleappname file usrlibpymodulespythondjangoutilsimportlibpy line importmodule importname importerror no module named myapp i assume problem imports i solve,2 i wrote article menus years ago httpwwwblogpythonlibraryorgwxpythonworkingwithmenustoolbarsandaccelerators it talks disabling menus there also example wxpython demo package i think bind menu events frame object though binding text control probably work i think focus event probably better place enabledisable bit though to unbind event use unbind method see httpzetcodecomwxpythonevents httpwwwwxpythonorgdocsapiwxevthandlerclasshtml info,i using python wxpython arch linux x i like make following example work way left textctrl texta focus pressing shifta execute doa pressing shiftb write b text area also menufoobarb disabled menufoobara enabled right textctrl textb focus pressing shifta write a text area pressing shiftb execute dob also menufoobara disabled menufoobarb enabled import wx class foowxframe def initself wxframeinitself none size selfinitmenu selfinittext selfcentre selfshowtrue def initmenuself selfmenu wxmenubar selfsetmenubarselfmenu selfmenufoo wxmenu selfmenuappendselfmenufoo ampfoo selfmenufoobara selfmenufooappendwxidany barampatshifta selfmenufoobarb selfmenufooappendwxidany barampbtshiftb selfbindwxevtmenu selfhandlea selfmenufoobara selfbindwxevtmenu selfhandleb selfmenufoobarb def inittextself selfbox wxboxsizerwxhorizontal selfsetsizerselfbox selftexta wxtextctrlself stylewxtemultiline selftextb wxtextctrlself stylewxtemultiline selfboxaddselftexta flagwxexpand selfboxaddselftextb flagwxexpand def handleaself event print a def handlebself event print b app wxapp foo appmainloop binding menu event something like selftextabindwxevtmenu selfhandlea selfmenufoobara work should i make use wxevtkillfocus wxevtsetfocus bindunbind menu items setreset shortcut keys enabledisable menu entries it sounds complicated larger applications general i like know proper frequent clean tidy way wxpython applications limit scope menu shortcut keys dynamically enabledisable menu items thank,1 not related tcp answered already appending string repeatedly rather inefficient expecting receive lot it might better append list turn list string finished receiving using joinlist,i trying write secure transfer file program using python aes got problem totally understand i send file parsing bytes chunks sending server side receive data crashes i use aes cbc therefore data length must multiple bytes error get says i tried print length data sent client client side length data received server shows client sending exactly bytes time like supposed server side shows point time received packet less bytes example bytes i tried put timesleep socket send client side seems work is possible kind socket buffer failure server side that much data send fast client breaks somehow socket buffer server side data corrupted vanish recv receive broken chunk that thing could think may also completely false anyone idea working properly would great following idea tried selfssetsockoptsocketsolsocket socketsorcvbuf print socketsorcvbuf i tried put mbytes buffer server side on windows xp shows print linux shows i know must interpret thing know seems mbytes buffer code work well really long post hope courage read totally lost anyone idea please share d thanks faisal code server side count filesize txtselfsrecv txt break txt selfcipherdecrypttxt countbis count txt txtrstrip tfilewritetxt countbis client side txt tfileread txt selfssend break txt lentxt txt selfcipherencrypttxt selfssendtxt thanks advance nolhian,1 nothing private python if using double underscore prefix member variables name simply mangled you access qualifying name form classmember this access member variable class class see also question why pythons private methods actually private,i trying improve i write unit test cases python programs i noticing cases would really helpful access private members ensure method functioning properly an example case would trying test method proper behavior expected return value none i know easy wrong way would make private attributes protected attributes instead test directly however i would like find way expose interface much so i test private attributes within classes without exposing interface applicable better way testing scenario private attribute access would necessarily needed proper unit testing,3 take look numpyconvolve the exponential moving sum convolution,i looking function calculate exponential moving sum numpy scipy i want avoid using python loops really slow specific i two series a t ti timestamp value ai i define halfdecay period tau for given time exponential moving sum sum values ai happens weight expttitau ai thanks lot,3 update figured method line requirements you structure pseudomodule qt qtinitpy qtqtcoreinitpy qtqtguiinitpy where qtinitpy import qtcore qtgui qtqtcoreinitpy pyqtqtcore import qtqtguiinitpy pyqtqtgui import then code reference follows import sys qt import qtgui app qtguiqapplicationsysargv qtqtgui import window qwidget windowshow appexec i highly recommend using qtqtgui import code importing everything considered bad form python since lose namespaces process update i like ryan suggestion conditional imports i recommend combining code for example qtqtguiinitpy import sys pyqt sysargv pyqtqtgui import else pysideqtgui import,i would like something like one source file qtpy import sys import pyqt sysmodulesqt pyqt then import file source files use like import qt qtqtcore import so i change pyqt pyside qtpy without touching source files possibly ugly sed script these modules mostly api compatibile i would like test is easy way because ways i tried working maybe i need imp module seems low level,1 you right track though ifs redundant i suggest refactor code check type using loop dict mime htmltexthtml csstextcss pngimagepng requestedfiletype mimekeys selfsendresponse selfsendheader contenttype mimerequestedfiletype selfendheaders print requestedfiletype f opencurdir sep selfpath selfwfilewritefread fclose return also sending binary files text instead opencurdir sep selfpath use opencurdir sep selfpath b gergely toptalcom,i going correct way ive never done anything like im sure i the code far gets html css files works fine images wont load i create new every different file type i silly wayhere i import stringcgitime os import curdir sep basehttpserver import basehttprequesthandler httpserver import os import mimetypes import pri port host class myhandlerbasehttprequesthandler def dogetself try requestedurl selfpath mimetype mimetypesguesstypeselfpath filetype mimetypesguessextensionmimetype infolist mimetype filetype infolist py selfsendresponse selfsendheader contenttype mimetype selfendheaders f opencurdir sep selfpath rb selfwfilewritefread fclose return filetype py pythonfilename selfpathlstrip selfsendresponse selfsendheader contenttype texthtml selfendheaders pyname pythonfilenamereplace print pythonfilename print pyname temp pynamesplit temp temp print temp module importrootindex selfwfilewritemodulerootindexdowork module importtestindex selfwfilewrite moduleindexdowork return return except ioerror selfsenderror file not found selfpath def dopostself global rootnode try ctype pdict cgiparseheaderselfheadersgetheader contenttype ctype multipartformdata querycgiparsemultipartselfrfile pdict selfsendresponse selfendheaders upfilecontent queryget upfile print filecontent upfilecontent selfwfilewritehtmlpost okbrbr selfwfilewriteupfilecontent except pass def main try server httpserverhost port myhandler print started httpserver print host host print port strport serverserveforever except keyboardinterrupt print c received shutting server serversocketclose name main main html css works png images load,2 exactly question use subprocess execute shell commands case simplistic pseudo code might look like import subprocess myprocess subprocesspopen shell stdoutsubprocesspipe stderrsubprocesspipe outstream errstream myprocesscommunicate whatever like standard outstream different things errstream exists standard error includes writing standard standard error file presume would diff files actual code example assuming python linux system might look like import subprocess open datehelplog w datelog open datehelperr w errlog datehelp subprocesspopen date h stdoutdatelog stderrerrlog datehelpcommunicate,let say i different versions app installed different virtualenvironments myapp v myapp v now i would like compare the comparison written python what would best way let assume i run separately write output file i compare later one way would write bash script i currently i activate one virtualenv run myapp v activate another virtualenv run myapp v later run comparison module files but i would like add dynamics take optional arguments etc would easier python edit currently i something like bash script source virtualenvbinactivate python myscriptpy deactivate source virtualenvbinactivate python myotherscriptpy deactivate python mycomparisonscriptpy instead i like python mycomparisonscriptpy scripts would run inside,1 the combinator curried form apply compared deprecated builtin function apply f reverses order arguments useful providing looks like dual functoolspartial function,this function f accepts argument list returns another callable argument list functions applied operator import add mul def fa kw return lambda g ga kw mapf add mul what call f is combinator kind,2 this mostly due variable lookup looking variable global scope requires dictionary lookup in contrast compiler determines local names statically references index dictionary look required note python x presence exec statement inside function deactivate optimisation since names determined statically in python x exec regular function allowed change variables local scope,in alex martelli response making python script objectoriented mentions putting module level code function calling function faster python can someone explain whether true implementations python,3 use findall method item treefindall httpwwwworgatomentry print item,i xml document following format feed xmlnshttpwwwworgatom xmlnsopensearchhttpacomspecopensearchrss xmlnsgsahttpschemasgooglecomgsa entry idhttpsipaddressfeedsdiagnosticssmbipaddresspathtofileid updatedtzupdated appedited xmlnsapphttppurlorgatomapptzappedited link relself typeapplicationatomxml hrefhttpsipaddressfeedsdiagnostics link reledit typeapplicationatomxml hrefhttpsipaddressfeedsdiagnostics gsacontent nameentryidsmbipaddresspathtodirectorygsacontent gsacontent namenumcrawledurlsgsacontent gsacontent namenumexcludedurlsgsacontent gsacontent nametypedirectorycontentdatagsacontent gsacontent namenumretrievalerrorsgsacontent entry entry entry feed i need retrieve entry elements using xpath lxml my problem i figure use empty namespace i tried following examples none work please advise import lxmletree et treeetfromstringxml the various things i tried node treexpath entry namespaces nonehttpwwwworgatom opensearchhttpacomspecopensearchrss gsahttpschemasgooglecomgsa node treexpath entry namespacesns node treexpath httpwwwworgatomentry at point i know try any help greatly appreciated,1 open sampletxt f true item rawinput please enter name item item break fwriteitem n key points write item file string item close file outside loop provide sentinel object break loop cleanly case hit enter without typing anything,true item strrawinput please enter name item f open sampletxt fwriteitem n fclose my goal get keep adding items text document sampletxt however time i run program old data appended written how fix to clarify i want running list text document item entered thanks,2 take look ipython used here section docs might particular interest httpipythonorgipythondocdevinteractivereferencehtmlsessionloggingandrestoring,i like realtime access interpreter input error standard output preferably information would written file i poll file changes every interpreter command entered for example given interpreter session printhello world hello world hello world hello world i like see following log file printhello world hello world hello world hello world the formatting important important i search file key words trigger interactive events session what i learned far trying accomplish python code module allows create interactiveconsole object rawinput method i redefine log file like import code class loggedconsolecodeinteractiveconsole def initself locals superloggedconsole selfinitlocals selffile open consolelogdat def delself selffileclose def rawinputself prompt data inputprompt selffilewritedata n return data furthermore interactiveconsole uses builtin write method log errors i redefine def writeself data sysstderrwritedata selffilewritedata n i also learned following snippet log stdout class teeobject def initself selffile open consolelogdat selfstdout sysstdout def delself sysstdout selfstdout selffileclose def writeself data selffilewritedata selfstdoutwritedata sysstdout tee my broken attempt bring together create loggedconsole object pass tee locals console loggedconsolelocalssysstdoutloggedexec consoleinteract i passed locals perhaps i incorrectly i receive error anyways open new interactive console log closing input errors output i banging head i feel like i close maybe even also way occur session currently logging takes place session closed thanks time sorry wall text edit i like able accomplish standard python interpreter portability purposes edit jaime snippet works well logging everything i need any way though i real time instead waiting session close edit figured the final working snippet import code import sys class teeobject def initself logfname mode selflog openlogfname mode def delself restore sin se sysstdout sysstdout sysstdir sysstdin sysstderr sysstderr selflogclose def writeself data selflogwritedata selflogflush sysstdoutwritedata sysstdoutflush def readlineself sysstdinreadline sysstdinflush selflogwrites selflogflush return def flushfoo return sysstdout sysstderr sysstdin tee consolelogdat w console codeinteractiveconsole consoleinteract,3 see virtualenv article doug hellmann showing log ipython session if comfortable working interactive prompt way want record future reference close session use ipython’s logging feature write session file to activate log use control command logstart illustrated listing the output file python source file easy clean turn “real” module done experimenting in logstart activating autologging current session state plus future input saved filename ipythonlogpy mode rotate output logging false raw input log false timestamping false state active in in b in c b in c out in b c in out in logstop,i like realtime access interpreter input error standard output preferably information would written file i poll file changes every interpreter command entered for example given interpreter session printhello world hello world hello world hello world i like see following log file printhello world hello world hello world hello world the formatting important important i search file key words trigger interactive events session what i learned far trying accomplish python code module allows create interactiveconsole object rawinput method i redefine log file like import code class loggedconsolecodeinteractiveconsole def initself locals superloggedconsole selfinitlocals selffile open consolelogdat def delself selffileclose def rawinputself prompt data inputprompt selffilewritedata n return data furthermore interactiveconsole uses builtin write method log errors i redefine def writeself data sysstderrwritedata selffilewritedata n i also learned following snippet log stdout class teeobject def initself selffile open consolelogdat selfstdout sysstdout def delself sysstdout selfstdout selffileclose def writeself data selffilewritedata selfstdoutwritedata sysstdout tee my broken attempt bring together create loggedconsole object pass tee locals console loggedconsolelocalssysstdoutloggedexec consoleinteract i passed locals perhaps i incorrectly i receive error anyways open new interactive console log closing input errors output i banging head i feel like i close maybe even also way occur session currently logging takes place session closed thanks time sorry wall text edit i like able accomplish standard python interpreter portability purposes edit jaime snippet works well logging everything i need any way though i real time instead waiting session close edit figured the final working snippet import code import sys class teeobject def initself logfname mode selflog openlogfname mode def delself restore sin se sysstdout sysstdout sysstdir sysstdin sysstderr sysstderr selflogclose def writeself data selflogwritedata selflogflush sysstdoutwritedata sysstdoutflush def readlineself sysstdinreadline sysstdinflush selflogwrites selflogflush return def flushfoo return sysstdout sysstderr sysstdin tee consolelogdat w console codeinteractiveconsole consoleinteract,2 i promoting comment answer if install using scripts keyword get correct mode get installed appropriate bin directory how would execute something files contained inside package install this question would appear address situation looks like reasonable answer,let assume i package calls executable file somewhere code example thirdparty cjavaprogram let assume application smalltrivial enough bundle package for example single executable file cfoo i could go ahead put files following structure foo initpy initpyc corepy corebin cfoo foomainpy setuppy and prepare setuppy follows setuptools import setup setup name foo version packages foo scripts foofoomainpy packagedata foo corebin zipsafefalse this allow properly install package later packagecode i could subprocess import call import pkgresources res def main fn resresourcefilename foo corebincfoo print resource located fn callfn unfortunately executable file installed without executable flag set even original file set adding chmod call end setuppy script easy one would need figure proper installation path first i tried resourcefilename returned local file preinstallation how problem solved also virtualenv mind,1 in short r amp complicated form writing r it matches characters ord ord ord ie following amp the escaping backslash ignored character classes unnecessary matching characters character class make sense since ampersand amp already character class superfluous well,is characters ord ord amp set i think interpretation incorrect based test but python reference say anything wrong interpretation httpdocspythonorglibraryrehtml,2 it probably bad idea log exception thrown within program since python uses exceptions also normal control flow therefore log uncaught exceptions you easily using logger exception method exception object to handle uncaught exceptions either wrap script entry point tryexcept block installing custom exception handler reassigning sysexcepthook import logging import sys logger logginggetlogger mylogger configure logger write file def myhandlertype value tb loggerexceptionuncaught exception formatstrvalue install exception handler sysexcepthook myhandler run main script name main main,i want check errors particular background file standard error stream controlled program foreground errors file question displayed i use logging module write output file though i wondering i use log exceptions errors tracebacks,3 see docs manytomany fields you need create meeting person objects separately first meetingpartcipatesaddperson btw think word looking participants,using djangorestframework models one meeting could many participates so tried use manytomanyfield django class meetingmodelsmodel namemodelscharfieldmaxlength participatesmodelsmanytomanyfieldperson python managerpy sqlall xxx db tables create table oameetingparticipates id integer not null primary key meetingid integer not null personid integer not null references oaperson id unique meetingid personid create table oameeting id integer not null primary key name varchar not null problems comes create meeting selecting persons server response participates invalid keyword argument function since oameeting participates field solve,2 i tested python i handy import code import sys class teeobject def initself logfname mode selflog openlogfname mode def delself restore sin se sysstdout sysstdout sysstdir sysstdin sysstderr sysstderr selflogclose def writeself data selflogwritedata sysstdoutwritedata def readlineself sysstdinreadline selflogwrites return tie ins outs tee sysstdout sysstderr sysstdin tee consolelogdat w console codeinteractiveconsole consoleinteract,i like realtime access interpreter input error standard output preferably information would written file i poll file changes every interpreter command entered for example given interpreter session printhello world hello world hello world hello world i like see following log file printhello world hello world hello world hello world the formatting important important i search file key words trigger interactive events session what i learned far trying accomplish python code module allows create interactiveconsole object rawinput method i redefine log file like import code class loggedconsolecodeinteractiveconsole def initself locals superloggedconsole selfinitlocals selffile open consolelogdat def delself selffileclose def rawinputself prompt data inputprompt selffilewritedata n return data furthermore interactiveconsole uses builtin write method log errors i redefine def writeself data sysstderrwritedata selffilewritedata n i also learned following snippet log stdout class teeobject def initself selffile open consolelogdat selfstdout sysstdout def delself sysstdout selfstdout selffileclose def writeself data selffilewritedata selfstdoutwritedata sysstdout tee my broken attempt bring together create loggedconsole object pass tee locals console loggedconsolelocalssysstdoutloggedexec consoleinteract i passed locals perhaps i incorrectly i receive error anyways open new interactive console log closing input errors output i banging head i feel like i close maybe even also way occur session currently logging takes place session closed thanks time sorry wall text edit i like able accomplish standard python interpreter portability purposes edit jaime snippet works well logging everything i need any way though i real time instead waiting session close edit figured the final working snippet import code import sys class teeobject def initself logfname mode selflog openlogfname mode def delself restore sin se sysstdout sysstdout sysstdir sysstdin sysstderr sysstderr selflogclose def writeself data selflogwritedata selflogflush sysstdoutwritedata sysstdoutflush def readlineself sysstdinreadline sysstdinflush selflogwrites selflogflush return def flushfoo return sysstdout sysstderr sysstdin tee consolelogdat w console codeinteractiveconsole consoleinteract,3 it seems intention regex match character notice slash escaping character amp unicode table httpwwwtamasoftcojpengeneralinfounicodehtml two comments expression usually need escape characters within brackets except maybe the ampersand symbol amp already contained range defined redundant,is characters ord ord amp set i think interpretation incorrect based test but python reference say anything wrong interpretation httpdocspythonorglibraryrehtml,1 there several ways easiest seems first convert d grid d grid proceed d case convert back d c pos myzerosscipyzeroscposcpos myzerosd myzerosravel gridscipyonespospos gridd gridravel distscrandompermutationposposcposcpos gridddistmyzerosd myzeros myzerosdreshapecposcpos grid griddreshapepos pos edit answer comment want part myzeros go grid array make dist array smaller example dist scipyrandompermutationposposcpos gridddist myzerosdcpos and i hope aware last line written gridddist really want set elements single instead using elements another array,if array myzerosscipyzeroscposcpos c pos array gridscipyonespospos how insert zeros grid random positions the problem dimensions i know myzerossczeroscpos array full zeros gridsconespos grid full available positionsones distscrandompermutationposcpos distribute cpos zeros random positions griddistmyzeros i tried something similar work i tried also myzerossczeroscpos still work,2 my choice print sysstderr spam because simply print listsdicts etc without convert string print sysstderr spam spam instead sysstderrwritestr spam spam,i come across least three ways print stderr import sys print sysstderr spam sysstderrwrite spamn future import printfunction print spam filesysstderr it seems contradict zen python †preferred way are advantages disadvantages one way †there one — preferably one — obvious way,3 tests may show pattern matches chr chr pattern guaranteed work way systems here character sets vary system system this perl regex documentation specifically recommends “to use ranges begin end either alphabetics equal case ae ae digits anything else unsafe” perl regex relevant regex used python so pattern ever run ebcdic based platform match different set characters it correct say pattern matches chr chr ascii based platforms,is characters ord ord amp set i think interpretation incorrect based test but python reference say anything wrong interpretation httpdocspythonorglibraryrehtml,1 here simple music player example pyqt import qtgui qtcore pyqtphonon import phonon class windowqtguiqpushbutton def initself qtguiqpushbuttoninitself choose file selfmediaobject phononmediaobjectself selfaudiooutput phononaudiooutputphononmusiccategory self phononcreatepathselfmediaobject selfaudiooutput selfmediaobjectstatechangedconnectselfhandlestatechanged selfclickedconnectselfhandlebutton def handlebuttonself selfmediaobjectstate phononplayingstate selfmediaobjectstop else path qtguiqfiledialoggetopenfilenameself selftext path selfmediaobjectsetcurrentsourcephononmediasourcepath selfmediaobjectplay def handlestatechangedself newstate oldstate newstate phononplayingstate selfsettext stop elif newstate phononstoppedstate selfsettext choose file elif newstate phononerrorstate source selfmediaobjectcurrentsourcefilename print error could play sourcetolocalbitdata name main import sys app qtguiqapplicationsysargv appsetapplicationname phonon win window winresize winshow sysexitappexec,i trying play single mp file software button pressed here qtcoreqobjectconnectselfpushbutton qtcoresignalfromutfclicked playsong function def playsong mmedia phononmediaobject mmediasetcurrentsourcephononmediasourcefilessongmp mmediaplay this doesnt raise error but song wont play i seen lot exemples c python lot songs playlist etc i want play single song missing something,1 the way i made work i using terminal let pythonhighlightall vimrc file everything works fine objects list tuple colored for information please look syntaxpythonvim,i using mac osx lion terminalapp supports output echo amptco in vimrc i pathtovimvimrc syntax filetype plugin indent set nobackup when i vim blahpy colorscheme torte syntax colors loading for example python keyword proper colors they regular text color that works c files python i updated syntaxpythonvim still luck can someone tell thanks,3 assuming lines contain c separated spaces result line open filenametxt resultappendlinesplit or happen like list comprehensions lsplit l open filenametxt note i assume care tuple list if cast tuplelsplit l open filenametxt edit thanks steven,i working chemistry program requires list elements corresponding atomic mass units something along lines elements hhec elements amu read file line written like c i need read information file append line tuple append tuple list here code i tried without success class chemistry def readamu infil openatomamutxt r line infilreadline atoms list element line line linerstripn parts linesplit element parts amu parts elementappendelement amuappendelement elementappendatoms am i right track if would i append two values tuple assign value index append list,2 an easier solution iterate file using loop elements openatomamutxt f line f name mass linesplit elementsappendname intmass,i working chemistry program requires list elements corresponding atomic mass units something along lines elements hhec elements amu read file line written like c i need read information file append line tuple append tuple list here code i tried without success class chemistry def readamu infil openatomamutxt r line infilreadline atoms list element line line linerstripn parts linesplit element parts amu parts elementappendelement amuappendelement elementappendatoms am i right track if would i append two values tuple assign value index append list,3 you opening connection smtp server closing email it would efficient keep connection open sending emails,i script i using send say messages myselfmyself however i noticed python really takes last year i needed system send emails attachments text i implemented msmtp bash as far i remember much faster moving loop inside around smtpservsendmailsender recepient msg function yields similar results am i something wrong surely slower bash msmtp i sending hi message attachments usrbinpython def sendmailrecepient msg import smtplib parameters sender logingmailcom password password smtpstr smtpgmailcom smtpport parameters smtpserv smtplibsmtpsmtpstr smtpport smtpservehloorheloifneeded smtpservstarttls smtpservehlo recepientexists smtpservverifyrecepient recepientexists smtpservloginsender password try smtpservsendmailsender recepient msg except smtplibsmtpexception printrecepientexists else print error recepientexists recepientexists smtpservquit range sendmail receivergmailcom hi,1 the easiest way run tests projecttestunit use for example nosetests whereprojecttestunit then use match exclude e refine list needed if still want use regex selectors probably like tested nosetests match foobttest executing script project directory would run tests start foo end ttest as general rule probably want use either match exclude these parameters specify pattern function names match you refine either one using ignorefiles naturally allows ignore whole files,i trying get nosetests identify tests running tests properly i following file structure project foo initpy barpy test initpy unit initpy bartestpy functional initpy footestpy within bartestpy class bartestunittesttestcase def bartest within footestpy class fooftestpy def footest using e options nosetests what regex i need run unit tests unit tests class bartest what regex i need run functional tests functional tests class fooftest i tried various combinations seem get nosetests i want consistently,3 you definitely want using datetime here code get datetime either string type datetime import datetime def strtodatetimedatestr return datetimestrptimedatestr dmy then print datetime format want strtodatetimestrftimedmy you never need roll datetimedatetime structure python,i reading data csv file date elements inconsistency dates for example sometimes date element like sometimes like since i plotting data later causes great deal noise plots the following date class can help modify code order get date form import class date def initself inputdate selfinputdate inputdate selfdate none selfmonth none selfyear none selfhour none selfmin none def setdateself date selfinputdate date refindall w date date selfmysplit printlen lendate assert lendate atleast ddmmyy datelength lendate selfmonth intdate selfdate intdate selfyear intdate lendate selfhour intdate selfmin intdate def mysplitself splitting date delimiters res selfinputdate print res seps sep seps sres res seq res seqsplitsep print res return res thanks,3 a dictionary would better data structure openatomamutxt f elementsamu dictlinesplit line f use like elementsamu h gets amu h elementsamukeys list elements without amu,i working chemistry program requires list elements corresponding atomic mass units something along lines elements hhec elements amu read file line written like c i need read information file append line tuple append tuple list here code i tried without success class chemistry def readamu infil openatomamutxt r line infilreadline atoms list element line line linerstripn parts linesplit element parts amu parts elementappendelement amuappendelement elementappendatoms am i right track if would i append two values tuple assign value index append list,1 after looking documentation briefly i think numpyfft may ignore mask i would try using mafilled function put value masked entries something like taken example code fttype nplognpabsnpfftfftmameancarbonfluxfilledcfluxfillvalue fttype nplognpmeannpabsnpfftfftcarbonfluxfilledcfluxfillvalue axes axis cfluxfillvalue reasonable guess substitute masked values the fill value also set another step stored part masked array could use carbonfluxfilled without argument,i problems d fast fourier transforms d array they mathematical nature understanding pythonnumpy nature edit for clarification core questions how numpyfft deal masked arrays can i average axis fft get result fft averaging axes involved fft the array consists carbon dioxide flux value units atmosphere ocean degree latitude longitude certain domain the shape array corresponding time latitude longitude the land values masked using import numpy np numpy import carbonflux mamaskedvaluescarbonflux e i would like show log variance d fourier transform carbonflux averaged longitude i average array last axis longitude fourier transform like fttype nplognpabsnpfftfftmameancflux this gives acceptable looking result however i told averaging first fttype nplognpmeannpabsnpfftfftcarbonflux axes axis this results masked values used calculate fft i tell first value fft order e from i understand result averaging fft differ averaging fft am i correct assumption make difference order i perform functions does fft use masked values can i avoid lastly i calculated log d fourier transform carbonflux averaged latitude i fail understand calculate log variance d fourier transform averaged latitude does value resultant fft image simply need squared become variance this seems come across complicated series questions help department would appreciated thank,2 for python pymedia pyffmpeg if need raw usage example see,i looking effective library encoding videos i would prefer something one rubypython ilk type languages i use libraries c php good essentially i looking something wraps ffmpeg would allow convert h mp theoraogv webm would nice flv files worst case i could always use language natively execute ffmpeg using something like commandffmpeg etc i prefer something bit higher levelinlanguage possible i already looked rvideo get work correctly,3 python code checkers include pyflakes pylint pychecker others,is application similar java checkmi python,1 you use ospathdirnamefile get directory script located,i trying run python script different location located i need reference files python script located i tried following oschdirosgetcwd but unfortunately gets current working dir i ran script script currently lives thanks,3 use import hook def setqtbindingspackage package pyqt pyside raise valueerror unknown qt bindings package import builtin import builtinimport def hookname globalsnone localsnone fromlistnone level root sep namepartition root qt name package sep return importname globals locals fromlist level builtinimport hook name main import sys lensysargv setqtbindingssysargv import qt print qt qt import qtcore print qtcore qtqtgui import qwidget print qwidget output python testpy pyside module pyside usrlibpythonsitepackagespysideinitpy module pysideqtcore usrlibpythonsitepackagespysideqtcoreso type pysideqtguiqwidget python testpy pyqt module pyqt usrlibpythonsitepackagespyqtinitpyc module pyqtqtcore usrlibpythonsitepackagespyqtqtcoreso class pyqtqtguiqwidget,i would like something like one source file qtpy import sys import pyqt sysmodulesqt pyqt then import file source files use like import qt qtqtcore import so i change pyqt pyside qtpy without touching source files possibly ugly sed script these modules mostly api compatibile i would like test is easy way because ways i tried working maybe i need imp module seems low level,2 you could smooth data gaussianfilter import numpy np import matplotlibpyplot plt import scipyndimage ndimage x y npmgrid z npcosxy nprandomnormalsizexshape increase value sigma increase amount blurring order means gaussian kernel z ndimagegaussianfilterz sigma order figpltfigure axfigaddsubplot aximshowz axfigaddsubplot aximshowz pltshow the leftside shows original data rightside gaussian filtering much code taken scipy cookbook demonstrates gaussian smoothing using handmade gauss kernel since scipy comes built i chose use gaussianfilter,i working creating contour plot using matplotlib i data array multidimensional it long wide so basically list lists length i contour plot working fine i need smooth data i read lot examples unfortunately i math background understand going so i smooth data i example graph looks like i want look like this graph what i want look similar what means i smooth contour plot like second plot the data i using pulled xml file but i show output part array since element array around items long i show excerpt here sample keep mind excerpt the dimension data rows columns the columns change depending data imported xml file i look values i use gaussianfilter change but changes great enough affect contour plot,3 depending nature asynchronous operation various existing solutions allow elegantly for example waiting response server use select socket wait reply you also several sockets note you always use timeout possible avoid waiting forever case kind error the loop mentioned post suffers well limit total time number iterations,i need implement function involves long async operation send request external server periodically check done needs behave like synchronous operation i following way startlongoperation true operationfinished return sleep i wonder acceptable better solution,1 the real answer profile code time long different parts code take know time spent that way real answer without guesswork still guess would calls smtpservverifyrecipient may slow ones reasons might server sometimes needs ask smtp servers info throttling operations avoid spammers use massively gather email addresses also try pinging smtp server if pingpong takes significant time i would expect sending email would take least long,i script i using send say messages myselfmyself however i noticed python really takes last year i needed system send emails attachments text i implemented msmtp bash as far i remember much faster moving loop inside around smtpservsendmailsender recepient msg function yields similar results am i something wrong surely slower bash msmtp i sending hi message attachments usrbinpython def sendmailrecepient msg import smtplib parameters sender logingmailcom password password smtpstr smtpgmailcom smtpport parameters smtpserv smtplibsmtpsmtpstr smtpport smtpservehloorheloifneeded smtpservstarttls smtpservehlo recepientexists smtpservverifyrecepient recepientexists smtpservloginsender password try smtpservsendmailsender recepient msg except smtplibsmtpexception printrecepientexists else print error recepientexists recepientexists smtpservquit range sendmail receivergmailcom hi,1 with index definition call function saveself text index index index tuple index index if passing tuple save argument text leave,i function def saveself text index filewritetext nresultsn index index rangelenselfdrinklist x index selfdrinklistxing filewrite min strymin max strymax value stryperc n filewrite nn filewrite npopulation fitness strselfcalculatepopulationfitness nnnn now i pass one argument index function works supposed i pass tuple indices i get typeerror list indices must integers tuple what i change,1 first whether class methods class structure nothing mutability int float immutable if i it points name somewhere memory first line on second line looks adds gets points memory change way the logic applies following examples using immutable types b string b string c tuple c tuple for mutable types i thing actallly change value stored memory with i created list locations memory if i e i point e list points i e and list e points updated also locations memory if i go back immutable type tuple f g f g then f still points original tuple pointed g entirely new tuple now example class sortedkeydictdict def newcls val return dictnewcls valclear where pass zhengcai huijun xinyi tuple tuples val getting error tuple clear method pass dictd val work case get empty sortedkeydict result,i confused immutable type i know float object considered immutable type example book class roundfloatfloat def newcls val return floatnewcls roundval is considered immutable class structure hierarchy meaning float top class method call similar type example even though book says dict mutable class sortedkeydictdict def newcls val return dictnewcls valclear whereas something mutable methods inside class type example class sortedkeydictadict def exampleself return selfkeys also last classsortedkeydicta i pass type set zhengcai huijun xinyi without calling example method returns dictionary the sortedkeydict new flags error i tried passing integers roundfloat class new flagged errors,3 the saveself text index syntax means index tuple arguments passed save text one so instance code myobjectsavesample text index tuple x index correctly loop values on hand havel myobjectsavesample text index element tuple x loop get value hence typeerror,i function def saveself text index filewritetext nresultsn index index rangelenselfdrinklist x index selfdrinklistxing filewrite min strymin max strymax value stryperc n filewrite nn filewrite npopulation fitness strselfcalculatepopulationfitness nnnn now i pass one argument index function works supposed i pass tuple indices i get typeerror list indices must integers tuple what i change,3 something like work import lxmletree et ns atom httpwwwworgatom tree etfromstringxml node treexpath atomentry namespacesns print node see also httplxmldexpathxslthtmlnamespacesandprefixes alternative node treexpathlocalname entry print node,i xml document following format feed xmlnshttpwwwworgatom xmlnsopensearchhttpacomspecopensearchrss xmlnsgsahttpschemasgooglecomgsa entry idhttpsipaddressfeedsdiagnosticssmbipaddresspathtofileid updatedtzupdated appedited xmlnsapphttppurlorgatomapptzappedited link relself typeapplicationatomxml hrefhttpsipaddressfeedsdiagnostics link reledit typeapplicationatomxml hrefhttpsipaddressfeedsdiagnostics gsacontent nameentryidsmbipaddresspathtodirectorygsacontent gsacontent namenumcrawledurlsgsacontent gsacontent namenumexcludedurlsgsacontent gsacontent nametypedirectorycontentdatagsacontent gsacontent namenumretrievalerrorsgsacontent entry entry entry feed i need retrieve entry elements using xpath lxml my problem i figure use empty namespace i tried following examples none work please advise import lxmletree et treeetfromstringxml the various things i tried node treexpath entry namespaces nonehttpwwwworgatom opensearchhttpacomspecopensearchrss gsahttpschemasgooglecomgsa node treexpath entry namespacesns node treexpath httpwwwworgatomentry at point i know try any help greatly appreciated,3 whether object mutable depends type this depend whether certain methods structure class hierarchy userdefined types ie classes generally mutable there exceptions simple subclasses immutable type other immutable types include builtin types int float tuple str well python classes implemented c a general explanation data model chapter python language reference the value objects change objects whose value change said mutable objects whose value unchangeable created called immutable the value immutable container object contains reference mutable object change latter’s value changed however container still considered immutable collection objects contains cannot changed so immutability strictly unchangeable value subtle an object’s mutability determined type instance numbers strings tuples immutable dictionaries lists mutable,i confused immutable type i know float object considered immutable type example book class roundfloatfloat def newcls val return floatnewcls roundval is considered immutable class structure hierarchy meaning float top class method call similar type example even though book says dict mutable class sortedkeydictdict def newcls val return dictnewcls valclear whereas something mutable methods inside class type example class sortedkeydictadict def exampleself return selfkeys also last classsortedkeydicta i pass type set zhengcai huijun xinyi without calling example method returns dictionary the sortedkeydict new flags error i tried passing integers roundfloat class new flagged errors,3 it depends parameters actually trying pass i presume called something effect objectsavehello world when use operator need pass variable number arguments tuple instead everything pass fixed arguments wrapped list therefore case variable index refers you call function save like instead objectsavehello world the variable index refers if reason wanted still pass tuple simply change function definition def saveself text index observe lack,i function def saveself text index filewritetext nresultsn index index rangelenselfdrinklist x index selfdrinklistxing filewrite min strymin max strymax value stryperc n filewrite nn filewrite npopulation fitness strselfcalculatepopulationfitness nnnn now i pass one argument index function works supposed i pass tuple indices i get typeerror list indices must integers tuple what i change,2 pywikipedia asks wikipedia login you register account wikipedia well mediawiki wiki assign edits when use pywikipedia usually expects use account instead editing anonymously note wikis may special requirements people run bots might require ask bot status first might disallow make changes via api i don’t exactly know done wikipedia you’ll need find for configuration please take look userconfigpy file inside pywikipedia directory this define wiki working family also username use usernamesfamilynamelanguage see also pywikipediabot meta pywikipediabot basics meta wikipediabots general information using bots wikipedia wikipediabot policy rules bot required follow,i new python i task access wikipedia for i using client pywikipedia access mediawiki api when i running loginpy asking password i get password somebody worked pywikipedia tool any suggestion client i use,2 in script takes five times time setup smtp connection seconds send email second could make sense setup single connection send several emails instead creating connection time usrbinenv python import smtplib contextlib import contextmanager datetime import datetime emailmimetext import mimetext netrc import netrc timeit import defaulttimer timer contextmanager def loginedsender password smtphost smtpgmailcom smtpport start timer smtpserv smtplibsmtpsmtphost smtpport timeout try make smtp server login smtpservehloorheloifneeded smtpservstarttls smtpservehlo print smtp setup took f seconds passed timerstart start timer smtpservloginsender password print login took f seconds timerstart start timer yield smtpserv finally print operations smtpserv took f seconds timerstart start timer smtpservquit print quiting took f seconds timerstart smtphost smtpgmailcom login password netrcauthenticatorssmtphost loginedlogin password smtphost smtpserv range msg mimetext timestamp datetimeutcnow msg subject test msg from login msg to login smtpservsendmessagemsg output smtp setup took seconds passed login took seconds operations smtpserv took seconds quiting took seconds if python version sendmessage could use smtpservsendmailfrom msgasstring,i script i using send say messages myselfmyself however i noticed python really takes last year i needed system send emails attachments text i implemented msmtp bash as far i remember much faster moving loop inside around smtpservsendmailsender recepient msg function yields similar results am i something wrong surely slower bash msmtp i sending hi message attachments usrbinpython def sendmailrecepient msg import smtplib parameters sender logingmailcom password password smtpstr smtpgmailcom smtpport parameters smtpserv smtplibsmtpsmtpstr smtpport smtpservehloorheloifneeded smtpservstarttls smtpservehlo recepientexists smtpservverifyrecepient recepientexists smtpservloginsender password try smtpservsendmailsender recepient msg except smtplibsmtpexception printrecepientexists else print error recepientexists recepientexists smtpservquit range sendmail receivergmailcom hi,2 you understand python represents data objects some objects like lists dictionaries mutable meaning change content without changing identity other objects like integers floats strings tuples objects changed an easy way understand look objects id below see string immutable you change content it error try change also assign new content new object created instead contents modified abc ids traceback recent call last file stdin line module typeerror str object support item assignment xyz ids uvw ids you list change objects identity idi idi to read python data model could look python language reference python datamodel python datamodel,i confused immutable type i know float object considered immutable type example book class roundfloatfloat def newcls val return floatnewcls roundval is considered immutable class structure hierarchy meaning float top class method call similar type example even though book says dict mutable class sortedkeydictdict def newcls val return dictnewcls valclear whereas something mutable methods inside class type example class sortedkeydictadict def exampleself return selfkeys also last classsortedkeydicta i pass type set zhengcai huijun xinyi without calling example method returns dictionary the sortedkeydict new flags error i tried passing integers roundfloat class new flagged errors,3 you would really prefer stay away polling synchronous operations scale better easier debug if control external protocol make sync i say mostly i think lot people make things async thinking somehow improves performance really makes things difficult you make sync operations appear async local event loop using multiple threads control threads processes select based fsms whatever if control external protocol really async choice poll depending think distribution response times i use sort exponential backoff cap poll period for programs i external main event loop report back via event mechanism event loop,i need implement function involves long async operation send request external server periodically check done needs behave like synchronous operation i following way startlongoperation true operationfinished return sleep i wonder acceptable better solution,1 maxlength supposed control total number words returned list would expected maxlength five yield words edit would keep two lists around since think easy read might like additional overhead def restrictwordsgivenlist whentostop outputlist wordlist pair givenlist stringtocheck pair listofwords stringtochecksplit word listofwords wordlistappendword outputlistappend stringtocheck len wordlist whentostop break return outputlist testlist one two three four five six seven eight nine give one two three give one two three give one two three four five,i python method takes list tuples form string float returns list strings combined would exceed certain limit i splitting sentences preserve output length making sure stay within sentence length desired output length for example where what next day when next event maxlength output where what next day maxlength output where this i l output stuples l maxlength outputappends llengetwordsfroms return joinoutput is smarter way make sure output word length exceed maxlength stopping length reached,1 one smarter way would break loop soon exceed maxlength way looping rest list reason stuples l maxlength break outputappends l lengetwordsfroms return joinoutput,i python method takes list tuples form string float returns list strings combined would exceed certain limit i splitting sentences preserve output length making sure stay within sentence length desired output length for example where what next day when next event maxlength output where what next day maxlength output where this i l output stuples l maxlength outputappends llengetwordsfroms return joinoutput is smarter way make sure output word length exceed maxlength stopping length reached,1 the code accumulate data input files memory unless process function itertools import izip def processline line process line input openfile r f openfile r f b izipf f processa b if process function efficient code run quickly enough purposes the loop terminate end one files reached if either file contains extraordinarily long line ie xml json files text code may work well,what efficient fastest way simultaneously read two large files processing i two files atxt btxt containing hundred thousand corresponding lines my goal read two files processing line pair def kernel afileopen atxt r bfileopen btxt r aline afilereadline bline bfilereadline aline processasplbspl process requiring corresponding file lines i looked xreadlines readlines wondering better speed paramount importance task thank,1 your code stop limit reached maxlength bad name not maximum length code allows exceeded first example deliberate l bad name let call totlen you even keep going totlen maxlength your example shows joining space code you probably need something like totlen output stuples totlen maxlength break outputappends totlen lengetwordsfroms return joinoutput,i python method takes list tuples form string float returns list strings combined would exceed certain limit i splitting sentences preserve output length making sure stay within sentence length desired output length for example where what next day when next event maxlength output where what next day maxlength output where this i l output stuples l maxlength outputappends llengetwordsfroms return joinoutput is smarter way make sure output word length exceed maxlength stopping length reached,1 the problem implementation performance rather actually incorrect never finishes second map there else continue missing part node removed closed set node already part either set must added open set,this implementation a python class node def initself x g h parent selfx x selfy selfg g selfh h selff gh selfparent parent def eqself none return selfx otherx selfy othery return false def ltself none return selff otherf return false def strself return strselfx strselfy strselff def meanlst print sumlstlenlst def findpathstartnode endnode map nodiagtrue openlist startnode closedlist solution lenopenlist openlistsort currentnode openlistpop currentnode endnode currentnode none solutionappendcurrentnode currentnode currentnodeparent break xy touchingnode nodecurrentnodexx currentnodeyy absendnodexcurrentnodex absendnodeycurrentnodey currentnode tileinrange touchingnodex touchingnodey touchingnodex lenmap touchingnodey lenmap tileinrange touchingnode currentnodeparent maptouchingnodeytouchingnodex continue touchingnode openlist n openlistopenlistindextouchingnode n touchingnode openlistremoven else continue touchingnode closedlist n closedlistclosedlistindextouchingnode n touchingnode closedlistremoven openlistaddtouchingnode closedlistappendcurrentnode return solution map map def testmap start end r map print r res findpathnodestartnone nodeendnone map n res print n testmap testmap with first map path found straight away on second one however even half hour path found i tried using faster list made difference can someone please point problem,2 i sure mean try replacing thingstab code see works class thingstabwxpanel def newaddimageselfparent thingslistboxappend hi selflistboxsetthingslistbox selflistboxsetselectionlenthingslistbox def renameselfparent sel selflistboxgetselection text selflistboxgetstringsel renamed wxgettextfromuser rename item rename dialog text renamed thingslistboxpopsel thingslistboxinsertselrenamed selflistboxsetthingslistbox selflistboxsetselectionsel def initself parent wxpanelinitself parent selflistbox wxlistboxself size choicesthingslistbox stylewxlbsingle selfsizer wxboxsizerwxvertical btnsizer wxboxsizerwxhorizontal selfsizermain wxboxsizer selflistboxbindwxevtlistboxdclick selfrename btn wxbuttonself labeltest btntwo wxbuttonself labeltest selfsizeraddselflistbox proportion flagwxtop wxexpand wxleft border btnsizeraddbtn wxall btnsizeraddbtntwo wxall selfsizeraddbtnsizer selfsizermainaddselfsizer proportion flagwxbottom wxexpand border selfsetsizerselfsizermain all i create button sizer add two buttons nest inside selfsizer i also changed following proportion zero one selfsizeraddselflistbox proportion flagwxtop wxexpand wxleft border hopefully help get farther along,trying put buttons underneath listbox however everything try seems distort cause problems i hoping anyone help i want put buttons underneath listbox always change position depending size window dissapear basicilly resize window app change position buttons here far thingsinlistbox thingslistbox thingslistbox thingslistbox import wx def areachangeselfpg print pg pgthings selfthingsareashow else selfthingsareahide class thingstabwxpanel def newaddimageselfparent thingslistboxappend hi selflistboxsetthingslistbox selflistboxsetselectionlenthingslistbox def renameselfparent sel selflistboxgetselection text selflistboxgetstringsel renamed wxgettextfromuser rename item rename dialog text renamed thingslistboxpopsel thingslistboxinsertselrenamed selflistboxsetthingslistbox selflistboxsetselectionsel def initself parent wxpanelinitself parent selflistbox wxlistboxself size choicesthingslistbox stylewxlbsingle selfsizer wxboxsizer selfsizermain wxboxsizer selflistboxbindwxevtlistboxdclick selfrename selfsizeraddselflistbox proportion flagwxtop wxexpand wxleft border selfsizermainaddselfsizer proportion flagwxbottom wxexpand border selfsetsizerselfsizermain class imageareawxframe def initself parent wxframeinitself parent wxstaticboxself personal info size selfquote wxstatictextself labelyour quote pos size selfshow selfsetsizerselfsizermain class thingstabwxpanel def initself parent wxpanelinitself parent wxstatictextself this pagetwo object class thingstabwxpanel def initself parent wxpanelinitself parent wxstatictextself this pagethree object class thingstabwxpanel def initself parent wxpanelinitself parent wxstatictextself this pagethree object class mynotebookwxnotebook def initself args kwargs wxnotebookinitself args kwargs class mypanelwxpanel def onpagechangedself event new eventgetselection areachangeselfselfnotebookgetpagetextnew eventskip def onpagechangingself event eventskip def initself args kwargs wxpanelinitself args kwargs selfnotebook mynotebookself size selfbutton wxbuttonself labelsomething else maybe tabthings thingstabselfnotebook tabthings thingstabselfnotebook tabthings thingstabselfnotebook tabthings thingstabselfnotebook add pages notebook label show tab selfnotebookaddpagetabthings thingsselecttrue selfnotebookaddpagetabthings things selfnotebookaddpagetabthings things selfnotebookaddpagetabthings things selfthingsareawxstatictextself this pageone object selfsizer wxboxsizer selfsizeraddselfnotebook proportion flagwxexpand selfsizeraddselfbutton proportion selfsetsizerselfsizer selfnotebookbindwxevtnotebookpagechanged selfonpagechanged selfnotebookbindwxevtnotebookpagechanging selfonpagechanging areachangeselfselfnotebookgetpagetext class mainwindowwxframe def initself args kwargs wxframeinitself args kwargs selfpanel mypanelself selfshow app wxappfalse win mainwindownone size appmainloop i sure anyone could help would greatly appiecated if something simple please forgive however i stuck days,1 you cannot mystuffpy mystuff package you two choices put code mystuffpy mystuffinitpy rename mystuffpy example mystuffstuffpy import mystuffinitpy the second option looks something like myprogram mystuffpy mystuff initpy stuffpy tests initpy testpy testpy mystuffinitpy looks like mystuffstuff import,i growing number scripts make program i writing decided time clean source tree package correctly i sure simple question i find if i group modules fit together one toplevel module others prefixed module name actually go lower level packages i for example say i wanted able import mystuff get mystuff i also able import mystufftesttest i thought i would create source tree like myprogram mystuffpy mystuff initpy tests initpy testpy testpy but case seems mystuff always takes precedence mystuffpy import mystuff nothing long mystuff initpy empty what would correct approach get desired behaviour or possible must i move mystuffpy mystuff access mystuffmystuff seem like unnecessary repetion sorry i missed something obvious i assume must documented somewhere i seem find somewhere update while i believe ignacio method correct one i really like if i multiple files open editor called initpy things could get messy so i decided leave structure link mystuffpy mystuffinitpy if anyone opinions i i like hear actually end i linking way around since i find way make distutils dereference symlinks creating targz i ended broken links output this way effect keeps happy,2 have cython code different file initpy import normal python initpy see answer previous question,i writing code cython i packages “within” modules mdash this actually follow question structure the problem cython i dealing py having initso works extent import mystuff work seems mask subpackages that import mystufftesttest i get importerror no module named error how i work around is something i need add pyx compiling c or perhaps i rename initso something else somehow pull initpy note initpy still needs exist alongside show package or something else update path attribute defined packages ok i thought maybe i could get around manipulating path attribute package interestingly enough defined py packages causes error it solution i wonder root problem,1 probably simple solution given problem would rename initso module something like nativeso afterwards create initpy would contain following line native import and work describe,i writing code cython i packages “within” modules mdash this actually follow question structure the problem cython i dealing py having initso works extent import mystuff work seems mask subpackages that import mystufftesttest i get importerror no module named error how i work around is something i need add pyx compiling c or perhaps i rename initso something else somehow pull initpy note initpy still needs exist alongside show package or something else update path attribute defined packages ok i thought maybe i could get around manipulating path attribute package interestingly enough defined py packages causes error it solution i wonder root problem,1 first i see reason defer breaking loop maximum length reached next iteration so altering code i come following code stuples where what next day when next event def getwordsnumbers return lenssplit def truncatestuples maxlength totlen output stuples outputappends totlen getwordsnumbers totlen maxlength break return joinoutput print truncatestuples second i really like temporary object output created we feed join method iterator iterates initial list without duplicating information def truncatestuples maxlength def stopiteratorstuples totlen snum stuples yield totlen getwordsnumbers totlen maxlength break return joinstopiteratorstuples print truncatestuples also examples output slightly bigger set maximum words if want number words always less limit still maximum possible put yield checking limit def truncatestuples maxlength def stopiteratorstuples totlen snum stuples totlen getwordsnumbers totlen maxlength totlen maxlength yield break yield return joinstopiteratorstuples print truncatestuples,i python method takes list tuples form string float returns list strings combined would exceed certain limit i splitting sentences preserve output length making sure stay within sentence length desired output length for example where what next day when next event maxlength output where what next day maxlength output where this i l output stuples l maxlength outputappends llengetwordsfroms return joinoutput is smarter way make sure output word length exceed maxlength stopping length reached,1 matplotlib optimized you bit better simpler options want display image onepixeltoonepixel have look tkinter example that said import matplotlibpyplot plt import numpy np dpi nothing screen dpi dpi xpixels ypixels fig pltfigurefigsizeypixelsdpi xpixelsdpi dpidpi figfigimagenprandomrandomxpixels ypixels pltshow or really want use imshow need bit verbose however advantage allowing zoom etc desired import matplotlibpyplot plt import numpy np dpi margin widthheight figure xpixels ypixels make figure big enough accomodate axis xpixels ypixels well ticklabels etc figsize margin ypixels dpi margin xpixels dpi fig pltfigurefigsizefigsize dpidpi make axis right size ax figaddaxesmargin margin margin margin aximshownprandomrandomxpixels ypixels interpolation none pltshow,i want display image say x matplotlibpyplot imshow function i want display one pixel image occupies one pixel screen zoom factor shrink stretch i beginner know proceed,3 astronomynet if astronomical imaging sky celestial coordinates know—or trust—then astrometrynet input image give back astrometric calibration metadata plus lists known objects falling inside field view we built astrometric calibration service create correct standardscompliant astrometric metadata every useful astronomical image ever taken past future state archival disarray we hope help organize annotate make searchable world astronomical information you even upload images website you download source it licensed gpl uses numpy muck around need note need first convert bitmap one following jpeg gif png fits image,i asked write program find stars image converting image file numpy array generating array coordinates brightest pixels image specified threshold representing background interference once i located brightest pixel image i must record xy coordinates set value pixel surrounding x pixel area zero effectively removing star image i already helper code converts image array attempted tackle problem follows i defined variable max arraymax used loop max threshold coordinates numpywherearray max find maximum value however i want loop whole array coordinatesnot find first maximum also remove maximum found setting surrounding x area zero i thought using loop unsure i use since i new python i would appreciate suggestions thanks,1 what looking numpyversion two underscores word version by inderstanding convention private semiprivate variables python,i installed python mac working fine i downloaded binary scipy httpsourceforgenetprojectsscipyfilesscipyscipypypythonorgmacosxdmg numpy httpsourceforgenetprojectsnumpyfilesnumpynumpypypythonorgmacosxdmg respectively installed however i tried following error occurred import numpy print numpyversion traceback recent call last file pyshell line module print numpyversion attributeerror module object attribute version however works fine numpyversionversion since i new python i followed instructions i wonder may cause error thanks,1 there number different ways numpy etc there brute force way import image import numpy np im imageopen testbmp data nparrayim threshold window this half window ni nj datashape newvalue j zipnpwheredata threshold istart istop max iwindow minni iwindow jstart jstop max jwindow minnj jwindow dataistartistop jstartjstop newvalue or faster approach import image import numpy np import scipyndimage im imageopen testbmp data nparrayim threshold window this full window newvalue mask data threshold mask scipyndimageuniformfiltermaskastypenpfloat sizewindow mask mask datamask newvalue,i asked write program find stars image converting image file numpy array generating array coordinates brightest pixels image specified threshold representing background interference once i located brightest pixel image i must record xy coordinates set value pixel surrounding x pixel area zero effectively removing star image i already helper code converts image array attempted tackle problem follows i defined variable max arraymax used loop max threshold coordinates numpywherearray max find maximum value however i want loop whole array coordinatesnot find first maximum also remove maximum found setting surrounding x area zero i thought using loop unsure i use since i new python i would appreciate suggestions thanks,1 alright fun adventure i figured one djangodb import connections import sqlite create django database connection test database connectionsdatabases test name memory engine sqlite we assume database sourcewrapper created sourcewrapper connectionsall targetwrapper connectionsall create tables source database sourcewrappercreationcreatetestdb dump database single text query query joinline line sourcewrapperconnectioniterdump generate inmemory sqlite connection connection sqliteconnectmemory targetwrapperconnection connection targetwrapperconnectionexecutescriptquery and database called test carbon copy default database use targetwrapperconnection reference newly created database,i writing test suite django runs tests treelike fashion for example testcase a might outcomes testcase b might testcase c might the tree looks like x abcx b x x cx x for path tree database contents may different so fork i thinking creating inmemory copy current state database feeding parameter next test anyone idea essentially copy inmemory database another one get reference pass database around thanks,1 basemap installer matplotlib basemap library matplotlib toolkit plotting d data maps need indepently install matplotlib use you get matplotlib,i trying install matplotlib windows vista both python numpy working i installed matplotlib via executable basemapwinpy followed official instructions but running matplotlib import gives following error no module named matplotlib any ideas get matplotlib working,3 i think could urlspy urlpatterns patterns urlr loginstorename login namelogin urlr loginstorename login namelogin urlr accountslogout logout nextpage name logout i exactly clear want,i working store based authentication system using django trying make url one specifies store user trying log ex loginstorename login user requested store my question way using django built login formmechanism would create login form view,1 with investigation appears stdinclose actually end bash session to could use bash command exit stdinwrite exitn dig paramiko channel object underneath stdin object stdinchannelshutdownwrite if like bash session continue another command need use channel object directly the documentation channel mentions recvreadyself recvself nbytes allow check data try get,i problem getting piping work paramiko this works ssh paramikosshclient stdin stdout stderr sshexeccommandfind tmp stdoutread this work blocks forever stdoutread stdin stdout stderr sshexeccommandbash stdinwritefind tmpn stdinclose stdoutread any ideas edit i looked source code paramiko channelfileclose really anything terms communication so i looked channel api seems work stdinwritefind tmpn stdinflush stdinchannelshutdownwrite stdoutread,3 option less efficient requires query incidentally note want exactly one result call get query return first result none none identical getbyid syntactic sugar constructing key fetching get,which cpu efficient key somethingkey id somethingkeyid dbgqlqueryselectfetch dbgetkey getbyidid,3 you get kind autocompletion dynamic language like python get explicitly typed languages consider def myfunctionmyarg myarg when type myarg expect editor provide list methods arguments that happen python editor absolutely way knowing type types myarg could possibly even python compiler information compiling code that put myargsomenonexistentfunction get kind error message runtime if wrote something like def myfunction myobject myclasssomearg myobject smart enough editor supply list methods available final you find editors supplying autocomplete sometimes cases similar second example cases similar first with python good get,i looked ide i set vim use autocompletion i using right however i seem get work like visual studio net autocompletion seems work certain cases shows methods parameters take it pretty much unusable what i popup show methods available parameters take pretty much feel vs programming net,3 to convert utc date string time import mktime datetime import datetime mktimedatetimeutctimetupledatetimestrptimeymdhm,i python datetime object i would like convert utc i planning output rfc format put http header i sure matters question i found information site converting time objects looks simpler way time i really want use datetime objects i using timedeltas adjust i tried something like datetime import datetime timedelta datetimenow fiveminuteslater datetimenow timedeltaminutes fiveminuteslaterutc nothing time datetime module looks like would help it seems like i may able passing datetime object functions i wondering simpler way i would prefer use thirdparty modules i may reasonable choice,1 gedit developer plugin tries syntax completion for reasons already mentioned work well i found annoying helpful disabled weeks trial ipython new qt console tab completion tooltip sort popups syntax help docstrings see screenshot example but people already pointed kind thing asking really appropriate less dynamic languages,i looked ide i set vim use autocompletion i using right however i seem get work like visual studio net autocompletion seems work certain cases shows methods parameters take it pretty much unusable what i popup show methods available parameters take pretty much feel vs programming net,2 use selfsizerboxaddselfimagesarea wxexpandwxall you indications wxpywiki point expand proportion parameters work give behavior widget,i troubles expanding staticbox here code using selfimagesarea wxstaticboxself selfsizerbox wxboxsizerwxhorizontal selfsizerboxaddselfimagesarea wxexpandwxall selfsetsizerselfsizerbox it appears working vertically however expand horizontally i would thought opposite since i used wxhorizontal boxsizer,1 i using eclipse pydev extension time the autocompletion really quite impressive i highly recommend,i looked ide i set vim use autocompletion i using right however i seem get work like visual studio net autocompletion seems work certain cases shows methods parameters take it pretty much unusable what i popup show methods available parameters take pretty much feel vs programming net,2 if want separate logins store need customize login form since django auth package create users universal stores,i working store based authentication system using django trying make url one specifies store user trying log ex loginstorename login user requested store my question way using django built login formmechanism would create login form view,1 unfortunately idle add py extension automatically get habit adding use another ide like eclipse komodo,in python ide save script prompt save dialog if specify filename test then file saved without extension test testpy is possible save script py extension automatically testpy,1 you pretty close zip looking listitertoolsproductzip,i trying get coordinates ndimensional cube list mins maxes dimension i able get corners using loops i would like generalize number dimensions so instance mins maxes would give coordinates this essentially finding paths two lists choosing value one lists index i seen algorithms give number paths fastest path i found one enumerates possible paths i assume itertools would come solution cannot figure use products permutations combinations way gives desired result the closest listitertoolsproductxmin xmax ymin ymax zmin zmax,2 a better solution problem put package separate package of course import package reusable would,python imports drive crazy experience python imports sometime correspond idiom explicit better implicit app startpy package import module package initpy print init package modulepy print init packagemodule import module modulepy print init packagemodule import sys pprint pprintpprintsysmodules import module i get vicubuntudesktopapp python startpy init package init packagemodule init packagemodule main module main startpy package module package homevicdesktopapppackageinitpy packagemodule module packagemodule homevicdesktopapppackagemodulepy packagemodule module packagemodule homevicdesktopapppackagemodulepy traceback recent call last file startpy line module package import module file homevicdesktopapppackagemodulepy line module import module file homevicdesktopapppackagemodulepy line module import module importerror cannot import name module vicubuntudesktopapp import packagemodule works want use import module want make package portable applications want use relative paths i using python i need circular imports a function module asserts one parameter instance class defined module viceversa in words sysmodules contains packagemodule module packagemodule homevicdesktopapppackagemodulepy i want get reference form import module tries get name package like case import packagemodule works fine i tried import module syntax error also import module module works fine import module module work update this hack works looking official way print init packagemodule import sys pprint pprintpprintsysmodules import module parentmodulename namerpartition module sysmodulesparentmodulename module,2 i assume want code follow end url returns if could try using urllib better still use requests install pip both urllib reliably requests follow give final page returns info requests module found httppypipythonorgpypirequests hope helps,i trying connect websites python get http status codes as answers question mine suggest reason http status code websites googlecom permanently moved servers redirecting however i would like able connect manner i get natural ok here current code import httplib conn httplibhttpconnectiongooglecom connrequestget r conngetresponse print rstatus rreason connclose what i need alteradd achieve i heard pycurl library might help googling brought useful results far i novice field please excuse question trivial,1 you searching double qoutes whereas example single qoutes researchr post datedw post date postcount viewcount questioncount answercount answeredquestion edit the problem longer within regex python here example import postline post date postcount viewcount questioncount answercount answeredquestion pattern post date dw p recompilepattern date psearchpostlinegroup print date outputs,the data like post date postcount viewcount questioncount answercount answeredquestion code task p recompilerpost date psearchpostline month researchr post datedw postlinegroup,2 take look hmevlc video streamer it crossplatform python gpl licensed pretty easy set,series later tivos music computername option music photos amp showcases lets play music hosted machine this option seems appear computer local network compatible server running for example windows pc running tivo desktop show configured correctly my nas also support neither servers configurable i would like however and windows box house laptop really relied server since asleep time is easily hackable opensource tivo media server library building one i need something run linux i prefer something written python java i mostly care able serve music mp files supporting photos computername thing would nice bonus,1 looking code one old projects looks like i used staticboxsizer added elements sizer quick test app wxappredirectfalse frame wxframenone staticbox wxstaticboxframe label label sizer wxstaticboxsizerstaticbox wxvertical range sizeraddwxbuttonframe label button stri framesizer sizer framesizerfitframe frameshow appmainloop,possible add things staticbox wxpython i know rather simple question however i cannot seem find anything google i would like actually able add things staticbox buttons,2 i pretty sure webserver using sockets select one line code not even using semicolons loops control structures are sure looking python simplehttpserver serving http port python version python httpserver,i seem remember seeing single line implementation webserver couple years ago i aware simplehttpserver like i think using socket select i thought python tutor mailing list archive search revealed anything google search i wondering anyone might leads i could look ideally link original although i guess entirely possible original author taken shame,3 when open file codecopen w encoding utf point writing byte arrays str objects file instead write unicode objects like corpusfile codecsopenfilename mode w encoding utf taggedtoken xdcmlxeut taggedtoken taggedtokendecode iso corpusfilewritetaggedtoken corpusfilewriteu n this write platformdependent endofline characters alternatively open binary file write byte arrays alreadyencoded strings corpusfile openfilename mode wb taggedtoken xdcmlxeut taggedtoken taggedtokendecode iso corpusfilewritetaggedtokenencode utf corpusfilewrite n this write platformindependent eols if want platformdependent eol print ossep instead n note encoding naming notepad misleading ansi utf want,i following function def storetaggedcorpuscorpus filename corpusfile codecsopenfilename mode w encoding utf token corpus taggedtoken joinstr str token taggedtoken taggedtokendecode iso taggedtoken taggedtokenencode utf corpusfilewritetaggedtoken corpusfilewriteun corpusfileclose and i execute i got following error storetaggedcorpus corpusfilewritetaggedtoken file cpythonlibcodecspy line write return selfwriterwritedata file cpythonlibcodecspy line write data consumed selfencodeobject selferrors unicodedecodeerror ascii codec decode byte xc position ordinal range so went debug discovered created file encoded ansi utf declared corpusfile codecsopenfilename mode w encoding utf if corpusfilewritetaggedtoken removed function obviously work file encoded ansi if instead i remove taggedtoken taggedtokenencode utf also work but resulting file encoding ansi utf latin characters mangled since i analizing ptbr text unacceptable i believe everything would work fine corpusfile opened utf i get work i searched web everything i found pythonunicode dealt something elses so file always ends ansi i using python windows x file encodings informed notepad edit mdash about corpus parameter i know encoding corpus string it generated plaintextcorpusreadertag method nltk the original corpus file encoded utf according notepad the taggedtokendecode iso guess i tried decode cp got mangled characters iso,2 i know tweepy but twitter rest api limits results at end result gives kind pointer next page use pointer httpsdevtwittercomdocsapi,is way access members list currently i see first members specifically i using python tweepy,1 i tried replicating error encountering i nose i getting error i installed nose using pip sudo pip install nose after scipytest worked i nothing else did install nose using pip if try using pip my machine scipy version dev nose,i new stackoverflow well python i hope use stackoverflow learn improve python programming however soon i set python scipy numpy mac i encountered problem i tried running full test scipy numpy verify install import scipy scipytest running unit tests scipy traceback recent call last file pyshell line module scipytest file libraryframeworkspythonframeworkversionslibpythonsitepackagesnumpytestingnosetesterpy line test selfshowsysteminfo file libraryframeworkspythonframeworkversionslibpythonsitepackagesnumpytestingnosetesterpy line showsysteminfo nose importnose file libraryframeworkspythonframeworkversionslibpythonsitepackagesnumpytestingnosetesterpy line importnose raise importerrormsg importerror need nose tests see httpsomethingaboutorangecommrlprojectsnose as suggested error message i install nose package via easyinstall install seems successful i get following bash mlstr mlstr nosetests v nosetests version so i tried scipy test failed message can someone please let know i need anything else installconfigure nose used unit tests scipy numpy thanks advance update after trying rahul suggestion using pip reinstall nose i think i found problem whenever i easyinstall pip bash package installed python directories instead ones and i think default one shipped snow leopard so i tell easyinstall pip i want install particular package python thanks update by following update i found solution easyinstall various versions python installed mac osx it indeed i used wrong version easyinstall thus nose installation python shipped mac os x thanks,3 try writing file utf signature aka bom def storetaggedcorpuscorpus filename corpusfile codecsopenfilename mode w encoding utfsig token corpus taggedtoken joinstr str token printtypetaggedtoken break taggedtoken taggedtokendecode cp corpusfilewritetaggedtoken corpusfilewriteun corpusfileclose note work properly taggedtoken unicode string to check uncomment first comment code print type unicode if taggedtoken unicode string need decode first using second commented line nb i assumed cp encoding certain iso course need change,i following function def storetaggedcorpuscorpus filename corpusfile codecsopenfilename mode w encoding utf token corpus taggedtoken joinstr str token taggedtoken taggedtokendecode iso taggedtoken taggedtokenencode utf corpusfilewritetaggedtoken corpusfilewriteun corpusfileclose and i execute i got following error storetaggedcorpus corpusfilewritetaggedtoken file cpythonlibcodecspy line write return selfwriterwritedata file cpythonlibcodecspy line write data consumed selfencodeobject selferrors unicodedecodeerror ascii codec decode byte xc position ordinal range so went debug discovered created file encoded ansi utf declared corpusfile codecsopenfilename mode w encoding utf if corpusfilewritetaggedtoken removed function obviously work file encoded ansi if instead i remove taggedtoken taggedtokenencode utf also work but resulting file encoding ansi utf latin characters mangled since i analizing ptbr text unacceptable i believe everything would work fine corpusfile opened utf i get work i searched web everything i found pythonunicode dealt something elses so file always ends ansi i using python windows x file encodings informed notepad edit mdash about corpus parameter i know encoding corpus string it generated plaintextcorpusreadertag method nltk the original corpus file encoded utf according notepad the taggedtokendecode iso guess i tried decode cp got mangled characters iso,1 i prefer lxml it nice api xpath support makes fairly simple accomplish import lxmlhtml doc lxmlhtmlparseurltosite feeds docxpath linktypeapplicationrssxmlhref list feed urls,the rss feed url available site meta data one available is way extract feed urls page using urllib htmlparser modules or better module available thanks,1 try install latest version macports python first set python default python version sudo port install python port select list python sudo port select set python python reinstall pyside sudo port install pypyside,trying get feet wet pyside development trouble getting setup i tried installing binaries r produced following message import pyside traceback recent call last file stdin line module file librarypythonsitepackagespysideinitpy line module import private file librarypythonsitepackagespysideprivatepy line module qtcore import moduleshutdown importerror dlopenlibrarypythonsitepackagespyside qtcoreso library loaded qtcoreframeworkversionsqtcore referenced librarypythonsitepackagespysideqtcoreso reason image found then i tried install gitorious build scripts using sudo dependenciesosxsh after completed i get following error import pyside traceback recent call last file stdin line module file librarypythonsitepackagespysideinitpy line module file librarypythonsitepackagespysideprivatepy line module importerror no module named qtcore any advice appreciated i using qtcreator qt sdk qt library thank,1 since seems pygame developers hang around much i brought question pygame mailing list originated monster thread issue debated large the summary would at present feature there interest implement least try implement although priority core devs way there one way skin cat scaling happen ways inputting coordinates reading deal lines thickness visible deal visibility objects edge image points taken reference know pixel lit see linked thread,this question related one in program uses pygame draw objects video i two representation world a physical one i use make calculations involved simulation objects located x metres surface a visual one i use draw screen objects located window measuring x pixels what i want achieve able pass pygame drawing functions normally accept inputs pixels physicalrealword coordinates in words i would like able say draw radius circle coordinates using precise pygame syntax pygamedrawcirclesurface get circle px radius centred pixels please note question native pygame way sort workaround achieve result want answer take look question i already mentioned instead thanks advance time support,1 when i asked question two years ago ubuntu gnome much closer today at present end gnome adopted gnomeshell canonical decided develop ui unity part tension brought split specifically involved libappindicator makes way i formulated question probably part answers obsolete besides askubuntu stack exchange would probably much better forum ask ubuntuspecific question,i linux mostly ubuntu user reasonable understanding system works although i certainly linux guru in past i developed small crossplatform desktop applications pythongtk i delivered clients selfcontained filetrees dependencies python gtk now i would like develop small applet ubuntu i would like release gpl in particular new steps i know i must learn order achieve goal possible i unaware though integrating gnome i want application available applet taskbar using dbus in particular i want applet use new osdnotification framework ubuntu communication applets also possible feature second iteration packaging i would like setup public ppa soon application reach alpha stage i also would like use dependencies existing packages official repos rather include libraries package of course official documentation first source knowledge basing judgment useful answers i received another topic so i decided turn so community collect additional advice like example are additional steps i outlined i learn order able implement project based experience would advise learn steps advance knowledge influence way coding core functionality would consider integration gnome dbus packaging higher encapsulating levels added top core functionality afterwards note dbus used first pushing data input data retrieved webservice would advise separate application two packages backend frontend keep together single package do know useful resource would advise look learning things i are aware common beginner mistakes i aware these questions meant exhaustive though feel i missing something general picture welcomed point right direction thank advance time ps should i failed explaining final goal take look project hamster i want achieve similar terms user interface meaning applet display status clicking open application could configure applet perform various operations,1 what floats immutable but i x x print x doesn mut x well agree strings immutable right but thing foo bar print foobar the value variable changes changes changing variable refers a mutable type change way also change place here difference x something immutable type print x funcx print x prints thing x something mutable type print x funcx print x might print something different x something immutable type x print x statement operates print x prints thing x something mutable type x print x statement operates print x might print something different concrete examples x foo x print x foo bar print x foo x x print x print x def funcval val bar x foo print x foo funcx print x foo def funcval val x print x funcx print x,i confused immutable type i know float object considered immutable type example book class roundfloatfloat def newcls val return floatnewcls roundval is considered immutable class structure hierarchy meaning float top class method call similar type example even though book says dict mutable class sortedkeydictdict def newcls val return dictnewcls valclear whereas something mutable methods inside class type example class sortedkeydictadict def exampleself return selfkeys also last classsortedkeydicta i pass type set zhengcai huijun xinyi without calling example method returns dictionary the sortedkeydict new flags error i tried passing integers roundfloat class new flagged errors,3 the idea behind duck typing document expecting duck objects fake duck nowhere docs api specify accepts stringio object instead place expect filelike object also part standard library trying avoid naming specific methods demand duck type that leaves implementation open change the randomsample api example could defined terms iterables terms sequences if want specific could use abstract base classes several already included collections module iterable hashable sized numbers module rational integral etc it hard model write then documentation simply mentions abcs required ie x sized iterable integral,i documentation bloat anytime i encounter complex ducktype i need way say duck type instead get caught endless cycle function requires input document documenting this results bloated repetitive documentation following def fooarg args arg an object supports x functionality y functionality passed z functionality insert code def bararg args arg an object supports x functionality y functionality passed z functionality insert code and baz qux functions i need shorter way writing arg type object for duck types easy a dictlike object know expect dict know pass a dict something mimic i feel c problem templated types haskell would one use type class definition document note haskell classes classes javacpythonetc note i really program haskell forgive crappy example should i go traditional oo route write base class say anything like base class docs the code enforce deriving base class requirement object derived base class adds value except document properties interface essentially on hand i programming python i try program within idioms language as otherwise usually hurts base classes good inheriting functionality base class completely abstract seem add value ducktyped language edit to answers i know duck typing evident post where i document question esp class exists attach documentation,3 the point duck typing notion type becomes abstract intuitive idea rather something formally part language this makes typing much fluid flexible languages type checking part language what required using duck typing program knows type using programmers so whole family classesfunctionsetc operate objects particular type type able described words add section comments docstring even external txt file describing type naming then refer name everywhere,i documentation bloat anytime i encounter complex ducktype i need way say duck type instead get caught endless cycle function requires input document documenting this results bloated repetitive documentation following def fooarg args arg an object supports x functionality y functionality passed z functionality insert code def bararg args arg an object supports x functionality y functionality passed z functionality insert code and baz qux functions i need shorter way writing arg type object for duck types easy a dictlike object know expect dict know pass a dict something mimic i feel c problem templated types haskell would one use type class definition document note haskell classes classes javacpythonetc note i really program haskell forgive crappy example should i go traditional oo route write base class say anything like base class docs the code enforce deriving base class requirement object derived base class adds value except document properties interface essentially on hand i programming python i try program within idioms language as otherwise usually hurts base classes good inheriting functionality base class completely abstract seem add value ducktyped language edit to answers i know duck typing evident post where i document question esp class exists attach documentation,1 more strictly typed languages like java concept interfaces collections methods class implementing interface supposed provide i suppose could borrow concept without necessarily bringing along baggage strict typing define document abstract class foo say method expects foo foo like object you even make class actually inherit foo want people reading documentation still know go find expected foo like object,i documentation bloat anytime i encounter complex ducktype i need way say duck type instead get caught endless cycle function requires input document documenting this results bloated repetitive documentation following def fooarg args arg an object supports x functionality y functionality passed z functionality insert code def bararg args arg an object supports x functionality y functionality passed z functionality insert code and baz qux functions i need shorter way writing arg type object for duck types easy a dictlike object know expect dict know pass a dict something mimic i feel c problem templated types haskell would one use type class definition document note haskell classes classes javacpythonetc note i really program haskell forgive crappy example should i go traditional oo route write base class say anything like base class docs the code enforce deriving base class requirement object derived base class adds value except document properties interface essentially on hand i programming python i try program within idioms language as otherwise usually hurts base classes good inheriting functionality base class completely abstract seem add value ducktyped language edit to answers i know duck typing evident post where i document question esp class exists attach documentation,1 microsoft support document kb demonstrates hide taskbar using visual basic here ctypes version python import ctypes ctypes import wintypes user ctypeswindlluser toggleunhidewindow x togglehidewindow x userfindwindowwrestype wintypeshwnd userfindwindowwargtypes wintypeslpcwstr lpclassname wintypeslpcwstr lpwindowname usersetwindowposrestype wintypesbool usersetwindowposargtypes wintypeshwnd hwnd wintypeshwnd hwndinsertafter ctypescint x ctypescint y ctypescint cx ctypescint cy ctypescuint uflags def hidetaskbar handlew userfindwindowwushelltraywnd u usersetwindowposhandlew togglehidewindow def unhidetaskbar handlew userfindwindowwushelltraywnd u usersetwindowposhandlew toggleunhidewindow,is way hide windows taskbar using python if way disable resize lock using registry,2 the steam overlaynotification system hooks games via directd opengl windows depending game understanding work games directdopengl like diablo it uses rendering libraries game uses thus overlay menus natively as python implementations check httpdirectpythonsourceforgenet httppyopenglsourceforgenet start directx opengl libraries respectively i warn i think simple hoping,so i tinkering different gui i able even find point begin researching question how i make gui like steam digital distribution app more specifically i interested manage make shifttab menu pop ingame without disruptingpausingeffecting game i somewhat successful making gui window stay top game window mode steam pops little menu top running fullscreen game that i interested learning any info would much appreciated sorry correct place post i sure exactly ask ps preferably something i could implement python,1 are using built authentication trying roll if former access user credentials get information need user object if latter handle credentials way wish rolling app engine magic way detect handling username password,what accepted way get authentication credentials login password using webapp i pretty sure get submitted andor interpreted differently rest information coming request i afraid i remember exactly i supposed get fyi the requests forced https thanks,1 httpwwwbialixcomintelhex intel hex i aware srec python implementations,is available open source library developed python java manipulating motorola srecord files intel hex files eg converting one format i looking pure java python library simply set java python bindings library like srecord,1 i think probably looking defaultdict a defaultdict like dictionary except keyerror would thrown dict factory function given upon initialization used create initial value in case need defaultdict days nested inside one weeks i think work collections import defaultdict r defaultdictlambda defaultdictint time week tdateisocalendar day tdateisoweekday rweekday thours,hopefully i explain i trying accomplish i problem achieving result i know probably best way i table entries date i trying take entries current month arrange list week sum value table day week the end result would look something like decimal decimal decimal decimal i solution but i know best way any ideas make better queries database returns time objects fields hours date time selfmonthtime r time get week year number week tdateisocalendar get day week number day tdateisoweekday week r rupdateweek day rweek rweekday rweekday rweekday thours,1 i got messages like i installed suds pythonntlm our site separate areafor installations maintain multiple versions first installation step python setuppy install prefixinstallsudssuds i got messages installplace to fix make sure directories mkdir p installsudssudslibpythonsitepackages this surprised little i thought setup would build directories make sure write permission tree chmod r installsudssudslibpythonsitepackages neither got rid message the last step put install area pythonpath setuppy export pythonpathinstallsudssudslibpythonsitepackagespythonpath python setuppy install prefixoptswfwqcesudssuds final chmod make newly installed files readable case umask set something restrictive chmod installsudssudslibpythonsitepackages after i could start python import suds the key step putting suds sitepackages directory pythonpath i expect help comes late help original poster i hope helps someone else come so question as i,i real trouble installing suds python i tried install setup file says location python cannot found this i changed location python i tried use easyinstall luck does anyone know simple way link clear installation instructions command i entered python setuppy install the result i recieved running install error cannot create remove files install directory the following error occurred trying add remove files installation directory errno permission denied usrlocallibpythonsitepackagestesteasyinstallwritetest the installation directory specified via installdir prefix distutils default setting usrlocallibpythonsitepackages perhaps account write access directory if installation directory systemowned directory may need sign administrator root account if administrative access machine may wish choose different installation directory preferably one listed pythonpath environment variable for information options may wish consult documentation httppeaktelecommunitycomeasyinstallhtml and i change python path exactly i tried one site said first create altinstallpth file python sitepackages directory containing following line import os site siteaddsitedirospathexpanduser libpython then says modify distutilscfg distutils directory install installlib libpython this next line optional often quite useful directs easyinstall distutils install scripts user bin directory for mac os x framework python builds use usrlocalbin instead neither bin default script installation location system path installscripts bin,1 even way test i recommend test client perspective outsidein behavior provided sut game your tests users need know care expose behavior using library as long behavior broken tests pass also like another answer says maybe need dependency may simpler solution eg hashtable might instinctively jumped relational database listen tests let tests pull behavior this also leaves free change dependency future without fix bunch tests,i make game using python libtcod roguelike game library more point i using pymock i starting learn testdriven development i determined cheat i really want get habit properly according tdd i need failing unit test i write first line code i figure first test production code dependency libcotdpy imported my testing file usrbinpython import pymock mocking unit testing import game empty production code file gamepy class initializetestpymockpymocktestcase def testlibtcodisimportedself how i test production file imports libtcodpy module namemain import unittest unittestmain please python people how i test module loaded tdd people should i unit testing something basic if first thing i testing,1 i gonna go different direction try write unit tests assert public behavior private state lets say call void method a modifies internal state now method called state change observable change little codeuniverse maybe b behaves differently so test would trivializing example void mytest assertthatb isfalse a assertthatb istrue avoid inappropriate intimacy test sut,i trying improve i write unit test cases python programs i noticing cases would really helpful access private members ensure method functioning properly an example case would trying test method proper behavior expected return value none i know easy wrong way would make private attributes protected attributes instead test directly however i would like find way expose interface much so i test private attributes within classes without exposing interface applicable better way testing scenario private attribute access would necessarily needed proper unit testing,2 in python unlike prog languages ​​like c stl predefined data structure stack regular list so want iterate stack regular list simply make something like item reversedmylist preserve lifo something item now want list behave stack lifo last in first out could use predefined list functions append pop stack stackappend stackappend stack stackpop stack more httpdocspythonorgtutorialdatastructureshtmlusinglistsasstacks,what specific method iterate stack python best practice use loop like iterate list,2 turns oid dbemailsinsert raw bsonbinarybinarydata saving binary ensures original content data changed,i encountering really strange bug emailid itemids resp data connfetchemailid rfc try dbemailsinsert raw data so i fetching bunch data gmail using oauthclientsimap after fetching email gmail i decided store raw first mongodb and another part script i something like ij enumeratedbemailsfind raws j raw email emailmodulemessagefromstringraws emailismultipart print getcleanedbodyemail note i import email emailmodule shadowed variable email i cannot think better term variable hold email instance now strange none email instances multipart if modify retrieval code emailid itemids resp data connfetchemailid rfc try dbemailsinsert raw data e emailmessagefromstringdata print eismultipart i seeing true i guess one possible explanation might saving data mongodb messes something allow email parse correctly,2 rebinding ie assigning attribute object name attribute class shadows attribute class the object always checked attributes first followed classes mro order,i question class python the documentation says class class class instance belongs so i conducted series experiments class counter count def initself selfclasscount newcounter counter print newcountercount the result newcounter counter print newcountercount the result print newcounterclasscount newcountercount result true everything goes well then i enter code follows newcounterclasscount print newcountercount result print newcounterclasscount result print newcountercount result print newcounterclasscount result print newcounterclasscount newcountercount result true from code i thought maybe newcountercount equals newcounter classcount following code surprised newcountercount print newcountercount result print newcounterclasscount result print newcountercount result print newcounterclasscount result print newcounterclasscount newcountercount result false why newcountercount changed newcounterclasscount remained what i changed newcountercount newcounterclasscount newcountercount became false what world attribute class ?,2 this line newcounterclasscount changes static count counter newcountercount newcounter count attribute hides static count line effect newcounter this also newcounterclasscount newcountercount,i question class python the documentation says class class class instance belongs so i conducted series experiments class counter count def initself selfclasscount newcounter counter print newcountercount the result newcounter counter print newcountercount the result print newcounterclasscount newcountercount result true everything goes well then i enter code follows newcounterclasscount print newcountercount result print newcounterclasscount result print newcountercount result print newcounterclasscount result print newcounterclasscount newcountercount result true from code i thought maybe newcountercount equals newcounter classcount following code surprised newcountercount print newcountercount result print newcounterclasscount result print newcountercount result print newcounterclasscount result print newcounterclasscount newcountercount result false why newcountercount changed newcounterclasscount remained what i changed newcountercount newcounterclasscount newcountercount became false what world attribute class ?,3 as others said python really builtin stack datatype per se use list emulate one when using list stack model firstinlastout behavior append push pop pop julioalegria describes if want use list forloop still behave filo fashion reverse order elements slice syntax example element stack print element if using custom class implements stack long iter next methods defined use list comprehensions loops whatever that way implement custom iterator removes items iterates proper stack example class stack def initself selfdata def pushselfn selfdataappendn def popself return selfdatapop def iterself return self def nextself lenselfdata return selfpop else raise stopiteration filo stack filopush filopush filopush filo print,what specific method iterate stack python best practice use loop like iterate list,1 macports removed pythonselect functionality use port select instead see macports didnt place pythonselect optlocalbin macports pythonselect command found,problem default command python used osx python that means example install pypil macports osx python find module python installed macports i command called python available earlier utility called pythonselect completely gone vain look romansmacbook holms ls optlocalbinpython optlocalbinpython optlocalbinpythonconfig optlocalbinpythonw romansmacbook holms sudo port v install pythonselect cleaning pythonselect removing work directory pythonselect i even tried remove macports completely system reinstalled everything still result pythonselect gone vain if anybody could confirm trying download macports install python use pythonselect would great i need write compability osx software would great know situation pythonselect osx lion so would two questions pythonselect lion make default python command use macport python osx one,1 import urllib import urllib url httpsnaleagueoflegendscomuserlogin params urlliburlencode name myaccountloginusername pass password formid userlogin response urlliburlopenurl paramsread urllib tutorial,i know much difference http get http post i hoping get information knowledgeable i written following code form actionhttpsnaleagueoflegendscomuserlogin methodpost input namename typetext valuemyaccountloginusername input namepass typepassword valuepassword input nameformid idedituserlogin valueuserlogin input classloginbutton valuesubmit typesubmit stylewidthpx form when i pass actual username password form click submit button i properly logged website however i change method post get returns following httpsnaleagueoflegendscomuserloginnamemyaccountloginusernameamppasspasswordampformiduserlogin i click link log my question possible direct post via python i create form instead i open url contains proper parameters log post server thank advance knowledge suggestions andor answers,1 the sophisticated library use purpose probably requests import requests response requestspost args cf documentation requestspost,i know much difference http get http post i hoping get information knowledgeable i written following code form actionhttpsnaleagueoflegendscomuserlogin methodpost input namename typetext valuemyaccountloginusername input namepass typepassword valuepassword input nameformid idedituserlogin valueuserlogin input classloginbutton valuesubmit typesubmit stylewidthpx form when i pass actual username password form click submit button i properly logged website however i change method post get returns following httpsnaleagueoflegendscomuserloginnamemyaccountloginusernameamppasspasswordampformiduserlogin i click link log my question possible direct post via python i create form instead i open url contains proper parameters log post server thank advance knowledge suggestions andor answers,1 logging basically means receiving cookie after sending post request get cookie authenticates future get requests a get request however cannot authenticate unless server side allowed shoudld allowed insecure so answer question possible inserting cookie real browser easy i suggest use mechanize want automate login process nothing else automatically if want automate things well look urllib requests good http request apis,i know much difference http get http post i hoping get information knowledgeable i written following code form actionhttpsnaleagueoflegendscomuserlogin methodpost input namename typetext valuemyaccountloginusername input namepass typepassword valuepassword input nameformid idedituserlogin valueuserlogin input classloginbutton valuesubmit typesubmit stylewidthpx form when i pass actual username password form click submit button i properly logged website however i change method post get returns following httpsnaleagueoflegendscomuserloginnamemyaccountloginusernameamppasspasswordampformiduserlogin i click link log my question possible direct post via python i create form instead i open url contains proper parameters log post server thank advance knowledge suggestions andor answers,1 it seems displayed complex output dct and tried save channel image dct outputs channels one real one imaginary part saved real part somehow close magnitude so dct output use magnitude phase functions extract useful info display separately and important read carefully dct httpenwikipediaorgwikidiscretecosinetransform know,i attempting use dct function opencv calculate discrete cosine transform i getting strange results my script import os sys import cv cv import numpy np fn originaljpg img cvimreadfn cvcvloadimagegrayscale h w imgshape vis npzeroshw npfloat vish w img vis cvdctvis img cvcreatematvisshape visshape cvcvfc cvcvtcolorcvfromarrayvis img cvcvgraybgr cvshowimage img cvwaitkey cvsaveimage savedjpg img this appears run without error image shown showimage image saved saveimage appear different unfortunately i seem find sample images dctprocessed image i sure either correct the original image the shown dct image the saved dct image why difference shown saved dct images which correct,1 good question i sure i completely answer here ideas sybasepy uses logging make sure using to bump logging i would import logging loggingbasicconfiglevel logginginfo format asctimes levelnames filenames names messages datefmt hms stream sysstdout log logginggetlogger sybase logsetlevelloggingdebug and apparently beyond get working sybasepy need set global debugtrue see line but look def execute see point blocking we sort answers question you going get anything back blocking so fix write nonblocking excute method there hints examplestimeoutpy apparently someone else run really fixed i know probably help i spent minutes looking i least tell i found you would think execute would give result wait value result line status result selfcmdctresults status cssucceed break if status cssucceed i assuming case true simply see result equal i wonder failed raise result exception,when i query isql i get following message query blocks the transaction log database foo almost full your transaction suspended space made available log when i python cursorexecutesql the query blocks i would like see message i tried sybasesetdebugsysstderr connectiondebug i using pythonsybasepre adaptive server enterpriseebf edit the question how i capture warning message python program,1 the elementmaker maps function tag name using eg edateadded build xml tree however discrepancy allowed characters htmlxml tags python functions as stated pep package module names modules short alllowercase names underscores used module name improves readability so dateadded function includes underscore allowed present python function def foobar file stdin line def foobar syntaxerror invalid syntax to resolve create dateadded tag bit verbosely supplying name argument instead etreetostringeurle dateadded urldateaddeddateaddedurl,i using lxml efactory aka elementmaker creating xml documents i trying generate xml document similar url dateaddeddateadded url however using efactory i sure specify dash dataadded element it seems interpreting dash minus sign here docs i referring httplxmldetutorialhtmltheefactory here reproduce error lxml import etree lxmlbuilder import elementmaker e elementmaker url eurl dateadded edateadded xml urldateaddedmyobjectcreatedstrftime ymdthms nameerror global name added defined does anyone know trick get properly render element dash thank reading joe,3 i think good thing rely much global setting debug changes whole behavior app what want audit code log stuff production you going turn debug true you rather tone log filter on stylistic point view makes little sense pythonistic settings debug log level affect single behavior long answer short opinion method superior technically stylisticly speaking,in django settingspy defines debug whole project now my debug level independently configured settingspy how i use loggingdebug way settingsdebug loggingdebugdebug message way without checking settingsdebug loggingdebugdebug message what good practice i think use way since logging level already decides message logged but say way standard practice,2 did try reversing admin url system that could give something like journal page ul volume originalvolumesetall li href url adminyourappvolumechange volumeid edit volume li endfor ul,hi everybody i defined several models journals volumes volumescaninfo etc a journal volumes volume scaninfo what i want admin page journals i want list volumes inline done connect volume previous list admin page i show form edit volume list scan info inline i want something like journal admin page name publisher url list volumes inline volume fields hreflinktovolumefull recorda volume fields hreflinktovolumefull recorda then volume admin page volume number fields list scan info inline scan info fields hreflinktoscaninfofull recorda scan info fields hreflinktoscaninfofull recorda what i tried defining model method create code trying use inside class defines volume inline admin work in words model volume inside something like def selflinkself return hrefadminjournaldbvolumesfull recorda selfvid selflinkallowtags true class volumeinlineadmintabularinline fields volumenumber selflink model volume extra but gives following error exception value volumeinlinefields refers field selflink missing form any idea thanks giovanni,2 print function python x in first snippet printing tuple last one invalid syntax if want use print function need enable via future import printfunction,instead simple debuglog print print error errornumber i would like use log function i expand required looking something like def logcondition message ifdo something printmessage perhaps something call like logcondition error errornumber but i get following syntax error print message syntaxerror invalid syntax is limitation print function way make work if equivalent print i could use i using python way,3 the returncode gets returned poll call also poll return none accessible via returncode attribute you already using code i sure problem when want update control process running use readline instead read latter wait entire output present former wait newline character to give full example using variable names subprocess import popen pipe selfmyproc popen dir shelltrue stdoutpipe stderrpipe selfmyprocpoll none selfparentappendupdateselfmyprocstdoutreadline selfparentappendupdate return code selfmyprocreturncode note might want strip readline result contain newline character edit to address confusion script output return code following first python script module level cannot return value would yield syntax error so differentiate output script return code gives the script output example read using selfmyprocstdoutreadline method every time external process produced line outputted text calling function would retrieve the return code however exit status integer gets passed child process parent process indicating state child process exited in python sysexit function most commonly value zero indicates success nonzero value depicts kind error say child process script looks like import sys do stuff print pass gets stdout sysexit return code executing external file let call testpy popen class get pass read selfmyprocstdout read selfmyprocpoll selfmyprocreturncode first poll the purpose return code parse child process output determine succeeded job free define exit codes for example could consider success failure kind invalid input given unknown error that way keep poll ing process based exit code returned poll directly know successful note bit less applicable case need output child process anyway still easier parse number string determine success,i would like get output print statements return status python subprocess along displaying logging info i using python windows xp how i get return code well here extract i reading output i redirect display wxpython textctrl separate thread selfmyprocpoll selfmyprocreturncode none still running check stdout txt selfmyprocstdoutreadselfreadblock txt add ui update queue selfparentappendupdatetxt else break,3 in song class add field artist modelsforeignkeyartist then song one artist artists many songs if want song many artists use manytomanyfield,i created model but i need song need artist how is possible i idea here model screenshot can please help thank class songmodelsmodel title modelscharfieldmaxlengthhelptextalbum name slug modelsslugfieldunique truehelptextmust unique artist modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength type modelsforeignkeycategory def unicodeself return selftitle update thank guys i think right solution if i found song belong album artist how possible class artistmodelsmodel name modelscharfieldmaxlength def unicodeself return selfname class albummodelsmodel name modelscharfieldmaxlength def unicodeself return selfname class songmodelsmodel song modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength song modelscharfieldmaxlength artist modelsmanytomanyfieldartist album modelsmanytomanyfieldalbum type modelsforeignkeycategory def unicodeself return selftitle,1 you one class per module required i would say related length module keeping long always good idea now structure declare subfolders packages for create initpy file subfolder done import modules like servicemodel import dbmodel use wrote dbmodeldbmodelclass notes naming files first letter uppercase really pythonic class name this means look like servicemodeldbmodeldbmodel servicemodel import dbmodel directly import class dbmodel module this done correct setting initpy content i know configure exactly some informations,i trying structure app python coming back cjava background i like approach one class per file i like project tree look like service database dbclasspy dbclasspy model dbmodelpy dbmodelpy theservicepy servicetests database dbclasstestspy dbclasstestspy model dbmodeltestspy dbmodeltestspy theservicetestspy is one class per file approach ok python is possible create packagesmodules way packages work like java packages net namespaces ie dbmodeltestspy import servicemodel def test dbmodel,2 in opinion i see i think regardless language good idea provides quick overview found file know single class i would make small exception helper classes though python allows nested classes also done quite nicely for possible well in example though simple load module thereby making classes functions available full namespace so say import servicemodel access class using servicemodeldbmodel to import things current namespace servicemodel import servicemodel import dbmodel need class then currently dbmodel,i trying structure app python coming back cjava background i like approach one class per file i like project tree look like service database dbclasspy dbclasspy model dbmodelpy dbmodelpy theservicepy servicetests database dbclasstestspy dbclasstestspy model dbmodeltestspy dbmodeltestspy theservicetestspy is one class per file approach ok python is possible create packagesmodules way packages work like java packages net namespaces ie dbmodeltestspy import servicemodel def test dbmodel,2 q you use class per file style python unusual q use servicemodel import stuff servicemodelinitpy generally frowned upon avoid import python my personal advice python cjava trying bend make look like otherlanguage cause frustration poor user experience keep mind stuff classes python modules functions instance import class module unless need instantiate class especially code uses instances dbmodel passed arguments functions methods need import part code servicemodeldbmodel import dbmodel looks bad prefer servicemodel import dbmodel avoid uppercase letters file names directory names group classes functions logically files rather grouping directories would class per file system,i trying structure app python coming back cjava background i like approach one class per file i like project tree look like service database dbclasspy dbclasspy model dbmodelpy dbmodelpy theservicepy servicetests database dbclasstestspy dbclasstestspy model dbmodeltestspy dbmodeltestspy theservicetestspy is one class per file approach ok python is possible create packagesmodules way packages work like java packages net namespaces ie dbmodeltestspy import servicemodel def test dbmodel,3 explanation what put e needs valid python identifier this includes underscores hyphens edateadded compiled successfully edate added fails run time case added defined alternatives the etag cosmetic trick work legal xml tags in reality python object attributes old rubbish objreallyfunkyattributenamedude source code one dud trick deserves better trick you keep pattern element creation ie need specify tag every time create element dateadded getattre dateadded using dateadded if schema control use underscore dateadded instead hyphendateadded,i using lxml efactory aka elementmaker creating xml documents i trying generate xml document similar url dateaddeddateadded url however using efactory i sure specify dash dataadded element it seems interpreting dash minus sign here docs i referring httplxmldetutorialhtmltheefactory here reproduce error lxml import etree lxmlbuilder import elementmaker e elementmaker url eurl dateadded edateadded xml urldateaddedmyobjectcreatedstrftime ymdthms nameerror global name added defined does anyone know trick get properly render element dash thank reading joe,3 a restful way upload image would use put request know image url usrbinenv python import httpclient h httpclienthttpconnection examplecom hrequest put filepicjpg open picjpg rb printhgetresponseread uploaddocspy contains example upload file multipartformdata basic http authentication it supports python x python you could use also requests post files multipartformdata usrbinenv python import requests response requestspost httphttpbinorgpost files file open filename rb printresponsecontent,i fairly new python using python i trying write python script pick file user machine image file submit server using rest based invocation the python script invoke rest url submit file script called this similar multipart post done browser uploading file i want python script if possible want add external libraries python would like keep fairly simple python script using core python install can one guide share script example achieve i want,2 you use print message directly enough print tuple extra arguments little addition previous answers python x print function statement printarg arg valid using print statement tuple arg arg this bit different print arg arg one see print aaa bbb aaa bbb print aaa bbb aaa bbb now addition themel answer case using expand argument tuple def pargs aargs args tuple def aargs print args args tuple nothing else used p bb bb result tuple tuple case expanding arguments p def pargs aargs arguments expanding p bb bb result tuple arguments given p so args correct use allowed statement,instead simple debuglog print print error errornumber i would like use log function i expand required looking something like def logcondition message ifdo something printmessage perhaps something call like logcondition error errornumber but i get following syntax error print message syntaxerror invalid syntax is limitation print function way make work if equivalent print i could use i using python way,1 it actually possible assign selfclass python really know the two classes compatible ways userdefined classes either oldstyle newstyle i sure use slots also pawnclass queen pawn object constructed queen constructor expected instance attributes might etc an alternative would sort copy constructor like class chesspieceobject classmethod def fromotherpiececls otherpiece return clsotherpiecex otherpiecey edit see also assigning instances class attribute python,i class describe chess pieces i make type piece board class example pawn queen keen etc i trouble pawn class i want convert queen object class pawn goto th row convert something another i class pawn def initself x selfx x selfy def moveself unit selfy selfy rawinputqueenrookknightbishopqrkb there changed may convert queen knight bishop rook selfy unit print accesible elif selfy unit selfy elif unit selfy else printcant move,3 an object python always instance class there way change without resorting dirty hacks in case probably consider refactoring logic instead letting piece move define kind controller moves pieces if pawn reaches last row controller easily replace piece another,i class describe chess pieces i make type piece board class example pawn queen keen etc i trouble pawn class i want convert queen object class pawn goto th row convert something another i class pawn def initself x selfx x selfy def moveself unit selfy selfy rawinputqueenrookknightbishopqrkb there changed may convert queen knight bishop rook selfy unit print accesible elif selfy unit selfy elif unit selfy else printcant move,1 in opinion create form login view djangocontribauth import authenticate login def myviewrequest username requestpost username password requestpost password user authenticateusernameusername passwordpassword user none userisactive user login store loginrequest user redirect success page else return disabled account error message else return invalid login error message user login store get path request check,i working store based authentication system using django trying make url one specifies store user trying log ex loginstorename login user requested store my question way using django built login formmechanism would create login form view,1 like said problem described hmm you essentially interested maintaining distribution latent hidden states would true quantities time point however seems confusing problem learning parameters hmm opposed simply inference known hmm you latter problem propose employing solution baumwelch designed former that model already use interestingly go coding discrete hmm problem get algorithm similar describe graphtheory solution the big difference solution tracking possible whereas correct inference algorithm like virterbi algorithm track likely the difference clear overlap range domain multiple possible states could potentially transition state your algorithm might add edges point i doubt compute next day effect count twice essentially anyway could use viterbi algortihm interested best guess recent day i give brief idea modify graphtheory solution instead maintaining edges states maintain fraction representing probability state correct one distribution sometimes called belief state at new day propagate forward belief state incrementing bucket probability parent instead adding edge adding floating point number you also make sure belief state properly normalized sums divide sum update after weight state observation since noisy observation go set impossible states zero probability renormalize you distribution underlying quantities conditioned observations i skipping lot statistical details give idea edit questions the answer question really depends want want distribution recent day get away onepass algorithm like i described if however want correct distribution quantities every single day going backward pass well hence aptly named forwardbackward algorithm i get sense since looking go back step delete edges probably want distribution days unlike i originally assumed of course noticed information used future inform past speak exactly reason need backward pass well really complicated run exact algorithm starting end chain for good overview check christopher bishop piece tutorial videolecturesnet because mentioned addingdeleting edges let clarify algorithm i described previously keep mind single forward pass let total n possible permutations quantities belief state sparse vector n elements long called v the first step receive observation sum populate vector setting possible values probability renormalize the next step create new sparse vector v iterate nonzero entries v increment probability v entries v within then zero entries v possible according new observation renormalize v throw away v repeat forever v always correct distribution possibilities by way things get way complex noisy observations large states continuous states for reason pretty hard read literature statistical inference quite general,i problem game i making i think i know solutionor solution apply sure ‘pieces’ fit together how game works how approach number guessing gamewith twist algorithm users given items valuevalues change every day program aware change price for example apple pears oranges they get chance choose combo like ie apples pears oranges the output computer gets total valuein example currently the computer try guess which obviously won’t able get correctly first turn value quantityday valueday apple pears orange total the next turn user modify numbers total quantity percent may chose i’ll use example the prices fruit changeat random total value may change based alsofor simplicity i changing fruit prices example using example day game user returns value day here example quantityday changeday valueday quantityday changeday valueday i hope tables show right i manually space hopefully screen work let know i try upload screenshot i trying see i figure quantities timeassuming user patience keep entering numbers i know right restriction total value cannot i cannot within accuracy right user entering forever what i done far i taken values fruit total value fruit basket that’s given created large table possibilities once i list possibilities i used graph theory created nodes possible solution i create edgeslinks nodes dayfor example day day within change i delete nodes edgeslinks nodes user keeps playing i also delete entire paths path becomes dead end this great narrows choices i’m stuck i want narrow choices even i’ve told hidden markov problem trickier version states changingas see new nodes added every turn oldnonprobable ones removed helps i got amazing answerwith sample code python implementation baumwelch modelits used train data example implementation baumwelch what i think needs donethis could wrong now i narrowed results i basically trying allow program try predict correct based narrowed result base i thought possible several people suggesting solved hidden markov model i think i run several iterations datausing baumwelch model probabilities stabilizeand get better turns user the way hidden markov models able check spelling handwriting improve make errorserrors case pick basket deleted upon next turn improbable two questions how i figure transition emission matrix states first equal for example states equally likely something must used dedicate probability states changing i thinking using graph i made weight nodes highest number edges part calculation transitionemission states does make sense better approach how i keep track changes states as new baskets added old ones removed becomes issue tracking baskets i though hierarchical dirichlet process hidden markov modelhdphmm would i needed exactly sure apply sorry i sound bit frustratedits bit hard knowing problem solvable able conceptually grasp needs done as always thanks time advicesuggestions would greatly appreciated,3 i see would want could give try row x print shape row numpyreshaperow rowsizeshape in optinion darray easier handle so make much sense reshape dmatrix,consider following convenient looping idiom import numpy print shape x numpyarray b c print x print xshape row x print shape row rowshape this gives shape b c shape b shape c my question one preserve convenient row x idiom returning arrays shape case thanks a function converts shape subarray would fine eg row x print shape somefuncrow rowshape returning shape b,1 problem analysis would dynamic nature python in fact set modules used may dependent runtime variable ie modules could imported used certain runtime conditions may best way pretty decent test coverage code use coveragepy output check modules loaded test execution,in general i would like understand exactly code code projects actually using big framework first i want know imports possibly static analysis possible imports actually used for first problem i could use regexp course i would like find cleaner way i see astinspectparser and second problem i able find automatically imports actually unused i edit second issue maybe best way simple import hook records everything imported call default importing mechanisms so i tried something like class myloaderobject loader object def initself selfloaded set def findmoduleself modulename packagenone printrequesting modulename selfloadedaddmodulename return self def loadmoduleself fullname fp pathname stuff impfindmodulefullname imploadmodulefullname fp pathname stuff but trying import random i get future import division importerror no module named future which i think means i missing something i found simple example using imp import introspection hints,1 refindallrss alice bob charlie sign s returns probably want alice bob charlie otherwise ss possibly match empty string end zeroormore zeroormore equal zerolength other possibility apart pop would refindallrss alice bob charlie refindallrss alice bob charlie return exactly need included whitespace beginning alice bob charlie,i text alice bob charlie i would like get pairs word whitespace that alice bob charlie in python i tried refindallrss alice bob charlie almost works adds empty pair end how get rid except pop also i really understand matches charlie whitespace finish edit clarify i want first pair ie word whitespace the last one word whitespace one i want get rid without pop possibly,1 try changing require least character whitespace refindallrss alice bob charlie alice bob charlie,i text alice bob charlie i would like get pairs word whitespace that alice bob charlie in python i tried refindallrss alice bob charlie almost works adds empty pair end how get rid except pop also i really understand matches charlie whitespace finish edit clarify i want first pair ie word whitespace the last one word whitespace one i want get rid without pop possibly,1 maybe best method works import struct structpackf structunpacki print,from ar drone developer guide the number − stored memory bit word whose value bf ccccd according ieee format this bit word considered holding bit integer value − is easy way builtin functionsexisting modules python,3 ok i fixed using kwargs although verbose equivalente django templates filter contextfilter def rendercontext value kwargs renders filtered value string template using context environment caller template kwargs kwargsupdatecontext ctx kwargs else ctx context render string template minitemplate environmentfromstringvalue return minitemplaterenderctx usage user listofusers greetingsuserlocalerenderuseruser endfor,i developed custom system jinja based following filter simplified contextfilter def rendercontext value renders filtered value string template using context environment caller template minitemplate environmentfromstringvalue return minitemplaterendercontext this allows example create following context context user name joel locale es greetings en hi username es â¡hola username and use like templates greetingsuserlocalerender that works perfectly now imagine i array users instead single one i following django templates work jinja variable user context user listofusers greetingsuserlocalerender endfor is anything i could add new variable user context i use contextfilter i need add name value i want work thank much help,1 once handler another url change url without redirecting if need maintain state original url get back encode get parameters url redirecting back also sure already deletion record really handled post get hope helps,i view delete record clicking anchor index pagei wanna redirect current page running viewin urlspy r airagencypkeyazaztourdeleteptouridd airagencyviewsdeletetour r airagencypkeyazaz airagencyviewsindex viewspy def deletetourrequestkeytourid tourtourobjectsgetpktourid tourdelete topnewsnewsobjectsfilteruseragentpositionagentcodeidagnidorderby actiondate return rendertoresponse airagencyindexhtml topnews topnewscontextinstancerequestcontextrequest imagine browser address httpairagencymastane i click anchor redirect deletetour viewafter deleting recoredbrowser locate url httpairagencymastanetourdeleteairagencyindexhtml i wanna redirect first url httpairagencymastane note i need requestcontext objecttooi mean httpresponseredirect good tnx advance,1 i found code might help thread urllib import urlopen threading import timer url httpwwwpythonorg def handlerfh fhclose fh urlopenurl timer handlerfh tstart data fhread tcancel,overview i using urlopen python urllib package http post form windows xp machine remote apache webserver instance builtin web sharing mac os x the sent data contains identifier data checksum data sent server responds acknowledgement the checksum data used check everything arrived fine order the problem usually works great however sometimes internet connection bad often client sending data uses wifi g connection this results internet connection loss arbitrary amount time urlopen contains timeout option make sure block program continue this i want problem urlopen stop socket continuing send whatever data still send timeout occurred i tested code i show trying send large bit data laptop i would see network activity show activity i stop wireless laptop wait function times reactivate wireless data transfer would continue program listening responses anymore i even tried exit python interpreter would still send data control handed windows somehow causes the timeout i understand works like it checks idle response time pythondev adding socket timeout urllib if set timeout open connection start counter try send data wait response point receiving response timer runs timeout exception called note sending data seem count activity far timeout timer concerned urllib times doesnt close socket connection close urllib connection apparently somewhere stated socket closeddereferencedgarbage collected calls close function waits data sent closing socket however also shutdown function stop socket immediately preventing data sent socketshutdown vs socketclose httpdocspythonorglibrarysockethtmlsocketsocketclose what i want i want connection shutdown timeout occurs otherwise client able tell data received properly might try send i rather kill connection try later knowing data probably send successfully server recognize checksum match here part code i used test the tryexcept parts yet work i expect help also appreciated as i said i want program shutdown socket soon timeout exception raised urllib import urlencode urllib import urlopen httperror urlerror import socket import sys class uploader def initself selfurl http selfdata urlencode fakerange range print data generated def uploadself try f urlopenselfurl selfdata timeout returncode fread except urlerror httperror msg returncode strmsg except socketerror returncode socket timeout else returncode im def main upobj uploader returncode upobjupload returncode print success else print maybe fail print returncode print the end name main main,1 if want collect results multiple greenlets modify printhead return result use get method collect put joinall totalresult xget x jobs actually joinall even necessary case if printhead looks like def printheadurl print starting url return urlliburlopenurlread then totalresult list size containing responses requests,here i want make modificatins setting i want response multiple api calls within single request made server api calls i want combine results return response until pretty much everything follows given examples gevent documentation now catch i want pass response incremental way first api call returned result i return result frontend one long waited request wait api calls pass request frontend i tried code i dont know proceed setting the gevent joinall join block untill greenlets finished getting responses any way i procceed gevent setting code i using given link httpsbitbucketorgdenisgeventsrctipexamplesconcurrentdownloadpy here joinall last statement waits urls complete giving responses i want non blocking i process responses callback function printhead return incrementally usrbinpython copyright c denis bilenko see license details spawn multiple workers wait complete urls httpwwwgooglecom httpwwwyandexru httpwwwpythonorg import gevent gevent import monkey patches stdlib including socket ssl modules cooperate greenlets monkeypatchall import urllib def printheadurl print starting url data urlliburlopenurlread print bytes r url lendata data jobs geventspawnprinthead url url urls geventjoinalljobs,1 requests library need you install pip install requests httpdocspythonrequestsorgenlatestuserquickstartpostamultipartencodedfile url httphttpbinorgpost files file open reportxls rb r requestsposturl filesfiles,i fairly new python using python i trying write python script pick file user machine image file submit server using rest based invocation the python script invoke rest url submit file script called this similar multipart post done browser uploading file i want python script if possible want add external libraries python would like keep fairly simple python script using core python install can one guide share script example achieve i want,2 if decide use httpresponseredirect try return httpresponseredirectrequestmetaget httpreferer,i view delete record clicking anchor index pagei wanna redirect current page running viewin urlspy r airagencypkeyazaztourdeleteptouridd airagencyviewsdeletetour r airagencypkeyazaz airagencyviewsindex viewspy def deletetourrequestkeytourid tourtourobjectsgetpktourid tourdelete topnewsnewsobjectsfilteruseragentpositionagentcodeidagnidorderby actiondate return rendertoresponse airagencyindexhtml topnews topnewscontextinstancerequestcontextrequest imagine browser address httpairagencymastane i click anchor redirect deletetour viewafter deleting recoredbrowser locate url httpairagencymastanetourdeleteairagencyindexhtml i wanna redirect first url httpairagencymastane note i need requestcontext objecttooi mean httpresponseredirect good tnx advance,1 if need requestcontext object showing delete success message use djangocontribmessages framework,i view delete record clicking anchor index pagei wanna redirect current page running viewin urlspy r airagencypkeyazaztourdeleteptouridd airagencyviewsdeletetour r airagencypkeyazaz airagencyviewsindex viewspy def deletetourrequestkeytourid tourtourobjectsgetpktourid tourdelete topnewsnewsobjectsfilteruseragentpositionagentcodeidagnidorderby actiondate return rendertoresponse airagencyindexhtml topnews topnewscontextinstancerequestcontextrequest imagine browser address httpairagencymastane i click anchor redirect deletetour viewafter deleting recoredbrowser locate url httpairagencymastanetourdeleteairagencyindexhtml i wanna redirect first url httpairagencymastane note i need requestcontext objecttooi mean httpresponseredirect good tnx advance,1 i think would refindall ss,i text alice bob charlie i would like get pairs word whitespace that alice bob charlie in python i tried refindallrss alice bob charlie almost works adds empty pair end how get rid except pop also i really understand matches charlie whitespace finish edit clarify i want first pair ie word whitespace the last one word whitespace one i want get rid without pop possibly,1 for coming google heres example config nginx server listen ssl default servername examplecom ssl sslcertificate etcnginxservercrt sslcertificatekey etcnginxserverkey addheader cachecontrol public mustrevalidate addheader cachecontrol nocache expires addheader stricttransportsecurity maxage includesubdomains location fastcgipass localhost fastcgiparam pathinfo fastcgiscriptname fastcgiparam requestmethod requestmethod fastcgiparam contenttype contenttype fastcgiparam contentlength contentlength fastcgiparam serverport serverport fastcgiparam servername servername fastcgiparam serverprotocol serverprotocol fastcgipassrequestheaders include fastcgiparams location static root homemyappapplication location faviconico root homemyappapplicationassets accesslog lognotfound,i planning sell products charging credit cards thus using ssl critical djangopowered website and i naive my initial django setup plan using apache webserver using modwsgi communicate django static media served apache all seemed good ssl protocol comes plans i using ssl protocol user account configuration pages whole purchase sequence maybe django admin i checked official documentations googled answers rather confusing what would recommended way implementing ssl setup any suggestions first time ssl implementer website from page seems like included nginx stack couldn done without thanks,3 a good way dealing associate accountloginwidget view like viewconfigname loginwidget renderer templatesaccountloginwidgetpt def loginwidgetrequest return username you able visit httpyourapploginwidget get back widget html what left call view include resulting html template that instead span metalusemacroload accountloginwidgetptspan want something like span talreplacestructure renderview loginwidget span renderview however exist templates provide it best use before render event httpdocspylonsprojectorgprojectspyramiddevnarrhookshtmlbeforerenderevent pyramidevents import subscriber pyramidevents import beforerender pyramidview import renderviewtoresponse subscriberbeforerender def addrenderviewglobalevent event renderview lambda name renderviewtoresponsecontext request name secureubody done this approach also help ever need reload widgets dynamically ajax,i would like able easily create ajax widgets backed chameleon pyramid server side does pyramid provide plumbing code would make writing widgets easy my current approach i home view uses homept renderer homept uses macro basept defines page structure provides slot homept fill basept also uses login widget macro i written see accountloginwidgetpt in theory sounds greati reusable login widget i use many pages current approach work well my login widget uses variables like username renderer server needs define i want login widget rendering independent possible but current way things home view code needs aware login widget needs provide username formrender variables dictionary definitely good i feel like i close right idea missing things any thoughts basept html headhead body div idcontainer div idheader span metalusemacroload accountloginwidgetptspan div div idmiddle span metaldefineslotcontentspan div div idfooterdiv div body html homept div metalusemacroload basept span metalfillslotcontent divmy stuffdiv span div accountloginwidgetpt span metaldefinemacroaccountloginwidget script typetextjavascript function fnmyfunction function loginform submitfunctione epreventdefault ajax call postsomeurl somedata functionresponse accountloginwidget htmlresponse return jquery define entry point documentreadyfunction documentmyfunction script div idaccountloginwidget div idloginbar talconditionnot username formrendererbegin form formrendererend span talconditionloginfailedlogin failedspan div idforgotpasswordlinka hrefforgot passwordadiv div idcreateaccountlinka hrefsignupurlcreate accountadiv div div talconditionusername welcome strongusernamestrong hreflogouturllogouta div div span,3 i think slowdown comes number times iterate sequences longestsequnder iterations takes toll here smoking fast version based combination code answer posted note primes lazy bind def vs defn defn prime n let r int mathsqrt n loop cond n false r true zero rem n false else recur inc def primes filter prime iterate inc defn makeseqaccumulator x amp xs map first iterate fn sum amp sum x xs def primesums conj makeseqaccumulator primes defn euler goal loop c let bots reverse take c primesums tops take c reverse takewhile goal last bots rest primesums prime map tops bots recur inc c this finished ms machine user time euler elapsed time msecs,i recently started learn clojure decided practice euler problems get hang available data structures practice recursion looping i tried various approaches problem matter i finding solution never finished after i looked others i guessed i take forever either i typed equivalent algorithm python see problem lies lack understanding clojure thing java setting python finished seconds for primes python version finished sec clojure i posting clojure version created specifically match python code can help understand difference performance should i use uncheckedadd type hints primitives so clojure defn prime n let r int mathsqrt n loop cond n false r true zero rem n false recur inc defn primes filter prime iterate inc defn cumulativesum reduce fn v x conj v last v x first rest defn longestsequnder n longest prime seq sum n let ps vec takewhile n primes prime numbers n primeset set ps set testing inclusion cs cumulativesum ps cnt count ps maxlen count takewhile n cs cannot longer sequences subsum fn j sum primes ith jth cs j get cs dec seqwithlen fn try length prime sequences return first sum prime loop try lowest sum cnt elements length sequence nil could find let j dec fix length subsum j n overshoot nil primeset sum prime inc j looked first recur inc shift window loop maxlen try longest sequence zero let j seqwithlen j subvec ps j recur dec assert longestsequnder let longestsequnder assert count assert reduce time reduce longestsequnder elapsed time msecs and python math import sqrt itertools import takewhile def isprimen xrange intsqrtn n return false return true def nextprimen isprimen n return n def primes true nextprimei yield def cumulativesums cs css si css si csappend css return cs def longestsequndern ps listtakewhile lambda p p n primes pss setps cs cumulativesumps cnt lenps maxlen lenlisttakewhilelambda n cs def subsumi j return csj csi else def intervalwithlengthm xrange cntm j sij subsumij sij n return none none sij pss prime return j return none none xrangemaxlen f intervalwithlengthm return psft assert longestsequnder assert sumlongestsequnder import timeit timeittimersumlongestsequnder main import longestsequndertimeit thanks,3 it looks like changing commented line the first sql statement appears running select stoplat stops running without quotes select stoplat stops,i strange bug i explain it occurs i combine python sqlite i table contains real field called stoplat when i run following code c conncursor cexecuteselect stoplat stops stoplat c print stoplat print typestoplat stoplat intstoplat i get following output stoplat type unicode traceback recent call last file extractdatatoolsextracttripspy line module stoplat intstoplat valueerror invalid literal int base stoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplatstoplat now i comment last line meaning i execute c conncursor cexecuteselect stoplat stops stoplat c print stoplat print typestoplat stoplat intstoplat i get following output type float type float type float type float type float meaning type stoplat depends whether i pass int really make sense it even gets stranger the following code c conncursor cexecuteselect stoplat stops stoplat c print stoplat print typestoplat stoplat stoplat print stoplat print typestoplat outputs type float type float type float type float type float type float type float type float can anyone explain going i reproduce problem without sqlite game ie code literals work expected,1 following joe shaw answer multithreaded code work expected i figured runcall method cprofile merely selfenable selfdisable calls around profiled function call simply whatever code want inbetween minimal interference existing code,project euler coding contests often maximum time run people boast fast particular solution runs with python sometimes approaches somewhat kludgey ie adding timing code main what good way profile long python program takes run,3 you use numpyexpanddim increase rank numpy array in xnparray in xshape out in npexpanddimsxaxisshape out,consider following convenient looping idiom import numpy print shape x numpyarray b c print x print xshape row x print shape row rowshape this gives shape b c shape b shape c my question one preserve convenient row x idiom returning arrays shape case thanks a function converts shape subarray would fine eg row x print shape somefuncrow rowshape returning shape b,1 in python x reading utf file accomplished using open onedat readdecode utf codecsopen onedat encoding utf read return python unicode object if want turn str asciibinary string unicode use sdecode utf in python x open onedat read open onedat encoding utf read the idea str pyx bytes pyx object contains binary representation string encoding without specifying encoding decode method turns proper unicode string unicode x str x btw utf binary data text nonascii encoding,i text file wordstxt contains english words let assume contains three words one two three i also three files onedat twodat threedat each files contains binary data representing transcription corresponding word format utf what i want i want combine wordstxt dats single document i would able print so i need something like lets name finaldat one wan two tu three ri correct th sign instead the important thing i must able load finaldat msword writer print i going accomplish python i really got stuck codecs encodes decodes,2 i looked selenium and running pure script meaning display start normal browser solution actually quite simple selenium import webdriver driver webdriverfirefox link httpyourlinkcom drivergetlink waits new page load whilelink drivercurrenturl timesleep redirectedurl drivercurrenturl for usecase enough selenium also interact forms send keystrokes website,i parse website python they use lot redirects calling javascript functions so i use urllib parse site help i find destination url returned html code is way access dom call correct javascript function python code all i need url redirect takes,3 if images width could wrap images container give container width equal images width float images check fiddle httpjsfiddlenetydusz i know python might stupid hopefully get i mean div clasimagewrapper images print htmlpage img src folders div css imagewrapper width image width imagewrapper img float left,i images read database python form images print htmlpage img src folders giving output static htmlpage like img src folderimagejpg img src folderimagejpg img src folderimagejpg img src folderimagejpg i would like images displayed grid five columns i tried position table output could get working syntax tr td i wondering i could put div let css stylesheet handling gridlayout i know could elegant solution generating wellformatted simple htmlpage generated pythoncode i hope someone clue hint trick thanks lot advance,1 using lxml import lxmlhtml lh htmltable table tr tr tr tr tr table nums doclhfromstringhtmltable trn zipdocxpath tr nums trattrib id n printlhtostringdocprettyprinttrue yields table tr idtr tr idtr tr idtr tr idtr tr idtr table,so i table i want go python find tr tags turn tr idnumber here number number list format what best way so basically first tr would become tr id second would become tr id etc it not always sequential see going the table stored string i specify currently string multiple tags ie htmltabletrblahtrtrblahblahtrtablehtml very oversimplified i want search instances tr string replace tr idnumber based position tr versus next number list,3 myarrayx x myarrayx x,i large d numpy array i know pair indices represent one element array i want set element surrounding 㗠area equal zero i attempted using slicing technique arrayx however although x previously defined invalid slice i would appreciate suggestions i accomplish i new python,2 the articles linked tell install cython buildout need write access sitepackages folder there ways able run buildouts run root install cython system python sitepackages usually want avoid compile python this may option want use version python already system there buildout configurations let build version python inside buildout use virtualenv this create buildout folder complete virtual environment python including sitepackages folder this usually best way run buildout use system python python already installed system wide i suggest make using virtualenv part installation instructions software,i facing problem cython buildout one part module build cython c file pyx file i already try many solutions sean gillies blog adding pyproj buildout gefira blog â» getting rid ‘no cython trying pyrex…’ zcbuildout but ends error importerror no module named cythondistutils this append buildout load setuppy cython module note setuppy functional called directory interpreter buildout bin directory thanks help,2 the problem newer jquery versions send braces part name cherrypy like one solution catch cherrypy side cherrypyexpose def savethevaluesself kw values kwpop values code save values another solution let jquery use traditional method sending params serializing params traditional flag set true the following works cherrypy code unaltered var arr string array jquerypost savethevalues param values arr true functiondata stuff returned data json,i jquery post something like var arr string array jquerypost savethevalues values arr functiondata stuff returned data json and goes cheerypy function cherrypyexpose def savethevaluesself valuesnone code save values but running javascript returns bad request unexpected body parameters values how i send array cherrypy,3 have moved templates dpastetemplates folder project template folder ie templatedirs settings,this basehtml doctype html public wcdtd xhtml transitionalen httpwwwworgtrxhtmldtdxhtmltransitionaldtd html xmlnshttpwwwworgxhtml xmllangen langen div stylewidth marginleft block main endblock div i installed dpaste according docs now i go link mypaste blank screen shows i guessing something wrong basehtml sure i might completely wrong,1 from codes i thought maybe newcountercount equals newcounter classcount the problem moment sentence question instructions newcounter counter newcounter counter newcounterclasscount created newcounter newcounter modified class attribute countercount objects newcountercount newcountercount existence equals real meaning see creation newcounter class counter count def initself selfclasscount print countercount before countercount the result newcounter counter print nnewcounterdict newcounterdict the result print newcountercount newcountercount the result print countercount after countercount the result newcounter dict namespace instance newcounter print newcountercount prints print countercount however count string count namespace newcounter say attribute count namespace created instance how possible that instance created without assignement count identifier inside init real creation attribute field newcounter say creation instance attribute the consequence instruction print newcountercount newcountercount evaluated interpreter find instance attribute newcounter namespace goes class instance search key count class namespace finds count key class attribute take value object countercount value display response instruction a class instance namespace implemented dictionary first place attribute references searched when attribute found instance’s class attribute name search continues class attributes httpdocspythonorgreferencedatamodelhtmlthestandardtypehierarchy so newcountercount equals newcounterclasscount means value newcountercount even one really exist value class attribute newcounter class count here english verb feature language tests identities two objects means considered when newcounterclasscount executed class attribute countercount affected the namespaces newcounter newcounter remain empty mechanism going class find value countercount followed at end newcountercount executed time instance attribute count created field newcounter object count appears namespace newcounter it overwrite anything nothing preceding instance dict no change affects newcounter countercount the following code shows explicitly underlying events execution itertools import islice class counter count def initself print countercount first dn selfcount first countercountidcountercount selfcountidselfcount selfclasscount print countercount second dn selfcount second dn idcounter idself countercountidcountercount selfcountidselfcount idcounteridself def displayli iterli ch nn lenchlenchlstrip n n x itnext print chx dict ch else stridx display countercount at start countercount print nn c counter c counter display cdict cdict ccount ccount ncountercount countercount print nn c counter c counter print display cdict cdict cdict cdict ccount ccount ccount ccount cclasscount cclasscount cclasscount cclasscount ncountercount countercount print nn cclasscount n cclasscount display cdict cdict cdict cdict ccount ccount ccount ccount cclasscount cclasscount cclasscount cclasscount ncountercount countercount print nn ccount n ccount display cdict cdict cdict cdict ccount ccount ccount ccount cclasscount cclasscount cclasscount cclasscount ncountercount countercount result countercount at start c counter countercount first selfcount first countercount second selfcount second idcounter idself cdict ccount countercount c counter countercount first selfcount first countercount second selfcount second idcounter idself cdict cdict ccount ccount cclasscount cclasscount countercount cclasscount cdict cdict ccount ccount cclasscount cclasscount countercount ccount cdict cdict count ccount ccount cclasscount cclasscount countercount an interesting thing add instruction selfcount countercount before line selfclasscount observe changing results in conclusion point concerning class mechanism searching attribute mechanism misleading ignored,i question class python the documentation says class class class instance belongs so i conducted series experiments class counter count def initself selfclasscount newcounter counter print newcountercount the result newcounter counter print newcountercount the result print newcounterclasscount newcountercount result true everything goes well then i enter code follows newcounterclasscount print newcountercount result print newcounterclasscount result print newcountercount result print newcounterclasscount result print newcounterclasscount newcountercount result true from code i thought maybe newcountercount equals newcounter classcount following code surprised newcountercount print newcountercount result print newcounterclasscount result print newcountercount result print newcounterclasscount result print newcounterclasscount newcountercount result false why newcountercount changed newcounterclasscount remained what i changed newcountercount newcounterclasscount newcountercount became false what world attribute class ?,3 you need separate mixin templateview already templateresponsemixin simply override gettemplatenames simplecategoryview subclass class simplecategoryviewtemplateview def gettemplatenamesself return selfgetcategorytemplatename,i model using djangomptt also field using specific template via templatenamefield i like able use generic templateview pass mixin using templatenamefield here model djangodb import models mpttmodels import mpttmodel mpttfields import treeforeignkey class categorymanagermodelsmanager def getself kwargs defaults defaultsupdatekwargs fullslug defaults defaults fullslug defaults fullslug defaults fullslug return supercategorymanager selfgetdefaults class categorympttmodel title modelscharfieldmaxlength description modelstextfieldblanktrue helptext a brief description category no html allowed slug modelsslugfieldhelptext prepopulates title field fullslug modelscharfieldmaxlength blanktrue templatename modelscharfieldmaxlength blanktrue helptextexample categoriescategoryparenthtml if provided system use categoriescategorydetailhtml parent treeforeignkey self nulltrue blanktrue relatedname children objects categorymanager class meta verbosename category verbosenameplural categories def saveself args kwargs origfullslug selffullslug selfparent selffullslug ss selfparentfullslug selfslug else selffullslug selfslug obj supercategory selfsaveargs kwargs origfullslug selffullslug child selfgetchildren childsave return obj def unicodeself return selftitle selffullslug here view djangocoreexceptions import improperlyconfigured djangocoreurlresolvers import reverse djangoviewsgeneric import templateview detailview djangoviewsgenericdetail import singleobjecttemplateresponsemixin djangoutilstranslation import ugettext djangocontribsyndicationviews import feed storefrontcategoriesmodels import category class simplecategoryviewtemplateview def getcategoryself return categoryobjectsgetfullslugselfkwargs fullslug def getcontextdataself kwargs context supersimplecategoryview selfgetcontextdatakwargs contextcategory selfgetcategory return context and urls djangoconfurlsdefaults import patterns include url storefrontcategoriesmodels import category storefrontcategoriesviews import categoryview urlpatterns patterns urlr pfullslugw simplecategoryviewasviewtemplatename categoriescategorydetailhtml name categoryview how would i go adding mixin using templatenamefield view,1 given basehtml block main endblock replaced anything would get blank page my guess would case what going block are sure block name correct,this basehtml doctype html public wcdtd xhtml transitionalen httpwwwworgtrxhtmldtdxhtmltransitionaldtd html xmlnshttpwwwworgxhtml xmllangen langen div stylewidth marginleft block main endblock div i installed dpaste according docs now i go link mypaste blank screen shows i guessing something wrong basehtml sure i might completely wrong,1 look template use block main uses extrahead title headline content sidebar scriptfooter blocks,this basehtml doctype html public wcdtd xhtml transitionalen httpwwwworgtrxhtmldtdxhtmltransitionaldtd html xmlnshttpwwwworgxhtml xmllangen langen div stylewidth marginleft block main endblock div i installed dpaste according docs now i go link mypaste blank screen shows i guessing something wrong basehtml sure i might completely wrong,1 in view need make sure template pointing testblockhtml testbasehtml assuming using rendertoresponse would look something like return rendertoresponse testblockhtml if view function referencing testbasehtml get unextended template that design here link template documentation good measure,python django i new django templates trying simple template inheritance testbasehtml hello block tester fail endblock testblockhtml extends testbasehtml block tester pass endblock result hello fail the two templates directory added project settingspy file since finds base template i trouble finding able find child template thanks ideas try next,1 listinsert modifies list inplace returns none use like instead numlist numlistinsert numlist also particular reason using quoted numbers,numlist numlist numlistinsert numlist print numlist none i get i trying append first position list giving nonetype,3 listinsert returns none list,numlist numlist numlistinsert numlist print numlist none i get i trying append first position list giving nonetype,3 try numlistinsert without assignment,numlist numlist numlistinsert numlist print numlist none i get i trying append first position list giving nonetype,1 just use numlistinsert listinsert return none,numlist numlist numlistinsert numlist print numlist none i get i trying append first position list giving nonetype,1 the directly c coded interface potential much much faster the bottleneck interface python c marshalling arguments results may example involve copying strings converting python lists tofrom c arrays if loop makes several hundred calls data marshalled separately call recode loop c may able massively reduce bottleneck ctypes give option call existing functions directly of course depends exactly sort functions calling sort data passing around it may reduce overheads case i would still expect ctypes slower perhaps significantly your best best would put together sample code written way benchmark otherwise many variables definitive answer,i functions written c game project these functions get called quite lot times per second the functions written c raw speed now easiest way include functions python use ctypes the alternative write c extension python around functions takes quite bit extra effort so i wondered including initial loading dll big overhead ctypes i using python standard cpython release i want use external library like cython i know question asked i seen much information performance comparison two options,3 rows line inputfile r linesplit rowsappend dns r ip r description r,i troubles converting file content list dictionaries could advise file content hostexamplecomweb server hostexamplecomdns server hostexamplecomweb server hostexamplecomapplication server hostexamplecomdatabase server there multiple files side folder format at end i would like receive list dictionaries following format dns hostexamplecom ip description webserver dns hostexamplecom ip description dns server dns hostexamplecom ip description web server dns hostexamplecom ip description application server dns hostexamplecom ip description database server thank advance,1 first want split line then use zip zip together labels convert dictionary labels dns ip description line data outappenddictziplabels linesplit that one append line bit complex break makes list hostexamplecom web server linesplit takes labels list matches dns hostexamplecom ip description web server ziplabels linesplit takes tuple makes first item key second item theâ value dict,i troubles converting file content list dictionaries could advise file content hostexamplecomweb server hostexamplecomdns server hostexamplecomweb server hostexamplecomapplication server hostexamplecomdatabase server there multiple files side folder format at end i would like receive list dictionaries following format dns hostexamplecom ip description webserver dns hostexamplecom ip description dns server dns hostexamplecom ip description web server dns hostexamplecom ip description application server dns hostexamplecom ip description database server thank advance,3 assuming file infiletxt entries linestripsplit line openinfiletxt r output dictzipdns ip description e e entries print output ip description web server dns hostexamplecom ip description dns server dns hostexamplecom ip description web server dns hostexamplecom ip description application server dns hostexamplecom ip description database server dns hostexamplecom,i troubles converting file content list dictionaries could advise file content hostexamplecomweb server hostexamplecomdns server hostexamplecomweb server hostexamplecomapplication server hostexamplecomdatabase server there multiple files side folder format at end i would like receive list dictionaries following format dns hostexamplecom ip description webserver dns hostexamplecom ip description dns server dns hostexamplecom ip description web server dns hostexamplecom ip description application server dns hostexamplecom ip description database server thank advance,1 you use python module configuration file say configpy import import config,i using configparser project configuration file getting large i plan split maintain central config file points others i seen documentation configparser handle hierarchical configuration file structure can i somehow point one config file another automatically of course i could manually better yet create module handles using configparser lowlevel tool i sure i first tackle thisproblem know different package handles perhaps different approach altogether,1 maplambda x dictzipdns ip description tuplexstripsplit open inputfile,i troubles converting file content list dictionaries could advise file content hostexamplecomweb server hostexamplecomdns server hostexamplecomweb server hostexamplecomapplication server hostexamplecomdatabase server there multiple files side folder format at end i would like receive list dictionaries following format dns hostexamplecom ip description webserver dns hostexamplecom ip description dns server dns hostexamplecom ip description web server dns hostexamplecom ip description application server dns hostexamplecom ip description database server thank advance,1 you use loggerexception method for example logger logginggetloggermyloggername myurl urlstotest try test url except exception baseexception really want catch python exceptions loggerexceptionsomething weird happened that display traceback url raise exceptions still continue test url,i wrote program python yesterday checks hundreds urls validity mainly currently program runs url valid throws many exceptions crashes i using urlliburlopen visit links is anyway program ignore exceptions continue running log somewhere lines code caused problem,2 only firewire camera maker included vfw driver it also possible grab data directshow filter camera maker might provide instead,i trying capture frames firewire cam firefyl mv using opencv python windows xp my example finds camera use capture cvcapturefromcam cant capture frames frame cvqueryframecapture here httpopencvwillowgaragecomdocumentationpythonhighguireadingandwritingimagesandvideohtmlcapturefromcam write currently two camera interfaces used windows video windows vfw matrox imaging library mil two linux vl firewire ieee so possible use firewire cam opencvpython winxp is simple workaround,1 import config simple flexible powerfull since anything might dangerous configpy safe place,configparser much debated vanilla configuration parser python however simply import config configpy python code sets configuration parameters what proscons two approaches configuration when i choose,3 imo comes matter personal style do intend rd parties edit config if maybe makes sense natural configuration style la configparser technical may far heads target audience many popular projects fabric django use native configuration style essentially python module fabry fabfilepy django settingspy overall going lot flexibility using native approach importing module simply anything want file including defining functions classes etc another python module importing,configparser much debated vanilla configuration parser python however simply import config configpy python code sets configuration parameters what proscons two approaches configuration when i choose,2 this completley depends needs goals script one way really isnt better different for detailed discussion pythons config parsers including configparser config modules see python wiki configparsershootout,configparser much debated vanilla configuration parser python however simply import config configpy python code sets configuration parameters what proscons two approaches configuration when i choose,3 xml xinclude support if use lxml parsing xml file go find configuration files included xinclude statements,i using configparser project configuration file getting large i plan split maintain central config file points others i seen documentation configparser handle hierarchical configuration file structure can i somehow point one config file another automatically of course i could manually better yet create module handles using configparser lowlevel tool i sure i first tackle thisproblem know different package handles perhaps different approach altogether,1 yes small difference there discussion rpython recently blog post explained readability difference work generators keeps type original technically get thing brand new list still points objects choose whichever one like better although bit faster personally i agree blog post listold readable to answer comment specific difference python import dis def colonx return x def newlistx return listx disdiscolon loadfast x loadconst none loadconst none buildslice binarysubscr returnvalue disdisnewlist loadglobal list loadfast x callfunction returnvalue why listold slower i think slicing mechanism need loadglobal callfunction list constructor entire operation handled c,old what difference following two lines new old new listold update i already accepted ubershmekel answer later i learned interesting fact faster small list elements list faster larger list elements python s mtimeit listrange loops best usec per loop python s mtimeit listrange lista loops best usec per loop python s mtimeit listrange loops best usec per loop python s mtimeit listrange lista loops best usec per loop,3 if old list old elements old kind container old maybe tuple string listold list elements ie old string foo old string foo listold wille list f,old what difference following two lines new old new listold update i already accepted ubershmekel answer later i learned interesting fact faster small list elements list faster larger list elements python s mtimeit listrange loops best usec per loop python s mtimeit listrange lista loops best usec per loop python s mtimeit listrange loops best usec per loop python s mtimeit listrange lista loops best usec per loop,3 the biggest issue i see import config know happen import yes get set symbols naturally referenced using style interface but code configuration file also whoknowswhat now completely trust users allowing whatever feel like config file possibly good thing however unknown quantities want protect users configuration file traditional format safer secure,configparser much debated vanilla configuration parser python however simply import config configpy python code sets configuration parameters what proscons two approaches configuration when i choose,3 do text formatselflineedittext cexecuteselect id name contacts nome like formattext include wildcard match string well also please consider using note corrected syntax cexecuteselect id name contacts nome like text cexecuteselect id name contacts nome like text make code safe sql injection attacks correctly handle cases text includes special characters like single quote instance name o reilly,i got address book names people i use following code perform search name column register text formatselflineedittext cexecuteselect id name contacts nome like formattext row c registerappendrow selflistwidgetadditemstrrow selflistwidgetadditemstrrow register selflistwidgetadditemno result the name column name surname like john smith the code works fine remember entire name starting letters but i want results show matches beginning names so i got names simonne welsh adam loyd john smith type letter s give result names simone welsh john smith how i,1 use backtick operator verbatim css backgroundimage webkitlineargradienttop fff eee the “official” pypi version clevercss maintained may feature get updated version github,i trying use webkitlineargradient inside clevercss however i try compile i get error typeerror enough arguments format string here clevercss button backgroundimage webkitlineargradienttop fff eee if i throw clevercssconvert error i get i see parenthesis special meaning clevercss i unsure result is way clevercss process,2 as thomas k said sysexecutable variable contains running interpreter to call process pass first argument subprocesspopen subprocesspopensysexecutable pathtoscriptpy,i main process creates child processes using subprocesspopen those child processes turn may many create new processes i want able use sysexecutable root process is way done without using environment variables passed process process,1 result dict lig open ouitxt base lig num sep txt ligstrippartition base resultnumstrip txtstrip,i currently looking process parse information txt file the file appears tab delimited i looking parse base value ie dictionary key company name ie xerox corporation dictionary value so example i look dictionary key xerox corporation would returned respective value i tried parsing txt file csv reading entry every nth line unfortunately pattern nth number varies is way capture value preceeding term base example term follows make dictionary entry many thanks,1 well entries seperated two newlines the second line always base one the data first tab base key last company name import urllib inputfile urlliburlopenhttpstandardsieeeorgdevelopregauthouiouitxt data inputfileread entries datasplitnn ignore first last entries real entries entry entries parts entrysplitnsplitt companyid partssplit companyname parts dcompanyid companyname some results fe leica microsystems schweiz ag ac weg bf caly networks cc printcounts llc mtx inc crosscomm corporation sony tektronix corp asante technologies emc corporation marconi electronics ltd anritsu corporation microcom proteon inc cogent data technologies baoding galaxy electronic technology coltd e hon hai precision ind coltd videofon mv ad radiolan inc ef vaddio goliath solutions,i currently looking process parse information txt file the file appears tab delimited i looking parse base value ie dictionary key company name ie xerox corporation dictionary value so example i look dictionary key xerox corporation would returned respective value i tried parsing txt file csv reading entry every nth line unfortunately pattern nth number varies is way capture value preceeding term base example term follows make dictionary entry many thanks,1 def ouiparsefn ouitxt openfn ouif content ouifread block contentsplit nn lines blocksplit n lines hex lines first block continue assert base lines oui linessplit company linessplit lenlines division linesstrip street linesstrip city linesstrip country linesstrip yield ouiinfo listouiparse,i currently looking process parse information txt file the file appears tab delimited i looking parse base value ie dictionary key company name ie xerox corporation dictionary value so example i look dictionary key xerox corporation would returned respective value i tried parsing txt file csv reading entry every nth line unfortunately pattern nth number varies is way capture value preceeding term base example term follows make dictionary entry many thanks,1 firstly ensure crawler returns html unicode text eg scrapy method responsebodyasunicode exactly once unicode text cant make sense step going unicode text equivalent ascii text lies httppypipythonorgpypiunidecode unidecode import unidecode print unidecodeuuueb the output bei jing,making crawler get text html inside using beautifulsoup i open url using urllib library converts automatically html using portuguese accents like 㣠㳠㩠㵠another characters like aâ³ aâ¡ aâ´aâ§ i want get words without accents contrã£â¡rio contrario i tried use algoritm bu one works text uses words like olã¡ coraã§ã£o contrã¡rio def stripaccentss return joinc c unicodedatanormalize nfd unicodedatacategoryc mn,1 import urllib f urlliburlopen httpstandardsieeeorgdevelopregauthouiouitxt dicts sstrip f base print xerox corporation,i currently looking process parse information txt file the file appears tab delimited i looking parse base value ie dictionary key company name ie xerox corporation dictionary value so example i look dictionary key xerox corporation would returned respective value i tried parsing txt file csv reading entry every nth line unfortunately pattern nth number varies is way capture value preceeding term base example term follows make dictionary entry many thanks,1 the cmdcmd class something would help build shelllike application likewise cmd nice upgrade module with build shell application command history help menus smart command parsing don build repl scratch modules probably suffice needs,i coding data entry system python user also able submit commands exactly like python shell works example sas r interfaces i would like know code shell for examnple provide prompt cannot deleted user eg prompt python receive input user furthermore entry submitted user cannot go back like dos prompt cannot go line speak can anybody help,3 you want getattr pass default value hasattr,groupnamegroup none error attributeerror nonetype object attribute group how check object attribute,3 for getting around daylight saving etc none answers particularly helped the code works gmt def getutcfromlocaldatetime localtznone assert datetimeclassname datetime localtz none localtz pytztimezonesettingstimezone django eg europelondon localtime localtznormalizelocaltzlocalizedatetime return localtimeastimezonepytzutc import pytz datetime import datetime summeram datetime getutcfromlocalsummeram datetimedatetime tzinfoutc winteram datetime getutcfromlocalwinteram datetimedatetime tzinfoutc,how i convert datetime string local time string utc time i sure i done find so hopefully help others future clarification for example i local timezone i like generate string equivalent utc time also httplucumrpocooorgeppursimuove note general possible dst issues unique conversion local time utc time,1 in python motto better say sorry ask permission i would suggest find needs eventually something like try something groupnamegroup except someexception e act way,groupnamegroup none error attributeerror nonetype object attribute group how check object attribute,1 you may want look import import modules knowing name string dir get names objects module attributes functions etc inspectisclassgetattrmodule ref object name identify classes among objects module issubclass identify subclasses given class explained with tools identify classes given module inheriting given class i using mechanism dynamically instantiate classes given module updates automatically taken account upper level,i following folder structure myproject app somemodulepy somemodulepy app someothermodulepy someothermodulepy inside modules somemodulepy example class extends base class case producer what i trying dynamically load class to i list installed apps looks like installedapps app app i trying write function check app package particular producer class ensure extends producer base class something like moduleclass somemodulesomeclass loop package installedapps tuple app installapps try moduleclass found app appsomemodulesomeclass yes appsomemodulesomeclass no class found subclass producer exception importerror pass i tried experimenting imp importlib seem handle kind import is anyway able achieve,3 python follows eafp motto claimed better style try handle exception so try try gr groupnamegroup except attributeerror complain else gr none goon but beware i sure none want maybe none would thing,groupnamegroup none error attributeerror nonetype object attribute group how check object attribute,1 well i found following much faster matplotlib import pyplot plt matplotlibcollections import linecollection lc linecollectionpointsedges fig pltfigure pltgcaaddcollectionlc pltxlimpointsmin pointsmax pltylimpointsmin pointsmax pltplotpoints points ro figsavefig fullfigurepng is still possible faster,i points edges type format points numpyarray edges numpyarray edges indices points start end coordinates edges given pointsedges i looking faster better way plot currently i matplotlib import pyplot plt x pointsflatten pointsflatten pltplotxedgest yedgest edges pltplotx ro points pltsavefig figurepng i read linecollections unsure use is way use data directly what bottleneck some realistic test data time plot seconds points numpyrandomrandint edges numpyrandomrandint,1 you could also single plot call considerably faster two though probably essentially adding linecollection import numpy import matplotlibpyplot plt points numpyarray edges numpyarray x pointsflatten pointsflatten pltplotxedgest yedgest linestyle color markerfacecolor red marker pltshow,i points edges type format points numpyarray edges numpyarray edges indices points start end coordinates edges given pointsedges i looking faster better way plot currently i matplotlib import pyplot plt x pointsflatten pointsflatten pltplotxedgest yedgest edges pltplotx ro points pltsavefig figurepng i read linecollections unsure use is way use data directly what bottleneck some realistic test data time plot seconds points numpyrandomrandint edges numpyrandomrandint,1 alternative jsondumps indent parameter python pretty printer httpdocspythonorglibrarypprinthtml it extremely simple use pretty prints python objects you give json string expect formatted output eg pydict namechateau des tours brouillycodechateaudestoursbrouillyregionfrance burgundy beaujolais brouillywinerychateau des tourswineryidchateaudestoursvarietalgamaypricevintagetypered winelinkhttpwwwsnoothcomwinechateaudestoursbrouillytagscolorful mauve intense purple floral violet lively rich raspberry berryimagehttpeiisnoothcomwinebwinesearchjpegsnoothrankavailablenummerchantsnumreviews pprint import pprint pprintpydict the output available code chateaudestoursbrouilly image httpeiisnoothcomwinebwinesearchjpeg link httpwwwsnoothcomwinechateaudestoursbrouilly name chateau des tours brouilly nummerchants numreviews price region france burgundy beaujolais brouilly snoothrank tags colorful mauve intense purple floral violet lively rich raspberry berry type red wine varietal gamay vintage winery chateau des tours wineryid chateaudestours,im trying extract data large batch files convert specific json format importing database using django fixtures i able get far n pkn model trialsconditionsn fields n trialid nctn keyword brain central nervous system tumorsn n pkn model trialsconditionsn fields n trialid nctn keyword lymphoman n pk n model trialscriterian fields n trialid nctn gender bothn minimumage yearsn maximumage nan healthyvolunteers non textblock n nttpknttmodel trialskeywordnttfields ntttrialid nctnttkeyword primary central nervous system nonhodgkin lymphomanttntt many lines later after completion study treatment patients followed every months year everyn months year every months yearsnn projected accrual a total patients accrued studyn n overallstatus recruitingn phase phase n enrollment n studytype interventionaln condition n criteria n overallcontact testdatan location n lastchangeddate march n firstreceiveddate may n keyword n conditionmesh n n n n pk testdatan model trialscontactn fields n trialid nctn lastname pamela z new mdn phone n email n the output actually needs look like pk trialid model trialstrial fields trialid trialid brieftitle brieftitle officialtitle officialtitle briefsummary briefsummary detaileddescription detaileddescription overallstatus overallstatus phase phase enrollment enrollment studytype studytype condition elligibility elligibility criteria overallcontact location lastchangeddate lastchangeddate firstreceiveddate firstreceiveddate keyword conditionmesh conditionmesh pk null model trialslocations fields trialsid trialsid facility facility city city state state zip zip country country any advice would much appreciated,2 turns issue version swig i using compile mcrypto i using something order swigel upgrading latest swig recompiling mcrypto fixes issue see reference httpsbugzillaredhatcomshowbugcgiid,i trying run mcrypto bit centos andor rhel i compiled python placed separate directory necessary centosrhel i tried compiling mcrypto builtin openssl e well manually compiled e behavior i even tried epel python pythonmcrypto it also crashes rootip usrlocalbinpython mtestpy segmentation fault the code mcrypto import evp file foo certprivkey evploadkeyfile the key foo generated openssl genrsa test begin rsa private key miibogibaajbakyjtntqzhesuvbjtbyndzbsipmacucfgtbmsjje swvqbljvmkswtjqoqnljeaxellecaweaaqjabzoazmjjcijioyfc mybqmcvxlnfvsbciapfffaztsolfvvccxnhnogbjvmxtbbeurn qihancelgudtazhdyjjtvyivgrkofpeuslnwpivabyeaaieawmvesimzug tjpsdfpuhqqvobfzqjpctevgmcihomxjxkoqnpsnxkdbkqvkjfkd jnnylkpysvaibbhfzeqdvxntvwirhcrywvviolgypoamwihakbc igjahstrgqtzycdfilhfdswxweebcs end rsa private key this test works bit course application uses lot perhaps i compiled python openssl wrong options bit both shared libs enabled installed added ldconfig etc anyone hints has anyone successfully run pythonmcrypto bit,1 the error message telling groupname none in case little point testing whether particular attribute so probably want something like if groupname none print groupnamegroup or groupname objects may group attribute if groupname none print getattrgroupname group none note last argument getattr default value anything want,groupnamegroup none error attributeerror nonetype object attribute group how check object attribute,3 note following code much assumes nothing nonbracket material either side json string import matcher recompiler starting beginning string match anything opening bracket open group record next the json substring close group end string anything closing bracket reverbose your example print matchermatch group example embedded hashmap print matchermatch ab cd group the short nonprecompiled noncommented version import print rematch group although sake maintenance commenting regular expressions much preferred,if i string valid json substring like one mystr what best way extract json string the numbers outside anything except including newlines things like just clear result i want newstr the best way i think use find rfind take substring this seems verbose python compliant i would prefer essential any help appreciated,3 you use twistedinternetstdio nonblocking standard io this provides alternate streaming ordered connectionoriented transport used protocol normally runs transport similar transports include tcp ssl see stdinpy stdiodemopy linked httptwistedmatrixcomdocumentscurrentcoreexamples also linereceiver blocking waiting user input it protocol even io,i building app using twisted server contains timers several times second writes timer values client udp the client needs able send various commands pause timer reset timer server change timers sent client the problem i see client constantly logging timer values received server i sure i without blocking i want asynchronously without threading twisted provides numerous asynchronous io options i really sure would appropriate basiclinereceiver protocol still blocking waiting user input thanks advance ben ps first post please let know improvements i could make,1 use try except else range try f except ioerror raise print retry else break you generically catch errors just let bubble appropriate handler,i need invoke method f if raises ioerror i need invoke retry three times i need log exceptions i need log retries code looks ugly please help make elegant pythonic i using python thanks count count try f except ioerror count count print retry continue except exception x print x break,3 the problem taggrab function def taggrabself tagname parentselfelement you cannot self header rather none correct body def taggrabself tagname parentnone parent none parent selfelement the reason class object created self besides globals element plus couple items names defined python gets taggrab module init gettree gettag as experiment prove try class testclasscreationobject printstarted creating class printnames far vars def initself pass printnow vars def noopself defaultnone printthis gets run noop called printand vars print printand fail def failureself someargselfnoop pass printwe never get,so i keep getting error i google common fix sure methods class self first argument here error file cusersmedocumentsprojectcodemodeltraineventpy line nameerror global name self definedpress key continue this seems like common error simple fix except methods self first argument then i realized traceback simply pointing line class name declared it pointing line i call method self this error raised long in fact seems raised upon importing here traineventpy xmletreeelementtree import element class traineventobject def initself element selfelement element selfmsgid selftaggrab msgid selfmsgtime selftaggrab msgtime selfoffset selftaggrab offset selftranid selftaggrab tranid selfportal selftaggrab portal moveelem selfelementfind move selfstarttime selftaggrab starttime moveelem selfendtime selftaggrab endtime moveelem selftype selftaggrab type moveelem carelem selfelementfind car selfname selftaggrab name carelem selfuniqueid selftaggrab uniqueid carelem selforientation selftaggrab orientation carelem selfwells selftaggrab wells carelem selfaxles selftaggrab axles carelem selflength selftaggrab length carelem selfisengine selftaggrab isengine carelem selfisghost selftaggrab isghost carelem def gettreeself atree element apsmessage selfaddtagatree msgid selfmsgid selfaddtagatree msgtime selfmsgtime selfaddtagatree offset selfoffset selfaddtagatree tranid selftranid selfaddtagatree portal selfportal moveelem element move selfaddtagmoveelem starttime selfstarttime selfaddtagmoveelem endtime selfendtime selfaddtagmoveelem type selftype atreeappendmoveelem carelem element car selfaddtagcarelem name selfname selfaddtagcarelem uniqueid selfuniqueid selfaddtagcarelem orientation selforientation selfaddtagcarelem wells selfwells selfaddtagcarelem axles selfaxles selfaddtagcarelem length selflength selfaddtagcarelem isengine selfisengine selfaddtagcarelem isghost selfisghost atreeappendcarelem return atree def gettagself return selfelementtag def taggrabself tagname parentselfelement helper function xml reading operations return parentfindtagnametext def addtagself element tagname textvaluenone helper function setting values xml elements note function assumes unique tag name values within element elementappendelementtagname textvalue elementfindtagnametext strtextvalue so methods self first argument call stack pointing class declaration problem self defined globally i wrong ps if helps i using latest ironpython interpreter case problem ironpython specific reason,3 make b member variable selfb button then selfchoosecolor see selfb make changes def choosecolorself color askcolor selfbbg color however change color pythontkinter,i new making guis python i trying pretty simple essentially i dialog class i use instantiate dialog program one things dialog button i want use change color i want user able click button taken color chooser return dialog button changing color chosen in dialog class i define button def bodyself master labelmaster texttrack urlgridrow labelmaster textshort labelgridrow labelmaster textlong labelgridrow b buttonmaster textcolorbgwhitecommandselfchoosecolorgridrow selfe entrymaster selfe entrymaster selfe entrymaster selfegridrow column selfegridrow column selfegridrow column return selfe initial focus then i want simple function choose color def choosecolorself color askcolor bbg color i understand b scope i change i understand get color chosen place i change button color any help would greatly appreciated,1 after comments i think i understand going i guess using periodic boundaries check wrong check position edges fix required inpos step scsizegrid inpos elif inpos step inpos scsizegrid else inpos step size returns total number elements array you need check individual lengths x directions array here shape friend and need correct index goes beyond limits mod operator use so code simply rewritten move step inpos step correct according periodic boundaries inpos inpos gridshape simply inpos gridshape second problem indexing grid suffice say way want check docs details for simple case rewritten gridinpos inpos initialtrap true,continuation previous stackoverflow question i want dimensions i tried following rangepos steps steps particle falls trap inpos scrandomrandint lengrid initialtrapfalse initialtrapfalse step particle one stepscarrayrandomchoice check position edges fix required inpos step scsizegrid inpos elif inpos step inpos scsizegrid else inpos step check trap order stop loop gridinpos initialtrap true if trap continue steps stepscountappendsteps return stepscount i also tried inposx intscrandomrandint lengrid initial position particle x axis inposy intscrandomrandint lengrid initial position particle axis inposx step lengrid inposy step lengrid inposx inposy elif inposx step inposy step inposx lengrid inposy lengrid else inposx step inposy step gridinposxinposy initialtrap true and lasti tried work lists arrays inpos scipyrandomrandintlengridtolist steprandomchoice success either i lost error messages if run program gives the truth value array one element ambiguous use aany aall line inpos step scsizegrid if use scanyinpos step scsizegrid scanygridinpos runs used printgridinpos i figured change values it get value loop never ends,2 i compared performance c extension vs ctypes wrapper in particular test difference x there multiple calls c library ctypes wrapper also executing python code the running time c library short made extra overhead python code even significant so ratio likely different significant case,i functions written c game project these functions get called quite lot times per second the functions written c raw speed now easiest way include functions python use ctypes the alternative write c extension python around functions takes quite bit extra effort so i wondered including initial loading dll big overhead ctypes i using python standard cpython release i want use external library like cython i know question asked i seen much information performance comparison two options,3 the difference first lookahead expects exactly one whitespace character digit capital letter second one expects least one whitespace character many possible the called quantifier it means n many possible to recap exactly one whitespace character allowed will fail without one at least one maybe whitespaces allowed further studying i multiple blanks w continues match blanks last blank capital letter to answer comment please consider what w actually matches a single word character azaz followed least one characterexcept newline lazy quantifier so case leaves one space lookahead later matches therefore consume blanks except one this see output,i following regex supposed find sequence words ended punctuation the look ahead function assures match space capital letter digit pat recompilerwsazd what function following lookahead pat recompilerwsazd is python supporting variable lookahead i get error furthermore i cannot see differences patterns both seem work regardless number blanks i is explanation purpose look ahead,1 i really sure tying achieve sequence words ended punctuation matched something like refindallr ws lookahead requires another string follow in case requires one one space requires least one space and yes lookahead accepts modifier even python x the lookahead refindallr wssw refindallr wssw try something like stefano ciao domani presto depending strings lookahead might necessary might might change one space option,i following regex supposed find sequence words ended punctuation the look ahead function assures match space capital letter digit pat recompilerwsazd what function following lookahead pat recompilerwsazd is python supporting variable lookahead i get error furthermore i cannot see differences patterns both seem work regardless number blanks i is explanation purpose look ahead,1 seems k people could get token start complete token so two things come mind keep track seats remaining event way count bookings cannot occur lock needed update event would prevent ever going zero at anytime persons subscription seats remaining drops zero remaining tokens become invalid users kicked signup process nice apologizing seats full etc,i looking system people rsvp free web conference web conferences get really busy lot interest limited places way ensure get oversubscribed so need countdown time book seat time order completed confirmed this way first x amount people actually click attending get seats conference if user complete booking allocated seat put back pool someone else grab an overview happens i see best working user clicks rsvp event makes ajax request rsvpeventid this goes stores unique id refered token rest question along timestamp it stores token session the user notified x amount time let say mins complete rest details nameemaildob etc however anything put database checks amount pending orders less total seats available seats left conference returns saying sorry seats available keep checking bookings completed seats become available if user fills time stores details database attending if however fail fill form time cron job running every second go delete tokens timestamp minutes ago loose chance attend seat conference put back pool they notified unsuccessful taken back first step all easy enough write simply putting records database count from pendingbookings where conferenceid x working many seats either confirmed orders pending subtracting total seats available conference but i feel using mysql would scalable i sure excess k people trying grab around seats count one people get pretty expensive decent caching needs checking real time many people process i looked using amazon simpledb deployandgo scalability i used seen count necessarily accurate nature scalability i guess obvious reasons count needs accurate i need able add records along timestamp able delete records older five minutes,2 virtualenv modifies path include python correct setup it completely separate program system python the path used look programs name first program given name path gets executed when “run file” windows uses extension file look program run it look name program check path the solution explicitly invoke python command line python managepy virtualenv active this way windows search path meant “python” find correct one,i virtualenv installed windows in cmd run python look syspath see virtualenv path included run managepy django i see virtualenv path virtualenv working django server why,1 dexy similar product sweave one advantage dexy exclusive one single language you could create dexy document included r code python code anything else,i recently started using sweave creating reports analyses run r looking python scripts i found references embedding python sweave docs seems like bit hack has anyone worked better solution equivalent python i aware sweave tool allows embed r code complete data analyses latex documents,3 try url r articleeditparticleidd mysiteviewseditarticle take look named groups django documentation,i url defined follows r articleedit mysiteviewseditarticle and function defined def editarticlerequest articleid however seems request page results wrong value passed articleid if i redefine url r article mysiteviewseditarticle minus edit seems work any suggestions fix,2 lasse right comma separated value file use csv module a brief example csv import reader test infile abcdefghiijk real probably like infile open filename r use open infile indent rest line readerinfile print line test input prints a b c d e f g h ii j k,i input looks like following abcdefghiijk the commaseparated values order i like split string commas however case something inside double quotation marks i need ignore commas strip quotation marks possible so basically output would list strings a b c d e f g h ii j k i look answers i thinking regular expression would best i terrible coming,3 every time execute addurlrule internal routing remaps url map this neither threadsafe fast i right understand need user specific url rules honest it kinda sounds like actually want user specific applications mounted maybe helpful httpflaskpocooorgdocspatternsappdispatch,i writing app users able store information specify rest interface ie store list products usernamerestproducts since urls obviously known hand i trying think best way implement dynamic url creation flask the first way i thought would write catchall rule route url but i basically duplicating url routing capabilities flask already builtin so i wondering would bad idea use addurlrule docs scroll bit attach directly app is specific reason done,3 you could cache count available database update whenever issue registration started confirm registration finished revoke minutes token but need kind performance really sql database you could implement fairly simple token broker using heap based expiringsoonest every time token requested check soonestexpiring token see expired if revoke whoever assigned give new person if tell try later when registration completed remove token heap relatively expensive operation times so heap would always tokens equal number freepending slots handling even thousandspersecond findsoonestexpiring requests eg fibonacci heap trivial even modest hardware i check i suspect someone else already solved problem may able download said token broker,i looking system people rsvp free web conference web conferences get really busy lot interest limited places way ensure get oversubscribed so need countdown time book seat time order completed confirmed this way first x amount people actually click attending get seats conference if user complete booking allocated seat put back pool someone else grab an overview happens i see best working user clicks rsvp event makes ajax request rsvpeventid this goes stores unique id refered token rest question along timestamp it stores token session the user notified x amount time let say mins complete rest details nameemaildob etc however anything put database checks amount pending orders less total seats available seats left conference returns saying sorry seats available keep checking bookings completed seats become available if user fills time stores details database attending if however fail fill form time cron job running every second go delete tokens timestamp minutes ago loose chance attend seat conference put back pool they notified unsuccessful taken back first step all easy enough write simply putting records database count from pendingbookings where conferenceid x working many seats either confirmed orders pending subtracting total seats available conference but i feel using mysql would scalable i sure excess k people trying grab around seats count one people get pretty expensive decent caching needs checking real time many people process i looked using amazon simpledb deployandgo scalability i used seen count necessarily accurate nature scalability i guess obvious reasons count needs accurate i need able add records along timestamp able delete records older five minutes,1 possible way parse file count different bwfronts import csv collections import counter def countbwfronts counts occurrences different bwfronts yourfiletxt returns counter object maps different bwfront values number occurances file reader csvreaderopen yourfiletxt rb delimiter counter counter counterupdaterow row reader return counter name main print countbwfronts as might guessed row taken reader list strings used separated comma input file in order complex calculations might want rewrite generator expression loop,i searched strings lists append etc seem handle i created files android based selections done app the output looks like text file house bwfrontcolorfrontbwtiltcolortilt house bwfrontcolorfrontbwtiltcolortilt house bwfrontcolorfrontbwtiltcolortilt house bwfrontcolorfrontbwtiltcolortilt house bwfrontcolorfrontbwtiltcolortilt reason naming i houses user firstly selects bwfront pictures color images the exercise map different pictures house i wish load text files count many different bwfront selected etc to clarify user selects four times per house this continue houses types picturesbut get started i able apply solution files does make sense,1 it appears cakephp mvc framework similar django included app engine python i sure would want store data google app engine unless dealing extremely large amount data case likely comfortable enough working python make app work entirely gae see official docs info httpcodegooglecomappenginedocspythonoverviewhtml httpcodegooglecomappenginearticlesdjangohtml,i thinking create webapplication cakephp consuming python appengine webservice but install cakephp etc i need configure database appengine uses another kind datastorage different mysql etc i thinking store data appengine using python webservices cakephp application comunicating webservice insert retrieve data is good resource unpossible obs also opened possibility developing webapplicaiton completely python running appengine if anyone good resource thanks,1 try using python version pyexe located httpsourceforgenetprojectspyexefilespyexe note upgrading previous versions python likely need modify setuppy files distribute extra microsoft dlls well httpwwwpyexeorgindexcgitutorialstep,i python installed bit windows machine i trying install pyexe i receive following error python version required found registry clue solve good alternative convert python solution exe thanks advance,1 while example may seem overly complicated i exercise better understand python makes dealing atomic parts file duration easier usrbinenv python duration display duration video file utilizes ffmpeg retrieve information usage duration file bash dimensionspy srcvideofile import subprocess import sys import ffmpeg usrlocalbinffmpeg get duration input string return dictionary hours minutes seconds def searchforduration ffmpegoutput pattern recompiler duration www match patternsearchffmpegoutput match hours matchgroup minutes matchgroup seconds matchgroup else hours minutes seconds return dictionary containing duration values return hours hours minutes minutes seconds seconds get dimensions specified file using ffmpeg def getffmpeginfo srcfile p subprocesspopen ffmpeg srcfilestdoutsubprocesspipestderrsubprocesspipe stdout stderr pcommunicate return stderr get duration pulling ffmpeg info searching line contains duration values def getvideoduration srcfile ffmpegoutput getffmpeginfo srcfile return searchforduration ffmpegoutput name main try lensysargv filename sysargv getvideoduration filename print hours minutes seconds else print error wrong number arguments except exception e print e raise systemexit,on linux youtube places temporary flash files tmp nautilus display duration minutesseconds i found way extract duration using python the fewer dependencies method requires better thanks advance,1 this method worked rsvn imagerun standard options sleep instance rsvninstances instanceaddtag tag name tag value,is way boto python api specify tags creating instance i trying avoid create instance fetch add tags it would much easier instance either preconfigured certain tags specify tags i execute following command ecservercreateinstance ecconn aminame securitygroup instancetypename keypairname userdata,1 i think try different solution httpawsamazoncomsimpledb,i thinking create webapplication cakephp consuming python appengine webservice but install cakephp etc i need configure database appengine uses another kind datastorage different mysql etc i thinking store data appengine using python webservices cakephp application comunicating webservice insert retrieve data is good resource unpossible obs also opened possibility developing webapplicaiton completely python running appengine if anyone good resource thanks,1 import numpy np n nparangenmreshapenm printa sz aitemsize hw ashape bhbw shape hbh wbw bh bw printshape strides sznparraywbhbww printstrides blocksnplibstridetricksasstrideda shapeshape stridesstrides printblocks starting ie blocks get ie blocks one item away since machine aitemsize bytes stride this gives us last value strides aitemsize starting get ie blocks ie w items away stride this accounts second last value strides starting yet get ie blocks ie bw items away stride this accounts second value strides finally starting get ie blocks ie wbh items away stride so strides,i trying using numpylibstridetricksasstrided iterate nonoverlapping blocks array i trouble finding documentation parameters i able get overlapping blocks for example i x array i like get x blocks i fine extra cells right bottom edge excluded so far code import sys import numpy np nparray sz aitemsize hw ashape bhbw shape hbh wbw bh bw strides wsz sz wsz sz blocks nplibstridetricksasstrideda shapeshape stridesstrides print blocks assert blockstolist print blocks assert blockstolist print blocks assert blockstolist the shape resulting blocks array seems correct last two asserts fail presumably shape strides parameters incorrect what values i set get nonoverlapping blocks,3 not sure understand question if need frequency table straightforward time find pattern add frequency count so real problem find pattern if want keep patterns sorted order pretty easy since keep table sorted time ends insertsort operation extremely quick now finding right pattern another story you need tree hash table followed trees lists whatever find best matching sequence this makes algorithm complex execute obviously small data set naive search testing entries one one could give results but expanding data set search cost become prohibitive,note this right use lzw compression i playing around question in single pass possible also update frequency counts elements inside dictionary my implementation import sys collections import defaultdict import the silliest string inputstring first sentence book first sentence really interesting first sentence always first inputstring inputstringlowersplit stringtable defaultdictint freqtable defaultdictint def dopass global inputstring global stringtable global freqtable print print input string print inputstring code string inputstring output stringtablestring code code total leninputstring range total word inputstringi string word stringtable string word else string stringtable outputappendstrstringtablestring else outputappendstring stringtablestring word code code string word stringtablestring code code outputappendstrstringtablestring print print output string print output print print dictionary built sortedstringtablekeys keylambda x lenx print stringtablei print print frequencies sortedfreqtablekeys keylambda x lenx print freqtablei def main dopass name main main output input string first sentence book first sentence really interesting first sent ence always first output string first sentence book sentence really interesting always dictionary built first book book always really first really sentence sentence always first first sentence interesting interesting first sentence first sentence frequencies i trying fill i want fill freqtable frequency counts whatever patterns finding i put method obvious reasons work gives wrong counts any suggestions whether possible would great,1 use setdashes,i satisfied default set linestyles namely size line segments gap i also want something like etc line patterns does anybody know customize best witches,3 i would write first function using generators def fiximportstopdir notuikeys walk directory substitute wrong imports itertools import imapifilter gen ifilternoneimapextractdotted notuikeys repl dictdottedaddmodeldotted dotted gen pyfiles pathjoinroot x root dirs files walktopdir x files x py py pyfiles openpy opf res replacetextopfread repl x py faster xendswith py,i dictionary form fromx fromchangedx possibly quite big i substitute text files accordingly dictionary quite big directory structure i find anything might nice solution i end using oswalk iterating dictionary writing everything with something like def fiximportstopdir notuikeys walk directory substitute wrong imports repl n notuikeys interleave model dotted extractdottedn dotted repldotted addmodeldotted root dirs files walktopdir pyfiles pathjoinroot x x files xendswith py py pyfiles res replacetextopenpyread repl def replacetextorigtext replacemap res origtext try grep keys using translate maybe dictionary replacements toreplace replacemap resreplacetoreplace replacemaptoreplace print differences un unifieddiffressplitlines origtextsplitlines printun return res is betternicerfaster way edit clarifying bit problem substitution generated function form xyz xyaddedz xba xbaddeda and yes sure i better use regexps i thought i need time i think help much however i really formalize whole range substitutions one multiple regexps,1 you also set entire script warnonly setting true def local envwarnonly true,when i define task run several remote servers task runs server one exits error fabric stop abort task but i want make fabric ignore error run task next server how i make for example fab siteservicegw siterpt executing task siteservicegw sitefep run echo nm sudo s route sitefep err sitefep err we trust received usual lecture local system sitefep err administrator it usually boils three things sitefep err sitefep err respect privacy others sitefep err think type sitefep err with great power comes great responsibility sitefep err root password sitefep err sudo route command found fatal error run encountered error return code executing echo nm sudo s route aborting,3 this question sort answered fully the issue to header wants emails string sendmail function wants list structure list emails emails banjerexamplecom slingbladeexamplecom dudeexamplecom use string to header msg to join emails use list sendmail function ssendmailfromemail emails msgasstring,i try send mails python multiple emailaddresses imported txt file i tried differend syntaxes nothing would work the code ssendmail sendermailcom recipientmailcom recipientmailcom recipientmailcom msgasstring so i tried import recipientaddresses txt file urlfile openmaillisttxt r maillist urlfileread ssendmail sendermailcom maillist msgasstring the mainlisttxt contains recipientmailcom recipientmailcom recipientmailcom but work i also tried maillist code txt file also effect maillist code txt file also effect does anyone knows thanks lot,3 are sure urlopen call hangs because loop terminate call successful,the function urlliburlopen freezes so question simple why urlopen freeze script ever even though timeout set how i access data url case httpapiowndtvlivechannelfnatictv without possibility python process freezing eternity this part freezes in owndpy try three times make contact true try connect api right it freezes connection urlliburlopenrequest timeout xmlstring connectionread except urlerror e tries tries sysstderrwrite owndstreamsupdater fatal error repeated timeouts exit this stack trace keyboardinterrupt traceback recent call last file line file honsappowndstreamsupdaterpy line updatestreaminfo streaminfo getstreaminfostream file honsappowndpy line getstreaminfo connection urlliburlopenrequest timeout file usrlocallibpythonurllibpy line urlopen return openeropenurl data timeout file usrlocallibpythonurllibpy line open response selfopenreq data file usrlocallibpythonurllibpy line open open req file usrlocallibpythonurllibpy line callchain result funcargs file usrlocallibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlocallibpythonurllibpy line doopen r hgetresponsebufferingtrue file usrlocallibpythonhttplibpy line getresponse responsebegin file usrlocallibpythonhttplibpy line begin version status reason selfreadstatus file usrlocallibpythonhttplibpy line readstatus line selffpreadline file usrlocallibpythonsocketpy line readline data selfsockrecvselfrbufsize keyboardinterrupt edit i let script run night i know exactly long took though five minutes script finally gave gave stacktrace traceback recent call last file honsappowndstreamsupdaterpy line newinfo file honsappowndstreamsupdaterpy line newinfo result updatestreaminfostream file honsappowndstreamsupdaterpy line updatestreaminfo streaminfo getstreaminfostream file rootdropboxprojectshonstreamshonsappowndpy line getstreaminfo connection urlliburlopenrequest timeout file usrlocallibpythonurllibpy line urlopen return openeropenurl data timeout file usrlocallibpythonurllibpy line open response selfopenreq data file usrlocallibpythonurllibpy line open open req file usrlocallibpythonurllibpy line callchain result funcargs file usrlocallibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlocallibpythonurllibpy line doopen r hgetresponsebufferingtrue file usrlocallibpythonhttplibpy line getresponse responsebegin file usrlocallibpythonhttplibpy line begin version status reason selfreadstatus file usrlocallibpythonhttplibpy line readstatus raise badstatuslineline httplibbadstatusline,2 most likely cause error mismatch calling conventions i guessing c dll exports functions cdecl convention use windll implies stdcall create library like use cdecl lpdllcdllcsomepathmydlldll,i trying use dll python source using ctypes i began reading python documentation i new after successfully loading dll python i try pass string function expects char gives valueerror procedure probably called many arguments bytes excess i also tried looking posts resolve problem i tried different approaches pas string using byref pointer change outcome i also tried winfunctype failed the dll i using windll here test program i wrote python ctypes import lpdllwindllcsomepathmydlldll print lpdll ipaddr createstringbuffer ipaddr ipaddr ccharp print ipaddr ipaddrvalue dinitlpdlldinit dinittesterlpdlldinittester dinittesterprototype winfunctypecint ccharp dinittesterparamflags ipaddress none dinittester dinittesterprototypedinittester lpdll dinittesterparamflags try dinit dinittester except valueerror msg print inittester failed print msg here dinittester implemented cpp file available dll exports dapi int dinittesterchar ipaddress int err errok libsinitialized code else err hndlconinitipaddress err err errnoconnection else ntesters instantiateanalysisclasses initializetestersettings ifnull hndlhndlfm fminitialized true else err errnotinitialized return err your help greatly appreciated,1 when submit form multiplechoisefield validates selected items belong choises parameter multiplechoisefield if dynamically later add fields naturally choises set read as solution could think using charfield selectmultiple widget override cleanmethod,i understand happening i form mylist formsmultiplechoicefieldrequiredfalse widgetformsselectmultiple label mylist helptext help i jquery page adds dynamic values i submit form i get formisvalid false object attribute cleaneddata this seems happens dynamically add values select box i select submitting if i select values cleaneddatamylist empty array how i fix basically i want access dynamically added list values django form submission edit requestmethod post form myformrequestpost action requestpost submit action update mylist formcleaneddata mylist else form myform edit def cleanmylistself data selfcleaneddata mylist return data def cleanself cleaneddata selfcleaneddata return cleaneddata,1 selfbitmaphide selfbitmapdestroy the first hide whereas second actually destroy widget you probably want call selflayout make window redraw update layout widgets,i know sounds easy delete image wxpython i using wxstaticbitmap wximage create image way delete image maybe theres something like bmp wximagefilename wxbitmaptypeanyconverttobitmap selfbitmap wxstaticbitmapselfsizer bmp deleteimageselfbitmap deleteimagebmp i tried replacing variable image still shows,3 that article meant show stretch resize image to probably require python imaging library pil then resize grab new size frame use calculate scale image see following link download pil httpwwwpythonwarecomproductspil,wondering put stretched background image sizer wxpython i looking tutorial httpwwwblogpythonlibraryorgwxpythonputtingabackgroundimageonapanel image resize import wx class mainpanelwxpanel def initself parent constructor wxpanelinitself parentparent selfsetbackgroundstylewxbgstylecustom selfframe parent sizer wxboxsizerwxvertical hsizer wxboxsizerwxhorizontal num range label button num btn wxbuttonself labellabel sizeraddbtn wxall hsizeradd wxexpand hsizeraddsizer wxtop hsizeradd wxall selfsetsizerhsizer selfbindwxevterasebackground selfonerasebackground def onerasebackgroundself evt add picture background yanked colourdbpy dc evtgetdc dc dc wxclientdcself rect selfgetupdateregiongetbox dcsetclippingrectrect dcclear bmp wxbitmapuntitledpng dcdrawbitmapbmp class mainframewxframe def initself constructor wxframeinitself none size panel mainpanelself selfcenter class mainwxapp def initself redirectfalse filenamenone constructor wxappinitself redirect filename dlg mainframe dlgshow name main app main appmainloop that code i sure resizing possible wxpython so basically i want able use picture background sizer however image stretched sizer size thanks,1 if want run django native language language file available need set languagecode httpsdocsdjangoprojectcomentopicsindeploymenthowdjangodiscoverslanguagepreference,i website two languages turkish english i already setup django internalization gettext if browser request turkish translates turkish if browser request english translates english but want turkish language show users how set language turkish permanentlyi using django thanks,2 are sure typo like something somthing typo left e traceback recent call last file stdin line module nameerror name somthing defined,i gui created glade i would like populate treeview widget here relevant part code def initself selffillstore selfaddcolumnselfwidget treeviewpreview selfwidget treeviewpreview setpixbufcolumn def fillstoreself selfwidget liststorepreview clear foo gdkpixbufpixbufnewfromfile png da gtkimagenewfrompixbuffoo selfwidget liststorepreview appendda def addcolumnself treeview renderer gtkcellrendererpixbuf column gtktreeviewcolumnpreview renderer pixbuf columnsetsortcolumnid treeviewappendcolumncolumn yet i try run code i get error informs renderer defined the offending line column gtktreeviewcolumnpreview renderer pixbuf can someone point error in case helps traceback traceback recent call last file testpy line module class test file testpy line test column gtktreeviewcolumnpreview r pixbuf nameerror name r defined thanks vz,1 try urlliburlopen instead urlliburlopen i situations urlliburlopen chokes proxy server urlliburlopen opens fine,i trouble script it supposed open website trough proxy i get always error several proxies i trying what could traceback recent call last file cusersshadydesktopptzplace copypy line module h urlliburlopenwebsite proxies http proxy file cpythonliburllibpy line urlopen return openeropenurl file cpythonliburllibpy line open return selfopenunknownproxyproxy fullurl data file cpythonliburllibpy line openunknownproxy raise ioerror url error invalid proxy type proxy ioerror errno url error invalid proxy http xxxxxxxxxxxx the script proxylist proxy proxylist h urlliburlopenwebsite proxies http proxy,3 wow this going complex job regardless that said if i understand needs project correctly something done using data migration south even i lying i said going joke my recommendation mostly parrot assumption question i want make clear one master table base records table added so table a keeps existing records gets additions b b feeds additions a done b deleted i hesitant write sample code actual job much complex i anyway try point right direction consider something like import datetime southdb import db southv import datamigration djangodb import models class migrationdatamigration def forwardsself orm b ormbobjectsall sanity check item get copied a ormaobjectsfilterusernamebusername continue make a record properties b record orma firstnamebfirstname lastnameblastname emailaddressbemailaddress save new a record delete b record asave bdelete def backwardsself orm backwards method write one this would end migrating bs a a leave table bs expected duplicates could check means deleting like i said sample meant complete if decide go route spend time south documentation particularly make sure look data migrations that ⢠hope helps,i two djangoorm managed databases i like merge both similar schema standard authusers table along shared tables reference well authusers i like merge single database automatically understandably could nontrivial depending upon foreignkey relationships constitutes unique record table does anyone know exists tool merge operation if nothing like currently exists i considering writing management command based standard loaddata command essentially use standard dumpdata command export tables source database use modified version loaddata merge destination database for example i databases a b i want merge database b database a i want follow procedure according pseudocode mergedatabasedst a mergedatabasesrc b table sortedmergedatabasedstgetredundanttablesmergedatabasesrc keyacyclicdependency key tablegetuniquecolumnkey srcidtodstid recordsrc mergedatabasesrctableobjectsall srckeyvalue recordsrcgetkeyvaluekey try recorddst mergedatabasedsttableobjectsgetkey dstkeyvalue recorddstgetkeyvaluekey except mergedatabasedsttabledoesnotexist recorddst mergedatabasedsttablekconvertfkv kv recordsrcmetafields recorddstsave dstkeyvalue recorddstgetkeyvaluekey srcidtodstidtablerecordsrcid recorddstid the convertfk function would use srcidtodstid index convert foreign key references source table equivalent ids destination table to summarize algorithm would iterate table merged order dependency parents iterated first so wanted merge tables authusers mycustomprofile dependent authusers iterate authusers mycustomprofile each merged table would need sort indicator documenting combination columns denotes universally unique record ie key for authusers might username andor email column if value key database b already exists a record imported b id existing record a recorded if value key database b exist a record imported b id new record recorded using previously recorded id mapping created explaining map foreignkey references specific record b new mergedpreexisting record a when future records merged a mapping would used convert foreign keys i could still envision cases imported record references table included dumpdata might cause entire import fail therefore sort dryrun option would needed simulate import ensure fk references translated does seem like practical approach is better way edit this exactly i looking i thought others might find interesting the turbion project mechanism copying changes equivalent records different django models within database it works defining translation layer ie mergingmodellayer two django models say update www field user bobbobcom profile automatically update url field user bobbobcom otherprofile the functionality i looking bit different i want merge entire partial database snapshot infrequent intervals sort way loaddata management command,1 as uses libediteditline syntax enable autocompletion little bit different you first force emacs bindings readline i wrong typing readlineparseandbindbind e then add autocompletion linked tab button man editrc readlineparseandbindbind rlcomplete and want support indenting history found internet look like unless i made mistake import readlinerlcompleter indenting class tabcompleterrlcompletercompleter completer supports indenting def completeself text state text return nonestate else return rlcompletercompletercompleteself text state readlinesetcompletertabcompletercomplete add autocompletion libedit readlinedoc readlineparseandbindbind e readlineparseandbindbind rlcomplete else readlineparseandbindtab complete add history import os histfile ospathjoinosenvironhome pyhist try readlinereadhistoryfilehistfile except ioerror pass import atexit atexitregisterreadlinewritehistoryfile histfile del histfile,before upgrading lion i tab complete working python shell via terminal following instructions possible tab complete working since upgrading lion i unable get tab complete working terminal session python i followed instructions letter still work is difference readline module lion hooking tabcomplete option longer seems work i wondering terminal ignoring readline python python version edit by tab complete i mean i could something like following django import mymodel mymodelobjectsatab complete,3 i completely understand algorithm looks like code hangs loop true selection randomrandrangeselfpool selection selfpoolindex index index index break it gets point never get value index index this could either indicate mistake somewhere code situation meets condition you could try putting cap number iterations example iters iters selection randomrandrangeselfpool selection selfpoolindex index iters index index break iters deal able identify couple,i implemented simple genetic algorithm python code import random ings w su su sy sy sy sy sy mutationrate crossoverrate iterations file open dlogfiletxt class ingredient def initself n p mi selfname n selfprice p selfmin mi selfmax selfperc randomrandrangeselfmin selfmax class drink def initself selfing ingredientx x ings selfnormalize selffitness selfevaluate def normalizeself sum x selfing sum xperc sum offset sum offset index randomrandrangelenselfing val selfingindexmax selfingindexperc threshold randomrandrangeval val else threshold threshold threshold offset else offset selfingindexperc threshold offset threshold sum offset sum offset index randomrandrangelenselfing val selfingindexperc selfingindexmin threshold randomrandrangeval val else threshold threshold threshold offset else offset selfingindexperc threshold offset threshold def evaluateself fitness x selfing fitness xperc xprice return fitness class geneticalgorithm def initself selfdrinklist drink x range selfpool def mutateself index ing ing randomrandrange randomrandrange ing ing ing randomrandrange ptr selfdrinklistindexing ingthr ptringmax ptringperc ingthr ptringperc ptringmin ingthr amp ingthr change randomrandrangeingthr ingthr ingthr else ingthr ptringperc change ptringperc change def crossoverself index index ing ing randomrandrange randomrandrange ing ing ing randomrandrange ptr selfdrinklistindexing ptr selfdrinklistindexing resultindex randomrandrangelenselfdrinklist true resultindex randomrandrangelenselfdrinklist resultindex resultindex break bias ptringperc ptringperc else bias maxchange minptringperc ptringmin ptringmax ptringperc ptringmax ptringperc ptringperc ptringmin maxchange change randomrandrangemaxchange ptringperc change ptringperc change ptringperc change ptringperc change selfdrinklistresultindexing ptr selfdrinklistresultindexing ptr bias maxchange minptringmax ptringperc ptringperc ptringmin ptringperc ptringmin ptringmax ptringperc maxchange change randomrandrangemaxchange ptringperc change ptringperc change ptringperc change ptringperc change selfdrinklistresultindexing ptr selfdrinklistresultindexing ptr def rouletteself sum lst x selfdrinklist sum xfitness lstappendsum return lst def selectoneself selection randomrandrangeselfpool index selection selfpoolindex index return index def selectcoupleself selection randomrandrangeselfpool index index selection selfpoolindex index true selection randomrandrangeselfpool selection selfpoolindex index index index break return index index def saveself text filewritetext x selfdrinklist xing filewrite min strymin max strymax value stryperc n filewrite nn filewrite npopulation fitness strselfcalculatepopulationfitness nnnn def runself filewritegenetic algorithmnnattributes valuesn mutation rate strmutationrate ncrossover rate strcrossoverrate niterations striterations ningredientsnn strings selfsave nnfirst populationnn cnt rangeiterations selfupdatefitness selfpool selfroulette randomrandom mutationrate index selfselectone selfshowfitness mutation iteration strcnt selfmutateindex selfupdatefitness selfshowfitness results randomrandom crossoverrate index index selfselectcouple selfshowfitness crossover iteration strcnt selfcrossoverindex index selfupdatefitness selfshowfitness results selfsave final populationnn def calculatepopulationfitnessself sum x selfdrinklist sum xfitness return sum def updatefitnessself x selfdrinklist xfitness xevaluate def showfitnessself text lst xfitness x selfdrinklist sumlst filewritetext n strlst strall n to run i create instance geneticalgorithm launch run method the problem low level iterations program works less fine i set iteration example seems fall infinite loop suspend random iteration logfile updated anymore program stop happenes random iteration what cause ps can suggest changes coding style i quite new python know conventions yet,1 i two methods handle one production one development in development append path apps settingspy in case i main project hgdjangoproject apps hgdjangoapps so i use devel syspathinsert ospathjoinospathdirnamefile apps i also use production method development box this method knock effect letting roll back recent production version simply commenting line path insertion settingspy in production i install apps using distutils i control deployment per server multiple projects running server access you read distutils setup scripts then install simply setuppy install,i starting first large django project realized default directory structure going work well i saw question answer decided implement something similar large django application layout what i need make something like work how i change django looks appsmodules,1 python works automatically deep directory structures that porbably find instructions ithere instructions get classes models work if want module folder yourprojectappsfirstapp add installedapps adding line appsfirstapp you add initpy file directories recognized python packages when import classes simply use yourprojectappsfirstappfilename import yourclass you also make sure template directories listed templatedirs,i starting first large django project realized default directory structure going work well i saw question answer decided implement something similar large django application layout what i need make something like work how i change django looks appsmodules,1 i thinking easiest way go use string method endswith this method works follows blacklisted foocom email xfoocom emailendswith foocom true email xsubdomainfoocom emailendswith foocom true so return true domain email whatever ends foocom as see include subdomains foocom conveniently also pass tuple endswith construct tuple blacklisted domains could something like blacklisted foocom barcom email xbarcom emailendswithblacklisted true this even benefit able blacklist subdomains others blacklisted foocom barcom subbaznet emailbad xsubbaznet emailbadendswithblacklisted true emailgood xgoodbaznet emailgoodendswithblacklisted false edit in response avaris comment in order make sure end situation blacklisted barcom bazcom email xfoobarcom emailendswithblacklisted true you included blacklisted list barcom barcom the result blacklisted barcom barcom bazcom bazcom email xfoobarcom emailendswithblacklisted false this obviously work at point i would say method versus regex matter preference while i try avoid regex costs might way go,i list emails domains i trying filter blacklist for email easy since i simply compare emails directly domains emails subdomains etc need matched well foocom domain i would need filter xfoocom xsubdomainfoocom how typically done via regex splitting email appropriate strings,2 one option add logging top foo indicate called need add lines def foo import traceback print foo called tracebackextractstacklimit previous foo code instead logging may find useful maintain global dictionary keep track count many times foo called different places,i using python hotshot profiler tells one methods foo called n times n larger number i expecting is way get detail foo called ideally listing module names line numbers i use grep my codebase contains lots calls foo i want find ones actually executed particular conditions i set profiler,1 if ready follow longer term approach i would advise go macports package manager software packaged works i followed approach successfully mac os x lion you basically first install macports package manager install programs like explained site sudo port install python pynumpy pyscipy pymatplotlib pyipython one advantage macports approach touch mac os x original software programs stored optlocal along programs applicationsmacports like gimp python idle the install procedure put optlocal front path automatically use macport programs instead installed default mac another advantage macports automatically downloads additional necessary programs dependencies their packages quite uptodate many k time writing so macports route access many additional programs side note i long experience another package manager mac os x fink i find macports simpler robust uptodate so i heartily recommended ps i believe also create new python macports command sudo port select python python ipython sudo port select ipython ipython these commands effect define version python ipython called use python ipython commands shell pps jd long i tried following instructions may possibly versions possibly idiosyncrasies mac i also run sudo port install pytornado pyzmq order get fully functioning ipythonnotebook stack working,what could i done instead order get items working together should i move everything windows i prefer reliable way okay happened i wanted install numpyscipy onto mac runs unfortunately numpy ver supports python i go install python but python work appicon bounces automatically quits this strange retrospect i heard python numpy ships mac i tried using sample code numpy website failed now real bind i eventually found httpstronginferencecomscipysuperpack which somehow installs numpy scipy matplotlib ipython pandas well pymc alpha it seemed like worked numpy work example code provided python but i working practice problems i found matplotlib working anymore the python launcher i think python launcher appicon says python name bounces app tray eventually freezes i worried could i matplotlib installed i followed instructions clean uninstall matplotlib followed installation scipysuperpack still fails way now i done clean install matplotlib hopes works and i import pylab throws ton error messages any advice would greatly appreciated,3 the number seconds datetimetimedelta x given timedeltatotalseconds xtotalseconds this function introduced python for older versions python compute totalseconds xdays xseconds xmicrosecondse,how i find number seconds since beginning day utc timezone python i looked docs understand get using datetimetimedelta,3 here one way datetime import datetime time utcnow datetimeutcnow midnightutc datetimecombineutcnowdate time delta utcnow midnightutc print deltaseconds careful edit as suggested want microsecond precision potentially crossing hour period ie deltadays use totalseconds formula given unutbu print deltatotalseconds print deltadays deltaseconds deltamicroseconds e,how i find number seconds since beginning day utc timezone python i looked docs understand get using datetimetimedelta,3 this would simplest way i think f foosubdomainbarcom joinfsplit barcom it use regex one line readable pull domain name added benefit caring domain com net whatever then check extracted domain blacklisted table edit ok couk domains et al import def getaddremailaddr parts resplitr emailaddr return joinparts parts co else getaddr foosubdomainbarcom barcom getaddr foosubdomainbarcouk barcouk getaddr foobarcom barcom edit wilduck pointed may use cases want filter specific subdoamins others ie communityebaycouk i figured may want blacklist specific email addresses without needing separate table ie exgirlfriendgmailcom here solution def isinblacklistaddr check addr list db table return true false def addrisblacklistedaddr addr return false isinblacklistaddr return true sliced joinaddrsplit addr else return addrisblacklistedsliced so deconstructing email address beginning end checking part blacklist obviously get answer single query filter single email addresses subdomains domains way top level domains inclined you queries per email average kill huge blacklist,i list emails domains i trying filter blacklist for email easy since i simply compare emails directly domains emails subdomains etc need matched well foocom domain i would need filter xfoocom xsubdomainfoocom how typically done via regex splitting email appropriate strings,1 what i keep sublists match items match list def matchallthelist tomatch return sublist sublist thelist allitem sublist item tomatch you speed using set def matchallthelist tomatch matches settomatchissubset return sublist sublist thelist matchessublist,given twodimensional list i would like find everything contains sublist i realize i something like psuedopython kosher def matchallthelisttomatch resultlistthelist nmatch tomatch nresult result nmatch nresult resultremovenresult return result but seems kinds bad it seems unlike python code i seen dealt far besides i making changes list iterating i read good thing also seems horribly inefficient tomatch length greater three purposes length thelist unknown could quite large any help greatly appreciated thanks advance,2 another option would epd epd free either install numpy scipy matplotlib ipython traits chaco window osx linux epd kitchensinkincluded version libraries science analysis available subscription basis free academics epd free free commercial use redistribution etc,what could i done instead order get items working together should i move everything windows i prefer reliable way okay happened i wanted install numpyscipy onto mac runs unfortunately numpy ver supports python i go install python but python work appicon bounces automatically quits this strange retrospect i heard python numpy ships mac i tried using sample code numpy website failed now real bind i eventually found httpstronginferencecomscipysuperpack which somehow installs numpy scipy matplotlib ipython pandas well pymc alpha it seemed like worked numpy work example code provided python but i working practice problems i found matplotlib working anymore the python launcher i think python launcher appicon says python name bounces app tray eventually freezes i worried could i matplotlib installed i followed instructions clean uninstall matplotlib followed installation scipysuperpack still fails way now i done clean install matplotlib hopes works and i import pylab throws ton error messages any advice would greatly appreciated,3 access methods different inheritance chain you call raw function method instance fix inheritance chain instead,hi trouble passing variablesdoing functions classes right i something like class def hi print class class def hi print class class def hi print class lets say class i would like execute function class how i go i googling awhile much success except finding images snakes any help problem would greatly appreciated,2 venuessearch supports querying rectangles addition circles specify sw ne params instead request you also specify intentbrowse get back best results area weighted proximity region center httpsdeveloperfoursquarecomdocsvenuessearchhtml this still support arbitrary polygons exhaustive retrieval venues return best region step closer looking,i want retrieve sq venues specific area now i get venues like thishttpsapifoursquarecomvvenuessearchll geopoint i pass radius argument area shape for backend i use django,1 what run cakephp app standard lamp web host access gae data store rest rpc web service this bad idea already cakephp frontend deals rpcs backend cake app stores models mysql could take considerable effort adapt itcakephp models abstract storage method using datasource class you might able find datasource class uses rest rpc however considerable investment cakephp controllers templates i would suggest simply building app entirely gae,i thinking create webapplication cakephp consuming python appengine webservice but install cakephp etc i need configure database appengine uses another kind datastorage different mysql etc i thinking store data appengine using python webservices cakephp application comunicating webservice insert retrieve data is good resource unpossible obs also opened possibility developing webapplicaiton completely python running appengine if anyone good resource thanks,1 it seems png file really value stored white pixel instead i assume something fact photoshop reality works bits bit mode small inaccuracy saving bit greyscale images,i writing script check image normalized i using python png module analyze image to test i created bit image consisting pixels line black white pixel photoshop my script correctly identifies black pixel gives different value i expecting white pixel i understand happens is something wrong script related way photoshop saves image minimalistic test png image httpiimgurcomdfpng script usrbinpython import sys import png httpspypipythonorgpypipypng lensysargv print invalid number arguments lensysargvnusage python getminmaxcolorpy pngfile sysexit pngfilepath sysargv f openpngfilepath rb r pngreaderfilef k rread bitdepth k bitdepth none bitdepth k bitdepth absmaxcolor bitdepth maxcolor mincolor absmaxcolor print content line k color line print color color maxcolor maxcolor color color mincolor mincolor color fclose print n print min color mincolor print max color maxcolor max absmaxcolor mincolor maxcolor absmaxcolor print image normalized else print image normalized,1 i think closer want fin readfiledb categorydict defaultdictdict automatically create subdict line fin itemdict new innermost dict every item iteminstance setiteminstancesline itemdictiteminstanceproductid iteminstance categorydictiteminstancecategoryid itemdict,how i create nested dictionary python so i want data form categoryid productid productinstanceprodid instance basically something like lets say i want check whether productid category i dicthaskey true false my bad code fin readfiledb categorydict defaultdictlist itemdict line fin iteminstance setiteminstancesline itemdictiteminstanceproductid iteminstance categorydictiteminstancecategoryidappenditemdict edit example dict pid pinstance pid pins pinthiscatid isntance thanks,3 dicts python basically always collection items item key value separated colon item separated next comma an item cannot one key value collections keys values looking second example dict pid pinstance pid pins pinthiscatid isntance outer dict needs another comma end first item key second key additionally quite clear instance meant mean often case methods objects passed object first parameter convention called self given name sometimes done reduce confusion metaclasses finally bare words pid forth rarely valid unless variable name assigned earlier attribute another object possibly selfpid i know problem,how i create nested dictionary python so i want data form categoryid productid productinstanceprodid instance basically something like lets say i want check whether productid category i dicthaskey true false my bad code fin readfiledb categorydict defaultdictlist itemdict line fin iteminstance setiteminstancesline itemdictiteminstanceproductid iteminstance categorydictiteminstancecategoryidappenditemdict edit example dict pid pinstance pid pins pinthiscatid isntance thanks,1 well bug report bug tracker exactly documentation though ah one even better okay possibly best one yet,the code x def f execx printx f runs python python prints different results is change documented anywhere a pointer mailing list discussion would also fine i ask purely curiosity,1 with ubuntu unity desktop environment ie ubuntu need whitelist application there different ways using gsettings application command line i get programs like skype showing system tray custom apps use wxpython,there tray unity ubuntu how i make icon appear somewhere unity wxtaskbaricon appear anywhere thanks,3 add import os projectroot ospathabspathospathdirnamefile settings py following managepy syspathinsert joinsettingsprojectroot apps syspathinsert joinsettingsprojectroot lib include installed apps would project root installedapps local apps myapp local libs pistondev allows bit freedom move apps around without redeclare imports,i starting first large django project realized default directory structure going work well i saw question answer decided implement something similar large django application layout what i need make something like work how i change django looks appsmodules,1 class needs functions class class could double inheritance class one def functself print i defined class one selfdata one class two def functself print i defined class two selfdata two class threeone two def functself print i defined class three selfdata three object created class three able call funct funct funct also object version selfdata selfdata selfdata ob three obdata prints one obfunct prints i defined class one now hand want function subclass call method superclass done class one def functself print class one class twoone def functself onefunctself ob two obfunct prints class one hope helps,hi trouble passing variablesdoing functions classes right i something like class def hi print class class def hi print class class def hi print class lets say class i would like execute function class how i go i googling awhile much success except finding images snakes any help problem would greatly appreciated,2 a fast solution query catalog like client xmlrpclibserverproxy httpuserpasswordblahcomplone completepath joinclientgetphysicalpath sitesngpathtofolder lenclientportalcatalogsearchresultspathcompletepath return true another solution could traverse folders structure like client xmlrpclibserverproxy httpuserpasswordblahcomplone path sitesngpathtofolder subdirs pathsplit dir client subdir subdirs subdir dirobjectids dir dirsubdir else return false return true edit i ammend answer i tried interact portalcatalog via xmlrpc actually easy my two options good use via xmlrpc so taking example transmogrifyploneremote simple option different implementation checking remote folder exists try path httpuserpasswordblahcomplonesitesngpathtofolder xmlrpclibserverproxypathgetphysicalpath return true except xmlrpclibfault e return false,i use xmlrpclib wsapiplone connect plone client xmlrpclibserverproxy httpuserpasswordblahcomplone method check folder plone exists url something like clientexists sitesngpathtofolder what i bit cheating try clientgettypes sitesngpathtofolder except exception means folder create clientpostobjectfolder i dont admin rights look methods list i told somewhere plone site i need admin i want keep ask question method available plone methods list anywhere web,1 this i make executable script it take eggs anything like account it simple script i want able execute i assuming using linux usrbinenv python import sys def main do something whatever processing need make happen don shove everything main break testable functions whatever function returns exit code interpreter ie script because main called sysexit behave differently depending return so return none returned if return integer return code used anything else printed console error returned anerroroccurred return i returning string printed returned otherwise success returned return this true script run interpreter imported another module name main main return success something else usually error sysexitmain now permissions set correctly execute script one thing realize script processed line executed interpreter this true regardless processor gets that importing script module executing script essentially work execute line module once realize script simply executing runs realize order functions matter a function declaration function declaration it call function matters so general layout script looks like def func pass def func pass def main return name main sysexitmain you create functions want use first use hope helps,i python script i wondering i make executable words i run using shell like bash i know first thing stick first line usrbinenv python i need example functions specific order ie main one top bottom what i need keep extension py python file i call function dosomething to short could provide simple guide important points someone take account make python file executable,1 found solution chatting automatedtester irc currently python webdriver implementation ignores selfbaseurl value get url need use full url bug report filed likely updated near future webdriver version,just title says i copy selenium installed svn repo when i import run things console everything works i try run unittest even one exported directly selenium ide open browser hang without trying open url additional details os ubuntu python browser firefox tried httpunit though i kept getting illegal character errors code import unittest import time import selenium import webdriver seleniumwebdrivercommonby import by seleniumcommonexceptions import nosuchelementexception localconfig import baseurl basefolder driver baseurl httplocalhost basefolder dirtosite driver firefox class checksitemapunittesttestcase def setupself global baseurl global driver driver firefox selfdriver webdriverfirefox elif driver httpunit selfdriver webdriverremotedesiredcapabilitieswebdriverdesiredcapabilitieshtmlunit else raise exception driver set selfdriverimplicitlywait selfbaseurl baseurl print selfbaseurl selfverificationerrors def getsitemapself global basefolder global driver print basefolder driver selfdriver op ssitemapxml basefolder driver httpunit op ss selfbaseurl oplenop print op drivergetopreplace print hello world urls print driverpagesource r recompiler href match rfinditerdriverpagesource urlsappendmatchgroup lenurls r recompiler locloc redotall match rfinditerdriverpagesource urlsappendmatchgroupstrip return urls def testchecksitemapself global driver driver selfdriver urls selfgetsitemap print urls url urls driver httpunit drivergeturl else drivergeturlreplaceselfbaseurl researchrphp line driverpagesource selfverificationerrorsappend php error url def iselementpresentself try selfdriverfindelementbyhow valuewhat except nosuchelementexception return false return true def teardownself selfdriverquit print selfverificationerrors selfassertequal selfverificationerrors name main unittestmain ideas,1 because called supergoblin selfinitself power maxhp magic maxmp speed name without difficulty you probably also want inherit like class enemyobject make sure enemy newstyle class x i guess must considering old way used super here simpler example class animalobject def initself talk print init animal talk class catanimal def initself talk meow print init cat supercat selfinittalk name main tom cat outputs init cat init animal meow edit well following work perhaps old class definitions cached interpreter try running fresh interpreter class enemyobject def initself difficulty power maxhp magic maxmp speed name selfpower power difficulty selfhp selfmaxhp maxhp difficulty selfmagic magic difficulty selfmp selfmaxmp maxmp difficulty print raaarghh i formidable formatname class goblinenemy def initself difficulty power maxhp magic maxmp speed namegoblin supergoblin selfinitdifficulty power maxhp magic maxmp speed name name main g goblinname user goblin,i trying make class generic init values defaults subclasses class enemy def initself difficulty power maxhp magic maxmp speed name selfpower power difficulty selfhp selfmaxhp maxhp difficulty selfmagic magic difficulty selfmp selfmaxmp maxmp difficulty class goblinenemy def initself difficulty power maxhp magic maxmp speed name goblin supergoblin selfinitself power maxhp magic maxmp speed name however i try make goblin object without full number default values like i put value difficulty tells i need full arguments even though rest given default values is reason i i something wrong,2 do chance recreate database it seems might something wrong as side note you call datetimenow createdat already set default field datetimenow,i basic model django class casemodelsmodel name modelscharfieldmaxlength createdat modelsdatetimefielddefaultdatetimenow updatedat modelsdatetimefielddefaultdatetimenow def saveself selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsave class meta dbtable u cases because i specify pk django took care i see field database called id marked primary key autoincrement i find odd getting warning since everything cool db model end the error mysqlexceptionswarning warning field id default value my work around saving set id it kills warning id gets set properly anyway since mysql handles case case caseid ugly workaround warning field id default value casename requestpostu casename casesave the issue solution it ugly the new pk inaccessible saving makes impossible serialize properly does anyone know fix i running python djangoversion final mysql ver distrib appledarwin using readline mysqlpythonpymacosxxegg and create table looks like create table cases id int not null autoincrement name varchar not null createdat datetime not null updatedat datetime not null primary key id enginemyisam autoincrement default charsetlatin,3 your save method really necessary use arguments datefieldautonow datefieldautonowadd those arguments handle createdat updatedat attributes datefieldautonow automatically set field every time object saved useful lastmodified timestamps datefieldautonowadd automatically set field object first created useful creation timestamps try using default save method hope helps more info autonow autonowadd httpsdocsdjangoprojectcomendevrefmodelsfieldsdatefield,i basic model django class casemodelsmodel name modelscharfieldmaxlength createdat modelsdatetimefielddefaultdatetimenow updatedat modelsdatetimefielddefaultdatetimenow def saveself selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsave class meta dbtable u cases because i specify pk django took care i see field database called id marked primary key autoincrement i find odd getting warning since everything cool db model end the error mysqlexceptionswarning warning field id default value my work around saving set id it kills warning id gets set properly anyway since mysql handles case case caseid ugly workaround warning field id default value casename requestpostu casename casesave the issue solution it ugly the new pk inaccessible saving makes impossible serialize properly does anyone know fix i running python djangoversion final mysql ver distrib appledarwin using readline mysqlpythonpymacosxxegg and create table looks like create table cases id int not null autoincrement name varchar not null createdat datetime not null updatedat datetime not null primary key id enginemyisam autoincrement default charsetlatin,1 save method sometimes uses additional arguments keywors arguments dont handle i sure may fix problem def saveself args kwargs selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsaveargs kwargs,i basic model django class casemodelsmodel name modelscharfieldmaxlength createdat modelsdatetimefielddefaultdatetimenow updatedat modelsdatetimefielddefaultdatetimenow def saveself selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsave class meta dbtable u cases because i specify pk django took care i see field database called id marked primary key autoincrement i find odd getting warning since everything cool db model end the error mysqlexceptionswarning warning field id default value my work around saving set id it kills warning id gets set properly anyway since mysql handles case case caseid ugly workaround warning field id default value casename requestpostu casename casesave the issue solution it ugly the new pk inaccessible saving makes impossible serialize properly does anyone know fix i running python djangoversion final mysql ver distrib appledarwin using readline mysqlpythonpymacosxxegg and create table looks like create table cases id int not null autoincrement name varchar not null createdat datetime not null updatedat datetime not null primary key id enginemyisam autoincrement default charsetlatin,1 django uses wsgi designed synchronous processing want easy that said one guy seems done implementation asynchronous responses that probably efficient reliable least possible,say i want ajax get request goes django view instead returning response client could i store request dictionary list forget leaving ajaxclient waiting response then say something happens server i use another view function retrieve request create response send client this kind like ajax push approach is possible done django efficient,1 no cons implementation detail lisplike languages exist meaningful sense python,is equivalent cons python version if built or i need easyinstall get module,1 you quite trivially define class behaves much like cons class consobject def initself car cdr selfcar car selfcdr cdr however heavyweight way build basic data structures python optimised i would expect results much cpumemory intensive something similar lisp,is equivalent cons python version if built or i need easyinstall get module,1 note python lists implemented vectors linked lists you could lstinsert val operation on if want data structure behaves like linked list try using deque,is equivalent cons python version if built or i need easyinstall get module,2 in python typical use arraybased list class lispstyle linked lists but hard convert def consseq result none item reversedseq result item result return result def iterconsseq seq none car cdr seq yield car seq cdr cons none itercons generator object uncons xd list,is equivalent cons python version if built or i need easyinstall get module,3 that standard precision floats python for arbitrary precision use bigfloat package,how i print digits float python right print sqrnewton sqrnewton newton algorithm square roots returns float gives many digits decimal place i get,3 they encrypted use smtp tls ssl,when i send credentials using login method python smtp library go wire encrypted plaintext,2 i fixed filtering warning import warnings warningsfilterwarningsignore field id default value now saving serialization looks good,i basic model django class casemodelsmodel name modelscharfieldmaxlength createdat modelsdatetimefielddefaultdatetimenow updatedat modelsdatetimefielddefaultdatetimenow def saveself selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsave class meta dbtable u cases because i specify pk django took care i see field database called id marked primary key autoincrement i find odd getting warning since everything cool db model end the error mysqlexceptionswarning warning field id default value my work around saving set id it kills warning id gets set properly anyway since mysql handles case case caseid ugly workaround warning field id default value casename requestpostu casename casesave the issue solution it ugly the new pk inaccessible saving makes impossible serialize properly does anyone know fix i running python djangoversion final mysql ver distrib appledarwin using readline mysqlpythonpymacosxxegg and create table looks like create table cases id int not null autoincrement name varchar not null createdat datetime not null updatedat datetime not null primary key id enginemyisam autoincrement default charsetlatin,1 here resources relied troubleshoot getting scientific python rig snow leopard lion hyperjeff blog first used reference snow leopard lion it excellent thorough stepbystep guide installing bit numpy scipy matplotlib mac os x though seemed equally helpful this survival guide couple things going stepbystep guide makes assumptions instance first step configuring bashprofile appropriate environmental variables deployment target package config paths cflags actually supplies code individual shell commands retrievedownload configure build install three packages dependencies addition blog post supplies diffs config files author recommends edit prior installation vetted community perhaps comments original post nearly author responded cases revised text original guide addition comments cover quite edge cases washington university astrology department this began panther actually date bothered revise document cases revision trivial change eg this resource useful discussed detail always seems problem menumpy scipy ok matplotlib fails fails libpng libjpeg et al some empirically likely causes failed install numpyscipymatplotlib unfortunately based personal experience libpng freetype zlib matplotlib dependencies one possible source problems source caused matplotlib versions compile default libpng version yet version developer likely mac version included x shipped versions xcode version this issue aside good idea use xquartz rather xll supplied xcode likewise past applesupplied x included broken version freetype v particular matplotlib default config straightforward way opt defaults edit makeosx setupcfgtemplate files included matplotlib source toplevel directory the posts hyperjeff blog supine sublime blog helpful set issues applesupplied fast fourier transform library various issues believe one persistent lack fortran bindings fft library version supplied mac developer tools in event difficult get latest version gold standard fft libraries fftw install source,what could i done instead order get items working together should i move everything windows i prefer reliable way okay happened i wanted install numpyscipy onto mac runs unfortunately numpy ver supports python i go install python but python work appicon bounces automatically quits this strange retrospect i heard python numpy ships mac i tried using sample code numpy website failed now real bind i eventually found httpstronginferencecomscipysuperpack which somehow installs numpy scipy matplotlib ipython pandas well pymc alpha it seemed like worked numpy work example code provided python but i working practice problems i found matplotlib working anymore the python launcher i think python launcher appicon says python name bounces app tray eventually freezes i worried could i matplotlib installed i followed instructions clean uninstall matplotlib followed installation scipysuperpack still fails way now i done clean install matplotlib hopes works and i import pylab throws ton error messages any advice would greatly appreciated,1 i know mechanism perform screen recording python however may able use python control one many existing screen recording programs recorditnow recordmydesktop byzanz istanbul vncswf pyvncswf,is library making screen recorder application python think would fun make somthing like library work linux im using ubuntu thanks,1 i sure operating system using bigfloat requires mpfr gmp libraries already exist computer it may easy use windows there two multiple precision libraries available support windows mpmath written pure python stable well documented gmpy currently active development the next release stable api famous last words if bigfloat works great it welldesigned documented package disclaimer i maintain gmpy helped mpmath,how i print digits float python right print sqrnewton sqrnewton newton algorithm square roots returns float gives many digits decimal place i get,2 to honest i skipped helloworld bit went straight lazy pirate pattern clientserver that one bugs python version client retry loops least something i added print statements got proper clientserver communication going after i wrote memcache kind server using json objects message bodies eg cmd get key albert jones a couple months later i needed persistent keyvalue server work multiprocessing system i turned existing code sqlite keyvalue server by keyvalue i mean entire schema server one table kvstore two columns key val i server accessed client processes time hitches i also tried hand writing server uses actual memcache protocol using asynchat far complex using zeromq so advice move if hello world example work try different one ps if want portable python distro runs fedora distro look httpsgithubcomwavetossedpybuild currently build ubuntu system resulting tarball includes shared library dependencies runs redhatrpm style distros suserpm style distros it plenty examples building rd party libraries problems adding favourite modules python distro,i trying get zeromq working python fedora as needed python i installed activepython i installed pyzmq using easyinstall installed fine when i run hello world example httpzguidezeromqorgpyhwclient it blocks socketrecv i read issues send messages faster client receive cause client miss first message so i sure whether expected behaviour least possible behaviour i would thought simple hello world example would worked box what i trying figure whether code installation causing problem anyone come across something similar,1 contacted author boto learned getcanonicaluserid sconnection class this give canonical user id credentials associated connection the connection used operation eg listing buckets very awkward possible,does canonical user id exist federated user created using sts when using boto i need canonical user id grant permissions bucket here quick tour code i successfully created temporary credentials using boto sts module using master account gives back federateduserarn federateduserid packedpolicysize accesskey secretkey sessiontoken expiration then i create bucket using boto bucket selfsconnectioncreatebucket sstore appid now i want grant permissions i left two choices boto addemailgrantpermission emailaddress recursivefalse headersnone addusergrantpermission userid recursivefalse headersnone displaynamenone the first method option since email attached federated user i look second here second parameter userid the canonical user id associated aws account granting permission but i seem find way come federated user do canonical user ids even exist federated users am i overlooking easier way grant permissions federated users,1 solution explicitly invoke python using python filepy described httpwwwvelocityreviewscomforumstproblemsrunningvirtualenvunderwindowshtml reason python registered py windows invoke virtualenv,i virtualenv installed windows in cmd run python look syspath see virtualenv path included run managepy django i see virtualenv path virtualenv working django server why,1 my money misspelled name i notice error message omnicloudappaccounts omnicloudappuser second table uses singular there second table like chance omnicloudappusers also using mixed case identifiers postgresql great source reputation so it bite sooner later victims folly regulars any table name maybe forgot double quotes omnicloudappuser somewhere omnicloudappuser it either transaction saving user committed yet can create user accounts yet check ends right database table right id edit tools diagnose problem if know users created question foreign key constraint useridrefsidfbceced look right place same database same schema same table to find tables exists database try following query necessary privileges select nnspname as schemaname crelname as tablename crelhastriggers creltuples from pgcatalogpgclass c left join pgcatalogpgnamespace n on noid crelnamespace where crelname user and crelkind r and nspname pgcatalog shows tables schemas user name case insensitive plus table triggers could cause problem many rows estimate updated analyze might give lead you also use metacommand standard command line client interactive terminal psql i would run test case postgres server log everything gets set parameter purpose set logstatement the manual loggingparameters logstatement enum controls sql statements logged valid values none ddl mod statements the manual set parameters,go edit calling following adduser function viewspy i save user first id automatically created django upon insert primaryforeign key accounts passwords adding user seems working fine gets accountsuseru following error throws integrityerror adduser insert update table omnicloudappaccounts violates foreign key constraint useridrefsidfbceced detail key userid present table omnicloudappuser but key since saved user db def adduserrequest username requestpost username password requestpost password u userobjectscreateuserusername requestpost email password usave accountsuseru p passwordsuseru asave psave user authenticateusernameusername passwordpassword user none userisactive authloginrequest user return httpresponseredirects uid else return httpresponseredirectaccountinvalid edit here beginning initialization accounts djangodb import models djangocontribauthmodels import user class accountsmodelsmodel user modelsforeignkeyuser edit i realized going admin page it complains database adding rd user adding th user throws error user id duh i see anything code would cause search userid ideas to war chest,2 i use sessions store last ping datetime session parameter don worry database hits certain point would feel getting many switch session storage cache make application robust cacheflushing one friends used host relatively popular djangobased social networking game pretty much standard virtual private server took forced switch cachebased sessions,the closest example case django ajax chat application the rooms need keep list active users aside displaying list users within chat given room might maximum number active users new users need blocked entering room currently i chat client page calling poll view every second via ajax the poll view returns text room i figure poll also type pinging adding users activeuser mm field room object i place far what i need next something drops users activeuser list kind timeout i imagine two ways i wondering would efficient app needs accurate second tenfifteen seconds using cookies sessions middleware la thread however seems method work momenttomoment info another model explicit usersrooms table datetime field time updated upon creation every ping following write function cleans old ones that i think i trying figure whether hitting mysql every second every user every room good idea wondering second indeed best option task thanks,2 mygroup groupobjectsgetnamemygroup mykeyword mykeywordsobjectscreatenamemykeyword mylistassoc mylistassocgroupmygroup mylistassocsave mylistassockeywordaddmykeyword if want remove association use removemykeyword instead addmykeyword however need intermediary model set relation groups keywords,how i create association mylistassoc how would i delete class groupmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname class mykeywordsmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname class mylistassocmodelsmodel group modelsforeignkeygroup keyword modelsmanytomanyfieldmykeywords mygroup groupobjectsgetnamemygroup mykeyword mykeywordsobjectscreatenamemykeyword,1 you use generator expression instead list comprehension elem item item mylist item do something,is possible basically following python elem mylist elem do something elem note i want specifically avoid using map lambdas filter create second list gives boolean condition i want following elem item item mylist item do something the latter method requires construction boolean list in code mylist large basically simplest way would write elem mylist elem do stuff i specifically want one line if allinoneline make code actually different last example i gave fine i go,3 check ifilter function itertools,is possible basically following python elem mylist elem do something elem note i want specifically avoid using map lambdas filter create second list gives boolean condition i want following elem item item mylist item do something the latter method requires construction boolean list in code mylist large basically simplest way would write elem mylist elem do stuff i specifically want one line if allinoneline make code actually different last example i gave fine i go,1 you need many many relation something like class groupmodelsmodel name modelscharfieldmaxlength uniquetrue keywords modelsmanytomanyfieldmykeywords def unicodeself return selfname class mykeywordsmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname then use mm relation group groupobjectsgetname something keyw mykeywordsobjectsgetname somethingelse groupkeywordsaddkeyw groupkeywordsall groupkeywordsremovekeyw note it recommended name class singular mykeyword instead mykeywords,how i create association mylistassoc how would i delete class groupmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname class mykeywordsmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname class mylistassocmodelsmodel group modelsforeignkeygroup keyword modelsmanytomanyfieldmykeywords mygroup groupobjectsgetnamemygroup mykeyword mykeywordsobjectscreatenamemykeyword,2 this looks like bug macports port python for sample works current macports python fails current macports python way reported macports automatically builds includes gdbm database manager python ports python includes berkeley db gdbm it looks like macports using db works fails using gdbm presumably macports port similar this investigated update if using uptodate macports installation likely problem reported httpbugspythonorgissue it looks like fix support latest gdbm beyond current macports version that fix applied python released macports folks backport python ports,i running python macports i attempting use shelve module i use successfully another dev machine different os etc i sure i may incorrectly any thoughts suggestions would greatly appreciated here error dbmerror db type could determined i searched error message found info i even tried force protocl see might help here interactive session python default oct gcc apple inc build darwin import shelve locker shelveopen myshelf protocol locker lockerclose exit python default oct gcc apple inc build darwin import shelve locker shelveopen myshelf protocol traceback recent call last file stdin line module file optlocallibraryframeworkspythonframeworkversionslibpythonshelvepy line open return dbfilenameshelffilename flag protocol writeback file optlocallibraryframeworkspythonframeworkversionslibpythonshelvepy line init shelfinitself dbmopenfilename flag protocol writeback file optlocallibraryframeworkspythonframeworkversionslibpythondbminitpy line open raise errordb type could determined dbmerror db type could determined,1 the second method fine fact use time the reason i putting answer infact something like work project years back turned although logging anything debug level production file cost creating debug message quite expensive impacting performance ie in production debug level message created boolean check instead in production debug messages created propagated logged file well fact setup logging the project pretty big calculation farm every ounce performance mattered case ever since might case hey thought would mention,in django settingspy defines debug whole project now my debug level independently configured settingspy how i use loggingdebug way settingsdebug loggingdebugdebug message way without checking settingsdebug loggingdebugdebug message what good practice i think use way since logging level already decides message logged but say way standard practice,1 here try ints except valueerror verr pass job handle contain anything convertible int except exception ex pass job handle exception occurred converting int,so i pretty stumped convert string int using tryexcept function does anyone know simple function i feel like i still little hazy string ints i pretty confident ints related numbers stringsnot much,3 it important specific exception trying catch using tryexcept block string abcd try intstring print except valueerror handle exception print please enter integer tryexcepts powerful something fail number different ways specify want program react fail case,so i pretty stumped convert string int using tryexcept function does anyone know simple function i feel like i still little hazy string ints i pretty confident ints related numbers stringsnot much,3 in typical wordcount example file name map file processing ignored since job output contains consolidated word count input files file level but get word count file level input file name used mappers using python get file name using osenvironmapinputfile command the list task execution environment variables the mapper instead emitting keyvalue pair hello also contain input file name processed the following emitted map inputtxt hello inputtxt key hello value now word counts particular file processed single reducer the reducer must aggregate word count particular file as usual combiner would help decrease network chatter mapper reducer also complete job faster check dataintensive text processing mapreduce algorithms text processing,i learning elastic mapreduce started word splitter example provided amazon tutorial sectioncode shown the example produces word count words input documents provided but i want get output word counts file names ie count word one particular document since python code word count takes input stdin i tell input line came document thanks usrbinpython import sys import def mainargv line sysstdinreadline pattern recompileazazazaz try line word patternfindallline print longvaluesum wordlower line sysstdinreadline except end file return none name main mainsysargv,3 the trunk version webdriversetwindowposition webdriversetwindowsize methods usrbinenv python import time contextlib import closing seleniumwebdriver import firefox pip install selenium closingfirefox browser browsersetwindowposition note might fail systems browsersetwindowsize timesleep,i wanted know maximize browser window using python bindings selenium webdriver,2 i exact problem last night i came across question mdash i also arch i guess problem could number different things solution i python version pythondisribute package installed therefore easyinstall easyinstall i believe case wrong version pythondistribute installed attempt previously install sphinx pacman installs version uninstalling sphinx subsequently unneeded dependencies pacman rsu pythonsphinx installing pythondistribute got right version easyinstall reinstalling sphinx easyinstall sphinx installation works expected if things depend pythondistribute process may little different but start trying remove pythondistribute work scrap last part it early morning i thinking straight pythondistribute pythondistribute seperate packages i believe coexist so problem need check pythondistribute install ensure use easyinstall install sphinx hope helps,i try create documentation project written python x sphinx tool i want use according official site last version compatible python my os archlinux linux distribution uses python default python package the installation configuration straight forward easyinstall u sphinx sphinxquickinstall i never asked choose x x python interpreter but i ask sphinx create documentation project code analyzed i wrote python x is sphinx ready python x did i make mistake,3 no matter point python interpreter going reading unobfuscated python bytecode from dead easy get back source code minus comments nonobvious layout this everybody says pretty much impossible obfuscate python the fact pretty much impossible obfuscate python implies good tools i afraid wishful thinking say i know done effectively tools probably best encrypt code standard encryption tools write little wrapper program language decrypts python runs program deletes unencrypted code done if want put way much effort could probably something c api embedding python interpreter c program feed unencrypted python interpreter memory rather files disk note schemes still relatively easy get around work want provide importable python modules rather whole programs which i expect find anyone already written tool,is existing python code obfuscating tool python please try teach python right choice i want hideobfuscate code or correct licenses protect code instead obfuscation update this question duplicate issue how i protect python code i simply ask tool obfuscate python nothing nothing less if none i wonder i get much feedback,3 there perl netepp package cpan implements lowlevel highlevel epp clients,do epp clientside implementations languages java exist i mostly interested c tcl client implementation also python perl,2 looking documentation syslastvalue friends their intended use allow interactive user import debugger module engage postmortem debugging without reexecute command caused error so interpreter debugging i suggest using syslastvalue script i suggest use sysexcinfo,should i prefer sysexcinfo syslastvalue friends syslasttype syslasttraceback,2 instead letting excelmicrosoft dictate store datetime would less trouble work rely standardobvious way things process objects according standards domain python way datetime objects inside pythonsqlalchemy sql way inside sqlite native datetime type instead float use apis necessary translation domains python talks sqlite via sqlalchemy python talks excel via xlrdxlwt python talks systems python glue using standard datetime types sqlite allows write sql without python involve standard readable way where date between and makes much sense where date between and it allows easily port another dbms without rewriting adhoc functions applicationdatabse needs grow using native datetime objects python allows use lot freely available well tested noneee embrace extend extinguish apis sqlalchemy one and i hope aware slight dangerous difference excel datetime floats mac windows who knows one clients would future submit excel file mac crash application actually worse suddenly earned million dollars error so suggestion use xlrdxlwt dealing excel python another package reading excel let sqlalchemy database use standard datetime types however insist continuing store datetime excel float could save lot time reuse code xlrdxlwt it functions converting python objects excel data viceversa edit clarity you issues reading database python class converts float python datetime you issues writing database sqlalchemy using native python functionsmodulesextensions trying force nonstandard type expecting standard python datetime exceldatetime type point view python float datetime although python uses dynamicduck typing still strongly typed it allow nonsensesilliness like adding integers string forcing float datetime at least two ways address declare custom type seems path wanted take unfortunately hard way it quite difficult create type float also pretend datetime possible yes requires lot study type instrumentation sorry grok documentation create utility functions should easier way imho you need functions floattodatetime converting data database return python datetime b datetimetofloat converting python datetime excel float about solution i saying could simplify life reusing xldatefromdatetimetuple xlrdxlwt that function convert datetime tuple year month day hour minute second excel date value install xlrd go pathtopythonlibsitepackagesxlrd the function xldatepy source well documented understanding,we sqlite databases datetimes actually stored excel format decent reason system standard representation choice sqlite databases may accessed multiple languagessystems have introducing python mix great success recent months sqlalchemy part the ability sqlite dbapi layer swiftly bind custom python functions sqlite lacks given sql function particularly appreciated i wrote exceldatetime type decorator works fine retrieving result sets sqlite databases python gets proper datetimes back however i real problem binding custom python functions expect input params python datetimes i thought bindparam i obviously missing something i cannot get scenario work unfortunately modifying functions convert excel datetimes python datetimes option neither changing representation datetimes database one systemlanguage may access the code selfcontained example run asis representative issue the custom function getmonth created fails receives raw data typeconverted data born column at end see i tried far errors spits is i trying impossible or different way ensuring bound function receives appropriate python type it problem i unable overcome far would great find solution import sqlalchemytypes types sqlalchemy import createengine table column integer string metadata sqlalchemysqlexpression import bindparam sqlalchemysql import select text sqlalchemyinterfaces import poollistener import datetime setup type decorator excelpython date conversions class exceldatetime typestypedecorator impl typesfloat def processresultvalue self value dialect lxdays int value lxsecs int roundvaluelxdays lxsecs lxsecs lxdays return datetimedatetimefromordinallxdays datetimetimedeltasecondslxsecs def processbindparam self value dialect value already excel float return value elif isinstancevaluedatetimedate return valuetoordinal elif isinstancevaluedatetimedatetime datepart valuetoordinal timepart valuehour valueminute valuesecond return datepart timepart time part day fraction create sqlite memory db via sqlalchemy def getmonth dt return dtmonth class connectionfactory poollistener def connect self dbapicon conrecord dbapiconcreatefunction getmonth getmonth eng createengine sqlitememory listenersconnectionfactory engdialectdbapienablecallbacktracebacks show better errors user functions meta metadata birthdays table birthdays meta column name stringprimarykeytrue column born exceldatetime column birthmonth integer metacreatealleng dbconn engconnect dbconnexecute insert into birthdays values jimi hendrix null demonstrate type decorator works get proper datetimes res dbconnexecute selectbirthdays tupleres u jimi hendrix datetimedatetime simple attempt blows attributeerror float object attribute month dbconnexecute textupdate birthdays set birthmonth getmonthborn involved attempt blows interfaceerror interfaceerror error binding parameter probably unsupported type dbconnexecute text update birthdays set birthmonth getmonthborn bindparamsbindparam born exceldatetime typemap born exceldatetime bornbirthdayscborn many thanks,1 does ossystem work import os ossystempathtoscriptsh,i trying run scripts python mac os i unable run scripts run bashsh scripts one idea i run bashsh from python mac os thanks help this scripts called runscriptsh i need run python script,2 get database group fairly easy piece code obviously adapt actual model schools schoolobjectsorderby name schooldict school schools firstletter schoolnamelower firstletter schooldict schooldictfirstletterappendschool else schooldictfirstletter school,i currently data model set school object name on primary page website i outputting school objects sorted alphabetically name i hoping would way django create index titles objects by i mean categorize school object first letter name this would prove useful i provide section titles potentially long list schools ideally instead returning school objects template i want manipulate sort objects way categorized dictionary arrays keys main dictionary letters alphabet excluding school names starting letter values arrays schools whose name starts first letter corresponding key this would make easy loop django templating system accomplish want section headers any help would greatly appreciated is native django or i going employ python logic,1 mainsysargv calls main content list sysargv respective arguments main method case equivalent mainsysargv mainsysargv sysargv depending length sysargv so call asterisk passes name first element list sysargv if call without asterisk passes name whole list sysargv,what star operator input argument list example def mainname datadir print name typename name main mainsysargv concretely i run program star operator prints name type str run without star mainsysargv prints name type list,1 the operator unpacks argument list it allows call function list items individual arguments for instance sysargv foo bar quux mainsysargv equivalent mainfoo bar quux,what star operator input argument list example def mainname datadir print name typename name main mainsysargv concretely i run program star operator prints name type str run without star mainsysargv prints name type list,3 this questions stale reference using ipython zeromq enabled take look vimipython older version shipped using plugin send lines whole files ipython execute also get back object introspection word completions vim like get objectenter objecttab ipython take look two screencasts plugin action post,i found ipython i report i deep love and affection immediate i think affair turn something lasting like one i screen ipython screen happen best friends triangular drama purely platonic mind the reason ipython hits soft spots much i generally like command prompts especially nixinspired prompts inspiration ksh csh yes chs monster prompt sport lots really good features bash zsh and ipython sure feel like home nix prompt rider mixing system shell python also really good idea plus course ipython helps lot solving python challenge riddles invaluable even now i love vim since i learnt vi back days turning back and i mac i choice now i like glue together ipython macvim workflow what i done far i start ipython using ipython e open macvim thus i edit ipython starts macvim filemodule loaded could look bit like in run foo this also imports foo anew hello world in edit foo editing done executing edited code this happens immediately hello world in run foo hello so world ok i think improved maybe way tie ipython macvim please share experiences of course use textmate fav editor i interested maybe lessons general,3 i go obfuscating approach i rather investigate alternative ways ship executable binary files instead bytecode tools known probably others httpwwwohlohnetppyc converts python c code compile httpwwwpyinstallerorg httpcxfreezesourceforgenet httpwwwpyexeorg windows httpsvnpythonmacorgpyapppyapptrunkdocindexhtml mac i know hackproof tools i think worth taking look edit damnit missed python part it little hard help write anything product os gui etc if also python code written code python already i suggest,is existing python code obfuscating tool python please try teach python right choice i want hideobfuscate code or correct licenses protect code instead obfuscation update this question duplicate issue how i protect python code i simply ask tool obfuscate python nothing nothing less if none i wonder i get much feedback,1 you tried use local variables class attributes try following changes class dobject def createself selffoo selfbar squirrels baz i insane head selffoo selfbar return baz class cd def createself superc selfcreate print selffoo selfbaz i cute yard selffoo selfbar ccreate,how i overload class methods i failed class dobject def createself foo bar squirrels baz i insane head foo bar return baz class cd def createself superc selfcreate baz i cute yard selffoo selfbar ccreate traceback attributeerror c object attribute foo,2 strin b script b compiler b cds b algo b timing arr strinstrip split res partstripb part arr res script compiler cds algo timing,i variable data data b script b compiler b cds b algo b timing i need convert remove occurrence b list how,1 not sure whether would help works sample initlist b script b compiler b cds b algo b timing resultlist strx x initlist or p resultlist xdecodeutf x initlist utf encoding used check decode function also may want take look following related so thread,i variable data data b script b compiler b cds b algo b timing i need convert remove occurrence b list how,2 b script b compiler b cds b algo b timing mapstr script compiler cds algo timing,i variable data data b script b compiler b cds b algo b timing i need convert remove occurrence b list how,2 here one way arguably pythonic if want parse byte string use struct module provided exact purpose import struct collections import namedtuple details namedtuple details name phone def lazyparsedata extract name phone data buffer if buffer could parsed parseerror raised try name structunpackfromdp lendata data phone structunpackfromdp lendatalenname data lenname except structerror raise parseerror return detailsname phone what i still find unpythonic throwing away useful structerror traceback replace parseerror whatever original tells wrong string latter tells something wrong,here quote httpstackoverflowcomusersgreghewgill answer good primer python slice notation python kind programmer fewer items ask for example ask contains one element get empty list instead error sometimes would prefer error aware may happen so error prefered pythonic way proceed is pythonic way rewrite example class parseerrorexception pass def safeslicedata start end start end assumed r datastartend lenr end start raise indexerror return r def lazyparsedata extract name phone data buffer if buffer could parsed parseerror raised try namelength orddata extractedname safeslicedata namelength phonelength orddata namelength extractedphone safeslicedata namelength namelength phonelength except indexerror raise parseerror return extractedname extractedphone name main print lazyparsexjackxa ok print lazyparsexjackxa raise parseerror edit example simpler write using byte strings real code using lists,3 the backdoor looking following get width widest label since every label need shift amount align right shift maxtgetwindowextentwidth legendgettexts legendgettexts tsetha right ha alias horizontalalignment tsetpositionshift,i trying rightalign entries matplotlib axes legend default leftaligned seem find way the setup i i added data labels myfig axes using axplot command ax myfiggetaxes legendfont fontpropertiessize axlegendproplegendfont numpoints markerscale there list legend keyword arguments docs matplotlib axes seem straighforward way set alignment legend entries anybody know backdoor way thanks edit to clarify i trying achieve right legend looks like maneuver oct utc bias oct utc i want look like maneuver oct utc bias oct utc,3 the problem xlrdnamedstyle different xlwtxfstyle the question seems duplicate preserving styles using pythons xlrdxlwt xlutilscopy,specifically i trying open existing workbook write data however whenever i write data obliterates borders cells so i wondering way copy style cell writing reapply i think i might right track code xlrd import openworkbook xlwt import easyxf xlutilscopy import copy xlutilsstyles import styles rbopenworkbook sourcexls formattinginfotrue styles stylesrb rsrbsheetbyindex wbcopyrb wswbgetsheet icell enumeraterscol continue cellstyle stylesrscelli wswriteicellvaluecellstyle wbsave outputxls but i getting error attributeerror namedstyle instance attribute font,2 unfortunately support bit python windows relatively poor bit version it fault python community relative difficulty getting free compilers bit windows if installed bit version python also need use packages built bit some simple python packages written pure python requiring externalc libraries install normal using setuptoolseasyinstallvirtualenv a lot bit packages however might break installed virtualenv require installer fortunately find bit precompiled installers popular packages try package first the installer target globalmain installation python thus isolated virtualenv note however unofficial builds provided free convenience please sue provider things fail expect help,i wonder right way install virtualenv bit python pywin module operating system windows bit i found exe installer sourceforge when run easyinstaller command line first everything goes fine soon see strange behavior pywinwinamdpy installs runs pywinpywinegg fails error no local packages download links found pywin best match none and full log sandboxvirtenv dtestpyexetesteasyinstall httpsourceforgenetprojectspywinfilespywinbuildpywinwinamdpyexe downloading httpsourceforgenetprojectspywinfilespywinbuildpywinwinamdpyexe processing pywinwinamdpyexe pywintypes module references file winevtlogutil module references file winserviceutil module references file wintimezone module references file demoswinrcparserdemo module references file demossecuritysspivalidatepassword module references file isapiinstall module references file isapisamplesadvanced module references file isapisamplestest module references file isapitestsetup module references file pywinframeworkscriptutils module references file pywinframeworkstartup module references path pywinscintillaconfig module references path pywinscintillacontrol module references file pywinscintillaidleenvironment module references file scriptsregsetup module references file scriptssetupd module references file testtestall module references file testtestclipboard module references file testtestwinapi module references file testtestwinrcparser module references file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandbdisteggpy unicodewarning unicode equal comparison failed convert arguments unicode interpreting unequal symbols dictfromkeysitersymbolscode testtestwintrace module references file wincominit module references path wincomserverregister module references file wincomserverregister module references path wincomtestgentestscripts module references path wincomtestpipposerver module references file wincomtesttestall module references file wincomtesttestaxscript module references path wincomtesttestdictionary module references file wincomtesttestpippo module references file wincomtesttestpycomtest module references file wincomtesttestservers module references file wincomtestutil module references file wincomextadsiinit module references path wincomextauthorizationinit module references path wincomextaxcontrolinit module references path wincomextaxdebugcodecontainer module references file wincomextaxdebugdebugger module references file wincomextaxdebuginit module references path wincomextaxscriptinit module references path wincomextbitsinit module references path wincomextdirectsoundinit module references path wincomextdirectsoundtestdstest module references file wincomextinternetinit module references path wincomextmapiinit module references path wincomextshellinit module references path wincomextshelldemosserversemptyvolumecache module references file wincomextshelldemosserversfolderview module references file wincomexttaskschedulerinit module references path creating cusersantpkyiappdatalocaltempeasyinstallkclmxkpywinpywinegg adding cusersantpkyiappdatalocaltempeasyinstallkclmxkpywinpywineggtmp creating dtestsandboxvirtenvlibsitepackagespywinpywinegg extracting pywinpywinegg dtestsandboxvirtenvlibsitepackages adding pywin easyinstallpth file installing pywinpostinstallpy script dtestsandboxvirtenvscripts installing pywinpostinstallpyc script dtestsandboxvirtenvscripts installing pywintestallpy script dtestsandboxvirtenvscripts installing pywintestallpyc script dtestsandboxvirtenvscripts installed dtestsandboxvirtenvlibsitepackagespywinpywinegg processing dependencies pywin searching pywin reading httppypipythonorgsimplepywin reading httpsfnetprojectspywin reading httpssourceforgenetprojectspywinfilespywin reading httpsourceforgenetprojectshowfilesphpgroupid no local packages download links found pywin best match none traceback recent call last file dtestsandboxvirtenvscriptseasyinstallscriptpy line module loadentrypoint setuptoolsc consolescripts easyinstall file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line main witheiusagelambda file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line witheiusage return f file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line lambda distclassdistributionwithouthelpcommands kw file cpythonlibdistutilscorepy line setup distruncommands file cpythonlibdistutilsdistpy line runcommands selfruncommandcmd file cpythonlibdistutilsdistpy line runcommand cmdobjrun file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line run selfeasyinstallspec selfnodeps file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line easyinstall return selfinstallitemnone download tmpdir deps true file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line installitem selfprocessdistributionspec dist deps file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line processdistribution requirement selflocalindex selfeasyinstall file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggpkgresourcespy line resolve dist bestreqkey envbestmatchreq self installer file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggpkgresourcespy line bestmatch return selfobtainreq installer try downloadinstall file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggpkgresourcespy line obtain return installerrequirement file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line easyinstall selflocalindex file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolspackageindexpy line fetchdistribution return distclonelocationselfdownloaddistlocation tmpdir attributeerror nonetype object attribute clone sandboxvirtenv dtestpyexetest now import python winapi quite confusing sandboxvirtenv dtestpyexetestpython python default jun msc v bit amd win type help copyright credits license information import winapi if find something unclear ask thanks advices,1 do want something like import csv open largecsv w f writercsvwriterf delimiter lineterminator n range row j j rangei writerwriterowrow also rowcolumn headers import csv open largecsv w f writercsvwriterf delimiter lineterminator n writerwriterow range range row j j rangei writerwriterowrow the latter returns following file i replaced,import csv open largecsv w f writercsvwriterf delimiter lineterminator n range j rangei aappendij print ija want write csv file like i done avoid caculation twice list grow large i initialize againafter one iteration outer loop so i want listbefore get initialized written csv file manner i able soplease help,3 you use plain dom httpdocspythonorglibraryxmldomminidomhtml parse source xmldomminidom import parse datasource open ctempmydataxml doc parsedatasource find nodes remove node docgetelementsbytagname div attr nodeattributes attrname id found targeted nodes replace new comment node parent nodeparentnode parentreplacechilddoccreatecommentpage break node docs httpdocspythonorglibraryxmldomhtml,what good way replace html tag like old div idpgbrk page breakdiv new page break div id might many values hence regex good idea hence i need lxml kind things basically problem replace html tag string,1 as long div parent tag could import lxmlhtml lh import lxmletree et content rootdiv idpgbrk page breakdivroot doclhfromstringcontent printlhtostringdoc div docxpath dividpgbrk parentdivgetparent parentreplacedivetcommentpage break printlhtostringdoc yields rootpage breakroot,what good way replace html tag like old div idpgbrk page breakdiv new page break div id might many values hence regex good idea hence i need lxml kind things basically problem replace html tag string,2 just came across issue way i solved remove sender function arguments check inside callback function djangodbmodels import signals features import models features def createfeaturesapp createdmodels verbosity kwargs print creating features app features work compares models module instances return do stuff signalspostsyncdbconnectcreatefeatures that way keep management module like django docs suggest i agree work like suggested you could probably dig implementation signal class djangodispatch,i myappmanagementinitpy registering postsyncdb handler like djangodbmodels import signals features import models features def createfeaturesapp createdmodels verbosity kwargs print creating features do stuff signalspostsyncdbconnectcreatefeatures senderfeatures i verified following both features myapp settingsinstalledapps myappmanagement getting loaded prior syncdb running verified via print statement module level the features app getting processed syncdb emitting postsyncdb signal verified examining syncdb output verbosity i using exact idiom another pair apps handler called correctly i compared two modules found relevant differences invocations however myappmanagementcreatefeatures never called what i missing,1 using function like safeslice would faster creating object perform slice speed bottleneck looking nicer interface could define class getitem perform checks returning slice this allows use nice slice notation instead pass start stop arguments safeslice class safesliceobject slice rules httpdocspythonorglibrarystdtypeshtmlsequencetypesstrunicodelisttuplebytearraybufferxrange def initselfseq selfseqseq def getitemselfkey seqselfseq isinstancekeyslice startstopstepkeystartkeystopkeystep start seqstart stop stop stoplenseqstop seqstop return seqkey seq printseq printsafesliceseq printsafesliceseq indexerror list index range if speed issue i suggest testing end points instead arithmetic item access python lists o the version safeslice also allows pass arguments with arguments second interpreted stop value similar range def safesliceseq start stopnone step stop none stopstart start else seqstart stop stoplenseqstop seqstop return seqstartstopstep,here quote httpstackoverflowcomusersgreghewgill answer good primer python slice notation python kind programmer fewer items ask for example ask contains one element get empty list instead error sometimes would prefer error aware may happen so error prefered pythonic way proceed is pythonic way rewrite example class parseerrorexception pass def safeslicedata start end start end assumed r datastartend lenr end start raise indexerror return r def lazyparsedata extract name phone data buffer if buffer could parsed parseerror raised try namelength orddata extractedname safeslicedata namelength phonelength orddata namelength extractedphone safeslicedata namelength namelength phonelength except indexerror raise parseerror return extractedname extractedphone name main print lazyparsexjackxa ok print lazyparsexjackxa raise parseerror edit example simpler write using byte strings real code using lists,1 according python documentation subprocesscall runs command waits complete equivalent subprocesspopen followed popenwait however popenwait method documentation explicitly warns problem buffer overflow recommends use popencommunicate instead hence solution looking something like import subprocess process subprocesspopencmd stdoutsubprocesspipe stdinsubprocesspipe shelltrue stdout stderr processcommunicate print show something subprocess,i problem using subprocesspopen subprocesscall i use execute command lines generates lot output python scripts hangs weird waiting script hanging state i find job commanded cmd line done script hung subprocesscallcmd shell true or subprocesspopencmd stdout subprocesspipe stdin subprocesspipe shell true hangs here print show something subprocess note last print never executed actually cmd executed note also cmd related serial port i plug serial cable everything become fine last print statetement get executed but i use terminal everything fine even serial plugged occurs python script thanks lot,3 you use httpceleryprojectorg works like charm nice django integration well documented used many,i fairly complex report generating work needs generated spaning multiple tables final report created excel sheetthe process takes anything minutes we provided django web app client only issue client requests report generating url takes time issue far ui go i would like task running behind mail client link report what right strategy libraries used,2 i accept comment answer question python worked clojure using last vector linear operation prevented cumulative sum computed way i intended updating function use transient vector like defn cumulativesum loop x amp xs ss acc transient x let ssx ss x recur xs ssx conj acc ssx persistent acc results clojure version run twice long python consistently i kind hoped clojure would faster python operations wonder i still miss something i using way thanks,i recently started learn clojure decided practice euler problems get hang available data structures practice recursion looping i tried various approaches problem matter i finding solution never finished after i looked others i guessed i take forever either i typed equivalent algorithm python see problem lies lack understanding clojure thing java setting python finished seconds for primes python version finished sec clojure i posting clojure version created specifically match python code can help understand difference performance should i use uncheckedadd type hints primitives so clojure defn prime n let r int mathsqrt n loop cond n false r true zero rem n false recur inc defn primes filter prime iterate inc defn cumulativesum reduce fn v x conj v last v x first rest defn longestsequnder n longest prime seq sum n let ps vec takewhile n primes prime numbers n primeset set ps set testing inclusion cs cumulativesum ps cnt count ps maxlen count takewhile n cs cannot longer sequences subsum fn j sum primes ith jth cs j get cs dec seqwithlen fn try length prime sequences return first sum prime loop try lowest sum cnt elements length sequence nil could find let j dec fix length subsum j n overshoot nil primeset sum prime inc j looked first recur inc shift window loop maxlen try longest sequence zero let j seqwithlen j subvec ps j recur dec assert longestsequnder let longestsequnder assert count assert reduce time reduce longestsequnder elapsed time msecs and python math import sqrt itertools import takewhile def isprimen xrange intsqrtn n return false return true def nextprimen isprimen n return n def primes true nextprimei yield def cumulativesums cs css si css si csappend css return cs def longestsequndern ps listtakewhile lambda p p n primes pss setps cs cumulativesumps cnt lenps maxlen lenlisttakewhilelambda n cs def subsumi j return csj csi else def intervalwithlengthm xrange cntm j sij subsumij sij n return none none sij pss prime return j return none none xrangemaxlen f intervalwithlengthm return psft assert longestsequnder assert sumlongestsequnder import timeit timeittimersumlongestsequnder main import longestsequndertimeit thanks,2 using code phone send file using chunked encoding because pybottle support chunked enconding solution rewrite android send file body post request,on android phone i used setentity put fileentity post request httppost post new httpposturi fileentity reqentity new fileentityf applicationxgzip reqentitysetcontenttypebinaryoctetstream reqentitysetchunkedtrue postaddheaderxaethersnotebookcustom configurationgetcustomheader postsetentityreqentity when using bottle tried working f requestbody gzipper gzipgzipfile fileobj f content gzipperread the content empty string so i tried look requestforms requestfiles both key value requestfileskeys requestformskeys when searching i read entity request may transfer entity entity entityheader entityvalue so may something like filecontent egetentityheader,1 almost numpy functions operate whole arrays andor told operate particular axis row column as long define function terms numpy functions acting numpy arrays array slices function automatically operate whole arrays rows columns it may helpful ask implement particular function get concrete advice numpy provides npvectorize npfrompyfunc turn python functions operate numbers functions operate numpy arrays for example def myfuncab ab return else return b vecfunc npvectorizemyfunc resultvecfunc printresult the elements first array get replaced corresponding element second array second bigger but get excited npvectorize npfrompyfunc syntactic sugar they actually make code faster if underlying python function operating one value time npvectorize feed one item time whole operation going pretty slow compared using numpy function calls underlying c fortran implementation to count many elements column x smaller number could use expression array x ysum for example import numpy np arraynparangeview x npint npint printarray printarray x printarray x true true false printarray x sum,i using numpy store data matrices coming r background extremely simple way apply function rowcolumns matrix is something similar pythonnumpy combination it problem write little implementation seems versions i come significantly less efficientmore memory intensive existing implementation i would like avoid copying numpy matrix local variable etc possible the functions i trying implement mainly simple comparisons eg many elements certain column smaller number x many absolute value larger,3 right i think yet ready however still manual introspection looking gtkgir file system located usrsharegirgtkgir the gir file xml file supposed used exactly explore exposed interface regardless programming language using for example label class found looking class namelabel inside class tag doc tag extensive information widget supposed also many method tags one one interested example method namesettext inside method tag doc tag describes method also parameters tag turn contains parameter tag used describe parameter terms name description type parameters parameter namestr transferownershipnone doc xmlwhitespacepreservethe text want setdoc type nameutf ctypegchar parameter parameters so information already,one great things python ability introspection methods functions as example get function signature mathlog ipython run in mathlog type builtinfunctionormethod base class type builtinfunctionormethod string form builtin function log namespace interactive docstring logx base return logarithm x given base if base specified returns natural logarithm base e x and see x optionally base parameters function with new gtk automaticall generated pygobject bindings i examples i tried ever get args kwargs parameters every gtk method example labelsettext requires string in girepository import gtk in mylabel gtklabelhello in mylabelsettext type instancemethod base class type instancemethod string form bound method labelsettext label object xb gtklabel xcd namespace interactive file usrlibpythondistpackagesgitypespy definition lsettextargs kwargs docstring docstring now the question loss method introspection python bindings something change documentation effort gone pygobjects something stay due way pygobjects works,2 def stepsdself ns return scrandomrandomintegers sizens def walkdself nsnone ns none ns selfns return sccumsumselfstepsdns,code class randomwalk ns number stepsd np number particles dimension choose d d def initselfnsnpdimensionnone selfnsns selfnpnp selfdimensiondimension def stepsdselfns return scrandomrandomintegerssizeselfns the position particles nth stepsd given sum n first stepsd def walkdselfns return sccumsumrandomwalkstepsdselfselfns when ns np dimension rwrandomwalknsnp rw creates instance class randomwalkswhich ns nowif example want print walkd rwwalkd give size array telling right created instance ns so want apply statement order give size array solutions exists,1 an alternate way dynamic sys scriptengineimportmodulesys syspathappendsomepath,i complete noob comes ironpython i need call py script aspnet website following code var ipy ironpythonhostingpythoncreateruntime dynamic test ipyusefileservermappathpythontestpy testdowork the version ironpython i using the rd party python file i need call following import directives import sys array import subprocess import i receiving error no module named subprocess i copied subprocesspy file ironpython installation lib directory i assume i need link c code thanks edit i found solution scriptengine scriptengine pythoncreateengine var sp scriptenginegetsearchpaths spaddservermappathpythonlib scriptenginesetsearchpathssp var scope scriptengineruntimeexecutefileservermappathpythontestpy if anyone commentsimprovements please feel free elaborate seeing i new ground pythonironpython malarky,1 this script freeze brilliant example code tired the loop supposed try connect api three times continue ever i forgot put break this question stupid i blame removing fixed code try three times make contact true try connect api connection urlliburlopenrequest timeout xmlstring connectionread break except urlerror e tries tries sysstderrwrite owndstreamsupdater fatal error repeated timeouts exit,the function urlliburlopen freezes so question simple why urlopen freeze script ever even though timeout set how i access data url case httpapiowndtvlivechannelfnatictv without possibility python process freezing eternity this part freezes in owndpy try three times make contact true try connect api right it freezes connection urlliburlopenrequest timeout xmlstring connectionread except urlerror e tries tries sysstderrwrite owndstreamsupdater fatal error repeated timeouts exit this stack trace keyboardinterrupt traceback recent call last file line file honsappowndstreamsupdaterpy line updatestreaminfo streaminfo getstreaminfostream file honsappowndpy line getstreaminfo connection urlliburlopenrequest timeout file usrlocallibpythonurllibpy line urlopen return openeropenurl data timeout file usrlocallibpythonurllibpy line open response selfopenreq data file usrlocallibpythonurllibpy line open open req file usrlocallibpythonurllibpy line callchain result funcargs file usrlocallibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlocallibpythonurllibpy line doopen r hgetresponsebufferingtrue file usrlocallibpythonhttplibpy line getresponse responsebegin file usrlocallibpythonhttplibpy line begin version status reason selfreadstatus file usrlocallibpythonhttplibpy line readstatus line selffpreadline file usrlocallibpythonsocketpy line readline data selfsockrecvselfrbufsize keyboardinterrupt edit i let script run night i know exactly long took though five minutes script finally gave gave stacktrace traceback recent call last file honsappowndstreamsupdaterpy line newinfo file honsappowndstreamsupdaterpy line newinfo result updatestreaminfostream file honsappowndstreamsupdaterpy line updatestreaminfo streaminfo getstreaminfostream file rootdropboxprojectshonstreamshonsappowndpy line getstreaminfo connection urlliburlopenrequest timeout file usrlocallibpythonurllibpy line urlopen return openeropenurl data timeout file usrlocallibpythonurllibpy line open response selfopenreq data file usrlocallibpythonurllibpy line open open req file usrlocallibpythonurllibpy line callchain result funcargs file usrlocallibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlocallibpythonurllibpy line doopen r hgetresponsebufferingtrue file usrlocallibpythonhttplibpy line getresponse responsebegin file usrlocallibpythonhttplibpy line begin version status reason selfreadstatus file usrlocallibpythonhttplibpy line readstatus raise badstatuslineline httplibbadstatusline,2 the real way know would profile measure your code could anything dosomething might timesleep case forking processes would make whole program run approximately seconds ignoring forking overhead resulting slowdowns use httpdocspythonorglibraryprofilehtml check see bottle necks see optimise fully optimised program using better coding if already fast enough stop then depending whether cpu io bound hardware might want try multiprocessing threading you also try distributing multiple machines mapreduce kind thing problem broken,i project written python work big size data i would like speed execution time in simple words let say i sample fully optimized code def foox dosomething main range fooi is way speed for example using multiprocessing stuff and important worth thanks replies i think i try route multiprocessing someone suggest guide example helping,3 you could use pypy interpreter jit compiler built might actually improve performance loops like here link explains speed ups pypy interpreter offers regular cpython or could write code using cython allows native c extensions inside python huge chunks numpy written way get good speed ups or could forget using python write asm sure harder see program runs faster everyone elses you happy went extra mile,i project written python work big size data i would like speed execution time in simple words let say i sample fully optimized code def foox dosomething main range fooi is way speed for example using multiprocessing stuff and important worth thanks replies i think i try route multiprocessing someone suggest guide example helping,2 besides already said could check cython but profile also pypy might worth checking there work needed make work,i project written python work big size data i would like speed execution time in simple words let say i sample fully optimized code def foox dosomething main range fooi is way speed for example using multiprocessing stuff and important worth thanks replies i think i try route multiprocessing someone suggest guide example helping,1 to answer last question first problem performance worth that criterion really as if algorithm slow computationally expensive consider rewriting c extension use cython let write fast extensions pythonesque language also pypy getting faster faster may able run code without modification if code computationally expensive loops huge amount may possible break multiprocessing gets done parallel lastly kind basic data splatting task consider using fast data store all major relational databases optimised wazoo may find task sped simply getting database you may even able shape fit redis store aggregate big data sets brilliantly,i project written python work big size data i would like speed execution time in simple words let say i sample fully optimized code def foox dosomething main range fooi is way speed for example using multiprocessing stuff and important worth thanks replies i think i try route multiprocessing someone suggest guide example helping,3 selecting elements numpy array based one conditions straightforward using numpy beautifully dense syntax import numpy np generate matrix demo code a nprandomrandint reshape a array many elements column greater ndx a ndx arrayfalse true false false true true true true dtypebool npsumndx many elements last column a absolute value larger a nprandomrandint reshape a array ndx npabsa npsumndx many elements first two rows a greater equal ndx a npsumndxravel ravel flattens ndx originally d x numpy indexing syntax pretty close r given fluency r key differences r numpy context numpy indices zerobased r indexing begins numpy like python allows index right left using negative indiceseg get last column a a get penultimate column a a big deal r equivalent expresson a dima numpy uses colon notation denote unsliced eg r get first three rows a would use a in numpy would use a numpy necessary fact preferable use a,i using numpy store data matrices coming r background extremely simple way apply function rowcolumns matrix is something similar pythonnumpy combination it problem write little implementation seems versions i come significantly less efficientmore memory intensive existing implementation i would like avoid copying numpy matrix local variable etc possible the functions i trying implement mainly simple comparisons eg many elements certain column smaller number x many absolute value larger,3 there documented way switch file modes r w open file instead tempfile consider using mmap share data programs,in python i open temporary file write using tempfilemkstemp order sure file destroyed released even application crashes now i need pass file another application application going able open file long file opened write can i change access mode reopen file without changing file handle order prevent deleted soon update opening file read mode solve problem file must opened shared mode,1 may program helps backgroundpy import subprocess def backgroundexecutecommand launching command p subprocesspopencommandshelltruestdouttrue pwait print wait child exits here add code send mail usage backgroundexecutepython sleeppy sleeppy import time print i sleep script sleep sec timesleep print exit child,i fairly complex report generating work needs generated spaning multiple tables final report created excel sheetthe process takes anything minutes we provided django web app client only issue client requests report generating url takes time issue far ui go i would like task running behind mail client link report what right strategy libraries used,1 true r randomstuff meetsconditionr break condition true condition r randomstuff condition meetsconditionr,i often randomly generate stuff certain constraints in many cases quicker ignore constraints generation check met afterwards redo process otherwise lacking keyword i usually write r randomstuff meetsconditionr r randomstuff that bit ugly i line code twice what i really like construct like r randomstuff meetsconditionr similar ternary operator introduced b condition else c just condition evaluated lefthand side statement executed does anybody suggestion design pattern work python remedies constructs intrinsic unpythonic ugliness,3 i understand first line work stdin stdout stderr redirections need blocking the second one supposed block process expects data via stdin sends data stdout pipe hold wothout read but subprocess terminates correctly i cannot see reason blocking well are sure really terminates,i problem using subprocesspopen subprocesscall i use execute command lines generates lot output python scripts hangs weird waiting script hanging state i find job commanded cmd line done script hung subprocesscallcmd shell true or subprocesspopencmd stdout subprocesspipe stdin subprocesspipe shell true hangs here print show something subprocess note last print never executed actually cmd executed note also cmd related serial port i plug serial cable everything become fine last print statetement get executed but i use terminal everything fine even serial plugged occurs python script thanks lot,1 your idea bad new keyword rather like expression condition extending idea generator expressions as exist help but use iter function sentinel dummysentinel object r iterrandomstuff dummysentinel meetsconditionr break if sure randomstuff returning certain kind values numbers strings etc take value sentinel especially none never occur take order neverending generator r iterrandomstuff none meetsconditionr break then randomstuff gets called meets condition even better might r nextr r iterrandomstuff none meetsconditionr gives first matching one,i often randomly generate stuff certain constraints in many cases quicker ignore constraints generation check met afterwards redo process otherwise lacking keyword i usually write r randomstuff meetsconditionr r randomstuff that bit ugly i line code twice what i really like construct like r randomstuff meetsconditionr similar ternary operator introduced b condition else c just condition evaluated lefthand side statement executed does anybody suggestion design pattern work python remedies constructs intrinsic unpythonic ugliness,1 python special syntax passing sequence arguments todaydatedaysplit but parameters also ints use todaydatemapintdaysplit,this works datetime import date todaydate but i day todaydatedaysplit note daysplit i seen linkbut need integers date list,1 this work datemapint daysplit mapint daysplit datemapint daysplit datetimedate,this works datetime import date todaydate but i day todaydatedaysplit note daysplit i seen linkbut need integers date list,1 use datetimedatetimestrptime designed specifically parsing dates in datetimedatetimestrptime ymd date out datetimedate,this works datetime import date todaydate but i day todaydatedaysplit note daysplit i seen linkbut need integers date list,3 you loop list get daysplit convert entry int today dateintx x daysplit,this works datetime import date todaydate but i day todaydatedaysplit note daysplit i seen linkbut need integers date list,1 dictzipkeys values please call dict dict builtin name,i read link but i initialize dictionary well say two list keys b c values dict i want initialize dict keys amp values,3 i know would help using gcc os x compile c program embedded python i link python library for instance command line i compiled gcc pythontestc lpython pythontest l flag python python library folder,i using eclipse cygwin gcc compiler trying use pythonh c program encounter errors compiling any ideas in file included cpythonincludepythonh srcembeddedpythonc cpythonincludeintobjecth error parse error pyintasunsignedlonglongmask cpythonincludeintobjecth warning type defaults int declaration pyintasunsignedlonglongmask cpythonincludeintobjecth warning data definition type storage class in file included cpythonincludepythonh srcembeddedpythonc cpythonincludelongobjecth warning parameter names without types function declaration cpythonincludelongobjecth error parse error pylongaslonglong cpythonincludelongobjecth warning type defaults int declaration pylongaslonglong cpythonincludelongobjecth warning data definition type storage class cpythonincludelongobjecth error parse error pylongasunsignedlonglong cpythonincludelongobjecth warning type defaults int declaration pylongasunsignedlonglong cpythonincludelongobjecth warning data definition type storage class cpythonincludelongobjecth error parse error pylongasunsignedlonglongmask cpythonincludelongobjecth warning type defaults int declaration pylongasunsignedlonglongmask cpythonincludelongobjecth warning data definition type storage class cpythonincludelongobjecth error parse error pylongaslonglongandoverflow cpythonincludelongobjecth warning type defaults int declaration pylongaslonglongandoverflow cpythonincludelongobjecth warning data definition type storage class make srcembeddedpythono error,1 i found djangotemplateaddons library counter tag works template level independent nested loops,i trying make custom template tag increment variable that would used like fruit basket fruitisapple count apples endif endfor pthere apples apples basketp i came projectapptemplatetagscounterpy class counternodetemplatenode def initself varname selfvarname varname def renderself context selfvarname context contextselfvarname else contextselfvarname return registertag def counterparser token try tagname args tokencontentssplitnone except valueerror raise templatetemplatesyntaxerror counter node requires variable name return counternodeargs this works fine try use counter tag within loop the count variable increments inside loop gets reset variable called outside loop this render method templatedefaulttagsfornode class calls contextpop end i able grasp done dealt within custom template tag so question could i get counter tag increment even loops,1 i think may need save carpool object adding legs otherwise leg count might zero wont another database hit carpool object that would explain loop skipping am i right thinking leg count zero loop print try saveing carpool object adding legs just hunch,djangopython rookie have function finishing called no error stops goes back python command prompt it first loop stops gets next print command takes back prompt everything executed correct i sure something basic i missed function def createcarpoolfamily startdate enddate name carpool carpool carpoolname name carpoolsave currentdate startdate currentdate enddate print processing currentdatestrftime mdy going enddatestrftime mdy currentdateday startleg leg startlegdrivedate currentdate startlegstarttime starttimeam startlegendpoint endpointam startlegsave endleg leg endlegdrivedate currentdate endlegstarttime starttimepm endlegendpoint endpointpm endlegsave carpoollegsaddstartleg carpoollegsaddendleg currentdate datetimetimedeltadays print adding driving preferences carpool legs numlegs carpoollegsallcount legidx leg carpoollegsall legidx print processing leg strlegidx strnumlegs rider riderobjectsall choicenumberlist legridersaddrider driver carpooldriversall drivepreference drivingpreference drivepreferenceleg leg drivepreferencedriver familydrivers drivepreferencepreference choice drivepreferencesave return carpool,1 i quite understand want use executormap i tried function return anything f function actually worked fine run map actually print values version f function print values import concurrentfutures fred def fx return x x concurrentfuturesprocesspoolexecutor executor num executormapf fred printnum,i’m trying understand use concurrentfutures module python playing examples documentation when i try apply understanding examples fail i hope somebody help get track i want able set number processes running concurrently asynchronously my processes return anything to simulate i written trivial example import concurrentfutures fred def fx printx x def main concurrentfuturesprocesspoolexecutor executor num fred executorsubmitf num name main main this code runs core windows xp box returns hangs clearly i’m something wrong so correct way python run processes process pool i don’t want use executormap approach i don’t return process or…do i fake process return true false something thanks,1 the builtin function zip almost want zip the difference get tuples instead lists you convert lists using maplist zip,suppose i list tuples i want convert multiple lists for example list tuples is builtin function python convert this simple program but i curious existence builtin function python,3 someone asked question like turned bucket global public read set using bucket policy double check acls etc allow access also looks like listing access want can call get bucket get listing files you able don know help use stringlike policy httpwwwtechtrickycomamazonshowtorestrictuseraccesstospecificfolderorbucket httpsforumsawsamazoncomsearchjspaobjidfampqstringlikeampxampy,i writing app i set users user number files associated directory within s bucket users authenticating using amazon sts getting temporary security credentials allow access resources allowing access resources think home directories assuming user already exists system authenticated file bucket created without specified policy acl using naming scheme app bucket user identifier during request user accessing file grant temporary security credentials follows using boto getfederationtoken user identifier durationpolicyuserpolicy userpolicy userpolicy r statement effectallow action sputobject sgetobject sgetobjectversion sdeleteobject sdeleteobjectversion resourcearnawsss user identifier i thought i understood policies apparently i missing something using scheme i able getput resources user directory also directoriesresources belonging users for life i get access properly segregated i played bucket policies well bear fruit any direction would appreciated note i stuck using sts likely many users createuse iam users,2 from python docs zip conjunction operator used unzip list specific example zip zip or really want lists maplist zip,suppose i list tuples i want convert multiple lists for example list tuples is builtin function python convert this simple program but i curious existence builtin function python,3 use b zipa,suppose i list tuples i want convert multiple lists for example list tuples is builtin function python convert this simple program but i curious existence builtin function python,2 i know enough python give specific code looks like need write execpy handle array commands provide control logic then json file would need write value cmd key first cmd second cmd last cmd i following question i really like idea,i various shell build scripts project want create one centralized build system options allow shell script run for example user presses cmd b user given option shellscriptsh shellscriptsh shellscriptsh the user presses sublime text runs sh shellscriptsh i reading httpsublimetextinfodocsenreferencebuildsystemshtml unsure integrate option json code sublime text build system how accomplish build system sublime text thanks,1 i feel pain as developer coming desktop world web development i used setting appearance application time i select arrange user interface widgets you accept browser based software work way you must separately learn css hopefully learn like method specifying appearance application whether really alternative approach browser,i hope knocked general i recently occasion learn webpy final year university project in subject teams four weeks design web app ultimately found webpy quite versatile easy get site running fast lot options janrain etc end style result relied almost entirely us amongst teams used frameworks team different one whole sites came slick polished look without spend much photoshopcss design time effort i got impression frameworks friendly came box design elements buttons navigation options widgets base css etc others i python cjava background intend learn php point what frameworks exist provided base site design beyond bare bones and emphasise i browsed python page listing frameworks interested design aspect even see assumption correct,1 in python python also make dictionary comprehension keyvalue key value zipkeys values although little verbose i found clear clearly see relationship,i read link but i initialize dictionary well say two list keys b c values dict i want initialize dict keys amp values,3 items python usually things retrieved modified using getitem setitem functions lists dictionaries items sets contrast implement getitem setitem documentation uses one usual terms refer members set element one,let take random container python list dict say container items refer members documentation seems suggest sets members,1 i say contents container inside refer element refer specific one i would restraint use items anything different keyvalue pairs dictionary returned dictitems avoid possible confusions but take look list constructor read listiterable new list initialized iterable items i guess item ok refer iterable yields taking look httpdocspythonorglibrarystdtypeshtml find references element item like particular tuples lists compared lexicographically comparing corresponding elements this means compare equal every element must compare equal what happened one element list containing empty list three elements pointers single empty list the pop method supported list array types the optional argument defaults default last item removed returned cmp specifies custom comparison function two arguments list items overall count element appearances item,let take random container python list dict say container items refer members documentation seems suggest sets members,1 no windows python suport cygwin paths cygwin python if add existing cygwin install might want consider userspecific cygwin install directory allowed write there way obtain limited cygwin path support windows programs although i suspect option either install cygwin c cygwin path equivalent cpath this relies fact windows api albeit windows programs accepts backslashes slashes path separators considers absolute paths without drive letter referring system drive ie c obviously work cygwin paths point drives via cygwin mount table it also work programs use rather introduce options includes builtin windows commandline tools but usually work crossplatform tools python yet another option use msys instead cygwin fork old cygwin version whereby distinctive feature automatically translates posix paths windows paths invoking windows programs note however approach pitfalls always clear whether argument path hence sometimes fail translate path wrongly change argument path,i access machine minimal cygwin installation windows version python i need run python scripts however python requires windows paths i use cygpath w arguments i provide however unixcygwin paths included numerous scripts subsequently invoked is way tell windows python accept unixcygwin paths,1 if attacker access password database way still hide password hashing include salt prevent attacker relying generic hash tables import hashlib salt uphieiv hash aaaccfbdbdccbebcbddcff hashlibmdhexdigestsalt rawinputhexdigest hash print correct password note still help poorly chosen passwords for make sure attacker access password database if want potential attackers able run program access piece data program manipulates move piece data remote secured server program performs authentication,i looking way use password statement obviously therawinput thecorrectpassword extremely nonsecure any ideas i seen questions topic suggest base also nonsecure i cracked compiled script password without using password,3 basically boolean array want find start stop contiguous regions it far better avoid looping item numpy array there different ways i usually something similar i probably originally got import numpy np def contiguousregionscondition finds contiguous true regions boolean array condition returns d array first column start index region second column end index find indicies changes condition idx npdiffconditionnonzero prepend append start end indicies idx block true start end condition idx npr idx condition idx npridx lencondition return idxreshape as quick example import numpy np def main generate data nplinspace nppi x npsint condition x regions contiguousregionscondition lengths regions regions reg length zipregions lengths print condition true seconds formatlength print from time formatreg def contiguousregionscondition idx npdiffconditionnonzero condition idx npr idx condition idx npridx lencondition return idxreshape main this yields condition true seconds from time condition true seconds from time condition true seconds from time,statussignal measured heatpump numpymaarray together timestamps what want lengths periods length periods not daily running time something would easy what exemplary fact minutevalues months time value and want output runningtimewas time value minutes offtimewas time value minutes exact timestamps matter much i already asked people know know python idea neither tried search internet know search so maybe someone could least give hint words could type google ps wow stackoverflow fantastic i already amazed usability passive user asking interface even better,1 you use methoddecorator dispatch method class djangoviewsgeneric import view djangoutilsdecorators import methoddecorator djangocontribauthdecorators import userpassestest class myviewview methoddecoratoruserpassestestlambda u uissuperuser def dispatchself args kwargs return supermyview selfdispatchargs kwargs,how i implement userpassestestlambda u uissuperuser decorator class based views i used function based views i work around feels unnaturally shouldn covered dispatch method,3 you also try package numpyscipymatplotlib installation using virtualenv a step step recipe using homebrew described it worked fine hope helps,what could i done instead order get items working together should i move everything windows i prefer reliable way okay happened i wanted install numpyscipy onto mac runs unfortunately numpy ver supports python i go install python but python work appicon bounces automatically quits this strange retrospect i heard python numpy ships mac i tried using sample code numpy website failed now real bind i eventually found httpstronginferencecomscipysuperpack which somehow installs numpy scipy matplotlib ipython pandas well pymc alpha it seemed like worked numpy work example code provided python but i working practice problems i found matplotlib working anymore the python launcher i think python launcher appicon says python name bounces app tray eventually freezes i worried could i matplotlib installed i followed instructions clean uninstall matplotlib followed installation scipysuperpack still fails way now i done clean install matplotlib hopes works and i import pylab throws ton error messages any advice would greatly appreciated,2 compile see c code cython produces nicely annotated cyexamplepyx cdef pyssizet n leninput n cur inputi pyxt pyxvn pyxvi pyxvi pyxt pyxvi cyexamplepyx n cur inputi return cur n pyxt pyxvi pyxt pyxt pyxt pyxbshapeinput unlikelypyxt pyxt else unlikelypyxt pyxbshapeinput pyxt unlikelypyxt pyxraisebufferindexerrorpyxt pyxfilename pyxf pyxlineno pyxclineno line goto pyxlerror pyxvcur pyxvcur pyxbufptrstrideddpyxtnumpydoublet pyxbstructinputbuf pyxt pyxbstrideinput and loop successfully turned c note days cython handle range naturally older n style necessary the point introducing nonpython forfrom syntax signify loops cified,i learning cython came across snippit code import numpy np cimport numpy np def meannpndarraynpdoublet input cdef npdoublet cur pyssizet numpy index type cdef pyssizet cdef pyssizet n leninput n cur inputi return cur n anparray dtypenpdouble obviously returns mean my question is loop python loop cython c,2 forfrom seems pyrex cython loop httpdocscythonorgsrcuserguidelanguagebasicshtmlintegerforloops,i learning cython came across snippit code import numpy np cimport numpy np def meannpndarraynpdoublet input cdef npdoublet cur pyssizet numpy index type cdef pyssizet cdef pyssizet n leninput n cur inputi return cur n anparray dtypenpdouble obviously returns mean my question is loop python loop cython c,3 you could check eventkeysym return class appobject def initself master kwargs selfmastermaster masterbind keyrelease selfrelease def releaseselfevent eventkeysym return print return release roottktk appapproot rootmainloop note autokey repeat keyrelease events even physically release key to turn autorepeat xwindows import xlibdisplay display import xlibx x import tkinter tk import atexit atexitregister def autorepeat ddisplaydisplay dchangekeyboardcontrolautorepeatmodexautorepeatmodeon xdgetkeyboardcontrol class appobject def initself master kwargs selfmastermaster masterbind keyrelease selfrelease def releaseselfevent eventkeysym return print return release ddisplaydisplay dchangekeyboardcontrolautorepeatmodexautorepeatmodeoff xdgetkeyboardcontrol roottktk appapproot rootmainloop,is way make return event call key release instead press if use keyrelease eventchar blank special key return,2 here variation cã©dric julien answer fail rare cases anytrue devdevices name devname here admittedly unusual possible case illustrates anytrue … gives correct result anyd … class specialdictdict def nonzeroself return false all specialdict objects false dev devices specialdictnamedevname xrange anyd devdevices name devname incorrect false anytrue devdevices name devname correct true in fact specialdict objects evaluate false make sense test truth value using true works though ps timing tests indicate anytrue … … … … approach faster nice any… … … solution doublep python timeit dev devices name badname xrange anyd name devname dev devices loops best usec per loop python timeit dev devices name badname xrange anytrue dev devices name devname loops best usec per loop the reason second generator returns one value true this seen disassembling python code two generators in def fmylist return anyx x mylist in ffunccodecoconsts out code object genexpr xfb file ipythoninputce line in disdis loadfast foriter storefast x loadfast x loadconst compareop yieldvalue poptop jumpabsolute loadconst none returnvalue this code contains yieldvalue poptop take additional time compared version answer in def gmylist return anytrue x mylist x in gfunccodecoconsts out code object genexpr xf file ipythoninputcd line in disdisgfunccodecoconsts loadfast foriter storefast x loadfast x loadconst compareop popjumpiffalse loadglobal true yieldvalue poptop jumpabsolute loadconst none returnvalue,i got lines code iterating dict within list i looking shorten it works perfectly seems like much code i trying get feel keep code efficient python general really dev devices name devname devfound true break the structure dev bit confusing data i care dev dict devices list n dict value name key within inner numbered dict varies depending search value elsewhere needs checked user input devname any input much appreciated,1 the basic operations described wikipedia transformation matrix page i going try ascii matrix art output p rp p output point r x transformation matrix containing sine cosine rotation angle p input point if want rotate something origin shift origin prior rotation p t rpt t translation coordinate the basic matrix operations interpolation using numpybased image processing library want reverse transform integervalued output coordinate find floating point coordinate point would rotated interpolate value input point surrounding pixels,i set greyscale images d numpy arrays i need rotate images one point inside different float angles the rotation need place i allow course i explained well far interpolation i like remain numpy i need perform numerical operations result i also impossible allow step inout example i tried using pil namely imagerotatetheta understand apply arrays get array back thank input,1 i quite sure i understand correctly goal i think i understand seem necessary crazy stuff descriptors let alone typesmethodtype a simple property fine like lambda use ordinary function decorated property class user name modelscharfieldmaxlength property def companyself return userprofileobjectsgetorcreateuserselfgetcompany edit if touch user class create derived class adding desired property class myuseruser property def companyself return userprofileobjectsgetorcreateuserselfgetcompany,i want nice convenient attribute following djangocontribauthmodels import user user userobjectsgetid usercompany company big company llc i currently solving using lambda in searching answer looks like perhaps right way solve would use typesmethodtype i seem get head around yes i read raymond excellent guide i clearly missing something here current solution interested defined elsewhere class user name modelscharfieldmaxlength class companymodelsmodel users modelsmanytomanyfielduser relatednamecompanies blanktrue nulltrue here meat class userprofilemodelsmodel this defines users user modelsonetoonefielduser def getcompanyself try companies selfusercompaniesall except attributeerror indexerror return none usercompany propertylambda u userprofileobjectsgetorcreateuserugetcompany right works but better way i crazy lambdas,1 f open filetxt r print fread fclose from httpdocspythonorgtutorialinputoutputhtml to read file’s contents call freadsize reads quantity data returns string size optional numeric argument when size omitted negative entire contents file read returned it’s problem file twice large machine’s memory otherwise size bytes read returned if end file reached fread return empty string,i searched i find questions way around writing stdin file is quick easy way dump contents file stdout,3 sure assuming string file name called fname following trick openfname r fin print finread,i searched i find questions way around writing stdin file is quick easy way dump contents file stdout,3 mul know x represent scalars matrix multiplication depends order arguments example k k necessarily equal if know program x always scalars type value multiplication commutative associative may way factor constants term compare constants compare sorted list terms,in project i use evaluatefalse time creating add mul objects in case i facing problem i apply equality checks objects the issue ordering arguments please consider example kmulxyevaluatefalse kmulxyevaluatefalse print kk the result false kargs xy kargs xy so comparison checks tuple equality returns false is way i get wanted result also i put operation tuples like reversing order checking fails cases k k formed different mul objects like kargs xy kargs yx edit cannot use sorting case addxyzevaluatefalse addxzyevaluatefalse two different expression also use evalautetrue case addxyx addxy dont want,1 if large file want consume ton memory might happen ben solution extra code import shutil import sys opentesttxt r f shutilcopyfileobjf sysstdout also works,i searched i find questions way around writing stdin file is quick easy way dump contents file stdout,3 rather attempting expand variable inside single quoted string typical solution concatenate single double quoted strings in words today date poor,first take look question bash googlecl new line string parameter i want add variable date summary google youtube post videoscatfallsdownstairsavi comedy tags currency internet summary today date poor whiskers takes tumblenshe fine though worry variable wont expand inside single quote bash is possible note googlecl commandline program written python i ubuntu python,3 i pleased say listing imports actually quite simple i need minimal implementation importer protocol defined pep findmodule returns none fallback next one this simple script actually show imports done program passed import sys class importinspectorobject def findmoduleself module path printimporting module module name main progname sysargv shift one position sysargv sysargv sysmetapathappendimportinspector code compileopenprogname rb read progname exec execcode given kind trick implemented top for example keep track imports set store program quits i think might even get hiearchy imports produce graph similar gprofdot based analysis imports,in general i would like understand exactly code code projects actually using big framework first i want know imports possibly static analysis possible imports actually used for first problem i could use regexp course i would like find cleaner way i see astinspectparser and second problem i able find automatically imports actually unused i edit second issue maybe best way simple import hook records everything imported call default importing mechanisms so i tried something like class myloaderobject loader object def initself selfloaded set def findmoduleself modulename packagenone printrequesting modulename selfloadedaddmodulename return self def loadmoduleself fullname fp pathname stuff impfindmodulefullname imploadmodulefullname fp pathname stuff but trying import random i get future import division importerror no module named future which i think means i missing something i found simple example using imp import introspection hints,1 you list deployed versions admin console admin logs short screenscraping page way access data programmatically you submit enhancement request issue tracker,i like get list deployed versions appengine either remote api via appcfgpy i seem find way certainly documented way does anyone know way even undocumented,1 a callback takes code calling gui toolkit passes if want pass convince said caller pass something extra luck but luckily loophole you pass arbitrary callables construct partial functions functions wrapping another function remembering additional arguments pass along whenever called import functools def callbackx return x g functoolspartialcallback g there issues strange argument orders eg easily call partial positional arguments first argument supplied via keyword argument use case add arguments end argument list work fine you need use keyword arguments,i creating couple swing jbuttons buttons loop jython on press button call function one different parameter i trouble passing parameters outside self event this works x range name jbuttonstrx nameactionperformed selffoo def fooself event print i work somehow event magically passed method this x range name jbuttonstrx nameactionperformed selffoox def fooself event number print i work print strnumber the issue i see i i add argument i longer pass event i end error telling foo takes exactly arguments given i get i extract event button,2 sets ordered collections python language matter sets usually implemented using hash keys hash codes so order probably related hash functions used instead natural order elements if need order please consider using list,with code print setab range b range i get answer set why sorted,3 sets nature unordered containers from documentation a set object unordered collection distinct hashable objects they implemented using hash table facilitating o membership tests if need ordered set try ordereddictfromkeys collections import ordereddict ordereddictfromkeysab range b range,with code print setab range b range i get answer set why sorted,1 variables expanded within single quotes either like william suggests rewrite line double quotes expand variable want today date poor whiskers takes tumblenshe fine though worry bonus doing way escape single quotes now i read link say n expand a workaround would something like summary echo e today it bit crude use subshell save backslashing quotes,first take look question bash googlecl new line string parameter i want add variable date summary google youtube post videoscatfallsdownstairsavi comedy tags currency internet summary today date poor whiskers takes tumblenshe fine though worry variable wont expand inside single quote bash is possible note googlecl commandline program written python i ubuntu python,1 it pretty much returning what see simply list url strings encoded unicode strings u front if simply want print urls nicely python module pretty printing used follows pprint import pprint pprintmylistofurls however print line line to need use url mylistofurls print url edit i tried pretty print module list unicode strings i think actually anything different u front strings i leaving wonders representing long data structures,my script import beautifulsoup bs beautifulsoup import beautifulsoup urllist sysargv urls tag href tag beautifulsoupopenurllistfindall returns u httpwwwyoutubecomwatchvggzipheg u httpwwwyoutubecomwatchvppvjgmmhfo u httpwwwyoutubecomwatchvytaudfye u httpwwwyoutubecomwatchvvhvqffge u httpwwwyoutubecomwatchvezgwqqu u httpwwwyoutubecomwatchvkhlsbvn u httpwwwyoutubecomwatchvxtndqbyva u httpwwwyoutubecomwatchvxttmqgwrrc u httpwwwyoutubecomwatchvjzyqngwsuw u httpwwwyoutubecomwatchvrzwvgunru u httpwwwyoutubecomwatchvvzqoywwm u httpwwwyoutubecomwatchvyarvqxyw u httpwwwyoutubecomwatchvlrreyhgci i would like return httpwwwyoutubecomwatchvggzipheg httpwwwyoutubecomwatchvppvjgmmhfo httpwwwyoutubecomwatchvytaudfye httpwwwyoutubecomwatchvvhvqffge httpwwwyoutubecomwatchvezgwqqu httpwwwyoutubecomwatchvkhlsbvn httpwwwyoutubecomwatchvxtndqbyva httpwwwyoutubecomwatchvxttmqgwrrc httpwwwyoutubecomwatchvjzyqngwsuw httpwwwyoutubecomwatchvrzwvgunru httpwwwyoutubecomwatchvvzqoywwm httpwwwyoutubecomwatchvyarvqxyw httpwwwyoutubecomwatchvlrreyhgci i really hard time wrapping head around beautifulsoup anything would help thank time,1 but completely basic python you getting list want output one url per line url urls print url,my script import beautifulsoup bs beautifulsoup import beautifulsoup urllist sysargv urls tag href tag beautifulsoupopenurllistfindall returns u httpwwwyoutubecomwatchvggzipheg u httpwwwyoutubecomwatchvppvjgmmhfo u httpwwwyoutubecomwatchvytaudfye u httpwwwyoutubecomwatchvvhvqffge u httpwwwyoutubecomwatchvezgwqqu u httpwwwyoutubecomwatchvkhlsbvn u httpwwwyoutubecomwatchvxtndqbyva u httpwwwyoutubecomwatchvxttmqgwrrc u httpwwwyoutubecomwatchvjzyqngwsuw u httpwwwyoutubecomwatchvrzwvgunru u httpwwwyoutubecomwatchvvzqoywwm u httpwwwyoutubecomwatchvyarvqxyw u httpwwwyoutubecomwatchvlrreyhgci i would like return httpwwwyoutubecomwatchvggzipheg httpwwwyoutubecomwatchvppvjgmmhfo httpwwwyoutubecomwatchvytaudfye httpwwwyoutubecomwatchvvhvqffge httpwwwyoutubecomwatchvezgwqqu httpwwwyoutubecomwatchvkhlsbvn httpwwwyoutubecomwatchvxtndqbyva httpwwwyoutubecomwatchvxttmqgwrrc httpwwwyoutubecomwatchvjzyqngwsuw httpwwwyoutubecomwatchvrzwvgunru httpwwwyoutubecomwatchvvzqoywwm httpwwwyoutubecomwatchvyarvqxyw httpwwwyoutubecomwatchvlrreyhgci i really hard time wrapping head around beautifulsoup anything would help thank time,2 when tried inserting br tag literally show output br if django automatically escaping error message see httpsdocsdjangoprojectcomendevtopicstemplatesautomatichtmlescaping details,i overriding clean method variables want specify custom error message error myerrormsg this error message myerrormsg nthis error message i would like next line selferrorsmytag myerrormsg however seems ignore line breaks i tried html br n nothing works everything gets put one line i loose capitalization,1 constructor texttestrunner class failfast parameter shown constructor documentation update i raised bug fixed verify httpdocspythonorglibraryunittesthtmlunittesttexttestrunner,all i found documentation unittest module description texttestrunner constructor following sample code using run method unittesttexttestrunnerverbosityrunsuite i would like know i use texttestrunner failfast mode,3 selferrorsmytag selferrorsgetmytag selferrorclass selferrorsmytagappendthis error message selferrorsmytagappendthis error message i would like next line like two errors escaping saying try selferrorsmytagappendmarksafetextbrtext selferrorsmytag selferrorclassmarksafetextbrtext,i overriding clean method variables want specify custom error message error myerrormsg this error message myerrormsg nthis error message i would like next line selferrorsmytag myerrormsg however seems ignore line breaks i tried html br n nothing works everything gets put one line i loose capitalization,1 you use valueslist mywords mygroupobjectsgetname blaallkeywordvalueslist name flattrue,how i convert queryset returned array string mywords mygroupobjectsgetname blaallkeyword mywords meltemi bla class mygroupmodelsmodel name modelscharfieldmaxlength uniquetrue allkeyword modelsmanytomanyfield keywordtag def unicodeself return selfname class keywordtagmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname,3 you provide string beautifulsoup parse bookmarkshtml opensysargv bookmarkfile soup beautifulsoupbookmarkfileread extract youtube video urls videourlregex recompile httpwwwyoutubecomwatch urls link href link soup hrefvideourlregex separate fast url parsing much longer downloading stats extract video ids urls ids could use set idsadd avoid duplicates videourl urls url urlparseurlparsevideourl videoid urlparseparseqsurlqueryget v videoid continue videoid url idsappendvideoid you need authenticate readonly requests get statistics videos ytservice youtubeservice ytservicessl true note works readonly requests ytservicedebug true show requests save statistics csv file provided commandline don stop video causes error writer csvwriteropensysargv wb save cvs file videoid ids try entry ytservicegetyoutubevideoentryvideoidvideoid except exception e print sysstderr failed retrieve entry videoids videoid e else title entrymediatitletext print title title viewcount entrystatisticsviewcount print view count viewcount writerwriterowvideoid title viewcount write here full script press playback watch written output python downloadvideostatspy neudorferhtml outcsv send u get httpsgdatayoutubecomfeedsapivideosggzipheg httprnacc eptencoding identityrnhost gdatayoutubecomrncontenttype applicationato mxmlrnuseragent none gdatapythonrnrn reply http okrn header xgdatausercountry ru header contenttype applicationatomxml charsetutf header expires thu nov gmt header date thu nov gmt header cachecontrol private maxage notransform header vary header gdataversion header lastmodified wed nov gmt header transferencoding chunked header xcontenttypeoptions nosniff header xframeoptions sameorigin header xxssprotection modeblock header server gse title paramore let the flames begin walmart soundcheck view count outcsv ggziphegparamore let the flames begin walmart soundcheck ppvjgmmhfoparamore walmart soundcheck ytaudfyeparamorewalmart soundcheck crushcrushcrushhq vhvqffgeparamorewalmart soundcheck that what you gethq ezgwqquparamorewalmart soundcheck interviewhq khlsbvnparamorewalmart soundcheck emergencyhq xtndqbyvaparamorewalmart soundcheck for pessimisthq xttmqgwrrcparamorewalmart soundcheck pressurehq jzyqngwsuwparamore walmart soundcheck interview rzwvgunruparamore interview walmart soundcheck vzqoywwmparamore that what you get walmart soundcheck yarvqxywparamore pressure walmart soundcheck lrreyhgciparamore walmart promo,bookmarkshtml looks like dta hrefhttpwwwyoutubecomwatchvggzipheg adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvggziphega dta hrefhttpwwwyoutubecomwatchvppvjgmmhfo adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvppvjgmmhfoa dta hrefhttpwwwyoutubecomwatchvytaudfye adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvytaudfyea dta hrefhttpwwwyoutubecomwatchvvhvqffge adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvvhvqffgea dta hrefhttpwwwyoutubecomwatchvezgwqqu adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvezgwqqua dta hrefhttpwwwyoutubecomwatchvkhlsbvn adddate lastmodified iconurihttpsytimgcomytfaviconvflzlzsbuico icondataimagepngbaseivborwkggoaaaansuheugaaabaaaaaqcayaaaafhaaabeeleqvqjawspudqbcfwgodzpqteqqjjlsujlgbnsdrdrqarsumyprjogkijiwitoyhrsepjrhptxkdrhrnmnbzxfsdpsprwrazbjhxdruakegvbfnepfzbqdjfroucsfhqdyjwcudzqpjtoylzknhzmidzgdeqgcmlfwpxnwadfvambuistxrwxbjalhgmizoldkicvbreezwtkgkbkqagqdogzljqayyxpmpgixhpwaesdunzzlwmbnnwekbqfgjnpabdggbvwbnoamnzewpfxynwuuqbkqtyyfrrkvqdptjzjpsbekaaaaasuvorkcyiihttpwwwyoutubecomwatchvkhlsbvna dta hrefhttpwwwyoutubecomwatchvxtndqbyva adddate lastmodifiedparamore walmart soundcheck for pessimisthqa dta hrefhttpwwwyoutubecomwatchvxttmqgwrrc adddate lastmodifiedparamore walmart soundcheck pressurehqa dta hrefhttpwwwyoutubecomwatchvjzyqngwsuw adddate lastmodifiedparamore walmart soundcheck interviewa dta hrefhttpwwwyoutubecomwatchvrzwvgunru adddate lastmodifiedparamore interview walmart soundcheck a dta hrefhttpwwwyoutubecomwatchvvzqoywwm adddate lastmodifiedparamore thatamps what you get walmart soundcheck a dta hrefhttpwwwyoutubecomwatchvyarvqxyw adddate lastmodifiedparamore pressure walmart soundcheck a dta hrefhttpwwwyoutubecomwatchvlrreyhgci adddate lastmodifiedparamore walmart promoa it standard bookmarks export file firefox i feed bookmarkspy looks like usrbinenv python import sys import beautifulsoup bs beautifulsoup import beautifulsoup urllist sysargv urls tag href tag beautifulsoupopenurllistfindall print urls this returns much clean list urls u httpwwwyoutubecomwatchvggzipheg u httpwwwyoutubecomwatchvppvjgmmhfo u httpwwwyoutubecomwatchvytaudfye u httpwwwyoutubecomwatchvvhvqffge u httpwwwyoutubecomwatchvezgwqqu u httpwwwyoutubecomwatchvkhlsbvn u httpwwwyoutubecomwatchvxtndqbyva u httpwwwyoutubecomwatchvxttmqgwrrc u httpwwwyoutubecomwatchvjzyqngwsuw u httpwwwyoutubecomwatchvrzwvgunru u httpwwwyoutubecomwatchvvzqoywwm u httpwwwyoutubecomwatchvyarvqxyw u httpwwwyoutubecomwatchvlrreyhgci next step get youtube urls videoinfopy usrbinpython import urlparse import sys import gdatayoutube import gdatayoutubeservice import import urlparse import urllib youtubeurl sysargv urldata urlparseurlparseyoutubeurl query urlparseparseqsurldataquery youtubeid queryv print youtubeid ytservice gdatayoutubeserviceyoutubeservice ytservicedeveloperkey aisiyomigehstxhnkivdftqjckqoysbbylkerpqxwjilwnujacdxpocglbbcapdyemlisbkvcoagykvkvg entry ytservicegetyoutubevideoentryvideoidyoutubeid print video title entrymediatitletext print video view count entrystatisticsviewcount url httpwwwyoutubecomwatchvaxrgwcrsw output looks like axrgwcrsw video title onerepublic good life live walmart soundcheck video view count how i feed list urls bookmarkspy videoinfopy extra points output csv format extra extra points checking duplicates bookmarkshtml passing data videoinfopy thanks help guys because stackoverflow i gotten far david so combined i usrbinenv python import urlparse import gdatayoutube import gdatayoutubeservice import import urlparse import urllib import sys import beautifulsoup bs beautifulsoup import beautifulsoup ytservice gdatayoutubeserviceyoutubeservice ytservicedeveloperkey aisiyomigehstxhnkivdftqjckqoysbbylkerpqxwjilwnujacdxpocglbbcapdyemlisbkvcoagykvkvg urllist sysargv urls tag href tag beautifulsoupopenurllistfindall print urls youtubeurl urls urldata urlparseurlparseyoutubeurl query urlparseparseqsurldataquery youtubeid queryv listsetmylist entry ytservicegetyoutubevideoentryvideoidyoutubeid myyoutubes myyoutubesappend joinyoutubeid entrymediatitletextentrystatisticsviewcount print njoinmyyoutubes how i pass list urls youtubeurl variable need cleaned passed one time i believe i got usrbinenv python import urlparse import gdatayoutube import gdatayoutubeservice import import urlparse import urllib import sys import beautifulsoup bs beautifulsoup import beautifulsoup ytservice gdatayoutubeserviceyoutubeservice ytservicedeveloperkey aisiyomigehstxhnkivdftqjckqoysbbylkerpqxwjilwnujacdxpocglbbcapdyemlisbkvcoagykvkvg urllist sysargv urls tag href tag beautifulsoupopenurllistfindall url urls youtubeurl url urldata urlparseurlparseyoutubeurl query urlparseparseqsurldataquery youtubeid queryv listsetmylist entry ytservicegetyoutubevideoentryvideoidyoutubeid myyoutubes myyoutubesappend joinyoutubeid entrymediatitletextentrystatisticsviewcount print njoinmyyoutubes i pass bookmarkshtml combinedpy returns first line how i loop line youtubeurl,1 i think need graphvv weight no need recreate whole dictionary add new item,please take look var name dictvar var i need name how i use dict dictelement way append element dictgraph also dictionary graphv dictgraphv vweight please help modify append method,2 var name var name,please take look var name dictvar var i need name how i use dict dictelement way append element dictgraph also dictionary graphv dictgraphv vweight please help modify append method,1 you question moot when got whole interpreter boxed number types heap allocations said types etc code machine cache efficency least worries since python builtin sequence types use dynamic overallocating c arrays hood rules apply two major caveats there lot hidden memory access every python operations eg type checking variable member lookup creating bound method objects calling methods number coercion may reduce benefit in many cases ie unless noted otherwise containers store references boxed objects iterate list int objects cpu cache help fetching pointers faster handling objects behind i surprised could measure difference if want optimize many things thousand times effective far obvious use builtins numpy write bit c use cython simply optimize python code,pretty inexperienced python i realize awfully basic well python cache blocks compared c for example c gridwidth gridheight igridheight j jgridwidth j massivenum arrigridwidth j way faster massivenum arri jgridwidth data cached efficiently first if i going speed python i something simple rangegridheight j rangegridwidth massivenum arrigridwidth j special thing i,1 you could simple way var name dict dvar graphv or var name graphv var or could use dictitems trick var name graphv dictvar dictditems trick or could silly var graphv dictd i think works,please take look var name dictvar var i need name how i use dict dictelement way append element dictgraph also dictionary graphv dictgraphv vweight please help modify append method,1 so far i seen yii framework php generate initial nice styled web application backbone ready work adding functionality dbs user roles etc course freedom define look feel defining html views css js etc i start learning using php framework next project i never yet used framework i several years using phpmysql for weeks i researched php frameworks cakephp codeigniter zend yii kohana etc i leaning yii even though codeigniter seems followers i stubborn checking yii high praise getting specially quality built performance i know good php frameworks default visual style area,i hope knocked general i recently occasion learn webpy final year university project in subject teams four weeks design web app ultimately found webpy quite versatile easy get site running fast lot options janrain etc end style result relied almost entirely us amongst teams used frameworks team different one whole sites came slick polished look without spend much photoshopcss design time effort i got impression frameworks friendly came box design elements buttons navigation options widgets base css etc others i python cjava background intend learn php point what frameworks exist provided base site design beyond bare bones and emphasise i browsed python page listing frameworks interested design aspect even see assumption correct,1 there course templating systems like jinja probably overkill asking you also format page using rst use generate latex probably overkill heck autogenerating page probably overkill number fields got define since overkill stop us i done something similar python string formatting take latex document tokenize file placing placeholdernames tokens document for example want class name go use coursenames textbflarge homeworktitles vspacecm textbflarge coursenames then python load template format template file templatetex r read page template coursename computer science homeworktitle npcomplete file resulttex w writepage if want find tokens automatically following pretty well import sys import import subprocess template file templatetex r read pattern recompile bcdeeffggnosxx tokens patternfindalltemplate tokenvalues dict token tokens sysstdoutwrite enter value token tokenvaluestoken sysstdinreadlinestrip page template tokenvalues file resulttex w writepage subprocesscall pdflatex resulttex the code iterate across tokens print prompt console asking input token in example get two prompts example answers enter value homeworktitle npcomplete enter value coursename computer science the final line calls pdflatex resulting file generates pdf if want go could also ask user output file name take command line option,i college guy college present kind homework standard coverpage college logo course name professor name name bla bla bla so i tex document generate standard coverpages pdfs it goes something like begindocument college logo vspacecm begincenter textbfhuge school program name vspacecm textbflarge homework title vspacecm textbflarge course name endcenter vspacecm beginflushright large my name endflushright so i wondering way make python script asks title homework course name rest strings use generate coverpage after compile tex generate pdf information given any opinions advice snippet library accepted,3 it widget needs attrs form field mylist formsmodelmultiplechoicefield label list requiredfalse queryset widgetselectmultipleattrs class foobar,how exactly i add css formsmodelmultiplechoicefield i tried pass attrs class foo but failing saying init got unexpected keyword argument attrs mylist formsmodelmultiplechoicefieldlabel list requiredfalse queryset,3 you start defining template tex file string content r documentclassarticle begindocument textbfhuge schools vspacecm textbflarge titles enddocument next use argparse accept values course title name school parser argparseargumentparser parseraddargument c course parseraddargument title parseraddargument n name parseraddargument school default my u a bit string formatting takes stick args content args parserparseargs contentargsdict after writing content file covertex open covertex w f fwritecontentargsdict could use subprocess call pdflatex covertex proc subprocesspopen pdflatex covertex proccommunicate you could add lpr command add printing workflow remove unneeded files osunlink covertex osunlink coverlog the script could called like makecoverpy c hardest class ever theoretical theory n me putting together import argparse import os import subprocess content r documentclassarticle begindocument p amp b textbfhuge schools vspacecm textbflarge titles enddocument parser argparseargumentparser parseraddargument c course parseraddargument title parseraddargument n name parseraddargument school default my u args parserparseargs open covertex w f fwritecontentargsdict cmd pdflatex interaction nonstopmode covertex proc subprocesspopencmd proccommunicate retcode procreturncode retcode osunlink coverpdf raise valueerror error executing command formatretcode joincmd osunlink covertex osunlink coverlog,i college guy college present kind homework standard coverpage college logo course name professor name name bla bla bla so i tex document generate standard coverpages pdfs it goes something like begindocument college logo vspacecm begincenter textbfhuge school program name vspacecm textbflarge homework title vspacecm textbflarge course name endcenter vspacecm beginflushright large my name endflushright so i wondering way make python script asks title homework course name rest strings use generate coverpage after compile tex generate pdf information given any opinions advice snippet library accepted,3 your problem stems fact endofline anchor the way nongreedy matching works engine first searches first unconstrained pattern line case it looks first character constrained anchor end line so nongreedy different greedy situation since cannot remove re looking final tag line need take different tacksee mark answer work,i confused python greedynotgreedy characters given multiline html return final tag line i would think would correct refindall html remultiline i irked i expected list single tags like html ul td my o reilly pocket reference says wil match times times possible so i getting greedier matches ie one tag matches,1 you try using sphinxapidoc sphinxapidoc help usage sphinxapidoc options outputpath modulepath excludepaths look recursively modulepath python modules packages create one rest file automodule directives per package outputpath you mix sphinxapidoc sphinxquickstart order create whole doc project like sphinxapidoc f docs project this call generate full project sphinxquickstart look recursively project python modules hope helps,i trying autogenerate basic documentation codebase using sphinx however i difficulty instructing sphinx recursively scan files i python codebase folder structure like workspace src mypackage initpy subpackagea initpy submodulea submodulea subpackageb initpy submoduleb submoduleb i ran sphinxquickstart workspace structure looks like workspace src mypackage initpy subpackagea initpy submodulea submodulea subpackageb initpy submoduleb submoduleb indexrst build static templates i read quickstart tutorial httpsphinxpocooorgtutorialhtml although i still trying understand docs way worded makes concerned sphinx assumes i going manually create documentation files every single moduleclassfunction codebase however i notice automodule statement i enabled autodoc quickstart i hoping documentation automatically generated i modified confpy add src folder syspath modified indexrst use automodule so indexrst looks like contents toctree maxdepth indices tables refgenindex refmodindex refsearch automodule alphabuyer members i dozens classes functions defined subpackages yet i run sphinxbuild b html build reports updating environment added changed removed and appears failed import anything inside package viewing generated indexhtml shows nothing next contents the index page shows mypackage module clicking shows also contents how direct sphinx recursively parse package automatically generate documentation every classmethodfunction encounters without manually list every class,3 firstly try except functions statements to convert string type converted integer python simply call int builtin function int raise valueerror fails catch specifically in python x value l b xfe not convertable try print int strvalue intvalue except valueerror ex print cannot converted int value ex int int int int int int not convertable cannot converted int invalid literal int base not convertable in python x syntax changed slightly value b xfe not convertable try print int strvalue intvalue except valueerror ex print cannot converted int value ex int int int int int int not convertable cannot converted int invalid literal int base not convertable,so i pretty stumped convert string int using tryexcept function does anyone know simple function i feel like i still little hazy string ints i pretty confident ints related numbers stringsnot much,2 i produced simple example could test the result could look like usrbinpython reportlabgraphicschartslineplots import lineplot reportlabgraphicsshapes import drawing reportlablib import colors random import randint datetime import date timedelta generate testdata data xrandint x range xrandint x range xrandint x range create drawing lineplot drawing drawing lp lineplot lpx lpy lpheight lpwidth lpinfill lpdata data rangelendata lplinesistrokecolor colorstocolor hsls specify labels lpxvalueaxisvaluesteps create formatter takes value format however like def formatterval return val return xs val return date timedeltavalstrftime ymd use formatter lpxvalueaxislabeltextformat formatter drawingaddlp reportlabgraphics import renderpdf renderpdfdrawtofiledrawing examplepdf lineplot dates in formatter alternative return statements could play get better grip of course data xaxis dates begin need formatter case could specify labels satisfied default positioning the example borrows ideas page reportlab documentation good luck,i using reportlab generate lineplot chart i seem get non numeric labels x axis does anyone ideas this lineplot chart class note im donig calculations setup outside class get gist import reportlab advisorchartingfont import font reportlablibcolors import color hexcolor reportlablibpagesizes import cm inch reportlabgraphicschartslegends import legend reportlabgraphicschartstextlabels import label reportlabgraphicschartslinecharts import horizontallinechart reportlabgraphicschartslineplots import lineplot reportlabgraphicsshapes import drawing string drawingeditormixin reportlabgraphicswidgetsmarkers import makemarker class tacticalauglinegraphdrawingeditormixin drawing def initself width height legendfalse args kw applydrawinginit self width height args kw chartfont font gothambold selfaddself lineplot name chart validatenone descnone selfchartinfill selfchartx selfcharty selfchartwidth selfchartheight selfchartlinelabelformat selfchartyvalueaxisvaluemin selfchartyvalueaxisvaluemax selfchartyvalueaxisvaluestep def applycolorsself colors selfchartlinesstrokecolor colors selfchartlinesstrokecolor colors selfchartlinesstrokecolor colors selfchartlinesstrokecolor colors,3 strings immutable modify directly create new string existing one try lens return else return,i using python trying find solution problem get string certain function need switch first last character example string hello return oellh slicing work cant replace characters like normally dont know string going long would i thought replacing character position character position cant find something enable does anyone suggestions,2 use following xpath expression nsentrynscontentname type directory,i filesyste represented xml document following format xml xmlnsnamespace xmlnsnsnamespace entry idid nscontent nametypedirectorynscontent nscontent namenumerrorsnscontent entry entry idid nscontent nametypefilenscontent nscontent namedocstatesuccessnscontent entry xml what i need using python lxml retrieve entry objects represent directories all entries contain nscontent namedocstate object i need know retrieve list entry objects object text equal directory i several inconvenient steps i would rather one query here way i would steps xmlparsepy ns ns namespace ns namespace node treexpathnsentrynamespacesns nodefindnscontentname type textdirectory stuff node pass can anyone explain within statement instead using thanks,3 lens else this swap everything except edge cases single char the snippet code slices string three chunks the end chunks swap first last letters middle chunk grabs middle string below i show chunk interpreter hello ell h you slice string length index errors fact reason swap character string that else protects if understand else works read snippet this returns expr expr true otherwise returns expr expr expr else expr the expression short hand expr expr else expr i hope made sense,i using python trying find solution problem get string certain function need switch first last character example string hello return oellh slicing work cant replace characters like normally dont know string going long would i thought replacing character position character position cant find something enable does anyone suggestions,3 what want search something called sqlstate set standard error codes cover common rdbms error states they necessarily provide enough detail purposes though i know sqlite supports httpwwwpostgresqlorgdocsstaticerrcodesappendixhtml httpdevmysqlcomdocrefmanenerrorhandlinghtml,in project i started mysql database instead checking first i insert i get integrityerror exception code i know duplicate entry warn user looks basically like try add duplicate nothing bad happens yet sqla session dbsessionadduseremail alreadyusedemailaddressthathastobeuniquecom commit integrityerror raised sqla inserts dbsessioncommit except integrityerror e dbsessionrollback mysql check exception code replace something db independent code msg eorig code send warning pass now one makes already impossible test eg inmemory sqlite not nice i could live second however i might towant scope question issues switch postgres of course i could change code also check postgres error codes i hoping way sqlalchemy tell duplicate happened independent database a database dialect abstraction,2 i add yet another option list define variable newline use inside doublequotes nl n summary today date poor whiskers takes tumblenlshe fine though worry,first take look question bash googlecl new line string parameter i want add variable date summary google youtube post videoscatfallsdownstairsavi comedy tags currency internet summary today date poor whiskers takes tumblenshe fine though worry variable wont expand inside single quote bash is possible note googlecl commandline program written python i ubuntu python,2 the web page reopened single ie instance using one pamie instance if really want multiple ie windows open use multiple pamie instances here one simple crude example note import line may slightly different mine pamie import pam ie pampamiehttpwwwgooglecom ie pampamiehttpnewsgooglecom so use ienavigate ienavigate etc fill forms websites for example use first ie instance iesettextboxqmy text goes ieclickbuttonbtnk and done instance kill leave web page open done anything else kills python object ie none,i using pamie auto log websites i couple i got scripts i get pamie open new ie window i run script opens one logs next one open closes first opens second so i get pamie open new windows this i websitehttpswebsite ienavigatewebsite iesettextboxusernamemyusername iesettextboxpasswordmypassword ieclickbuttonbtnsubmit then i want need new window websitehttpswebsite ienavigatewebsite iesettextboxusernamemyusername iesettextboxpasswordmypassword ieclickbuttonbtnsubmit i tried ienew navigatewebsite someone could please tell command open new window i would appreciate i also trie iechangewindow get work thanks,1 this exactly model managers class myactivemanagermodelsmanager def activeself return selffilterisactivetrue def onlineself return selffilterisonlinetrue class mymodel objects myactivemanager activeobjects mymodelobjectsactive onlineobjects mymodelobjectsonline,in django application several views may contain similar db queries for instance query entities isactive true isonline true during refactoring duplicate calls need moved function question filterquery function better placed into definition classentity but object know filter methods this seems typical solution may good design since selection feels feature external object on hand methods inside object create sideeffects seem pretty safe into modulenamespace dealing filtering like filterusers filterentities or somewhere else whats best practice,2 as schildmeijer quoted tornado website i recommend using nginx serve static files having setup early convenient easy this also allows potential benefits future using nginx load balancing using nginx handle ssl,i directory structure setup like root js css libs indexhtml from tornado i want serve js css libs static directories i find serve one can done,1 here i would first define string search remove extraneous characters tosearch this text string i typed hlelo i meant type hello import string exclude setstringpunctuation tosearch joinch ch tosearch ch exclude tosearch this text string i typed hlelo i meant type hello words settosearchsplit next use difflib library find close matches given word import difflib difflibgetclosematches hello words hello hlelo,i list keywords i trying find text string the exact matches works fine anyone aware library could help approximate matches instance list words i provide hello bye i like watch text string hlelo certain degree closeness any recommendations,2 you could invoke windows shell command dir q parse output find owners subprocesscalldir q shelltrue,i writing script needs determine username owner files windows while i found solution using pywin i hesitant use i want add module dependency the script written python run bit plattforms i wondering different method maybe ctypes determine information,2 v v cexecute update archive set date where id vv for cursorexecute pass sequence values sequence sequence values for cursorexecutemany contrast would want pass sequence sequences,how take two values sqlite v v vvv vvv conn sqliteconnect datedb c conncursor cexecute update archive set date where id vvvv vvvv work conncommit i know probably simple find anything net tnx,1 beautifulsoup unicodedammit able detect encoding document even specified what happens run page question beautifulsoup import unicodedammit unicodedammithtmlstringunicode what specific line code throwing error sample problematic html,i plugging away hours i seem get bottom i website detail although others seem similar problem solutions given work i python script reads html website uses beautiful soup find things like head body h etc store utf mysql table seems straight forward i keep running unicodedecodeerror ascii codec decode byte xxxxxx when i encode i tried everything i find stop happening avail here one version code soup beautifulsoupstrindexpage strindexpagebody strsoupbody strindexpagebody strindexpagebodyencode ascii ignore i know ignore best practice i really interested anything outside ascii character set strindexpagebody strindexpagebody replace ampquot strindexpagebody strindexpagebody replace amprsquo an earlier version i tried convert utf works better i end character present html breaks mysql insertupdate obviously i tried searching character replacing python tells i non ascii character code i read tons articles say i looking encoding html first decode encode suit encoding always come back bs andor declared within html i sure simple way around i find thanks help,1 there technique strip accents characters characters need directly replaced check article httpeffbotorgzoneunicodeconverthtm,know wether trivial i need convert unicode string ascii string i like escape chars around i mean possible approximate conversion quite similar ascii character for example gavin o’connor gets converted gavin oxconnor i really like converted gavin o connor is possible did anyone write util i manually replace chars thank much marco,1 import unicodedata unicodestring ugavin o’connor print unicodedatanormalize nfkd unicodestringencode ascii ignore output gavin o connor here document describes normalization forms httpunicodeorgreportstr,know wether trivial i need convert unicode string ascii string i like escape chars around i mean possible approximate conversion quite similar ascii character for example gavin o’connor gets converted gavin oxconnor i really like converted gavin o connor is possible did anyone write util i manually replace chars thank much marco,1 use unidecode package transliterate string import unidecode unidecodeunidecodeu gavin o’connor gavin o connor,know wether trivial i need convert unicode string ascii string i like escape chars around i mean possible approximate conversion quite similar ascii character for example gavin o’connor gets converted gavin oxconnor i really like converted gavin o connor is possible did anyone write util i manually replace chars thank much marco,3 b straencode utf decode ascii ignore work fine,know wether trivial i need convert unicode string ascii string i like escape chars around i mean possible approximate conversion quite similar ascii character for example gavin o’connor gets converted gavin oxconnor i really like converted gavin o connor is possible did anyone write util i manually replace chars thank much marco,3 python float builtin set stone you change you could use float numpy,is anyway i ask python explicitly treat floats bits even bit machine i want change codes,2 filter returns iterator python iterator consumed first run inner forloop after measuring speed contructor repeat often make consume least bit time so seems constructor set fastest one dealing empty iterator,i’m running filter interable want store result sequence i need sequence i use randomchoice i noticed creating set filter object lot faster creating list tuple why i first though filter type subtype set would explain filter function actually identical generator expression cannot really set internally i ran following test check speed import time def test n seq method set list tuple timetime range n method seq print methodname timetime somefilter filter lambda x x range test somefilter and results speaking clearly using set set list tuple so creating set filter much faster shouldn’t usually take long creating set sequence every element hashed or somehow getting boost internal filter representation for comparison running test range expression set takes twice long list tuple nearly identical speed edit sven’s answer totally right completeness updated test run actual filter import time def testfilter n test rangesize method set list tuple timetime range n method filter test range rangesize print methodname timetime testfilter lambda x x the result actually shows makes sense list tuple fastest although set isn’t really slower won’t make difference use set list tuple,3 why use youtube data api the video feed contains gdrating average max min numraters rel httpschemasgooglecomgoverall within entry,lots results php likedislike results youtube nothing python i want scrape number likes dislikes using beautifulsoup youtubeapi include i know likes dislikes contained within spanclass span classwatchlikesdislikes span classlikesspan likes span classdislikesspan dislikes span thank,2 when timings suggest results illogical often timing suite fault try using timeit module help steer clear common timing mistakes in particular want run fresh setup test time loop body rather body plus test code in case would least made timings comparable would used fresh iterator returned python version filter would shown unbelievably fast timings methoditerator code would timed loop fwiw pypy even harder time overly simple loops get optimized away completely answer question edited you new timings comparable good improvement results still show combination setup time loop time making difficult see differences might significant your expectation lists tuples beat sets sets work hashing inputs rather simply storing,i’m running filter interable want store result sequence i need sequence i use randomchoice i noticed creating set filter object lot faster creating list tuple why i first though filter type subtype set would explain filter function actually identical generator expression cannot really set internally i ran following test check speed import time def test n seq method set list tuple timetime range n method seq print methodname timetime somefilter filter lambda x x range test somefilter and results speaking clearly using set set list tuple so creating set filter much faster shouldn’t usually take long creating set sequence every element hashed or somehow getting boost internal filter representation for comparison running test range expression set takes twice long list tuple nearly identical speed edit sven’s answer totally right completeness updated test run actual filter import time def testfilter n test rangesize method set list tuple timetime range n method filter test range rangesize print methodname timetime testfilter lambda x x the result actually shows makes sense list tuple fastest although set isn’t really slower won’t make difference use set list tuple,2 it known issue ipython it fixed hopefully christmas,ipython i set automatic launch pdb exceptions in ipython works fine in zerodivisionerror traceback recent call last homezoncaipython console module zerodivisionerror float division zero ipython consolemodule ipdb instead ipython exception not visible in ipythoninputebfbdamodule ipdb i see i exit debugger in ipythoninputebfbdamodule ipdb zerodivisionerror traceback recent call last homezoncaipythoninputebfbda module zerodivisionerror float division zero in anybody else issue i ubuntu python ipython installed pip,1 you could find files created modified last halfhour looking mtime file import os import datetime dt dtdatetimenow ago nowdttimedeltaminutes root dirsfiles oswalk fname files path ospathjoinroot fname st osstatpath mtime dtdatetimefromtimestampststmtime mtime ago print modified path mtime to generate list deleted files also list files minutes ago a robust alternative use revision control system like git making commit files directory like making snapshot then command git status would list files changed since last commit this list files deleted,i know list subdirectories files directory tree but i looking way list newly created files modified possible deleted files directories directory tree starting root directory,3 looks like need qpixmapfill pyqt import qtgui class windowqtguiqcombobox def initself qtguiqcomboboxinitself selfresize pixmap qtguiqpixmap color red orange yellow green blue grey violet split pixmapfillqtguiqcolorcolor selfadditemqtguiqiconpixmap colortitle name main import sys app qtguiqapplicationsysargv win window winshow sysexitappexec,i know possible i cannot life get proper code work what i want simple monochromatic rectangle size say x constructed presumably qpainter from i wish use painted rectangle qicon use qcombobox any ideas thanks advance,2 this size float baked compilation time you pass compile option treat c double float fresh python executable file,is anyway i ask python explicitly treat floats bits even bit machine i want change codes,1 for worth simple numpy numpyarangereshape array block block numpyrotblock copy array,x matrix list lists python the matrix divided square blocks size x i want way take transpose block i using traditional method going element copying another array back i want see better way transposing matrix python done one line using zip method eg representation matrix blocks block block block block rotate right result block block block block i want find method takes block number rotates block left right is easy way,2 note getting decode error call encode this ugliest part python lets try encode string already encoded first decoding ascii what equivalent sdecode ascii strict encode ascii ignore i think expect soup beautifulsoupstrindexpage strindexpagebody unicodesoupbody strindexpagebody strindexpagebodyencode ascii ignore note calling unicode get unicode string validly try encode,i plugging away hours i seem get bottom i website detail although others seem similar problem solutions given work i python script reads html website uses beautiful soup find things like head body h etc store utf mysql table seems straight forward i keep running unicodedecodeerror ascii codec decode byte xxxxxx when i encode i tried everything i find stop happening avail here one version code soup beautifulsoupstrindexpage strindexpagebody strsoupbody strindexpagebody strindexpagebodyencode ascii ignore i know ignore best practice i really interested anything outside ascii character set strindexpagebody strindexpagebody replace ampquot strindexpagebody strindexpagebody replace amprsquo an earlier version i tried convert utf works better i end character present html breaks mysql insertupdate obviously i tried searching character replacing python tells i non ascii character code i read tons articles say i looking encoding html first decode encode suit encoding always come back bs andor declared within html i sure simple way around i find thanks help,2 httpdocspythonorgtutorialfloatingpointhtml almost machines today july use ieee floating point arithmetic almost platforms map python floats ieee “double precision” doubles contain bits precision input computer strives convert closest fraction form jn j integer containing exactly bits it looks like sized floats bit machine neither bits if must bit floats either use virtual machine run version python use bit floats though i idea thing exists compile idea you able use bit python version bit machine though change way floats work i think main difference bit bit python ram use bit use ram also ram hungry,is anyway i ask python explicitly treat floats bits even bit machine i want change codes,1 use csvreader parse file dictionary cluster results the strrpartition method splitoff seconds use sum len compute average data splitlines import csv timestamp value csvreaderdata minute colon second timestamprpartition minute dminute floatvalue else dminuteappendfloatvalue minute values sortedditems avgvalue sumvalues lenvalues print minute stravgvalue,i big csv file datetime value recorded every seconds the csv file looks like datetime data i want write script would calculate minute average write new csv file giving following output datetime data any idea done suggestions modules i look examples,1 it seems easiest way treat time string rather time use itertoolsgroupby csv import reader itertools import groupby lines datetime data lines iterlinessplitlines testing really open filename rb lines indent rest nextlines minute group groupbyreaderlines lambda row row group listgroup print minute sumfloatrow row group lengroup,i big csv file datetime value recorded every seconds the csv file looks like datetime data i want write script would calculate minute average write new csv file giving following output datetime data any idea done suggestions modules i look examples,1 edit i recommend using greenlet but interested pure python approach read this addressed pep somewhat tough understand first i try explain simply works first let sum i think problem really trying solve problem you callstack generator functions calling generator functions what really want able yield generator top yield propagate way stack the problem python language level support real coroutines generators but implemented real coroutines allow halt entire stack function calls switch different stack generators allow halt single function if generator f wants yield yield statement f another function f calls the solution i think using something like simon stelling answer ie f call g yielding g results this verbose ugly looking syntax sugar wrap pattern note essentially unwinds stack every time yield winds back afterwards solution there better way solve problem you basically implement coroutines running generators top trampoline system to make work need follow couple patterns when want call another coroutine yield instead returning value yield def f result g … return returnvalue becomes def f result yield g … yield returnvalue say f the trampoline system called f when yield generator say g trampoline system calls g behalf then g finished yielding values trampoline system restarts f this means actually using python stack trampoline system manages callstack instead when yield something generator trampoline system treats return value it passes value back caller generator yield statement using send method generators comments this kind system extremely important useful asynchronous applications like using tornado twisted you halt entire callstack blocked go something else come back continue execution first callstack left the drawback solution requires write essentially functions generators it may better use implementation true coroutines python see alternatives there several implementations coroutines python see httpenwikipediaorgwikicoroutineimplementationsforpython greenlet excellent choice it python module modifies cpython interpreter allow true coroutines swapping callstack python provide syntax delegating subgenerator see pep,i studying coroutines generators various programming languages i wondering cleaner way combine together two coroutines implemented via generators yielding back caller whatever callee yields let say using following convention yields apart last one return null last one returns result coroutine so example could coroutine invokes another def a yield certain condition met yield result def b something may may yield x binda return result case i wish bind may may implementable question coroutine b yields whenever a yields a returns final result assigned x allowing b continue i suspect actual code explicitly iterate a def b something may may yield x a return result tad ugly error prone ps game users language designers write scripts script coroutine each character associated script many subscripts invoked main script consider example runship invokes many times reachclosestenemy fightwithclosestenemy fleetoallies all subscripts need invoked way describe developer problem designer less code write better,3 here excerpt one batch files rem configure environment bit builds rem use vcvarsbat bit build cprogram files xmicrosoft visual studio vcbinvcvarsbat rem convince setuppy use sdk tools set mssdk set distutilsusesdk the sdk uses effectively vs python compiled vs if use sdk i think also known net sdk access vs compiler it risky mix different compilers runtimes libraries,i trying compile simple cython extension example page windows bit machine python bit version installed i installed cython windows bit version gohlke page basically answer options i really need python bit version address larger memory also i trying compile using microsoft sdk net i cannot use approach latter solution i tried steps observed green window compilation throws cannot find vcvarsallbat error following sequence commands i tried ccd program filesmicrosoft sdkswindowsv cprogram filesmicrosoft sdkswindowsvset distutilsusesdk cprogram filesmicrosoft sdkswindowsvsetenv x release setting sdk environment relative cprogram filesmicrosoft sdkswindowsv targeting windows x release cprogram filesmicrosoft sdkswindowsve ecd cython ecythonpython setuppy buildext inplace running buildext skipping fibc cython extension uptodate building fib extension error unable find vcvarsallbat any suggestions i solve,3 the docs httpwikicythonorgbitcythonextensionsonwindows say for python use microsoft windows sdk windows net framework sp later earlier versions sdk link wrong c runtime note later versions python likely require recent version windows sdk this required make sure extension linked c runtime version python using correct version sdk way control microsoft build tools,i trying compile simple cython extension example page windows bit machine python bit version installed i installed cython windows bit version gohlke page basically answer options i really need python bit version address larger memory also i trying compile using microsoft sdk net i cannot use approach latter solution i tried steps observed green window compilation throws cannot find vcvarsallbat error following sequence commands i tried ccd program filesmicrosoft sdkswindowsv cprogram filesmicrosoft sdkswindowsvset distutilsusesdk cprogram filesmicrosoft sdkswindowsvsetenv x release setting sdk environment relative cprogram filesmicrosoft sdkswindowsv targeting windows x release cprogram filesmicrosoft sdkswindowsve ecd cython ecythonpython setuppy buildext inplace running buildext skipping fibc cython extension uptodate building fib extension error unable find vcvarsallbat any suggestions i solve,3 instead reinventing wheel check dbpedia already extracted wikipedia infoboxes easily parsable database format,i need get content infobox movie i know name movie one way get complete content wikipedia page parse i find infobox get content infobox is way using api parser i using python pywikipediabot api i also familiar wikitools api so instead pywikipedia someone solution related wikitools api please mention well,2 you use modulo division remainder operator lens if want strip string length divisible use slens slens,string string abcdefg wanted check length string divisible lenstring command would use,3 hexordc x formatordc x cencodehex,i interested taking single character c c example hexvalstring chartohexstringc print hexvalstring output what simplest way going any predefined string library stuff,3 everything looks working like even example bytes swapped back if system byte order network noop question states network bytes order big host little swapping in xece in b xeec in out in b out in sockethtonsa out in sockethtonsb out in sockethtonsa b out true in sockethtonsb out true in hexsockethtonsa out xeec in hexsockethtonsb out xece in binsockethtonsa out b in binsockethtonsb out b from python socket reference sockethtonsx convert bit positive integers host network byte order on machines host byte order network byte order noop otherwise performs byte swap operation,i currently looking socket programming python i experiencing strange behavior sockethtons appears flipping bytes every call i implementing simple ping script far i aware network byte order big endian systems byte order little endian if i use htons bit checksum wireshark reports incorrect however i pack checksum struct without using htons wireshark confirms correct this wireshark captured using htons checksum xece incorrect xeec and quick example z xff print z z sockethtonsz print z z sockethtonsz print z any thoughts would greatly appreciated hopefully something wrong edit print sysbyteorder little,1 there post i wrote talks setup mongrel wsgid run wsgi app it httpdaltonmatoswordpresscomdeployingyourdjangoapplicationwithmongrelandwsgid,this attempt discover canonical answer something seems hard google right i writing web app pyramid i luxury deciding server stack look like i heard good things mongrel would like try using serve app however i figure mongrel manual google searches connect mongrel wsgi app do i roll existing solutions problem,2 i think reversed looking records ppnref epdfeae presult ppnref epeb presult ppnref epad presult ppnref epaac presult ppnref epaffc presult ppnref epba presult record reversedrecords record presult print record ppnref break,i dict dicts results print recurring ppnref epdfeae presult recurring ppnref epeb presult recurring ppnref epad presult recurring ppnref epaac presult recurring ppnref epaffc presult recurring ppnref epba presult im interested value presult i easily grabb last entry listresultspresult i looking go loop list backwards i land entry presult in example second line ppnref epeb how i accomplish if i could iterate negative index i think i could figure rest im sure assuming recurring payments successful payment im trying grab recent successful transaction,2 you sense already written descrambler all feed scrambler inverse permutation below inverse permutation given argsortp p permutation def scrambles p scramble string s permutation p pn lenp length permutation array e lens pn lenspn array chars padded rangelens segj divmodipn e segpn pj si return joinerstrip def argsortseq httpstackoverflowcomquestions seq indexargsortseq given seq index construct sorted seq sortedseqseqx x index assert sortedseq sortedseq given sorted seq index reconstruct seq assert sortedseqx x argsortindex seq return sortedrangelenseq keyseqgetitem p textabcdefghij print scrambletextp ahgedbifjc printscramblescrambletextpargsortp abcdefghij by way instead preallocating enough space e e lens pn lenspn generate items e order using argsort def scrambles p pn lenp e idx argsortp rangelens segj divmodipn eappendsidxjsegpn return joine,help trying descramble file using permutation keyi know scramble need create function descramble back using permutation key code def stringtoarrays a ilens aappendsi return a def arraytostringa s c a elementvalue c array a s sc return s arraytostring def scrambles p scramble string s permutation p pn lenp length permutation array e lens pn lenspn array chars padded lens seg ipn segment number j pn segment offset e segpn pj si return arraytostringe scramble print scrambleabcdefghij prints ahgedbifjc i want set back string abcdefghij,1 i problem windows i deleted netbeans directory located home folder that fixed problem hope fixes,i went tools plugins then chose install three python items show after installation i choose restart netbeans option but instead restarting netbeans closed and opening any ideas fix i normally develop java netbeans install i using mac osx i see takers let ask is way revert new plugin install,1 while telnet insecure essentially serial console network makes easy code ssh much much complex there encryption authentication negotiation etc and easy get wrong spectacular fashion there nothing wrong telnet per se change things network private network opening trouble assuming running computer restrict server localhost then ssh computer telnet localhost all security minimal hassle,i write python telnet client communicate server telnet however many people tell secure how i convert ssh should i need totally rewrite program,1 i used viewdecorator snippet httpdjangosnippetsorgsnippets wrap normal function decorators,how i implement userpassestestlambda u uissuperuser decorator class based views i used function based views i work around feels unnaturally shouldn covered dispatch method,1 building sven marnach idea use nprot version rotates quadrant clockwise requested in key step block nprotblockcopy copy used righthand side rhs without copy values assigned block underlying data used rhs also changed this muddles values used subsquent assignments without copy multiple values spread block i see way operation without copy import numpy np nparangereshape printa block to rotate counterclockwise block nprotblockcopy printa to rotate clockwise nparangereshape block block nprotblockcopy printa,x matrix list lists python the matrix divided square blocks size x i want way take transpose block i using traditional method going element copying another array back i want see better way transposing matrix python done one line using zip method eg representation matrix blocks block block block block rotate right result block block block block i want find method takes block number rotates block left right is easy way,3 the easiest way create single wsgi app tingpy add handlers urls then delete mapping,i need help appyaml url management i scripts tingpy searchandlerpy toplawfirmspy i created tingpy first i appyaml url script tingpy pages declared tingpy but i think i made mistake searchhandlerpy toplawfirmspy making second level is way appyaml three scripts appyaml would look like url script searchhandlerpy url script toplawfirmspy url script tingpy i declare pages scripts this i application ting version runtime python apiversion handlers url ahmail script incomingpy login admin url stylesheets staticdir stylesheets url faviconico staticfiles staticimagesfaviconico upload staticimagesfaviconico url image script toplawfirmspy url imageupload script toplawfirmspy url imagesave script toplawfirmspy url imageresize script toplawfirmspy url displayimage script toplawfirmspy url histogram script toplawfirmspy url testurlopen script toplawfirmspy url printdb script toplawfirmspy url cropimage script toplawfirmspy url jquerytest script toplawfirmspy url urlopenppp script toplawfirmspy url deleteone script toplawfirmspy url enterppp script toplawfirmspy url saveppp script toplawfirmspy url searchhandler script searchhandlerpy url site script searchhandlerpy url searchall script searchallpy url script tingpy inboundservices mail,1 currently possible use waitforcondition webdriver the python selenium code provide drivenselenium class accessing old selenium methods waitforcondition the selenium wiki info your best bet use webdriverwait class this helper class periodically executes function waiting return true my general usage driver webdriverfirefox driverget httpexamplecom add driverfindelementbyidajaxbutton addclick source driverpagesource def comparesourcedriver try return source driverpagesource except webdriverexception pass webdriverwaitdriver untilcomparesource assertions this solution means ideal the tryexcept necessary situations page requestresponse cycle delayed waiting ajax activity complete if comparesource get called midst requestresponse cycle throw webdriverexception the test coverage webdriverwait also helpful look,i moving tests selenium webdriver my problem i find equivalent seleniumwaitforcondition do python bindings moment still planned,3 select word from table where word not like and word not like b and word not like c,i sqlite query executed inside python code an example would select word from table where word not like this would select words occur word this i get work perfectly the problem i want restrict results include b anywhere word i picturing something like select word from table where word not in b z obviously work kinda idea and adding and clause really option unless way perform so code option select word from table where word not like and not like b if option i work i hoping something else thanks advance help,3 soupfind abbr string work fine there must something wrong date beautifulsoup import beautifulsoup doc abbr classdtstart titletnovember abbr soup beautifulsoupdoc abbr soupfindall abbr print abbrstring result november update based code added question you use text parameter like httpwwwcrummycomsoftwarebeautifulsoupdocumentationhtmlargtext text argument lets search navigablestring objects instead tags either looking text nodes looking tags a text node tag name maybe want joinelstring el rfindall strong,say i used date rfind abbr get abbr classdtstart titletnovember abbr i want print november i try print datestring i get attributeerror nonetype object attribute string what i wrong answer here final working code learning purposes soup beautifulsouppage calendar soupfind table class vcalendar ical dates calendarfindall abbr class dtstart events calendarfindall strong rangelendates print datesistring eventsistring,1 if use sqlite regexp support see answer problem regexp python sqlite easily one clause select word from table where word not regexp abc,i sqlite query executed inside python code an example would select word from table where word not like this would select words occur word this i get work perfectly the problem i want restrict results include b anywhere word i picturing something like select word from table where word not in b z obviously work kinda idea and adding and clause really option unless way perform so code option select word from table where word not like and not like b if option i work i hoping something else thanks advance help,3 i sure avoiding and clause it simplest solution otherwise would need intersect multiple queries select word from table where word not like intersect select word from table where word not like b intersect select word from table where word not like c alternatively use regular expression version sql supports,i sqlite query executed inside python code an example would select word from table where word not like this would select words occur word this i get work perfectly the problem i want restrict results include b anywhere word i picturing something like select word from table where word not in b z obviously work kinda idea and adding and clause really option unless way perform so code option select word from table where word not like and not like b if option i work i hoping something else thanks advance help,1 you explicitly set binding release return key binding keyreleasereturn for example import tkinter tk class sampleapptktk def initself args kwargs tktkinitself args kwargs selftext tktextself selftextpack selftextbindkeyreleasereturn selfonreturnrelease def onreturnreleaseself event selftextinsertend boink name main app sampleapp appmainloop if want anything happen press return key remove default binding create binding returns break,is way make return event call key release instead press if use keyrelease eventchar blank special key return,3 my guess tag template rendering anything mean confirmed actual html csrf token generated either use requestcontext instead dictionary rendertoresponsefoohtml requestcontextrequest or make sure djangocorecontextprocessorscsrf contextprocessors setting httpsdocsdjangoprojectcomendevrefcontribcsrf or add token context manually,beginner django i trying fix long time i djangomiddlewarecsrfcsrfviewmiddleware middleware classes i token post form heres code i wrong djangocontribauthforms import usercreationform djangoshortcuts import rendertoresponse djangohttp import httpresponseredirect chartseyauthenticationforms import registrationform djangotemplate import requestcontext djangocorecontextprocessors import csrf def registerrequest requestmethod post c requestcontextrequestpost form registrationformc formisvalid newuser formsave return httpresponseredirect else form registrationform return rendertoresponseregisterhtml form form here template block content hregisterh form action methodpost csrftoken formasp input typesubmit valuesubmit form endblock,3 numpyndarray defines iter usual mechanism make instances type iterable note numpyndarray c extension type matter question iterable both types define python c extension types made iterable defining iter,numpy ndarray class defined class ndarraybuiltinobjects from i gather builtinobjects iterable type for reason i find behavior surprising arr numpyarray as far as i know split array as far as i know dtype s print maplambda x xarr a f a i k or come attributes list object passed init method ndarray but cannot i use methods like listreverse array object internally stored list side anyone know better way apply stringoperations element ndarray objects,2 ctypes gets job done would simpler reliable use pywin rolling runs risk introducing bugs that said following example uses ctypes access winapi functions code snippet linked question import ctypes ctypes ctypes import wintypes wintypes advapi ctypeswindll advapi uselasterrortrue errorinvalidfunction x errorfilenotfound x errorpathnotfound x erroraccessdenied x errorinsufficientbuffer xa lpbool ctypespointerwintypesbool lpdword ctypespointerwintypesdword psid ctypespointerwintypesbyte psecuritydescriptor ctypespointerwintypesbyte securityinformation wintypesdword ownersecurityinformation x groupsecurityinformation x daclsecurityinformation x saclsecurityinformation x labelsecurityinformation x attributesecurityinformation x scopesecurityinformation x backupsecurityinformation x unprotectedsaclsecurityinformation x unprotecteddaclsecurityinformation x protectedsaclsecurityinformation x protecteddaclsecurityinformation x class sidnameusewintypesdword sidtypes dictenumerate user group domain alias wellknowngroup deletedaccount invalid unknown computer label split def initself valuenone value none value selfsidtypes raise valueerror invalid sid type supersidnameuse selfinitvalue def strself selfvalue selfsidtypes raise valueerror invalid sid type return selfsidtypesselfvalue psidnameuse ctypespointersidnameuse def checkboolresult func args winerrorctypeswinerror getlasterrorctypesgetlasterror result raise winerrorgetlasterror return args msdnmicrosoftcomenuslibraryaa advapigetfilesecuritywerrcheck checkbool advapigetfilesecuritywargtypes wintypeslpcwstr in lpfilename securityinformation in requestedinformationrequested psecuritydescriptor outopt psecuritydescriptor wintypesdword in nlength lpdword out lpnlengthneeded msdnmicrosoftcomenuslibraryaa advapigetsecuritydescriptorownererrcheck checkbool advapigetsecuritydescriptorownerargtypes psecuritydescriptor in psecuritydescriptor ctypespointerpsid out powner lpbool out lpbownerdefaulted msdnmicrosoftcomenuslibraryaa advapilookupaccountsidwerrcheck checkbool advapilookupaccountsidwargtypes wintypeslpcwstr inopt lpsystemname psid in lpsid wintypeslpcwstr outopt lpname lpdword inout cchname wintypeslpcwstr outopt lpreferenceddomainname lpdword inout cchreferenceddomainname psidnameuse out peuse def getfilesecurityfilename request length wintypesdword nb this query may fail errorinvalidfunction filesystems try advapigetfilesecuritywfilename request none ctypesbyreflength except windowserror e ewinerror errorinsufficientbuffer raise lengthvalue return none sd wintypesbyte lengthvalue advapigetfilesecuritywfilename request sd length ctypesbyreflength return sd def getsecuritydescriptorownersd sid psid siddefaulted wintypesbool advapigetsecuritydescriptorownersd ctypesbyrefsid ctypesbyrefsiddefaulted return sid def lookupaccountsidsid size name ctypescreateunicodebuffersize domain ctypescreateunicodebuffersize cchname wintypesdwordsize cchdomain wintypesdwordsize sidtype sidnameuse advapilookupaccountsidwnone sid name ctypesbyrefcchname domain ctypesbyrefcchdomain ctypesbyrefsidtype return namevalue domainvalue sidtype example name main import sys filename sysargv isinstancefilename bytes filename filenamedecodesysstdinencoding request ownersecurityinformation sd getfilesecurityfilename request sid getsecuritydescriptorownersd name domain sidtype lookupaccountsidsid domain name formatdomain name printfile formatfilename printowner formatname sidtype output cgetfilesecuritypy cwindows file cwindows owner nt servicetrustedinstaller wellknowngroup cgetfilesecuritypy cusers file cusers owner nt authoritysystem wellknowngroup cgetfilesecuritypy ctemp file ctemp owner builtinadministrators alias,i writing script needs determine username owner files windows while i found solution using pywin i hesitant use i want add module dependency the script written python run bit plattforms i wondering different method maybe ctypes determine information,3 you want create symlink desired version cd libraryframeworkspythonframeworkversions sudo rm current sudo ln libraryframeworkspythonframeworkversions current this removes current pointer default python version sets version,how i change default python version used mac snow leopard i trying switch v v,1 after stripping right back chatting guy sa irc channel appeared mac osx problem so i set linux thing occured in end i resorted running script crontab works fine m,this script slowly eats ram when i run i see ram usage python creep approx mb loop i figure i figured iteration query adds ram i figure any help would awesome haystackpmod import piliplacement sa model time import sleep datetime import datetime sqlalchemy import createengine sqlalchemyorm import sessionmaker datetimenow engine createengine mssqlxxxxxxxuiduserpwdxxxxx echofalse session sessionmakerbindengine def syncplacementssession query sessionquerypiliplacementfilterpiliplacementtime piliplacements pidplacement p queryall adds ram del piliplacements print loop true session session syncplacementssession sleep,1 try changing line page requestgetget page to page requestgetget page the problem getting parameter exist indexing using would result keyerror get method returns none exist the paginator calling intnone fails the second parameter get method default return key exist rather none i passed int fail,i trying use django pagination module including standard distribution version when attempting load page currently controlled pagination i include page uri throws typeerror i never situation arise see reason occurring here current view paginator paginatormailslist shows mails per page page requestgetget page try mails paginatorpagepage except pagenotaninteger if page integer deliver first page mails paginatorpage except emptypage if page range eg deliver last page results mails paginatorpagepaginatornumpages typeerror int argument must string number nonetype the error presented line code mails paginatorpagepage anyone witnessed error andor know correct,3 judging commentto evan correct answer want skip nls in case try normalizespacetrcontainstddescriptionfollowingsiblingtrtd note if argument normalizespace selects one node function return result processing first selected node all leading trailing whitespace characters deleted all intermediate groups adjacent whitespace characters replaced single space character,i new xpath please bear currently i looking use scrapy scrape content webpages content looks something like td colspan valigntop classregularlandsize sq extensive shoreline mbr br call or email infobr fulllength olympicpoolchildren pooljacuzzibr landscapesdkey bridgesbr tennis courtsbr water features true seafront development iconic design architect daniel libeskindbr lconic residential located less metres shorelinebr br opposite future integrated resort sentosa islandbr a part keppel bay world calss water front precinct luxury homesbr br call email info td specifically i using following hxsselect trcontainstddescriptionfollowingsiblingtrtdtext extract however break resulting item list due content separated br if i exclude text xpath td element included resulting string desirable is way xpath ensure resulting string everything shown without td tags i hope i need manually join back list br,2 you returning fx probably reassigning def funcfx aaa bbb ccc lengthlenfx length pass elif length fx fx elif length fx fx fxfxupper fxfxii rangelenfx translatedx x fx return translate here alternate function figure know python def funcfx aaa bbb ccc return djoinxupper x zipiterfx,i made function dictionary the purpose function separate input string sets if input string value multiple i want delete remainder function working perfectly i added part deleting remainders def funcfx aaa bbb ccc lengthlenfx length return fx length return fx length return fx fxfxupper fxfxii rangelenfx translatedx x fx return translate x aaabbbcc output funcx print output aaabbb function recognizing input sequence multiple deleting values want however splitting new string letter words translated dictionary anymore if delete statements function works strings multiple what i wrong,1 while i agree laurence occasions quick dirty approach gets job done without creating problems here example demonstrates regex based approach import cleanbodyre recompiler rem def replmatch tag matchgroupsplit tag p return sp matchgroup elif tag br ul li b strong em return matchgroup return u def cleanbodyhtml return cleanbodyresubrepl html,i like strip html javascript except bb ulul lili aa thanks,1 use itervalues ditervalues print aha note much slower key lookup potentially require inspecting values dictionary if need perform operation often might want consider storing values set,i want print aha i want read values keys what pythonic way,3 in previous question already demonstrated code retrieves entry given videoid run python gdatayoutubeservice import youtubeservice yt youtubeservice entry ytgetyoutubevideoentryvideoid ppvjgmmhfo entryrating gdatayoutuberating object xcd print entryrating xml version encoding utf nsrating average max min numraters relhttpschemasgooglecomgoverall xmlnsnshttpschemasgooglecomg entryratingaverage entryratingnumraters traceback recent call last file stdin line module attributeerror rating object attribute numraters direntryrating findextensions tostring addmemberstoelementtree becomechildelement convertelementattributetomember convertelementtreetomember harvestelementtree toelementtree class delattr dict doc format getattribute hash init module new reduce reduceex repr setattr sizeof str subclasshook weakref attributes children namespace tag average extensionattributes extensionelements max min numraters text entryratingnumraters,how i call gdrating xml file using python youtube gdata api i youtube videoid variable i know possible return gdrating average max min numraters rel httpschemasgooglecomgoverall i figure python,1 the nature dictionary cannot efficiently test whether value present way test whether key present you need iterate dictionary testing value although done transparently using code mark suggests if large dictionaries performance may issue may require different data structure,i want print aha i want read values keys what pythonic way,2 why scale variables one one in paste import numpy np list b scale lambda x x xmean arr nprecfromrecordslistnames id var var varstoscale var var var varstoscale arrvar scalearrvar print arr end pasted text b,i want apply transformation certain columns record array reassign values what canonical way list b arr nprecfromrecordslistnames id var var and i want apply scaling variables i let example general scaling may complex subtracting means scale lambda x x xmean this work arr var var mean typeerror cannot perform reduce flexible type so i convert unstructured array first reassign back record array do i loop unstr arr var var view float reshapelenarr arr var var scaleunstr indexerror unsupported iterator index,1 it looks like urlpatterns might getting overwritten urlpatterns apiurls adding like work it seems assigning directly urlpatterns may unexpectedly clobbering old assignment,so i started using tastypie plugin django make rest api project i following getting started guide project i got point i supposed put foreign key started giving errors the maior one i simple get reverse apidispatchdetail arguments keyword arguments pk apiname v resourcename typep found the code resourcespy class typeofplaceresourcemodelresource class meta queryset typeofplaceobjectsall resourcename typep allowedmethods get class poiresourcemodelresource typep foreignkeytypeofplaceresource typep class meta queryset pointofinterestobjectsall resourcename pois filtering code all code all and models class typeofplace modelsmodel name modelscharfieldmaxlength blanktrue code modelscharfieldmaxlength uniquetrue def unicodeself return selfname class pointofinterestgeoinformation name modelscharfieldmaxlengthblanktrue code modelscharfieldmaxlengthnulltrue uniquetrue code modelscharfieldmaxlengthnulltrue uniquetrue typep modelsforeignkeytypeofplace def unicodeself return selfname the urlspy api apiapiname v apiregistertypeofplaceresource canonicaltrue apiregisterpoiresource canonicaltrue urlpatterns apiurls so i something wrong or missing something any help would really appreciated d,1 here example based answer linked clarity import numpy np nparangereshape array areshapeashapemeanaxismean array as function def rebina shape sh shapeashapeshapeshapeashapeshape return areshapeshmeanmean,i trying reimplement python idl function httpstarpstqubacukidlrebinhtml downsizes integer factor array averaging for example anparangereshape array i would like resize taking mean relevant samples expected output would b rebina b array ie b npmeana b npmeana i believe i reshape dimensional array take mean correct slice could figure algorithm would hint,3 the way i python fairly simple depends middleman message broker basically i receive message process ack if message acked timeout broker requeues with place simpy kill restart process in case process traps sigint orderly shutdown however dies supervisor notices worker died starts new one continues processing messages queue i inspired erlang supervision tree model everything designed survive death process i even made workers send heartbeat supervisor periodically zeromq pub supervisor sub supervisor kill restart process hangs reason,multiprocessing import process aprocesstargetworker args astart i making multiple workerprocess app laugh yet worker gracefully reload whenever code updated new requests served new worker processes new code this a newly launched thread contains updated code ensure requests dropped i already made worker listens serves requests gets aa request signal kills next signal control signal i zeromq the clients connect server using zeromq the clients interact http what good way reload code can explain scheme simple stupid enough robust what i mind launch thread within main process iterates signal every worker process die launch new worker processes but approach drop i configured way requests death last old worker spawning first new worker and i college student the homework means curiositydriven pursuit,1 unfortunately possible without copying please note gdkpixmap gdkpixbuf deprecated favor cairo,i created instance gtkgdkpixmap painted something for example pixmap gtkgdkpixmapwidgetwindow pixmapdrawrectanglegc true pixmapdrawlinegc how i resize pixmap one way i see copy pixmap pixbuf using gtkgdkpixbufgetfromdrawable resize pixbuf copy pixbuf pixmap is way without copying,1 you could keep histogram dictionary mapping element type int and iterate row column diagonal increment histogramelement either check end see histogram allow copies stop reached element simple onedimensional example a a a a b a h x x h hx else hx print histogram h k h hk print appears times khk output histogram a b a appears times essentially hx store number times element x appears array case current row column diagonal the elements appear consecutively counts would reset time start considering new rowcolumndiagonal,good algorithm checking whether elements row column diagonally given square matrix say x ofcourse naive algorithm iterating every spot point matrix iterate row col diagonal i wondering better way,1 your question how i track answer show us full text error message got without knowing encoding trying use tell anything a traceback snippet code reads file reproduces error would also handy write tiny python script find line file print reprtheline python x print asciitheline python x copypaste result edit question see unambiguously line it look like random gibberish except ampshy tell us whether expect line text human language,i trying track python unicodedecodeerror following log line nov gfrxâ¢xã¬ã„bkxfã—ãã–ã xceããŒyxcâ¿dãŒjx㏠â®atxã¥fxã©pwâ¤xcxã¶xcxâªikcraxâ xã¾pã¢xhxâ­â¢ã¨â´xdzãµwiã‹xcxsã²ãŠâ¨râ¶â²xfã¤lâ¾â¢ã†nwxã·ã¯ i opened entire log file vim yanked line new file i could test one line however parsing script works ok new file throw unicodedecodeerror i understand one file would generate error one would surface identical here i tried running enca determine file encoding complained cannot determine understand language preferences file says files regular file i also deleted every line original log file still got error one file error i tried deleting set encodingutf vimrc writing file i still got error one file the logs nginx logs nginx note release notes change xxf characters escaped xxx accesslog thanks maxim dounin my python script open logfile f error comes i try call jsondumps dict how i track,1 i think couple bugstypos make code work i assume created small code sample show issue i hope fix original code problem solved well instead newingparenting parentingobj newingparent parentingobj i believe solve issue so assign parent instance relationship object key using jf sebastian suggestions could work objects already stored database new instances id assigned yet addingredient two issues typo parameter ingredient renamed ingname viceversa bigger issue addingredient return value fact assign none parent side relationship again given sample code might issues real code,i great time learning python i gotten bit stuck trying incorporate recursive function sqlalchemy essentially function creates instance class put database inside function i get user input whether instance parent class defined using selfreferential adjacency table if function called recursively this function seems work parent class needed whenever recursive element activated crashes my code like engine createengine sqliterecdbdb session sessionmakerbindengine session session base declarativebase class inglistbase tablename inglist id columninteger primarykey true ingredient columnstring nullablefalse parenting columninteger foreignkey inglistid children relationshipinglistbackrefbackref parent remotesideid def initself ingredient selfingredient ingredient def addingredientingredient global newinglist newing inglistingname create new class instance parenting rawinputto add parent ingredient type otherwise press enter parenting parentingobj addingredientparenting recursion newingparenting parentingobj newinglistappendnewing name main newinglist ingredient rawinputenter new ingredient addingredientingredient ing newinglist sessionadding sessioncommit i kept sample simple keep readable i missing important information please let know i assumed problem class instances losing scope i recursed adding global list variable seem fix i also thought fact session acts sort buffer would handle scope problems does something eager loading i saw documentation really understand the error i getting traceback recent call last file cworkspacerecipeslangprocpy line module sessioncommit file cpythonlibsitepackagessqlalchemyormsessionpy line commit selftransactioncommit file cpythonlibsitepackagessqlalchemyormsessionpy line commit selfprepareimpl file cpythonlibsitepackagessqlalchemyormsessionpy line prepareimpl selfsessionflush file cpythonlibsitepackagessqlalchemyormsessionpy line flush selfflushobjects file cpythonlibsitepackagessqlalchemyormsessionpy line flush flushcontextexecute file cpythonlibsitepackagessqlalchemyormunitofworkpy line execute recexecuteself file cpythonlibsitepackagessqlalchemyormunitofworkpy line execute uow file cpythonlibsitepackagessqlalchemyormmapperpy line saveobj executestatement params file cpythonlibsitepackagessqlalchemyenginebasepy line execute params file cpythonlibsitepackagessqlalchemyenginebasepy line executeclauseelement compiledsql distilledparams file cpythonlibsitepackagessqlalchemyenginebasepy line executecontext context file cpythonlibsitepackagessqlalchemyenginebasepy line executecontext context file cpythonlibsitepackagessqlalchemyenginedefaultpy line doexecute cursorexecutestatement parameters sqlalchemyexcinterfaceerror interfaceerror error binding parameter probably unsupported type u update inglist set parenting where inglistid assigndbinglist object xe,2 you check whether k elements matrix integers single pass suppose n size matrix largest element we n column n row diagonal foreach column row diagonal n distinct element now create histogram containing n n element representing rows columns diagonal containing n distinct element size n n histogram zerossize int now tricky part update histogram consider function pseudocode updatehistogrami j element element element element rowindex element columnindex n j element diagonalindex n element histogramrowindex histogramrowindex histogramcolumnindex histogramcolumnindex j histogramdiagonalindex histogramdiagonalindex now iterate throw histogram check whether element k,good algorithm checking whether elements row column diagonally given square matrix say x ofcourse naive algorithm iterating every spot point matrix iterate row col diagonal i wondering better way,1 you try watchdog package turn uses kqueue bsd inotify linux etc,given certainpath freebsd system i would like python use kqueue detect files created deleted anywhere path how would i,1 consider loop name func inspectgetmemberstargetcls inspectismethod def wrapperargs kwargs print start debug support ss targetclsname name when wrapper eventually called looks value name not finding locals looks finds extended scope forloop but forloop ended name refers last value loop ie testmethod so times wrapper called name evaluates testmethod the solution create extended scope name bound right value that done function closure default argument values the default argument values evaluated fixed definitiontime bound variables name def debugtargetcls name func inspectgetmemberstargetcls inspectismethod def closurenamenamefuncfunc def wrapperargs kwargs print start debug support ss targetclsname name result funcargs kwargs return result return wrapper setattrtargetcls name closure return targetcls in comments eryksun suggests even better solution def debugtargetcls def closurenamefunc def wrapperargs kwargs print start debug support ss targetclsname name result funcargs kwargs return result return wrapper name func inspectgetmemberstargetcls inspectismethod setattrtargetcls name closurenamefunc return targetcls now closure parsed each call closurenamefunc creates function scope distinct values name func bound correctly,i wrote class decorator like tried add debug support every method target class import unittest import inspect def debugtargetcls name func inspectgetmemberstargetcls inspectismethod def wrapperargs kwargs print start debug support ss targetclsname name result funcargs kwargs return result setattrtargetcls name wrapper return targetcls debug class mytestclass def testmethodself print testmethod def testmethodself print testmethod class testunittesttestcase def testnameself name func inspectgetmembersmytestclass inspectismethod print name func print testcls mytestclass testclstestmethod testclstestmethod name main import syssysargv testtestname unittestmain run code result finding files done importing test modules done testmethod unbound method mytestclasswrapper testmethod unbound method mytestclasswrapper start debug support mytestclasstestmethod testmethod start debug support mytestclasstestmethod testmethod ran test ok you find testmethod printed twice is problem is understanding right decorator python is workaround btw want add decorator every method class,2 you edit admin classes adminpy you use admininline class help example django website add book author admin page class bookinlineadmintabularinline model book class authoradminadminmodeladmin inlines bookinline adminsiteregisterauthor authoradmin read edit you able add methods useradmin model refer setting listdisplay fields listdisplay yourmethod,i django application users additional data that data collected profile model onetoonefield pointing user this fine works perfectly purposes i trouble customizing admin user in particular i would like able show profile field inside listdisplay i know without writing additional method user i would like able show information related models eg resources owned user inside user detail page again i know without writing custom user method do know solution,1 i agree first example for latter one pep readability counts the semantically important part complex slice expression slice operator divides expression two parts parsed human reader interpreter separately therefore intuition consistency pep sacrificed order highlight operator ie surrounding whitespaces example question omitting whitespaces within two sides expression increases readability spamham eggs vs spamham eggs i find quicker parse,pep mention slice operator from understanding unlike operators surrounded whitespace spam ok spam not ok does hold using complex expressions one considered better style spamhameggs spamham eggs spamham eggs something else,1 i see slicing used pep use startswith endswith instead string slicing check prefixes suffixes startswith endswith cleaner less error prone for example yes foostartswith bar no foo bar i call definitive backs understanding spam ok as far use complex situation i use i think nospacesaroundthe method looks good case spamham eggs looks like time middle bad if want stand sacrifice operator spacing add extra spaces spamham eggs wow easy read i would use i like operator spacing looks much like dictionary key value syntax i also call operator it special syntax constructing slice object could also spamslice,pep mention slice operator from understanding unlike operators surrounded whitespace spam ok spam not ok does hold using complex expressions one considered better style spamhameggs spamham eggs spamham eggs something else,2 as already mentioned pep explicitly mention slice operator format spam definitely common imho readable if pep checker anything go space flagged mehome pep echo spam warnings mehome pep echo spam devfd e whitespace assumes operator defining literal dict space expected operator spam passes reason seem right on count i stick spam nested arithmetic operations little trickier of examples nd one passes pep validation mehome pep echo spamhameggs devfd e missing whitespace around operator mehome pep echo spamham eggs ok mehome pep echo spamham eggs devfd e whitespace however i find difficult parse eye first glance for readability compliance pep i personally go spamham eggs or complication operations sfrom ham sto eggs spamsfromsto,pep mention slice operator from understanding unlike operators surrounded whitespace spam ok spam not ok does hold using complex expressions one considered better style spamhameggs spamham eggs spamham eggs something else,3 use numpyargsort it returns indices one would use sort array import numpy np import numpylinalg linalg a nprandomrandom eigenvalueseigenvectors linalgeiga idx eigenvaluesargsort eigenvalues eigenvaluesidx eigenvectors eigenvectorsidx,i using numpylinalgeig obtain list eigenvalues eigenvectors a somematrixarray numpylinalg import eig eigenvaluesandvectors solution eigenvaluesandvectorsa eigenvalues solution eigenvectors solution i would like sort eigenvalues eg lowest highest way i know associated eigenvector sorting i finding way python functions is simple way i code sort version,3 odds reference sessionid object associated session example caching sessionid given applicationoncreate method session created in case use sessionlookupsession method look session sessionid if construct sessionid first beginstring sendercompid targetcompid session interested sorry i know python i provide example,i use python bindings come quickfix i like set sequence number see how i i found following swig bindings class sessionobject def setnextsendermsgseqnumself args return quickfixsessionsetnextsendermsgseqnumself args it requires two parameters session object int sequence number how i get session object or another method setting sequence number,1 an importerror already python error looks like jython working you need however set path if xxx stands one python modules set syspath contain appropriate directory importing if xxx stands one java modules set java classpath contain appropriate directory jar if xxx stands builtin module probably supported jython yet have look list modules supported jython some newer modules available python platforms json yet available jython,stated one invoke jython source code unix platforms i installed jython put directory path windows how could i set invoke jython py code automatically thanks make example specific clear usrbinenv jython import sys syspathappendpackagejar import orgabcname importerror no module named orgabcname and i run jython barpy cmd work but running python barpy fails error,1 take look homebrew recipe vim macvim modify necessary httpsgithubcommxclhomebrew,i start vim src directory pwd vimsrc configure prefixhomeapplicationsvimcompiled enablerubyinterpyes enablepythoninterpyes withpythonconfigdirlibraryframeworkspythonframeworkversionslibpythonconfig make at end make i get following error ld warning libraryframeworkspythonframeworkpython missing required architecture x file undefined symbols long list undefined symbols long list undefined symbols ld symbols found collect ld returned exit status make vim error what causing error i found answers similar questions advise using macports homebrew macvim i want use is way around update this output listing undefined symbols httppastebincomggvref,1 use gdkpixbuf get icon data assign cluttertexture c version cluttertexturesetfromrgbdata texture gdkpixbufgetpixels pixbuf gdkpixbufgethasalpha pixbuf gdkpixbufgetwidth pixbuf gdkpixbufgetheight pixbuf gdkpixbufgetrowstride pixbuf gdkpixbufgethasalpha pixbuf cluttertexturenone error i pretty sure achieve python well,i attempting get window icon name python use pyclutterbased taskbar i gotten xid via wnck wnck seems capable giving gtkgdkpixbuf useful clutter i sure way pythonxlib pythonxcb i find any ideas,1 i used predicate make sure classes come module question def predc return inspectisclassc cmodule predmodule fetch members module name matching pred classes inspectgetmemberssysmodulesname pred i want type current module name,i already seen following question quite get i want python get list classes within current module in particular i want classes imported eg i following module mynamespace import mybaseclass somewhereelse import someotherclass class newclassmybaseclass pass class anotherclassmybaseclass pass class yetanotherclassmybaseclass pass if i use clsmembers inspectgetmemberssysmodulesname inspectisclass like accepted answer linked question suggests would return mybaseclass someotherclass addition defined module how i get newclass anotherclass yetanotherclass,3 they must strings since joini would returned typeerror int but general find type variable use type printtypei,i need know variable python stringname number i want check degree graphs however i need know iterator number inside string name inside string showing degree graphs end is something wrong code import csv sys import networkx nx def ministrolei stf csvreaderopen resultsetcsv rb delimiter quotechar eds iii stf g nxdigraphnome ministrolei gaddweightededgesfromeds gdegree isinstanceistr print this name elif isinstancei int print this number else raise valueerror return g eds ministrolei here lies examples outs min octavio gallotti min sydney sanches min joaquim barbosa please help thanks,1 i hope helps hello types type str types str true n typen type int typen int true,i need know variable python stringname number i want check degree graphs however i need know iterator number inside string name inside string showing degree graphs end is something wrong code import csv sys import networkx nx def ministrolei stf csvreaderopen resultsetcsv rb delimiter quotechar eds iii stf g nxdigraphnome ministrolei gaddweightededgesfromeds gdegree isinstanceistr print this name elif isinstancei int print this number else raise valueerror return g eds ministrolei here lies examples outs min octavio gallotti min sydney sanches min joaquim barbosa please help thanks,1 have tried upgrading osx bitbit version python i sure specific bit version might causing problems,i start vim src directory pwd vimsrc configure prefixhomeapplicationsvimcompiled enablerubyinterpyes enablepythoninterpyes withpythonconfigdirlibraryframeworkspythonframeworkversionslibpythonconfig make at end make i get following error ld warning libraryframeworkspythonframeworkpython missing required architecture x file undefined symbols long list undefined symbols long list undefined symbols ld symbols found collect ld returned exit status make vim error what causing error i found answers similar questions advise using macports homebrew macvim i want use is way around update this output listing undefined symbols httppastebincomggvref,1 check new project alembic httpreadthedocsorgdocsalembicenlatestindexhtml,i looked sqlalchemymigrate seems like lot work i able find useful examples anyone care share handle,3 you convert path polygon shown example httpphrogznetsvgconvertpathtopolygonxhtml the simpler algorithm page javascript function polygonsampledfrompathpathsamples var doc pathownerdocument var poly doccreateelementns httpwwwworgsvg polygon var points var len pathgettotallength var step steplensamples var iilenistep var p pathgetpointatlengthi pointspush px py polysetattribute points pointsjoin return poly instead sampling based certain number points may wish simply sample particular distance this assumes python binding access full svgpathelement dom interface,i trying figure point svg path using python the algorithm i use raycasting algorithm but algorithm need polygon sides i pathdata svg path path dm c … z corresponds image so way get sides path,1 if submitting page python backend check mechanize,how i fill submit form remotely httpmtanyccusthelpcomcgibinmtanyccfgphpenduseraskphp the form asks email pull menu fields subject question clicking next button takes new page page click submit can i fill form submit one click site i form site user fill email i prepopulated fields subject question user click submit button remote form filled submitted how i python javascript,1 use haproxy nginx proxy multiple tornado processes restart one one the tornado docs cover nginx support websockets using need haproxy,i recently started experiment python tornado web serverframework web development previously i used php framework lamp stack with php deploying updated codenew code easy uploading server way modphp apache interact when i add new code update code pythontornado i need restart tornado server i could see problematic number active users do i restart server anotherbetter way b if i avoid users disconnectedgetting errorsetc restarting could take seconds one possible thought use page flipping paradigm nginx pointing server launch new server instance updated code redirect nginx take original server,1 try twill httptwillidyllorgpythonapihtml i wrapper mechanize,how i fill submit form remotely httpmtanyccusthelpcomcgibinmtanyccfgphpenduseraskphp the form asks email pull menu fields subject question clicking next button takes new page page click submit can i fill form submit one click site i form site user fill email i prepopulated fields subject question user click submit button remote form filled submitted how i python javascript,1 add widgets central widget first then select central widget use layout grid layout vertically etc buttons toolbar add main layout the layouts widget box sidebar used adding child layouts main layout,i started new clear main window project there objects mainwindow centralwidget menubar statusbar i need set default layout inside window probably centralwidget but i didnt found way i get layoutwidget particular size centralwidget but i want set layout whole centralwidget,1 right click anywhere within centralwidget go lay out sub menu select layout want this applied automatically contents centralwidget in order see works place inside push buttons try changing layouts,i started new clear main window project there objects mainwindow centralwidget menubar statusbar i need set default layout inside window probably centralwidget but i didnt found way i get layoutwidget particular size centralwidget but i want set layout whole centralwidget,1 this uac if run elevated see behaviour expect but standard token uac user administrator rights even admin group for special administrator user account uac apply processes special user always given privileged token so difference see os user log special administrator account windows see behaves server box,i trying use ctypeswindllshellisuseradmin determine running process started user admins group i getting inconsistent incorrect results on windows professional install logging user administrator memebr administrators group i get ctypeswindllshellisuseranadmin but user admins group i get expected answer windows server machine logging administrator ctypeswindllshellisuseranadmin does anybody know hints i getting returned win box even though user administartors group i wondering issue caused interaction local vs domain admins groups knowledge sketchy best thanks matt,3 i would start ability change filehandle init as replace mock fake object write signature test written maybe creating method sets filehandle overwriting method test,i logger class needs write strings file so i method like def writetofileself string selffilehandlewritestring note error handling edited clearly i want test without writing file thus mocks via mock i seen explains mock open help i open filehandle init now i setup mockopen seems go scope setup thus use test case how would write test method test writetofile method using mock,1 it turns winguigetforegroundwindow returns window handle process id winprocessgetwindowthreadprocessidhwnd used get thread id process id handle import wincomclient import wingui import winprocess hwnd winguigetforegroundwindow pid winprocessgetwindowthreadprocessidhwnd shell wincomclientdispatchwscriptshell shellappactivate console shellsendkeys upenter shellappactivatepid,i tried following focus returned program focus script run import wincomclient import wingui current winguigetforegroundwindow shell wincomclientdispatchwscriptshell shellappactivate console shellsendkeys upenter shellappactivatestrcurrent,1 you omitted actual exception stack trace i guessing attributeerror local object attribute currentsession if likely skipped middleware configuration step create appengineconfigpy per instructions restart dev server resolve error,i new python well gae i trying include gaesessions application exactly i i copied gaesessions folder src folder folder includes initpy file added working code gaesessions import getcurrentsession session getcurrentsession i received following error traceback recent call last file cprogram filesgooglegoogleappenginegoogleappengineruntimewsgipy line handle result handlerselfenviron selfstartresponse file cprogram filesgooglegoogleappenginelibwebappwebapppy line call response selfinternalerrore file cprogram filesgooglegoogleappenginelibwebappwebapppy line call rv selfhandleexceptionrequest response e file cprogram filesgooglegoogleappenginelibwebappwebapppy line call rv selfrouterdispatchrequest response file cprogram filesgooglegoogleappenginelibwebappwebapppy line defaultdispatcher return routehandleradapterrequest response file cprogram filesgooglegoogleappenginelibwebappwebapppy line call return handlerdispatch file cprogram filesgooglegoogleappenginelibwebappwebapppy line dispatch return selfhandleexceptione selfappdebug file cprogram filesgooglegoogleappenginelibwebappwebapppy line dispatch return methodargs kwargs file dsrchelloworldpy line get session getcurrentsession file dsrcgaesessionsinitpy line getcurrentsession return tlscurrentsession file cpythonlibthreadinglocalpy line getattribute return objectgetattributeself name,3 i going delnan answer i find another problem specific solution i going use case thought would worth passing along instead adding additional information function call rather easy use event passed get information caller ie x range name jbuttonstrx nameactionperformed selffoo def fooself event sender eventgetsource print sendergettext,i creating couple swing jbuttons buttons loop jython on press button call function one different parameter i trouble passing parameters outside self event this works x range name jbuttonstrx nameactionperformed selffoo def fooself event print i work somehow event magically passed method this x range name jbuttonstrx nameactionperformed selffoox def fooself event number print i work print strnumber the issue i see i i add argument i longer pass event i end error telling foo takes exactly arguments given i get i extract event button,1 cgifieldstorage returns dictionary containing parameters request,so i trying use cgi module comes python python server page i want know way pull name checkbox submitted i actually need know status whether submit new page name script going run ie first page i input typecheckbox nameavd i submit form form formchangedatepspavdon all i care pull avd anyway,1 you triggering cleaning validation form made calling isvalid method note parentheses cleaned data correction requestmethod post form testformrequestpost formisvalid print form valid print formcleaneddata,i trying generate form using django documentation i continously getting error testform object attribute cleaneddata even though formisvalid true prints form valid line code following relevant portions code urlspy urlr test viewstest formspy django import forms class testformformsform name formscharfield viewspy def testrequest requestmethod post form testformrequestpost formisvalid print form valid print formcleaneddata else print form valid else form testform return rendertoresponse usertesthtml form formcontextinstancerequestcontextrequest testhtml form action methodpost csrftoken table formastable table input typesubmit valuesubmit form,3 since celery information related currently executed task saved taskrequest called â«the contextâ» so get task id context keyword arguments deprecated task def dojobpath cachesetdojobrequestid operationresults the list available fields documented httpceleryreadthedocsorgenlatestuserguidetaskshtmlhighlightrequestcontextcontext,how i get taskid value task within task here code celerydecorators import task djangocorecache import cache task def dojobpath performs operation file code perform operation cachesetcurrenttaskid operationresults the idea i create new instance task i retrieve taskid task object i use task id determine whether task completed i want keep track task path value file cleaned task completes may may exist in example would i get value currenttaskid,3 there similar reports race condition issues chrome devappserverpy the usual story chrome opens multiple concurrent connections server sends request second connection first because devappserver singlethreaded first request blocks server hangs someone gives supposedly starting chrome disablepreconnect prevents condition,running django nonrel google app engine python i getting exception trying load first time localhost localhostadmin i expect happen page though exception happened processing request traceback recent call last file usrlibpythonsocketserverpy line handlerequestnoblock selfprocessrequestrequest clientaddress file usrlibpythonsocketserverpy line processrequest selffinishrequestrequest clientaddress file usrlibpythonsocketserverpy line finishrequest selfrequesthandlerclassrequest clientaddress self file usrlocalgoogleappenginegoogleappenginetoolsdevappserverpy line init basehttpserverbasehttprequesthandlerinitself args kwargs file usrlibpythonsocketserverpy line init selffinish file usrlibpythonsocketserverpy line finish selfwfileflush file usrlibpythonsocketpy line flush selfsocksendallviewwriteoffsetwriteoffsetbuffersize error errno broken pipe strangely enough appears using google chrome when using firefox print exception least i able replicate problem firefox many tries does anyone know something problem thanks,3 simple really mock import patch def setupself mockfilehandle mock patch builtinopen mockfilehandle selfsut logger def testwriteself selfsutwritemessagetofileook selfasserttrueselfsutfilehandlewritecalled selfasserttrueselfsutfilehandleflushcalled if anyone better solution please let know,i logger class needs write strings file so i method like def writetofileself string selffilehandlewritestring note error handling edited clearly i want test without writing file thus mocks via mock i seen explains mock open help i open filehandle init now i setup mockopen seems go scope setup thus use test case how would write test method test writetofile method using mock,1 for gb file second approach clearly way go here outline need open input file open first output file read one line input file write output file maintain count many lines written current output file soon reaches close output file open next one repeat steps reached end input file close files,i trouble trying split large files say around gb the basic idea simply read lines group every say lines one file but two ways reading files the first one read whole file make list but require loading whole file memory painful large file i think i asked questions in python approaches read whole file i tried include inputfreadlines input commandsgetoutput zcat filesplitlinestrue input subprocesspopencatfile stdoutsubprocesspipebufsize well i easily group lines one file list list or advantage using list easily point specific lines the second way read line line process line reading those read lines saved memory examples include fgzipopenfile line f blablabla line fileinputfileinputfilename i sure gzipopen f not list file object and seems process line line i execute split job how i point specific lines file object thanks,1 fout openoutputtxtwb line fileinputfileinputfilename foutwriteline foutclose fout openoutputdtxtiwb foutclose,i trouble trying split large files say around gb the basic idea simply read lines group every say lines one file but two ways reading files the first one read whole file make list but require loading whole file memory painful large file i think i asked questions in python approaches read whole file i tried include inputfreadlines input commandsgetoutput zcat filesplitlinestrue input subprocesspopencatfile stdoutsubprocesspipebufsize well i easily group lines one file list list or advantage using list easily point specific lines the second way read line line process line reading those read lines saved memory examples include fgzipopenfile line f blablabla line fileinputfileinputfilename i sure gzipopen f not list file object and seems process line line i execute split job how i point specific lines file object thanks,3 chunksize fout none line enumeratefileinputfileinputfilename chunksize fout foutclose fout open outputdtxt ichunksize w foutwriteline foutclose,i trouble trying split large files say around gb the basic idea simply read lines group every say lines one file but two ways reading files the first one read whole file make list but require loading whole file memory painful large file i think i asked questions in python approaches read whole file i tried include inputfreadlines input commandsgetoutput zcat filesplitlinestrue input subprocesspopencatfile stdoutsubprocesspipebufsize well i easily group lines one file list list or advantage using list easily point specific lines the second way read line line process line reading those read lines saved memory examples include fgzipopenfile line f blablabla line fileinputfileinputfilename i sure gzipopen f not list file object and seems process line line i execute split job how i point specific lines file object thanks,1 if nothing special specific number file lines file readlines function also accepts size hint parameter behaves like if given optional parameter sizehint reads many bytes file enough complete line returns lines this often used allow efficient reading large file lines without load entire file memory only complete lines returned could write code something like assume average line chars long want k file sizehint filenumber openinputfiletxt rt f true buf freadlinessizehint buf read entire file done break outfile openoutfiledtxt filenumber wt outfilewritebuf outfileclose filenumber,i trouble trying split large files say around gb the basic idea simply read lines group every say lines one file but two ways reading files the first one read whole file make list but require loading whole file memory painful large file i think i asked questions in python approaches read whole file i tried include inputfreadlines input commandsgetoutput zcat filesplitlinestrue input subprocesspopencatfile stdoutsubprocesspipebufsize well i easily group lines one file list list or advantage using list easily point specific lines the second way read line line process line reading those read lines saved memory examples include fgzipopenfile line f blablabla line fileinputfileinputfilename i sure gzipopen f not list file object and seems process line line i execute split job how i point specific lines file object thanks,2 you translate indices back using idx w npwherea idx arrayidxtw array,i following x x numpy array called comments make sense read rest question array irrelevant position rather line i irrelevant cross irrelevant position rather i first line irrelevant position rather furthermore i list indexes refers central cross said matrix called idx array array edit i call cross marks central column row following array what i would like obtain indexes arrays located idx whose first value i struggling understanding use numpywhere right way since idx array i tried npwherea idx array see returns index sliced array i would like get array array equal thank advance help ps in comments i suggested try give broader scenario applicability although i using i suppose could used process images many d libraries source layer destination layer mask see example cairo in case mask would idx array one might imagine working r channel rgb colors,3 update see larsman answer question numpy recently added numpychar module basic string operations short answer numpy provide vectorized string operations the idiomatic way something like arr numpy array print joinitemupper item arr strings long answer numpy provide vectorized string operations good bit rambling one size fit comes data structures your question probably seems odd people coming nondomainspecific programming language makes lot sense people coming domainspecific language python gives wide variety choices data structures some data structures better tasks others first numpy array default holdall container python python builtin containers good designed often list dict want numpy ndarray homogenous data in nutshell numpy vectorized string operations ndarray specialized container focusing storing ndimensional homogenous groups items minimum amount memory possible the emphasis really minimizing memory usage i biased mostly i need useful way think vectorized mathematical operations nice side effect things stored contiguous block memory strings usually different lengths eg dog cat horse numpy takes databaselike approach requiring define length strings simple fact strings expected fixed length lot implications most useful string operations return variable length strings eg join example those eg upper etc mimic operations want eg upper roughly xviewnpuint view s i recommend as basic example a b yields ab ab length a b numpy deals things eg npuint npfloat strings much flexible length numbers upcasting downcasting rules numbers pretty simple another reason numpy focus numerical operations a particular definition python you certainly make string class string arrays second class citizens numpy they exist operations defined python already really good handling string processing the really main reason numpy try offer string operations python already really good lists fantastic flexible containers python huge set nice fast string operations list comprehensions generator expressions fairly fast suffer overhead trying guess type size returned item care they store pointer also iterating numpy arrays python slower iterating list tuple python string operations really best using normal listgenerator expressions eg print joinitemupper item arr strings example better yet use numpy arrays store strings first place it makes sense single column structured array strings python gives rich flexible data structures numpy arrays beall endall specialized case generalized case also keep mind want numpy array learn python numpy i trying cheeky working numpy arrays similar lot things matlab r idl etc it familiar paradigm anyone first instinct try apply paradigm rest language python lot numpy it multiparadigm language easy stick paradigms already used try learn think python well thinking numpy numpy provides specific paradigm python lot paradigms better fit tasks others part becoming familiar strengths weaknesses different data containers lists vs dicts vs tuples etc well different programming paradigms eg objectoriented vs functional vs procedural etc all python several different types specialized data structures this makes somewhat different domainspecific languages like r matlab types data structures focus everything one specific structure my experience r limited i may wrong impression anyway it certainly true matlab anyway at rate i trying rant took quite awhile stop writing fortran matlab took even longer stop writing matlab python this rambling answer sort concrete examples hopefully makes least little bit sense helps somewhat,are better ways apply string operations ndarray rather iterating i would like use vectorized operation i think using map example shown list comprehensions arr numpyrecfromrecordsziprange far know split names name strings print joinmaplambda x xupper arr strings afaik for instance r language string operations also vectorized string unliststrsplitas far know far know pastesprintfstouppersubstrstringcollapse afaik,3 just fyi i whipped ioloop based smtp client while i say production tested near future httpsgistgithubcom,i looking python async smtp client connect torando ioloop i found simple implmementation httptornadogistsorg blocking solution might bring performance issues does anyone encountered non blocking smtp client tornado some code snippet would also useful,2 try approach problem python side python great glue language i would suggest python run matlab c programs python numpy pylab matplotlib ipython thus combination good alternative almost existing matlab module,i trying embed python matlab i wanted embed mex file written c this worked fine small simple examples using scalars however numpy imported anyway matlab crashes i say anyway i tried number ways load numpy libraries including in python module py numpy import with pyrunsimplestring mex file pyrunsimplestring“from numpy import ” calling numpy functions pyobjectcallobject pout pyobjectcallobjectpfunc pargs originally i thought may problem embedding numpy c however numpy works fine embedded simple c files compiled command line md multithread switch visual studios c compiler next i thought i change make file matlab include md switch no luck mexoptsbat compiles md switch i also manually commented lines numpy init module find crashing matlab it seems loading file extension pyd crashes matlab the first files loaded numpy multiarraypyd the matlab documentation describes debug mex files visual studios i placed error message at point i know problem memory problem pyd’s conflict matlab interestingly i use system command matlab kick process python uses numpy error generated i paste error message matlab followed debug output visual studios processes crash matlab however i pasting whole thing list firstchance exceptions long are suggestions solving integration problem matlab error matlab encountered internal problem needs close matlab crash filecuserspmlappdatalocaltempmatlabcrashdump segmentation violation detected tue oct configuration crash decoding disabled default encoding windows matlab license matlab root cprogram filesmatlabra matlab version ra operating system microsoft windows processor id x family model stepping genuineintel virtual machine java b sun microsystems inc java hotspottm client vm mixed mode window system version build fault count abnormal termination segmentation violation register state fault eax ebx cc ecx edx aeda esp afc ebp af esi cc edi aeda eip bd efl cs b ds ss es fs b gs stack trace fault xbd cpythonlibsitepackagesnumpycoremultiarraypyd xbfead cpythonlibsitepackagesnumpycoremultiarraypyd xc cpythonlibsitepackagesnumpycoremultiarraypyd xb cpythonpythondll pyevalevalframeex xadf cpythonpythondll pyevalevalcodeex this error detected mexfile running if mexfile official mathworks function please examine source code errors please consult external interfaces guide information debugging mexfiles if problem reproducible please submit service request via httpwwwmathworkscomsupportcontactus a technical support engineer might contact information thank help output visual studios debugger firstchance exception xcc matlabexe xc access violation reading location x firstchance exception xcc matlabexe xc access violation reading location x firstchance exception xcc matlabexe xc access violation reading location x firstchance exception xd matlabexe microsoft c exception jitcgfailedexception memory location xce firstchance exception xd matlabexe microsoft c exception jitcgfailedexception memory location xce firstchance exception xbd matlabexe xc access violation writing location x throwsegvlongjmpsehfilter throwsegvlongjmpsehfilter invoking throwsegvlongjmp seh filter mnunhandledwindowsexceptionfilter matlabexe triggered breakpoint,3 well finally got but millions thanks answer joe kington highly inspired teached whole stuff script import numpy np def main generate data nplinspace nppi x npsint condition npwherex onarrayoffarray onofftimescondition print condition condition print ontimes onarray print offtimes offarray def onofftimescondition changingnpdiffcondition complete array tunring turning idx changingnonzero indices changepoints timesnpdiffidx times changes timesnprtimes the first time calculated set ontimesnpwherechangingidxtimesfalse when turning was ontime timesarray false instead offtimes offtimesnpwherechangingidxtimesfalse when turning was offtime onarraynprchangingcopy copy array values add empty array right size offarraynprchangingcopy npputonarrayidxontimes put times changepoints npputoffarrayidxofftimes return onarrayoffarray main yields condition ontimes offtimes things mention yes code gives another output i requested question sorry beeing unprecise output function gives finally need now get zeros outputs masked easy if anybody nicer way put data new array please edit how link user joe or thank,statussignal measured heatpump numpymaarray together timestamps what want lengths periods length periods not daily running time something would easy what exemplary fact minutevalues months time value and want output runningtimewas time value minutes offtimewas time value minutes exact timestamps matter much i already asked people know know python idea neither tried search internet know search so maybe someone could least give hint words could type google ps wow stackoverflow fantastic i already amazed usability passive user asking interface even better,2 at shell prompt terminal run sudo aptget install buildessential this fetch common packages need build anything eg compiler etc then run sudo aptget builddep python fetch libraries need build python then download source code python decompress directory go run configure prefixpathwhereyouwantpythoninstalled make make install get built installed if hit snags way ask back i try offer guidance,ubuntu comes python preinstalled i also downloaded python dev packages because another issue i explained extreme depth how i replaceupdate version expat library used apache graham dumpleton told distro explicitly built python way use external pyexpat implementation causing issue he also said i could build python source code resolve issue how would i ubuntu keep mind i new linux,3 insert into values where valid sql you add where clause insert statement i guessing want update checkupdate column row currently data table opposed inserting new row if case try update data set checkupdate where machinename instead,trying run mysql script via python keeps giving errors here mysql cexecuteinsert datacheckupdate valuess where machinename date machine what i wrong programmingerror you error sql syntax check manual corresponds mysql server version right syntax use near where machinename tld nvalues line,2 this known phenomenon python code dynamic interpreted java code statically typed compiled no surprises the reasons people give preferring python often smaller code base less redundancy dry cleaner code however use library written c python performance may much better compare pickle cpickle,we making knn svd implementations python others picked java our execution times different i used cprofile see i make mistakes everything quite fine actually yes i use numpy also but i would like ask simple question total range xrange slower according j range test memoryfriendly total j print total this snippet takes computer java version code takes second less computer type checking main problem code i suppose but i make lots operation like project i think big number i think i making mistakes i know python used lots scientific projects but code slow i handle problems bigger should i use jit compiler psyco edit i also say loop problem example the code simple like it may tough put practice improvementscode samples another question i implement lots data mining amp machine learning algorithms numpy scipy i use correctly,2 the memory string entirely database dependent as explained documentation sqlite you use memory open database connection database resides ram instead disk as far python language concerned memory string like,i learning python i must say i loved but new learners i problems well could guys tell whether feature python library i checking connect sqllite database i came article code sample pysqlite import dbapi sqlite connection sqliteconnect testdb memoryconnection sqliteconnect memory cursor connectioncursor when wrote memory string put two colon well i wondering whether peculiar library instead python,3 it peculiar sqlite connection string nothing python,i learning python i must say i loved but new learners i problems well could guys tell whether feature python library i checking connect sqllite database i came article code sample pysqlite import dbapi sqlite connection sqliteconnect testdb memoryconnection sqliteconnect memory cursor connectioncursor when wrote memory string put two colon well i wondering whether peculiar library instead python,1 httpnullegecomcodessearchpysqlitedbapiconnect you use memory open database connection database resides ram instead disk colon special python,i learning python i must say i loved but new learners i problems well could guys tell whether feature python library i checking connect sqllite database i came article code sample pysqlite import dbapi sqlite connection sqliteconnect testdb memoryconnection sqliteconnect memory cursor connectioncursor when wrote memory string put two colon well i wondering whether peculiar library instead python,1 because mention scientific code look numpy what probably already done rather uses lapack things like svd when hear python used scientific code people probably referring using way example as quick example if using python example would use float division my example assumes using pythonx therefore integer division if specify nparange dtypenpfloat etc import numpy np nparange j nparange print npdivideouterijsum to give idea timing i use floating point division instead integer division example import numpy np def fnum total rangenum j range num total floati j return total def fnum nparangenum dtypenpfloat j nparange num dtypenpfloat return npdivideouteri jsum def fnum less memoryhungry faster version f total j nparange num dtypenpfloat xrangenum total jsum return total if compare timings in timeit f loops best per loop in timeit f loops best per loop in timeit f loops best ms per loop,we making knn svd implementations python others picked java our execution times different i used cprofile see i make mistakes everything quite fine actually yes i use numpy also but i would like ask simple question total range xrange slower according j range test memoryfriendly total j print total this snippet takes computer java version code takes second less computer type checking main problem code i suppose but i make lots operation like project i think big number i think i making mistakes i know python used lots scientific projects but code slow i handle problems bigger should i use jit compiler psyco edit i also say loop problem example the code simple like it may tough put practice improvementscode samples another question i implement lots data mining amp machine learning algorithms numpy scipy i use correctly,3 words mama papa sister brother pairs listitertoolsproductwords repeat print pairs prints mama mama mama papa mama sister mama brother papa mama papa papa papa sister papa brother sister mama sister papa sister sister sister brother brother mama brother papa brother sister brother brother,i want create list word pairs separated tabs word list i think one option could create matrix range want words combined i need list word pairs make analyses from word list mama papa sister brother output mama papa sister brother mama sister papa sister brother mama someone knows would best way,3 first really odd way invoke instance method normally would memcacheclientaddsearchindex json or simply memcacheaddsearchindex json since add overwrite key already exists cache calling repeatedly impact behavior application whether calls increase cache size really concern memcache designed make memory available needed application based least use algorithm junk memory inert add calls certainly evicted first,im using memcache store json working but problem cache size grow i call line many times memcacheclientaddmemcacheclientsearchindexjson so i looked memcache viewer content still since im using key already cache but even though size cache continues increase,3 you find list comprehensions generator expressions significantly faster for example total sumi j j xrange xrange this executes seconds machine vs original code still order magnitude slower java line expect your original code way sped slightly initializing total rather use integer rather floatingpoint addition your divisions integer results point summing results float on machine psyco actually slows generator expressions speed original loop accelerate,we making knn svd implementations python others picked java our execution times different i used cprofile see i make mistakes everything quite fine actually yes i use numpy also but i would like ask simple question total range xrange slower according j range test memoryfriendly total j print total this snippet takes computer java version code takes second less computer type checking main problem code i suppose but i make lots operation like project i think big number i think i making mistakes i know python used lots scientific projects but code slow i handle problems bigger should i use jit compiler psyco edit i also say loop problem example the code simple like it may tough put practice improvementscode samples another question i implement lots data mining amp machine learning algorithms numpy scipy i use correctly,2 i think i making mistakes i know python used lots scientific projects they heavily using scipy numpy prominent component i heard ecosystem developed around numpy api even important vastly speeds kinds operations projects need there wrong you writing critical code c python great developing general wellplaced extension modules vital optimization right least crunching numbers python really crappy language implement tight inner loops the default time popular widelysupported implementation simple bytecode interpreter even simplest operations like integer division take hundreds cpu cycles multiple memory accesses type checks popular example several c function calls etc instead even single case integer division instruction moreover language designed many abstractions add overhead your loop allocates objects heap use xrange far use range integer minus around small integers cached also xrange version calls method iteration advance range version would iteration sequences optimized specifically it still takes whole bytecode dispatch though vastly complex compared integer division course it would interesting see jit i recommend pypy psyco latter actively developed anymore limited scope anyway might work well simple example though after tiny fraction iterations produce nighoptimal machine code loop augmented guards simple integer comparisions jumping fail maintain correctness case got string list java thing sooner trace first fewer guards least use int that much faster,we making knn svd implementations python others picked java our execution times different i used cprofile see i make mistakes everything quite fine actually yes i use numpy also but i would like ask simple question total range xrange slower according j range test memoryfriendly total j print total this snippet takes computer java version code takes second less computer type checking main problem code i suppose but i make lots operation like project i think big number i think i making mistakes i know python used lots scientific projects but code slow i handle problems bigger should i use jit compiler psyco edit i also say loop problem example the code simple like it may tough put practice improvementscode samples another question i implement lots data mining amp machine learning algorithms numpy scipy i use correctly,3 here working solution problem lines def replicatelines n width reducemax maplen lines return joinlineljustwidth n line lines line replicatelines print line edit added spacing management edit used generator expression peer pressure,i problen i try print result function several times lets say example several commands result dreawing i want duplicate according function used loop print vertical way like i want horizontal like help,2 if checking link correct use head request,i want program try open page get data time interval time expires connection close i using urllib try accomplish task urlhttpexamplecom responseurlliburlopenurltimeoutt htmlresponseread this seems work url exists however put nonexistent url takes long error stop program and i put program used web site user would need wait error message long is way stop execution urlopen command takes longer set time,1 words mama papa sister brother pairs listitertoolspermutationswords print pairs note use permutations i think may asking,i want create list word pairs separated tabs word list i think one option could create matrix range want words combined i need list word pairs make analyses from word list mama papa sister brother output mama papa sister brother mama sister papa sister brother mama someone knows would best way,2 your super call schoolhouse wrong it superschool selfbuildargs it superschoolhouse selfbuildargs,i trying wrap head around multiple inheritance python suppose i following base class class structureobject def buildself args print i building structure selfcomponents args and let say i two classes inherit class housestructure def buildself args print i building house superhouse selfbuildargs class schoolstructure def buildself typeelementary args print i building school superschool selfbuildargs finally create class uses multiple inheritance class schoolhouseschool house def buildself args print i building schoolhouse superschool selfbuildargs then i create schoolhouse object run build sh schoolhouse shbuildroof walls i building schoolhouse i building house i building structure so i wondering happened school class is way get python run somehow i wondering specifically fair number django packages provide custom managers models but appear way combine without writing one managers inheriting one it nice import use somehow looks like done also i guess help pointed good primer multiple inheritance python i done work mixins really enjoy using i guess i wonder elegant way combine functionality two different classes inherit base class yup silly it typo along i feel dumb i promise i always put right class i super real life i cutting pasting try i messed,3 i sure experiencing long delays when i try make request nonexistant domain i get urlliburlerror urlopen error errno getaddrinfo failed raised seconds what exact code running domain fetching try using requests timeout parameter,i want program try open page get data time interval time expires connection close i using urllib try accomplish task urlhttpexamplecom responseurlliburlopenurltimeoutt htmlresponseread this seems work url exists however put nonexistent url takes long error stop program and i put program used web site user would need wait error message long is way stop execution urlopen command takes longer set time,1 sending push notifications client browser using django easy unfortunately the simplest implementation client continuously poll server updates increases amount work server lot here better explanation different options django push http response users if using django use websockets notifications however django built using websockets here good explanation suggestions go using websockets making moves w websockets python django twisted,i celery task registered taskspy file when someone post runpk i run task given parameters this task also executes tasks normal python functions i like update page httpresponse returned runpk whenever subtask finishes work here task celerydecorators import task task def runproject branchnone branch none branch projectbranch print creating virtualenv createvirtualenvproject branch print virtualenv created here i want send signal something update page runner runnerproject branch print using formatrunner try result output runnerrun except exception e print error formate return false print finished run runprojectproject branchbranch outputoutput resultasdict runsave return true,1 i would suggest taking look setting simple site google app engine it free use python site than would matter creating simple restful service could send post pickled data store database than create simple web front end onto database,i program i wrote python collects data i want able store data internet somewhere allow another user access another computer somewhere else anywhere world internet connection my original idea use email client gmail store data sending pickled strings address this would allow anyone access address simply read newest email get data it worked perfectly program requires new email sent every seconds so method fell limit gmail emails among reasons i unable completely delete old emails now i want try different idea i know much network programming python i want setup webpage essentially nothing the master program program actually collecting data send pickled string webpage then remote programs able read string i also need master program delete old strings updates webpage it would preferred able store multiple string chance master updating remote reading i know feasible task python ideas welcome also ideas different way i ears well eyes case,1 you could try using javalangsecuritymanager see also question using security manager set different security settings per thread you set security manager security policy like jython djavasecuritymanagersecuritymanager djavasecuritypolicypolicyfile securitymanager security manager use policyfile contains policy specification described example if use policy file source security policy example grant permission javasecurityallpermission jython need permissions start including following grant permission javaiofilepermission userhome read write permission javalangruntimepermission createclassloader permission javalangruntimepermission getprotectiondomain assumes cachedir current user home directory this something close need allowing read write access files current user home disallowing access parts filesystem here outcome first open refers file current user home directory since current working directory fopen testtxt r fopen tmptesttxt r traceback innermost last file console line javasecurityaccesscontrolexception access denied javaiofilepermission tmptesttxt read javasecurityaccesscontrolcontextcheckpermissionaccesscontrolcontextjava javasecurityaccesscontrollercheckpermissionaccesscontrollerjava javalangsecuritymanagercheckpermissionsecuritymanagerjava javalangsecuritymanagercheckreadsecuritymanagerjava javaiofileexistsfilejava orgpythoncorepyfilesetupunknown source orgpythoncorepyfilefileinitunknown source orgpythoncorepyfilenewimplunknown source orgpythoncorepytypeinvokenewunknown source orgpythoncorepytypetypecallunknown source orgpythoncorepytypecallunknown source orgpythoncorepyobjectcallunknown source orgpythonpycodepyxfconsole orgpythonpycodepyxcallfunctionconsole orgpythoncorepytablecodecallunknown source orgpythoncorepycodecallunknown source orgpythoncorepyruncodeunknown source orgpythoncorepyexecunknown source orgpythonutilpythoninterpreterexecunknown source orgpythonutilinteractiveinterpreterruncodeunknown source orgpythonutilinteractiveinterpreterrunsourceunknown source orgpythonutilinteractiveinterpreterrunsourceunknown source orgpythonutilinteractiveconsolepushunknown source orgpythonutilinteractiveconsoleinteractunknown source orgpythonutiljythonmainunknown source javasecurityaccesscontrolexception javasecurityaccesscontrolexception access denied javaiofilepermission tmptesttxt read,i programming java server handle python code given user using jython obviously i execute without risk cracker accessing files system commands heshe i searching way restrict file permissions specific threads hours closest i gotten restricting file permissions entire application is class implemented something like method,2 another option addition casey already provided set remote mysql database somewhere user access levels allowing remote connections your python program could simply access database insert data trying store centrally eg mysqldb package pyodbc package your users could either read data client supports mysql could write simple frontend python php displays data database,i program i wrote python collects data i want able store data internet somewhere allow another user access another computer somewhere else anywhere world internet connection my original idea use email client gmail store data sending pickled strings address this would allow anyone access address simply read newest email get data it worked perfectly program requires new email sent every seconds so method fell limit gmail emails among reasons i unable completely delete old emails now i want try different idea i know much network programming python i want setup webpage essentially nothing the master program program actually collecting data send pickled string webpage then remote programs able read string i also need master program delete old strings updates webpage it would preferred able store multiple string chance master updating remote reading i know feasible task python ideas welcome also ideas different way i ears well eyes case,1 xizor use link instead button redirect edition form becasue button probably sending post view ps please forgive english edit answer think right make useful,i modelform i created view template add instance database i trying extend editable user clicks button formtemplate page appears i get this field required message fields empty instead prepopulated instance i passed i edit values something different originally database correct instance updated so passing primary key none values showing if anyone tell i wrong i would appreciate oh i using post django edit form based add form basis please send here files modelform class creditcardformformsmodelform class meta model creditcard fields nameoncard cardnumber contactnumberoncard view def editrequest idnone templatename articleedittemplatehtml id print edit mode card getobjectorcreditcard pkid cardcardowner requestuser raise httpresponseforbidden else print create mode card creditcardcardownerrequestuser requestpost print requestpost form creditcardformrequestpost instancecard formisvalid print isvalid formsave if save successful redirect another page redirecturl reversearticlesavesuccess return httpresponseredirect cards else print else form creditcardforminstancecard return rendertoresponse createcredithtml form form contextinstancerequestcontextrequest template include basehtml form action methodpost csrftoken fieldset legendrequiredlegend div classfieldwrapper formnameoncarderrors label foridtopicname appears cardlabel formnameoncard div div classfieldwrapper formcardnumbererrors label foridtopiclast digits card numberlabel formcardnumber div fieldset fieldset legendoptionallegend this credit card only div classfieldwrapper formcontactnumberoncarderrors label foridtopicinstitution contact number label formcontactnumberoncard div fieldset pinput typesubmit valuesavep form urls urlr newcredit viewsedit crdsnewcredit urlr editcreditpidd viewsedit crdseditcredit,2 one way accomplish matplotlib suggested tags to i would use numpy create nxn array represent imagegradient create figure square shape size inches correlated radius circle imagecircleradius need keep mind figure dotsperinch figdpi create axes margins frame ticks figaddaxesframeonfalse xticks yticks use imshow plot array image create circle center radius units dpi use setclippath method clip axesimage created imshow call this approach inspired matplotlib example here attempt prescribe import numpy np import matplotlibpyplot plt import matplotlibpath path import matplotlibpatches patches pi nppi sqrt npsqrt exp npexp def makenodeimagemeasuredvalue stddev coverageimageid dpi todpi minsize dpi maxsize dpi maxamplitude make radiusstddev values grid units meancircleradius intsqrtmeasuredvaluepitodpi imagecircleradius intsqrtmeasuredvalue stddevpitodpi imagecircleradius minsize raise exceptionimagecircleradius small imagecircleradius maxsize raise exceptionimagecircleradius large gridstddev stddevtodpi gradientamplitude stddevsqrtpimaxamplitude gradientfade npzerosimagecircleradius imagecircleradius ix rangeimagecircleradius iy rangeimagecircleradius r sqrtiximagecircleradius iyimagecircleradius gradientfadeixiy exp rmeancircleradius gridstddev imagegradient gradientamplitudegradientfade fig pltfigurefigsizeimagecircleradiusdpi imagecircleradiusdpidpidpi ax figaddaxesframeontrue xticks yticks generateimagefromgradient im aximshowimagegradientvminvmax patch patchescircleimagecircleradiusimagecircleradius radiusimagecircleradiusfc white scaleandclipimagetoimagecircleradius imsetclippathpatch name circimagedpng imageid figsavefigname return name makenodeimagepi this results the circle seems clipped edges the almost certainly vectorized approach build gradientfade though hand i know this feels kludgy i really hope someone provides elegant answer obviously code starting point someone definitely improve upon,i producing simple pythonbased program produces graphviz graphs output i would like use custom nodes depict data program using custom nodes simple enough image i trouble figuring convenient method producing images i want specifically i would like nodes circles whose area represents measured value gradient represents uncertainty value it seems reasonable use contour map produced math program eg sagemath tend make square images scaled alternatively gradient functions image manipulation programs seem difficult relate rigorous gaussian function ideally i would like write function along lines pseudocode def makenodeimagemeasuredvalue stddev meancircleradius sqrtmeasuredvaluepi imagecircleradius sqrtmeasuredvalue stddevpi gradientamplitude stddevsqrtpi gradientfade ermeancircleradiusstddev imagegradient gradientamplitudegradientfade generateimagefromgradient scaleandclipimagetoimagecircleradius return image the two starred bits i need help i appreciate suggestions thanks,1 this might dangerous reason done one line project modelspy file usermetaorderingusername,i application makes use django userprofile extend builtin django user model looks bit like class userprofilemodelsmodel user modelsforeignkeyuser uniquetrue local stuff imageurls modelscharfieldmaxlength blanktrue imageurlm modelscharfieldmaxlength blanktrue admin class admin pass i added new class model class teammodelsmodel name modelscharfieldmaxlength manager modelsforeignkeyuser relatedname manager members modelsmanytomanyfielduser blanktrue and registered admin class teamadminadminmodeladmin listdisplay name manager adminsiteregisterteam teamadmin alas admin inteface i go select manager dropdown box set team members via multiselect field ordered user numeric id for life i figure get sorted i similar class class meta ordering name that works great but i user class i try trick useradmin class meta ordering username i get djangocoremanagementbasecommanderror one models validate eventsuserprofile ordering refers username field exist userusername work either i could specify like imageurls i wanted i tell admin sort lists users username thanks,2 the superior solution building python pythonbrew automates process also allows install several different versions also easily select in pyenv pyrun viable solutions,ubuntu comes python preinstalled i also downloaded python dev packages because another issue i explained extreme depth how i replaceupdate version expat library used apache graham dumpleton told distro explicitly built python way use external pyexpat implementation causing issue he also said i could build python source code resolve issue how would i ubuntu keep mind i new linux,1 it appears best method use nginx multiple tornado instances i alluded original question cole mentions nginx reload configuration file fly so process looks like update pythontornado web application code start new instance application different port update configuration file nginx point new instance testing syntax configuration file first reload nginx configuration file kill hup command stop old instance pythontornado web server a couple useful resources nginx regarding hotswapping configuration file httpscalomelorgnginxhtml explaining directives nginxconf section httpwikinginxorgcommandline loading new configuration using signals section,i recently started experiment python tornado web serverframework web development previously i used php framework lamp stack with php deploying updated codenew code easy uploading server way modphp apache interact when i add new code update code pythontornado i need restart tornado server i could see problematic number active users do i restart server anotherbetter way b if i avoid users disconnectedgetting errorsetc restarting could take seconds one possible thought use page flipping paradigm nginx pointing server launch new server instance updated code redirect nginx take original server,3 there variety approaches ipythonparallel includes two implementations zeromq one simple purezmq another elaborate controller implemented python we split controller two actors hub outoftheway process sees traffic keeps track state cluster pushing results database etc notifying clients engine connectdisconnect etc scheduler core simple routerdealer device forwards requests clients engines replies back looking taskfarming part topology scheduler mq queue device router dealer socket bind clients dealer sockets connected scheduler router engines router sockets connected scheduler dealer which makes use two properties dealers lru loadbalance requests across peers routers use identity prefixes send replies back peer made particular request a toy loadbalanced task farm pyzmq routes replies back requesting client httpsgistgithubcom an alternative results go somewhere back requesting client ventilatorsink pattern mq guide,i using zeromq solve problem involves several hundred potentially thousands clients request tasks carried each client would request specific task carried results completed whould returned back client issued request these actors i identified far pattern i come client actor requests unit work job carried controller actor loadbalances jobs accross available engines engine actor receives job request controller publishes result back client i still yet worked engine gets mesage back client i guessing one way implemented using zeromq would client push job messages one socket controller subscribe completed results published engine another socket controller pull job messages client one socket publish job messages engines another socket clearly forwarding device engine subscribe job messages one socket publish result another socket it would helpful someone provide skeletonsnippet show outline pattern may implemented using zeromq framework the code snippet c c php python c edit after reading task farms suggested akappa i think problem indeed modelled task farm i modified original actors accordingly changed title it would still useful someone familiar zeromq sketch skeleton would show i use core components build framework,3 it default behaviour comparing lists x xsortreverse true printx,i need sort list lists entry outer list list three integers like the trick i need sort entry tie sort entry also tie sort entry list i keep overthinking loops sort statements i able get way check entries order without rearranging lists values instead keeping hierarchy any suggestions,3 i see article linked tuples one types python maintains free lists they could well according article specific culprits int float dict list although article things could changed since in python later free lists everything int float cleared gccollect i guess help gae i thought i mention,according article i read looks like immutable type may become immortal httpeffbotorgpyfaqwhydoesntpythonreleasethememorywhenideletealargeobjecthtm i currently working solve memory usage problem web service running google app engine does use much tuple could potential reason cause problem thanks reply i running code google app engine backend instance memory usage upper bounds mb it said i use memory allowed stopped instance as comments mentioned it could memory usage remain large instead memory leaks,1 the immutable type become immortal the memory occupied still owned python available use objects circular dependencies possibility memory leak class parentobject def initself selfoffspring childself def delself matter goes gc able auto collect freed parents childs class childobject def initself parent selfparent parent johndoe parent at point child link parent parent link child python may trouble releasing,according article i read looks like immutable type may become immortal httpeffbotorgpyfaqwhydoesntpythonreleasethememorywhenideletealargeobjecthtm i currently working solve memory usage problem web service running google app engine does use much tuple could potential reason cause problem thanks reply i running code google app engine backend instance memory usage upper bounds mb it said i use memory allowed stopped instance as comments mentioned it could memory usage remain large instead memory leaks,1 this article specify immutable types specifies another possible cause excessive memory usage python uses socalled “free lists” certain object types including integers floats i know information get gae process try experiment system first start python interpreter find process then run command manytuples x range replace xrange x then take look memory usage you created list million tuples now type del manytuples on system python win memory usage shot k dropped amount i del ed variable if get information processes cpu memory usage try maybe several times row give spikes higher memory usage,according article i read looks like immutable type may become immortal httpeffbotorgpyfaqwhydoesntpythonreleasethememorywhenideletealargeobjecthtm i currently working solve memory usage problem web service running google app engine does use much tuple could potential reason cause problem thanks reply i running code google app engine backend instance memory usage upper bounds mb it said i use memory allowed stopped instance as comments mentioned it could memory usage remain large instead memory leaks,3 linker error fix yum install pythondevel,i using python pygments version rhel always get error message i try create new project gitlabhq gem list reveals pygmentsrb rubypython among others after running rails e production i see following error stdout this error happens first completed internal server error ms actionviewtemplateerror could open library libso libso cannot open shared object file no file directory bashlexer pygmentslexerbash div class div classgitempty hgit global setuph appviewsprojectsemptyhtmlerbin appviewsprojectsemptyhtmlerb appcontrollersprojectscontrollerrbin show i see actionviewtemplateerror undefined method highlight nilnilclass git config global useremail currentuseremail eos raw bashlexerhighlightsetupstr br br hnext stepsh appviewsprojectsemptyhtmlerbin appviewsprojectsemptyhtmlerb appcontrollersprojectscontrollerrbin show,1 use strjoin waypoints joinformatplatitude plongitude p points,i set points latitude longitude values i trying create string following format order work gmaps api latitudexlongitudexlatitudeylongitudey the final string built using unknown number lat long pairs my previous experience php whilst i managed get something working however seems bit clumsy i wondering pythonic way achieve result here i far waypoints point points waypoints waypointsss pointlatitude pointlongitude waypoints waypoints any advice appreciated thanks,3 have considered python audio tools it ability load mp play using player class the player class initializer accepts audiooutput object lets specify number playback channels the project seems well supported last git commit october th two weeks prior posting it also around appear flybynight library,im coding music player python using pyqt i wanted feature mono playback mp files i accomplished using pygame mixer specific parameter channels i set get mono playback however pygame mp support limited i searching library able handle mp files and mono playback currently i using pyaudiere playback site example processing song playing maybe i could turn song mono i really idea accomplish i like help code feature using pyaudiere library handle mp files edit i would also accept solution c i always build python wrapper using boostpython,1 the source xmlrpclib contains comment might find applicable outside original context note call remote object nonstandard name use result getattrserver strangepythonnameargs it general python idiom,how using python i dynamically generate call xmlrpc server using xmlrpc lib something like def callmethodmethodname server serverselfurl transportproxiedtransport servermethodnameparams the resolution takes methodname instead example methodnamegettime servergettimeparams,1 setupclass new unittest framework if want use older version need use nose test runner instead unittest,i trying get started unittest i problem getting setupclass work here test code import unittest class testrepgenunittesttestcase contains methods training data testing testvar none classmethod def setupclasscls clstestvar def testmethodself ensure data selected selfassertisnotnoneselftestvarselftestvar none run tests name main unittestmain the assert error message displayed indicating selftestvar none changed setupclass is something wrong code i get result i run code within ide wing directly command line for record i using python windows,3 there database must purchased called pdnickname i found via question database common name aliases nicknames people searched google nickname database second result in addition transformations pointed hunter simple you implement transformations minutes less the one pointed william bill still quite simple although need list names nicknames hence link database from sample text name variation gender abigail abbey f abigail abbie f abigail abby f abigail gail f abigail abaegayle f abigail abagael f may bit overkill williams like called bill p edit there also alternative google code csv names common nicknamesdiminuntives,i looking apidictionary resource help return variants names i give eg if pass william defoe return wdefoe billd williamd etc i found adequate resource online my implementation either python java,1 look tornadoescapeurlescapevalue tornadoescapeurlunescapevalue encoding utf something like coding utf dont know show import tornadoioloop import tornadoweb class abdoutornadowebrequesthandler def getself selfwritehi miaw tornadowebapplication tornadoescapeurlescapeu ã©ã©ã© abdou name main miawlisten tornadoioloopioloop you probably also want able get urls user inputs i think like class pagetornadowebrequesthandler def getselftitle title tornadoescapeurlunescapetitle encoding utf selfwritetitle miaw tornadowebapplication tornadoescapeurlescapeu ã©ã©ã© page get ã©ã©ã©pagename pagename unicode name main miawlisten tornadoioloopioloop,tornado accept unicode adress coding utf dont know show import tornadoioloop import tornadoweb class abdoutornadowebrequesthandler def getself selfwritehi miaw tornadowebapplication u ã©ã©ã© abdou name main miawlisten tornadoioloopioloop flask worked flask import flask miaw flaskname miawrouteu ã©ã©ã© def abdou return hi name main miawrun nb problem using escape like hello world flask works nb thank wisty edit appears professional code p,1 everything tried far creates shallow copy outer list to create deep copy use either copiedlist x x mylist using list comprehension copiedlist copydeepcopymylist using copydeepcopy function,i need able duplicate list lists python example right i function returns list always lists within list example mylist i need create two copies list mylist mylist separately mutable example i edit mylist mylist edited i tried everything simple mylist mylist mylist mylist complicated mylist ch mylist mylistappendch mylist ch mylist mylistappendch nothing works if i change value one list mylist lists become any idea,3 use copydeepcopy mylist copydeepcopymylist see working online ideone,i need able duplicate list lists python example right i function returns list always lists within list example mylist i need create two copies list mylist mylist separately mutable example i edit mylist mylist edited i tried everything simple mylist mylist mylist mylist complicated mylist ch mylist mylistappendch mylist ch mylist mylistappendch nothing works if i change value one list mylist lists become any idea,2 the mysqldb developer recommends building application specific api db access stuff worry mysql query strings application code it make code bit extendable link as cursors understanding best thing create cursor per operationtransaction so check value update value read value type transaction could use cursor next one would create new one this pointing direction building internal api db access instead generic executesql method also remember close cursors commit changes connection queries done your getdatabaseresult function need connect every separate query though you share connection queries long act responsible cursors,i writing python cgi script query mysql database i using mysqldb module since database queryed repeatedly i wrote function def getdatabaseresultsqlqueryconnectioninfohere connect database vdatabase mysqldbconnectconnectioninfohere create cursor execute sql statement get result tuple cursor vdatabasecursor try cursorexecutesqlquery except cursorclose return none result cursorfetchall cursorclose return result my question is best practice of i reuse cursor within functions for example which better def callsanewcursorandconnectioneachtime result getdatabaseresultsomequery result getdatabaseresultsomequery result getdatabaseresultsomequery result getdatabaseresultsomequery away getdatabaseeresult function together something like def reusesthesamecursor vdatabase mysqldbconnectconnectioninfohere cursor vdatabasecursor cursorexecutesomequery result cursorfetchall cursorexecutesomequery result cursorfetchall cursorexecutesomequery result cursorfetchall cursorexecutesomequery result cursorfetchall,3 if find another ideal solution one method i ended using ocr preprocessing past convert source images ppm use unpaper ubuntu you attempt deskew image based whichever sides specify clearlydefined edges option bypass filters would normally applied black white text you probably want images example images skewed degrees using bottom right edges detect rotation unpaper n dn bottomright dr inputppm outputppm unpaper written c source help,i process lot scanned ids i need extract photos processing here fictional example the problem scans perfectly aligned rotated degrees so i need find position rotate cut photo this turned lot harder i originally thought i checked opencv thing i found rectangle detection give good results rectangle always matches good enough samples also image matching algorithm works notrotated image since brute force comparison so i though using artoolkit augmented reality lib i know able precisely locate given marker image but seems markers simple i use constant part document purpose please correct i wrong also i found superhard compile ubuntu ocr tried one yet i start research i thankful suggestions look i look cpreferablec solution python option,1 import datetime os def mtimefilename return datetimedatetimefromtimestamposstatfilenamestmtime timediff mtimefilepatha mtimefilepathb … format resulting datetimetimedelta object desired way,is handy functions retrieve timestamp given files even compare my ideal usage would like timediff datefilepatha datefilepathb timediff would formatted string days hrs mins i know builtin datetime module python i found anything similar usage and i know i achieve similar effect issuing osstatfilepath get timestamp transform format i want just wondering handy function,3 you use timectime ospathgetctime getmtime functions if prefer format time string use timestrftime formatting timectimeospathgetctime filea ospathgetctime fileb,is handy functions retrieve timestamp given files even compare my ideal usage would like timediff datefilepatha datefilepathb timediff would formatted string days hrs mins i know builtin datetime module python i found anything similar usage and i know i achieve similar effect issuing osstatfilepath get timestamp transform format i want just wondering handy function,2 here pseudocode php script start transaction insert into table anything want sleep update table set field foo commit script start transaction update table set field foo sleep insert into table anything want commit execute script immediately execute script another terminal you get deadlock database table already data in words starts deadlocking second time try note mysql honor sleep command use python equivalent application,i want make python library working mysqldb able detect deadlocks try i believe i coded good solution i want test any ideas simplest queries i could run using mysqldb create deadlock condition would system info mysql client windows xp python mysqldb p,1 gstreamer python bindings here simple music player import gobject import gst pipeline gstparselaunch filesrc locationstereomp mad audioconvert audioxrawintchannels autoaudiosink pipelinesetstategststateplaying gobjectthreadsinit gobjectmainlooprun i really suggest look gstreamer become defacto multimedia solution open source platforms supports wide variety audio files sample apps using rhythmbox banshee totem etc,im coding music player python using pyqt i wanted feature mono playback mp files i accomplished using pygame mixer specific parameter channels i set get mono playback however pygame mp support limited i searching library able handle mp files and mono playback currently i using pyaudiere playback site example processing song playing maybe i could turn song mono i really idea accomplish i like help code feature using pyaudiere library handle mp files edit i would also accept solution c i always build python wrapper using boostpython,1 use one libraries python application talk sshd daemon server httpwikipythonorgmoinsecureshell you want look something help set sshd secure manner like httpwwwlinuxjournalcomarticle you also need ensure update sshd daemon regularly make use keys strong rotating passwords all standard telnet application due lack transport level encryption really using telnet anything,i write python telnet client communicate server telnet however many people tell secure how i convert ssh should i need totally rewrite program,1 adding alternative pan answer need use many different proxies time in case need create opener like http proxy there code available github httpsgistgithubcom opener urllibbuildopenersocksipyhandlersocksproxytypesocks localhost print openeropen httpwwwwhatismyipcomautomationnasp read,how i use socks proxy urllib download web page,3 just create tcp tunnel via ssh relay data need reinvent wheel you find examples ssh docs tcp tunneling man ssh instance but really want rewrite check paramiko project,i write python telnet client communicate server telnet however many people tell secure how i convert ssh should i need totally rewrite program,1 indeed deprecated more importantly gdkpixmap serverside resource contents pixmap live x server memory when getfromdrawable asking contents transferred application expensive instead create cairo image suface drawing this clientside resource get performance penalty image surfaces scaled drawing another surface suitable transformation,i created instance gtkgdkpixmap painted something for example pixmap gtkgdkpixmapwidgetwindow pixmapdrawrectanglegc true pixmapdrawlinegc how i resize pixmap one way i see copy pixmap pixbuf using gtkgdkpixbufgetfromdrawable resize pixbuf copy pixbuf pixmap is way without copying,1 bnc e f g h j knl n p q r resplitr ss b c e f g h j k l n p q r resplitr ss maxsplit b c e f g h j k l n p q r resplitr ss flagsredotall b c e f g h j k l n p q r the problem passing redotall positionally sets maxsplit argument flags argument redotall happens constant,i mac running lion python i noticing something strange module if i run following line print resplitr ss bnc e f g h j knl n p q r i get result b c e f g h j k l n p q r but i run redotall flag like print resplitr ss bnc e f g h j knl n p q r redotall then i get result b c e f g h j k l n p q r note q r counted one match instead two why happening i see redotall flag would make difference i using dots pattern am i something wrong sort bug,3 nice easy solution lol it turns page args useful cause fact creating problem overwriting myargs none one pages keyword variables accessed directly files without using page args,goal to access myargs base child templates currently i access one call childrendermyargs b base excerpt page argsmyargsnone kwargs myargs myargs endif selfbodymyargsmyargs child excerpt version page argsmyargsnone kwargs inherit filebasehtml myargs b b myargs b endif child excerpt version page argsmyargsnone kwargs inherit filebasehtml def namebody myargs b b myargs b endif def using child version child throws error myargs undefined base works using child version base throws error myargs undefined child works these exact examples essence dilemma if someone explain pass variables inheritance chain would lovely unfortunately documentation mako seems skip section,2 that particular error commonly caused trying decode using utf string actually encoded latin see unicodedecodeerror invalid continuation byte info i suspect despite header server returning utf encoded content a solution might worth pursuing use chardet guess encoding used despite chardet awesomeness consider last resort however,okay i coding utf python file snippet opener urllibbuildopener openeraddheaders useragent mozilla openeraddheaders acceptcharset utf f openeropenurl doc freaddecode utf the server response via finfo contenttype texthtml charsetutf get error unicodedecodeerror utf codec decode byte invalid continuation byte what wrong,1 this variation paul mcguire docstringinheritor metaclass it inherits parent member docstring child member docstring empty it inherits parent class docstring child class docstring empty it inherit docstring class base classes mros like regular attribute inheritance unlike class decorator metaclass inherited need set metaclass toplevel base class docstring inheritance occur throughout oop hierarchy import unittest import sys class docstringinheritortype a variation httpgroupsgooglecomgroupcomplangpythonmsgfbfcbdc paul mcguire def newmeta name bases clsdict doc clsdict clsdict doc mrocls mrocls base bases mrocls basemro docmroclsdoc doc clsdict doc doc break attr attribute clsdictitems attributedoc mrocls mrocls base bases mrocls basemro hasattrmrocls attr docgetattrgetattrmroclsattr doc doc isinstanceattribute property clsdictattr propertyattributefget attributefset attributefdel doc else attributedoc doc break return typenewmeta name bases clsdict class testunittesttestcase def testnullself class fooobject def frobnicateself pass class barfoo metaclassdocstringinheritor pass selfassertequalbardoc objectdoc selfassertequalbardoc objectdoc selfassertequalbarfrobnicatedoc none def testinheritfromparentself class fooobject foo def frobnicateself frobnicate gonk class barfoo metaclassdocstringinheritor pass selfassertequalfoodoc foo selfassertequalfoodoc foo selfassertequalbardoc foo selfassertequalbardoc foo selfassertequalbarfrobnicatedoc frobnicate gonk def testinheritfrommroself class fooobject foo def frobnicateself frobnicate gonk class barfoo pass class bazbar metaclassdocstringinheritor pass selfassertequalbazdoc foo selfassertequalbazdoc foo selfassertequalbazfrobnicatedoc frobnicate gonk def testinheritmetaclassself class fooobject foo def frobnicateself frobnicate gonk class barfoo metaclassdocstringinheritor pass class bazbar pass selfassertequalbazdoc foo selfassertequalbazdoc foo selfassertequalbazfrobnicatedoc frobnicate gonk def testpropertyself class fooobject property def frobnicateself frobnicate gonk class barfoo metaclassdocstringinheritor property def frobnicateself pass selfassertequalbarfrobnicatedoc frobnicate gonk name main sysargvinsert verbose unittestmainargvsysargv,i oo hierarchy docstrings take much maintenance code eg class swallowobject def airspeedself returns airspeed unladen raise notimplementederror class africanswallowswallow def airspeedself whatever now problem africanswallowairspeed inherit superclass method docstring i know i keep docstring using template method pattern ie class swallowobject def airspeedself returns airspeed unladen return selfaskarthur implementing askarthur subclass however i wondering whether another way docstrings inherited perhaps decorator i discovered yet,3 try decoding data using latin see looks like what seeing indicates utf decode error see unicodedecodeerror invalid continuation byte it would helpful posted result listfread see data fyi putting coding utf unrelated issue that encoding refers encoding python script data handling,okay i coding utf python file snippet opener urllibbuildopener openeraddheaders useragent mozilla openeraddheaders acceptcharset utf f openeropenurl doc freaddecode utf the server response via finfo contenttype texthtml charsetutf get error unicodedecodeerror utf codec decode byte invalid continuation byte what wrong,2 gdrating deprecated httpcodegooglecomapisyoutubereferencehtmlyoutubedataapitaggdrating anyway check raiting exists entryrating print entryratingaverage print entryratingnumraters else print entry rating,this works perfectly finding average rating number raters youtube video usrbinpython import sys gdatayoutubeservice import youtubeservice yt youtubeservice entry ytgetyoutubevideoentryvideoidsysargv direntryrating findextensions tostring addmemberstoelementtree becomechildelement convertelementattributetomember convertelementtreetomember harvestelementtree toelementtree class delattr dict doc format getattribute hash init module new reduce reduceex repr setattr sizeof str subclasshook weakref attributes children namespace tag average extensionattributes extensionelements max min numraters text print entryratingaverage print entryratingnumraters video rating throws error attributeerror nonetype object attribute average any suggestions thanks,1 no possible when python process launched gets copy environment copied parent shell the python process modify private copy changes propagated back parent process if want something like best get print shell commands needed desired environment variable changes eg print export pythonpathpythonpath run script using eval python myscriptpy,for following python script import os ossystem pythonpathuser ossystem export pythonpath is anyway export pythonpath variable shell executing script,2 class repeatinggroupedsequence needs overwrite extractpadding method def extractpaddingself return by default sub packet treats everything belonging layer ie def extractpaddingself return none and used grouping purposes can someone elaborate difference padding layer separation,i trying specify new packet format using scapy in packet list items items consist grouped fields by grouped fields i mean subsequence fields different types the way making grouped fields i know scapy using packet class using fieldlenfield packetlistfield reference length sequence type list members is way go something looks like scapypacket import packet scapyfields import class repeatinggroupedsequencepacket name simple group two fields fieldsdesc intfield field intfield field class toplayerpacket name storage repeating sequence fieldsdesc fieldlenfieldlength none countof repseq packetlistfield repseq none repeatinggroupedsequence countfrom lambda pkt pktlength now problem i assembling packetlistfield craft toplayer packet p toplayer add two repeated sequences prepseq repeatinggroupedsequence repeatinggroupedsequence sequences observed pshow underlying structure repeated sequence raw stage pshow length print prepseq length lenprepseq cloned packet one repeated sequence rest raw clone toplayerstrp cloneshow length print clonerepseq length lenclonerepseq the problem approach structure grouping preserved packet reassembled on assembly second instance repeatedsequence treated raw body even though count field how add repeatingsequences like structure preserved reassembly is way group fields without resorting packet storage type lists,2 write function classdecorator style copying in python apply directly class created in later versions apply decorator notation here first cut import types def fixdocscls name func varsclsitems isinstancefunc typesfunctiontype funcdoc print func needs doc parent clsbases parfunc getattrparent name none parfunc getattrparfunc doc none funcdoc parfuncdoc break return cls class animalobject def walkself walk like duck class doganimal def walkself pass dog fixdocsdog print dogwalkdoc in newer python versions last part even simple beautiful fixdocs class doganimal def walkself pass this pythonic technique exactly matches design existing tools standard library for example functoolstotalordering class decorator add missing rich comparison methods classes and another example functoolswraps decorator copies metadata one function another,i oo hierarchy docstrings take much maintenance code eg class swallowobject def airspeedself returns airspeed unladen raise notimplementederror class africanswallowswallow def airspeedself whatever now problem africanswallowairspeed inherit superclass method docstring i know i keep docstring using template method pattern ie class swallowobject def airspeedself returns airspeed unladen return selfaskarthur implementing askarthur subclass however i wondering whether another way docstrings inherited perhaps decorator i discovered yet,3 minx x mylist x,i question algorithm point view i list numbers floats and i want find smallest number greater lets say so answer but besides obvious solution iterating thru list keeping track smallest number greater k pythonic way thanks,3 i idea python algorithmic point view maybe i add something in example list monotonically increasing sorted if always true list small optimization might stop iterating reached number larger if list always numbers lower great optimization number items target number random improvement reliable in case might want search list partitioning test middle element larger if larger throw away upper half otherwise throw away lower half do thing new halflength list you need deal even odd numbers case items left listsegment for large list reduce number tests significantly,i question algorithm point view i list numbers floats and i want find smallest number greater lets say so answer but besides obvious solution iterating thru list keeping track smallest number greater k pythonic way thanks,1 binary search would standard way deal list sorted previous answer pointed see python binary searchlike function find first number sorted list greater specific value in python find index first value greater threshold sorted list discussion module httpdocspythonorglibrarybisecthtml,i question algorithm point view i list numbers floats and i want find smallest number greater lets say so answer but besides obvious solution iterating thru list keeping track smallest number greater k pythonic way thanks,3 i would make use xml attributes envvar namemake typecommandwhich makeenvvar envvar nameqtdir typestringhomeqtlibsqtqtenvvar pseudocode depending xml library nodeattributes type command value ospopennodefirstchildtextread elif nodeattributes type string value nodefirstchildtext osenvironnodeattributes name value,i xml contains information environment variable set shell python script here snippet xml envvar name qtdir homeqtlibsqtqtenvvar envvar name make makeenvvar this part snippet tells python script set environment variables qtdir make my concern difference set variables i know use osenviron set environment variables something like osenviron qtdir homeqtlibsqtqt but use set make variable execute command make get path make executable my goal use methodfunction set every variables so thought something like popenqtdirhomeqtlibsqtqt export qtdir shelltrue stdoutpipe stderrpipe popenmakewhich make export make shelltrue stdoutpipe stderrpipe but variable set subprocess current shell so question way want i don t want analyse xml something like pseudocode qtdir normal value osenviron qtdir homeqtlibsqtqt make value executed p popenwhich make shelltrue stdoutpipe stderrpipe stdout stderr pcommunicate osenviron make stdout,2 no significant digits big deal get little support computer languages people real computations need error bars far precision — real measurements say exact things like “this â± mm“ instead saying either less exact statements “this mm” “this mm” makes choose power ten even inexactness actually fall power ten,is way python count significant figures doublefloatetc i seeing easy way i expect library thanks advance,2 the bad news root problem python datetime implementation the good news django open ticket problem the bad news ticket opened the good news recent proposal useful reading seems development the thread containing proposal long informative the bad news proposal boils real mess still development going i found postgres backend directs django create columns use time zones no django design decision postgresql stores utc store timezone store offset the timezone conceptually like environmental variable gets applied timestamps inserted selected retrieval from django developer mail archive in absence actual time zone support database action taken django going inconvenience somebody likely compatible nondjango use database that big problema fix might make database incompatible languages frameworks that absolute showstopper i work many programming languages frameworks access database sqlite microsoft access mysql datetime data type timestamp cited thread lacking timezone support database,i thought django created datetime columns time zone agnostic i looked postgres table i saw values recorded time zone information going i found postgres backend directs django create columns use time zones from djangodbbackendspostgresqlcreationpy datatypes datetimefield timestamp time zone the schema shows created column specified timestamp time zone create table notificationnotice created timestamp time zone not null the postgres log shows update statement sent django constructed sql statement used utc time zone directed django settings file update notificationnotice set senderid groupid null noticetypeid contenttypeid objectid created e where notificationnoticeid this table looks like the created column timestame time zone postgres must inspecting time zone system clock find time zone mydb select notificationnotice limit id senderid groupid noticetypeid contenttypeid objectid created lastinteractiontime row questions doesn django hands policy time zones why postgres backend use time zones modelsdatetimefield is required postgres is way force django create timestamp columns postgres use time zone,3 you giving facecolors boolean the parameter defined facecolor facecolors matplotlib color arg sequence rgba tuples just make facecolor none work you probably dont want get color two plots if eliminate parameter get automatic colors if still need custom colors easiest way indicate matplotlib colors yellow red etc,i learning draw scatter using matplotlib however bug seems related color argument could anyone explain mistake i googled answer found thanks advance xacta range yacta nprandomrandn xactq range yactq nprandomrandn xra nprandomrandn yra nprandomrandn f figure scatterxacta yacta c b marker facecolors true label answers scatterxactq yactq c r marker facecolors true label questions xscale log yscale log title user activity xlabel number posts ylabel number users legend fshow fsavefig figuretestpng,1 if mycnt string integer read directly sysargv loop never end,i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit,2 you instead you want exit program count mycnt,i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit,1 you added else clause loop it execute loop never executes your loop terminates count increases past mycnt anoter iteration loop executed mabe notice â­â€” loop may take long,i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit,1 fwiw repr module tools display list limiting number lines output,i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit,2 there assignment python primitive types assignment pointers if want create copy need special copy function,i exporting c class python i noticed compilation swig issued following warning warning operator ignored i sure operator overloaded says swig documentation swig capable handling operators assignment operator there nothing special class declared like class foo public foo fooamp operator const fooamp etc why swig failing generate wrapper code assignment operator may i fix,3 larry lustig already hit nail head regarding mycnt check see hit limit also wrong hamish points rather count mycnt could use slice like maximum removing need count variable speaking variables i suggest would benefit betternamed variables viz usrbinenv python import sys import os rootdir sysargv maximum intsysargv print printing biggest maximum files rootdir filedict root files oswalkrootdir filename files filepath ospathjoinroot filename filesize ospathgetsizefilepath filedictfilepath filesize sortedbysize sortedfiledictiteritems keylambdapath size size path reversetrue path size sortedbysizemaximum print size path,i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit,1 the built command finding current screen sessions screen ls to get functionality python subprocess import checkoutput def screenpresentname var checkoutputscreen ls trueshelltrue namet var print name running else print name running screenpresentserver a couple comments code i use true shelltrue screen returns exit code play well checkoutput function also i added make sure matching screen name another part printout,how check python whether screen given name ex server running thanks,2 usrbinpython import os import sys print ospathrealpathsysargv,if i execute python script actually symbolic link linked real script somewhere else anyway print location real script,1 the answer appears search engine query away you also use direct link time complexity page pythonorg quick summary average ominlens lent worst case olens lent edit as raymond points worst case scenario likely occur i included originally thorough i leaving provide context discussion i think raymond right,in python get intersection two sets amp set sintersections set anybody knows complexity intersection amp algorithm edit in addition anyone know data structure behind python set,3 alternatively want use argv usrbinpython import os print ospathrealpathfile,if i execute python script actually symbolic link linked real script somewhere else anyway print location real script,2 the intersection algorithm always runs ominlens lens in pure python looks like def intersectionself lenself lenother little big self else little big self result set elem little elem big resultaddelem return result answer question additional edit the data structure behind sets hash table,in python get intersection two sets amp set sintersections set anybody knows complexity intersection amp algorithm edit in addition anyone know data structure behind python set,3 call base class method outerclassamethodsomeclassbobject,when i call method outer class ends calling derived class method instead how i force call base class method is best inner class init call parent init class outerclassa init method def methodself class innerclassbouterclassa def methodself,1 python double underscores name mangling designed help issue for details workedout example see httpdocspythonorgtutorialclasseshtmlprivatevariables httpdocspythonorgreferenceexpressionshtmlatomidentifiers class outerclassa def initself selfmethod call class private copy def methodself method method make private class local copy class innerclassbouterclassa def methodself,when i call method outer class ends calling derived class method instead how i force call base class method is best inner class init call parent init class outerclassa init method def methodself class innerclassbouterclassa def methodself,2 configure error acceptable c compiler found path this error selfexplanatory get c compiler xcode work,i trying install django project onto osx machine requires pycrypto i getting following error running install running build running buildpy running buildext running buildconfigure checking gcc checking cc checking clexe configure error usershomedocumentstmpdlitzpycryptoda configure error acceptable c compiler found path see configlog details traceback recent call last file setuppy line module coresetupkw file systemlibraryframeworkspythonframeworkversionslibpythondistutilscorepy line setup file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommands file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilscommandinstallpy line run file systemlibraryframeworkspythonframeworkversionslibpythondistutilscmdpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilscommandbuildpy line run file systemlibraryframeworkspythonframeworkversionslibpythondistutilscmdpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand file setuppy line run selfruncommandcmdname file systemlibraryframeworkspythonframeworkversionslibpythondistutilscmdpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand file setuppy line run raise runtimeerrorautoconf error runtimeerror autoconf error,3 why use a lot existing python code compatible python yet if need use django example forced use python x my second question one i use python pyqt recommendations,i used python years ago version now was reason continued upgrade split two different pythons like one uses python they use whatever why use obviously reason i unable find googling my second question one i use i assuming only based higher number i wonder still around if major bugs i going use i reckon much matters either one would probably work py qt,3 python significantly different python x breaks numerous libraries likely lot dependent code python x likely around quite libraries ported fieldtested,i used python years ago version now was reason continued upgrade split two different pythons like one uses python they use whatever why use obviously reason i unable find googling my second question one i use i assuming only based higher number i wonder still around if major bugs i going use i reckon much matters either one would probably work py qt,2 costs lot upgrade python x python project still uses python,i used python years ago version now was reason continued upgrade split two different pythons like one uses python they use whatever why use obviously reason i unable find googling my second question one i use i assuming only based higher number i wonder still around if major bugs i going use i reckon much matters either one would probably work py qt,1 the latest ubuntu ship python yet openbsd package python either some people may python platform care compile,i used python years ago version now was reason continued upgrade split two different pythons like one uses python they use whatever why use obviously reason i unable find googling my second question one i use i assuming only based higher number i wonder still around if major bugs i going use i reckon much matters either one would probably work py qt,1 prefix command pythonpath replace directory app without telling python find modules know look current directory part path default,my app needs backup system remote administration i disabled federated login easier remoteapi access now i log i import module montao python remoteapishellpy montaoprojectappspotcom email niklasro password app engine remoteapi shell python r apr gcc the db users urlfetch memcache modules imported smontaoproject import traceback recent call last file console line module importerror no module named smontaoproject could tell run simple remote api commands i could run backup system connect via ahremoteapi python setup seems correct i might need clearer understanding use remoteapi update this works seems use django ubuntuubuntumedialexarmontao pythonpathmontaoproject python remoteapishellpy montaoprojectappspotcom app engine remoteapi shell python r apr gcc the db users urlfetch memcache modules imported smontaoproject import warningrootyou using default django version the default django version change app engine release near future please call uselibrary explicitly select django version for information see httpcodegooglecomappenginedocspythontoolslibrarieshtmldjango smontaoproject,2 your class demonstrates new python i try clean point things without completely rewriting other solutions cleaner hopefully help understand concepts class chemistry because class method automatically receive reference instance call method you account declaring method standard name self def readamuself infil openatomamutxt r line infilreadline atoms list as frã©dã©ric said tuples immutable means changed this means empty tuple never added later program therefore leave next line element line line linerstripn parts linesplit element parts amu parts the next several lines indicate got right idea got method calls reversed if work would want reverse object append method getting called original elementappendelement amuappendelement elementappendatoms correct element element amu atomsappendelement if make sure atoms part self work disappear end method able anything later selfatoms atoms now want load atomic numbers instantiate chemistry class call readamu method c chemistry creadamu print catoms remember atoms part c instance last line selfatoms atoms,i working chemistry program requires list elements corresponding atomic mass units something along lines elements hhec elements amu read file line written like c i need read information file append line tuple append tuple list here code i tried without success class chemistry def readamu infil openatomamutxt r line infilreadline atoms list element line line linerstripn parts linesplit element parts amu parts elementappendelement amuappendelement elementappendatoms am i right track if would i append two values tuple assign value index append list,1 this quite simple arrange numpy the function nproll returns copy array rolled specified direction for example given array x xnparangereshape array roll columns right nprollxshiftaxis array using nproll boundaries wrapped like torus if want wrapped boundaries could pad array edge zeros reset edge zero every iteration import numpy np def diffusionarr true arrnprollarrshiftaxis right arrnprollarrshiftaxis left arrnprollarrshiftaxis arrnprollarrshiftaxis yield arr n initialnprandomrandomnn state diffusioninitial printstate rawinput,i pretty new python i project part includes diffusion across map i implementing going making current tile equal sum neighbors nwse if i c i double loop loops array arriwidth j arr j j ii neighbors several different arrays i thing different qualities map i changing however i sure really fastest way python some people i asked suggest stuff like numpy width probably k elements max i sure overhead worth i really know builtin functions i want any advice edit this dense ie every spot going nontrivial calculation,2 the easiest way make sure state object saved local scopes attributes object consider import cpickle class testobjet def initself filenamemystatepickle selfindex selffilename filename def saveself f openselffilename w cpickledumpself f fclose def dosomeworkself selfindex print selfindex selfindex selfsavecondition suppose condition become true index value selfsavecondition false selfsave might saved file restoreclassobject getsavedobject get object file of course dosomework makes sense sake example imagine method thread could still interact object setting restoreclassobjectsavecondition true save next iteration step,i want save object state reuse time i got example how save object pickle module i able find resume classmethod save state proceed like game save game latter continue i know game save data game read data build game i want save complete object i restore start working saved state for example class testobjet def dosomeworkself index index print index index savecondition suppose condition become true index value savecondition none savetheobjecttofile might saved file restoreclassobject getsavedobject get object file now start printing i want resume object state saved,1 instead saving temporary value val save list return list def encryptkey temp list char inkey tempappendordchar return temp,i trying save output loop iterationfor example code def encryptkey char key val ordchar example someone entered lol interpreter program outputs encryptlol in example i need store memory use another function anyone help,1 there number different methods could use python probably nicest way use list comprehension like def encryptkey return ordchar char key see httpdocspythonorgtutorialdatastructureshtmllistcomprehensions encrypt lol would return list,i trying save output loop iterationfor example code def encryptkey char key val ordchar example someone entered lol interpreter program outputs encryptlol in example i need store memory use another function anyone help,1 computers simply work way least unless programmed the assumption number give exact if create number operations treat exactly that error least significant digit may end propagating larger errors later computations something good code deal using algorithms minimize issues possible as i said however computers told so packages written use called interval arithmetic a number may described interval might create interval we operate intervals adding subtracting multiplying etc those operations often see interval widths expand operate the fact however even use interval arithmetic tools you must know beginning number significant digits numbers if create number storing double computer actually try store number assume digits exactly correct in fact course floating point arithmetic employed number actually stored internally binary number so probably effectively stored number decimal fractional numbers representable exactly binary form again care must employed software also always person using tools understand numbers really mean this last point important many people treat numbers generated computer truth handed computer god stone tablet if computer prints believe every digit see in fact common sense must applied know perhaps number generated data significant digits may choose rely first significant digits number and course taught concept school know trust trust remember however computers generally infinitely trusting it must apply filter,is way python count significant figures doublefloatetc i seeing easy way i expect library thanks advance,1 how threadingevents import threading import time import logging loggerlogginggetloggername def fresumeiswaitingname true resumeisset iswaitingset loggerdebug n pausing formatnname resumewait iswaitingclear loggerinfoname timesleep def hresumewaiters true loggerdebug halt resumeclear iw enumeratewaiters loggerdebug wait worker pause formatii wwait loggerinfo h begin timesleep loggerinfo h end loggerdebug resume resumeset timesleep loggingbasicconfiglevelloggingdebug format asctimes threadnames messages datefmt hms set means resume clear means halt resume threadingevent resumeset waiters name fg iswaitingthreadingevent waitersappendiswaiting threadingthreadtargetfargsresumeiswaitingnamestart threadingthreadtargethargsresumewaitersstart yields thread f thread g thread halt thread wait worker pause thread f pausing thread g pausing thread wait worker pause thread h begin thread h end thread resume thread f thread g thread f thread g thread f thread g thread f thread g thread f thread g thread halt in response question comments this code tries measure long takes h thread acquire lock worker threads it seems show even h waiting acquire lock worker thread may fairly high probability release reacquire lock there priority given h waiting longer david beazley presented pycon problems related threading gil here pdf slides it fascinating read may help explain well import threading import time import logging loggerlogginggetloggername def flockn true lock loggerinfon timesleep def hlocks true ttimetime nlock enumeratelocks lockacquire ttimetime loggerinfo h acquired n formatnndtt tt ttimetime loggerinfo h formatdtt tt lock locks lockrelease timesleep loggingbasicconfiglevelloggingdebug format asctimes threadnames messages datefmt hms locks n n rangen lockthreadinglock locksappendlock tthreadingthreadtargetfargslockn tstart threadingthreadtargethargslocksstart,i new concurrent programming i like execute three tasks repeatedly the first two run time third run every hour the first two tasks run parallel i always want pause third task running here skeleton i tried import threading import time flock threadinglock glock threadinglock def f true flock print f timesleep def g true glock print g timesleep def h true flock glock print h timesleep threadingthreadtargetfstart threadingthreadtargetgstart threadingthreadtargethstart i would expect code print f g every second h every five seconds however i run takes around f g i start seeing h it looks like first two threads constantly release reacquire locks third thread left loop why when third thread tries acquire currently held lock released acquisition immediately succeed instead firstsecond thread immediately acquiring i probably misunderstanding something what would good way achieve i want note moving timesleep calls flockglock block works simple example apparently real application threads spend time actual operations when first two threads sleep second execution loop body lock released third task still never gets executed,3 count one people get pretty expensive have found gut feeling i rather benchmark also whether web servers carry load assume beforehand indexing properly selecting storage engine might help lot furthermore lot userfriendly let people register enter account data registering event because seem favor people type real quick use decent browser,i looking system people rsvp free web conference web conferences get really busy lot interest limited places way ensure get oversubscribed so need countdown time book seat time order completed confirmed this way first x amount people actually click attending get seats conference if user complete booking allocated seat put back pool someone else grab an overview happens i see best working user clicks rsvp event makes ajax request rsvpeventid this goes stores unique id refered token rest question along timestamp it stores token session the user notified x amount time let say mins complete rest details nameemaildob etc however anything put database checks amount pending orders less total seats available seats left conference returns saying sorry seats available keep checking bookings completed seats become available if user fills time stores details database attending if however fail fill form time cron job running every second go delete tokens timestamp minutes ago loose chance attend seat conference put back pool they notified unsuccessful taken back first step all easy enough write simply putting records database count from pendingbookings where conferenceid x working many seats either confirmed orders pending subtracting total seats available conference but i feel using mysql would scalable i sure excess k people trying grab around seats count one people get pretty expensive decent caching needs checking real time many people process i looked using amazon simpledb deployandgo scalability i used seen count necessarily accurate nature scalability i guess obvious reasons count needs accurate i need able add records along timestamp able delete records older five minutes,2 using communication synchronization usrbinenv python import threading import time queue import empty queue def fq c true try qgetnowait qget get pause signal except empty pass signal thing else qget block resume signal print c timesleep def hqueues true q queues qputnowait qput block pause received print h q queues qput put resume timesleep queues queue range threadingthreadtargetf argsqueues f start threadingthreadtargetf argsqueues g start threadingthreadtargeth argsqueuesstart it might notoptimal performance point i find much easier follow output f g f g h f g f g g f f g g f g f f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h,i new concurrent programming i like execute three tasks repeatedly the first two run time third run every hour the first two tasks run parallel i always want pause third task running here skeleton i tried import threading import time flock threadinglock glock threadinglock def f true flock print f timesleep def g true glock print g timesleep def h true flock glock print h timesleep threadingthreadtargetfstart threadingthreadtargetgstart threadingthreadtargethstart i would expect code print f g every second h every five seconds however i run takes around f g i start seeing h it looks like first two threads constantly release reacquire locks third thread left loop why when third thread tries acquire currently held lock released acquisition immediately succeed instead firstsecond thread immediately acquiring i probably misunderstanding something what would good way achieve i want note moving timesleep calls flockglock block works simple example apparently real application threads spend time actual operations when first two threads sleep second execution loop body lock released third task still never gets executed,1 pymongo,want log information mongodb using python found libraries mongodblog logmongo python idea one better library better,3 read last line documentation link section also aware certain operators map cleanly python for instance overloaded assignment operators map python semantics ignored,i exporting c class python i noticed compilation swig issued following warning warning operator ignored i sure operator overloaded says swig documentation swig capable handling operators assignment operator there nothing special class declared like class foo public foo fooamp operator const fooamp etc why swig failing generate wrapper code assignment operator may i fix,3 i executable i want change permissions write nowhere reading executing that chmod works sets permissions file restrict executable write,i change file permissions executable file using oschmod i executable i want change permissions write nowhere reading executing how i thanks rubik,1 the permissions set file chmod affect read fromwrite toexecute file privileges process created running file on unix could get form protection playing file owner sticky bit appropriate permissions filesystem easy get right work windows sticky bit,i change file permissions executable file using oschmod i executable i want change permissions write nowhere reading executing how i thanks rubik,1 a workaround used linux unixes forbid executable write something make executable setuid user permission nearly exist nobody user eg debian ubuntu be careful read seteuid amp setreuid amp capabilities amp credentials i know precisely syscalls pythonic interface,i change file permissions executable file using oschmod i executable i want change permissions write nowhere reading executing how i thanks rubik,1 the basic form query person example typepeopleperson namenone commontopicalias limit ​ there documentation available httpwikifreebasecomwikimqlmanual using freebasemqlreaditer python library httpcodegooglecompfreebasepython easiest way cycle in case limit clause determines chunk size used querying get result individually api level btw plan disambiguate jack kennedy president hurler football player book etc etc httpwwwfreebasecomsearchlimitampstartampqueryjackkennedy you may want consider capturing additional information freebase birth amp death dates book authors types assigned etc enough context able use disambiguate past certain point may easier andor efficient work bulk data dumps rather api httpwikifreebasecomwikidatadumps edit working python program assumes got list type ids file called typestxt import freebase f file typestxt f ttstrip q type mid none name none commontopicalias limit r freebasemqlreaditerq print jointr mid r name r commontopicalias fclose if make query much complex probably want lower limit keep running timeouts simple query like boosting limit default make efficient querying bigger chunks,vocabulary i using nounphrase a short phrase refers specific person place idea examples different nounphrases include barack obama obama water bottle yellowstone national park google chrome web browser etc category the semantic concept defining nounphrases belong ones examples categories include politician household items food people sports teams etc so would barack obama belongs politician people belong food sports teams i lage unlabeled nlp dataset consisting millions nounphrases i would like use freebase label nounphrases i mapping freebase types categories what i need download every single examples every single freebase type i the problem i face need figure structure type query at high level query ask freebase examples topic xx freebase respond list examples topic xx i would grateful someone could give syntax query if done python would awesome,2 the pythonic way something like bestofall maxpbest p selfplayers bestplayers p p selfplayers pbest bestofall lenbestplayers bestplayer bestplayers bestplayerwins print winner bestplayername nresult bestplayerbest elif lenbestplayers more one player best score resolve tie the first line generates list best properties selfplayers finds maximum the next line generates list players whose scores match best score the rest program prints results there really reason mess list indices,i begin written player selfplayers playershot selfplayersbest selfplayersbest selfplayersbest selfplayerswins print winner selfplayersname nresult selfplayersbest elif selfplayersbest selfplayersbest selfplayersbest selfplayerswins printwinner selfplayersname nresult selfplayersbest i know create loop dont know use comparing object values this works know many players players code would useless how write loop returns highest selfbest values,2 if k dictionary k xv xv kiteritems x for for anything older k dictxv xv kiteritems x,i want iterate dictionary examine value delete items matches certain values example del but know dangerous since list updated iterated what clean way python,3 this hardly useful question go yes webhelpers module frameworks make life much easier,i starting web project python likely using django pyramid i done work aspnet mvc i wondering python templating engines concept like web helpers for know callable piece serverside code generate bit even lot html for example module i call serverside python fill data set properties like number pages example generate pageable sortable table html aspnet mvc webgrid purpose also sometimes called datagrid listview httpblogbekijkhetcommvcwebgridhtmlhelperpaginghtml i wondering python templating engines something similar i would write,1 this behaviour controlled qabstractitemviewautoscroll property set like treewidgetsetautoscrollfalse however property mainly used automatically scrolling tree widget dragging items edge widget viewport so behaviour still needed might better override tree widget mousepress event instead def mousepresseventself event selfsetautoscrollfalse qtguiqtreewidgetmousepresseventself event selfsetautoscrolltrue,i qtreewidget bunch qtreewidgetitems each item couple columns when one columns wider width widget scroll bar bottom when i click qtreewidgetitem inside column wider widget qtreewidget automatically scroll try get much column within widget possible i want happen how i turn,3 you could use eval class name config file exactly matches class names python code classes scope eval evil coincidence one letter difference i think a safer way would add extra dictionary maps configuration class name python class name i configuration files know code names change config files without changing code vice versa avoids eval so look something like mappingdict classname mypythonclass classname mypythonclass keys strings values classes then perform lookup using value config file myclassname types extension myclass mappingdictmyclassname,i configcfg i parse using pythonmodule configparser in one section i want configure assignments form fileextension classname parsing results following dictionary types extension classname extension classname edit i know i class evaltypesextension foo class but i given understand eval evil used do know nicer way dynamically configure fileextension results class,2 something like tupleab b x,i know multiply elements single tuple tup tuptup my question multiply elements several tuples using loop example how i get x x,2 i would recommend use builtin filter function since clear done list also filter works iterable sequence container iterator here example work function in in filterlambda x x out instead lambda pass name function used filter data list documentation filter available httpdocspythonorglibraryfunctionshtmlfilter also note filter wellknown world functional programming utilizes powerful concepts find many languages even different paradigm,i want iterate dictionary examine value delete items matches certain values example del but know dangerous since list updated iterated what clean way python,1 x def multiplytheelementsofseveraltuplesusingaforloopx tupleofproducts x x product element x product element tupleofproductsappendproduct return tupletupleofproducts printmultiplytheelementsofseveraltuplesusingaforloopx printmultiplytheelementsofseveraltuplesusingaforloopy output,i know multiply elements single tuple tup tuptup my question multiply elements several tuples using loop example how i get x x,1 the issue linestyle the directive marker linestyle replace linestyle marker first two lines code you see complete list markers scatter,i using matplotlibpyplotscatter draw simple scatter plot however something wrong appears i cannot find solution here code drawing scatter plot xacta yacta xactq yactq lists dimensions ax scatterxacta yacta color blue label answers linestyle ax scatterxactq yactq color black label questions linestyle axsetlabel answers axsetlabel questions xscale log yscale log title user activity xlabel number posts ylabel number users legend fshow fsavefig figuretestpng and error plot contain dots here data xacta lenxacta yacta lenyacta xactq lenxactq yactq lenyactq and second error raised using another data set i checking datasorry previous unclear description,2 compares python objects objects database query returns new python objects c c different see try changing properties c c only one change seen docs c c equivalent cid cid,using django example foreignkey implicit example coconutsmodels import coconut swallow c coconutobjectsgetid swallowobjectsgetid c scoconutscarriedfilterid c c true c c false my understanding tests identity tests equality in case c c exact object why thing,2 they objects talk database objects python objects b true b python object instance identity the operator overloaded works python objects to understand whats going check idc idc interactive python shell you notice different identities b true b considered equal the operator overloaded different objects behaves differently compared when comparing django model objects considered equal type primary keys equal,using django example foreignkey implicit example coconutsmodels import coconut swallow c coconutobjectsgetid swallowobjectsgetid c scoconutscarriedfilterid c c true c c false my understanding tests identity tests equality in case c c exact object why thing,1 you need init every python class optional called present the actual constructor newstyle python classes new inherited object class fooobject pass foo mainfoo object xf foo traceback recent call last file stdin line module typeerror objectnew takes parameters if class inherits class provide init function inherited along like method this different say c constructors treated special inherited,in code following op created class inheriting template class class batchrenametemplate bottom code instantiating class batchrenamefmt albeit construction method def init as i understand inheritance python might something wrong code i new python i might missing something could anyone explain little code explaining the op shows use custom delimiters templates batch renaming files example he creating custom class inherits template change delimeter namefieldpropertyattribute use inner functionality time import time ospath photofiles imgjpg imgjpg imgjpg class batchrenametemplate delimiter fmt rawinput enter rename style ddate nseqnum fformat enter rename style ddate nseqnum fformat ashleynf batchrenamefmt date timestrftime dby filename enumeratephotofiles base ext ospathsplitextfilename newname tsubstituteddate ni fext print formatfilename newname imgjpg ashleyjpg imgjpg ashleyjpg imgjpg ashleyjpg i took code httpdocspythonorgtutorialstdlibhtmltemplating,2 the class batchrename need init inheriting super class template example class a def initself selfage class ba pass does nothing aage bage calling init super class a,in code following op created class inheriting template class class batchrenametemplate bottom code instantiating class batchrenamefmt albeit construction method def init as i understand inheritance python might something wrong code i new python i might missing something could anyone explain little code explaining the op shows use custom delimiters templates batch renaming files example he creating custom class inherits template change delimeter namefieldpropertyattribute use inner functionality time import time ospath photofiles imgjpg imgjpg imgjpg class batchrenametemplate delimiter fmt rawinput enter rename style ddate nseqnum fformat enter rename style ddate nseqnum fformat ashleynf batchrenamefmt date timestrftime dby filename enumeratephotofiles base ext ospathsplitextfilename newname tsubstituteddate ni fext print formatfilename newname imgjpg ashleyjpg imgjpg ashleyjpg imgjpg ashleyjpg i took code httpdocspythonorgtutorialstdlibhtmltemplating,1 the reason observation aes block cipher encrypt data blocks bits bytes to normally used mode operation allow encrypting larger pieces data padding mode it looks like python decrypting function decrypting undo padding giving result you using pkcs padding appends number bytes least one value number final length multiple block length for bytes string one needs append bytes value ascii backspace character terminal moves cursor one left times resulting xxx overprinting abc for bytes string one needs append bytes value this horizontal tabulator making xxx appear quite right either find supply right padding mode decryption function option remove padding check last byte decryptstring convert number using ascii value take many bytes end decryptstring you also check value you first interpreting output string ie applying encoding like utf ascii,i input string i encrypting mysql aesencrypt decrypting python mysql aesdecrypt i printed tests decrypted string print decryptstring print sxxx decryptstring print lendecryptstring print selftohexdecryptstring when input string length ie abcdefgh tests output abcdefgh xxxdefgh xxxxxxxxxxxxxxxx if input string length ie abcdefg abcdefg abcdefg xxx xxxxxxxxxxxxxxxx i found ending char progressively decreases length input string increases why difference if i use php aes encrypt instead mysql aesencrypt ending char x i using use third party python aes lib,1 if want use tuples length tupleproductmytuple mytuple def productcont base e cont base e return base,i know multiply elements single tuple tup tuptup my question multiply elements several tuples using loop example how i get x x,1 tuples length one line script tpl tuplereducelambda x xy tp tp tpl,i know multiply elements single tuple tup tuptup my question multiply elements several tuples using loop example how i get x x,1 i answer part question getting message something build process invoking gcc c source file option wstrictprototypes for c objectivec causes compiler warn oldstyle function declarations declare types arguments for c option make sense declarations even allowed language prototypes mandatory i know message mentions ada wstrictprototypes makes even less sense ada c it huge deal i submitted bug report marked resolvedfixed the solution remove wstrictprototypes option invocation gcc but since invoking gcc directly difficult know i able reproduce warning using setuppy manually creating dummy examplewrapcxx file python setuppy buildext running buildext building foolib extension gcc pthread fnostrictaliasing dndebug g fwrapv o wall wstrictprototypes fpic iusrincludepython c examplewrapcxx buildtemplinuxiexamplewrapo ccplus warning command line option wstrictprototypes valid adacobjc c so probably minor bug python buildext but since warning fatal error i say safely ignore gcc warns meaningless option ignores edit looking python sources section configurein might culprit case gcc yes test cc g strictprotowstrictprototypes fi i assuming invoked using buildext it turns wstrictprototypes option compiler invoked g case using gcc command compile c source code and libdistutilscommandbuildextpy buildextension pay attention source file language invoking selfcompilercompile invoking selfcompilerlinksharedobject which seems odd compilers gcc necessarily able use command compile c c makes sense use g command anyway even linking update a python bug report submitted httpsbugspythonorgissue closed duplicate one httpsbugspythonorgissue still open i write but i said warning probably safely ignore perhaps python maintainers use information fix problem future release,i building c extension use python i seeing warning generated compilation process type python setuppy buildext what causing i fix btw copy setup file usrbinenv python setuppy file swig example distutilscore import setup extension examplemodule extension foolib sources examplewrapcxx wrappersrcfoocpp librariesfoopp setup name foolib version author me myself i description example extmodules examplemodule pymodules example i using gcc ubuntu,3 i structure class using init new different accepts arbitrary arguments besides default first argument only rarely worry new usually define init let default new pass constructor arguments self keyword terms name changed something else but i wondering cls terms name subject change something else parameter name both parameter names special meaning language but use strong convention python community pythonistas never change names self cls contexts confused someone else note use def newtuple rebinds name tuple inside constructor function when actually implementing new want def newcls args kwargs allocation get object say obj return obj albeit i said i want return tuple code works fine returned myclass value new returns there implicit type checking python responsibility programmer return correct type consenting adults being able return different type requested useful implementing factories return subclass type requested this also explains issubclass isinstance behavior observe subclass relationship follows use class myclasstuple isinstance reflects return wrong type new for reference check requirements new python language reference edit ok example potentially useful use new the class eel keeps track many eels alive process refuses allocate exceeds maximum class eelobject maxeels neels def newcls args kwargs clsneels clsmaxeels raise hovercraftfull obj supereel clsnewcls clsneels return obj def initself voltage selfvoltage voltage def delself typeselfneels def electricself is electric eel return selfvoltage mind smarter ways accomplish behavior,i learning python far i tell things new init new object creation init object initialization new invoked init new returns new instance init invoked afterwards initialize inner state new good immutable object cannot changed assigned so return new instance new state we use new init mutable object inner state changed but i another questions when i create new instance myclasshelloworld arguments passed i mean i structure class using init new different accepts arbitrary arguments besides default first argument self keyword terms name changed something else but i wondering cls terms name subject change something else parameter name i made little experiments class myclasstuple def newtuple return i myclass albeit i said i want return tuple code works fine returned i knew passing first parameters type wanted receive new function invoked we talking new function right i know languages return type bound type and i anther things well issubclassmyclasslist false issubclassmyclasstuple true isinstanceamyclass false isinstanceatuple false isinstancealist true i experiment bright i decided stop decided ask stackoverflow the so posts i read python object creation pythons use new init,3 pygame support two displays single pygame processyet see question developer answer immediately says once sdl finished pygame get support using multiple windows process so options use multiple processes two pygame instances maximized screen communicating back forth could use cool python multiprocessing module local tcp pipes writingreading files etc set resolution displays create large wide window spans information one half user display then manually place window user side screen laptop screen it hacky might better use time engineering better solution if studpid works stupid use pyglet similar pygame supports full screen windows pygletwindowwindowfullscreentrue screens good luck,i using pygame program simple behavioral test i running macbook pro almost functionality working however testing i second external monitor subject sees laptop monitor i like game fullscreen external monitor laptop monitor i monitor performance currently start file looks something like usrbinenv python import pygame import sys stdscr cursesinitscr pygameinit screen pygamedisplaysetmode pygameresizable i thinking starting game resizable screen os x problems resizing window,3 each app engine instance max parallel http queries could potentially make times faster createrpc amp makefetchcall there scenarios work either need split job several tasks let run parallel,i working facebook application it written python running google app engine gae i know get relationship status users network way i running way slow there time limit gae order reduce cpu usage seconds using following code i get relationship status persons time frame getting deadlineexceedederror of course good enough since manymost people higher amount friends facebook what i get friend list user making api call one asking name relationship status the code i use f friends friendsinfof facebookapi f u fields namerelationshipstatus u accesstoken facebookaccesstoken and i get data relstatus friendsinfofu relationshipstatus what i need suggestions optimization ways extract relationship status entire network thanks advance edit the answers seems good ways solve problem though i find good tutorials batch request python i ended using fql call by using following takes seconds get data q select uid sex relationshipstatus user uid select targetid connection sourceid and actual data retrieved data fqlqueryqfacebookaccesstoken call function def queryselfqaccesstoken endpoint httpsapifacebookcommethod params dictqueryq accesstokenaccesstoken format json url endpoint fqlquery return selffetchurl paramsparams def fetchself url paramsnone conn urlliburlopenurl dataurlencodeparams try return jsonloadsconnread finally connclose hope someone make use well,1 you use facebook graph batch query api query users,i working facebook application it written python running google app engine gae i know get relationship status users network way i running way slow there time limit gae order reduce cpu usage seconds using following code i get relationship status persons time frame getting deadlineexceedederror of course good enough since manymost people higher amount friends facebook what i get friend list user making api call one asking name relationship status the code i use f friends friendsinfof facebookapi f u fields namerelationshipstatus u accesstoken facebookaccesstoken and i get data relstatus friendsinfofu relationshipstatus what i need suggestions optimization ways extract relationship status entire network thanks advance edit the answers seems good ways solve problem though i find good tutorials batch request python i ended using fql call by using following takes seconds get data q select uid sex relationshipstatus user uid select targetid connection sourceid and actual data retrieved data fqlqueryqfacebookaccesstoken call function def queryselfqaccesstoken endpoint httpsapifacebookcommethod params dictqueryq accesstokenaccesstoken format json url endpoint fqlquery return selffetchurl paramsparams def fetchself url paramsnone conn urlliburlopenurl dataurlencodeparams try return jsonloadsconnread finally connclose hope someone make use well,1 why would exit you iterating elements range exit condition run elements rebinding name change anything inside iterable if want break prematurely use break range break,python noob please explain loop exit range print hello world print next regards,1 because done range created array elements like going one in programming languages called foreach loop otherwise another way,python noob please explain loop exit range print hello world print next regards,3 because whatever means element whatever loop body executed setting element there rule says end iteration must still element whatever reassigning loop body effect whatsoever often loop body executes value hold next iteration,python noob please explain loop exit range print hello world print next regards,1 because python loop count iterates range produces iterable list python x iterable iterated each time loop body executed next item pulled changes make loop body iteration variable affect memory next value supposed that saved elsewhere generally affect simply use break,python noob please explain loop exit range print hello world print next regards,3 you iterating range object collection values ranging there logic behind collection numbers the item set syntax essentially loops every element set breaking every item looped your code equivalent c loop would produce desired result int if want break loop break loop range print hello world break print,python noob please explain loop exit range print hello world print next regards,2 in python loop loop like c java instead iteration iterable in case assuming python x range way range function returns list a python list iterable therefore used loop language assigning variable first second third element time execute body part it matter alter variable body python pick next element list elements processed consider loop really different print hello world print turn also quite similar print hello world print assignment break loop,python noob please explain loop exit range print hello world print next regards,1 you could try shutilmove shutil import move move cuserstesttxt cuserstestscsv or osremove shutilmove os import remove shutil import move remove cuserstestscsv move cuserstesttxt cuserstestscsv,is possible force rename osrename overwrite another file already exists for example code file testscsv already exists would replaced teststxt file also renamed testscsv osrenamecuserstesttxtcuserstestscsv,3 change function bit lots ways add id form idchoiceform add line submits form function writetostorage user user count count localstoragesetitemchooser user documentgetelementbyidchoiceformsubmit,i handler choice textarea field choicehandler writes information returned database but posting form i want write user name localstorage this form form namechoiceform actionchoicehandler methodpost textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form on click i want assign username user write localstorage writetostorage head script typetextjavascript var count function writetostorage user user count count localstoragesetitemchooser user script head what i confused use onclickwritetostorage call writetostorage time actionchoicehandler form what correct way achieve something like i working google app engine python i add ajax call choicehandler later i solve as summary i want write javascript variable user localstorage post textarea choicehandler one click update i trying johndoe answer writetostorage never fired what i wrong the full code handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage alertcount count user user count line giving error fixed alertuser user count count alertuser user count count count localstoragesetitemchooser user script head body form namechoiceform idchoiceform actionchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form selfresponseoutwrite body html,1 on unix dst exists file replaced silently user permission the operation may fail unix flavors src dst different filesystems if successful renaming atomic operation posix requirement on windows dst already exists oserror raised even file may way implement atomic rename dst names existing file httpdocspythonorglibraryoshtmlosrename,is possible force rename osrename overwrite another file already exists for example code file testscsv already exists would replaced teststxt file also renamed testscsv osrenamecuserstesttxtcuserstestscsv,3 let function get invoked right form gets submitted form namechoiceform actionchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form,i handler choice textarea field choicehandler writes information returned database but posting form i want write user name localstorage this form form namechoiceform actionchoicehandler methodpost textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form on click i want assign username user write localstorage writetostorage head script typetextjavascript var count function writetostorage user user count count localstoragesetitemchooser user script head what i confused use onclickwritetostorage call writetostorage time actionchoicehandler form what correct way achieve something like i working google app engine python i add ajax call choicehandler later i solve as summary i want write javascript variable user localstorage post textarea choicehandler one click update i trying johndoe answer writetostorage never fired what i wrong the full code handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage alertcount count user user count line giving error fixed alertuser user count count alertuser user count count count localstoragesetitemchooser user script head body form namechoiceform idchoiceform actionchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form selfresponseoutwrite body html,1 as documentation says impossible guarantee atomic renaming operation windows file exists python asking double step osremove osrename handling potential errors on unix systems rename overwrites destination exists operation guaranteed atomic note windows also possible deleting destination file fail even permission file may use this another essential limitation windows file system handle code,is possible force rename osrename overwrite another file already exists for example code file testscsv already exists would replaced teststxt file also renamed testscsv osrenamecuserstesttxtcuserstestscsv,3 sorry misreading question in case i would suggest cache table yes updated using trigger on insert delete table transactions when allow user go transaction insert hash expiration timestamp table it triggers trigger update cached value ie value cache table according insert delete when checking wheteher free seats check cache table would sort caching work,i looking system people rsvp free web conference web conferences get really busy lot interest limited places way ensure get oversubscribed so need countdown time book seat time order completed confirmed this way first x amount people actually click attending get seats conference if user complete booking allocated seat put back pool someone else grab an overview happens i see best working user clicks rsvp event makes ajax request rsvpeventid this goes stores unique id refered token rest question along timestamp it stores token session the user notified x amount time let say mins complete rest details nameemaildob etc however anything put database checks amount pending orders less total seats available seats left conference returns saying sorry seats available keep checking bookings completed seats become available if user fills time stores details database attending if however fail fill form time cron job running every second go delete tokens timestamp minutes ago loose chance attend seat conference put back pool they notified unsuccessful taken back first step all easy enough write simply putting records database count from pendingbookings where conferenceid x working many seats either confirmed orders pending subtracting total seats available conference but i feel using mysql would scalable i sure excess k people trying grab around seats count one people get pretty expensive decent caching needs checking real time many people process i looked using amazon simpledb deployandgo scalability i used seen count necessarily accurate nature scalability i guess obvious reasons count needs accurate i need able add records along timestamp able delete records older five minutes,1 instead checking corrupted file assume intact import bz try bzbzfilezipfileread print intact except ioerror print corrupted,is way check crc validity bz file python i using check png corrupted bz file thank,3 elif location default item nothing print you picked item inventoryappenditem location elif location default item nothing print you enter room location i guess want call function name for need reference module class inside defined module somemodule function defined function getattrmodule location get reference function function call function if function defined current module function globalslocation function call function,i trying make textbased game python however code could get hand pretty quickly i one thing one line first source code sys import exit prompt inventory def menu true print enter start game start playing print enter password skip level want print enter exit exit game choice rawinputprompt choice start game shell elif choice password password elif choice exit exit else print input invalid try def password print enter password password rawinputprompt password go back print going menu else print wrong password you trying cheat pointlessly guess passwords deadcheating def shelllocationdefault item nothing location default item nothing print starting game starterroom disabled room actually made elif location default item nothing print you picked item inventoryappenditem location elif location default item nothing print you enter room location else print error closing game def location print nothing see placeholder location script spout errors def deadreason print you died reason exit print welcome menu first explanation game basically works the game shell input done receives information sends information different rooms game stores inventory it receive two arguments location eventual item added inventory however line first elif block shell line last elif block shell supposed go back whatever location location line exact i tried location work seems work printing things something is way if even writing engine game would nightmare or i make entirely different engine i think would way better approach case sorry i made mistakes first questionpost ever,1 the cost depends implementation obviously i worry it unlikely going matter anyway standard protocols raise exceptions strangest places think stopiteration surrounded raising catching whether like when choosing lbyl eafp worry readability code instead focusing microoptimisations i avoid typechecking possible might reduce generality code,i looking python faq mentioned another question having never really looked detail i came across question “how fast exceptions” a tryexcept block extremely efficient actually catching exception expensive in versions python prior common use idiom try value mydictkey except keyerror mydictkey getvaluekey value mydictkey i little bit surprised “catching exception expensive” part is referring except cases actually save exception variable generally except including one example i’ve always thought using idioms shown would pythonic especially python “it easier ask forgiveness get permission” also many answers so generally follow idea is performance catching exceptions really bad should one rather follow lbyl “look leap” cases note i’m directly talking example faq many examples look exception instead checking types,3 no running quick tests heroku proxy proxyherokucom i make connections ports being heroku provide popsmtp make sense ports open i afraid,web services heroku normally use port environment variable i want run custom mail server heroku so i need expose ports preferably i live alternatives is possible,2 use import eventlet eventletmonkeypatch import module or module eventletimportpatchedmodule either work httpeventletnetdocpatchinghtml,i would like multithread sending mail using django smtpconnection perhaps smtplib module i hoping module similar urllib i import eventlet eventletgreen import urllib except using smtplib instead urllib import however appear supported i read could monkey patched i unsure proceed any ideas accomplished eventlets or i drop python thread class etc,1 here simple example based code provided tkinter import def changeimageargs change image label accordingly labelconfigimagephotosintstudfilesget app tk apptitleexample appgeometry x appconfigurebackground black appresizable studfiles stringvar studfilesset image files number corresponding list index studdropdown optionmenuapp studfiles files studdropdownconfigfonttimes italic studdropdownmenuconfigfonttimes italic studdropdownpack studfilestracew changeimage list photoimages image photos photoimagefile imgif photoimagefile imgif label labelappimagephotos labelpack appmainloop you make listtuple photoimage every graphic want you also trace stringvar know value optionmenu changed then set image label config method,i dropdown menu couple choices label image i would like change image according choice selected dropdown menubut cant figure example code tkinter import import tkinter tk def image list imgif imgif studdropdown menu delete end string list studdropdown menu addcommandlabelstringcommandlambda valuestringstudfilessetvalue apptk apptitleexample appgeometry x appconfigurebackground black appresizable buttonbuttonapptext press commandimage buttonpack studfiles stringvar studfilesset image files please wait studdropdown optionmenuapp studfiles files studdropdownconfigfonttimesitalic studdropdownmenuconfigfonttimesitalic studdropdownpack photo photoimagefile imgif label labelappimagephoto labelimage photo keep reference labelpack appmainloop maybe even use label display image suitable any ideas,3 first tornado fapws web servers bottle web framework those belong completely different categories web frameworks usually run wsgi server behind http web proxy the http server included frameworks fast development deployment easy deployment sites high efficiency matter the idea basically http server apachelighttpdnginxtornadofapws etc good understanding http serving static files disk the dynamic content hand generated python server using web framework like bottleflaskwebpypylonsetc the document produced web framework sent back http server wsgi put http response sent client,so i done reading python web frameworks servers mostly tornado bottle also fapws still grey areas first three web frameworks said fast yet include web server written python except fapws put behind nginxapache isn reducing performance i mean know python much slower c use nginx worst included python web server,3 the format response cmgl indexmessagestatusaddressaddresstextservicecentertimestampaddresstypesmsmessagebodylength smsmessagebody source you want text apart first line messagebody smstextsmstextindex rn,this sms message i obtained using at commands mobile cmgl rec readdd hey working bbc news channel pack rs dial now i need extract text message i tried approaches something always gets missed i using python any good suggestion,1 your custom execute method return anything meaning checkuserid code none furthermore interested least one row returned query if none userid available the docs say calling fetchone returns none rows available you use checksql select userid from bsmembers where userid checkuser true newuseruserid gagetinput enter userid w dsexecutechecksqlcheckusernewuseruserid dsfetchone none this userid available break else print that user name already use please enter new username i assuming ds instance cursor subclass thereof,checksql select userid from bsmembers where userid checkuser doesuserexist false true doesuserexist false newuseruserid gagetinput enter userid w checkuserid dsexecutechecksqlcheckusernewuseruserid row ds row checkuserid doesuserexist true print that user name already use please enter new username break doesuserexist false break else continue i using cxoracle module python i trying prompt user enter userid the program check userid already exists prompt user different userid the execute method helper method uses execute method cxoracle interact oracle database the getinput method prompts user input checked regular expression i know i wrong i believe loop starts first action taken user prompted userid then userid checked database the loop starts checks row returned dsexecute userid provided user if user told use another user name break exits loop the statement checks user exists breaks loop if loop iterates user prompted enter nonexistent userid what happens user prompted userid none checking ever appears happen user program moves next piece code what i missing i included link docs execute the execute method code part following helper method def executeself statement parameters parameters none selfcursexecutestatement else selfcursexecutestatementparameters if i need provide information let know edit i forgot line doesuserexist false immediately beginning loop i added,2 all deduced information available something expecting bytestring fed unicode object containing unicode character ub cyrillic small letter che with descender course encodable ascii default encoding hence error message best possible answer far don update you still asked question nonetheless so something crypto gadget decrypt method that surely needs str object what print reprencrypted tell if looks like random rubbish encrypted stuff somehow converted str object unicode object you need backtrack see happening if encrypted looks like meaningful text encryption process broken step start known plaintext encrypt decrypt simple script outside gae apparatus use print repr stage reasonable expectations next step step repeat step using gae inspecting type contents piece data update it appears urlencode page a corresponding urldecode page b part problem,i trying pass encrypted query string another url the following code gives error unicodeencodeerror ascii codec encode character u ub position ordinal range the encryption module pycrypto running python app engine page a import crypto cryptocipher import arc objarcnew stackoverflow msg this secret msg encrypted objencryptmsg selfredirect pageb urlliburlencode q encrypted page b import crypto cryptocipher import arc encrypted selfrequestget q objarcnew stackoverflow decrypted objdecryptencrypted getdata cgiparseqsdecrypted selfresponseoutwritedecrypted selfresponseoutwritepprintpprintgetdata traceback traceback recent call last file cprogram filesgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlergetgroups file cprogram filesgooglegoogleappenginedemosguestbookguestbookpy line get decrypted objdecryptencrypted unicodeencodeerror ascii codec encode character u ub position ordinal range,1 any directory write access long filesystem enough space store whoosh index like homemysitewhooshindex straight docs just make sure contents made public webserver,requires setting haystackwhooshpath place filesystem whoosh index located can anyone explain exactly path pointing i mean give path,1 if tweepy feature need always access twitter directly http request the full twitter rest api described httpsdevtwittercomdocsapi the ones seem relevant interest get trendswoeid looks tweets woeid yahoo identifier collecting information given placelandmarketc get geoidplaceid mines geotagged tweets there documentation information available get request ip address among available fields httpsdevtwittercomdocsapigetsearch lastly twitter location search faq may interest,i following questions tweepy python module i trying retrieve tweets specific location i able using tweepy python module streaming api i get tweets whose geo locations enabled means i would loose rest tweeter’s tweet enabled geo location is better way retrieve tweets given location i use streamsample method retrieve tweets can someone tell parameters used sample method i see count async parameters now specify what firehose method tweepystream any help much appreciated,2 catching exceptions expensive exceptions exceptional read happen often if exceptions rare trycatch faster lbyl the following example times dictionary key lookup using exceptions lbyl key exists exist import timeit sappend try x d key except keyerror x none sappend x d key key d else none sappend try x d xxx except keyerror x none sappend x d xxx xxx d else none ic enumerates timeittimercd key value print run mintrepeat output run trycatch key exists run lbyl key exists slower run trycatch key exist much slower run lbyl key exist when usual case exception trycatch extremely efficient compared lbyl,i looking python faq mentioned another question having never really looked detail i came across question “how fast exceptions” a tryexcept block extremely efficient actually catching exception expensive in versions python prior common use idiom try value mydictkey except keyerror mydictkey getvaluekey value mydictkey i little bit surprised “catching exception expensive” part is referring except cases actually save exception variable generally except including one example i’ve always thought using idioms shown would pythonic especially python “it easier ask forgiveness get permission” also many answers so generally follow idea is performance catching exceptions really bad should one rather follow lbyl “look leap” cases note i’m directly talking example faq many examples look exception instead checking types,3 don use nested loops use enumerate get index item item enumeratelst writetome open listitemtxt formati w writetomewriteitem writetomeclose sidenote don forget close files finished using,i list length n each item list need written n txt files for reason following basic approach working item lst rangelenlst writetome open listitemitxt w writetomewriteitem the file names fine listitemtxt listitemtxt etc same item written file so i end n files duplicate contents file any ideas,1 i facing kind problem timesleep reliable android device locked mode here things i tried sla release pythonforandroidr android samsung galaxy s wrap timesleepinterval loop inside droidwakelockacquirepartial droidwakelockrelease this prevent cpu slowing use eventwaitforeventname timeoutinmilliseconds call droideventwaitforthiseventcannothappen interval threadingtimer object seems also work expected tests device confirmation needed i sure better keep mind tricks might drain power expected true lockedsleeping mode therefore reduce runtime device update eventwaitfor reliable either long intervals here snippet showing timer works import android import threading import logging def dostuff logginginfotesttimerpy stuff done droidnotify testtimerpy dostuff called droidvibrate def createlogpath loggingbasicconfigfilenamepath levellogginginfo format asctimes messages delay droidandroidandroid logpathmntsdcardtesttimerpylog createloglogpath timerthreadingtimerdelaydostuff logginginfotimer starting timerstart logginginfodostuff called timerdelayd delay,here python script written using androidscripting import android time droid androidandroid interval every minute true define vibrate pattern droidvibrate timesleep droidvibrate timesleepinterval it basically vibrates every minute like motivator however phone locked screen blanked i sense vibration perhaps android freezing script hence loop note i indeed running script service longtap click start service is way make script work time regardless phone suspend state update i hear vibration occasionally every minute rather like every minutes randomly update this problems occurs i run script normally service seems like timesleep sleeping specified time,1 this worked note sort return sorted list sorted want pass template use sorted parameters sort pass list parameter itemizedactionlist listchaindetectionpointinsertbodyactionsetall detectionpointinsertheaderactionsetall detectionpointmodifybodyactionsetall detectionpointmodifyheaderactionsetall detectionpointremovebodyactionsetall detectionpointremoveheaderactionsetall detectionpointredirectactionsetall sorteditemizedactionlist keyattrgetter priority,i custom objects dictionaries i want sort i want sort objects dictionaries together i want sort objects attribute dictionaries key objectname jack name jill sortme object how i sort list using object name attribute dictionary name key,1 here simple rule thumb code acts upon single instance object use method even better use method unless compelling reason write function in specific example want look like chessboard chessboard chessboardgetkingmoves don think always use methods point comes say make sense make method case make function,the zen python states one way things yet frequently i run problem deciding use function versus use method let take trivial example chessboard object let say need way get legal king moves available board do write chessboardgetkingmoves getkingmoveschessboard here related questions i looked why python use magic methods is reason python strings dont string length method the answers i got largely inconclusive why python use methods functionality eg listindex functions eg lenlist the major reason history functions used operations generic group types intended work even objects didn’t methods eg tuples it also convenient function readily applied amorphous collection objects use functional features python map apply et al in fact implementing len max min builtin function actually less code implementing methods type one quibble individual cases it’s part python it’s late make fundamental changes the functions remain avoid massive code breakage while interesting really say much strategy adopt this one reasons custom methods developers would free choose different method name like getlength length getlength whatsoever python enforces strict naming common function len used slightly interesting my take functions sense pythonic version interfaces lastly guido talking abilitiesinterfaces made think rogue special method names in language reference says a class implement certain operations invoked special syntax arithmetic operations subscripting slicing defining methods special names but methods special names like len unicode seem provided benefit builtin functions rather support syntax presumably interfacebased python methods would turn regularlynamed methods abc len would become class container def lenself raise notimplemented though thinking i see syntactic operations invoke appropriate normallynamed method specific abc instance would presumably invoke objectlessthan perhaps comparablelessthan so another benefit would ability wean python away mangledname oddness seems hci improvement hm i sure i agree figure there two bits python rationale i like explain first first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something file write method saying thing another way i see len builtin operation i hate lose i say sure whether meant def lenself certainly sounds like want demote ordinary method i strongly the second bit python rationale i promised explain reason i chose special methods look special merely special i anticipating lots operations classes might want override standard eg add getitem standard eg pickle reduce long time support c code i want special operations use ordinary method names preexisting classes classes written users without encyclopedic memory special methods would liable accidentally define operations mean implement possibly disastrous consequences ivan krstiä‡ explained concise message arrived i written guido van rossum home page httpwwwpythonorgguido my understanding certain cases prefix notation makes sense ie duckquack makes sense quackduck linguistic standpoint functions allow interfaces in case guess would implement getkingmoves based solely guido first point but still leaves lot open questions regarding say implementing stack queue class similar push pop methods functions methods i would guess functions i really want signal pushpop interface tldr can someone explain strategy deciding use functions vs methods,2 my general rule operation performed object object done object member operation if could apply things done something else object function perhaps member something else when introducing programming traditional albeit implementation incorrect describe objects terms realworld objects cars you mention duck let go class duck def initselfpass def eatself pass def crapself pass def dieself in context objects real things analogy correct add class method anything object so say i want kill duck i add kill duck no far i know animals commit suicide therefore i want kill duck i def killo duck odie elif dog print why odie elif nyancat raise exceptionnyan else print kill moving away analogy use methods classes because want contain data hopefully structure code manner reusable extensible future this brings us notion encapsulation dear oo design the encapsulation principal really comes designer hide everything implementation class internals absolutely necessarily user developer access because deal instances classes reduces operations crucial instance if operation instance specific member function tldr bryan said if operates instance needs access data internal class instance member function,the zen python states one way things yet frequently i run problem deciding use function versus use method let take trivial example chessboard object let say need way get legal king moves available board do write chessboardgetkingmoves getkingmoveschessboard here related questions i looked why python use magic methods is reason python strings dont string length method the answers i got largely inconclusive why python use methods functionality eg listindex functions eg lenlist the major reason history functions used operations generic group types intended work even objects didn’t methods eg tuples it also convenient function readily applied amorphous collection objects use functional features python map apply et al in fact implementing len max min builtin function actually less code implementing methods type one quibble individual cases it’s part python it’s late make fundamental changes the functions remain avoid massive code breakage while interesting really say much strategy adopt this one reasons custom methods developers would free choose different method name like getlength length getlength whatsoever python enforces strict naming common function len used slightly interesting my take functions sense pythonic version interfaces lastly guido talking abilitiesinterfaces made think rogue special method names in language reference says a class implement certain operations invoked special syntax arithmetic operations subscripting slicing defining methods special names but methods special names like len unicode seem provided benefit builtin functions rather support syntax presumably interfacebased python methods would turn regularlynamed methods abc len would become class container def lenself raise notimplemented though thinking i see syntactic operations invoke appropriate normallynamed method specific abc instance would presumably invoke objectlessthan perhaps comparablelessthan so another benefit would ability wean python away mangledname oddness seems hci improvement hm i sure i agree figure there two bits python rationale i like explain first first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something file write method saying thing another way i see len builtin operation i hate lose i say sure whether meant def lenself certainly sounds like want demote ordinary method i strongly the second bit python rationale i promised explain reason i chose special methods look special merely special i anticipating lots operations classes might want override standard eg add getitem standard eg pickle reduce long time support c code i want special operations use ordinary method names preexisting classes classes written users without encyclopedic memory special methods would liable accidentally define operations mean implement possibly disastrous consequences ivan krstiä‡ explained concise message arrived i written guido van rossum home page httpwwwpythonorgguido my understanding certain cases prefix notation makes sense ie duckquack makes sense quackduck linguistic standpoint functions allow interfaces in case guess would implement getkingmoves based solely guido first point but still leaves lot open questions regarding say implementing stack queue class similar push pop methods functions methods i would guess functions i really want signal pushpop interface tldr can someone explain strategy deciding use functions vs methods,3 use class want isolate calling code implementation details taking advantage abstraction encapsulation when want substitutable objects taking advantage polymorphism when want reuse code similar objects taking advantage inheritance use function calls make sense across many different object types example builtin len repr functions apply many kinds objects that said choice sometimes comes matter taste think terms convenient readable typical calls for example would better xsin ycossqrt sqrtsinx cosy,the zen python states one way things yet frequently i run problem deciding use function versus use method let take trivial example chessboard object let say need way get legal king moves available board do write chessboardgetkingmoves getkingmoveschessboard here related questions i looked why python use magic methods is reason python strings dont string length method the answers i got largely inconclusive why python use methods functionality eg listindex functions eg lenlist the major reason history functions used operations generic group types intended work even objects didn’t methods eg tuples it also convenient function readily applied amorphous collection objects use functional features python map apply et al in fact implementing len max min builtin function actually less code implementing methods type one quibble individual cases it’s part python it’s late make fundamental changes the functions remain avoid massive code breakage while interesting really say much strategy adopt this one reasons custom methods developers would free choose different method name like getlength length getlength whatsoever python enforces strict naming common function len used slightly interesting my take functions sense pythonic version interfaces lastly guido talking abilitiesinterfaces made think rogue special method names in language reference says a class implement certain operations invoked special syntax arithmetic operations subscripting slicing defining methods special names but methods special names like len unicode seem provided benefit builtin functions rather support syntax presumably interfacebased python methods would turn regularlynamed methods abc len would become class container def lenself raise notimplemented though thinking i see syntactic operations invoke appropriate normallynamed method specific abc instance would presumably invoke objectlessthan perhaps comparablelessthan so another benefit would ability wean python away mangledname oddness seems hci improvement hm i sure i agree figure there two bits python rationale i like explain first first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something file write method saying thing another way i see len builtin operation i hate lose i say sure whether meant def lenself certainly sounds like want demote ordinary method i strongly the second bit python rationale i promised explain reason i chose special methods look special merely special i anticipating lots operations classes might want override standard eg add getitem standard eg pickle reduce long time support c code i want special operations use ordinary method names preexisting classes classes written users without encyclopedic memory special methods would liable accidentally define operations mean implement possibly disastrous consequences ivan krstiä‡ explained concise message arrived i written guido van rossum home page httpwwwpythonorgguido my understanding certain cases prefix notation makes sense ie duckquack makes sense quackduck linguistic standpoint functions allow interfaces in case guess would implement getkingmoves based solely guido first point but still leaves lot open questions regarding say implementing stack queue class similar push pop methods functions methods i would guess functions i really want signal pushpop interface tldr can someone explain strategy deciding use functions vs methods,3 suppose array xnprandomrandintsize printx create array ynparray you look upon array mapping mapped then array desire given yx printyx,in numpy i array like i want replace element array array eg etc this convert elements arrays whole array array i tried things nothing worked what right way thanks,2 you may interested arbitrary precision floating point library one httpcodegooglecompmpmath,is way python count significant figures doublefloatetc i seeing easy way i expect library thanks advance,1 dir returns names current scope i remember exactly equivalent localskeys differences,question what object queried call dir python interpreter info i playing around package i want able pull names functions global dictionary i thought would dirglobal dirsysmodules i really sure if jump command line type dir fresh interpreter session give builtins doc name package would ob dirob would give return,2 it appears installed xcode removed gcc used build python installed from path names traceback chances bitonly python downloaded pythonorg with xcode try installing latest bitbit os x installer python pythonorg instead you likely need reinstall packages installed like distribute pip dependencies depending version xcode may also need supply following environment variable setting running pip easyinstall export ccgcc,i used pip install scrapy mac get error anyone help please creating buildlibmacosxfattwistedinternetiocpreactoriocpsupport copying twistedinternetiocpreactoriocpsupportiocpsupportc buildlibmacosxfattwistedinternetiocpreactoriocpsupport copying twistedinternetiocpreactoriocpsupportwinsockpointersc buildlibmacosxfattwistedinternetiocpreactoriocpsupport copying twistedpythonepollc buildlibmacosxfattwistedpython copying twistedpythoninitgroupsc buildlibmacosxfattwistedpython copying twistedrunnerportmapc buildlibmacosxfattwistedrunner copying twistedtestraiserc buildlibmacosxfattwistedtest running buildext gcc fnostrictaliasing fnocommon dynamic arch ppc arch g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c conftestc conftesto usrlibexecgccpowerpcappledarwinas assembler usrbinlibexecgccdarwinppcas usrbinlocallibexecgccdarwinppcas architecture ppc installed installed assemblers usrbinlibexecgccdarwinxas architecture x usrbinlibexecgccdarwinias architecture lipo open input file varfoldersjkjktyafdwecfvztscjwktitmpccbidblout no file directory gcc fnostrictaliasing fnocommon dynamic arch ppc arch g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c conftestc conftesto conftestc error sysepollh no file directory conftestc error sysepollh no file directory lipo figure architecture type varfoldersjkjktyafdwecfvztscjwktitmpcceiymstout building twistedtestraiser extension creating buildtempmacosxfat creating buildtempmacosxfattwisted creating buildtempmacosxfattwistedtest gcc fnostrictaliasing fnocommon dynamic arch ppc arch g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c twistedtestraiserc buildtempmacosxfattwistedtestraisero in file included usrincludearchitectureimathh usrincludemathh libraryframeworkspythonframeworkversionsincludepythonpyporth libraryframeworkspythonframeworkversionsincludepythonpythonh twistedtestraiserc usrincludeavailabilitymacrosh warning warning building intel mac os x deployment target invalid usrlibexecgccpowerpcappledarwinas assembler usrbinlibexecgccdarwinppcas usrbinlocallibexecgccdarwinppcas architecture ppc installed installed assemblers usrbinlibexecgccdarwinxas architecture x usrbinlibexecgccdarwinias architecture lipo open input file varfoldersjkjktyafdwecfvztscjwktitmpccnvrcyzout no file directory error command gcc failed exit status command libraryframeworkspythonframeworkversionsresourcespythonappcontentsmacospython c import setuptoolsfile usersbbbdropboxprojectsandroidcontinuousintegrationbuildtwistedsetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record varfoldersjkjktyafdwecfvztscjwktitmppipmxezuxrecordinstallrecordtxt failed error code storing complete log usersbbbpippiplog,1 sort pymongo takes key direction parameters so want sort let say id sortid,i trying use sort feature querying mongodb failing the query works mongodb console code follows import pymongo pymongo import connection connection connection db connectionmydb print dbpostscount post dbpostsfind entitiesusermentionsscreenname sortu entitiesusermentionsscreenname print post the error i get follows traceback recent call last file findowpy line module post dbpostsfind entitiesusermentionsscreenname sort entitiesusermentionsscreenname file librarypythonsitepackagespymongopymacosxuniversaleggpymongocursorpy line sort file librarypythonsitepackagespymongopymacosxuniversaleggpymongohelperspy line indexdocument typeerror first item key pair must string i found link elsewhere says i need place u infront key using pymongo work either anyone else get work bug,3 generally i use classes implement logical set capabilities thing rest program i reason thing worry little concerns make implementation anything part core abstraction thing usually method this generally includes everything alter thing internal data state usually considered private part logical idea thing when come higher level operations especially involve multiple things i find usually naturally expressed functions built public abstraction thing without needing special access internals unless methods object this big advantage i decide completely rewrite internals thing works without changing interface i small core set methods rewrite external functions written terms methods just work i find insisting operations class x methods class x leads overcomplicated classes it depends code i writing though for programs i model collection objects whose interactions give rise behavior program important functionality closely coupled single object implemented methods scattering utility functions for programs important stuff set functions manipulate data classes use implement natural duck types manipulated functions,the zen python states one way things yet frequently i run problem deciding use function versus use method let take trivial example chessboard object let say need way get legal king moves available board do write chessboardgetkingmoves getkingmoveschessboard here related questions i looked why python use magic methods is reason python strings dont string length method the answers i got largely inconclusive why python use methods functionality eg listindex functions eg lenlist the major reason history functions used operations generic group types intended work even objects didn’t methods eg tuples it also convenient function readily applied amorphous collection objects use functional features python map apply et al in fact implementing len max min builtin function actually less code implementing methods type one quibble individual cases it’s part python it’s late make fundamental changes the functions remain avoid massive code breakage while interesting really say much strategy adopt this one reasons custom methods developers would free choose different method name like getlength length getlength whatsoever python enforces strict naming common function len used slightly interesting my take functions sense pythonic version interfaces lastly guido talking abilitiesinterfaces made think rogue special method names in language reference says a class implement certain operations invoked special syntax arithmetic operations subscripting slicing defining methods special names but methods special names like len unicode seem provided benefit builtin functions rather support syntax presumably interfacebased python methods would turn regularlynamed methods abc len would become class container def lenself raise notimplemented though thinking i see syntactic operations invoke appropriate normallynamed method specific abc instance would presumably invoke objectlessthan perhaps comparablelessthan so another benefit would ability wean python away mangledname oddness seems hci improvement hm i sure i agree figure there two bits python rationale i like explain first first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something file write method saying thing another way i see len builtin operation i hate lose i say sure whether meant def lenself certainly sounds like want demote ordinary method i strongly the second bit python rationale i promised explain reason i chose special methods look special merely special i anticipating lots operations classes might want override standard eg add getitem standard eg pickle reduce long time support c code i want special operations use ordinary method names preexisting classes classes written users without encyclopedic memory special methods would liable accidentally define operations mean implement possibly disastrous consequences ivan krstiä‡ explained concise message arrived i written guido van rossum home page httpwwwpythonorgguido my understanding certain cases prefix notation makes sense ie duckquack makes sense quackduck linguistic standpoint functions allow interfaces in case guess would implement getkingmoves based solely guido first point but still leaves lot open questions regarding say implementing stack queue class similar push pop methods functions methods i would guess functions i really want signal pushpop interface tldr can someone explain strategy deciding use functions vs methods,2 yeah um works you comparing integer list printyou caught nothing elif printyou caught minnow points score,this part bigger problem i problems ifelif function def fish import random score randomrandint printyou caught nothing elif printyou caught minnow points score printi printscore fish when i run i get randint number score i exactly sure i wrong,3 you comparing integer list to trying one way range printyou caught nothing elif range printyou caught minnow points score,this part bigger problem i problems ifelif function def fish import random score randomrandint printyou caught nothing elif printyou caught minnow points score printi printscore fish when i run i get randint number score i exactly sure i wrong,1 instead configure withapxsusrlocalapachebinapxs withpythonusrlocalsharemanmanpython i would assume would want use configure withapxsusrlocalapachebinapxs withpythonusrlocalbinpython i think want tell modwsgi use path python executable rather man page,i want build modwsgi python i built source code ubuntu you see specifically i built how would i build python source code ubuntu i tried running within modwsgi directory sudo configure withapxsusrlocalapachebinapxs withpythonusrlocalsharemanmanpython probably pretty naive since i know python text file executable command probably expects i ended getting bunch permission denied messages even though i ran sudo so would i build modwsgi python built source code also inherent issues i expect future python i built default ubuntu python coexisting separate directories,1 first use easyinstall pip much reliable try installing see things go how install pip windows then install package search cmd search bar start menu run administrator pip install sqlalchemy,i trying install sqlalchemy project i tried different computers running windows vista identical python installations my first issue inability execute easyinstall computers different reasons next running included setuppy script work even running distributesetuppy running script command prompt python setuppy install finally trying manually run satopy script manually sqlalchemy folder work spat error message able find folder even given absolute path,3 in general process called stemming package called stemming python used like stemmingporter import stem stemsimpsons stemming stem plurals could modify stemming package perform plural stemming take look source httptartarusorgmartinporterstemmerpythontxt,i list strings bill simpsons cosbys cosby bills mango mangoes what best remove plurals list so i want output bill simpsons cosby mango,3 pluralization rules many corner cases perhaps bypass rules based approach use dictionary lookup identify plural form singular form word,i list strings bill simpsons cosbys cosby bills mango mangoes what best remove plurals list so i want output bill simpsons cosby mango,1 you define following function def lcountkeyword fname openfname r fin return sum line fin keyword line now want know number lines containing int foocpp print lcount int foocpp an alternative command line appropriate platform grep int foocpp wc l,i pretty sure i thinking simple outcome i seem put together i looking kind search method i like python script search text file keyword count many lines appears though keyword comes single line multiple times i like still count long story short if keyboard comes single line i want count line add math equation any help greatly appreciated thanks advance,1 iterate lists compare x rangelenseq rangelenseq ax seqx seqy,i two strings python i converted lists seq xxxx seq yyyy the strings length composed letters c g u then i created empty matrix lenseq lenseq numpyzerosshapelenseqlenseq next i want compare list values place values match the value placed relevant array element ie seq seq else repeat values print i loop working filled first row column i see problem range function like seqi seqj i figure,1 ok i see going docs if one groups present pattern return list groups list tuples pattern one group as turns group returning last occurrence group one solution surround entire regex group like regex recompile return tuple containing matched groups course care first one personally would use following regex regex recompile dd avoid matching stuff like bad number edit here way avoid surround expression parenthesis deal tuples regex recompile refinditerregex match print matchgroup finditer returns iterator use access matches found match objects research returns group returns result expect,i need find matches string given regex i using findall i came across case i expected for example regex recompile there bicycles beijing print researchregex sgroup print refindallregex in case search returns i need longest match findall behaves differently although docs imply findall matches occurrences pattern first one search why behaviour different how i achieve result search findall something else,3 the documentation pretty clear required httpcodegooglecompmodwsgiwikiquickinstallationguideconfiguringthesourcecode,i want build modwsgi python i built source code ubuntu you see specifically i built how would i build python source code ubuntu i tried running within modwsgi directory sudo configure withapxsusrlocalapachebinapxs withpythonusrlocalsharemanmanpython probably pretty naive since i know python text file executable command probably expects i ended getting bunch permission denied messages even though i ran sudo so would i build modwsgi python built source code also inherent issues i expect future python i built default ubuntu python coexisting separate directories,1 you indexing lst rate loop variable one list four elements list three elements you either going miss element one list try access nonexistent element list,i started learning python i problem wring specific function basically function update list adding interest rate lst rate output here i far def multiplylst rate rangelenlst lsti ratei lsti i getting error message typeerror multiply sequence nonint type float thank,1 lsti list numbers number you multiply list numbers number multiply elements list number,i started learning python i problem wring specific function basically function update list adding interest rate lst rate output here i far def multiplylst rate rangelenlst lsti ratei lsti i getting error message typeerror multiply sequence nonint type float thank,2 alephnull answer correctly explains causing problem i think i better solution use regex regex recompiler dd some reasons better noncapturing group get one result match dd better regex efficient less likely return false positives you always use python raw strings regexes possible less likely surprised regex escape sequences like b word boundary interpreted stringliteral escape sequences like b backspace,i need find matches string given regex i using findall i came across case i expected for example regex recompile there bicycles beijing print researchregex sgroup print refindallregex in case search returns i need longest match findall behaves differently although docs imply findall matches occurrences pattern first one search why behaviour different how i achieve result search findall something else,3 there two possible approaches make single bat file contains commands including regsvrexe commands execute have python script everything for first approach use open mode append batch file perhaps delete script start write contents three commands batch file within loop wind long batch file includes commands need then call subprocesscall command outside loop end script run entire thing for second approach remove batchfile writing run pathtoexe using python subprocesscall it almost simple deleting lines work output change outputwrite subprocesscall obviously fiddle contents little bit work subprocesscall directly,i exe file i call several parameters purpose i use bat file after i execute bat file command prompt close wait press key now i run exe several times i want run script path paths outout codecsopen runexebat w outputwritepathtoexe param param paramval param paramval param paramval param paramval outputclose subprocesscallregsvrexe path u subprocesscallregsvrexe path subprocesscallrunexebat paramval paramval paramval lists values related command prompt parameters when i call bat file everything works perfectly first fun exe executes command promt waits respond when i press key closes exe file starts different parameters so i want eliminate keypressing thing i tried put exit end bat file work how i close command prompt window script exe finishes working thanks advance upd sarmold way thing works fine i think exe console application waiting response smth exe file prevents console window closing i access sources how i close window executes upd i tried add shell call subprocesscall seem work either still respond console manually shell wincomclientdispatchwscriptshell shellappactivatecommand prompt shellsendkeysclsenter,1 any directory wish you use configuration import os sys projectroot ospathdirnamefile haystackwhooshpath ospathjoinprojectroot searchindex,requires setting haystackwhooshpath place filesystem whoosh index located can anyone explain exactly path pointing i mean give path,2 in view write sth like def myloginrequest app requestgetget app urlconf stays posted generally handle get parameters urlconf job views,i want url weibologinappfirst i want urlconf call view function parameters i know write url dispatcher pass appfirst view function the original urlconf urlpatterns patterns r weibologin weiboviewsmylogin the view function def myloginrequest i want pass appfirst view function eventually get dictionary function i know every parameter passed any good suggestions,2 general guidelines add base encodingdecoding step encrypted stuff import base baseencryptedmessage basebencodeencryptedmessage send message via post get seen system logs encryptedmessage basebdecodebaseencryptedmessage decrypt message for error try reading unicode amp utf encoding nonascii characters you need step passing deencrypt function,i trying pass encrypted query string another url the following code gives error unicodeencodeerror ascii codec encode character u ub position ordinal range the encryption module pycrypto running python app engine page a import crypto cryptocipher import arc objarcnew stackoverflow msg this secret msg encrypted objencryptmsg selfredirect pageb urlliburlencode q encrypted page b import crypto cryptocipher import arc encrypted selfrequestget q objarcnew stackoverflow decrypted objdecryptencrypted getdata cgiparseqsdecrypted selfresponseoutwritedecrypted selfresponseoutwritepprintpprintgetdata traceback traceback recent call last file cprogram filesgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlergetgroups file cprogram filesgooglegoogleappenginedemosguestbookguestbookpy line get decrypted objdecryptencrypted unicodeencodeerror ascii codec encode character u ub position ordinal range,3 if working windows use pywin i found example import wincomclient wmi wincomclientgetobject winmgmts usb wmiinstancesof winusbhub print usbdeviceid,how query connected usb devices info python i want get uid device name ex sonyericsson w path device ex devttyacm and also would best parameter info used identifying device whenever connected uid i working ubuntu atm i code using pyusb busses usbbusses bus busses devices busdevices dev devices print reprdev print device devfilename print idvendor xx devidvendor devidvendor print idproduct xx devidproduct devidproduct print manufacturer devimanufacturer print serial deviserialnumber print product deviproduct the problem i get desired output paste one example usblegacydevice object x device idvendor xfce idproduct xda manufacturer serial product first i get filename important i assuming devttyacm etc part second i guess uid every usb device i use vendor product id edit apparently i setup issues i think i using wrong usb library using libusb atm that i get device devfilename string empty if someone please tell operating system using usb library version pyusb i think solve problems,3 you try libusb bindings,how query connected usb devices info python i want get uid device name ex sonyericsson w path device ex devttyacm and also would best parameter info used identifying device whenever connected uid i working ubuntu atm i code using pyusb busses usbbusses bus busses devices busdevices dev devices print reprdev print device devfilename print idvendor xx devidvendor devidvendor print idproduct xx devidproduct devidproduct print manufacturer devimanufacturer print serial deviserialnumber print product deviproduct the problem i get desired output paste one example usblegacydevice object x device idvendor xfce idproduct xda manufacturer serial product first i get filename important i assuming devttyacm etc part second i guess uid every usb device i use vendor product id edit apparently i setup issues i think i using wrong usb library using libusb atm that i get device devfilename string empty if someone please tell operating system using usb library version pyusb i think solve problems,1 sorry i know i understand correctly but i think good ide automatic code validation also work django for example good python plugin eclipse called pydev there also good ide based eclipsepydev called aptana studio try also good support editing htmljscss this question also good comparison python ide,what tools techniques help avoid bugs especially silly mistakes typos coding python django i know unittesting every line code proper way shortcuts i know pylint unfortunately check django orm named parameters typo go unnoticed is tool handle kind bugs a colleague thought idea gather smart statistics tokens example named parameters functions onceinacodebase token encountered warned possible typo do know tool something similar,1 i think general correct approach two techniques could look eigenfaces name algorithms use eigenvectors facial recognition the bagofwords visual words approach,as selfdevelopment exercise i want develop simple classification algorithm given particular cell dilbert cartoon able identify characters present cartoon dilbert phb ratbert etc i assume best way apply algorithm image converts set features use training set one many possible machine learning algorithms correlate presenceabsence certain features particular character present cell so questions correct approach b since number classification algorithms ml algorithms test good methodology finding right one c algorithms would start given essentially conducting classification exercise cartoon,1 pyflakes static analyser find undeclared variables eg typos like plenty editors plugins run pyflakes fly save this substitute unit tests save unnecessary savereloadrun cycles,what tools techniques help avoid bugs especially silly mistakes typos coding python django i know unittesting every line code proper way shortcuts i know pylint unfortunately check django orm named parameters typo go unnoticed is tool handle kind bugs a colleague thought idea gather smart statistics tokens example named parameters functions onceinacodebase token encountered warned possible typo do know tool something similar,1 anydbm module dbdbmgdbm type files it work sqlite they thing file format use sqlite module sqlite databases,i db file created sqlite i want use anydbm read file my code import anydbm db anydbmopen mydbdb r however throws error anydbmerror db type could determined i get what wrong the file type according unix file command sqlite x does anybody know causing also better library reading db files thanks,2 try committing closing connection curclose conncommit connclose from psycopg documentation note closing connection without committing changes first cause pending change discarded rollback performed unless different isolation level selected see setisolationlevel,i trying call function psycopg like conn psycopgconnecthostnamehostex userusername passwordsecret cur conncursor curcallprocfdoaction aaa bbb curclose connclose when calling function psql everything works fine using psycopg nothing seems happen i get exception it call function actual database also queries psycopg work select insert,3 you might like consider rabbitmq amqp message broker amqp protocol designed build messaging queuing routing systems there several python clients connecting amqp brokers,i developing system queue filled millions items i need process reads items queue constantly sends items registered clients i thinking using twisted queue reader twisted server listening tcp port clients connect port item pulled queue server writes clients does sound like something twisted would ideal does anyone know sample code may something similar,1 i gotten rc interface work piped stdinstdout windows i get ioerror attempts communicate write directly stdin there option rcfaketty lets rc interface scripted linux available windows least somewhat dated version vlc using socket interface hand seems work fine the structure assigned startupinfo option used win createprocess function configured hide process window however vlc rc console i think simpler use existing rcquiet option in general configure startupinfo hide process window startupinfo subprocessstartupinfo startupinfodwflags subprocessstartfuseshowwindow subprocesspopencmd startupinfostartupinfo just complete case using pipes failing system little demo i cooked using rchost option communicate using socket it also uses rcquiet hide console this prints help quits i tested anything else i checked works python versions i know ask maybe useful nonetheless import socket import subprocess select import select try import winreg except importerror import winreg winreg try vlcpath winregqueryvalueex winregopenkeywinreghkeylocalmachine r softwarevideolanvlc except windowserror exiterror vlc found def sendcommandsock cmd getresultfalse try cmd cmd n encode ascii except attributeerror cmd b n sent total socksendcmd total lencmd sent socksendcmdtotal sent raise socketerror socket connection broken total sent getresult return receiveresultsock def receiveresultsock data bytearray socksetblocking selectsock chunk sockrecv chunk b raise socketerror socket connection broken dataextendchunk socksetblocking return datadecode utf def mainaddress port import time rchost formataddress port vlc subprocesspopenvlcpath i rc rchost rchost rcquiet sock socketsocketsocketafinet socketsockstream try sockconnectaddress port helpmsg sendcommandsock help true printhelpmsg sendcommandsock quit except socketerror e exiterror eargs finally sockclose timesleep vlcpoll none vlcterminate name main main localhost,i using windows vista python answers python so i start interact subprocesses stdinstdout normally using python commandline programs dir however program i want call likes make new console window windows curses new handles even run preexisting cmdexe window odd remote control interface vlc is way either getting handles processmade console stdinout getting new shell run within old like invoking bash within bash failing i hack subprocesses code would new console set windows inoutput transferred edit ie p popenargs vlc i rc stdinpipestdoutpipe new console appears text asking commands pstdinwritequitrn traceback file stdin line module ioerror errno invalid argument pstdoutreadline pstdoutreadline but new console window comes accept keyboard input either whereas normally p popenargs cmd stdinpipestdoutpipe pstdinwritedirrn pstdinflush pstdoutreadline don irl may block microsoft windows version,1 your data structure dictionary dictionaries first place njnkjkn embeddedlist jbbhjhb embeddedlist this make desired operations much easier if inner dictionaries contain embedded list simplified njnkjkn jbbhjhb now need collectionsdefaultdictlist collections import defaultdict defaultdictlist njnkjkn appendwhatever,i attempting create list dicts following structure id njnkjkn embeddedlist id jbbhjhb embeddedlist initially list empty what i need able check see dict specific id exists list already if dict containing id exists append something embeddedlist if dict containing id exist create dict append list i aware able test dict exists list based something inside dict using something like extracteddict nextitem item list item id uniqueid none i unsure append something list within dict within list efficiently is obvious way i seeing probably thank advance,2 simple dic njnkjkn jbbhjhb,i attempting create list dicts following structure id njnkjkn embeddedlist id jbbhjhb embeddedlist initially list empty what i need able check see dict specific id exists list already if dict containing id exists append something embeddedlist if dict containing id exist create dict append list i aware able test dict exists list based something inside dict using something like extracteddict nextitem item list item id uniqueid none i unsure append something list within dict within list efficiently is obvious way i seeing probably thank advance,1 if want rely extra installed modules parse output wmic eg c wmic process get descriptionexecutablepath explorerexe cwindowsexplorerexe cmdexe cwindowssyswowcmdexe conhostexe cwindowssystemconhostexe reference httpgeekpediawordpresscomusecommandlinetotrackwindowsprocesses,i amm writing little python script grab information vms windows i running at moment i list processes bit xp machine following method httpcodeactivestatecomrecipes is possible somehow detect version windows running excute different method getting processes bit machine i trying get processes bit vista bit windows any ideas,3 it easy install manually download may newer releases pythonorg wget httpswwwpythonorgftppythonpythontarxz unzip tar xf python cd python prepare compilation configure build make install make install or want overwrite python executable safer least distros yum needs python x rhel install python concurrent instance system default altinstall make altinstall now want alternative installation directory pass prefix configure command example installing python optlocal add prefixoptlocal after make install step in order use new python installation could still add prefixbin path prefixlib ldlibrarypath depending prefix passed,i trying install python rhel using following steps yum search python which returned no matches found python followed yum search python none search results contained python what i try next,3 try setting environment variable pythonioencoding utf that make python use encoding instead none default,i using php i trying learn python i never really serious problem encoding php at least i could solve minutes i spent hours solve encoding problems python i still solve so problem i want print japanese string file using shell redirect using command python makecsvpy csvfilecsv but japanese texts printed csv file messed i tried several solutions like using encode utf etc still luck i also encounter error unicodedecodeerror ascii codec decode byte xe position ordinal range i solve please help,1 change wind tkintertk wind tkintertoplevel def new wind tkintertoplevel windgeometry x that need change reference tkinter toplevel,i message image pyimage exist i want multi windows images here code import image import imagetk import tkinter def new wind tkintertk windgeometry x this work imagefile imageopensomeimagejpg image imagetkphotoimageimagefile panel tkinterlabelwind imageimage panelplacerelx rely windmainloop master tkintertk mastergeometry x this work fine imagefile imageopensomeimagejpg image imagetkphotoimageimagefile panel tkinterlabelmaster imageimage panelplacerelx rely b tkinterbuttonmaster text new image command newpack mastermainloop,2 you need use redotall flag allow capture newline characters also escape braces special characters python regex syntax researchrbook pagetext redotall,in python i big text multline i need get text book i tired using regular expression problem text inside mutiline string i tried book gives text first line i tried book gives error researchbook pagetextgroup i tried varied expression problem go next line regular expression lot text book series name twilight image filethe twilight saga hardbackjpgpx language english do link per wp overlink genre romance novelromance fantasy literaturefantasy youngadult fiction publisher little brown company pubdate ã¢â‚¬â€œ mediatype print lot text,1 that good question i afraid answer might matplotlib gtk backend written pygtk oldstyle python bindings gtk the girepository package newstyle python bindings i know one way whether mix results seem indicate,i troubles understanding girepository i use contruction code girepository import gtk but i want use component i get import error i searched i got worked components like gtksource vte glib so code like girepository import gtk gtksource vte glib everything worked fine i want add matplotlib draw canvas i get error enter codeusrlibpythonsitepackagesgtkgtkinitpy warning specified class size type pygtkgenericcellrenderer smaller parent type gtkcellrenderer class size gtk import gtk usrlibpythonsitepackagesgtkgtkinitpy warning gtypegetqdata assertion node null failed gtk import gtk usrlibpythonsitepackagesgtkgtkinitpy warning gasciistrncasecmp assertion null failed gtk import gtk segmentation fault core dumped how i get matplotlib working girepository thank,3 l b c newl jj j l newl b c this works python python need newl jj j l these list comprehensions equivalent following verbose code newl l temp j tempappendjj newlappendtemp,i list like following mylist b c i got different operations code is possible get output like following newlist b c the input list contents ranges output list generated taking average two numbers range thank,2 to work one lists valid python portion could use list comprehension numbers print sumx floatlenx x numbers this get right direction gives,i list like following mylist b c i got different operations code is possible get output like following newlist b c the input list contents ranges output list generated taking average two numbers range thank,1 list comprehensions nice favorite pythonic technique map applies function every element structure ls b c li ls printli listmaplambda x sumxlenx li as tim says works python need floatlenx python,i list like following mylist b c i got different operations code is possible get output like following newlist b c the input list contents ranges output list generated taking average two numbers range thank,2 you need look tail property well text text gives text directly start tag tail gives text directly end tag this provide many small strings tip use etreeiterwalkelem thing etreeiterparse existing tree instead iterate start end tags to idea event elem etreeiterwalkxmlelem events start end event start start tag print starting element elemtag print elemtext elif event end end tag print ending element elemtag elem xmlelem dont want text trailing xmlelem print elemtail i guess complete rest warning text tail none want concatenate guard use elemtext example if familiar sax existing sax code need lxml lets produce sax events element tree lxmlsaxsaxifyelem handler some things look extracting text element itertext method xpath expression text lxml lets return smart strings xpath expressions allow check element belong etc,i xml data looks like xml the captial place pidsouth africaplace placepretoriaplace xml i would like able extract the xml elements currently provided etree the full plain text document start end tags the location within plain text start element character offset important requirement right etree provides fine i cannot see way directly hoped iterating elements document tree would return many small string could reassembled thus providing however requesting text root node returns text root node first element eg the capital doing sax could involve implementing lot already written many times eg minidom etree using lxml option package code go can anybody help,1 i think windows supports shebang line try invoking python djangoadminpy,run djangoadminpy startproject mysite djangoadminpy located cpythonscriptsdjangoadminpy open file editor opens python ide past pype would open pype file opens cpythonpythonexe djangocore import management name main managementexecutefromcommandline see output command prompt lets say typed cabcdjangoadminpy startproject mysite i hit enter see cabc project created using command prompt issue new creating python projects using pydev would love fix issue command prompt though slugonamission i run pyhon djangoadminpy startproject mysite output command prompt python open djangoadminpy file errno no file directory,3 so think right track wrt step apply algorithm image converts set features this project challenging ml problems actually create training data set raw data individual frames comprising cartoons for instance grab frame identify two characters frame dilbert character horns dilbert boss believe know name extract two characters frame append appropriate class label eg dlibert step to extract individual characters frames comprising dilbert cartoon would suggest spectral decomposition frame if familiar technique core eigenvector decomp if like python r given use pythontor bindings like rpy would strongly encourage look sklearn in particular excellent library originally developed scipy scikits project umbrella therefore uses numpy scipy matrix computation several algorithms image segmentation one based spectral clustering for step project would likely want look two scikitslearn modules sklearnfeatureextraction esp image submodule sklearnclusterspectralclustering included two modules two good example scripts one segmenting digital photograph segmenting image comprised three partially superimposed circles minimal contrast wrt wrt backgroundboth suspect difficult problems decompositions need perform in words sklearn two complete welldocumented example scripts included source distribution process data similar either would excellent template step step so first step second sort components decomposed images groups one group dilbert character next assign class label group eg four characters decomposition step decent choice class labels append class labels component matrices decomposition products step character matrix mapped corresponding class dilbert character step select suitable ml technique you many choices step criteria technique supervised category assigned class labels data function classifier ie returns class label versus regressor outputs numerical value given personal project would chose one seems interesting a satisfy criteria mentioned multilayer perceptron neural network support vector machine svm knearest neighbors knn step train validate test classifier alternative technique template matching once step completed image decomposed set objects doubt represent characters manually sift decomposition products collect exemplars character cartoon the templates next compare objects segmented image set unique templates in scikitimage another scipy scikit use method matchtemplate pass template image candidate image method returns d array showing pixelbypixel correlation,as selfdevelopment exercise i want develop simple classification algorithm given particular cell dilbert cartoon able identify characters present cartoon dilbert phb ratbert etc i assume best way apply algorithm image converts set features use training set one many possible machine learning algorithms correlate presenceabsence certain features particular character present cell so questions correct approach b since number classification algorithms ml algorithms test good methodology finding right one c algorithms would start given essentially conducting classification exercise cartoon,3 even unix shebang forcing version run if program executed directly mypy instead run like python mypy python still used i would suggest safest way check version beginning script bail error message suitable example sysversioninfo print requires python sysexit,i know write python script tell unix box version python run usrbinenv python i windows i deploying program distutils windows boxes python installed i need force use thanks,2 files designated static appyaml available application code python runtime they served directly user browser response requests matching regular expression appyaml do mark templates static only files served asis user javascript css images marked static,i problem using template google app engine python thing i address static folder yaml i not access template i remove access able look files file structure src calcpy mainpy indexhtml templ calchtml js css yaml handlers url script mainpy mainpy def main application webappwsgiapplication mainpage calc calc debugtrue wsgirefhandlerscgihandlerrunapplication calcpy class calcwebapprequesthandler def getself temp ospathjoinospathdirnamefile templcalchtml outstr templaterendertemp tempval selfresponseoutwriteoutstr the result is status ok contenttype texthtml charsetutf i reach file template addressing working buttttttt i add following line yaml access css js it access able yaml handlers url script mainpy url templ staticdir templ if change order yaml handlers url templ staticdir templ url script mainpy both not working error status internal server error traceback recent call last file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebappwebapppyquot line call handlergetgroups file quotusersemdocumentsworkspacenerkharzsrccalcpyquot line get outstr templaterendertemp tempval file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line render loadtemplatepath debug file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line load return loaduserdjangopath debug file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line loaduserdjango template djangotemplateloadergettemplatefilename file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangotemplateloaderpyquot line gettemplate source origin findtemplatesourcetemplatename file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangotemplateloaderpyquot line findtemplatesource raise templatedoesnotexist name templatedoesnotexist calchtml please help must simple solution i really dont believe gae much fool thank advanced,2 almost although would still possible path like foo better would use ospathjoin ospathabspath together correctly handle leading anywhere path targetdir target trailing slash important tarfileopen… tarf n tarfnames ospathabspathospathjointargetdir nstartswithtargetdir print unsafe filenames sysexit tarfextractallpathtargetdir,in python documentation adviced extract tar archive without prior inspection what best way make sure archive safe using tarfile python module should i iterate filename check wether contain absolute pathnames would something like following sufficient import sys import tarfile tarfileopen sampletar r tarf n tarfnames n n print sampletar contains unsafe filenames sysexit tarfextractall edit this script compatible versions prior cf tarfile i iterate members targetdir target closingtarfileopen sampletar mode rgz tarf tarf pathn ospathabspathospathjointargetdir mname pathnstartswithtargetdir print the tar file contains unsafe filenames aborting sysexit tarfextractm pathtdir,2 you using assertraises incorrectly instead write selfassertraisesintegrityerror adduser userdetail userdetail you give function arguments separately assertraises control function called eg tryexcept block assertraises the problem function test swallowing error try def adduseruserdetails try u useruserdetails sessionaddu sessioncommit except sessionrollback raise reraise exception allowing transaction rolled back,i trying unit test sqlalchemy code def adduseruserdetails try u useruserdetails sessionaddu sessioncommit except sessionrollback now unit test def testduplicateself adduseruserdetailuserdetail selfassertraisesintegrityerror adduseruserdetailuserdetail this test succeed adduser function call raises integrity error fail exception but problem test succeeds cases why happening is something wrong code assertraises works differently i expecting atfirst i thought happening i put except try clause exception dealt assertraises get exception but would case assertraises failed receiving exception if something wrong way writing unit test tell i still learning incorporate unit testing coding habits,2 it bug httpcodegooglecompgoogleappengineissuesdetailid hopefully corrected next version,i trying make change old appengine application formating pc installing updated tools logging functions raising unicode error in previous development environment everything worked fine ubuntu python google appengine sdk now i trying make change using environment ubuntu python google appengine sdk in new development environment i getting errors using logging functions logginginfou gerando lista de exibiã§ã£o error error ascii codec decode byte xc position ordinal range args ascii gerando lista de exibixcxaxcxao ordinal range encoding ascii end message object gerando lista de exibixcxaxcxao reason ordinal range start to work i need remove accents logginginfou gerando lista de exibicao ok my editor utf scripts coding utf first line this version problem there settings,2 would probably override form init method take user argument set somewhere form class myform def initself user args kwargs supermyform selfinitargs kwargs selfuser user def cleanfield selfuser etc,as part form validation django i want check user last made post i look question stackoverflow appear address issue initially used accepted answer essentially process moment add requestuser object def formvalidself form method createview subclass however allow user variable used form validation since i want access user variable validation check time since last post logically validation i need user variable injected form earlier i tried altering getinitial method def getinitialself initial superarticlecreateview selfgetinitial initial user selfrequestuser return initial this successfully sets user key initial dictionary never makes cleaning process deals stuff data dictionary removes anything initial i deliberately excluded user form display appears also remove cleaning process validation is correct way override init method form getinitial method view putting user initial form pulling extra information initial form init i looking pass requestuser form i access within formwide clean method additional checks amount validation def cleanself superarticleform selfclean check whether user posted recently raise validationerror return selfcleaneddata j,1 the way i solved moment keep validation within form rest business logic view consequently i done following in view def getinitialself initial supermycreateview selfgetinitial initial user selfrequestuser return initial in form def initself args kwargs selfuser kwargs initial user supermyobjectform selfinitself args kwargs def cleanself clean submitted data supermyobjectform selfclean validate user submitted n time ago profile selfusergetprofile datetimenow profilelastpost timedeltahours raise formsvalidationerrorneed wait longer n hours else selfcleaneddata user selfuser return selfcleaneddata which seems work flaws i seen solution,as part form validation django i want check user last made post i look question stackoverflow appear address issue initially used accepted answer essentially process moment add requestuser object def formvalidself form method createview subclass however allow user variable used form validation since i want access user variable validation check time since last post logically validation i need user variable injected form earlier i tried altering getinitial method def getinitialself initial superarticlecreateview selfgetinitial initial user selfrequestuser return initial this successfully sets user key initial dictionary never makes cleaning process deals stuff data dictionary removes anything initial i deliberately excluded user form display appears also remove cleaning process validation is correct way override init method form getinitial method view putting user initial form pulling extra information initial form init i looking pass requestuser form i access within formwide clean method additional checks amount validation def cleanself superarticleform selfclean check whether user posted recently raise validationerror return selfcleaneddata j,1 write function query single float call twice def inputfloatmsg true try return floatrawinputmsg except valueerror pass zacatek inputfloatzacatek konec inputfloatkonec,i little problem try statement along multiple conditions when error nd condition asks st condition what i want repeat condition whole cycle i hope understand since english good also i newbie python i also know describe native language i hope following example help better understand thought true try zacatek floatrawinputzacatek konec floatrawinputkonec except exception pass else break following zacatek konec zacatek i want zacatek konec konec thanks advance help,3 itertoolsgroupby provides easy way collect lines groups import itertools data open datatxt r f keygroup itertoolsgroupbyflambda line linestartswith meta key metanextgroupstrip else lines joingroupstrip dataappendmetalines printdata yields meta data skadjflaskdjfasljdfalskdjflnsdkfjhasdlkgjhsdlkjghlaskdjnasdhfk meta data jflaksdjflaksjdflkjasdlfjasnldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf the expression itertoolsgroupbyflambda line linestartswith meta returns iterator it loops lines f calls lambda function line when encounters line begins meta function returns true otherwise false itertoolsgroupby collects contiguous lines return value so line begins meta placed group subsequent lines beginning meta placed next group the key return value lambda function in case either true false,i file mb looks like meta data skadjflaskdjfasljdfalskdjfl sdkfjhasdlkgjhsdlkjghlaskdj asdhfk meta data jflaksdjflaksjdflkjasdlfjas ldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf this file contains one row meta data corresponds several variable length data containing alphanumeric characters what best way read data simple list like data meta data skadjflaskdjfasljdfalskdjflsdkfjhasdlkgjhsdlkjghlaskdjasdhfk meta data jflaksdjflaksjdflkjasdlfjasldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf my initial idea use read method read whole file memory use regular expressions parse data desired format is better pythonic way all metadata lines start octothorpe data lines alphanumeric thanks,2 i know whether fastest way top head data open inputfile r fp line fp line linestrip line dataappendline else dataappendline data x joiny x y data,i file mb looks like meta data skadjflaskdjfasljdfalskdjfl sdkfjhasdlkgjhsdlkjghlaskdj asdhfk meta data jflaksdjflaksjdflkjasdlfjas ldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf this file contains one row meta data corresponds several variable length data containing alphanumeric characters what best way read data simple list like data meta data skadjflaskdjfasljdfalskdjflsdkfjhasdlkgjhsdlkjghlaskdjasdhfk meta data jflaksdjflaksjdflkjasdlfjasldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf my initial idea use read method read whole file memory use regular expressions parse data desired format is better pythonic way all metadata lines start octothorpe data lines alphanumeric thanks,1 not clear exactly asking i know mean version but idle meaning open shell looks something like python r jul msc v bit intel win type copyright credits license information you either create new window file new ctrln windows save file you also use editor instead idle emacs notepad vim etc save file if want keep log shell activity executable script also save idle file menu,currently i working python interactive shell version when start python shell use code line know store code so command keyword save session python shell like py,1 it looks like problem regex double quotes without works fine sample string more anotherstring n import researchr smores samplegroups more fwiw great resource developing regex directly sample string httptxtrecom another good resource learn regular expressions httpwwwregularexpressionsinfo,i file following grammar whitespacesequencestringwhitespacesequencemorewhitespacesequencestringsequencenewline using python i would like remove sequence whitespacesequencemorewhitespacesequence grammar i using following regex pattern x recompilesmores matching sequence i need remove,1 you override getformkwargs method createview articlecreateview case pass user form def getformkwargsself kwargs superarticlecreateview selfgetformkwargs kwargs user selfrequestuser return kwargs override form init method def initself args kwargs selfuser kwargspopuser now use selfuser clean method,as part form validation django i want check user last made post i look question stackoverflow appear address issue initially used accepted answer essentially process moment add requestuser object def formvalidself form method createview subclass however allow user variable used form validation since i want access user variable validation check time since last post logically validation i need user variable injected form earlier i tried altering getinitial method def getinitialself initial superarticlecreateview selfgetinitial initial user selfrequestuser return initial this successfully sets user key initial dictionary never makes cleaning process deals stuff data dictionary removes anything initial i deliberately excluded user form display appears also remove cleaning process validation is correct way override init method form getinitial method view putting user initial form pulling extra information initial form init i looking pass requestuser form i access within formwide clean method additional checks amount validation def cleanself superarticleform selfclean check whether user posted recently raise validationerror return selfcleaneddata j,2 if want really good windows support i suspect might need find easier use different api windows check links httppeoplecsailmiteduhubertpyaudio crossplatform httpffmpegorgffmpeghtml crossplatform httpwwwcodeprojectcomkbaudiovideompexampleaspx windowsspecific httpmsdnmicrosoftcomenuslibrarywindowsdesktopddvvsaspx windowsspecific edit probably solution far comments pretty positive another option httpwwwunseencombasshtml beware commercial asked free use noncommercial applications python wrapper called pybass,im coding music player python using pyqt i wanted feature mono playback mp files i accomplished using pygame mixer specific parameter channels i set get mono playback however pygame mp support limited i searching library able handle mp files and mono playback currently i using pyaudiere playback site example processing song playing maybe i could turn song mono i really idea accomplish i like help code feature using pyaudiere library handle mp files edit i would also accept solution c i always build python wrapper using boostpython,2 itertoolspermutations simply works way it takes arbitrary iterable argument always returns iterator yielding tuples it specialcase strings to get list strings always join tuples listmapjoin itertoolspermutations,why itertoolspermutations return list characters digits permutation instead returning string for example printx x itertoolspermutations why return,3 because expects iterable parameter know string the parameter described docs httpdocspythonorglibraryitertoolshtmlitertoolspermutations,why itertoolspermutations return list characters digits permutation instead returning string for example printx x itertoolspermutations why return,3 use selfstatusbarsetstatustext text fieldnumber,how i make statusbar show specific text without hover one menubar items i want make mp player i building able output currently playing file statusbar,2 the strsplit method without argument splits whitespace many fancy word nhello thisplit many fancy word hello hi,i looking python equivalent string str many fancy word nhello thi string whitespaceregex string words strsplitwhitespaceregex many fancy word hello hi,3 import many fancy word nhello thi resplit,i looking python equivalent string str many fancy word nhello thi string whitespaceregex string words strsplitwhitespaceregex many fancy word hello hi,3 first get know json module the native json module work appengine import djangoutilssimplejson json then format json objects python dicts obj name foo age then use jsondumps get str object represents json object jsonobj jsondumpsobj jsonobj string write using conventional methods try interactive interpreter after read page info templates webapp framework i use django i sure webapp uses templating system though looks similar better read if talking jquery ajax post generate xhtmlxmlwhatever server side unless course causing postpost url loaded iframe if answer wanted clarify question bit and unlikely imo anyone would post answer code jsfiddle,i done jquery post successfully however order get data returned server side can anyone gives example done google app engine python using webapp framework if possible i need example how send json data template from template access json jquery post success function i would appreciate much anyone could post httpjsfiddlenet,2 you need pass self instantiating class assignmentself name discription deadline grade studentid assignmentname discription deadline grade studentid the error letting know trying use var self defined either local global scope,im trying learn classes something holding em back get nameerror global name self defined happens class field help find wrong thank code class assignment def initself name discription deadline grade studentid selfname name selfstudentid studentid selfdescription discription selfdeadline deadline selfgrade grade def strself return studentid selfstudentid assignment name selfname description selfdescription deadline selfdeadline grade selfgrade def validationself errors selfstudendid errorsappendno existing student id selfdescription errorsappendno existing description selfdeadline errorsappendno existing deadline selfdeadline errorsappendno existing deadline return errors staticmethod def dummyassignments ret studentid range print sda assignmentself name discription deadline grade studentid retappenda return ret def testassigment assignment print testassigment print assignmentdummyassignments,2 the problem assignmentself name discription deadline grade studentid this staticmethod self defined indeed none values defined come think except studentid,im trying learn classes something holding em back get nameerror global name self defined happens class field help find wrong thank code class assignment def initself name discription deadline grade studentid selfname name selfstudentid studentid selfdescription discription selfdeadline deadline selfgrade grade def strself return studentid selfstudentid assignment name selfname description selfdescription deadline selfdeadline grade selfgrade def validationself errors selfstudendid errorsappendno existing student id selfdescription errorsappendno existing description selfdeadline errorsappendno existing deadline selfdeadline errorsappendno existing deadline return errors staticmethod def dummyassignments ret studentid range print sda assignmentself name discription deadline grade studentid retappenda return ret def testassigment assignment print testassigment print assignmentdummyassignments,3 the dummyassignments static method studentids fields try giving default values fields class assignment def initself name discription deadline grade studentid selfname name selfstudentid studentid selfdescription discription selfdeadline deadline selfgrade grade def strself return studentid selfstudentid assignment name selfname description selfdescription deadline selfdeadline grade selfgrade def validationself errors selfstudendid errorsappendno existing student id selfdescription errorsappendno existing description selfdeadline errorsappendno existing deadline selfdeadline errorsappendno existing deadline return errors staticmethod def dummyassignments ret studentid range print sda assignmentstudentidstudentid retappenda return ret def testassigment assignment print testassigment print assignmentdummyassignments,im trying learn classes something holding em back get nameerror global name self defined happens class field help find wrong thank code class assignment def initself name discription deadline grade studentid selfname name selfstudentid studentid selfdescription discription selfdeadline deadline selfgrade grade def strself return studentid selfstudentid assignment name selfname description selfdescription deadline selfdeadline grade selfgrade def validationself errors selfstudendid errorsappendno existing student id selfdescription errorsappendno existing description selfdeadline errorsappendno existing deadline selfdeadline errorsappendno existing deadline return errors staticmethod def dummyassignments ret studentid range print sda assignmentself name discription deadline grade studentid retappenda return ret def testassigment assignment print testassigment print assignmentdummyassignments,1 i problem netbeans starting netbeans first errored error message then start give error i looked netbeans directory user directory found attempted delete lock file directory when i first tried delete said use so task manager i go processes tab find netbeans i killed task able delete lock then netbeans started,i went tools plugins then chose install three python items show after installation i choose restart netbeans option but instead restarting netbeans closed and opening any ideas fix i normally develop java netbeans install i using mac osx i see takers let ask is way revert new plugin install,1 v absyx v x v edit for pretty printing use something like print leni tuplei,i vector int values like v i want create mm matrix stores distance elements ie take element vector substract ones end i end i want implement python without using numpy i done far def main v llenv filling matrix rangel j rangel mijabsvivj visualize matrix rangel j rangel print mij but i getting error recognize bounds why,2 i found prepending cflagsilocal include dir ldflagsllocal lib dir command line calling setuppy trick,i trying install python module contains c modules the c code relies library available system global install locations usrinclude usrlib case i local installation lib available therefore i would like pass parameters eg incdir libdir calling setuppy build values end setup script is way achieve,3 you probably use builtin bulkloader tool download objects via remote api save selected fields csv format,i want commaseparated list email addresses application stores it large regular request writing blobstore also large request class csvhandlerwebapprequesthandler def getself entities entityallfetch entity entities sstrentityemail filename filesblobstorecreatemimetype applicationoctetstream filesopenfilename f fwrites filesfinalizefilename blobkey filesblobstoregetblobkeyfilename can i task queue backend something else instead thank advance suggestion,1 you need make list row inside enveloping list i used double list comprehension make made formatting little prettier printing matrix also watch indices remember range goes first index one minus second index passed you could also print joinrow row print nicely def main v llenv filling matrix mabsx v x v visualize matrix rangel j rangel print mij print main result,i vector int values like v i want create mm matrix stores distance elements ie take element vector substract ones end i end i want implement python without using numpy i done far def main v llenv filling matrix rangel j rangel mijabsvivj visualize matrix rangel j rangel print mij but i getting error recognize bounds why,1 after running following defaults write comappleversionerpython version to make sure packages install sudo installed correct python version also set versioner option superuser sudo su enter password defaults write comappleversionerpython version exit,i upgraded lion came python i need use default python project i primarily work uses,2 when enter nonunicode string literal python interactive session system default encoding assumed it appears using windows default encoding therefore probably cp cp cpython python default jun msc v bit intel win type help copyright credits license information import sys sysstdinencoding cp olã¡ mundo olxa mundo u olã¡ mundo encode cp olxa mundo if change codepage roughly equivalent latin strings display expected cchcp active code page cpython python default jun msc v bit intel win type help copyright credits license information import sys sysstdinencoding cp olã¡ mundo olxe mundo,i facing huge encoding problem python dealing iso latin character set when using oslistdir get contents folder i getting strings encoded iso ex olxe mundo however python interpreter string encoded different charset in olã¡ mundo decode latin out u olxa mundo how i force python decode string format i seen oslistdir returning strings correctly encoded interpreter ã¡ character corresponds xe iso xa httpenwikipediaorgwikiisoiec any thoughts overcome,2 your list starts empty you index element list one way solve would create lists append filling matrix rangel x j rangel xappend absvivj mappendx or could create matrix fill l x rangel filling matrix rangel j rangel mijabsvivj better yet list comprehension shown absyx v x v i use numpyscipy scipyspatialdistancepdistv,i vector int values like v i want create mm matrix stores distance elements ie take element vector substract ones end i end i want implement python without using numpy i done far def main v llenv filling matrix rangel j rangel mijabsvivj visualize matrix rangel j rangel print mij but i getting error recognize bounds why,1 i found using rather localhost worked ab n c http update may bug ab httpsgroupsgooglecomforummsgnodejstzuhmdoiiyivudlmaaj,i testing eventlet i getting error ab n c httplocalhost this apachebench version revision copyright adam twiss zeus technology ltd httpwwwzeustechnet licensed the apache software foundation httpwwwapacheorg benchmarking localhost patientaprsocketrecv connection reset peer total requests completed the website works localhost returns ok i issue tomcat website worked fine what could issue,3 try using pylibmc memcache driver rather using pythonmemcache i seen issue memcache ubuntu well,i discovered issue trying store lot keys using pythonmemcached here i import memcache this dict entries generated production server v evalopenhomedragoonoutputread memcacheclient unixtmpmemcachedsock debug next i trying set values in lenasetmultiv memcached memcache unixtmpmemcachedsock timed marking dead out the log output memcached server going connnewcmd connparsecmd set dbdeafcaaaff going connparsecmd connnread found key dbdeafcaaaff stored going connnread connwrite failed write due blocking broken pipe going connwrite connclosing connection closed after time in lenasetmulti test out in aget test out default timeout seconds increasing even seconds help memcached getting stucked so question problem memcache i saw people talking storing entries even store,1 yes use pyexe ask questions specific problems,i scrapy script working fine to distribute friends i need executable know much scrapy would someone tell turn scrapy script exe file is pyexe applicable regard,1 instead trying save entire file single write operation write blobstore chunks using csv module make easier allowing write progressively,i want commaseparated list email addresses application stores it large regular request writing blobstore also large request class csvhandlerwebapprequesthandler def getself entities entityallfetch entity entities sstrentityemail filename filesblobstorecreatemimetype applicationoctetstream filesopenfilename f fwrites filesfinalizefilename blobkey filesblobstoregetblobkeyfilename can i task queue backend something else instead thank advance suggestion,1 your problem wrote j instead last line j listex listex j print listexindexi however better approach use enumerate item listex item enumeratelistex item item print,listex cat select brown dog turtle apple listex hampter bird monkey banana cat j listex listex j print listexindexj what i trying accomplish search items listex listex if item listex found listex i would like know print index value item found listex listex thanks,2 there problems code not images px x px trying add image list contain x images to solve scale x adding list you assign image list tree object applying images tree items here fixed code import wx class testframewxframe def initself wxframeinitself none selftree wxtreectrlself style wxtrhideroot selfroot selftreeaddroot gr selftreeappenditemselfroot grooveshark popr selftreeappenditemgr popular sr selftreeappenditemgr search dr selftreeappenditemselfroot download pr selftreeappenditemselfroot pandora statr selftreeappenditempr stations imagelist wximagelist grooveshark imagelistaddwximageimagesgrooveshark custompng wxbitmaptypepngscaleconverttobitmap popular imagelistaddwximageimagespopular custompng wxbitmaptypepngscaleconverttobitmap search imagelistaddwximageimagessearch custompng wxbitmaptypepngscaleconverttobitmap download imagelistaddwximageimagesdownload custompng wxbitmaptypepngscaleconverttobitmap pandora imagelistaddwximageimagesplaylisticon custompng wxbitmaptypepngscaleconverttobitmap stations imagelistaddwximageimagesstations custompng wxbitmaptypepngscaleconverttobitmap selftreeassignimagelistimagelist selftreesetpydatagr none selftreesetitemimagegr grooveshark wxtreeitemiconnormal selftreesetpydatapopr none selftreesetitemimagepopr popular wxtreeitemiconnormal selftreesetpydatasr none selftreesetitemimagesr search wxtreeitemiconnormal selftreesetpydatadr none selftreesetitemimagedr download wxtreeitemiconnormal selftreesetpydatapr none selftreesetitemimagepr pandora wxtreeitemiconnormal selftreesetpydatastatr none selftreesetitemimagestatr stations wxtreeitemiconnormal name main wxappfalse f testframe fshow amainloop,ok i example runable example example extract zip files run otherwise work however run images added tree ctrl simply error code note run without images see zip file import wx class testframewxframe def initself wxframeinitself none selftree wxtreectrlself style wxtrhideroot selfroot selftreeaddroot gr selftreeappenditemselfroot grooveshark popr selftreeappenditemgr popular sr selftreeappenditemgr search dr selftreeappenditemselfroot download pr selftreeappenditemselfroot pandora statr selftreeappenditempr stations imagelist wximagelist grooveshark imagelistaddwximageimagesgrooveshark custompng wxbitmaptypepngconverttobitmap popular imagelistaddwximageimagespopular custompng wxbitmaptypepngconverttobitmap search imagelistaddwximageimagessearch custompng wxbitmaptypepngconverttobitmap download imagelistaddwximageimagesdownload custompng wxbitmaptypepngconverttobitmap pandora imagelistaddwximageimagesplaylisticon custompng wxbitmaptypepngconverttobitmap stations imagelistaddwximageimagesstations custompng wxbitmaptypepngconverttobitmap selftreesetpydatagr none selftreesetitemimagegr grooveshark wxtreeitemiconnormal selftreesetpydatapopr none selftreesetitemimagepopr popular wxtreeitemiconnormal selftreesetpydatasr none selftreesetitemimagesr search wxtreeitemiconnormal selftreesetpydatadr none selftreesetitemimagedr download wxtreeitemiconnormal selftreesetpydatapr none selftreesetitemimagepr pandora wxtreeitemiconnormal selftreesetpydatastatr none selftreesetitemimagestatr stations wxtreeitemiconnormal name main wxappfalse f testframe fshow amainloop why i followed demo wxpython demo app luck,1 the thing confusing page table hash hashes pagetablev contains hashref hash contains key page whose value integer the loop bitshifts integer clear perl code simpler would foreach v ram pagetablevpage now translation python obvious v ram pagetablevpage,hi i working converting perl python something i looking code hash tables perl i come across line code i really know python i know shifts bit strings page pagetable page table hash hashes pagetableentry page table entry structure dirty boolean referenced boolean valid boolean frameno indicates x ie page ram page used aging algorithm bit string ram x numframes could someone please give idea would represented python i got definitions hash tables done references i thanks help give fori iram pagetableramipage pagetableramipage,2 just use enumerate listex cat select brown dog turtle apple listex hampter bird monkey banana cat j listex pos enumeratelistex j print j found position pos listex this print cat found cat select brown position listex,listex cat select brown dog turtle apple listex hampter bird monkey banana cat j listex listex j print listexindexj what i trying accomplish search items listex listex if item listex found listex i would like know print index value item found listex listex thanks,2 something like ast import literaleval r hellonworld printliteraleval hello world edit ok want what want done general sven marnach explained strings actually contain escape sequences those notation string literals you filter strings nonascii characters list def isasciis try sdecode ascii return true except unicodedecodeerror return false william short x twitter xaa xe video guy ray isasciis,i want remove types escape sequences list strings how i input william short x twitter xaa xe video guy ray output william short twitter video guy ray httpdocspythonorgreferencelexicalanalysishtmlstringliterals,3 you could filter words alphanumeric using list comprehension strisalnum l william short x twitter xaa xe video guy ray word word l wordisalnum william short twitter video guy ray if wish filter numbers use strisalpha instead l william short x twitter xaa xe video guy ray word word l wordisalpha william short twitter video guy ray,i want remove types escape sequences list strings how i input william short x twitter xaa xe video guy ray output william short twitter video guy ray httpdocspythonorgreferencelexicalanalysishtmlstringliterals,1 okay much easier understand answer form i move i would write comment answer luckily overwrite system version python ubuntu comes preinstalled your python binaries python python located usrlocalbin directory userspecific stuff usually installed this fine means system python still first try run system python type command line usrbinpython c import bz print bzdoc this print something like î» usrbinpython c import bz print bzdoc the python bz module provides comprehensive interface bz compression library it implements complete file interface one shot decompression functions types sequential decompression if means fine so fix path tells shell find commands usrlocalbin going priority usrlocal ways fix order difficultyannoyancealtering system remove symlink python usrlocalbin this make type python go back executing usrbinpython alias system python sudo rm usrlocalbinpython move usrbin higher precedence path might desirable already stuff usrlocalbin precedence usrbin i adding completeness in shell profile sure ubuntu default i using bashprofile export pathusrbinpath remove python install this extreme first option i presented first option do really need version python if want isolated python environments probably really want virtualenv you probably remove unless reason it going little annoying though basically remove python python pythonw pythonw commands usrlocalbin remove usrlocallibpython this part complete i forget else,i using python ubuntu i got error importing bz module importerror no module named bz i thought bz module supposed come python how i fix problem edit i think i previously installed python compiling source probably point i libbzdev bz module installed now i hoping install python sudo aptget install python but say already installed is way uninstall previous python installation reinstall,3 this cannot done least broad scope asking as others mentioned runtime python know difference something escape sequences something without example print x prints true so way find difference two strings unless try static analysis python script,i want remove types escape sequences list strings how i input william short x twitter xaa xe video guy ray output william short twitter video guy ray httpdocspythonorgreferencelexicalanalysishtmlstringliterals,1 if want strip characters like use translate function strip sxxxxxxhello world prints hello world xxxx hello world delete escapes joinchrchar char range stranslatenone escapes hello world this strip control characters soh start heading stx start text etx end text eot end transmission enq enquiry ack acknowledge bel bell bs b backspace ht horizontal tab a lf n new line b vt v vertical tab c ff f form feed d cr r carriage ret e so shift f si shift dle data link escape dc device control dc device control dc device control dc device control nak negative ack syn synchronous idle etb end trans blk can cancel em end medium a sub substitute b esc escape c fs file separator d gs group separator e rs record separator f us unit separator,i want remove types escape sequences list strings how i input william short x twitter xaa xe video guy ray output william short twitter video guy ray httpdocspythonorgreferencelexicalanalysishtmlstringliterals,3 the problem kb windows update httpsupportmicrosoftcomkb messing dll search routine security fix setting registry value hkeylocalmachinesystemcurrentcontrolsetcontrolsession manager cwdillegalindllsearch allowed properly load dll files properly import pyd modules this may also happen windows versions,i spent last days trying launch examples boostpython importerror dll load failed the specified module could found error trying load compiled using bjam pyd modules i using windows x python x boost i followed different answers stackoverflow sites incl fresh installs python bit boost precompiled manual boost libraries building dll checks dependency walker luck i registered share solution worked i hope may help someone struggling error,1 that assignment user def postloopself user lilith return user acting local instance var to affect global var user would need add global user top function though i recommend usually better ways things use globals one note globals python while assign value global var without global keyword read global nonlocal scopes without this allows make closures,i two files i trying work menupy menus programpy imports menupy import cmdsys user one class loginmenucmdcmd def postloopself user lilith return user intrologin menu def dosmtoggleselfperson return true def doquitselfperson sysexit class storemenucmdcmd introstore menu def dowhoamiselfperson print storemenu user def doquitselfperson quit true return quit programpy menu import import cmdsys lm loginmenu sm storemenu true lmcmdloop print user smcmdloop i expect programpy gets print user print lilith instead prints one why postloop defined docs method executes cmdloop return i thought would return value user lilith lilith would printed prints one edit it recommended i use globals i reading find,1 cmd nothing user lilith introduces new local binding to rebind global name need global user user lilith also avoid globals,i two files i trying work menupy menus programpy imports menupy import cmdsys user one class loginmenucmdcmd def postloopself user lilith return user intrologin menu def dosmtoggleselfperson return true def doquitselfperson sysexit class storemenucmdcmd introstore menu def dowhoamiselfperson print storemenu user def doquitselfperson quit true return quit programpy menu import import cmdsys lm loginmenu sm storemenu true lmcmdloop print user smcmdloop i expect programpy gets print user print lilith instead prints one why postloop defined docs method executes cmdloop return i thought would return value user lilith lilith would printed prints one edit it recommended i use globals i reading find,1 if want fast python code hog features i ported code cython httpsgithubcomcvondrickpyvisionblobmastervisionfeaturespyx,i read post use opencv hogbased pedestrian detector how i detect track people using opencv i want use hog detecting types objects images pedestrians however python binding hogdetectmultiscale seem give access actual hog features is way use python opencv extract hog features directly image,3 you possibly something else working port try command netstat ln grep check alternatively try telnet localhost connection refused port clear use,im trying create website webpy letting open create socket port works every port i port forwarded problem python mainpy i i get error http traceback recent call last file mainpy line module apprun file usrlocallibpythondistpackageswebapplicationpy line run return wsgirunwsgiselfwsgifuncmiddleware file usrlocallibpythondistpackageswebwsgipy line runwsgi return httpserverrunsimplefunc validiplistgetsysargv file usrlocallibpythondistpackageswebhttpserverpy line runsimple serverstart file usrlocallibpythondistpackageswebwsgiserverinitpy line start raise socketerrormsg socketerror no socket could created code far import mysqldb import web import hashlib h urls index register register login login thankyou thankyou app webapplicationurls globals render webtemplaterendertemplates db webdatabase dbnmysql userroot pw dbrealmd class index def getself return renderindex class register def getself return renderregister def postself webinput user hshaiusernamehexdigest pw hshaipasswordhexdigest n dbinsertaccount usernameuser passwordpw name main apprun can someone help please,3 one easy way smooth data using moving average algorithm one simple form moving average calculate average adjacent measurements certain position in onedimensional series measurements an example moving average calculated example if go measurements done in simple example averaging window size you also use windows different sizes depending much smoothing want to make calculations easier faster wider range applications also use algorithm based convolution the advantage using convolution choose different kinds averages like weighted averages simply changing window let coding illustrate the following excerpt needs numpy matplotlib scipy installed click full running sample code future import division import numpy import pylab scipysignal import convolved def movingaverageddata window moving average twodimensional data makes sure window function normalized window windowsum makes sure data array numpy array masked array typedataname ndarray maskedarray data numpyasarraydata the output array dimensions input data mode symmetrical boundary conditions assumed boundary symm return convolveddata window mode boundary symm the following code generates arbitrary noisy data calculates moving average using four different sized box windows m n the shape data array n the shape window array x numpymgridm n the signal lots noise signal numpycosx noise numpyrandomnormalsizem n z signal noise calculating couple smoothed data win numpyonesm n z movingaveragedz win win numpyonesm n z movingaveragedz win win numpyonesm n z movingaveragedz win win numpyonesm n z movingaveragedz win and see different results code plotting initializing plot pylabclose pylabion fig pylabfigure bbox dictedgecolor w facecolor w alpha crange numpyarange color scale data range the plots ax pylabsubplot pylabcontourfx z crange pylabcontourx z crange colors k axtext n ha left va top transformaxtransaxes bboxbbox bx pylabsubplot sharexax shareyax pylabcontourfx z crange pylabcontourx z crange colors k bxtext n ha left va top transformbxtransaxes bboxbbox bx pylabsubplot sharexax shareyax pylabcontourfx z crange pylabcontourx z crange colors k bxtext n ha left va top transformbxtransaxes bboxbbox bx pylabsubplot sharexax shareyax pylabcontourfx z crange pylabcontourx z crange colors k bxtext n ha left va top transformbxtransaxes bboxbbox axsetxlimxmin xmax axsetylimymin ymax figsavefig movingavgsamplepng that folks and plotted results different sized windows the sample code given uses simple box rectangular window two dimensions there several different kinds windows available might want check wikipedia examples,i working creating contour plot using matplotlib i data array multidimensional it long wide so basically list lists length i contour plot working fine i need smooth data i read lot examples unfortunately i math background understand going so i smooth data i example graph looks like i want look like this graph what i want look similar what means i smooth contour plot like second plot the data i using pulled xml file but i show output part array since element array around items long i show excerpt here sample keep mind excerpt the dimension data rows columns the columns change depending data imported xml file i look values i use gaussianfilter change but changes great enough affect contour plot,3 use splat operator apply arbitrary number arguments op def vectorizeitargs op opargs reference salty crane how use args kwargs also linked aboved unpacking argument lists official docs,i attempting wrap call operation variable argument list generalized function fixed arguments like def vectorizeitargs op op function variable number arguments args list arguments i like pass for example lenargs i like call op like opargsargsargs as far i tell op needs arguments explicitly passed like i change argument list single list dictionary any suggestions appreciated,2 in addition problem identified wooble adding staticdir handler script handler handlers processed order staticdir handler never executed since requests caught one,i problem using template google app engine python thing i address static folder yaml i not access template i remove access able look files file structure src calcpy mainpy indexhtml templ calchtml js css yaml handlers url script mainpy mainpy def main application webappwsgiapplication mainpage calc calc debugtrue wsgirefhandlerscgihandlerrunapplication calcpy class calcwebapprequesthandler def getself temp ospathjoinospathdirnamefile templcalchtml outstr templaterendertemp tempval selfresponseoutwriteoutstr the result is status ok contenttype texthtml charsetutf i reach file template addressing working buttttttt i add following line yaml access css js it access able yaml handlers url script mainpy url templ staticdir templ if change order yaml handlers url templ staticdir templ url script mainpy both not working error status internal server error traceback recent call last file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebappwebapppyquot line call handlergetgroups file quotusersemdocumentsworkspacenerkharzsrccalcpyquot line get outstr templaterendertemp tempval file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line render loadtemplatepath debug file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line load return loaduserdjangopath debug file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line loaduserdjango template djangotemplateloadergettemplatefilename file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangotemplateloaderpyquot line gettemplate source origin findtemplatesourcetemplatename file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangotemplateloaderpyquot line findtemplatesource raise templatedoesnotexist name templatedoesnotexist calchtml please help must simple solution i really dont believe gae much fool thank advanced,1 you mostly need worry if come point something work come back ask note however determines lineending convention programming language use platform runs nixwindowsmac different,i note sure conventions different types line termination different programming languages i know types line feed carriagereturn line feed my question readline different programming languages like python fdreadline cc filegetline buffer java line bufreadline deal line termination if sensitive different types terminations i treat separately,1 python dicts work like javascript dicts you need use way access elements list querystring param,querystring cgiparseqsdecryptedqs selfresponseoutwritequerystring output param v param v selfresponseoutwritequerystringparam attributeerror dict object attribute param the original dict param v param v so second one working right way access values i running python app engine,1 visit browser there likely already process using port port supposed used http probably easiest way see using,im trying create website webpy letting open create socket port works every port i port forwarded problem python mainpy i i get error http traceback recent call last file mainpy line module apprun file usrlocallibpythondistpackageswebapplicationpy line run return wsgirunwsgiselfwsgifuncmiddleware file usrlocallibpythondistpackageswebwsgipy line runwsgi return httpserverrunsimplefunc validiplistgetsysargv file usrlocallibpythondistpackageswebhttpserverpy line runsimple serverstart file usrlocallibpythondistpackageswebwsgiserverinitpy line start raise socketerrormsg socketerror no socket could created code far import mysqldb import web import hashlib h urls index register register login login thankyou thankyou app webapplicationurls globals render webtemplaterendertemplates db webdatabase dbnmysql userroot pw dbrealmd class index def getself return renderindex class register def getself return renderregister def postself webinput user hshaiusernamehexdigest pw hshaipasswordhexdigest n dbinsertaccount usernameuser passwordpw name main apprun can someone help please,2 your custom index appears wrong order query likely done zigzag mergejoin rather using custom index try filtering properties order indexyaml,i query looks like userbase userentryallfilter debug falsefilter disabled falsefilter firstmessage falsefetch and index built serving kind userentry properties name firstmessage name disabled name debug there around entries userentry filtering fethed the problem the aforementioned fetch single line code takes complete any ideas could my guess might something wrong userentry model it quite properties i know start looking,1 this closest thing looking value test else notest otherwise much else,for reason i remember i believe way set variable python condition true what i mean value test where would hopefully set value test condition true and i going test multiple conditions set different variables like value test testtwo and conditions is possible,3 no python ternary else construct way conditionally bind name assignment statement,for reason i remember i believe way set variable python condition true what i mean value test where would hopefully set value test condition true and i going test multiple conditions set different variables like value test testtwo and conditions is possible,2 i figured answer reading doctestpy posting posterity doctest redirects standard output assigning new file descriptor sysstdout the problem function description closing value original sysstdout file descriptor prior doctest redefinition instead i following def printingfuncinarg filenone stuff file none file sysstdout printresult filefile printingfunc capture sys module rather sysstdout runs retrieve doctest redefined stdout attribute sys running inside test edit this also yields easy way check whether running inside doctest def insidedoctestoriginalstdoutsysstdout return originalstdout sysstdout,how i make python code aware whether running doctest the scenario follows i function print output file descriptor passed argument something like future import printfunction def printingfuncinarg filesysstdout stuff printresult filefile but i try use printingfunc doctest test fails specification keyword argument file invoking print output actually goes sysstdout rather whatever default output redirection set doctest module doctest never sees output so i make printingfunc aware whether running inside doctest knows pass file keyword argument calling print,1 check see module path to python shell import sys print syspath if installed correctly see mock directory one directories printed if find mock directory i assuming pip installing module virtualenv packages directory,i tried install mock library django httpwwwvoidspaceorgukpythonmock but type pip install u mock virtualenv try import mock django project shell get importerror no module named mock what i,2 result x x itertoolsizipa b or result mapoperatoradd itertoolsizipa b,suppose i made large list numbers i want make another one i add pairwise first list here first list a and b how might i generate arithmetic addition logic processing pairwise value one one a b a b producing list c a b a b,3 here two possible options use list comprehension use numpy i using shortened versions lists convenience elementwise sum go c list comprehension b c ael bel aelbel zipa b numpy import numpy np nparray b nparray c b,suppose i made large list numbers i want make another one i add pairwise first list here first list a and b how might i generate arithmetic addition logic processing pairwise value one one a b a b producing list c a b a b,1 choiceform form textarea you need give textarea id use id instead,this follow question i asking seems javascript question google app engine question i form form namechoiceform idchoiceform methodpost actiongchoicehandler onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form i want take value textarea send app formdata i tried var choice documentgetelementbyidchoiceformvalue i get undefined value choice what i wrong and also i understand correctly gchoicehandler called twice form xhr how i fix below handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var choice documentgetelementbyidchoiceformvalue var formdata new formdata formdataappendchooser user formdataappendchoice choice var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata added per aaron dufour answer return script head body changed onsubmit like onsubmitreturn writetostorage per aaron dufour answer form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update see aaron dufour answer solution,2 i suspect really want use factory method pattern you could change code something like name main variables would normally called config file jobtype job univar jobselect superclassoptionfactoryjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar this definition called main function redirects request appropriate job sub class def jobself raise notimplementederror staticmethod def optionfactoryjobtype univar return instance superclass based jobtype univar jobtype job return optionjobtype univar else return optionjobtype univar class optionsuperclass def initself jobtype univar superoption selfinitjobtype univar def jobself print job option print univar class optionsuperclass def initself jobtype univar superoption selfinitjobtype univar def jobself print job option print univar however notice implementation require superclass changed every time new subclass created another alternative would make optionfactory method standalone function rather method superclass like name main variables would normally called config file jobtype job univar jobselect optionfactoryjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar this definition called main function redirects request appropriate job sub class def jobself raise notimplementederror class optionsuperclass def initself jobtype univar superoption selfinitjobtype univar def jobself print job option print univar class optionsuperclass def initself jobtype univar superoption selfinitjobtype univar def jobself print job option print univar def optionfactoryjobtype univar return instance superclass based jobtype univar jobtype job return optionjobtype univar else return optionjobtype univar,i written code allows term job used universally perform unique task the specific jobs chosen setting initial variable jobtype from initial variable particulay subclass chosen perform appropriate job maybe code make sense name main variables would normally called config file jobtype job univar jobselect superclassjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar selfjobtype job selfjobchoice option else selfjobchoice option this definition called main function redirects request appropriate job sub class def jobself selfjobchoicejob class optionsuperclass def initself pass def jobself print job option print univar class optionsuperclass def initself pass def jobself print job option print univar the thought behind code allow singleconstant main function action variety unique tasks based purely variable jobtype which seems fine my question inexperienced coder i gone right way better way things also i set variable univar correctly superclass correctly shared across allany superclass subclasses thanks,1 iterparse function available xmletree import xmletreecelementtree etree event elem etreeiterparsefile events start end event start printelemtag use tag name attributes elif event end elem children elements elemtext elemtail available elemtext none elemtail none printreprelemtail another option override start data end methods etreetreebuilder xmletreeelementtree import xmlparser treebuilder class mytreebuildertreebuilder def startself tag attrs printamplts tag return treebuilderstartself tag attrs def dataself data printreprdata treebuilderdataself data def endself tag return treebuilderendself tag text xml the captial place pidsouth africaplace placepretoriaplace xml elementtreefromstring parser xmlparsertargetmytreebuilder parserfeedtext root parserclose return ordinary element output xml nthe captial place south africa place pretoria n,i xml data looks like xml the captial place pidsouth africaplace placepretoriaplace xml i would like able extract the xml elements currently provided etree the full plain text document start end tags the location within plain text start element character offset important requirement right etree provides fine i cannot see way directly hoped iterating elements document tree would return many small string could reassembled thus providing however requesting text root node returns text root node first element eg the capital doing sax could involve implementing lot already written many times eg minidom etree using lxml option package code go can anybody help,2 i suggest using urllib like source urlliburlopenhttpsomeurlcomsomepagehtmlread openpathtosomefile wbwritesource you could even shorten although wouldnt want shorten plan enclose individual call try except openpathtosomefile wbwriteurlliburlopenhttpsomeurlcomsomepagehtmlread,i tried download something internet using python i using urllibretriever urllib module i get work i would like able save downloaded file location choice if someone could explain clear examples would very appreciated,3 you access form formally using documentforms choiceform also documentformschoiceform each form elements collection form controls you access much way documentforms choiceform elements choice documentchoiceformchoice provided names follow rules valid javascript identifiers if need use square bracket notation document choiceform choice return reference element named choice form name choiceform so get value documentchoiceformchoicevalue,this follow question i asking seems javascript question google app engine question i form form namechoiceform idchoiceform methodpost actiongchoicehandler onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form i want take value textarea send app formdata i tried var choice documentgetelementbyidchoiceformvalue i get undefined value choice what i wrong and also i understand correctly gchoicehandler called twice form xhr how i fix below handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var choice documentgetelementbyidchoiceformvalue var formdata new formdata formdataappendchooser user formdataappendchoice choice var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata added per aaron dufour answer return script head body changed onsubmit like onsubmitreturn writetostorage per aaron dufour answer form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update see aaron dufour answer solution,2 itertoolsgroupby collects together contiguous items key if want items key sort selfdata first mid group itertoolsgroupby sortedselfdatakeyoperatoritemgetter keyoperatoritemgetter,i data selfdata list when i run code mid group itertoolsgroupbyselfdata keyoperatoritemgetter listgroup i get list i want but i use instead mid group itertoolsgroupbyselfdata keyoperatoritemgetter group second number tuples i get list even though tuples nd position,3 some great answers i haven’t seen one puts together have… since form one input need access value particular one there ways straightforward might use form’s elements property forms documentgetelementbyidchoiceformelementschoicevalue,this follow question i asking seems javascript question google app engine question i form form namechoiceform idchoiceform methodpost actiongchoicehandler onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form i want take value textarea send app formdata i tried var choice documentgetelementbyidchoiceformvalue i get undefined value choice what i wrong and also i understand correctly gchoicehandler called twice form xhr how i fix below handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var choice documentgetelementbyidchoiceformvalue var formdata new formdata formdataappendchooser user formdataappendchoice choice var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata added per aaron dufour answer return script head body changed onsubmit like onsubmitreturn writetostorage per aaron dufour answer form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update see aaron dufour answer solution,1 don use class factory silly you need consistent interface across implementations class jobaobject def dojobself arg print job arg class jobbobject def dojobself arg print job b arg jobtypes job joba job jobb jobtype job univar job jobtypesjobtype jobdojobunivar hell jobs keep state classes either functions instead def jobaarg def jobbarg job jobtypesjobtype jobunivar,i written code allows term job used universally perform unique task the specific jobs chosen setting initial variable jobtype from initial variable particulay subclass chosen perform appropriate job maybe code make sense name main variables would normally called config file jobtype job univar jobselect superclassjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar selfjobtype job selfjobchoice option else selfjobchoice option this definition called main function redirects request appropriate job sub class def jobself selfjobchoicejob class optionsuperclass def initself pass def jobself print job option print univar class optionsuperclass def initself pass def jobself print job option print univar the thought behind code allow singleconstant main function action variety unique tasks based purely variable jobtype which seems fine my question inexperienced coder i gone right way better way things also i set variable univar correctly superclass correctly shared across allany superclass subclasses thanks,1 what want probably possible using com python tutorial it messy hard code hard debug and way work mac instead i i would try take problem excel for instance python i would first directly access mysql i would parse second xls file using xlrd with results mysql query parsed xls file python data structures replicating behaviour vlookup easy i would write results output xls file using xlwt,i looking way automate entire process uses excel amp odbc queries i know excel use odbc driver run queries mysql database but i need query triggered programmatically the individual steps program script able open excel file run mysql query query change values query hits database come excel file save results query excel file sheet use results vlookups another sheet excel file save results vlookups close file flexible language addons necessary anything would help i looking run windows mac,1 you actually using inheritance original code code contains severe bug masks appearing you create instance superclass stores jobtype univar instantiates either option option stores reference the subclasses initialised data jobtype univar attributes override init donothing methods avoid error when call jobselectjob superclass explicitly delegates jobchoice attribute so useful inheritance going overridden everything superclass subclasses instead jobselect instance different subclasses depending jobtype using method resolution call right code jobselect always superclass contains option option explicitly delegates the serious bug i mentioned neither option option actually contains information job job methods anything interesting you call print univar work would normally print selfunivar get univar job seems work global called univar as soon start anything complicated scheme fall badly srgerg answer good example could actually use inheritance factory functions solve problem catplusplus answer good example use appropriate tools simple code example may need real requirements complex got written moment,i written code allows term job used universally perform unique task the specific jobs chosen setting initial variable jobtype from initial variable particulay subclass chosen perform appropriate job maybe code make sense name main variables would normally called config file jobtype job univar jobselect superclassjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar selfjobtype job selfjobchoice option else selfjobchoice option this definition called main function redirects request appropriate job sub class def jobself selfjobchoicejob class optionsuperclass def initself pass def jobself print job option print univar class optionsuperclass def initself pass def jobself print job option print univar the thought behind code allow singleconstant main function action variety unique tasks based purely variable jobtype which seems fine my question inexperienced coder i gone right way better way things also i set variable univar correctly superclass correctly shared across allany superclass subclasses thanks,1 most likely defining candidate another module imported where candidate defined have imported module call dbget calling candidategetkeylist work since forces valid candidate call,i contest entity uses listproperty store keys candidate entities here details class contestdbmodel candidates dblistpropertydbkey def createcandidateobjectsself putlist n name enumerateselftmpcandidates putlistappendcandidateparent self name name keys dbputputlist selfcandidates keys selfput class candidatedbmodel name dbstringpropertyrequired true when i query c modelscandidateallancestorcontestfetch everything works fine but i query using listproperty like c dbgetcontestcandidates i get error kinderror no implementation kind candidate can help understand last query work i imported candidate class module query update note dev server case might make difference update as suggested nick works c modelscandidategetcontestcandidates work raises kinderror models import candidate c dbgetcontestcandidates update the offending line occurs test code i try particular failure production server i used exact line elsewhere work dev production servers nick asked imports i test code syspathappendusrlocalgoogleappenginelibsimplejson import simplejson json everything else typical,1 after looking source code elementtree python hard coded fixtag function as workaround i xmletree import elementtree etree etreeversion etree workaround supressing prefixes def fixtagtag namespaces import string given decorated tag form uritag return prefixed tag namespace declaration isinstancetag etreeqname tag tagtext namespaceuri tag stringsplittag prefix namespacesgetnamespaceuri namespaceuri namespaces prefix etreenamespacemapgetnamespaceuri namespaceuri etreenamespacemap prefix nsd lennamespaces namespacesnamespaceuri prefix prefix xml xmlns none else prefix none nsprefix prefix else nsprefix xmlns xmlnss nsprefix namespaceuri else xmlns none prefix none prefix else prefix return ss prefix tag xmlns etreefixtag fixtag etreenamespacemap httpsomenamespace none else for etree use registernamespace function etreeregisternamespace httpsomenamespace in case post ever gets date code maintained,in python etree i suppress xml prefixes elements like python r jun gcc based apple inc build llvm build darwin type help copyright credits license information import xmletreeelementtree etree etreeversion something etreeelement httpsomenamespacetoken etreetostringsomething nstoken xmlnsnshttpsomenamespace etreeregisternamespace httpsomenamespace etreetostringsomething token xmlnshttpsomenamespace the registernamespace function added i trying remove prefix way compatible python etree version here i tried python r jul gcc based apple inc build llvm build darwin type help copyright credits license information import xmletreeelementtree etree etreeversion something etreeelement httpsomenamespacetoken etreetostringsomething nstoken xmlnsnshttpsomenamespace etreenamespacemap httpsomenamespace etreetostringsomething token xmlnshttpsomenamespace this i want the prefixes still blank is way remove completely,3 as others said accessing form data want textarea if give textarea id probably easiest way get value after much discussion determined need xhr here form look like form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typehidden namechooser idformchooser input typesubmit valuesubmit choice form and use javascript function edit form allowing submitted var count function writetostorage var user user count count localstoragesetitemchooser user documentgetelementbyidformchooservalue user,this follow question i asking seems javascript question google app engine question i form form namechoiceform idchoiceform methodpost actiongchoicehandler onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form i want take value textarea send app formdata i tried var choice documentgetelementbyidchoiceformvalue i get undefined value choice what i wrong and also i understand correctly gchoicehandler called twice form xhr how i fix below handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var choice documentgetelementbyidchoiceformvalue var formdata new formdata formdataappendchooser user formdataappendchoice choice var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata added per aaron dufour answer return script head body changed onsubmit like onsubmitreturn writetostorage per aaron dufour answer form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update see aaron dufour answer solution,1 to start main want notice loops first read line one time assign list words line words but overwriting words words list words last line now put words doclist think loop nesting fix section first def main x docread words xsplit word words doclistappendword now move parts missing python lot useful libraries for lowercasing string try looking httpdocspythonorglibrarystdtypeshtmlstrlower for getting rid punctuation might find function helpful determining whether character letter httpdocspythonorglibrarystdtypeshtmlstrisalpha since homework i hesitant give away code otherwise learn say something get stuck,awful programmer for class assignment i take words text document count order i trouble erasing punctuation replacing upper case letters lower ones any guidance would greatly appreciated docwords docrawinputplease enter name text file docreadopendoc r doclist def main x docread words xsplit word words doclistappendword def wordcount main counter doclist docwordscounter docwordsgetcounter wordcount docreadclose p sorteddocwords print p docwordsp,1 raise raise exceptions first place a lone raise exception handler propagates exception external handlers,i brand new python need help understanding code fragment c b c d try raise c except d print d except c print c except b print b reading python docs seems raise throws exception i figure raise within try block shouldn something like try something catch raise,1 that code kind ridiculous bizarre way things pretty clear going the list b c d list exceptions since exception raise try block immediately handled appropriate except handler succession except b except c except d handlers thus code equivalent print b print c print d except throw uncaught exception b c d exception,i brand new python need help understanding code fragment c b c d try raise c except d print d except c print c except b print b reading python docs seems raise throws exception i figure raise within try block shouldn something like try something catch raise,1 erasing punctuation one option regular expression module resub function in case i remove characters alphanumeric spaces import it ok print resub w its ok lower case a straightforward lower function string object its ok lower ok,awful programmer for class assignment i take words text document count order i trouble erasing punctuation replacing upper case letters lower ones any guidance would greatly appreciated docwords docrawinputplease enter name text file docreadopendoc r doclist def main x docread words xsplit word words doclistappendword def wordcount main counter doclist docwordscounter docwordsgetcounter wordcount docreadclose p sorteddocwords print p docwordsp,1 python eliminate overhead structures like sorry its dynamic nature makes compiler optimizations difficult but i know language would eliminate overhead introduced keeping things dictionaries dict owner probably includes dictionaries creating inside object they marked noowner dictionaries object instances what use slots add slots names fields class attribute python use efficient implementation class it get rid dictionary used hold attributes if dictionaries rewritten use lists would improve situation lists memory efficient dictionaries for best efficiency rework system use numpy arrays each attribute class would become sized array each element stored efficiently spacewise case alternatively could checkout pypy it provides alternate implementation python jit well various timespace optimizations might help sysgetsizeof reporting think reporting sysgetsizeofmyobjcontainer reports size class object size actual container objects you want sysgetsizeofmyobjcontainer similar even accurate include anything besides base object it take account dictionary holding attributes it report size third row report,i got results heapy unclear exactly mean index count size cumulative kind class dict class dict owner dict myobjcontainer myobjcontainer myobj class truefalse values number values could stored bytes i array i really see consume mb memory i like bring mb possible much data inside object organized dictionaries ease access the dictionaries change rather pointless would cause much overhead would beneficial pack data number bitwise operators i able store entire data object bytes i hoping compiler would sort thing automatically like languages seems opposite the class inherits builtin type object reason use decorators would cause much overhead also curious dict owner means consuming half memory edit sysgetsizeofmyobjcontainer indeed reporting bytes this insane i used dictionaries i need access data based index as far i concerned compiler get rid structures access values directly is better way i imagine lists answer,3 i took look python data model documentation if skip ahead class instances section see crucial explanation attribute assignments deletions update instance’s dictionary never class’s dictionary so example aname introduce new key name dict after access name attribute standard attribute lookup mechanism looks dict first,i defined simple class class myclassobject name google and i creating instance call name attribute myclass aname google also calling directly class myclassname google so far i background c java i call myclassname static invocation calling static members instances fine but i observing till i set aname another value changing myclassname also affecting aname once i set aname changing myclassname affect aname begin different values you see whole experiment class myclassobject name google myclassname google myclass aname google myclassname yahoo aname yahoo myclassname hello world aname hello world myclassname hello world myclassname another trick myclassname another trick aname another trick aname i changed value aname i changed value myclassname another trick myclassname changed aname i changed value i would like someone explain reason behind behavior thanks,2 this situation kind strange completely relying functions sideeffects instead returning values however solution def secondlst rate rangelenlst firstlsti rate,i created function updates single list adding interest rate def firstlst rate rangelenlst lsti lsti ratei my question use function update two dimensional list adding interest rate for example lst rate lst printi my code def secondlst rate x lst x lstxy firstlstxyratex any help much appreciated thanks,1 read length limit proc subprocesspopenargs stdinnone stdoutsubprocesspipe stderrnone true chunk procstdoutread chunk bytes this code comment slightly modified it works import subprocess class containerobject pass self container args yes test selfp subprocesspopenargs stdinnone stderrnone stdoutsubprocesspipe shellfalse true chunk selfpstdoutread print printing chunk print chunk,i think i might repeating question i find answers suited requirement pardon ignorance i program running continuously spits binary data serverit never stops killed i want wrap python script read output process arrives i tried subprocess ideas stack overflow use please suggest psubprocesspopenargsstderrpipestdinpipestdoutpipeshellfalse pcommunicateblocks forever expected pstdoutreadreadlinesreadlineblocks selecton pstdoutfilenoblocks best method,2 jython python java sure want i answered normal python windows i assume to use python windows need install windows binary installer download python download page make sure choose binary installer next need install setuptools get python package index pypi once installed python available windows you able open command prompt type python get python prompt look like python r nov msc v bit intel win type help copyright credits license information then install pywhois open command prompt type ceasyinstall pywhois you see output like searching pywhois reading httppypipythonorgsimplepywhois best match pywhois downloading httppypipythonorgpackagessourceppywhoispywhoistargz mdbdcdbbdafb processing pywhoistargz running pywhoissetuppy q bdistegg distdir cdocumelocals tempeasyinstallhugnulpywhoiseggdisttmpaarhii adding pywhois easyinstallpth file installing pywhoisscriptpy script cpythonscripts installing pywhoisexe script cpythonscripts installing pywhoisexemanifest script cpythonscripts installed cpythonlibsitepackagespywhoispyegg processing dependencies pywhois finished processing dependencies pywhois to confirm installed able import python python r nov msc v bit intel win type help copyright credits license information import pywhois netbeans removed python support see httpwikinetbeansorgpythonroadmap information this httpwikipythonorgmoinintegrateddevelopmentenvironments wiki entry lists ides try,i trying install python module windows computer i installed development version netbeans ide use python editor seems install jython program folder force use installation development i trying install pywhois module half hour i getting pretty infuriated kludginess developing python windows netbeans does anyone know install modules setup should i destroy dev environment use something else would less rageinducing,3 when i web project i found jake gordon javascriptstatemachine quite useful a later i needed fsm python i find anything matching javascript one terms simplicity flexibility i ported python it called fysom,these python fsm implementations i found far fysom a slick fsm implementation provides function callbacks state skip montanero fsm fsm decorators pythoncourse fsm tutorial welldocumented example fsm parsing sentences fsmme a graphical fsm editor w python target also see fsmme tutorial python fsm recipe active state code suited text parsing tasks gof state pattern atampt weighted fsm python python fsm so code golf i need parse text file configurations i looking fsm implementation provides ability munge data inputting next state,3 python supports use case directly collections import counter counter abracadabra mostcommon r b c,i got far def mostfrequentstring dict key string key dkey else dkey return print mostfrequent aabbbc returning c b now i need reverse pair sort number decreasing order print letters should i convert dictionary tuples list,2 actually submitting form twice once writetostorage via ajax also normal way form you change two things writetostorage return false last action change onsubmit onsubmitreturn writetostorage this way prevent default submission form done via ajax writetostorage,the following code seem work i try get chooser google app engine python undefined chooser selfrequestgetchooser selfresponseoutwritechooser chooser returns chooser without value is valid javascript var formdata new formdata formdataappendchooser user var xhr new xmlhttprequest ok test localhost xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata is problem xhr call app update i including code choice clarify chooser per daniel roseman comment in choice handler i writetostorage assigns username form user user writes localstorage after writing user name localstorage i also need write database app i use xhr send gchoicehandler handler so chooser i believe string made var user user count i copy choice handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var formdata new formdata formdataappendchooser user var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata script head body form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update i noticed logs text textarea choice chooser sent xhr shown together one always without value info chooser user choice info chooser choice abcd info chooser user choice info chooser choice efgh this code log chooser selfrequestgetchooser choice selfrequestgetchoice logginginfochooser choice tuplechooser choice newchoice user choice choice owner chooser newchoiceput datastore see chooser choice written different rows what i wrong,1 python tempfile module may looking,i find scripting i often need osmkfifo tmpsomefifoname later osremove tmpsomefifoname is way autogenerate temporary filename guaranteed unique directory i bother put try except oserror around things i aware i could checking fname oslistdir tmp regenerating needed i sure must something little elegant,3 use recent version djangouniform it fixes much,i using djangouniforms display fields rather rudimentary example straight book when i render form fields using formcsrftag formasuniformform everything works expected however djangouniform helpers allow generate form tag helperrelated content using following syntax formhelper helper uniform form helperendwith this creates form tag nowhere embed csrftoken when i try use syntax form renders perfectly without csrf token submitting form fails every time does anyone experience is established way add token i much prefer second syntax reuse reasons thanks,1 one way seems work suggested andreas kloeckner comments alternatives welcome the greet modified follows char const greetboostpythonobject obj pyobject pobj objptr pybuffer pybuf ifpyobjectgetbufferpobj amppybuf pybufsimple void buf pybufbuf double p doublebuf p p pybufferreleaseamppybuf return hello world python use print cmodgreeta,i trying use boostpython wrapper c function receives pointer modifies data managed python side numpy array example returns how i get python numpy boostpython collaborate give raw pointer inside function include boostpythonhpp namespace char const greetdouble p p return hello world boostpythonmodulemodule boostpythondefgreet ampgreet in python i try import numpy np npempty dtypenpdouble rawptr adata print cmodgreetrawptr i get error boostpythonargumenterror python argument types modulegreetbuffer match c signature greetdouble,1 see reflecting database objects sa documentation tablename meta autoloadtrue autoloadwithengine,using table creation normal tablename meta columns this first run i create table in future executions i would like use table without indicate columns this seems redundant already specified table schema in words future accesses i like simply tablename meta columns already read schema is way sqlalchemy,1 there builtin function trivial write def roundquarterx return roundx,i running following issue given various numbers like already builtin function exists round closest step like eg or i go ahead hack together function performs desired task thanks advance best regards dan,2 def myroundx return roundx assert myround assert myround assert myround assert myround,i running following issue given various numbers like already builtin function exists round closest step like eg or i go ahead hack together function performs desired task thanks advance best regards dan,3 this general purpose solution allows rounding arbitrary resolutions for specific case need provide resolution values possible shown test cases def roundpartial value resolution return round value resolution resolution print rounding quarters print roundpartial print roundpartial print roundpartial print roundpartial print rounding tenths print roundpartial print roundpartial print roundpartial print rounding hundreds print roundpartial this outputs rounding quarters rounding tenths rounding hundreds,i running following issue given various numbers like already builtin function exists round closest step like eg or i go ahead hack together function performs desired task thanks advance best regards dan,3 your second list contain logs primes contains logs integers lp,mathematical rule shows program gives wrong answer i would grateful could check small piece code tell problem i know problem somewhere line i pinpoint exact cause but i know sum logarithms primes less n less n my program violates rule here code math import log lp create list n range x rangen n x break else lpappendn fill list primes print lp found value lp create second list range lp number corresponding lp logi llappendi fill second list logs primes print sum sumll,3 ok fault i ran shell tests managepy instead python manage virtualenv directory included syspath mock package unavaible thanks help,i tried install mock library django httpwwwvoidspaceorgukpythonmock but type pip install u mock virtualenv try import mock django project shell get importerror no module named mock what i,1 i ended using addsignalwatchfull unfortunately verbose it works fine though i receive messages handler,i using pygst project working fine i trying migrate new introspection system gi i getting different behavior in old pygst i something like imports import pygst pygstrequire import gst imports gobjectsthreadsinit def myhandlerbus message handle message player gstelementfactorymake playbin myplayer bus playergetbus busconnect message myhandler busaddsignalwatch playersetstategststateplaying start main glib loop the message parameter attribute type used selective processing i interested end stream eos error using new system i imports girepository import gst import glib import gobject imports gobjectthreadsinit loop glibmainloopnone false def bushandlerbus message print message handle message gstinitchecknone player gstelementfactorymake playbin myplayer playersetproperty uri filehomekenjibuttonogg bus playergetbus busconnect message bushandler busaddsignalwatch playersetstategststateplaying start main loop however handler always receives parameter message none i tried filtering i still get nothing ie messages none i read lot gstreamer documentation especially gstbus addsignalwatch playbin i find anything related behavior i checked gst gir file i seen addwatch cannot introspected dead end the glib main loop example make things shorter without full gtk example real thing uses gtkmain giving exactly behavior i using gstreamer informed gstversion arch linux i tested behavior gstreamer ubuntu bit is alternative busconnect am i using wrong way i spent quite hours hunting bug i would really appreciate insight thanks,1 i think using subprocess would better allow control stdin stdout stderr well return exit code captured python httpdocspythonorglibrarysubprocesshtml,i working python based tkinter script flow like a csh script run specifying script name arguments unix terminal a python script written take script name argument input user gui the python script needs execute script prompt user run button gui the code running like def run ossystem scriptfile able execute code problem the control switch back python script execution it waits terminal cursor keeps blinking terminal still execution going i certain execution please suggest to switch back control,1 i ended making plugin placed following run selfviewwindowruncommand exec cmd sh scriptsh quiet false i based code git support plugin httpsgithubcomnotanumbergitst,i various shell build scripts project want create one centralized build system options allow shell script run for example user presses cmd b user given option shellscriptsh shellscriptsh shellscriptsh the user presses sublime text runs sh shellscriptsh i reading httpsublimetextinfodocsenreferencebuildsystemshtml unsure integrate option json code sublime text build system how accomplish build system sublime text thanks,1 this wrong range lp gives numbers lp logi changes loop variable llappendi should range llappend loglpi,mathematical rule shows program gives wrong answer i would grateful could check small piece code tell problem i know problem somewhere line i pinpoint exact cause but i know sum logarithms primes less n less n my program violates rule here code math import log lp create list n range x rangen n x break else lpappendn fill list primes print lp found value lp create second list range lp number corresponding lp logi llappendi fill second list logs primes print sum sumll,1 i going guess launch ninjaide terminal source bashrc new environment variable influences child processes whichever shell process sourcing of course logging may living entirely gui eg click button start ninjaide may need go effort set environment variable how depends upon graphical environment using,i trouble getting pythonpath set i added line bashrc export pythonpathpythonpathhomesaythmyprogramspython i ran source bashrc here issue though i type python terminal get python repl i import modules myprogramspython without problem however i run bpython idle console ninjaide etc import fails import temperature traceback recent call last file pyshell line module import temperature importerror no module named temperature i syspathappendhomesaythmyprogramspython get working i wanted pythonpath work consoles automatically how ps using ubuntu,2 the problem insertedtext signal emitted gtkentrybuffer objects gtkentry ones to connect signal use something like entry gtkentry entrybuffer entrygetbuffer entrybufferconnect insertedtext callback,greetings guys girls i new programming gtk need decent opensource twitter client i find one i developing one opensource i using gtk python pygobject pygtk i problems entry connect handler signals deletedtext insertedtext tweettext entry i tryied selftweettextconnectinsertedtext selfontweet selftweettextsetpropertyinsertedtext selfontweet keeps failing make tweettext multine i searched documentation httpreadthedocsorgdocspythongtktutorialenlatest i find nothing related and also searched c documentation related gtk i apreciate someone help thanks advance,1 no ignore check your xml file xml file xml file ampersand would escaped therefore software designed read xml files parse without error you need correct software generated file generates proper wellformed xml all benefits using xml interchange disappear entirely people start sending stuff wellformed people receiving try patch,i reading xml file using python but xml file contains amp characters running python code gives following error xmlparsersexpatexpaterror wellformed invalid token is way ignore amp check python,3 your range expression range lp expands numbers th element lp exclusive using lp yield right result,mathematical rule shows program gives wrong answer i would grateful could check small piece code tell problem i know problem somewhere line i pinpoint exact cause but i know sum logarithms primes less n less n my program violates rule here code math import log lp create list n range x rangen n x break else lpappendn fill list primes print lp found value lp create second list range lp number corresponding lp logi llappendi fill second list logs primes print sum sumll,1 i think need put dots this test string line this test string line this test string line,suppose i following code def foos a dummy function foo for example this test string line this test string line this test string line fooa this test string line this test string line this test string line print name main import doctest doctesttestmod and let save foopy when i run cpythonpythonexe foopy file foopy line mainfoo failed example this test string line exception raised traceback recent call last file cpythonlibdoctestpy line run compileflags testglobs file doctest mainfoo line this test string line syntaxerror eof scanning triplequoted string literal file foopy line mainfoo failed example fooa exception raised traceback recent call last file cpythonlibdoctestpy line run compileflags testglobs file doctest mainfoo line module fooa nameerror name defined items failures mainfoo test failed failures have tried indent docstring have checked indents spaces indent changed single quote double quote errors different doctest go successfully currently thing work join lines extreme long string separate rn do i miss something,3 count means work the bit iterable type number try rangecount,i using python windows i trying create program accepts numbers tells user many positive many negative many zero i got far count count num floatinputtype number number num zero elif num positive elif num negative print positive print negative print zero but i run code i get typeerror float object iterable if i replace float line int i get problem except says int object iterable i also tried changing value count now i took challenge python tutorial book answer i tell i done everything within syntax put forward the tutorial pdf,3 how something like module import mymodule hasattrmodule classname classname moduleclassname myobject classname,with python application i modules classes contain parser text in function i want instanciate use particular module these sorted database i point i know parser python file name class i want import create however how actually python eg filename lexparser classname lexparser i filename import classname parser classname follow i mean,2 well i looking something similar i came across php equivalent question i translated anwer python f examplejpg fd openf fdread xmpstart dfind xxmpmeta xmpend dfind xxmpmeta xmpstr dxmpstartxmpend printxmpstr convert xmpstr parse xml api,can i use pil like example i need read data i looking easiest simplest way i install pyexiv edit i want believe way library pythonxmptoolkit pyexiv needs exempi boost there must another option,3 for performance reasons pycharm generate python stubs net assemblies default you trigger generation putting caret unresolved reference import statement pressing altenter selecting generate stubs binary module quickfix,i like pycharm used python projects i started messing ironpython i figure make pycharm ide matter except vs works fine recognize net libraries for example i code systemenvironment import path environmentgetfolderpathenvironmentspecialfoldermydocuments the code works fine system part underlined grey everywhere message unresolved reference system the ironpython documentation explains system module rather namespace if i typesystem i get type namespace so way make pycharmpydev recognize namespaces well on side note path fine everything fine,3 the jar file nothing archive bytecompiled java code to execute properly try import subprocess run rjava jar xgreenadamfilejarjar proc subprocesspopenrun,i trying open java link i saved folder desktop i get find file the java address xgreenadamfilejarjar this executable jar file i want open desktop open run normal java link want python open import subprocess runxgreenadamfilejarjar procsubprocesspopenrun i get traceback recent call last file cpythontest line module procsubprocesspopenrun file cpythonlibsubprocesspy line init restoresignals startnewsession file cpythonlibsubprocesspy line executechild startupinfo windowserror error the system cannot find file specified what i wrong find file,1 as don kirkby said first must check conditions asked moreover per point view onemany field blockline treeview field check conditions in py field referenced manyone field call blockid onemany class in xml mo blockid field om tree form view visibleinvisible save record appropriate form id current record id must stored mo field saving om line record if store save action record database onemany class visible tree view mo reference id stored may wrong mo id stored om class show related om records in case data database displayed tree view case need check note take reference saleorder saleorderline class details,i added tree view page notebook element while adding data tree view saving database also displayed tree view when i reload page data tree view vanishes empty the code looks like field namearch typexml notebook colspan page stringblock area field colspan nameblockline nolabel modetreeform tree stringblock field nameblockname field namesize field nameactivefrom field nameactivethru field nameactive tree field page notebook field,1 if usowner userproperty need use user gql datafiles dbdatafilegqlwhere usowner user useremail also remember always use placeholders string interpolation sql mean vulnerable injection,i create entity like company dbdatafileusowner user companyname selfrequestgetname companyput user google user account now i try search user like datafiles dbdatafilegqlwhere usowner useruserid assign jinja template var templatevalues datafiles datafiles output html datafile datafiles datafilename chevrons indicate looping endfor get output the data admin dashboard i access any ideas thanks,3 unfortunately could find way implement resize pgmagick uses c api support scale op yet implemented ugly def resizenewsize g pgmagickgeometrynewsize distinguishes whether width height given image pgmagickimageimg rw rh imagesize w h gwidth gheight w h gheightintrh w rw elif h w gwidthintrw h rh imagescaleg width important resizing final size adjusted according width height respectively for example image x resized resize x function calculates final height uses scale image imgscale x otherwise using scale directly would result new image x,i using graphicsmagick simple operations images resizing croppping etc trying use pgmagick via python instead for resizing script issues following commands gm convert imagejpg resize x resizing mages according width main concern command works expect considers width resizing using pgmagick try operation given import pgmagick p img pimagepblobopen imagejpg rb read imgscale imgscale x pgmagick scale seem respect parameter code scales image width height ever appropriate example image x dimensions resulting image x dimensions terms graphicsmagick behaves like gm convert imagejpg resize x resize x how scale image respect width using pgmagick,1 you define foreign keys using strings avoid exactly problem class artc art mforeignkey article fromotherapp mforeignkey otherapparticle,hello i spliting files model getting bigger so problems my models if category model i remove articletocategory manytomany relationship works well but i need how fix i deleted modelpy order load files model package category modelscategory class categorympttmodel relationships rubetedjangogenericmodelsarticle import article rubetedjangogenericmodelsarticletocategory import articletocategory articles mmanytomanyfieldarticle througharticletocategory articletocategory modelsarticletocategory djangodb import models class articletocategorymmodel rubetedjangogenericmodelsarticle import article rubetedjangogenericmodelscategory import category article mforeignkeyarticle category mforeignkeycategory class meta dbtable articlestocategories verbosenameplural articlestocategories thanks,3 the method match looks beginning string you use search instead also regex built match even amount characters researchr azazazaz str,in python code want pattern match string atleast two consecutive alphabets anywhere string i used rematchr azazazaz str this matches string example abc match abc what mistake regex please help thank you,1 i quite understand want example provided one see misinterpreted rematch see search vs match docs python module,in python code want pattern match string atleast two consecutive alphabets anywhere string i used rematchr azazazaz str this matches string example abc match abc what mistake regex please help thank you,1 to answer updated question researchr azaz str or simply like want alphanumerical characters including underscore researchr w str to match really alphanumericals researchr azaz str the research might help expect match anywhere string beginning,in python code want pattern match string atleast two consecutive alphabets anywhere string i used rematchr azazazaz str this matches string example abc match abc what mistake regex please help thank you,1 try filename lexparser classname lexparser parser getattrimportfilename classname note filename must contain py this work module within package import would return top level package in case import sys filename parserslexparser classname lexparser importfilename parser getattrsysmodulesfilename classname this work cases recommeded import function documentation in examples parser class instantiate normally parser parser,with python application i modules classes contain parser text in function i want instanciate use particular module these sorted database i point i know parser python file name class i want import create however how actually python eg filename lexparser classname lexparser i filename import classname parser classname follow i mean,3 since logfile sorted chronologically parse completely datetime import datetime timedelta datetimenow lookback timedeltaminutes oldest lookbackstrftime ymd hms lines open logfilelog r f line f line oldest linesappendline lines message n joinlines send message per mail,i trying analyze java application logs using logj logged within last five minutes i planning use python analyze last five minutes logs ans warnings send mail can one suggest best method getting log lines last five minutes i use python log format warn sample warning warn sample warning warn sample warning warn sample warning,2 i familiar python api selenium probably receive link using getattributeattributename method so something like linkstr link listlinker linkstr linkgetattributehref linkstr domenesider pass elif strhoveddomene linkstr domenesiderappendside,i sure answered somewhere basic question i however life find answer web i feel like complete idiot i ask goes i writing python code produce list page addresses domain this done using selenium problem occurs i try access list links produced selenium here i far selenium import webdriver import time hoveddomene httpwwwexamplecom listlinker domenesider domenesiderappendhoveddomene driver webdriverfirefox side domenesider drivergetside timesleep listlinker driverfindelementsbyxpatha link listlinker link domenesider pass elif strhoveddomene strlink domenesiderappendside printdomenesider driverclose listlinker variable contain links found page instead list contains i guessing selenium specific objects called webelements i however find webelement attributes give links matter fact i find examples webelement attributes accessed python least manner reproduce i would really appreciate help could give sincerely rookie,3 change function definition changebuttontext accept parameters callback functions called trace function always receive three arguments name variable index mode none really interesting function needs match signature callback work to fix change callback function look like def changebuttontextname index mode buttontextsetwidgetget if prefer also put lambda trace call keep function definition clean along lines define variables use widgettracew lambda n changebuttontext your callback remain case,i dropdown menu buttoni trying change text button according choice dropdown menui used tracebut gives error typeerror changebuttontext takes arguments given this example tkinter import import tkinter tk import os def changebuttontext buttontextsetwidgetget apptk apptitleexample appgeometry x widget stringvar widgetset numbers files one two three widgetdropdown optionmenuapp widget files widgetdropdownconfigbg white foreground black fonttimesitalic widgetdropdownmenuconfigbg white fonttimesitalic widgetdropdownpack widgettracew changebuttontext buttontextstringvar buttontextset zero buttonbuttonapptextvariablebuttontextfonttimes widthborderwidth buttonpacksideleft padxpady appmainloop any ideasthanks,1 use rangecount int float iterable,i using python windows i trying create program accepts numbers tells user many positive many negative many zero i got far count count num floatinputtype number number num zero elif num positive elif num negative print positive print negative print zero but i run code i get typeerror float object iterable if i replace float line int i get problem except says int object iterable i also tried changing value count now i took challenge python tutorial book answer i tell i done everything within syntax put forward the tutorial pdf,1